* feat(web-search): add Bocha AI Search provider
Add a Bocha (bochaai.com) web search provider following the Metaso
adapter pattern: hardcoded official endpoint (SSRF-safe), Bearer auth,
4MB response cap, error-detail extraction, and RFC3339 date parsing
(datePublished preferred, dateLastCrawled fallback).
Tenant-facing config fields:
- freshness: noLimit/oneDay/oneWeek/oneMonth/oneYear (default noLimit)
- summary: request long text summaries, preferred as snippets (default on)
Wiring: registry factory in container, provider type enum + /types
metadata (dynamic form fields), frontend provider union type, and
swagger docs enum entries.
* fix(web-search): match Bocha's real wire format for codes and error messages
Live endpoint probing showed errors return {"message": .., "code": "401"}
(string code, message field) instead of the documented {msg, code:int}.
Parse the code tolerantly (string or number) and extract the detail from
message/msg so auth and rate-limit failures surface their reason.
* fix(web-search): allow Bocha in provider CRUD validation
In-service integration testing caught a fourth wiring point the adapter,
registry, /types metadata and frontend covered but CRUD did not: the
service-layer whitelist (isValidProviderType) and parameter validation
switches rejected provider type 'bocha', so providers could be tested
via POST /web-search-providers/test but never created or updated.
Add Bocha to both switches (delegating to ValidateBochaParameters like
Metaso/Zhipu) with service-level test coverage.
* fix(web-search): correct Bocha legacy timestamp timezone
---------
Co-authored-by: vicfei <vicfei@users.noreply.github.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
* feat(sandbox): run sandboxed execs as root by default
Every chat session owns its own sandbox, so the in-container account is
not a tenant boundary and root is the least surprising default for an
agent that installs packages and writes wherever it needs. Host and
cross-tenant isolation stay at the container boundary.
DefaultSandboxExecUser becomes "root" (remote_client.go) and the sandbox
image ends with USER root. The three backends keep naming the account
explicitly on every exec so the account a call lands on does not depend
on which backend a workspace selected; the adapter default, the file
operations and the artifact-directory bootstrap all follow the constant.
The template still provisions a uid 1000 "user" account for interop with
E2B/Cube tooling that addresses it by name.
Root also makes the skill-install flow's account hand-over pointless, so
it goes: verification no longer runs after a chown/chmod lock-down and a
repair round no longer reopens the tree (normalizeSkillPermissions and
reopenSkillDirForRepair are gone), and the prepare and scratch commands
stop chowning. The scratch wipe now also clears /tmp, and the cache
budget guard sizes only root's caches, since no second account can grow
one. Verification is asserted to stay on the ordinary executor (no
AsRoot, no AllowSkillsRoot) rather than on which account it ran as.
* refactor(skills): install chat-time extras into the skill's own env
PYTHONPATH / NODE_PATH pointed at a per-session overlay
(/workspace/.skill-packages/<skill>) because the skill tree was frozen
after install: root-owned, mode 555, and often built by `uv venv` with no
pip, so `pip install --target` somewhere else was the only way a chat
session could add a package.
None of that holds now. The lock-down is gone and execs run as root, so a
missing package goes straight into the skill's own environment, and the
write is already session-local: a chat sandbox is built from the config's
image and its filesystem dies with the session, so nothing reaches the
image other sessions start from. The overlay bought nothing over that
while splitting one skill's packages across two locations.
SessionSkillPackageDir goes, and applySessionPackagePath becomes
applySkillNodePath: it appends the skill's own node_modules after
whatever the caller supplied, replacing a `+=` that prepended a bare
separator once the overlay stopped seeding the variable. No PYTHONPATH is
injected at all. Python dependencies are reached through the skill's venv
interpreter, which the shell wrapper already puts first on PATH; the
overlay-era value named the venv root, which is not an importable path.
PYTHONPATH stays on the injected-name blacklist so a stored value cannot
shadow the venv.
The runtime hints and every prompt that described the overlay now name
`<skillDir>/.venv/bin/python -m pip install` and `npm install` in the
skill directory. frozenSkillTreeGuidance / isFrozenSkillVenvFailure are
renamed for what they detect now that nothing is frozen.
* docs(prompts): reserve /workspace/output for finished deliverables
/workspace/output is the one directory an artifact collector reads, so
everything written there is offered to the user as a deliverable. The
prompts described it as the place for "deliverables" or "downloadable
artifacts" without saying it is exclusively that, which reads as "the
directory you write results to" — and a model doing multi-step work has
results at every step. Drafts, intermediate renders and debug dumps land
next to the finished file and the user is handed all of them.
The four places that describe the workspace now say the same thing: the
collector reads only /workspace/output, so finished deliverables go there
and everything in progress goes anywhere else under /workspace. The
attachment block gains the matching half for the other direction —
/workspace/input holds the user's own files and is not ours to write to,
which it previously implied by calling the paths "read-only inputs" while
the tools that enforce it say so plainly.
Only the /workspace/input half is enforced (write_sandbox_file refuses
that tree). Whether a file is finished is a judgement no tool can make,
so the output half stays guidance and is stated wherever the model is
already reading about the workspace rather than in one place it might
not see.
* fix(skills): restore executable bundles and package recovery
* style(sandbox): wrap prompt text for repository lint checks
* fix(sandbox): guard recovery paths and document root execution
---------
Co-authored-by: hailongzhao <hailongzhao@tencent.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
* fix(system): keep one-time create-user passwords from being discarded
Escape leaked to the Settings modal, and a double submit could replace a
201 reveal with an idempotent 200. Show the password in plaintext and
distinguish create vs retry via an idempotent body flag.
* i18n(system): update copy button and success message for account details
Changed the labels for the copy button and success message across multiple languages in the localization files to reflect the new terminology for copying account details instead of just passwords. This update enhances clarity for users when interacting with the Create User dialog.
* feat(agent): unify sandbox tools and drop host preloaded skills
Read workspace and skill files through read_file, and run installed or staged skills through shell_exec(skill_name). Remove the unused skills/preloaded tree and keep generated-file previews stable across re-renders.
* fix(frontend): do not assume classList in markdown sanitize hooks
Node unit tests stub anchors without a DOM classList. Detect download cards from class/download attributes instead.
The editor no longer exposes inbound access; saves omit
allow_public_inbound so the zero value (require credentials) is stored.
Cube L7 rules can be moved so first-match-wins order is explicit.
* feat(sandbox): add the tenant network policy with its secrets and validation
Administrators need control over sandbox network access, so a named sandbox
config gains a network policy block. It lives inside the existing config JSONB,
so there is no schema change and old rows read back as the zero value.
Both booleans are phrased so that the zero value IS the intended default --
outbound open, inbound closed. That makes "no network block" and "explicitly
saved defaults" provably the same thing, and avoids a tri-state pointer where
nil would have to mean "allowed" for egress and "closed" for ingress.
Injected header values are credentials, so they ride the encrypt-at-rest and
mask-on-read path EnvVars already uses instead of a parallel mechanism. One
CloneWithSecrets traversal serves encrypt, decrypt and mask so the three
directions cannot disagree about which fields are secret.
Validation runs at save time because the alternative is failing at
sandbox-create time, where the admin no longer has the form in front of them.
It rejects both what a provider would refuse and what a provider would accept
without doing what the admin meant -- a domain allowlist with no deny-all
fallback still leaves every unresolved destination reachable.
* feat(sandbox): apply the network policy on both providers, persist the inbound token
Resolve the stored policy into one fully specified provider-neutral policy so
that nothing downstream re-derives a default. Both booleans come out non-nil on
every path, including the nil-tenant one, because a partially specified policy
would let the adapters fall back to their providers' more permissive defaults.
The three inversions (deny-egress to allow-internet, public-inbound, rule-deny
to rule-allow) happen in exactly one place.
Every sandbox-creating path carries it, so sessions, skill installs and the
deep connectivity check all run under the same config's policy rather than
each wiring its own.
Inbound access defaults to CLOSED, deliberately stricter than either
provider's own default: a sandbox URL reachable by anyone who learns the ID is
not a reasonable default for a tenant's workspace. Closing it makes the
provider issue a per-sandbox traffic token, and only at create time -- so the
token is stored with the session binding and replayed through Connect on every
reconnect. Without that, a sandbox that was paused on TTL or rebound after a
restart would answer 403 on every exec and file read, and 403 classifies as an
authentication error rather than NotFound, so the binding would never be
replaced and the session would stay wedged.
Connect therefore takes a request struct instead of a bare ID, which gives the
token a single documented way in rather than implicit state inside an adapter.
Metadata-based recovery is the one reconnect path with no binding to read the
token from. Rather than adopt a sandbox that would be permanently 403, it is
deleted and replaced -- but only for providers that have the credential at
all, since Docker has no inbound token and its containers are still adoptable.
go-e2b keeps the token and never sends it, so for E2B the data-plane
RoundTripper attaches the header from a process-local registry. Cube's SDK
already does this itself.
* fix(sandbox): classify data-plane traffic by authority shape, not the configured domain
isDataPlane suffix-matched the configured sandbox domain, which was wrong in
both directions. Both required a configured proxy_url, so E2B Cloud's default
usage was unaffected; the affected deployments are exactly the self-hosted and
E2B-compatible ones the gateway exists for.
A configured gateway could be silently ignored. sandbox_domain is optional for
E2B -- MissingRequiredFields asks only for api_key and template_id -- and with
it empty the check returned false for everything. The general form is worse
than the empty case: go-e2b's envdBaseURL prefers the domain the control plane
reported over the client-wide one, so the authority actually dialled need not
appear in the config at all. The failure is quiet whenever public DNS happens
to resolve the sandbox domain, and the operator believes traffic is passing
through a gateway that never sees it.
Control-plane calls could be sent to the gateway. E2B's own defaults put the
API host under the sandbox domain (api.e2b.app beneath e2b.app), so the suffix
match classified every Create, Connect and List as data-plane traffic. That
is loud where the gateway does not serve the API, but where it proxies both
planes it succeeds while downgrading an X-API-Key request to plaintext for an
http:// gateway. Cube was immune to the first problem, since it requires both
fields, but not to this one.
Classify on the "<port>-<sandboxID>.<domain>" shape both SDKs generate, using
the SandboxIDFromDataPlaneHost helper that token injection on the very same
request already relies on -- so routing and injection now agree by
construction instead of applying two different rules. That helper exists
precisely because the configured domain is unreliable here; it was simply
never used for the routing half.
The control host stays as an explicit exclusion. The shape test already
rejects api.<domain>, so this only covers an API host that itself wears the
shape, such as 8080-api.example.com.
One existing assertion was replaced rather than kept: the E2B pool test proved
that the Cube fields were ignored by asserting a cube.app authority was not
data-plane traffic, which tested the domain matching rather than the field
selection. It now asserts the transport dials the E2B gateway address and not
the Cube one.
* feat(sandbox): add the network policy editor to the sandbox config drawer
The policy sits in the runtime step, directly under the settings it
constrains, rather than in a step of its own. The existing execution timeouts
were compressed into a two-column grid to make room, keeping each field's own
label and its own tip -- the reason they were one per row was that three
unlabelled numbers sharing a footnote gave no clue which one you were editing,
and two columns with per-field tips does not regress that.
Provider-specific sections are shown only for the backend that has them: the
Cube L7 rule cards, E2B's per-host header transforms, and for Docker just the
bridge/none selector, since Docker can only express the overall switch.
Injected header values are write-only. A stored one shows as configured and is
preserved when the input is left blank, which is how env-var secrets already
behave. Renaming a rule or a header is the case worth care: the merge indexes
credentials on the rule-and-header pair, so a rename means the old value can no
longer be recovered. One helper decides both the placeholder text and whether
the payload re-attaches the value, so the form cannot claim a credential is
kept while the save blanks it.
The add buttons use keys of their own instead of reusing the env-var table's
"add variable", which read wrongly under a list of network destinations and
which the i18n key check cannot catch, since the key exists in every bundle.
* docs(sandbox): document the network policy and its inbound default change
The existing network bullet described the pre-feature state -- both providers
open by default, tunable only through the neutral policy at create time --
which is no longer true of the defaults or of the admin-facing surface.
Three things needed writing down rather than restating.
The inbound default flips from publicly reachable to credential-required. A
deployment that relies on a browser or an external service reaching a sandbox
port directly, rather than going through WeKnora, has to opt back in on that
config.
The binding store now holds a bearer credential in plaintext. Leaving it
unencrypted was a deliberate trade -- per-reconnect crypto on the hot path
against Redis's own access control -- and the trade is only sound if the
requirement is actually stated, along with the code-side constraint it depends
on: a binding or a handle is never logged whole, only the sandbox ID and
whether a credential is present.
On binding loss, a closed-inbound Cube or E2B config no longer adopts its old
sandbox by metadata. The token went with the binding and the provider will not
reissue it, so adoption would produce a session that answers 403 on every
data-plane call with no way back. The sandbox is deleted and rebuilt, which
costs the /workspace scratch. Docker has no such credential and still adopts.
* fix(sandbox): fail closed when a closed-inbound create has no traffic token
A Cube/E2B sandbox created without the inbound token would be bound anyway,
then 403 on every data-plane call as an unreplaceable authentication error.
Refuse the create, destroy the sandbox, and stop Docker from persisting
inbound/egress radios it cannot honour. Canonicalize IPv4 /0 deny-all onto
0.0.0.0/0 and reject CR/LF in injected header names and values.
* fix(sandbox): satisfy pre-push lint on the network policy files
Unexport the data-plane host parser, drop file-level package docs that
revive rejected, and lowercase error-string prefixes that staticcheck
ST1005 treats as capitalized English.
* fix(sandbox): persist rotated inbound tokens and stop misreporting restricted egress
Connect can reissue the traffic token after pause/resume; write it back onto
the binding so a restart does not restore a stale credential that 403s and
cannot be replaced. Restore the volume-support i18n key, map Docker
network_mode=none onto deny-egress, inject the E2B inbound header without a
gateway pool, and fold header names when merging redacted secrets.
---------
Co-authored-by: hailongzhao <hailongzhao@tencent.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
Refuse truncated tool calls, compact-and-retry once on overflow, and let
sandbox files be appended, paged, and batch-edited instead of rewritten.
Models can set context_window (default 200K) so compaction sizes itself
from the real window; agent max_iterations of -1 means unlimited.
* fix(models): show usage details when deletion is blocked
* fix(models): open the matching agent section and cap usage lists
Agent "open configuration" now lands on the tab that owns the binding
(VLM/ASR vs follow-ups), and delete failures keep the server message when
structured details cannot be parsed. Listed KB/agent rows are capped at 50
while totals still drive the deletion guard and dialog headings.
---------
Co-authored-by: Leon <leon_hfut@foxmail.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
Those /skills-sh/owner/repo/slug listings are federated, not native
@owner/slug pages, and the GitHub folder is often deeper than the URL
slug. Resolve them through ClawHub so the commit-pinned handoff names
the real skill path.
- Introduced StopSkill method to allow users to abort ongoing skill installations, enabling retry or uninstall options.
- Updated API documentation to include the new stop endpoint for skills.
- Enhanced frontend components to support stopping skills, including UI updates and user feedback messages.
- Added tests to ensure the StopSkill functionality works as intended, including handling various skill states.
- Updated internationalization files to include new messages related to stopping skills.
The app drops to appuser via gosu, so compose group_add never reaches the
process. Matching the socket GID before the drop lets a mounted Engine API
socket work without chmod 666 on the host.
* fix(auth): record last-active-tenant preference on SwitchTenant
* docs(auth): note SwitchTenant updating last-active-tenant preference
* fix(auth): persist last-active tenant before SwitchTenant tokens
RefreshToken re-resolves from this preference because refresh JWTs omit
tenant_id. Fail the switch if the write fails so a 200 never returns a
token pair whose later refresh would land in a different workspace.
* fix(cli): align HybridSearch interfaces with SDK variadic options
Client.HybridSearch gained ResourceURLOptions; CLI ChunksService and
MCP knowledgeService still used the old signature, so *Client no longer
satisfied those interfaces.
* style(cli): wrap HybridSearch signatures under the 120-column lint
---------
Co-authored-by: wizardchen <wizardchen@tencent.com>
* feat: require opt-in for the Docker sandbox backend
Docker engine access is host-root equivalent, so keep the backend off
until System Settings or WEKNORA_SANDBOX_DOCKER_ENABLED says otherwise.
Also move system-settings help into the title icon and add i18n for
tenant.auto_accept_invitation.
* fix(i18n): drop tenant wording from Docker host-risk copy
The workspace terminology check rejects 租户 / tenant in user-facing strings.
* feat(provider): add LiteLLM as an OpenAI-compatible provider
* docs: use revive-compliant comment for ProviderLiteLLM const
* fix(provider): stop defaulting LiteLLM to localhost under SSRF
The catalog URL localhost:4000 is blocked by default SSRF and does not
match DetectProvider, so UI/CLI could neither save nor auto-detect it.
Use a placeholder host, keep thinking aligned with generic, and sync
ModelSource across types, Swagger, and docs.
---------
Co-authored-by: wizardchen <wizardchen@tencent.com>
* feat: support complex password
* fix: honor runtime complex-password policy on all password writes
Keep the service layer as the last check, share one resolver with invite
registration and admin user create, and drop the leftover startup debug print.
* fix: satisfy pre-push lint on password-policy error paths
The hook diffs against origin/main, so wrap the original error strings
and check c.Error on the new validation branches.
---------
Co-authored-by: wuwc.ew <wuwc.ew@cebwm.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
The endpoints this PR added were reachable but undescribed: Swagger had no
/me/env-vars paths, docs/api/skill.md never mentioned the admin PATCH, and
the Go SDK could neither set a workspace value nor a personal one, so an
integration had to hand-roll the calls.
Regenerates the swag artifacts and adds the missing client methods, plus
the caveat that matters most in practice: values are stored per calling
identity, so a personal value entered in the web UI never applies to a run
driven by an API key.
* feat(agent): preview skill artifacts and verify installs without running them
Generated files open in the chat drawer with overlay/Esc returning to the
list, and install verification no longer executes guessed skill entry
points. A failed install can be retried from the saved archive.
* ui(chat): use a folder icon and corner count for skill artifacts
The eye and document glyphs read as preview or copy, and TDesign's
loading spinner sat beside the icon. A folder with a top-right count
matches the generated-files drawer without covering the toolbar action.
* feat(artifact): implement inline artifact references with previews
Add support for inline artifact references in Markdown, allowing generated files to be displayed as clickable cards. Implemented a new rendering mechanism for artifacts, enabling previews directly from the chat interface. Updated localization files for new inline preview hints and missing file messages. Introduced tests for artifact reference normalization and rendering logic.
* fix(client): document AgentResponseType constants for revive
Touching the const block made golangci-lint require comments on every
exported value. Match the rest of the SDK and describe artifacts_pending.
* fix(agent): wrap artifact-reference prompt lines for lll
Pre-push golangci-lint rejected the branch on three lines over 120
characters in the sandbox: reference guidance.
* fix(agent): scope HTML scripts and tighten install verification
Keep scripted HTML preview on skill artifacts only, recreate sandbox
workspace dirs after they are deleted, and treat nested skill files as
dependencies rather than first-party imports.
* refactor(artifact): enhance artifact reference handling and metadata
Updated artifact metadata to include a stable resource handle for better identification. Adjusted artifact reference resolution to support both handle and name forms, ensuring compatibility with existing references. Enhanced tests to validate the new handling logic and ensure proper rendering of artifacts in chat messages. Improved documentation for clarity on artifact reference formats and their usage in the system.
Local was a host-subprocess fallback that skill install, snapshots, and
session sandboxes already excluded. Drop it so Cube, E2B, and Docker are
the only backends; leftover local configs can only be deleted.
Deleting the WeKnora template before its replacement was ready left
sessions targeting a missing ID, and freeze was per-config while rebuild
is cluster-scoped. Rebuild in place when possible, persist the new
template ID, refuse replace across siblings with skills, and name
snapshots by tenant and config on every backend.
Guest DNS only applies through the WeKnora template spec, and sessions
already on a skill snapshot would miss connection or rebuild changes.
Stop auto-creating templates, require explicit create/rebuild, and
refresh the settings card list when installs finish.
Added a new column `planned_name` to the `tenant_skill_snapshots` table to store the intended name of a snapshot before the provider call. This allows for the identification and reclamation of abandoned builds that may have left unreferenced snapshots due to process failures. Updated related functions to utilize this new field for better snapshot management and cleanup.
Docker already ran session sandboxes, but skill install required snapshots
that only Cube and E2B advertised. Commit local skill images, boot sessions
from them, and show the skills step for Docker configs.
Updated documentation across multiple files to specify that the `source` for skill installation must be explicitly defined as `@owner/slug` for ClawHub or a full URL for GitHub/SkillHub. Bare `owner/slug` is now rejected as ambiguous. This change enhances clarity for users regarding valid input formats and improves error handling in the installation process.
Updated the skill installation process to eliminate the need for a token when installing skills from ClawHub, SkillHub, or Git URLs. The source must now be readable anonymously, ensuring that no credentials are sent during the fetch process. Adjusted related documentation and UI components to reflect this change, enhancing the user experience by simplifying the installation workflow.
* feat: support editing document summaries
* fix: address review feedback for manual summary editing
Reset summary edit state when the drawer closes or generation is in
flight, sync summary_status on manual description updates, and add
service tests plus API docs for partial PUT behavior.
* chore: gofmt client/initialization.go for pre-push hook
---------
Co-authored-by: wizardchen <wizardchen@tencent.com>
* feat(datasource): add Feishu/Lark Drive (云盘) connector
Add a new Drive (云盘) data source alongside the existing Feishu wiki
connector, letting users sync documents/files under a user-supplied Drive
folder_token. Shares the feishu connector package (Client/Config/Region/
export/download/error-handling) with the wiki connector; only resource
enumeration and fetch dispatch differ.
Backend:
- types/datasource.go: ConnectorTypeFeishuDrive / ConnectorTypeLarkDrive
- region.go: RegionFeishuDrive / RegionLarkDrive + driveFolderURL
- types.go: driveFile / driveFileListResponse / partialDriveFileListError
/ feishuDriveCursor
- client.go: ListDriveFiles / ListDriveFilesRecursiveFrom (shortcut
expansion via shortcut_info, visited cycle guard, root-folder rejection)
- drive_connector.go: DriveConnector implementing StreamingConnector
(FetchStream) + FetchAll + FetchIncremental fallback paths, mirroring
the wiki connector's three cursor semantics (resume fast-path,
failure-does-not-advance-cursor, toSyncCursor snapshot), plus
ListResources / ResolveResourceAncestors (top-down shared traversal,
best-effort) / fetchDriveFileContent / parseDriveResourceID
- container.go + connector.go: register two Drive instances + metadata
Incremental detection uses modified_time returned directly by the list
API (verified) - no batch_query/metas call needed. Shortcuts are expanded
at list-parse time via shortcut_info; target_type is never "folder".
Frontend:
- DataSourceEditorDialog.vue: connectorDefs for feishu_drive/lark_drive,
Drive root folder_token input + load button before the lazy-load tree,
edit-mode prefill from resource_ids
- datasourceIcons.ts: reuse feishu/lark icons
- i18n (zh-CN/en-US/ko-KR/ru-RU): connector labels, descriptions, drive
input group
Co-Authored-By: Claude <noreply@anthropic.com>
* fix(datasource): refine Feishu Drive connector UI, channel and root folder
A batch of fixes from end-to-end verification of the Feishu/Lark Drive
connector, all aimed at matching the wiki connector's behavior:
Channel (knowledge "source" label):
- Add ChannelFeishuDrive / ChannelLarkDrive constants so Drive docs show
"飞书云盘" / "Lark 云盘" instead of "unknown", distinct from the wiki
connector's "飞书" (ChannelFeishu).
- fetchDriveFileContent / appendDriveFileListFailureItems select the
channel by region via a new driveChannel() helper.
- ingestItem now prefers metadata["channel"] over ds.Type so the
connector-supplied channel value reaches the knowledge base.
- doc-content.vue channelLabelMap maps feishu_drive/lark_drive.
Frontend Drive picker UX:
- loadDriveRoot persists the new folder_token in edit mode too (previously
skipped updates in edit mode, so listResources read the old token).
- The folder_token input is now always visible alongside the tree (not a
switch); the tree area shows a "load a folder first" placeholder until
the first successful load.
- extractDriveFolderToken accepts a bare token or a Feishu Drive folder
URL (https://xxx.feishu.cn/drive/folder/<token>) and extracts the token.
- Edit mode auto-loads when a saved folder_token exists, and reveals
pre-existing selections via revealExistingSelections.
- Classify Drive list errors (403/forbidden, 401/auth, not-found) into
actionable i18n hints.
Root folder name & selection:
- Add GetDriveFolderMeta (GET /drive/explorer/v2/folder/:folderToken/meta)
to resolve the root folder's human-readable name; the list API only
returns children. Best-effort, falls back to the token.
- Fix root folder ExternalID to be the bare rootFolderToken (no ":token"
suffix) so it matches the saved resource_id form and the direct
children's ParentID, which previously broke selection matching on edit.
Co-Authored-By: Claude <noreply@anthropic.com>
* fix(datasource): sync a single selected Drive file without folder error
When a user selects a single file (not a folder) in the Drive picker, the
resourceID is "rootFolderToken:fileToken". FetchStream/FetchAll/
FetchIncremental previously passed fileToken straight to
ListDriveFilesRecursiveFrom, which expects a folder token - the Feishu
list API returns 1061002 (params error) for a file token, failing the
whole sync with "all fetched items failed".
The wiki connector resolves a single selected node via GetWikiNode; Drive
has no single-file meta API (folder meta only works on folders, and
metas/batch_query requires doc_type as input - a chicken-and-egg).
Instead, listDriveFilesForResource walks the root folder subtree (the
file's parent) and filters to the selected fileToken, yielding the full
driveFile (type/name/modified_time) needed for fetchDriveFileContent.
A sub-folder selection (fileToken is itself a folder) still walks that
sub-folder directly - ListDriveFilesRecursiveFrom accepts a folder token,
so no filtering is needed there.
Co-Authored-By: Claude <noreply@anthropic.com>
* ci: add build-test-images workflow for tar.gz artifact export
Manual-only workflow_dispatch that builds linux/amd64 Docker images for
the current branch and exports them as .tar.gz artifacts downloadable
from the Actions run page. No Docker Hub push, no secrets required.
- build-ui: builds frontend dist, builds weknora-ui image, exports tar.gz
- build-app: builds weknora-app image (CGO + duckdb), exports tar.gz
- Input choice: build both / app only / ui only
- Artifacts retained 7 days
Co-Authored-By: Claude <noreply@anthropic.com>
* ci: add build-test-images workflow for tar.gz artifact export
Manual-only workflow_dispatch that builds linux/amd64 Docker images for a
selected branch and exports them as .tar.gz artifacts downloadable from the
Actions run page. No Docker Hub push, no secrets required.
- build-ui: builds frontend dist, builds weknora-ui image, exports tar.gz
- build-app: builds weknora-app image (CGO + duckdb), exports tar.gz
- Input choice: build both / app only / ui only
- Artifacts retained 7 days
Placed on the default branch so the workflow appears in the Actions list;
trigger it with the branch you want to build (e.g. feat/datasource-feishu-drive).
Co-Authored-By: Claude <noreply@anthropic.com>
* docs(datasource): add feishu shared-blocks extraction design spec
Co-Authored-By: Claude <noreply@anthropic.com>
* docs(datasource): add feishu shared-blocks implementation plan
Co-Authored-By: Claude <noreply@anthropic.com>
* feat(datasource): sync feishu drive docx via blocks API with export fallback
- Extract wiki/drive shared helpers from connector.go into shared.go
- Make fetchDocxWithBlocks a package-level function taking docxFetchInput
- Drive docx now renders via blocks API (Markdown + attachment/image
sub-items), falling back to the export API on blocks errors or empty
renders, mirroring the wiki connector
- fetchDriveFileContent returns item slices and takes multimodalEnabled
Co-Authored-By: Claude <noreply@anthropic.com>
* fix(frontend): label feishu drive knowledge as 飞书云盘 in list
The knowledge list source column (DocumentListView.getSourceInfo) only
whitelisted feishu/notion/yuque/etc., so feishu_drive/lark_drive docs
fell through to the default "上传" label while the wiki connector's
"feishu" showed "飞书". Map feishu_drive → 飞书云盘 and lark_drive →
Lark 云盘 (i18n keys already existed), and add feishu_drive to the
source filter options in KnowledgeBase.vue.
Co-Authored-By: Claude <noreply@anthropic.com>
* fix(frontend): polish feishu drive resource-step UI in datasource editor
- Replace the two stacked t-alert banners under the folder_token input:
shareHint becomes an always-visible form-desc line, rootNotSupportedHint
moves into a help-circle tooltip next to the label.
- folder_token is now required: red asterisk on the label, inline error
status + tips on the input (replacing the global MessagePlugin) when
empty on 加载/下一步, cleared on input.
- Step 2 选择范围 no longer scrolls as a whole: the token input stays
fixed and the resource region (placeholder / loading / empty / tree)
fills the remaining drawer height, with the tree scrolling internally.
Co-Authored-By: Claude <noreply@anthropic.com>
* docs(datasource): add feishu drive datasource integration guide
User-facing setup guide for feishu_drive/lark_drive: app creation,
required scopes (drive:drive:readonly / drive:export:readonly /
docx:document:readonly), sharing the folder to the app's group, the
four-step wizard, supported file types, sync semantics and FAQ.
Also clarify in extractDriveFolderToken's comment that pasted folder
URLs are matched by path and work for Lark links too.
Co-Authored-By: Claude <noreply@anthropic.com>
* refactor(datasource): unify feishu wiki/drive sync into a single generic streaming engine
Extract a single generic streaming sync engine (engine.go) shared by the wiki Connector and the Drive DriveConnector. Per-connector differences (node type, listing API, edit-time field, cursor wire format, fetch dispatch, log tag) are isolated behind the NodeOps[N] adapter; FetchAll/FetchIncremental become thin shells over the same engine.
Deliberate behaviour changes (design §2.4): the #2136 failure-doesn't-advance-cursor fix now applies to FetchIncremental too (previously it advanced the cursor before fetching, permanently skipping a node on a transient export failure); logs use 'stream progress/summary' uniformly and the FetchIncremental path gains per-100 progress + tally summary logs.
Structural prep for package split (design §3.1): anonymous Data structs in types.go/blocks.go are named so tests can construct wire types across packages.
Co-Authored-By: Claude <noreply@anthropic.com>
* refactor(datasource): split feishu connector into core/wiki/drive packages
Move shared code (Client, blocks, markdown, types, region, engine, shared helpers) into feishu/core; wiki and drive connectors into their own packages. Export core symbols (capitalize) so wiki/drive can reference them; wiki/drive import core and prefix cross-package references.
container.go registration updated to import core/wiki/drive (NewConnector from wiki, NewDriveConnector from drive, Region* from core).
Tests are NOT migrated yet (left in feishu/ root, package feishu) and will fail to compile until moved + adapted in a follow-up commit. Source builds clean (go build ./...feishu/... passes).
Co-Authored-By: Claude <noreply@anthropic.com>
* test(datasource): migrate feishu tests to core/wiki/drive packages
Move 14 test files to their subpackages per design §4. Adapt package declarations, imports, and capitalized core symbol references. Add TestMain (SSRF whitelist) to core and drive. Add local helpers (writeJSON, makeConfig, txt, blk constructors, recordingHandler) where cross-package sharing was not possible. Fix engine.go log wording (summary) clobbered by the capitalization script.
All tests pass: core 4s, wiki 13s, drive 3s.
Co-Authored-By: Claude <noreply@anthropic.com>
* refactor(datasource): reduce feishu core export surface; add drive cursor round-trip test
Lower-case 87 core symbols that are not referenced cross-package back to unexported (BlocksToMarkdown, CellToString, response types, BlockType constants, etc.), shrinking core's API surface to only what wiki/drive actually use. Restore NodeOps.Fetch capitalization (interface method must match wikiOps/driveOps implementations).
Add TestDriveCursorRoundTrip (design §3.2): driveOps.EncodeCursor/DecodeCursorTimes were new code with no direct test.
All tests pass: core 3.5s, wiki 13s, drive 3s.
Co-Authored-By: Claude <noreply@anthropic.com>
* fix(datasource): repair feishu cleanup fallout
Restore core.RegionLarkDrive (cleanup lower-cased it; only container.go references it, outside wiki/drive scan). Restore wiki/connector_realapi_test.go local collectHandler type (cleanup wrongly prefixed core.). Apply gofumpt to helpers_test.go. Add open.feishu.cn/open.larksuite.com to test SSRF whitelist: BaseURL-default tests call ParseFeishuConfig which SSRF-validates the resolved hostname; under a proxy open.feishu.cn resolves to 198.18.0.0/15 restricted range.
All tests pass: core 3.2s, wiki 13s, drive 2.6s. make build-lite passes.
Co-Authored-By: Claude <noreply@anthropic.com>
* feat(frontend): feishu drive data source UI and i18n
Add Drive folder/token picker strings and data source editor entries for the feishu_drive/lark_drive connectors across en-US/zh-CN/ko-KR/ru-RU.
Co-Authored-By: Claude <noreply@anthropic.com>
* chore: add trellis journal merge=union rule
Append-only developer journals merge cleanly across parallel sessions; task state lives in task.json, not the journal.
Co-Authored-By: Claude <noreply@anthropic.com>
* refactor(datasource): rename feishu/drive drive_connector.go to connector.go
Aligns naming with feishu/wiki subpackage (connector.go).
Co-Authored-By: Claude <noreply@anthropic.com>
* fix(frontend): allow data:image base64 URIs in sanitized markdown
DOMPurify's ALLOWED_URI_REGEXP rejected data: URIs, so <img src="data:image/...">
in uploaded markdown files had their src stripped during sanitizeHTML — the file
preview showed broken images while the chunk view (minio:// via
hydrateProtectedFileImages) worked. Add data:image/ to the allowed URI scheme so
base64 images render in preview and in LLM answers that embed base64 images.
Co-Authored-By: Claude <noreply@anthropic.com>
* feat(datasource): add FEISHU_DOCX_PARSE_MODE for feishu docx parse path
The blocks API path renders image blocks as empty ![图片]() placeholders and
fans images into separate knowledge items, breaking image↔document association
across retrieval/wiki/agent. FEISHU_DOCX_PARSE_MODE=export forces the async
export API (.docx binary -> docreader), so images are parsed inline and bound to
the parent document via parent_chunk_id (same as a regular docx upload). Default
(unset / "blocks") keeps the existing blocks-first behaviour. Affects both wiki
and drive connectors since they share FetchDocxWithBlocks.
Co-Authored-By: Claude <noreply@anthropic.com>
* feat(datasource): default FEISHU_DOCX_PARSE_MODE to export
Switch the feishu docx parse default from blocks to export so embedded
images are parsed inline and bound to the parent document via
parent_chunk_id (retrieval / wiki / agent all associate images). Operators
who need the blocks behaviour (faster, keeps docx attachments, no
docreader round-trip) set FEISHU_DOCX_PARSE_MODE=blocks.
- shared.go: default unset -> export; update comment to match
- .env.example / docker-compose.yml: default export
- tests: pin FEISHU_DOCX_PARSE_MODE=blocks on blocks-behaviour tests so
they don't break under the new default
Co-Authored-By: Claude <noreply@anthropic.com>
* docs(datasource): document FEISHU_DOCX_PARSE_MODE and refresh feishu source layout
- 飞书云盘接入说明: add section on docx parse mode (export default vs
blocks), permission differences, export tradeoffs
- 数据源导入开发: add env var + mode comparison
- 数据源导入开发文档: rewrite content fetch flow (blocks/export paths),
add pros/cons table, fix source-file table to core/wiki/drive layout
Co-Authored-By: Claude <noreply@anthropic.com>
* fix: 修复合并main后丢失新增的国际化问题
* fix(i18n): 修复误删的国际化内容
* docs: 删除误提交的文件
* feat(im): support reverse proxy for feishu websocket long connection
Add api_base_url channel config for Feishu/Lark IM adapters so internal
deployments can route Feishu API calls and the WebSocket long connection
through a reverse proxy (nginx). The config overrides both the SDK
bootstrap domain (WithDomain) and the adapter HTTP API origin (api()),
unified into a single field.
- adapter: NewAdapter gains apiBaseURL + SSRF validation (http(s) scheme,
ValidateURLForSSRF), mirroring wecom's validateEndpointURL; api() uses
the override instead of region.OpenBaseURL
- longconn: NewLongConnClient forwards apiBaseURL to larkws.WithDomain
- factory: reads api_base_url once, passes to both adapter and longconn
- frontend: Feishu/Lark channel config gains an API Base URL input
Co-Authored-By: Claude <noreply@anthropic.com>
* fix(ci): restore build-test-images workflow dropped by 00d7090f
00d7090f ("docs: 删除误提交的文件") deleted build-test-images.yml
alongside two obsolete design docs, causing the workflow_dispatch
trigger to disappear from the branch. Restore it so the manual
build-test-images action is available again.
Co-Authored-By: Claude <noreply@anthropic.com>
* feat(im): support reverse proxy for feishu websocket long connection
飞书 SDK 的 WebSocket 长连接分两阶段:bootstrap HTTP 拿 ws 地址 + ws dial
直连飞书下发的地址。WithDomain 只控制 bootstrap 请求目标,ws dial 的地址
由飞书服务端下发(host 为 msg-frontier.feishu.cn),SDK 不支持改写。
内网部署无法直连飞书 wss,因此新增 api_base_url 字段:让 bootstrap 和
HTTP API 走反代,并通过 nginx sub_filter 改写飞书下发的 wss 地址为明文
ws,使 ws dial 也经反代回连 nginx。
Co-Authored-By: Claude <noreply@anthropic.com>
* feat(frontend): add api_base_url config for feishu IM channel
新增 api_base_url 配置入口与 i18n 文案,用于内网反代部署。
Co-Authored-By: Claude <noreply@anthropic.com>
* docs(im): document feishu api_base_url reverse proxy usage
补充 nginx 反代配置说明:三个 location(bootstrap/open.feishu.cn +
sub_filter、ws dial/msg-frontier.feishu.cn、OpenAPI/open.feishu.cn),
以及 sub_filter 改写 wss 地址、rewrite 前缀剥离、SSRF 白名单等要点。
Co-Authored-By: Claude <noreply@anthropic.com>
* feat(ci): add manual docker build workflow
Add a workflow_dispatch-only workflow to build ui/app/docreader/sandbox
images on demand. No auto-trigger on push/tag. Each package is gated by
a boolean input (build_all + per-package), and the branch is picked via
the native workflow_dispatch ref selector. Builds are load-only (push
false) to verify Dockerfiles without needing any registry secret.
Co-Authored-By: Claude <noreply@anthropic.com>
* fix(ci): sync manual docker build workflow from main (add tar export + unified package job)
* Delete .github/workflows/docker-build.yml
* Delete .github/workflows/build-test-images.yml
---------
Co-authored-by: Claude <noreply@anthropic.com>
* feat(sandbox): unify remote sandbox on E2B protocol with self-hosted support
- Add e2b.proxy_url gateway config and generic gateway transport layer
- Add envd compat layer for Basic auth and multipart /files uploads
- Support Dockerfile.sandbox runtime and e2b-backend build targets in CI
- Rename sandbox image non-root user to align with E2B template convention
- Add sandbox-protocol.md and extend cluster deployment / local repro docs
Enables connecting to any E2B-compatible control plane (E2B Cloud,
CubeSandbox, Agent-Sandbox, etc.) without per-backend client code.
* style(sandbox): gofmt tenant_resolver struct alignment
New endpoint GET /api/v1/auth/oidc/start — unlike /auth/oidc/url which
returns JSON and requires frontend JS to navigate, this endpoint directly
returns a 302 redirect to the OIDC Provider's authorization page. This
enables external platforms (enterprise portals, Nexus, etc.) to give a
single clickable link that triggers the full OIDC authorization code
flow and, when the IdP has an active SSO session, achieves passwordless
login without any frontend involvement.
- backend derives the callback URL from the request origin automatically
(no caller-supplied redirect_uri needed)
- OIDC nonce cookie is bound identically to /auth/oidc/url (CSRF/replay
protection)
- registered in the auth middleware public-path whitelist (otherwise
the global auth middleware returns 401 before routing reaches the
handler)
- refactored shared nonce-cookie helper out of GetOIDCAuthorizationURL
for reuse by OIDCStart
* cubesandbox support
* feat(agent): add sandbox shell execution, file management tools, and Artifacts collection/download system
- Add three sandbox agent tools: shell_exec / sandbox_ls / sandbox_read
- shell_exec: safely execute shell commands in session sandbox with timeout & output truncation
- sandbox_ls: enumerate files under sandbox artifact output directory with recursive listing & pagination
- sandbox_read: read sandbox file content with offset-based chunked reading
- Add Artifacts system:
- ArtifactCollector: real-time collection of sandbox tool output files, attached to messages
- /api/artifacts/{session_id}/{message_id}/{filename}: download endpoint for frontend
- ChatArtifactsDrawer.vue: frontend artifacts sidebar UI
- DB migration 000066_message_artifacts: add artifacts column to messages table
- Attachment sandbox staging: upload user attachments to session sandbox on QA request for skill tool access
- Update Agent Prompts: add shell/sandbox tool usage constraints and safety rules
- Extend Agent Observe: include agent steps in Langfuse observability tracing
- Refactor Sandbox SessionManager: support session-scoped file listing, reading, and status queries
- Frontend: render artifact events in AgentStreamDisplay, i18n updates for 4 locales
- Add comprehensive tests: shell_exec_test, sandbox_read_test, artifact_collector_test, etc.
* feat(agent):add remote sandbox client abstract & client errors
* feat(sandbox): implement Redis binding store with distributed lifecycle lock;
* feat(sandbox): add remote session lifecycle with ownership context
Implement remoteSessionLifecycle to coordinate persistent remote sandboxes
across multi-instance deployments. Supports Resolve (lazy provision,
recovery, race-safe create) and Destroy with compare-delete semantics.
Add ownership context isolation to decouple remote resource cleanup from
request cancellation.
* feat(sandbox): add CubeRemoteClient adapter for RemoteSandboxClient
Implement CubeRemoteClient as a provider-neutral RemoteSandboxClient
implementation. Error normalization, timeout mapping, and metadata
support are fully integrated. SDK details remain private to the
adapter.
* refactor(sandbox): decouple SessionBoundManager from Cube
Remove internal/sandbox/cube.go (CubeSandbox, sync.Map reaper). Add
RemoteSandbox as provider-neutral Sandbox interface implementation.
Rewrite SessionBoundManager to depend on RemoteSandboxClient +
SessionSandboxBindingStore + SessionExistenceChecker, with all
lifecycle ops delegated to remoteSessionLifecycle (Redis + distributed
lock). Application-layer interfaces migrated to RemoteDirEntry/StatEntry
with time.Time ModTime. Cleanup delegated to provider idle-timeout.
* refactor(agent): enhance session capability handling in sandbox manager
- Introduced sessionFileStore and sessionShellExecutor functions to centralize capability checks for session-scoped file and shell execution.
- Updated agent service to register tools based on the presence of session filesystem capabilities, improving compatibility with various sandbox backends.
- Refactored tests to validate behavior when session capabilities are absent, ensuring robust handling of different sandbox types.
- Removed Cube-specific checks, promoting a more provider-neutral approach to session management.
* refactor(sandbox): add E2B backend, modernize Cube adapter, and enable multi-instance Redis binding
- Add e2b_remote_client.go (~850 lines) — full RemoteSandboxClient implementation
covering lifecycle, execution, and filesystem ops (ListDir/Stat/MakeDir/Remove)
- Wire E2B into NewManagerFromType and container/bootstrap path (buildE2BManager)
- Dependency: matiasinsaurralde/go-e2b v0.1.0
- Cut ~1500 lines of legacy SDK wrapper (cube_client.go, cube_envd.go,
cube_defaults.go) and replace with direct *cubesandbox.Client usage
- Parse CubeProxy URL directly in adapter (parseProxyURL), removing the
old hand-rolled envd transport layer
- Pass lifecycle extra fields (onTimeout, autoResume) via SDK CreateOptions.Extra
- Target Cube deployment v0.5.1
- Add RemoteNetworkPolicy to RemoteCreateRequest with AllowInternetAccess,
AllowPublicTraffic, AllowOut/DenyOut — shared by Cube and E2B adapters
- Both adapters default to permissive (internet+public on) for backwards compat
- Add selectSessionBindingStore() — Redis-backed or in-memory, controlled by
WEKNORA_SANDBOX_REDIS_NAMESPACE / WEKNORA_REDIS_NAMESPACE
- Add repositorySessionExistenceChecker — checks session existence via DB
(gorm.ErrRecordNotFound → not exists, transient errors → preserve binding)
- newSandboxManager() now accepts redisClient + sessionRepo; deprecated
hardcoded NewMemorySessionSandboxBindingStore() in production path
- buildSessionCreateRequest default timeout action: Kill → Pause+AutoResume
(Cube and E2B). Sessions survive brief idle periods; providers still
handle TTL-based reaping.
- buildSessionCreateRequest() and effectiveHTTPTimeout() parameterized
by RemoteProvider (was hardcoded to Cube Config fields)
- NewSessionBoundManager validates provider and delegates defaults to
per-provider apply*Defaults helpers
- Legacy SDK wrapper: cube_client.go, cube_envd.go, cube_defaults.go,
cube_envd_test.go, cube_net_diag_test.go, cube_test.go (~2500 lines)
- Unused helpers: DefaultManager.validateExecution, IsRemoteTerminal,
IsRemoteUnsupported, IsRemoteTransient, ShouldPreserveRemoteBinding
- Dead Config fields: CubeEnvdPort, CubeIdleTTL, AllowedCmds
- Dead ExecuteResult method: GetOutput
- Unused test: session_artifacts_integration_test.go
- Preloaded skill: sandbox-test-python
- Extract shared httpErrorKind() from per-adapter normalize functions
- Add SupportsFilesystemEnumeration capability flag — gates SessionFileStore
advertisement (E2B returns true post-reconnect, Cube always true)
- Fix stale comments: Cube-only → remote backends, remove "tomorrow"/"future"
- Bump session sandbox TTL defaults: 604800s → 300s (.env.example)
- Update docs/agent-skills.md: full multi-instance deployment guide
Total: 29 files, +1188 / -3721
* feat(agent): bind collected skill artifacts to owning message in resource registry
When ArtifactCollector persists a skill-generated file it now registers a
resource:// binding (owner_type=message, owner_id=assistantMessageID,
relation=artifact) in addition to the messages.artifacts JSONB record. This
mirrors how knowledge uploads and chat attachments bind their resources, so
artifacts can be enumerated and garbage-collected through the resource
registry instead of only via the message JSONB column.
- ArtifactCollector: inject ResourceCatalog, add messageID to Collect/
maybePersist, and add best-effort bindArtifactResource (binding failures are
logged, never drop the artifact; only resource:// refs are bound).
- agent_stream_handler: pass assistantMessageID into Collect.
- Renumber message_artifacts migration 000066 -> 000077 to resolve the
version collision with existing migrations (upstream now uses 000075/000076).
- Tests: update collector signatures and add coverage for the binding path
and for graceful degradation when Bind fails.
Note: binding applies to newly generated artifacts only; existing rows are
not backfilled.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(sandbox): harden remote sandbox security and artifact collection
Disable Cube local fallback so skill scripts never run on the host when
the remote provider is unavailable. Require Redis for cube/e2b binding
unless WEKNORA_SANDBOX_ALLOW_MEMORY_BINDING=true for single-node dev.
Collect artifacts with WithoutCancel so user stop does not drop files,
reject shell_exec work_dir outside /workspace, and refuse session-scoped
Execute when a local fallback would be engaged.
* fix(ci): gofmt sandbox files and resolve artifact drawer type error
Apply gofmt to PR-touched Go files and narrow ChatArtifactsDrawer
props in AgentStreamDisplay so session-id is always a string.
* fix(sandbox): adapt to upstream main after rebase
Renumber the message_artifacts migration 000077 -> 000079: upstream now
uses 000077_remove_wiki_log and 000078_chunk_editing_and_custom_metadata.
Declare empty model-handle policies for shell_exec / list_sandbox_files /
read_sandbox_file. Upstream added a coverage test requiring every
UI-exposed tool to declare one; sandbox output is arbitrary skill-authored
content, so it gets the same treatment as execute_skill_script.
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(sandbox): replace single tenant sandbox config column with a configs table to support multi-sandbox config per tenant.
* feat(sandbox): add sandbox config entity, cordon lease and session pin field
* feat(sandbox): add sandbox config repository with tenant scoping and cordon lease
* feat(sandbox): stamp sandbox config ID onto sandbox metadata
* feat(sandbox): scope sandbox listing, release and reaping to a single config
* feat(sandbox): resolve managers per config and refuse cordoned or missing configs
* feat(sandbox): implement session pinning and config identity change detection
- Add SessionSandboxPinner with read/pin/clear to bind session to config
- Refactor four entry points (execute/attachment/artifact/destroy) to use pinned config
- Add config_identity.go to detect identity changes by effective values (APIURL/APIKey/Domain/ProxyURL)
- Add SandboxIdentityChanged with key-masked comparison to prevent false 409 conflicts
- Fix artifact collection for default backend and destroy for legacy empty-pin sessions
* feat(sandbox): add multi-tenant sandbox config management and HTTP APIs
Service layer:
- Add sandbox config business service supporting CRUD and inventory listing
- For non-identity changes (e.g., template, TTL), save directly without locking or remote interactions
- For identity changes (e.g., API key, endpoint), reject save if there are still live sandboxes under this config on the remote side,
and return structured inventory details (sandbox count, affected sessions, related agents) for frontend prompting
- Before deleting a config, check remote live sandboxes; if occupied, reject and prompt user to end sessions or create a new config
- Identity comparison based on effective values to avoid normal saves being misidentified as credential rotation
HTTP interfaces and routing:
- Add REST endpoints for sandbox config (List/Create/Get/Update/Delete/Inventory)
- Mask sensitive credentials (API key, etc.) in all read responses
- Return 409 with structured inventory details on rejection scenarios
- sandbox-check probing supports specifying an existing config_id directly
- Remove old handler file, consolidate validation logic into service layer
- DI wiring and route registration for all six endpoints
* feat(sandbox): add sandbox_config_id field to allow agent referencing named sandbox config
- Add SandboxConfigID field to CustomAgentConfig with omitempty; empty value falls back to global defaults
- Validate config existence on create/update; return 400 if not found
- Inject sandboxConfigService into CustomAgentHandler
- Add unit tests covering field serialization and validation logic
* feat(sandbox, agent): Migrate sandbox config to multi-config CRUD, support named backend selection and workspace scripts policy
Migrate frontend API from legacy KV single-config to /sandbox-configs REST interface, supplement type definitions, detection methods and policy fields; refactor sandbox settings page to multi-config card grid, manage configs with cube/e2b tabs, add editor drawer for create/edit/delete, connection testing and occupancy hints, and add workspace scripts policy toggle; add sandbox config dropdown in Agent editor skill section, integrate config caching, and support selecting named config or falling back to deployment default.
* feat(sandbox): Unify sandbox disable semantics and add tenant-level policy master switch
- Backend: Unify interception in resolveTenantSandboxForConfig with priority: global disable > tenant disable > default fallback > named config; add deploymentSandboxDisabled() using env var to avoid mis‑impacting named E2B; update WorkspaceSandboxPolicy comment as master switch for entire workspace; add unit tests for various scenarios.
- Frontend: Sync i18n copy: button text changed to "Disable/Enable sandbox execution"; confirmation dialog clarifies impact scope; success/failure messages aligned.
- Semantic layering: WEKNORA_SANDBOX_MODE=disabled disables globally; tenant‑level "Disable sandbox execution" only disables for the current workspace.
* feat(sandbox): Add SSRF protection, Agent binding to named configs, and reference query capabilities
- Add outbound URL security guard to validate Cube/E2B API/Proxy addresses against SSRF (including cloud metadata), support allowing private endpoints via env var, link-local always blocked
- Add named backend type validation, only cube/e2b can be stored as workspace named config
- Add sandbox config ID field to Agent at runtime, resolve sandbox for attachments and execution based on Agent's selected named config instead of always global default
- Add query to list Agents referencing a sandbox config ID, useful for deletion/changes to show dependents
- Adapt artifact collector and other callers to fill missing resolve signature parameter
* fix(sandbox): fix session teardown and config-update, add HTTP pool sharing for Cube
Session teardown & deletion ordering
- Move sandbox destroy (and pin `Clear`) before soft‑delete operations (`DeleteSession`/`BatchDeleteSessions`/`DeleteAllSessions`) to prevent remote sandbox leaks and stale pins.
- Pass deployment‑wide `SessionBoundManager` as fallback into `resolveTenantSandboxForConfig` for sentinel pins (`"-"`) to support deployment‑default sessions.
## Config update edge cases
- When identity fields change but old credentials cannot build a client or list config sandboxes, log a warning and proceed with the update instead of returning `sandbox_inventory_unverifiable`; live sandboxes still return 409.
- UI: move `sandboxes_still_live` / `unverifiable` alerts to the top of the sandbox config drawer and auto‑scroll on save refusal and connectivity check results.
Artifact collection for Cube skills
- Pre‑create `/workspace/output` via envd with correct ownership/permissions for `DefaultSandboxExecUser` to ensure Cube skill artifacts are collected properly by `ArtifactCollector`.
HTTP pool sharing for named Cube configs
- Named sandbox configs rebuilt a client on every `Resolve`, causing fresh TCP connections to CubeAPI and the envd proxy on each request.
- Add `CubeTransportPool` and `cubeSplitTransport`:
- Control plane traffic reuses the same `SharedTransport` as E2B.
- Data plane traffic uses a guarded transport cached per proxy host:port, preserving the sandbox `Host` header.
- Wire the pool through the tenant resolver `buildClient`; keep SDK defaults for the deployment‑default manager and connectivity probes.
* feat(sandbox): sandbox execution DefaultUser change from root to user
* fix(multi-sandbox-config-per-tenant): align deployment config with tenant resolver and centralize defaults
- Merge form overrides onto DeploymentConfig() via WEKNORA_SANDBOX_* env vars
instead of DefaultConfig() hardcoded values, allowing empty fields to inherit
from .env rather than Go constants
- Centralize deployment baseline parsing in sandbox/defaults.go with
DeploymentConfig, CubeConfigFromEnv, E2BConfigFromEnv
- Delegate container startup to shared helpers to avoid drift
- Propagate tenant env_vars through ResolveEffectiveConfig into
buildSessionCreateRequest for both Cube and E2B session sandboxes
* fix(multi-sandbox-config-per-tenant): fix some bugs frontend.
* fix(sandbox): guard check-path dials, fix staging gate and shared-agent binding tenant
Three defects found while reviewing the remote sandbox work:
- The Cube connectivity probe and the deployment-default Cube/E2B managers
built clients without a guarded transport, so an admin-supplied api_url or
proxy_url could reach link-local addresses via DNS rebinding even though
save-time validation passed. All three now dial through the same outbound
guard the per-tenant resolver enforces.
- Attachment staging was gated on the process-wide manager, so a workspace
pointing an agent at a named Cube/E2B config while the deployment default
stayed docker/local would run its tools remotely against an empty
/workspace/input. The gate now resolves the manager the session actually
runs on.
- Session to sandbox bindings were keyed by the tenant in context, which a
shared agent deliberately swaps for the agent owner's so models, KBs and
named configs resolve in the sharing workspace. Session deletion only ever
knows the session's own tenant, so teardown looked up a key nobody wrote
and abandoned a paused MicroVM that keeps billing. The binding tenant is
now carried separately and survives CloneContext.
* chore(sandbox): renumber migrations above upstream and de-collide test stub
Upstream main took 000079 (knowledge_folder_path) and 000080
(knowledge_base_auto_tag_config) while this branch was open, so the three
sandbox migrations move to 000081-000083. golang-migrate requires unique,
ordered versions, and the RAISE NOTICE labels move with the file names.
Main also added a handler test declaring stubSessionService in the same
package; the artifact download test's configurable variant is renamed rather
than merged, since the two stubs answer GetSession differently.
---------
Co-authored-by: hailongzhao <hailongzhao@tencent.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
- Reconcile stale pending invites after auto-accept AddMember
- Adopt invited workspace as home tenant when invitee is tenantless
- Await refreshFromAuthMe on SPA boot; sync auto_accept in hydrateSessionFromToken
- Document capabilities.auto_accept_invitation; extend client SDK and OpenAPI
Address post-merge review: verify old password before policy checks,
reject same-password rotations, mark OIDC-provisioned users in preferences
and hide the self-service form with guidance, map API error details to
i18n, sync docs/api, Swagger, and the Go client SDK.
Automatic tagging shipped with a few paths that quietly disabled it and a
prompt that spent most of its budget on data the model never needed.
Robustness:
- Treat an omitted confidence as a deliberate selection instead of zero.
Models frequently drop the field, and the 0.75 floor then filtered out
every match, silently turning the feature off. Percentage-scale values
are rescaled rather than accepted as out-of-range certainty.
- Classify the first 500 tags when a knowledge base has more, logging a
warning, instead of dropping the task entirely. Large knowledge bases
previously got no auto-tagging at all with no user-visible signal.
- Reuse common.ParseLLMJsonResponse for the model reply, and give that
helper a balanced-scan fallback. The local extraction cut the payload at
the last "}" or "]", so a trailing citation such as "see [1]" produced
invalid JSON and burned the task's retries.
Prompt:
- Address candidates by ordinal rather than UUID. Tag names are short while
a UUID is 36 characters, so this cuts candidate tokens roughly tenfold,
keeps the model from having to reproduce (and corrupt) an id, and is what
makes the raised 500 ceiling affordable. Ordinals are range-checked and
mapped back to ids server-side.
- Drop the rationale field. Nothing read it, and at max_tags=10 it competed
with the 1024-token output budget and risked truncating the JSON.
- Fence document text in <document> so file content cannot be read as
instructions.
Behaviour:
- Add auto_tag_config.skip_if_tagged, defaulting to true, so documents the
user already tagged at upload time keep their classification. Existing
tags are now loaded before the model call, so a skipped document costs no
LLM round-trip. Configs stored without the field adopt the default.
Also promote AddKnowledgeTagRelations to KnowledgeRepository instead of
reaching for it through a type assertion that failed at runtime, and route
the max_tags bounds through AutoTagConfig.Normalize so the prompt, the match
filter and the persisted config cannot drift apart.
Adds handler-level coverage for scope, cancellation, idempotency, ordinal
validation and the new toggle, plus SDK, Swagger and API doc updates.