Commit Graph

1677 Commits (e18cf138a3e96edbb2cc3e706ceb89ae40e24e21)

Author SHA1 Message Date
wizardchen e18cf138a3 fix: remove GPL converter and bundle third-party license sources 2026-09-08 15:19:10 +08:00
wizardchen 694f0413dd refactor(agent): discover and invoke MCP tools on demand 2026-09-08 12:01:36 +08:00
lyingbug 647848f395
fix(agent): improve web search and persistent page reading (#3086)
* fix(agent): improve web search and persistent page reading

* fix(agent): make web fetch snapshots waitable and retryable

Keep in-flight page fetches independent of a caller's short deadline so
content=true and continuations cannot cancel a shared download or miss a
snapshot that is still loading. Mark snapshot_expired as retryable, fetch
only the first three search hits in parallel, and stop forcing Brave's
country to US.
2026-09-07 23:09:27 +08:00
Fei.Chen 15727591a7
feat(web-search): add Bocha AI Search provider (#3036)
* 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>
2026-09-07 20:06:26 +08:00
coderdailyone bd7aa40119 fix(wiki): make the category_path directory filter match on SQLite
StringArray is stored as a BLOB on SQLite, so the TEXT equality used by the directory listing never matched and every wiki folder listed empty on the SQLite build. Compare the text form there.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DFSMrLZZ3oq1dKmJFAofz6
2026-09-07 20:02:21 +08:00
小妍儿 ✨ 061df8efdc
feat(datasource): persist source created time; Feishu uses content edit time for source_updated_at (#3083)
* feat(datasource): persist source document creation time and use content edit time for Feishu

Follow-up to 160c806b (Refs #3016), which started persisting the source
last-modified time as metadata.source_updated_at. Two gaps remained:

1. Creation time was never carried. FetchedItem gains CreatedAt and
   ingestItem persists it as metadata.source_created_at (RFC3339, UTC)
   with the same absent-means-unknown rule as source_updated_at.

2. The Feishu wiki connector filled FetchedItem.UpdatedAt from
   NodeEditTime, which moves when a node is renamed or dragged in the
   tree without any content change. The connector's own cursor already
   prefers ObjEditTime for exactly this reason; use the same rule for the
   persisted value (contentEditTime / contentCreateTime, node_* as
   fallback), so source_updated_at reflects document edits.

Feishu Drive populates CreatedAt from created_time. GitLab stops
fabricating UpdatedAt = time.Now(): a fetch timestamp is not a document
timestamp, and an absent value is the documented "unknown" (the commit
time is not fetched today; leaving it unset is honest until it is).

Tests: ingestItem covers both keys present/absent; the wiki fetch test
asserts obj_* times win and node_* are the fallback.

* style(gitlab): break up the FetchedItem literal (lll)

---------

Co-authored-by: xiaoyaner0201 <>
2026-09-07 19:39:01 +08:00
GUO Zhaogong 6f0ed94a47
feat(i18n): add Japanese (ja-JP) locale support (#3080)
* feat(i18n): add Japanese (ja-JP) locale support

Add a complete Japanese UI locale for the admin frontend and the web
embed widget, and register it everywhere the supported-locale list is
enumerated.

- frontend/src/i18n/locales/ja-JP.ts: full bundle (5,600+ keys) aligned
  with en-US/zh-CN key structure; verified by the locale key audit
- frontend/src/i18n/embed.ts: ja-JP block for the embed widget, plus
  `ja*` normalisation in normalizeEmbedLocale
- Register ja-JP in i18n index, SUPPORTED_LOCALES, localeKeyAudit
  bundles/order, TDesign locale map (ja_JP), login language picker,
  general settings dropdown and embed default-locale options
- Add `language.jaJP` key to every locale so the settings dropdown can
  use $t like its siblings
- Accept ja-JP as an embed channel default_locale on the backend and as
  DEFAULT_LOCALE in the frontend docker entrypoint
- Extend locale-enumerating tests and update accepted-value lists in
  .env.example, public/config.js, widget script and website-docs

* feat(i18n): add ja-JP names and descriptions for prompt templates

Add a ja-JP block to the i18n map of all 32 prompt templates
(system_prompt, context_template, rewrite, fallback, intent_prompts,
agent_system_prompt) so the template picker shows Japanese labels when
the UI locale is ja-JP instead of falling back to the Chinese names.
Prompt content is unchanged.

* feat(i18n): add ja-JP strings for the CLI integration page

main gained the CLI setup page (#3081) with 18 new integrations.cli.* /
integrations.tabs.cli keys; add their Japanese translations so the
locale key audit stays green after rebasing onto main.

* style(i18n): unify ja-JP spacing and long-vowel conventions

- Remove spaces between Latin tokens and adjacent Japanese text
  (e.g. "MCP サービス" -> "MCPサービス"), matching the majority style
  already used in the bundle
- Drop the trailing long-vowel mark on common technical katakana terms
  (サーバ, ユーザ, フォルダ, プロバイダ, パラメータ, ヘッダ, クラスタ, ...)
  so the whole locale follows one convention

* feat(i18n): add ja-JP labels for agent type presets

config/agent_type_presets.yaml carried default / zh-CN / zh-TW labels
only, so the agent editor showed English preset names in the Japanese
UI. Add a ja-JP label and description to all five presets.
2026-09-07 19:20:41 +08:00
lyingbug 1c448bf72c
fix(chat): send one completion-token field per provider (#3082)
* fix(chat): send one completion-token field per provider

Agent dual-wrote max_tokens and max_completion_tokens, which Volcengine Ark
rejects. Collapse them to one budget and pick the wire name the way Pi does.

Fixes #3014

* fix(chat): shrink max_tokens provider whitelist to documented hosts

Only DeepSeek, Zhipu, SiliconFlow, Moonshot, NVIDIA, and self-hosted
vLLM-class runtimes stay on the legacy field. Aliyun DashScope documents
max_completion_tokens for thinking models and must not be forced onto
max_tokens.

* fix(chat): send max_tokens for LKEAP completions

Tencent LKEAP documents max_tokens only. Keep Pi's default of
max_completion_tokens, and classify every AllProviders() host so a new
vendor cannot silently inherit the default.
2026-09-07 19:16:27 +08:00
MidoriKurage c591f16d53 refactor(system): drop idempotent flag from create-user response body 2026-09-07 17:30:47 +08:00
coderdailyone 9e8673816e fix(wiki): keep folder names that look like page-type labels when placing pages
A folder named 概念/实体/Concepts was stripped from category_path as model noise, so a page moved into it kept depth 0 and a root-level wiki_path and rendered at the root of the directory tree. Folder paths are authoritative and now map to category_path verbatim; the model-label cleaner still applies to pages without a folder.

Fixes #3053

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DFSMrLZZ3oq1dKmJFAofz6
2026-09-07 17:23:19 +08:00
wizardchen 02c1759044 fix(knowledge): confirm document deletion before reporting success 2026-09-07 15:43:28 +08:00
Fei.Chen 86136b25e3
fix(session): serve org-shared KB images through the message file proxy (#3069)
* fix(session): serve org-shared KB images through the message file proxy

The message-scoped file proxy only authorized resources whose tenant
matched the message's agent tenant, so replies produced by an agent of
the caller's own workspace over an org-shared knowledge base rendered
text but lost every image with 403 (#3022).

Fall back to the org-share relation for exactly that case: the
message's persisted retrieval references must contain the resource
handle (chunk evidence — an unrelated handle from the owner tenant
cannot ride along), the reference's knowledge base must belong to the
resource's tenant, and that KB must still be shared to the caller with
at least viewer permission. Messages written before agent_tenant_id
existed get the same fallback before the shared-agent relation is
demanded; the shared-agent path itself is unchanged.

* fix(session): prove shared-KB images from agent steps and image_info

Smart-reasoning turns never persist KnowledgeReferences, and OCR hits often
keep the resource handle only in image_info. Collect tool retrieval onto the
message and accept that evidence in the message-file proxy so org-shared KB
images stop 403ing.

* fix(session): keep shared-KB image evidence in the message-file proxy

Drop the agent-engine KnowledgeRefs collector so pre-push does not lint the
whole agent package. AgentSteps already persist knowledge_search hits, which
is enough for the proxy to authorize org-shared images.

---------

Co-authored-by: vicfei <vicfei@users.noreply.github.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-07 15:43:09 +08:00
LuckVd 25fcbb9401 fix(wiki): treat rate-limit-shaped 403 responses as transient
Wiki ingest makes several independent LLM calls per document and already
retries transient failures (408/429/5xx, timeouts, connection resets) with
exponential backoff, but some gateways report QPM/QPS throttling as HTTP
403 instead of 429 (e.g. DeepSeek MaaS: code 0x04030020, message
"调用频率(qpm)超限"). Those 403s were classified as permanent caller
errors and the wiki span failed immediately with EXTRACT_FAILED /
SUMMARY_FAILED, so a QPM burst aborted generation for the whole batch
(issue #2688).

isTransientLLMError now also matches "status 403" errors whose embedded
response body carries rate-limit wording (qpm/qps, rate limit, too many
requests, throttled, 调用频率/频率超限/请求过于频繁/繁忙, try again
later, slow down). Authorization-shaped 403s (invalid key, forbidden,
permission denied) and unrelated bodies stay permanent, so the change
cannot turn authz failures into retry loops.

Tests: 14-case table covering rate-limit 403 acceptance and
authorization-shaped 403 rejection, all existing isTransientLLMError
cases unchanged and passing.
2026-09-07 14:41:48 +08:00
十三分之五六七 2544fedcd3 fix: report embedding dimension mismatches 2026-09-07 14:41:28 +08:00
Roovelrz 91a24fc376
fix: sanitize qdrant string payloads (#2997)
* fix: sanitize qdrant string payloads

* perf: avoid unnecessary qdrant payload sanitization
2026-09-07 14:22:25 +08:00
nullptr-error 524deeaad5
feat(sandbox): run sandboxed execs as root by default (#3067)
* 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>
2026-09-07 13:03:35 +08:00
po-et 160c806b94 feat(datasource): keep the source document's last-modified time through ingestion
Connectors already fill FetchedItem.UpdatedAt (Feishu from the real edit
time), but ingestItem dropped it: the persisted metadata only carried
external_id, source_resource_id and datasource_id, and the knowledge
row's own UpdatedAt moves on every re-parse, so nothing downstream could
tell how old a document is.

Write it into metadata as source_updated_at (RFC3339, UTC) when the
connector supplied one, and leave the key out otherwise so an absent
time stays distinguishable from a zero one.

Refs #3016
2026-09-07 11:52:56 +08:00
Max Freedom Pollard 801005f736 fix(knowledge): keep long non-ASCII folder names valid UTF-8
NormalizeKnowledgeFolderPath capped a directory name with
segment[:MaxKnowledgeFolderSegmentLength] (internal/types/knowledge_folder.go:51).
That is a raw byte index, so a name longer than 128 bytes was cut wherever
byte 128 landed. For a Chinese folder name that is inside the 43rd character,
and the leading bytes of the half-cut character stay in the string.

The result is an invalid UTF-8 folder_path. json.Marshal replaces the broken
bytes with U+FFFD, so the path the client reads back is not the path stored in
the row, and RenameKnowledgeFolder (internal/application/service/knowledge.go:611)
normalizes that returned value and matches nothing.

The cut now backs off to the nearest rune start. The cap stays a byte budget,
so a 60-character Chinese name keeps its first 42 characters (126 bytes)
instead of 128 bytes ending in half a character. ASCII names are unchanged.
2026-09-07 11:50:32 +08:00
LuckVd 4fb0b08719 fix(initialization): pass stored ExtraConfig to model connection test
fillSecretsFromStoredModel only copied APIKey/AppSecret from the stored
model into the test request, so the temporary test model built by
buildTestModel always had a nil ExtraConfig. Any provider-specific
setting (thinking_control, api_version, remote_model_name, ...) was
silently dropped from POST /initialization/remote/check, making the
'Test Connection' button validate a bare model instead of the stored
configuration — and masking fixes that depend on extra_config.

Request-provided values keep precedence: extraConfig is only filled
when the request does not carry one, matching the existing secret
semantics ('non-empty request values are always preferred').

Fixes #3057
2026-09-07 11:43:44 +08:00
LuckVd b037e26260
fix(chat): keep OCR/caption text of scanned-page image hits in merge (#3064)
* fix(chat): keep OCR/caption text of scanned-page image hits in merge

When pdf_force_scanned is enabled, the recognized page text lives only
in image_ocr/image_caption child chunks, while the parent markdown is
cut from image placeholders alone. The merge stage's image_parent_resolve
overwrote the hit content with the pruned parent markdown, so the OCR
text never reached the LLM context and answers degraded to placeholders.

Save the hit chunk's own body before the parent expansion and re-attach
it via JoinChunkContent, which collapses duplicates, so normal multimodal
hits (whose text is already covered by the surrounding content) are not
duplicated.

Fixes #3052

* fix(chat): avoid duplicating scanned OCR after parent merge

Re-attaching the image hit body into Content would be injected again
from ImageInfo during chat enrichment. Clear the matching OCR/caption
field so the model sees one copy, and cover caption plus pruned-placeholder paths.

* style(chat): wrap long merge parent-resolve test fixture

---------

Co-authored-by: LuckVd <LuckVd@users.noreply.github.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-07 11:38:47 +08:00
wizardchen 316db899d8 fix(security): reject traversal in local prefixes, task IDs, and wiki sort
Local storage prefixes now join under the base directory instead of
filepath.Join, FAQ import rejects client task IDs that can leak into
object names, and wiki list ORDER BY uses quoted identifiers instead of
sprintf.
2026-09-07 11:23:45 +08:00
lyingbug 3d3bb7f6d1
fix(system): keep one-time create-user passwords and copy full account details (#3039)
* 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.
2026-09-06 00:35:08 +08:00
ninesun 1e36e071ec
feat(mcp): add per-tool enable toggle (#2989)
* feat(mcp): add per-tool enable toggle

* style: format migration test

* fix(mcp): keep enable and approval updates from overwriting each other

Partial policy writes now touch only the supplied columns, and a missing
tenant fails closed so a disabled tool cannot slip through.

---------

Co-authored-by: myysophia <myysophia@users.noreply.github.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-05 17:19:20 +08:00
linhongyu510 df7e84eb30 fix(message): log why chat history indexing was skipped
IndexMessageToKB returned silently when getChatHistoryConfig yielded nil,
so an operator who enabled message indexing in the UI could see
"indexed messages: 0" with nothing in the logs to explain it.

The two paths disagree on what "enabled" means:

  GetChatHistoryKBStats  -> cfg != nil && cfg.Enabled
  IndexMessageToKB       -> cfg.IsConfigured(), which also requires
                            EmbeddingModelID != "" && KnowledgeBaseID != ""

So Enabled=true with either field empty reports the feature as on while
every message is skipped, and the skip emitted no log line at all.

Log the specific missing precondition instead. Behaviour is unchanged -
this only makes an existing silent path attributable.
2026-09-05 16:52:27 +08:00
Zhaowei Li e847114d19 fix(feishu): preserve images embedded in post messages 2026-09-05 16:48:16 +08:00
lyingbug d5cb842580
feat(agent): unify sandbox tools and drop host preloaded skills (#3033)
* 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.
2026-09-05 16:45:59 +08:00
asmh1989 5b057af467 fix(agent): web_fetch 兼容 LLM 双重序列化的 items 参数 2026-09-04 17:34:24 +08:00
hailongzhao 4d56f64a0b fix(sandbox): always require inbound credentials
Ignore and clear allow_public_inbound on save so API clients cannot open public inbound.
2026-09-03 13:34:40 +08:00
nullptr-error e39277a75e
feat(sandbox): add tenant-configurable network policy (#2995)
* 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>
2026-09-03 10:49:46 +08:00
wizardchen 22489ba663 feat(chat): keep prompt prefixes stable and send provider cache markers
Provider prefix caches only hit when system/tools stay byte-stable and
cache routing is actually on the request. Stop rewriting those prefixes
mid-turn, attach prompt_cache_key / cache_control, and log hit rate
instead of showing it in the conversation tree.
2026-09-03 00:45:52 +08:00
wizardchen b747cdb3f6 feat(agent): stream live +/- progress for sandbox write and edit
Large write/edit calls used to sit on a spinner until the full JSON
arrived. Emit path and running line counts from partial arguments so
the UI can update in place, without putting file bodies on the SSE wire.
2026-09-02 23:36:58 +08:00
wizardchen 4c0d42c4cb feat(agent): keep long sandbox turns from truncating, overflowing, or rewriting files
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.
2026-09-02 22:09:09 +08:00
leon4z 988cbb0330
fix(models): show usage details when deletion is blocked (#2975)
* 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>
2026-09-02 17:20:37 +08:00
wizardchen 3d40ee0aff fix(skills): install ClawHub skills.sh catalog pages via the install resolver
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.
2026-09-02 16:22:55 +08:00
wizardchen 79995b996f fix(agent): scope the sandbox tools to the workspace they actually serve
Three inconsistencies in how the sandbox tools are granted and bounded.

Tool checkboxes that decide nothing. list/read/write/edit_sandbox_file,
shell_exec, read_skill and execute_skill_script were offered in the settings
UI, but registerSandboxFileTools, registerSandboxShellIfAllowed and
initializeSkillsManager all register from the capability (a sandbox with a
session filesystem, SkillsEnabled, install mode) and never consult
AllowedTools. Clearing a checkbox changed nothing. Drop them from
AvailableToolDefinitions the way search_memory and web_search already are,
so the switch that decides is the only thing shown.

Readers narrower than writers. write_sandbox_file accepts anything under
/workspace except the attachment tree, while list/read stopped at the
artifact output dir, so the agent could not read back the scratch script it
had just written and had to detour through `shell_exec cat`. Since
shell_exec reaches those files anyway the narrowing bought no safety; the
inspectable roots now cover /workspace, still ordered so a reported root
names the artifact or attachment tree when the path is inside one.

Two answers for one directory. A WEKNORA_SKILL_OUTPUT_DIR override was
validated on the execution path (falling back to /workspace/output) but
taken as-is from the host environment by the tools and ArtifactCollector, so
an override outside /workspace pointed the readers at a directory no skill
could write. Both now go through sandbox.ValidatedSessionOutputDir.
2026-09-02 16:16:52 +08:00
wizardchen 439443e1e1 feat(agent): tell session agents which workspace they are working in
The installer agent was recently given its working directory up front and
stopped prefixing `cd <skill-dir> &&` onto every command. Session agents
never got the same treatment: shell_exec only mentioned /workspace as the
work_dir default, so the model could not tell it was already there, and
execute_skill_script never said scripts run with /workspace as their cwd —
a relative path inside a skill script silently resolves outside the skill.

Describe the workspace once, where each tool is described: shell_exec gains
a Working Directory section (already in /workspace, relative paths, no `cd`
prefix, and each call starts there again so a `cd` does not carry over),
execute_skill_script states its cwd and points at $WEKNORA_SKILL_DIR, and
the skills prompt gains a Workspace section covering input, output and the
per-session package overlay.

Also drop the installer prompt's paragraph about write_sandbox_file and
friends: those tools are not registered in install mode, so the model never
sees them in its schema and the note only spent tokens describing — and
misdescribing — a scope it could not reach.
2026-09-02 16:16:52 +08:00
养乐多 13abc41b0d fix(skill): 解析 stringified JSON 数组形式的 args
部分模型供应商把 execute_skill_script 的 args(schema 为 []string)
emit 成 JSON 字符串,内容本身是个 JSON 数组("[\"--project-name\",\"X\"]")。
原 UnmarshalJSON 兜底用 strings.Fields 拆这种字符串,把方括号/引号拆成
垃圾 token,脚本 argv 全是乱码,argparse 永远报参数缺失,模型无论如何
调整格式都失败。改为先把字符串内容当 JSON 数组解析,成功即用;否则再
退回 strings.Fields。补 UnmarshalJSON 各形态单测。

Co-Authored-By: Claude <noreply@anthropic.com>
2026-09-02 15:37:14 +08:00
养乐多 53ba549dbb fix(skill): @mention 不再收窄技能白名单
applyPerRequestSkillScope 原把 @mention 实现为收窄 AllowedSkills,
导致用户提及技能 A 后,智能体提示词要求调用未提及的技能 B 时
read_skill(B) 返回 "skill not allowed"。改为 @mention 只生成
<must_use> pin 提示,不动门控:智能体配置的全部技能始终可用,
pin 仅记录被提及且当前允许的技能(空 AllowedSkills 视为全允许,
与 Manager.isSkillAllowed 一致)。

Co-Authored-By: Claude <noreply@anthropic.com>
2026-09-02 15:32:20 +08:00
wizardchen 12c3465b95 feat(skills): add StopSkill functionality to abort in-flight installs
- 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.
2026-09-02 15:08:05 +08:00
wizardchen dd647fefad refactor(skills): introduce write_skill_file and edit_skill_file tools for skill directory management
- Added write_skill_file and edit_skill_file tools to facilitate writing and editing files directly within the skill directory during installation.
- Updated the agent service to register these tools exclusively for the built-in skill installer, ensuring they operate within the correct scope.
- Enhanced error handling and validation to prevent unauthorized file access outside the designated skill directory.
- Improved documentation and prompts to clarify usage and limitations of the new tools, emphasizing the importance of proving import resolutions by executing them.
- Added tests to validate the functionality and security of the new file management tools.
2026-09-02 15:08:05 +08:00
wizardchen bbe95a6c1b refactor(skills): enhance skill upload size management and error handling
- Updated .env.example to clarify skill zip upload limits and their implications for Nginx configuration.
- Refactored frontend logic to differentiate between skill zip uploads and other uploads, ensuring accurate error messages for oversized requests.
- Improved utility functions for managing upload limits and added tests to validate behavior for oversized JSON bodies.
- Enhanced error handling in various handlers to provide clearer feedback on upload size constraints, particularly for sandbox and catalog installations.
2026-09-02 15:08:05 +08:00
wizardchen 17324c46e4 refactor(skills): improve skill bundle size handling and error management
- Updated .env.example and docker-compose.yml to clarify skill bundle size limits and their implications for GitHub source downloads.
- Enhanced frontend logic to differentiate between skill bundle uploads and knowledge uploads, ensuring proper error messages for oversized requests.
- Introduced new utility functions for managing upload limits and added tests to validate behavior for oversized JSON bodies.
- Refactored error handling in various handlers to provide clearer feedback on upload size constraints.
2026-09-02 15:08:05 +08:00
wizardchen 3a06a3b9e9 refactor(skills): improve skill bundle size management and nginx configuration
- Updated .env.example to clarify the skill bundle size limits and their impact on Nginx configuration.
- Refactored frontend/docker-entrypoint.sh to separate max file size settings for skills and general uploads.
- Enhanced nginx.conf to apply specific body size limits for skill uploads without affecting other endpoints.
- Added tests to ensure proper handling of skill bundle file indexing and size constraints.
- Improved error handling in tenant_source.go and tenant_sandbox_config.go to manage skill file limits effectively.
2026-09-02 15:08:05 +08:00
wizardchen a2315add0b refactor(skills): enhance skill bundle management and catalog handling
- Introduced loadInstalledSkillBundle to streamline the retrieval of installed skill archives.
- Updated pinInstallsToReplacedBundle to ensure proper handling of installations when catalog definitions are updated.
- Enhanced error handling and logging for skill file retrieval and catalog archive management.
- Added tests to verify the behavior of skill installations and catalog updates, ensuring that previous archives are retained when necessary.
2026-09-02 15:08:05 +08:00
wizardchen 9e0333984f fix(skills): store one catalog zip and cache compressed archives
Each catalog keeps a single object: same SHA skips SaveBytes, a new zip replaces the old ref, and install rows only store CatalogID. Agent and admin caches keep the zip compressed under a 64MiB budget so read_skill does not unpack the whole tree.
2026-09-02 15:08:05 +08:00
wizardchen 4f670bce7d fix(skills): keep catalog archives when uninstalling from a sandbox
Uninstalling the last install deleted the shared zip, so the catalog row stayed but files and reinstalls failed. Store the bundle on the definition and delete it only when the skill is removed from the catalog.
2026-09-02 15:08:05 +08:00
wizardchen 56bf53a1fd fix(skills): raise skill zip cap and keep uninstall progress stable
GitHub skill packages such as ppt-master exceed the 50MB knowledge-upload limit. Give skills their own 256MB download/upload cap, keep uninstalling visible if the list lags, and distinguish zip-entry vs skill-file errors.
2026-09-02 15:08:05 +08:00
wizardchen 2783d9cab8 fix(skills): count GitHub skill subtrees and polish catalog install UI
Large GitHub skill folders were rejected because the installer counted the whole repo zip. Count only the SKILL.md subtree, raise the file cap, and hide uninstall while install is running.
2026-09-02 15:08:05 +08:00
nullptr-error 940799a74d
perf(skills): batch install verification and live installer progress (#2960)
* perf(skills): batch install verification and keep caches under budget

The tail of an install (agent_done -> verified) issued one remote exec per
check: two for permission normalisation, one per bundled script for the tree
check, three for the scratch wipe. A skill with twenty scripts paid thirty-
odd round trips, each carrying a hidden bootstrap exec and a distributed-
lock resolve, while the console sat on a finished agent with no feedback.

- normalizeSkillPermissions sends chmod and chown as one command.
- verifySkillTree folds the SKILL.md probe and one test per script into a
  single command that reports every missing file instead of stopping at the
  first. Exit codes 0/1/3 carry the verdict, stderr lines are the final
  messages, and the two existing error texts survive verbatim.
- cleanImageScratch merges the workspace reset, the directory restore and
  the cache pass into one command whose exit code is still owned by the
  strict workspace half. Package caches are no longer wiped wholesale: uv,
  npm and pnpm trim their own entries, and the pip/uv/npm/pnpm totals of
  both accounts are kept while under 256MB and wiped whole over it, so the
  next install resolves a previous download instead of the network.
- The install prompt hands the agent absolute paths for uv, npm, pnpm, pip,
  python3 and node from the same one-command probe that used to ask only
  whether uv exists, so it neither burns a turn on `which` nor gambles on
  the shell PATH.

Tests pin the new command shapes exactly, cover quoting of archive-chosen
file names, assert the tree check stays one command regardless of script
count, exercise the budget guard against a real shell, and keep the
workspace-restore failure semantics intact.

* fix(skills): credit a script's own sys.path bootstrap for shipped modules

The python check resolved every import against the script's directory, its
ancestors up to the skill root and the venv - and nothing else. A module the
skill ships in a sibling subtree (lib/image_video.py, imported by
scripts/generate.py) was invisible to that set, so a skill whose scripts
bootstrap their own library directory was refused for a dependency no
package provides, and the repair round that followed could not fix it
either: it installs packages and is forbidden from editing the tree. One
real install spent seven minutes discovering that, three LLM stream
timeouts included.

The verifier now scans what the tree ships and statically evaluates the
sys.path.insert/append calls each script raises before its imports - the
os.path and pathlib idioms, with variables tracked in source order. A
bootstrap proven to raise the directory that provides the module turns the
finding into a note; anything unprovable stays a refusal, now naming the
shipped file instead of pretending a dependency is missing. The refusal is
unrepairable on purpose: no installer round can fix a shipped module the
import cannot reach.

Tests pin the incident's exact shape, the pathlib idiom, and the guarantee
that makes the evaluator safe: a vendored module still cannot satisfy an
import unless the script's own bootstrap provably reaches it, and modules
pip placed under .venv never count as shipped.

* feat(skills): move the install progress bar while the installer works

The progress card sat at the seeded 35% for the whole agent phase and
only jumped at agent_done. Every tool call the transcript already sees
now advances an asymptotic curve 35 + 44·(1 − e^(−k/12)): monotonic for
any round count, converging below the agent_done anchor at 80, topping
out around 75 even when max_iterations is exhausted.

Each step publishes a one-line command summary (engine hint preferred,
80-rune cap) so the admin can see what the installer is doing. After
the first round ends the activity progress is muted — verification and
repair rounds own the stage anchors (80/82) from there, and a repair
round's tool calls must not drag the bar back under them.

* fix(skills): pin the installer agent's thinking mode off

installerAgentConfig left AgentConfig.Thinking nil, which most providers
read as "defer to the model's own default" — a thinking-capable model
would reason on every ReAct round of an install, burning latency and
completion tokens on what are short shell-command turns. Set an explicit
false so every provider path (Qwen enable_thinking, Ollama think, LKEAP
thinking type) receives a deterministic off instead of a default.

* style(skills): gofmt tenant_skill_verify_python_test.go

CI rejects aligned map keys in this table-driven test; gofmt drops the extra spaces.

* docs(skills): drop the duplicated exit 1 line in the python verifier

The shipped-module case was appended by repeating the whole exit 1 block
instead of extending the existing one.

---------

Co-authored-by: hailongzhao <hailongzhao@tencent.com>
2026-09-02 12:23:42 +08:00
wizardchen ecb9a1f737 fix(agent): recover tool arguments with a stray trailing fragment
Some upstream inference gateways append an extra `""` arguments delta
right after a zero-argument tool call, so the accumulated payload becomes
`{}""` and fails to parse. RepairJSON now drops anything following the
first balanced top-level value, which also covers a duplicated payload.
Truncated JSON is left untouched so balanceBrackets can still recover it.
2026-09-02 10:12:55 +08:00