* 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.
* 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(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 <>
* 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.
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
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.
* 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>
* 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.
* 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>
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.
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>
- 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.
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.
* 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(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>
POST /suggestions often wins the race to generate follow-ups and has no
Langfuse parent, so chat.completion auto-creates an orphan root. Stamp
the originating W3C traceparent on the assistant message and resume it
before the extra LLM call.
ppt/pptx still fall back to markitdown when anydoc is not in the binary.
pdf/docx/xlsx and other anydoc formats now default to the in-process
converter as well; csv/md stay on the Go simple reader.
Type-level defaults still fall back to markitdown, but a linked anydoc
build should use the in-process converter first instead of always
shipping Office decks through docreader.
Empty parser_engine_rules used to resolve to builtin, which historically
did not register ppt/pptx and failed with an unusable ValueError. Route
those types to markitdown by default on both the Go resolver and the
docreader registry, and list engines that actually support the type.
Refs: https://github.com/Tencent/WeKnora/issues/2882
Unset (0) now resolves at call time (2048 / 4096 / 24576 with sandbox) so the editor can offer Default vs Custom without silently rewriting a saved value.
Generated PPT/report scripts overflowed the shell_exec command cap, and
session agents kept mutating the frozen skill tree or failing SkillHub
installs on display titles. Add write/edit sandbox tools, attach the
skill venv to /workspace scripts, and accept slug-based install names.
* fix(wiki): prevent concurrent duplicate page identities
* fix(wiki): keep identity claims stable across LLM merges and Redis
Only exact same-title pages may overwrite a Redis identity claim. Successful
Redis reads now refresh the batch-local map so concurrent batches stay
aligned, citation slugs are reclaimed, and Reduce remaps onto the claimed
slug before locking.
* fix(wiki): batch identity lookups and harden claim convergence
Exact title resolution was one seq-scan per extracted item, and a dirty Redis claim could split concurrent workers. Batch the lookup, memoize it per batch, overwrite invalid claims, and keep remapped Item.Slug in sync.
---------
Co-authored-by: wizardchen <wizardchen@tencent.com>
A skill is a workspace definition, not a sandbox setting. Keep one catalog
row and run a full image install for each backend, so agents only enable
skills that are already ready on the sandbox they use.
Capture existed so a credential a user typed in chat survives the turn.
It also overwrote values already stored, inferred the skill from a path in
the command, and logged the command that carried the secret — so one
hallucinated `export KEY=test` could permanently replace a working key,
and the key ended up in the application log either way.
Capture now only fills a blank: a name the workspace or the caller has
already filled in is dropped before the write path sees it, the skill must
be named explicitly, and assignment values are masked in logs.
The path the error message advertised did not exist: a required variable
was refused before the call's own env was considered, so an IM user, who
has no settings page, could never get the skill to run. Values supplied by
the call now satisfy the requirement, and the message names the tool that
accepts them.
Also take envs out of the generic UpdateSkill. Every install-progress
write is a read-modify-write of the whole row, and the heartbeat reloads
it every 30 seconds, so carrying envs along could put a stale declaration
back over one just recorded. Encryption failures abort the write instead
of storing plaintext in a queryable JSONB column, matching TenantAPIKey.
Reverts an unrelated deletion of the no-volume-support warning.
Skills declare the environment variables they read at run time, so a
credential no longer has to be an admin-set value shared by everyone
using the same skill image.
The installer agent writes a declaration the server validates against the
bundle. Admins fill workspace-wide values from the skill drawer, members
fill their own under Settings, and a successful shell_exec captures the
declared names a run already used for the current speaker. Resolution is
keyed by Principal so IM callers do not collapse onto one synthetic
account, and values are injected only into the process of that one run.
Values are AES-GCM encrypted at rest and never returned by any endpoint.
* 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.
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.
* fix(sandbox): skip identical skill installs and prune old snapshots
Re-uploading the same archive of a ready skill was still booting a billed sandbox and growing a new generation. Superceded snapshots also accumulated on the provider because the ledger never deleted them.
Skip the rebuild when the digest already matches a skill still in the live image, and let the reaper delete superseded provider snapshots after 24h while leaving extras not in the ledger untouched.
* fix(sandbox): retry stale same-zip installs and prune active leftovers
A re-upload of the same archive skipped every installing row, so a dead process could not recover until the reaper. Skip only recent in-flight runs, still refresh the stored bundle, and prune non-live active snapshots after retention.
* fix(sandbox): beat install liveness and guard the snapshot prune
A fixed window on the submission time cannot tell a slow install from a
dead one: a single agent command may take installCommandTimeout and an
install runs several of them, so a two-minute window called live runs
dead, reset their progress and pushed the reaper's own deadline out.
Stamp InstallingSince while the run works and read that instead, which
also stops the reaper from failing installs that are merely long.
Answer the skip question from the image only for a ready row. The ledger
records which skill a snapshot carries, not which archive, so a row
installing a new bundle would look finished from the previous bundle's
snapshot and report a success that never happened.
Prune now refuses to delete once the credentials no longer address the
account that built the image: the delete would come back not-found, and
the ledger would record another account's still-billed snapshots as
gone. It also waits for an eligible row before building a provider
client, since most configs have nothing to prune on most sweeps.
* feat(sandbox): enhance skill management in sandbox configurations
Updated the skill management system to allow listing, installing, and removing skills within sandbox configurations. The ListSkills function now accepts a sandboxConfigID to filter skills based on the selected configuration. Introduced a new SandboxSkillsDrawer component for managing skills through the UI, along with necessary updates to the API and localization files to support these features.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: keep skill maintenance sessions out of the console session list
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat: store and expose the installer transcript locators
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat: record the skill installer agent's conversation
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat: stream and persist the installer transcript during a skill install
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat: expose install transcript locators on the skill type
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat: add the floating skill install transcript window
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat: open the install transcript from the sandbox skills drawer
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(sandbox): 重构技能安装体验,支持内联时间线、编辑第4步及保留镜像指针
- 替换右下角浮窗为内联安装时间线 (SkillInstallTimeline.vue)
- 新增 GET /api/v1/sandbox-configs/:id/skills/:skillId/transcript 接口,支持回放与追尾
- 移除 /sessions/continue-stream 依赖,避免 404 问题
- 事件日志以 install_prompt 开头,不再将工具调用 preamble 拼入最终答案
- 删除 SkillInstallTranscript.vue,技能条目下可展开/折叠时间线
- 编辑向导新增第 4 步「管理技能」
- Cube/E2B 环境:连接 → 模板 → 运行配置 → 技能(第4步)
- Docker/Local 环境:无第4步(无快照镜像)
- 首次创建必须按 1→2→3 顺序,第3步保存成功后自动进入第4步
- 已有配置支持步骤条数字跳转,可直接访问任意步骤
- 卡片菜单「管理技能」打开同一抽屉并定位至第4步
- SandboxSkillsDrawer.vue 重命名为 SandboxSkillsPanel.vue,去除独立抽屉壳
- 修复保存运行配置时冲掉 skill_image 的问题
- 顶部展示信息(基础模板/快照ID/版本/构建时间)读取 config.skill_image
- 编辑器保存 payload 不再包含 skill_image,合并时保留已有 SkillImage 和 VolumeMount
- MergeSandboxConfigForUpdate 增加对 SkillImage 和 VolumeMount 的保护
- 已冲掉的配置需重新安装技能才能恢复镜像指针
- 「查看安装过程」在安装开始时即显示
- 技能列表中出现「正在安装」状态即展示按钮
- 若记录尚未写入,展示等待提示并自动重试,避免误报「没有留下记录」
* 沙盒内技能目录从 UUID 改成 SKILL.md 的 name。
* fix(sandbox): heal stuck skill rows and block planted maintenance sessions
The reaper left a mid-upgrade install spinning forever when the old snapshot was still live, and restored removals to ready after the pointer had already moved. Client session create/update can no longer hide chats behind the skill_maintenance: prefix.
* style: gofumpt the skill reaper test stubs
* style: satisfy golangci on the tenant skill admin API
* feat(sandbox): rebuild skill images at turn boundaries, not mid-exec
Hold a session turn lease through AgentQA so an install cannot tear down
the live sandbox between tool calls; the next turn's first resolve picks
up the new image. Configs can instead keep existing sandboxes and boot
the new snapshot only for new sessions.
* fix(sandbox): judge stuck skill runs from the snapshot chain
InstalledSnapshotID only records the generation that installed a skill; later
installs of other skills advance the live pointer without rewriting older rows.
Comparing those IDs made the reaper fail healthy installs and delete live
skills whose removal had stalled.
---------
Co-authored-by: hailongzhao <hailongzhao@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
Introduce the hidden skill-installer agent and TenantSkillService so a
sandbox config can install or remove skills into snapshot images under a
per-config lock, without yet exposing HTTP or UI entry points.
Co-authored-by: Cursor <cursoragent@cursor.com>
The settings form rebuilds the payload without skill_image, so merge
must ignore client values or a save would drop the snapshot (and a
crafted PUT could plant one). Also reject skill names that escape
the image root and require SupportsSnapshots on the snapshot manager.
Give Cube/E2B a shared snapshot API and persist skill image pointers so later session sandboxes can inherit installed skills from a config snapshot instead of the base template.
Co-authored-by: Cursor <cursoragent@cursor.com>
Accumulate token usage across every LLM round of an agent turn and
expose the aggregate everywhere a turn is observable:
- AgentState.TurnUsage accumulates each round's reported usage,
including the final-answer synthesis call; TokenUsage.Accumulate
keeps the cache counters as prompt subsets and recomputes the
combined cache status (unsupported survives only while every call
was itself unsupported).
- The agent completion event carries the aggregate, and the complete
stream event exposes it both as data.usage and as a typed
StreamEvent.Usage that buildStreamResponse promotes into the
previously-unused StreamResponse.Usage wire field.
- The assistant message persists it as a nullable usage column on
both migration targets (postgres 000085 jsonb, sqlite 000012 text),
for web and IM channels alike, so history reads still carry the
turn's cost after the live stream is gone.
- "[LLM Usage]" log lines gain ", session_id=..., principal=type:id"
when the context carries them; calls outside sessions stay
byte-identical.
Usage from failed retry attempts is not accumulated: the per-call
usage log remains the ground truth, while the turn aggregate serves
as the operational signal.
* feat(types): add AdminCreateUserRequest for system-admin user creation
Password un-tagged so an empty value reaches the service and triggers
OIDC-style random-password generation.
* feat(system-admin): scaffold POST /system/admin/users/create endpoint
- Handler skeleton under the SystemAdmin()-guarded group
- Binding and validation live (400); happy path 501 until the
service logic lands
- Response type declares the once-only generated_password contract
* test(system-admin): contract tests for user creation
- Create/audit/generated-password cases assert the final contract
and are intentionally red against the 501 stub
- Binding and trim validation cases already pass
- Adds the system.user_created audit action as the audit contract
* feat(frontend): add createSystemUser API wrapper
Mirrors promote/revoke/reset-password conventions, including the
once-only generated_password contract on the response type.
* fix(system-admin): never rewrite password; re-check trimmed username
- Handler no longer trims the password: whitespace is part of the
credential, hashed byte-for-byte (mirrors auth.go Register)
- Trimmed username re-checked to 2-50 runes (binding ran on the
raw JSON)
* feat(service): implement AdminCreateUser with random-password fallback
- Empty password: OIDC-style crypto/rand generation, returned once
- Explicit password: must satisfy the 8-32 letter-and-number policy
- Delegates to Register: duplicate checks, tenant provisioning and
Owner membership bootstrap match public registration
* feat(system-admin): implement create-user handler
- Resolves tenant mode from the shared auth.default_tenant_mode
policy (single source for registration and admin creation)
- Emits system.user_created audit without the plaintext password
- 201 + once-only generated password; 400 for policy/duplicate,
500 for internal failures
* test(service): whitespace-only password must be rejected
- All-whitespace password: ErrPasswordPolicy, nothing persisted
(matches AdminResetPassword); only truly empty triggers generation
- Red against the current TrimSpace-empty check
- Handler test drops the whitespace-only 201 expectation, keeps
byte-for-byte pass-through for spacey valid passwords
* fix(service): treat only a truly empty password as generate-request
Generation now triggers only on the empty string; whitespace-only
input is rejected by the 8-32 policy like AdminResetPassword.
* fix(service): regenerate until the generated password passes policy
A 32-char base64url draw misses digits ~0.4% of the time and could
400 a creation nobody picked a password for; regenerate until the
policy passes (expected ~1.004 draws).
* refactor(system-admin): drop TenantProvisioning from create payload
The value lived both on the request and as the service argument;
keep it only as the argument, mirroring LoginWithOIDC.
* test(system-admin): pin password_generated audit value; cover dupes
- Audit assertions check the exact password_generated boolean
(true generated, false caller-supplied)
- Duplicate mapping table-driven over email and username errors
* feat(system-admin): explicit provide-and-validate password semantics
- Password pointer-typed: absence (or null) triggers random
generation; any provided value, empty string included, is
policy-checked and rejected otherwise
- Service: generation on nil only, all provided values hashed
byte-for-byte
- Tests: empty string -> 400, absent -> generate, nil pass-through
at the handler boundary
- Frontend: document that any provided value is policy-checked
* test(system-admin): merge duplicate rejection tests
Whitespace-only and weak-password rejection tests were structurally
identical, differing only in inputs. Merged into one table-driven
test covering weak, empty, whitespace and whitespace-only values.
* feat(system-admin): idempotent create on duplicate identity
- Register returns typed sentinels ErrUser{Email,Username}Exists
- AdminCreateUser re-queries the existing row, lookup targeted at the
sentinel-named identity (email or username)
- Handler: duplicate sentinels -> 200 + UserInfo with idempotent=true
audit, policy errors stay 400; drops the substring-matched branch
* fix(system-admin): reject partial identity conflicts on user create
Idempotent 200 now requires both email and username to match the existing
row; partial collisions return 409. Align handler identity sanitization and
password docs with nil-or-null generation semantics.
---------
Co-authored-by: wizardchen <wizardchen@tencent.com>
* 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>
* fix(hybrid-search): normalize MatchCount once instead of at the truncation site
An omitted match_count deserializes to Go's zero value, which reached the
truncation step in HybridSearch and sliced the deduplicated chunk list to
[:0] — a successful retrieval returned an empty result set. A negative
value panicked on that same slice bound and surfaced as a 500.
Resolve the value once at the top of HybridSearch via normalizedMatchCount
so all three consumers agree, rather than patching the truncation site
alone: the over-retrieval floor, the FAQ iterative-retrieval trigger
(which never fired on this path because len(chunks) < 0 is false), and the
truncation itself.
Bound the FAQ iterative path while here, since normalization is what makes
it reachable with a large MatchCount: its TopK seeds from MatchCount*3 and
doubles five times, previously without limit. It now stops at the pool cap
instead of re-issuing an identical query.
Co-authored-by: Cursor <cursoragent@cursor.com>
* refactor(retrieval): share the default retrieval depth as one constant
The value 50 was written three times — the over-retrieval floor in
HybridSearch, the MatchCount fallback added alongside it, and
RetrievalConfig.GetEffectiveEmbeddingTopK — with nothing recording that the
three are meant to agree. Anyone tuning one would silently desync the
others.
Promote it to types.DefaultRetrievalTopK. No behavior change.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: drakezhang <drakezhang@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
* test(datasource): cover scoped sync deletions
- deleted connector items remove the matching KB knowledge, scoped per data
source via metadata datasource_id + external_id
- SyncDeletions=false neither deletes nor counts
- stream handler classifies deleted/failed items like the batch loop
* fix(datasource): perform real sync deletions scoped per data source
- applyFetchedItem now performs the KB deletion instead of only counting
- lookup is scoped to datasource_id + external_id so identical external IDs
from two data sources cannot collide or overwrite each other
- ingestItem update-path lookup uses the same scoped query
* fix(datasource): note failed deletions retry only on full sync
- SyncResult.DeletionFailed tracks deletion failures (subset of Failed)
- streaming partial message warns that failed deletions only retry on a full
sync, since the connector cursor is checkpointed past the deleted item
* fix(datasource): humanize deletion errors, keep raw detail in logs
- raw lookup/delete errors go to server logs only, with full context
- UI samples carry a humanized "see server logs" fallback
- add datasource.syncError.* i18n keys
Note: ko-KR / ru-RU syncError translations were generated without a
native-speaker review.
* fix(datasource): hard-delete synced rows and tighten deletion scoping
Sync-internal deletions now call HardDeleteKnowledge after the soft-delete
cascade so tombstones cannot block re-sync; subtree sweeps and URL metadata
attach failures are handled with datasource scoping and explicit errors.
* chore: add git hooks aligned with CI and PR checks
Install via scripts/install-git-hooks.sh (sets core.hooksPath). Pre-commit
runs whitespace/gofmt/golangci-lint on staged files; pre-push mirrors
app/frontend/cli workflows on the diff since origin/main.
* fix: gofmt test file; tighten pre-push to match CI app workflow
Pre-push now gofmts the full PR diff and runs go vet on all app packages
(like app.yml), not only Go files in the latest commit. Previous pushes
skipped checks via --no-verify and because hook-only commits had no .go files.
* fix(hooks): align pre-push diff with GitHub PR base via gh
Use three-dot diff against the open PR baseRefOid (same as CI) instead of
a two-dot merge-base range; run full go vet on every push with Go PR changes.
* style: gofumpt datasource_service_test.go
---------
Co-authored-by: wizardchen <wizardchen@tencent.com>
- Updated test files to use types.EmbedChannelContextKey instead of middleware.EmbedChannelContextKey for consistency.
- Introduced context cloning decisions for EmbedChannelContextKey to ensure proper context management during background tasks.
- Added tests to verify the correct behavior of context key declarations and their cloning decisions.