Merge branch 'feat/session-workspace-root' into feat/session-workspace-root-consumers
This commit is contained in:
commit
f9eb524891
1155 files changed
+31527
-9869
No files matched your search
+8
-8
@@ -18,23 +18,23 @@
|
||||
en: 5f5daec51b20db77
|
||||
zh: e4d6f78fc1b4b835
|
||||
/agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/decision/combo-external-script-arrival-and-source-maps:
|
||||
en: 0a4240d88cca240a
|
||||
zh: 8f5f1527caf571cd
|
||||
en: 04b9f0138b5d2288
|
||||
zh: 2a749db57f6e7a10
|
||||
/agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/decision/the-loading-flow-end-to-end:
|
||||
en: 1f7db6ecfc0b0831
|
||||
zh: f6bf37dc921a7d40
|
||||
/agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/decision/live-graph-reconciliation:
|
||||
en: ab9577214d7b2f2b
|
||||
zh: fc8f10fd8c90b34b
|
||||
en: d7777566a2594654
|
||||
zh: 509cad4a363184ae
|
||||
/agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/decision/hot-reload-one-driver-plugin-self-watched-bundles:
|
||||
en: e6a0bee3d31cd2c6
|
||||
zh: 7f7384c5d1a74751
|
||||
en: d31506b6ccca554e
|
||||
zh: 91f4eb62927ebabe
|
||||
/agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/package-ownership:
|
||||
en: 94ca0d09e6fd1e3a
|
||||
zh: d5949a2bdec795ba
|
||||
/agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/consequences:
|
||||
en: 624efdd136029771
|
||||
zh: 7d60207147e631fe
|
||||
en: cfeb5dc97753e46f
|
||||
zh: 92da07a598f7cfb0
|
||||
/agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/alternatives-considered:
|
||||
en: b8f036f50cff7cd8
|
||||
zh: 6d623c4a1f4314b1
|
||||
@@ -46,7 +46,7 @@ A `require.async("./client.<name>.js")` call requests the exact revisioned `/plu
|
||||
|
||||
The shared tsdown preset emits a map for every plugin entry and chunk and rewrites first-party source paths into the browser-resolvable repository form `/packages/<group>/<package>/src/...`. The production Client pass consumes `lib/types`; the preset supplies each tsc map to Rolldown and fills `sourcesContent` from the original files, so the final map reaches TypeScript/TSX instead of stopping at emitted JavaScript. Other workspace sources inlined into a bundle likewise resolve to their `packages/` owner, while dependency paths remain unchanged. Combo generation strips each local debug directive, records its generated-line offset, resolves every authored source against the original per-plugin map URL, and emits an Indexed Source Map v3. An authored map supplies its section; otherwise an identity section embeds the generated bundle and uses the packer's `sourceURL` as its source name when present. The absolute combo map URL mirrors the script resource list by changing every `client.js` suffix to `client.js.map`, so `/plugins/??<package-a>/client.js,<package-b>/client.js&rev=<rev>` points to `/plugins/??<package-a>/client.js.map,<package-b>/client.js.map&rev=<rev>`. A chunk script likewise points to its own map URL. Source-map files are read and combined only when those map URLs receive `GET`; `HEAD` materializes neither script nor map bodies. The Vite shell also emits source maps, letting shell code and externally loaded plugins map stacks and performance profiles back to TypeScript/TSX.
|
||||
|
||||
The graph retains each row's revisioned one-resource combo URL for HMR and adds a revisioned descriptor for every startup combo request; several descriptors may carry the same scheduling phase. Initial publication and `rebuilt(id)` use the same hash of entry mtime, ctime, and size; artifact contents never enter the hash. Ctime distinguishes rewrites that preserve mtime and size. A Host restart over unchanged artifacts therefore retains every row revision, so the reconnecting SSE snapshot does not trigger browser plugin replacement. The shared preset stamps the entry after every package output is written; a chunk-only build therefore advances the owner revision without a Host-side sibling scan. Startup combo revisions derive from the ordered row revisions. Script bodies are assembled on their first `GET`; source-map files are read and combined separately on their first map `GET`. `HEAD` materializes neither body. Versioned scripts and maps use immutable caching, and unrelated graph recomposition retains already-materialized chunk responses at the same revision. The Host serves only exact generated URLs; stale revisions and unadvertised resource lists return 404 instead of aliasing different bytes. An external script's `error` event exposes neither response status nor body, so failure diagnostics name only the URL; the same-origin Host and build-stamped registration id form the identity boundary, while the post-`load` factory-presence check rejects an artifact that did not register the expected id.
|
||||
The graph retains each row's revisioned one-resource combo URL for HMR and adds a revisioned descriptor for every startup combo request; several descriptors may carry the same scheduling phase. Initial publication and `rebuilt(id)` use the same hash of entry mtime, ctime, and size; artifact contents never enter the hash. Ctime distinguishes rewrites that preserve mtime and size. A Host restart over unchanged artifacts therefore retains every row revision, so the reconnecting stream baseline does not trigger browser plugin replacement. The shared preset stamps the entry after every package output is written; a chunk-only build therefore advances the owner revision without a Host-side sibling scan. Startup combo revisions derive from the ordered row revisions. Script bodies are assembled on their first `GET`; source-map files are read and combined separately on their first map `GET`. `HEAD` materializes neither body. Versioned scripts and maps use immutable caching, and unrelated graph recomposition retains already-materialized chunk responses at the same revision. The Host serves only exact generated URLs; stale revisions and unadvertised resource lists return 404 instead of aliasing different bytes. An external script's `error` event exposes neither response status nor body, so failure diagnostics name only the URL; the same-origin Host and build-stamped registration id form the identity boundary, while the post-`load` factory-presence check rejects an artifact that did not register the expected id.
|
||||
|
||||
### The loading flow, end to end
|
||||
|
||||
@@ -76,13 +76,13 @@ Stylesheet metadata and renderer ownership follow the [module metadata decision]
|
||||
|
||||
The modules controller owns exactly the Loader entries created from the boot manifest. Full Host snapshots update its module descriptors and reconcile those entries; other Loader contributors retain ownership. New modules arrive through single-resource URLs because replaying a startup batch could register an existing factory twice. Removal uses Loader deletion, then drains the captured fiber before removing unused module records. Declared and observed transitive requests keep shared modules alive. Factory revision tracking is independent of entry activation because a download or materialization can finish without creating an entry. Graph updates invalidate stale factories and failed arrival targets without managed entries, notifying resource consumers before any consumer imports its dependencies; rebuilt frames also reconcile entries missing after import failures.
|
||||
|
||||
The Host SSE adapter forwards existing graph-change notifications and sends the current full graph on connection. The graph describes desired browser entries, not Host cleanup completion: Host lifecycle ordering belongs to its Loader, while each browser waits for its own removed fibers. Graph reconciliation and rebuilt code share one page-owned queue. Local generations prevent stale downloads from mounting; opaque revisions are compared only for equality. The settings inventory reports page-local errors and can retry the same graph without changing Host enablement. This preserves unrelated page state and avoids both an application restart and a second plugin executor. Electron's independent installation flow remains outside this mechanism.
|
||||
The Host `pluginEvents/follow` Remote stream forwards existing graph-change notifications and opens every generation with the current full graph; graph rows also carry each plugin's synced configuration ([browser plugin configuration sync](2026-11-15-client-config-sync.md)). The graph describes desired browser entries, not Host cleanup completion: Host lifecycle ordering belongs to its Loader, while each browser waits for its own removed fibers. Graph reconciliation and rebuilt code share one page-owned queue. Local generations prevent stale downloads from mounting; opaque revisions are compared only for equality. The settings inventory reports page-local errors and can retry the same graph without changing Host enablement. This preserves unrelated page state and avoids both an application restart and a second plugin executor. Electron's independent installation flow remains outside this mechanism.
|
||||
|
||||
### Hot reload: one driver plugin, self-watched bundles
|
||||
|
||||
Hot reload is a composition decision: the web bundle mounts the `client-hmr` row (a normal plugin package) unconditionally; its node half brings the bundle watch and the SSE channel, and the chain stays idle until a rebuild watcher rewrites client bundles. A composition that must not expose it disables the row.
|
||||
Hot reload is a composition decision: the web bundle mounts the `client-hmr` row (a normal plugin package) unconditionally; its node half brings the bundle watch and the authenticated plugin-events Remote stream, and the chain stays idle until a rebuild watcher rewrites client bundles. A composition that must not expose it disables the row.
|
||||
|
||||
How does a rebuilt bundle become a reload signal? The hmr node half observes it itself — no builder tells it. Before reading each startup snapshot, the module host captures the entry stat baseline and exposes it through `ctx.clientModules.artifactBaseline(id)`. One HMR-owned interval compares every current graph row with that baseline. An unchanged row starts watching without a content read or hash; a write after baseline capture is already a stat delta and only that row enters `rebuilt(id)`. This avoids redundant reads when installing the watcher and avoids `fs.watchFile`, whose asynchronous first baseline can silently absorb a construction-time rebuild. Watch membership follows `onGraphChanged`; vanished rows drop out, and an entry missing at poll time keeps its row dirty so reappearance retries publication even when mtime and size match the baseline. The shared tsdown preset stamps `client.js` after every sibling output has been written; on an entry mtime, ctime, or size delta, or a dirty row, `rebuilt(id)` derives the revision from those three metadata values. It reads the new bundle snapshot only if the revision changes. A chunk-only edit therefore changes the revision, and a partial write followed by the completion stamp supplies a later stat change that self-heals. When the `rev` changes, the node half broadcasts a `rebuilt` frame on `GET /plugins/events` — a system SSE channel that sends the full graph on connect and `rebuilt` frames on change, presentation-only wire that never enters the session log. Polling is deliberate because inotify does not fire on the weka network mount, the same reason the build-side watcher needs `--poll`; one entry stat per row and interval is sufficient, the interval is a validated config field (default 500ms), and disposal clears the one timer. Rebuilding artifacts is any process using the shared Client tsdown preset — `scripts/dev-web.ts` remains the watch-build entry point, discovering its package list through `dsh.client` while scanning `packages/*/*/package.json` at startup — and builder and host share no notification protocol.
|
||||
How does a rebuilt bundle become a reload signal? The hmr node half observes it itself — no builder tells it. Before reading each startup snapshot, the module host captures the entry stat baseline and exposes it through `ctx.clientModules.artifactBaseline(id)`. One HMR-owned interval compares every current graph row with that baseline. An unchanged row starts watching without a content read or hash; a write after baseline capture is already a stat delta and only that row enters `rebuilt(id)`. This avoids redundant reads when installing the watcher and avoids `fs.watchFile`, whose asynchronous first baseline can silently absorb a construction-time rebuild. Watch membership follows `onGraphChanged`; vanished rows drop out, and an entry missing at poll time keeps its row dirty so reappearance retries publication even when mtime and size match the baseline. The shared tsdown preset stamps `client.js` after every sibling output has been written; on an entry mtime, ctime, or size delta, or a dirty row, `rebuilt(id)` derives the revision from those three metadata values. It reads the new bundle snapshot only if the revision changes. A chunk-only edit therefore changes the revision, and a partial write followed by the completion stamp supplies a later stat change that self-heals. When the `rev` changes, the node half publishes a `rebuilt` frame on the authenticated `pluginEvents/follow` Remote stream, which opens every generation with the full graph and then sends `graph` and `rebuilt` increments; it is presentation-only wire that never enters the session log. Polling is deliberate because inotify does not fire on the weka network mount, the same reason the build-side watcher needs `--poll`; one entry stat per row and interval is sufficient, the interval is a validated config field (default 500ms), and disposal clears the one timer. Rebuilding artifacts is any process using the shared Client tsdown preset — `scripts/dev-web.ts` remains the watch-build entry point, discovering its package list through `dsh.client` while scanning `packages/*/*/package.json` at startup — and builder and host share no notification protocol.
|
||||
|
||||
On the browser side, the transport delegates code replacement to the same modules controller that owns graph reconciliation:
|
||||
|
||||
@@ -96,7 +96,7 @@ On the browser side, the transport delegates code replacement to the same module
|
||||
|
||||
Bootstrap replacement is rejected before invalidation or teardown: the module system retains its initial exports, so remounting its old code would reset consumers without applying the requested revision. The page reports the required reload and preserves the bootstrap fiber. Every non-bootstrap plugin shares the replacement semantics; an `immediately` row reloads exactly like a lazy one. Dependency cascade costs zero client code: a fiber's activation epoch strings its service providers' uids, so replacing a foundational provider such as connection re-loads every dependent through cordis itself — correct, if heavy.
|
||||
|
||||
Reload creates a fresh fiber and component state; it does not preserve React state inside the replaced plugin. Static assembly libraries and the shell require a rebuilt page; when the Host itself serves another release, the page holds plugin replacement and asks whether to reload ([Host release change prompt](../feature/2026-10-14-host-release-change-refresh-prompt.md)). Failed imports or activation remain diagnosable and retryable without rolling back unrelated plugins. Self-reload closes the old SSE channel and opens a new one; its full snapshot repairs missed graph changes. Boot, graph updates and rebuilt frames share the same queue, so a code replacement cannot overlap initial module arrival.
|
||||
Reload creates a fresh fiber and component state; it does not preserve React state inside the replaced plugin. Static assembly libraries and the shell require a rebuilt page; when the Host itself serves another release, the page holds plugin replacement and asks whether to reload ([Host release change prompt](../feature/2026-10-14-host-release-change-refresh-prompt.md)). Failed imports or activation remain diagnosable and retryable without rolling back unrelated plugins. Self-reload closes the old stream and opens a new one; its full snapshot repairs missed graph changes. Boot, graph updates and rebuilt frames share the same queue, so a code replacement cannot overlap initial module arrival.
|
||||
|
||||
## Package ownership
|
||||
|
||||
@@ -108,7 +108,7 @@ One governance implementation runs on both sides of the wire; the browser-specif
|
||||
|
||||
Costs accepted: the vendored Loader carries idle machinery in the browser (EntryTree persistence is a no-op, groups/isolation unused); every plugin edit in dev pays a bundle rebuild plus fiber remount; graph `inject` rows guide factory arrival but service availability remains the activation authority, so a mismatch appears at the boot audit; the static UI libraries keep direct value exports; every bundle gains a source-map artifact; and external-script failures provide only coarse URL diagnostics instead of the HTTP status available to an explicit fetch. The Host retains bundle snapshots and lazy response plans for the current graph and one prior startup generation. Script and map bodies are cached after their first `GET`, so memory grows with bundle snapshots and requested response bodies. Each materialized response stays fixed at its URL; a prior-generation map first requested after a rebuild reads the current map file.
|
||||
|
||||
Roster: it lives in the web bundle's config tree (`packages/bundle/web-app/cordis.patch.yml`); `mountWebPlugins` and the `CLIENT_PACKAGES` constant are gone, and recomposing a deployment means swapping the yml/overlay. The graph composer lives in the `dsh-client-modules` node half, while the parser-preloaded client face bootstraps the browser module table. The webserver remains a plain route-registration plugin; `/api/*` binding, browser authentication, RPC envelopes, and exact Fetch routes belong to the Connection node half, while Remote dispatch belongs to API Gateway and the dev bundle watch plus SSE channel belongs to the hmr node half.
|
||||
Roster: it lives in the web bundle's config tree (`packages/bundle/web-app/cordis.patch.yml`); `mountWebPlugins` and the `CLIENT_PACKAGES` constant are gone, and recomposing a deployment means swapping the yml/overlay. The graph composer lives in the `dsh-client-modules` node half, while the parser-preloaded client face bootstraps the browser module table. The webserver remains a plain route-registration plugin; `/api/*` binding, browser authentication, RPC envelopes, and exact Fetch routes belong to the Connection node half, while Remote dispatch belongs to API Gateway and the dev bundle watch plus the plugin-events Remote stream belongs to the hmr node half.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
|
||||
@@ -46,7 +46,7 @@ Host 会快照每个已构建插件入口 bundle,并把每个调度阶段的
|
||||
|
||||
共享 tsdown 预设为每个插件入口与 chunk 产出 map,并把第一方源码路径重写成浏览器可识别的仓库形式 `/packages/<group>/<package>/src/...`。生产 Client 构建会消费 `lib/types`;预设把每份 tsc map 交给 Rolldown,并从原文件补齐 `sourcesContent`,使最终 map 回到 TypeScript/TSX,而不是停在编译后的 JavaScript。内联进 bundle 的其他 workspace 源码同样回到其 `packages/` 归属,依赖包路径保持原样。Combo 生成会移除每个局部调试指令、记录其生成行偏移、以原插件 map URL 解析每个自带 source,再产出 Indexed Source Map v3。插件有自带 map 时直接用于对应 section;没有时则生成 identity section,内嵌构建后 bundle,并在存在时把 packer 写入的 `sourceURL` 用作 source 名。绝对 combo map URL 会平行改写脚本资源列表中的每个 `client.js` 后缀,因此 `/plugins/??<package-a>/client.js,<package-b>/client.js&rev=<rev>` 指向 `/plugins/??<package-a>/client.js.map,<package-b>/client.js.map&rev=<rev>`。chunk 脚本同样指向自己的 map URL。只有在这些 map URL 收到 `GET` 后,source map 文件才会被读取和组合;`HEAD` 不会物化脚本或 map body。Vite 壳同样产出 sourcemap,使壳代码与经外部加载的插件都能从 stack 和性能 profile 回到 TypeScript/TSX。
|
||||
|
||||
图为 HMR 保留每个 row 带 revision 的单资源 combo URL,并为每个启动 combo 请求增加带 revision 的描述;多条描述可以使用同一调度阶段。首次发布与 `rebuilt(id)` 使用相同的入口 mtime、ctime 和大小哈希;产物内容不参与求哈希。ctime 用于区分保留 mtime 和大小的重写。Host 重启时若产物未变,每个 row 的 revision 都保持不变,因此重连后的 SSE 快照不会触发浏览器插件替换。共享预设会在每个包输出写完后标记入口;因此只重建 chunk 也会推进 owner revision,无需 Host 扫描 sibling。启动 combo revision 从有序 row revision 派生。脚本 body 在首次 `GET` 时组合;source map 文件在首次 map `GET` 时单独读取并组合。`HEAD` 不会物化任一 body。版本化脚本与 map 使用 immutable 缓存,无关图重组会保留相同 revision 下已经物化的 chunk 响应。Host 只提供精确生成的 URL;陈旧 revision 与未发布资源列表返回 404,不会别名到其他字节。外部脚本的 `error` 事件不给响应状态与正文,因此失败诊断只报告 URL;同源 Host 与构建期写入的 registration id 是身份边界,`load` 后的 factory 存在性检查负责拒绝未登记预期 id 的产物。
|
||||
图为 HMR 保留每个 row 带 revision 的单资源 combo URL,并为每个启动 combo 请求增加带 revision 的描述;多条描述可以使用同一调度阶段。首次发布与 `rebuilt(id)` 使用相同的入口 mtime、ctime 和大小哈希;产物内容不参与求哈希。ctime 用于区分保留 mtime 和大小的重写。Host 重启时若产物未变,每个 row 的 revision 都保持不变,因此重连后的流 baseline不会触发浏览器插件替换。共享预设会在每个包输出写完后标记入口;因此只重建 chunk 也会推进 owner revision,无需 Host 扫描 sibling。启动 combo revision 从有序 row revision 派生。脚本 body 在首次 `GET` 时组合;source map 文件在首次 map `GET` 时单独读取并组合。`HEAD` 不会物化任一 body。版本化脚本与 map 使用 immutable 缓存,无关图重组会保留相同 revision 下已经物化的 chunk 响应。Host 只提供精确生成的 URL;陈旧 revision 与未发布资源列表返回 404,不会别名到其他字节。外部脚本的 `error` 事件不给响应状态与正文,因此失败诊断只报告 URL;同源 Host 与构建期写入的 registration id 是身份边界,`load` 后的 factory 存在性检查负责拒绝未登记预期 id 的产物。
|
||||
|
||||
### 装载流程,端到端
|
||||
|
||||
@@ -76,13 +76,13 @@ Host 会快照每个已构建插件入口 bundle,并把每个调度阶段的
|
||||
|
||||
modules 控制器只持有从启动清单创建的 Loader 条目。Host 的完整快照更新模块描述并对账这些条目;其他 Loader 贡献方保留自身所有权。新增模块通过单资源 URL 到达,因为重放启动 batch 可能重复注册现有 factory。移除使用 Loader 删除语义,随后等待已捕获 fiber 清理完毕,再移除未使用的模块记录。已声明及已观察到的传递依赖使共享模块保持存活。Factory revision 的跟踪独立于条目激活,因为下载或物化完成后仍可能没有创建条目。图更新会在任何消费者导入依赖前,使未归属受管条目的陈旧 factory 和失败的到达目标失效,并通知资源消费者;重建帧也会对账因导入失败而缺失的条目。
|
||||
|
||||
Host SSE 适配器转发现有图变化通知,并在连接时发送当前完整图。图描述浏览器的目标条目,不代表 Host 清理完成:Host 生命周期顺序属于其 Loader,每个浏览器则等待自身被移除 fiber 的清理。图对账与代码重建共用一个页面队列。本地代际阻止过期下载挂载;不透明 revision 只比较相等。失败页面报告本地错误,并可重试同一张图而不改变 Host 启用状态。这保留了无关页面状态,也无需重启应用或引入第二套插件执行器。Electron 的独立安装流程不属于此机制。
|
||||
Host 的 `pluginEvents/follow` Remote 流转发现有图变化通知,每一代流先发送当前完整图;图行还携带各插件的同步配置([前端插件配置同步](2026-11-15-client-config-sync.zh.md))。图描述浏览器的目标条目,不代表 Host 清理完成:Host 生命周期顺序属于其 Loader,每个浏览器则等待自身被移除 fiber 的清理。图对账与代码重建共用一个页面队列。本地代际阻止过期下载挂载;不透明 revision 只比较相等。失败页面报告本地错误,并可重试同一张图而不改变 Host 启用状态。这保留了无关页面状态,也无需重启应用或引入第二套插件执行器。Electron 的独立安装流程不属于此机制。
|
||||
|
||||
### 热重载:一个驱动插件,自行监视的 bundle
|
||||
|
||||
热重载是一项组合决策:web 组合包无条件挂载 `client-hmr` 行(一个常规的插件包),其 node 半带来 bundle 监视与 SSE(Server-Sent Events)通道;没有重建 watcher 改写客户端 bundle 时链路保持空闲。不应暴露它的组合可以禁用该行。
|
||||
热重载是一项组合决策:web 组合包无条件挂载 `client-hmr` 行(一个常规的插件包),其 node 半带来 bundle 监视与经过鉴权的插件事件 Remote 流;没有重建 watcher 改写客户端 bundle 时链路保持空闲。不应暴露它的组合可以禁用该行。
|
||||
|
||||
重建好的 bundle 怎么变成重载信号?hmr 的 node 半自己观察——没有构建器来通知它。模块 host 在读取每份启动快照前捕获入口 stat 基线,并通过 `ctx.clientModules.artifactBaseline(id)` 暴露它。HMR 自持的单个定时器把当前图的每个 row 与这份基线比较:未变化的 row 直接开始监视,不读取内容也不求哈希;基线捕获后的写入已经形成 stat 差异,只有该 row 会进入 `rebuilt(id)`。这既避免安装 watcher 时重复读取,也避开 `fs.watchFile` 以异步首次 stat 建立基线、可能静默吸收构造期重建的问题。监视集合的成员随 `onGraphChanged` 更新;消失的 row 撤下监视,轮询时缺失的入口则让对应 row 保持标脏状态,文件重现时即使 mtime 和大小与基线相同也重试发布。共享 tsdown 预设会在每个 sibling 输出写完后标记 `client.js`;入口 mtime、ctime 或大小变化、或 row 处于标脏状态时,`rebuilt(id)` 从这三个元数据值派生 revision。只有 revision 变化时,它才读取新的 bundle 快照。只修改 chunk 因此也会更换 revision;部分写入之后的完成标记还会提供一次更晚的 stat 变化以完成自愈。`rev` 变化时,node 半在 `GET /plugins/events` 上广播 `rebuilt` 帧——这是一条系统级 SSE 通道,连接即发全量图,变更时发 `rebuilt` 帧,仅供呈现的 wire,永不进会话日志。轮询是刻意选择:inotify 在 weka 网络挂载上不触发,构建侧监视器需要 `--poll` 也是同一原因;每个 row 每个间隔只需一次入口 stat,轮询间隔是一个经校验的配置字段(默认 500ms),dispose(资源释放)会清掉那一个定时器。重建产物的进程必须使用共享 Client tsdown 预设;`scripts/dev-web.ts` 仍作为 watch 构建入口保留,其包清单在启动时扫描 `packages/*/*/package.json` 按 dsh.client 发现,构建器与 host 之间没有通知协议。
|
||||
重建好的 bundle 怎么变成重载信号?hmr 的 node 半自己观察——没有构建器来通知它。模块 host 在读取每份启动快照前捕获入口 stat 基线,并通过 `ctx.clientModules.artifactBaseline(id)` 暴露它。HMR 自持的单个定时器把当前图的每个 row 与这份基线比较:未变化的 row 直接开始监视,不读取内容也不求哈希;基线捕获后的写入已经形成 stat 差异,只有该 row 会进入 `rebuilt(id)`。这既避免安装 watcher 时重复读取,也避开 `fs.watchFile` 以异步首次 stat 建立基线、可能静默吸收构造期重建的问题。监视集合的成员随 `onGraphChanged` 更新;消失的 row 撤下监视,轮询时缺失的入口则让对应 row 保持标脏状态,文件重现时即使 mtime 和大小与基线相同也重试发布。共享 tsdown 预设会在每个 sibling 输出写完后标记 `client.js`;入口 mtime、ctime 或大小变化、或 row 处于标脏状态时,`rebuilt(id)` 从这三个元数据值派生 revision。只有 revision 变化时,它才读取新的 bundle 快照。只修改 chunk 因此也会更换 revision;部分写入之后的完成标记还会提供一次更晚的 stat 变化以完成自愈。`rev` 变化时,node 半在经过鉴权的 `pluginEvents/follow` Remote 流上发布 `rebuilt` 帧;该流每一代先发全量图,之后发送 `graph` 与 `rebuilt` 增量,是仅供呈现的 wire,永不进会话日志。轮询是刻意选择:inotify 在 weka 网络挂载上不触发,构建侧监视器需要 `--poll` 也是同一原因;每个 row 每个间隔只需一次入口 stat,轮询间隔是一个经校验的配置字段(默认 500ms),dispose(资源释放)会清掉那一个定时器。重建产物的进程必须使用共享 Client tsdown 预设;`scripts/dev-web.ts` 仍作为 watch 构建入口保留,其包清单在启动时扫描 `packages/*/*/package.json` 按 dsh.client 发现,构建器与 host 之间没有通知协议。
|
||||
|
||||
浏览器侧的传输把代码替换交给负责图对账的同一个 modules 控制器:
|
||||
|
||||
@@ -96,7 +96,7 @@ Host SSE 适配器转发现有图变化通知,并在连接时发送当前完
|
||||
|
||||
Bootstrap 替换会在失效或卸载前被拒绝:模块系统保留其初始导出,重新挂载旧代码会重置消费者,却无法应用请求的 revision。页面会报告需要刷新,并保留 bootstrap fiber。所有非 bootstrap 插件都共享同一套替换语义;`immediately` 行的重载与 lazy 行分毫不差。依赖级联不花一行 client 代码:fiber 的激活纪元串接着它各服务提供方的 uid,因此替换 connection 等基础 provider 的 fiber 时,每个依赖方都会经 cordis 本身重新装载——行为正确,但代价较高。
|
||||
|
||||
重载会创建新的 fiber 和组件状态,不保留被替换插件内部的 React 状态。静态组装库与应用壳需要重建后的页面;Host 本身换成另一个 release 时,页面会暂停插件替换并询问是否刷新([Host release 变化提示](../feature/2026-10-14-host-release-change-refresh-prompt.zh.md))。导入或激活失败仍可诊断和重试,不会回滚无关插件。自重载关闭旧 SSE 通道并打开新通道;其完整快照补齐遗漏的图变更。启动、图更新和重建帧共用同一队列,因此代码替换不会与初始模块到达重叠。
|
||||
重载会创建新的 fiber 和组件状态,不保留被替换插件内部的 React 状态。静态组装库与应用壳需要重建后的页面;Host 本身换成另一个 release 时,页面会暂停插件替换并询问是否刷新([Host release 变化提示](../feature/2026-10-14-host-release-change-refresh-prompt.zh.md))。导入或激活失败仍可诊断和重试,不会回滚无关插件。自重载关闭旧流并打开新流;其完整快照补齐遗漏的图变更。启动、图更新和重建帧共用同一队列,因此代码替换不会与初始模块到达重叠。
|
||||
|
||||
## 包归属
|
||||
|
||||
@@ -108,7 +108,7 @@ Wire 两侧运行同一份治理实现;浏览器特有层只包含一套模块
|
||||
|
||||
接受的代价:vendored Loader 在浏览器里背着闲置机件(EntryTree 持久化是 no-op,分组/隔离未用);开发期每次修改插件都要付一次 bundle 重建加 fiber 重挂;graph `inject` row 指导 factory 到达,但服务可用性仍是激活权威,因此不匹配会在启动审计时浮出;静态 UI 库保留直接实体导出;每个 bundle 多出一份 sourcemap 产物,外部 script 失败也只能给出粗粒度 URL 诊断,不能像显式 fetch 那样报告 HTTP 状态。Host 为当前图及上一代启动图保留 bundle 快照与惰性响应计划。脚本和 map body 在首次 `GET` 后缓存,因此内存随 bundle 快照和已请求的响应 body 增长。每份已物化响应在其 URL 下保持固定;若上一代 map 在重建后才首次被请求,则会读取当前 map 文件。
|
||||
|
||||
名册位于 web 组合包的配置树(`packages/bundle/web-app/cordis.patch.yml`);`mountWebPlugins` 与 `CLIENT_PACKAGES` 常量已消失,重组一次部署等于替换 yml/overlay。Graph 组合器位于 `dsh-client-modules` node 半,由 parser 预载的 Client face 则自举浏览器模块表。Webserver 继续作为朴素路由注册插件;`/api/*` 绑定、浏览器认证、RPC envelope 与精确 Fetch 路由属于 Connection node 半,Remote 分发属于 API Gateway,开发期 bundle 监视与 SSE 通道属于 HMR node 半。
|
||||
名册位于 web 组合包的配置树(`packages/bundle/web-app/cordis.patch.yml`);`mountWebPlugins` 与 `CLIENT_PACKAGES` 常量已消失,重组一次部署等于替换 yml/overlay。Graph 组合器位于 `dsh-client-modules` node 半,由 parser 预载的 Client face 则自举浏览器模块表。Webserver 继续作为朴素路由注册插件;`/api/*` 绑定、浏览器认证、RPC envelope 与精确 Fetch 路由属于 Connection node 半,Remote 分发属于 API Gateway,开发期 bundle 监视与插件事件 Remote 流属于 HMR node 半。
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
|
||||
+2
-2
@@ -9,8 +9,8 @@
|
||||
en: 6228c81e4965b688
|
||||
zh: 04b702be0cfbf195
|
||||
/agent-note-credential-boundaries-whole-snapshot-requests-and-atomic-route-registration/decision:
|
||||
en: 052787311a4e6edc
|
||||
zh: 963eed632ea198de
|
||||
en: 3ecf963f99b8e9ae
|
||||
zh: 84fa0bed2316ce94
|
||||
/agent-note-credential-boundaries-whole-snapshot-requests-and-atomic-route-registration/alternatives-considered:
|
||||
en: 90c5883b247f7301
|
||||
zh: 6d2a660d8653f805
|
||||
|
||||
+1
-1
@@ -18,7 +18,7 @@ Two request-path defects sat beside them. DeepSeek resolved connection and crede
|
||||
|
||||
**The stored credential has no boundary against the model, and the READMEs say so.** `0600` under a `0700` directory stops other OS users; the model's bash and filesystem tools run as that same user, and the shipped default confines nothing. What the harness does hold to is narrower and stated as exactly that: no surface hoists the document into `process.env`, and the model is never handed a resolved path to it, so reaching the value takes a deliberate read of a path it was not given. An OS-keychain provider — a store the model's processes cannot read at all — is recorded as the real answer rather than implied by a partial one.
|
||||
|
||||
**One request, one generation.** DeepSeek's resolved snapshot carries the credential reference beside the endpoint, and `resolveApiKey` receives that snapshot instead of re-reading configuration. A rejected generation now contributes nothing at all. pi-ai defers to provider-native discovery only for a profile naming no credential; a configured reference that misses fails with `MISSING_CREDENTIAL` naming the route and the reference. The boot-time credential probe is deleted: it could run before the credentials service mounted and reported every failure as a missing key, while the first request already gives the accurate error.
|
||||
**One request, one generation.** DeepSeek's resolved snapshot carries the credential reference beside the endpoint, and the API-key route's `resolveAuth` hands that snapshot's endpoint and reference to `ctx.deepseekAuth` instead of re-reading configuration. A rejected generation now contributes nothing at all. pi-ai defers to provider-native discovery only for a profile naming no credential; a configured reference that misses fails with `MISSING_CREDENTIAL` naming the route and the reference. The boot-time credential probe is deleted: it could run before the credentials service mounted and reported every failure as a missing key, while the first request already gives the accurate error.
|
||||
|
||||
**Route replacement is a registry operation, not a caller sequence.** `registerAdapter` returns a handle carrying `replace(providers)`: the candidate set is validated in full first (conflicts, names, provider metadata), then swapped in one synchronous section. A refused replacement leaves the previous routes registered and serving, and the caller's facts cache only advances after the registry actually holds the new set, so reverting to a working configuration re-applies. pi-ai's registration facts are sorted by provider, so a settings document that merely reorders its keys is no longer a route change.
|
||||
|
||||
|
||||
+1
-1
@@ -22,7 +22,7 @@ Status: implemented
|
||||
|
||||
**存下的凭据对模型没有边界,而 README 就是这么写的。**`0700` 目录下的 `0600` 挡得住其他 OS 用户;模型的 bash 与文件系统工具正是以同一用户身份运行,而已交付的默认配置不提供任何约束。harness 真正守住的边界更窄,文档也严格按这一范围表述:没有任何一个面会把该文档提升进 `process.env`,模型也从不会拿到它的解析后路径,因此要拿到这个值,需要刻意去读一条并未交给它的路径。OS 钥匙串(keychain)提供方——一个模型的进程根本读不到的存储——被记录为真正的答案,而不是靠一个残缺的方案去暗示它。
|
||||
|
||||
**一次请求,一代设置。**DeepSeek 解析出的快照在端点旁一并携带凭据引用,`resolveApiKey` 接收这份快照,而不再重新读取配置。被拒绝的那一代如今完全不再贡献任何东西。只有当一个 profile 完全没有点名凭据时,pi-ai 才交给提供方原生的发现流程;配置了引用却解析不到,就以 `MISSING_CREDENTIAL` 失败,并点名该路由与该引用。启动时的凭据探测被删除:它可能在凭据服务挂载之前就运行,并把每一种失败都报成密钥缺失,而第一次请求本就会给出准确的错误。
|
||||
**一次请求,一代设置。**DeepSeek 解析出的快照在端点旁一并携带凭据引用,API 密钥路由的 `resolveAuth` 把这份快照的端点和引用交给 `ctx.deepseekAuth`,而不再重新读取配置。被拒绝的那一代如今完全不再贡献任何东西。只有当一个 profile 完全没有点名凭据时,pi-ai 才交给提供方原生的发现流程;配置了引用却解析不到,就以 `MISSING_CREDENTIAL` 失败,并点名该路由与该引用。启动时的凭据探测被删除:它可能在凭据服务挂载之前就运行,并把每一种失败都报成密钥缺失,而第一次请求本就会给出准确的错误。
|
||||
|
||||
**路由替换是注册表的操作,不是调用方的一串步骤。**`registerAdapter` 返回一个携带 `replace(providers)` 的句柄:候选集合先被完整校验(冲突、名称、提供方元数据),再在一个同步区段内完成替换。被拒绝的替换会让先前的路由保持注册并继续服务,而调用方的事实缓存只有在注册表确实持有新集合之后才会推进,因此改回可用配置时会重新生效。pi-ai 的注册事实按提供方排序,因此仅仅调换键顺序的设置文档不再算作路由变更。
|
||||
|
||||
|
||||
+2
-2
@@ -9,8 +9,8 @@
|
||||
en: 8d4d00e33af763b2
|
||||
zh: 61977c82d66ae9bf
|
||||
/agent-note-account-provider-and-active-request-cancellation/decision:
|
||||
en: 6f5463ecf88c1435
|
||||
zh: 7c9e46f90c8ccffb
|
||||
en: 383ef40d2ec7b6f1
|
||||
zh: 2e9482475015b1ff
|
||||
/agent-note-account-provider-and-active-request-cancellation/alternatives-considered:
|
||||
en: 7ed93136cf11074a
|
||||
zh: 1ee997e271e919ad
|
||||
|
||||
@@ -14,7 +14,7 @@ Selecting credentials from login state changes the billing identity of an existi
|
||||
|
||||
Account cancellation reads each running Agent’s latest `Session.requestContext()` instead of maintaining another provider field. This logged value remains through tools and retries and follows the next bound request. Idle Agents are excluded. During a new turn’s first preparation it can still name the previous turn’s account route, so sign-out can also interrupt an API-key turn that has not bound its new request yet. A missing account credential rejects a first request without a previous context before transport.
|
||||
|
||||
Successful local sign-out publishes an account event. The account route plugin installs a listener, which enumerates the Agent registry and cancels matching account routes through `Agent.cancel`, preserving inboxes. It registers the same predicate with the account service as the running-task report behind sign-out confirmation. Each registered child is classified independently; existing parent-owned cancellation still applies to children whose lifetime is attached to a cancelled parent. The existing HTTP signal carries cancellation to transport. Requests this listener cannot reach end through the withdrawal signal of their credential, which the [route credential decision](2026-11-10-llm-route-credential-seam.md) owns.
|
||||
Successful local sign-out publishes an account event. The account route plugin installs a listener, which enumerates the Agent registry and cancels matching account routes through `Agent.cancel`, preserving inboxes. It registers the same predicate with the account service as the running-task report behind sign-out confirmation. Each registered child is classified independently; existing parent-owned cancellation still applies to children whose lifetime is attached to a cancelled parent. The existing HTTP signal carries cancellation to transport. Requests this listener cannot reach end through the withdrawal signal of their credential, which the [DeepSeek request authentication decision](2026-11-10-deepseek-request-authentication.md) owns.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ Status: implemented
|
||||
|
||||
账号取消读取运行中 Agent 最近的 `Session.requestContext()`,不维护额外提供方字段。该已记录值在工具和重试阶段保留,随下一次绑定请求更新;空闲 Agent 不计入。新轮次首次准备期间,它仍可能指向上一轮的账号路由,因此退登也可能打断尚未绑定新请求的 API key 轮次。没有历史上下文的首请求若缺少账号凭据,会在传输前失败。
|
||||
|
||||
本地退登成功后发布账号事件。账号路由插件安装监听器,遍历 Agent 注册表,通过 `Agent.cancel` 取消匹配的账号路由并保留收件箱。它把同一判断函数注册到账号服务,作为退登确认所依据的运行中任务报告。每个已注册子代理独立分类;生命周期绑定到已取消父代理的子代理仍受现有父级取消规则约束。现有 HTTP 信号将取消传递到传输层。该监听器到达不了的请求通过其凭据的撤回信号结束,这一信号由[路由凭据决策](2026-11-10-llm-route-credential-seam.zh.md)负责。
|
||||
本地退登成功后发布账号事件。账号路由插件安装监听器,遍历 Agent 注册表,通过 `Agent.cancel` 取消匹配的账号路由并保留收件箱。它把同一判断函数注册到账号服务,作为退登确认所依据的运行中任务报告。每个已注册子代理独立分类;生命周期绑定到已取消父代理的子代理仍受现有父级取消规则约束。现有 HTTP 信号将取消传递到传输层。该监听器到达不了的请求通过其凭据的撤回信号结束,这一信号由 [DeepSeek 请求鉴权决策](2026-11-10-deepseek-request-authentication.zh.md)负责。
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
|
||||
+2
-2
@@ -9,8 +9,8 @@
|
||||
en: e42db40b879fdbf4
|
||||
zh: 6017da9c4da17835
|
||||
/agent-note-node-ptc-execution-modes-and-in-memory-state/decision:
|
||||
en: 411054071757d5fe
|
||||
zh: e683ef7d80f33fc6
|
||||
en: 13a72b9728d25394
|
||||
zh: 1f44510fe93836dc
|
||||
/agent-note-node-ptc-execution-modes-and-in-memory-state/alternatives-considered:
|
||||
en: 396157a9fc293198
|
||||
zh: a061f05b4423e26f
|
||||
|
||||
@@ -18,7 +18,7 @@ One npm package and one plugin entry keep existing installation and loading path
|
||||
|
||||
The Session records submitted programs, nested tool calls and returned output. It does not serialize the REPL heap or rerun earlier programs after restart, resume or fork: replaying automation could repeat external side effects. A missing variable is a normal program error, and the model-visible instructions require recreating variables and reacquiring resources. No environment identifier or new durable Session event is required because the provider exposes no unlogged model input.
|
||||
|
||||
Protocol or output-limit failure, owner disposal and process exit discard the environment. The [interruption decision](2026-10-29-retained-ptc-interruption.md) owns timeout and cancellation recovery with retained state. Ordinary exceptions retain earlier mutations. A retained function uses the active evaluation's host bindings; asynchronous work from an earlier evaluation cannot acquire a later evaluation's tool authority or output sink.
|
||||
Protocol failure, owner disposal and process exit discard the environment. [Output truncation](2026-11-13-ptc-output-truncation.md) owns bounded output without state disposal. The [interruption decision](2026-10-29-retained-ptc-interruption.md) owns timeout and cancellation recovery with retained state. Ordinary exceptions retain earlier mutations. A retained function uses the active evaluation's host bindings; asynchronous work from an earlier evaluation cannot acquire a later evaluation's tool authority or output sink.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ Status: implemented
|
||||
|
||||
Session 记录提交的程序、嵌套工具调用和返回输出。它不序列化 REPL 堆,也不在重启、恢复或派生后重新执行旧程序,因为重放自动化可能重复外部操作。缺失变量产生普通程序错误,模型指引要求重新创建变量并获取资源。提供方没有引入日志之外的模型输入,因此不需要环境标识或新的持久 Session 事件。
|
||||
|
||||
协议失败、输出超限、所有者销毁和进程退出都会丢弃环境。[中断决策](2026-10-29-retained-ptc-interruption.zh.md)负责保留状态的超时和取消恢复。普通异常保留此前发生的修改。保留的函数使用当前执行的宿主绑定;较早执行中的异步任务不能获取后续执行的工具权限或向其输出。
|
||||
协议失败、所有者销毁和进程退出都会丢弃环境。[输出截断](2026-11-13-ptc-output-truncation.zh.md)负责限制输出而不丢弃状态。[中断决策](2026-10-29-retained-ptc-interruption.zh.md)负责保留状态的超时和取消恢复。普通异常保留此前发生的修改。保留的函数使用当前执行的宿主绑定;较早执行中的异步任务不能获取后续执行的工具权限或向其输出。
|
||||
|
||||
## 考虑过的替代方案
|
||||
|
||||
|
||||
+2
-2
@@ -9,8 +9,8 @@
|
||||
en: 32ba2b2b42e8deb5
|
||||
zh: 6a6532561f81b8e2
|
||||
/agent-note-offer-web-search-and-web-fetch-only-while-the-selected-provider-is-ready/decision:
|
||||
en: 023c6db0af5f9424
|
||||
zh: 7bdf40c49e381ee3
|
||||
en: 9bf594047ad5c864
|
||||
zh: 366263d56f8a4fbf
|
||||
/agent-note-offer-web-search-and-web-fetch-only-while-the-selected-provider-is-ready/alternatives-considered:
|
||||
en: 6da221f6b821ea44
|
||||
zh: b15774011abed7ed
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ English | [中文](2026-09-27-web-search-offered-by-provider-readiness.zh.md)
|
||||
Each role of the web capability seam owns one part of a per-step check:
|
||||
|
||||
- **Service Definition.** `WebSearchProvider` and `WebFetchProvider` have an optional `ready(llmProvider)` that answers whether an operation made for a model request on that chat route has a credential to send. It checks configuration only and makes no network calls. `ctx.web.searchReady(llmProvider?)` and `ctx.web.fetchReady(llmProvider?)` resolve the provider with the same rules as `search()` and `fetch()` and return its answer. A provider without `ready()` counts as ready, and a selection failure answers true because the operation reports that failure as a structured `WebError`.
|
||||
- **Service Provider.** Each DeepSeek provider checks its credentials in the order its operation resolves them. `dsh-web-search-deepseek` checks, on a route whose `ctx.llm.providerCredential()` publishes an account credential, whether that credential is configured for its Messages endpoint, and then its literal `apiKey` or its `apiKeyEnv` reference. The Search and Fetch API providers of `dsh-web-deepseek-api` resolve the same plan as the operation ([credential resolution](2026-10-29-web-provider-selection.md)): a capability with its own YAML fields checks only the key under its `*ApiKeyEnv`; otherwise, on the account route with the account model route mounted, that route's credential configured for its `/v1/tools` base counts, and then the key of the `deepseek-official` route, or `DEEPSEEK_API_KEY` without that route. A key counts when `ctx.credentials.describe()` reports its reference configured (without that service, when the launching environment carries it); the reference helpers of `dsh-credentials` and each route's own presence check perform these checks. A failed account-token or credential-store read answers false, because the operation fails on that read instead of trying the next credential. The providers name no tool or prompt section.
|
||||
- **Service Provider.** Each DeepSeek provider checks its credentials in the order its operation resolves them. `dsh-web-search-deepseek` checks, in a conversation on the account route, whether `ctx.deepseekAuth` has the account sign-in configured for its Messages endpoint, and then its literal `apiKey` or its `apiKeyEnv` reference. The Search and Fetch API providers of `dsh-web-deepseek-api` resolve the same plan as the operation ([credential resolution](2026-10-29-web-provider-selection.md)): a capability with its own YAML fields checks only the key under its `*ApiKeyEnv`; otherwise, on the account route with the account model route mounted, the account sign-in configured for the endpoint under that route's origin counts, and then the key of the `deepseek-official` route, or `DEEPSEEK_API_KEY` without that route. A key counts when `ctx.credentials.describe()` reports its reference configured (without that service, when the launching environment carries it); `ctx.deepseekAuth` performs these checks, a key's through the reference helpers of `dsh-credentials`. A failed account-token or credential-store read answers false, because the operation fails on that read instead of trying the next credential. The providers name no tool or prompt section.
|
||||
- **Consumer.** `dsh-tool-web` registers `web_search` and `web_fetch` with [step activation conditions](../../../../packages/core/tools/README.md#conditional-tools) that ask `ctx.web.searchReady()` and `ctx.web.fetchReady()` about the route of the step's model selection. The agent loop resolves conditions before it assembles the step, so the declared tools, the `tool:web_search` and `tool:web_fetch` prompt sections, PTC program bindings, and dispatch all read the same admitted set.
|
||||
|
||||
The route decides only whether the account token is checked before the API key, which happens on the `deepseek-account` route; an API key counts on every route, so a conversation on another provider's model is offered the DeepSeek web tools whenever a DeepSeek key is configured. A Search or Fetch API capability with its own YAML fields ignores the route and is ready exactly when its own key is configured.
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ Status: implemented
|
||||
web 能力 seam 的每个角色各负责逐步骤检查的一部分:
|
||||
|
||||
- **Service Definition。** `WebSearchProvider` 与 `WebFetchProvider` 有一个可选的 `ready(llmProvider)`,回答为该对话路由上的模型请求发起的操作是否有可发送的凭据。它只检查配置,不发起网络调用。`ctx.web.searchReady(llmProvider?)` 与 `ctx.web.fetchReady(llmProvider?)` 按与 `search()`、`fetch()` 相同的规则解析提供方并返回其回答。没有 `ready()` 的提供方视为就绪;选择失败时回答 true,因为对应操作会把该失败报告为结构化 `WebError`。
|
||||
- **Service Provider。** 每个 DeepSeek 提供方都按其操作解析凭据的顺序检查凭据。`dsh-web-search-deepseek` 在 `ctx.llm.providerCredential()` 发布账号凭据的路由上检查该凭据是否已为其 Messages 端点配置,然后检查其字面 `apiKey` 或 `apiKeyEnv` 引用。`dsh-web-deepseek-api` 的 Search 与 Fetch API 提供方解析与操作相同的方案([凭据解析](2026-10-29-web-provider-selection.zh.md)):在 YAML 中设置了单独字段的能力只检查其 `*ApiKeyEnv` 下的密钥;否则,在账号路由上且账号模型路由已挂载时,该路由为其 `/v1/tools` 基础地址配置的凭据算数,然后是 `deepseek-official` 路由的密钥,没有该路由时为 `DEEPSEEK_API_KEY`。`ctx.credentials.describe()` 报告其引用已配置时(没有该服务时,启动环境中存在该变量),密钥即算存在;这些存在性检查由 `dsh-credentials` 的引用函数和各路由自身的存在性检查执行。读取账号 token 或凭据存储失败时回答 false,因为操作会在该次读取上失败,而不会尝试下一种凭据。提供方不点名任何工具或提示词段落。
|
||||
- **Service Provider。** 每个 DeepSeek 提供方都按其操作解析凭据的顺序检查凭据。`dsh-web-search-deepseek` 在账号路由上的会话里检查 `ctx.deepseekAuth` 是否已为其 Messages 端点配置账号登录凭据,然后检查其字面 `apiKey` 或 `apiKeyEnv` 引用。`dsh-web-deepseek-api` 的 Search 与 Fetch API 提供方解析与操作相同的方案([凭据解析](2026-10-29-web-provider-selection.zh.md)):在 YAML 中设置了单独字段的能力只检查其 `*ApiKeyEnv` 下的密钥;否则,在账号路由上且账号模型路由已挂载时,为该路由 origin 之下的端点配置的账号登录凭据算数,然后是 `deepseek-official` 路由的密钥,没有该路由时为 `DEEPSEEK_API_KEY`。`ctx.credentials.describe()` 报告其引用已配置时(没有该服务时,启动环境中存在该变量),密钥即算存在;这些存在性检查由 `ctx.deepseekAuth` 执行,其中密钥的检查经由 `dsh-credentials` 的引用函数。读取账号 token 或凭据存储失败时回答 false,因为操作会在该次读取上失败,而不会尝试下一种凭据。提供方不点名任何工具或提示词段落。
|
||||
- **Consumer。** `dsh-tool-web` 注册 `web_search` 与 `web_fetch` 时各带一个[步骤激活条件](../../../../packages/core/tools/README.zh.md#conditional-tools),以该步骤模型选择的路由询问 `ctx.web.searchReady()` 与 `ctx.web.fetchReady()`。agent loop 在组装该步骤之前解析各条件,因此声明的工具、`tool:web_search` 与 `tool:web_fetch` 提示词段落、PTC 程序绑定与派发都读取同一个准入集合。
|
||||
|
||||
路由只决定是否先检查账号 token 再检查 API 密钥,这发生在 `deepseek-account` 路由上;API 密钥在每条路由上都算数,因此只要配置了 DeepSeek 密钥,使用其他提供方模型的对话也会获得 DeepSeek Web 工具。在 YAML 中设置了单独字段的 Search 或 Fetch API 能力不看路由,恰在其自身密钥已配置时就绪。
|
||||
|
||||
+2
-2
@@ -24,8 +24,8 @@
|
||||
en: 428699f74f19e998
|
||||
zh: 2e8fcdbc9616f70b
|
||||
/agent-note-boot-the-preview-worker-from-the-shipped-profile-and-fetch-lazy-chunks-on-demand/decision/watching-and-client-plugin-delivery:
|
||||
en: f3e6ba098433a70a
|
||||
zh: 345b93f451d2768c
|
||||
en: 814c344e891f7f91
|
||||
zh: a024d5e30607968b
|
||||
/agent-note-boot-the-preview-worker-from-the-shipped-profile-and-fetch-lazy-chunks-on-demand/alternatives-considered:
|
||||
en: 99ee505e82fa9c7c
|
||||
zh: 448bc0e160424cbf
|
||||
|
||||
+1
-1
@@ -61,7 +61,7 @@ The Worker's structural stubs throw errors carrying `ERR_FEATURE_UNAVAILABLE_ON_
|
||||
### Watching and Client plugin delivery
|
||||
|
||||
- Worker `fs.watch` and `fs.watchFile` listeners run in the async context where the watcher was created, as Node delivers watch events from the watch handle, not in the context of the code whose write produced the event. HMR's configuration watcher therefore runs outside the writer's HMR transaction, and a configuration write made inside a transaction does not make the follow-up reload fail as a nested transaction.
|
||||
- The browser half of `@deepseek-ai/dsh-client-hmr` reads `/plugins/events` through the page's `__DSH_TRANSPORT__.fetch` when a shell provides one (the Worker preview tunnel), otherwise through `EventSource`. The Client plugins of a bundle enabled in the Preview therefore mount without a page reload.
|
||||
- The browser half of `@deepseek-ai/dsh-client-hmr` follows the `pluginEvents/follow` Remote stream over the Remote carrier the page's Connection provides, including the Worker preview tunnel. The Client plugins of a bundle enabled in the Preview therefore mount without a page reload.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
|
||||
+1
-1
@@ -61,7 +61,7 @@ Worker 的结构化 stub 抛出带 `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM` 的错
|
||||
### 文件监听与 Client 插件下发
|
||||
|
||||
- Worker 的 `fs.watch` 和 `fs.watchFile` 监听器在创建 watcher 时的异步上下文里运行,与 Node 从 watch 句柄派发事件一致,而不是在写入方的上下文里运行。因此 HMR 的配置 watcher 在写入方的 HMR 事务之外运行,事务内的配置写入不会让随后的重载因嵌套事务而失败。
|
||||
- `@deepseek-ai/dsh-client-hmr` 的浏览器部分在 shell 提供 `__DSH_TRANSPORT__.fetch` 时(Worker preview 隧道)经它读取 `/plugins/events`,否则经 `EventSource` 读取。因此在 Preview 里启用 bundle 后,其 Client 插件无需刷新页面即可挂载。
|
||||
- `@deepseek-ai/dsh-client-hmr` 的浏览器部分经页面 Connection 提供的 Remote 载体(包括 Worker preview 隧道)跟随 `pluginEvents/follow` Remote 流。因此在 Preview 里启用 bundle 后,其 Client 插件无需刷新页面即可挂载。
|
||||
|
||||
## 考虑过的替代方案
|
||||
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
# Bilingual-pair consistency record for 2026-10-27-plugin-cli-absolute-paths.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-10-27-plugin-cli-absolute-paths.md
|
||||
/agent-note-plugin-clis-by-absolute-path-in-runtime-context:
|
||||
en: cf842dd82c5a905a
|
||||
zh: 1cb7923bbc0e3583
|
||||
/agent-note-plugin-clis-by-absolute-path-in-runtime-context/problem:
|
||||
en: 623b3e7c6bbb038d
|
||||
zh: 0c3725119fb9c41e
|
||||
/agent-note-plugin-clis-by-absolute-path-in-runtime-context/decision:
|
||||
en: 3911a3ee37139116
|
||||
zh: 648b896c5c71b16d
|
||||
/agent-note-plugin-clis-by-absolute-path-in-runtime-context/alternatives-considered:
|
||||
en: 7c2f56152247cadf
|
||||
zh: a77e41a020ec6835
|
||||
/agent-note-plugin-clis-by-absolute-path-in-runtime-context/consequences:
|
||||
en: c80b941f81db6daf
|
||||
zh: 964ff6d38b3903d1
|
||||
@@ -0,0 +1,35 @@
|
||||
# Agent Note: Plugin CLIs by absolute path in runtime context
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-10-27-plugin-cli-absolute-paths.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
CLI app plugins such as Feishu, WeCom, DingTalk, and Tencent Meeting install a vendor CLI outside PATH. The upstream guides, the CLIs' own messages, and the DingTalk and WeCom skill scripts call it by name. The model must run the plugin's installation, not another installation or none, and the harness should not change how model commands run to make that happen.
|
||||
|
||||
## Decision
|
||||
|
||||
Each app plugin registers its CLI's absolute path with `ctx.cliAccounts`, the Service of [`@deepseek-ai/dsh-cli-account`](../../../../packages/connector/cli-account/README.md). The Service registers required runtime context at the `PLUGIN_CLIS` context order, without interpolation, that tells the model to run the CLI by that path. For a skill whose scripts call the CLI by name, which applies to DingTalk and WeCom, the context also tells the model to prefix only the commands that run those scripts with `PATH="<directory>:$PATH"`, and never to export PATH or run the CLI by name. On Windows, where the shipped compositions mount `tool-pwsh` instead of `tool-bash`, the text uses PowerShell syntax: the call operator, `& '<path>'`, and the prefix `$env:PATH = '<directory>;' + $env:PATH`. Skills tell the model to use the path from the current runtime context. The plugin's own sign-in, status, and sign-out commands spawn the same path through the Service's command runner.
|
||||
|
||||
The harness changes no command environment: Bash, PowerShell, the sandbox, persistent terminals, and hooks run as they do without these plugins. Tencent Meeting registers its platform executable, `dist/tmeet-<platform>`. The DingTalk context contributes nothing until dws and its skills are installed. No load-time check requires commands to run on the Host; when a composition runs commands over SSH, a command fails when it reaches the missing path.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**A private PATH.** Shell executors and the plugin backend put each plugin's bin directory first on PATH, and a system-prompt section listed the plugin CLIs. This needed a path prefix in every shell request, a prepared environment for backend commands, a Host-runtime check, and a `tmeet` symlink for Tencent Meeting. Persistent terminals and hooks did not get the prefix, and it hid a CLI of the same name that the user installed.
|
||||
|
||||
**Paths in skill text.** The model sees a skill's text only after loading it, compaction can reduce that text to a summary, and history keeps the old path after an upgrade. Static skill files would also have to be generated at run time.
|
||||
|
||||
**One shared registry and one combined entry.** Rewriting shell-env or adding a package for it states the rule once, but adds a service and its documentation for four callers. Other runtime contexts, such as the working directory and the sandbox policy, are registered by the package that owns the fact; a separate entry per plugin only repeats one sentence.
|
||||
|
||||
**A Host check.** Shipped profiles always run commands on the Host. The check would only move an SSH composition's failure from first use to load, at the cost of a `runsOnHost` member on the subprocess and shell services.
|
||||
|
||||
**A hint after a failed bare-name command.** Appending the path to the tool result when a command cannot find a registered name would correct the model after the failure, but no evidence yet shows that the context text alone is insufficient.
|
||||
|
||||
## Consequences
|
||||
|
||||
The model, not PATH, maps each name to its path. Counted on 2026-10-23, the upstream guides call the CLIs by name on 3,004 lines for DingTalk, 2,542 for Feishu, 321 for WeCom, and 248 for Tencent Meeting, and 33 DingTalk scripts call `dws` by name. A command that still uses the bare name runs the installation that PATH resolves, or fails because none is found; nothing rewrites it. The script sentence forbids exporting PATH and running the CLI by name because, in real-model runs, a sentence that only asked for the prefix on script commands led the model to export PATH and then run the CLI by name. Approval details, tool cards, and job lists show the full path.
|
||||
|
||||
A CLI that the user installed under the same name is no longer hidden, and persistent terminals and hooks need no PATH handling. Runtime context stays out of the cached system prompt and is admitted again after compaction; installing, enabling, or disabling a plugin appends one runtime-context snapshot. The text's dialect follows the Host platform with the same test the compositions use to choose the shell tool, so a composition that mounts the other shell on a platform gets the wrong syntax.
|
||||
|
||||
Unit tests in the kit pin the text, required status, literal paths, readiness, and removal on disposal; each plugin's recorded Session snapshot pins its rendered context.
|
||||
@@ -0,0 +1,35 @@
|
||||
# Agent Note: 插件 CLI 通过运行时上下文给出绝对路径
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-10-27-plugin-cli-absolute-paths.md) | 中文
|
||||
|
||||
## Problem
|
||||
|
||||
飞书、企业微信、钉钉、腾讯会议等 CLI 应用插件把厂商 CLI 装在 PATH 之外。上游指南、CLI 自己的提示信息,以及钉钉和企业微信 skill 里的脚本,都按名称调用 CLI。模型必须运行插件安装的那一份,而不是别的安装或者找不到,同时 harness 不应为此改变模型命令的运行方式。
|
||||
|
||||
## Decision
|
||||
|
||||
每个应用插件把 CLI 的绝对路径注册到 [`@deepseek-ai/dsh-cli-account`](../../../../packages/connector/cli-account/README.zh.md) 的 Service `ctx.cliAccounts`。这个 Service 在 `PLUGIN_CLIS` 上下文顺序处注册一条必需、不做变量插值的运行时上下文,让模型按这个路径运行 CLI。skill 里的脚本按名称调用 CLI 时(钉钉和企业微信属于这种情况),这条上下文还让模型只在运行这些脚本的命令前加上 `PATH="<目录>:$PATH"`,并且不要导出 PATH,也不要按名称运行 CLI。在 Windows 上,内置组合挂载 `tool-pwsh` 而不是 `tool-bash`,文本改用 PowerShell 语法:调用运算符 `& '<路径>'`,以及前缀 `$env:PATH = '<目录>;' + $env:PATH`。skill 让模型使用当前运行时上下文给出的路径。插件自己的登录、状态和登出命令通过这个 Service 的命令执行器启动同一路径。
|
||||
|
||||
harness 不改变任何命令的环境:Bash、PowerShell、沙箱、持久终端和 hook 的运行方式与没有这些插件时相同。腾讯会议直接注册各平台的可执行文件 `dist/tmeet-<平台>`。钉钉的上下文在 dws 和钉钉 skill 安装完成前不贡献任何内容。加载时不检查命令是否在 Host 上运行;组合把命令放到 SSH 远端运行时,命令在访问不存在的路径时失败。
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**私有 PATH。** Shell 执行器和插件后端把各插件的 bin 目录放到 PATH 最前面,再由一段系统提示词列出插件 CLI。这需要在每个 shell 请求里加路径前缀、为后端命令准备环境、检查 runtime 是否在 Host 上,并为腾讯会议建一个 `tmeet` 符号链接。持久终端和 hook 拿不到这个前缀,而且它会遮住用户自己安装的同名 CLI。
|
||||
|
||||
**把路径写进 skill 正文。** 模型要加载 skill 之后才看得到正文,压缩可能把正文缩成摘要,升级之后历史里留的还是旧路径。静态的 skill 文件也要改成运行时生成。
|
||||
|
||||
**一个共享注册表、合成一条上下文。** 改造 shell-env 或为此新建一个包,可以只写一次规则,但要为四个调用方增加一个服务及其文档。工作目录、沙箱策略等其他运行时上下文都由掌握该事实的包自己注册;每个插件各一条,只是重复一句话。
|
||||
|
||||
**检查是否在 Host 上。** 发布的 profile 总在 Host 上运行命令。这个检查只会把 SSH 组合的失败从首次使用提前到加载,代价是 subprocess 和 shell 服务上多一个 `runsOnHost` 成员。
|
||||
|
||||
**按名称调用失败后追加提示。** 命令找不到已注册的名称时在工具结果里追加路径,可以在失败后纠正模型,但目前没有证据表明仅靠上下文文字不够。
|
||||
|
||||
## Consequences
|
||||
|
||||
把名称换成路径的是模型,不再是 PATH。按 2026-10-23 的统计,上游指南按名称调用 CLI 的行数为:钉钉 3,004 行、飞书 2,542 行、企业微信 321 行、腾讯会议 248 行;钉钉还有 33 个脚本按名称调用 `dws`。仍用名称的命令会运行 PATH 解析到的那份安装,或者因为找不到而失败;没有任何机制改写它。脚本那句话之所以禁止导出 PATH 和按名称运行 CLI,是因为在真实模型的运行中,只要求给脚本命令加前缀的写法会让模型先导出 PATH、再按名称运行 CLI。审批详情、工具卡和任务列表显示完整路径。
|
||||
|
||||
用户自己安装的同名 CLI 不再被遮住,持久终端和 hook 也不需要处理 PATH。运行时上下文不进入缓存的系统提示词,压缩后会重新提交;安装、启用或停用插件时追加一份运行时上下文快照。文字的写法按 Host 平台选择,判断条件与组合选择 shell 工具的条件相同;因此某个平台上的组合如果挂载了另一种 shell,得到的写法就不对。
|
||||
|
||||
kit 的单元测试固定了文字、必需状态、路径原样保留、就绪条件和释放时移除;每个插件的录制会话快照固定了它渲染出的上下文。
|
||||
@@ -18,8 +18,8 @@
|
||||
en: 9d68ffca5c8be681
|
||||
zh: 36bb661f98de0ebb
|
||||
/agent-note-web-provider-selection-independent-menus-over-registered-providers/decision/credential-resolution:
|
||||
en: aa5522b172d2c580
|
||||
zh: 04561ffe78d69ff4
|
||||
en: dca56d7ced4e5294
|
||||
zh: e984a7fddac3228f
|
||||
/agent-note-web-provider-selection-independent-menus-over-registered-providers/decision/defaults-and-stored-selections:
|
||||
en: 5fcd3319fbceed1d
|
||||
zh: 20771646b9c36fa6
|
||||
|
||||
@@ -30,11 +30,11 @@ The Search and Fetch APIs read one `web-deepseek-api` namespace, and each resolv
|
||||
|
||||
Each of Search and Fetch has a billing setting, `web-deepseek-api.searchBilling` or `fetchBilling`, which the settings page edits as a **Billing** menu under the selected API. The default, `auto`, follows the DeepSeek credential of the conversation; `account` sends only the signed-in account's token and `api-key` only the API key, without falling back to the other. The conversation's route is the `provider` of the initiating Session's latest request context, which account sign-out also reads; `ready()` uses the route of the model request being prepared, so readiness and execution resolve the same plan.
|
||||
|
||||
The account credential is the one `ctx.deepseekAccount` releases for the dispatch endpoint under the origin of the base URL the mounted `deepseek-account` route publishes through `ctx.llm.providerCredential()`, with `/v1/tools`; without that route, the origin `DEEPSEEK_BASE_URL` names is used. An HTTP 401 invalidates that credential. With `auto` billing on the `deepseek-account` route, the operation sends the account credential when that route is mounted and a credential is released. Every other `auto` operation, including one in an account conversation without a sign-in or a credential, sends the key the mounted `deepseek-official` route publishes, which the route resolves under its `apiKeyEnv` (its base URL includes `DEEPSEEK_BASE_URL`), to the origin of that route's base URL with `/v1/tools`; without that route, `DEEPSEEK_API_KEY` goes to `https://api.deepseek.com/v1/tools`. With `auto` billing on a route other than the two DeepSeek routes, or outside a Session, an operation without a configured key sends the account token instead, so a signed-in user without a key keeps web tools in conversations on other model providers; on the `deepseek-official` route it never sends the token, because that conversation bills the API key. Sending the API key in a signed-out account conversation keeps web tools available there. A user with only `DEEPSEEK_API_KEY`, including every headless, SDK, and ACP run, therefore searches and fetches by default, and a gateway or internal deployment set through the model provider's base URL serves web access at the same origin. A missing credential makes the capability not ready, and an operation fails with `WEB_PROVIDER_CREDENTIAL_MISSING` and guidance for its billing that names the account sign-in, the Models page and the reference, and the billing field. A mounted route whose configuration does not resolve is not treated as absent: an operation that needs that route is not ready and fails with `WEB_PROVIDER_MISCONFIGURED` before reading the credential that depends on that route, without trying later sources or sending the request, so a broken gateway setting never redirects requests to the official endpoint.
|
||||
The account credential is the one `ctx.deepseekAccount` releases for the dispatch endpoint under the origin of the base URL the mounted `deepseek-account` route connects to `ctx.deepseekAuth`, with `/v1/tools`; without that route, the origin `DEEPSEEK_BASE_URL` names is used. An HTTP 401 invalidates that credential. With `auto` billing on the `deepseek-account` route, the operation sends the account credential when that route is mounted and a credential is released. Every other `auto` operation, including one in an account conversation without a sign-in or a credential, sends the key of the mounted `deepseek-official` route, read under that route's `apiKeyEnv` (its base URL includes `DEEPSEEK_BASE_URL`), to the origin of that route's base URL with `/v1/tools`; without that route, `DEEPSEEK_API_KEY` goes to `https://api.deepseek.com/v1/tools`. With `auto` billing on a route other than the two mounted DeepSeek routes, which includes either DeepSeek route id while its plugin is not mounted, or outside a Session, an operation without a configured key sends the account token instead, so a signed-in user without a key keeps web tools in conversations on other model providers; on the mounted `deepseek-official` route it never sends the token, because that conversation bills the API key. Sending the API key in a signed-out account conversation keeps web tools available there. A user with only `DEEPSEEK_API_KEY`, including every headless, SDK, and ACP run, therefore searches and fetches by default, and a gateway or internal deployment set through the model provider's base URL serves web access at the same origin. A missing credential makes the capability not ready, and an operation fails with `WEB_PROVIDER_CREDENTIAL_MISSING` and guidance for its billing that names the account sign-in, the Models page and the reference, and the billing field. A mounted route whose configuration does not resolve is not treated as absent: an operation that needs that route is not ready and fails with `WEB_PROVIDER_MISCONFIGURED` before reading the credential that depends on that route, without trying later sources or sending the request, so a broken gateway setting never redirects requests to the official endpoint.
|
||||
|
||||
A capability whose YAML sets a non-empty `searchBaseURL` or `searchApiKeyEnv` (`fetchBaseURL` or `fetchApiKeyEnv` for Fetch) instead, whatever its billing, always sends the key under its `*ApiKeyEnv` (`DEEPSEEK_API_KEY` when unset) to its `*BaseURL` (the official base when unset) and never the account token, so an intranet or third-party endpoint receives only the key chosen for it. Each capability has its own fields because a deployment can serve search and fetch from different gateways. These fields are YAML-only, and an empty value counts as unset. Stored values of fields outside the schema, including `baseURL`, `apiKeyEnv`, and `apiKey`, load without schema errors and have no effect.
|
||||
|
||||
The DeepSeek model routes publish the credential they send through `ctx.llm.providerCredential()` ([route credentials](2026-11-10-llm-route-credential-seam.md)): the API-key route its key under `apiKeyEnv`, the account route the credential `ctx.deepseekAccount` releases for a destination. Messages search and the Search and Fetch APIs read those publications instead of provider configuration, and read `DEEPSEEK_API_KEY` and own keys through the reference helpers of `dsh-credentials`, so every DeepSeek request reads the credential store the same way; a credential whose grant offers invalidation is invalidated after an HTTP 401. Shipped profiles need no per-profile credential override, because the API-key path works wherever `DEEPSEEK_API_KEY` or the DeepSeek API-key route has a key.
|
||||
`ctx.deepseekAuth` orders and releases these credentials ([DeepSeek request authentication](2026-11-10-deepseek-request-authentication.md)): each DeepSeek model route connects the deployment its settings name, the API-key route with its key reference under `apiKeyEnv`, and the account sign-in is the credential `ctx.deepseekAccount` releases for a destination. Messages search and the Search and Fetch APIs ask that service instead of reading provider configuration, and it reads route keys, `DEEPSEEK_API_KEY`, and own keys through the reference helpers of `dsh-credentials`, so every DeepSeek request reads the credential store the same way; a credential whose authorization offers invalidation is invalidated after an HTTP 401. Shipped profiles need no per-profile credential override, because the API-key path works wherever `DEEPSEEK_API_KEY` or the DeepSeek API-key route has a key.
|
||||
|
||||
### Defaults and stored selections
|
||||
|
||||
|
||||
@@ -30,11 +30,11 @@ Search 与 Fetch API 读取同一个 `web-deepseek-api` namespace,并各自解
|
||||
|
||||
Search 与 Fetch 各有一个计费方式设置 `web-deepseek-api.searchBilling` 或 `fetchBilling`,设置页在选中的 API 下方以**计费方式**下拉框编辑它。默认值 `auto` 跟随会话的 DeepSeek 凭据;`account` 只发送已登录账号的令牌,`api-key` 只发送 API 密钥,都不回退到另一种凭据。会话的路由是发起会话最近一次请求上下文的 `provider`,账号退出登录读取的也是它;`ready()` 使用正在准备的模型请求的路由,因此就绪判断与执行解析出相同的方案。
|
||||
|
||||
账号凭据是 `ctx.deepseekAccount` 为请求端点释放的凭据,端点位于已挂载的 `deepseek-account` 路由通过 `ctx.llm.providerCredential()` 发布的基础地址的 origin 加 `/v1/tools` 下;没有该路由时使用 `DEEPSEEK_BASE_URL` 所指的 origin。HTTP 401 会作废该凭据。`auto` 计费在 `deepseek-account` 路由上,若该路由已挂载且释放出凭据,操作发送账号凭据。其他所有 `auto` 操作,包括账号会话中没有登录或没有凭据的操作,都把已挂载的 `deepseek-official` 路由发布的密钥(由该路由按其 `apiKeyEnv` 解析,其基础地址包含 `DEEPSEEK_BASE_URL`)发往该路由基础地址的 origin 加 `/v1/tools`;没有该路由时,把 `DEEPSEEK_API_KEY` 发往 `https://api.deepseek.com/v1/tools`。`auto` 计费在两个 DeepSeek 路由之外的路由上或会话之外,没有配置密钥的操作改为发送账号令牌,因此已登录但没有密钥的用户在其他模型提供方的会话中仍可使用网页工具;在 `deepseek-official` 路由上从不发送令牌,因为该会话按 API 密钥计费。未登录的账号会话发送 API 密钥,网页工具因此在其中仍然可用。因此只有 `DEEPSEEK_API_KEY` 的用户(包括所有 headless、SDK 与 ACP 运行)默认即可搜索和抓取,通过模型提供方基础地址设置的网关或内部部署也在同一 origin 上提供 Web 访问。缺少凭据时,该能力未就绪,操作以 `WEB_PROVIDER_CREDENTIAL_MISSING` 失败,指引信息按计费方式点名账号登录、模型页面与该引用,以及计费方式字段。已挂载但配置无法解析的路由不视为不存在:需要该路由的操作未就绪,并在读取依赖该路由的凭据前以 `WEB_PROVIDER_MISCONFIGURED` 失败,不再尝试后续来源,也不发送请求,因此网关设置出错时请求不会被改发到官方端点。
|
||||
账号凭据是 `ctx.deepseekAccount` 为请求端点释放的凭据,端点位于已挂载的 `deepseek-account` 路由向 `ctx.deepseekAuth` 登记的基础地址的 origin 加 `/v1/tools` 下;没有该路由时使用 `DEEPSEEK_BASE_URL` 所指的 origin。HTTP 401 会作废该凭据。`auto` 计费在 `deepseek-account` 路由上,若该路由已挂载且释放出凭据,操作发送账号凭据。其他所有 `auto` 操作,包括账号会话中没有登录或没有凭据的操作,都把已挂载的 `deepseek-official` 路由的密钥(按该路由的 `apiKeyEnv` 读取,其基础地址包含 `DEEPSEEK_BASE_URL`)发往该路由基础地址的 origin 加 `/v1/tools`;没有该路由时,把 `DEEPSEEK_API_KEY` 发往 `https://api.deepseek.com/v1/tools`。`auto` 计费在两个已挂载的 DeepSeek 路由之外的路由上(包括这两个路由 id 之一而其插件未挂载的情况)或会话之外,没有配置密钥的操作改为发送账号令牌,因此已登录但没有密钥的用户在其他模型提供方的会话中仍可使用网页工具;在已挂载的 `deepseek-official` 路由上从不发送令牌,因为该会话按 API 密钥计费。未登录的账号会话发送 API 密钥,网页工具因此在其中仍然可用。因此只有 `DEEPSEEK_API_KEY` 的用户(包括所有 headless、SDK 与 ACP 运行)默认即可搜索和抓取,通过模型提供方基础地址设置的网关或内部部署也在同一 origin 上提供 Web 访问。缺少凭据时,该能力未就绪,操作以 `WEB_PROVIDER_CREDENTIAL_MISSING` 失败,指引信息按计费方式点名账号登录、模型页面与该引用,以及计费方式字段。已挂载但配置无法解析的路由不视为不存在:需要该路由的操作未就绪,并在读取依赖该路由的凭据前以 `WEB_PROVIDER_MISCONFIGURED` 失败,不再尝试后续来源,也不发送请求,因此网关设置出错时请求不会被改发到官方端点。
|
||||
|
||||
在 YAML 中设置了非空 `searchBaseURL` 或 `searchApiKeyEnv`(Fetch 为 `fetchBaseURL` 或 `fetchApiKeyEnv`)的能力,则无论计费方式如何,始终把其 `*ApiKeyEnv`(未设置时为 `DEEPSEEK_API_KEY`)下的密钥发往其 `*BaseURL`(未设置时为官方基础地址),从不发送账号令牌,因此内网或第三方端点只收到为它选择的密钥。每个能力有自己的字段,因为一个部署可以由不同网关提供搜索和抓取。这些字段只能在 YAML 中设置,空值视为未设置。schema 之外字段的已保存值,包括 `baseURL`、`apiKeyEnv` 和 `apiKey`,可以加载而不产生 schema 错误,且不生效。
|
||||
|
||||
DeepSeek 模型路由通过 `ctx.llm.providerCredential()` 发布自己发送的凭据([路由凭据](2026-11-10-llm-route-credential-seam.zh.md)):API 密钥路由发布其 `apiKeyEnv` 下的密钥,账号路由发布 `ctx.deepseekAccount` 为目标地址释放的凭据。Messages 搜索以及 Search 与 Fetch API 读取这些发布的凭据而不读取提供方配置,并通过 `dsh-credentials` 的引用函数读取 `DEEPSEEK_API_KEY` 和单独配置的密钥,因此每个 DeepSeek 请求都以同一方式读取凭据库;授权提供失效操作的凭据会在 HTTP 401 后被作废。内置配置不需要按 profile 覆盖凭据,因为只要 `DEEPSEEK_API_KEY` 或 DeepSeek API 密钥路由有密钥,API 密钥路径就能工作。
|
||||
这些凭据由 `ctx.deepseekAuth` 排序并释放([DeepSeek 请求鉴权](2026-11-10-deepseek-request-authentication.zh.md)):每条 DeepSeek 模型路由登记其设置所指的部署,API 密钥路由同时登记其 `apiKeyEnv` 下的密钥引用,账号登录凭据则是 `ctx.deepseekAccount` 为目标地址释放的凭据。Messages 搜索以及 Search 与 Fetch API 向该服务索取凭据而不读取提供方配置,该服务通过 `dsh-credentials` 的引用函数读取路由密钥、`DEEPSEEK_API_KEY` 和单独配置的密钥,因此每个 DeepSeek 请求都以同一方式读取凭据库;授权提供失效操作的凭据会在 HTTP 401 后被作废。内置配置不需要按 profile 覆盖凭据,因为只要 `DEEPSEEK_API_KEY` 或 DeepSeek API 密钥路由有密钥,API 密钥路径就能工作。
|
||||
|
||||
### 默认值与已保存的选择
|
||||
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
# Bilingual-pair consistency record for 2026-11-08-mcp-connector-accounts.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-11-08-mcp-connector-accounts.md
|
||||
/agent-note-mcp-connector-accounts-in-the-connector-account-registry:
|
||||
en: de9535f7ca161ae3
|
||||
zh: 50be52d2946e2058
|
||||
/agent-note-mcp-connector-accounts-in-the-connector-account-registry/problem:
|
||||
en: 3fcafe54fc134ff3
|
||||
zh: bbef331a0d9eccd5
|
||||
/agent-note-mcp-connector-accounts-in-the-connector-account-registry/decision:
|
||||
en: b6d50660986dad38
|
||||
zh: 4903122d0efd6e68
|
||||
/agent-note-mcp-connector-accounts-in-the-connector-account-registry/alternatives-considered:
|
||||
en: 0b7871c3d4aa7c52
|
||||
zh: c26061baed87bee4
|
||||
/agent-note-mcp-connector-accounts-in-the-connector-account-registry/consequences:
|
||||
en: c90b9de7c3b4e662
|
||||
zh: 7e126b5ac0f3e59e
|
||||
@@ -0,0 +1,35 @@
|
||||
# Agent Note: MCP connector accounts in the connector account registry
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-11-08-mcp-connector-accounts.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
Connector plugins such as Linear, Notion, and Tencent Docs register an OAuth MCP server with the MCP manager on the Host and show its account on the Plugins page. The manager already owns the authorization attempt, the grant, and the server status, and every connector shares the same states, buttons, and 23 strings. The [connector account registry](2026-11-06-connector-account-registry.md) shows each account from a Host source and presenter, so MCP needs one adapter that turns the manager's view of a server into that source and presenter.
|
||||
|
||||
## Decision
|
||||
|
||||
[`@deepseek-ai/dsh-mcp-account`](../../../../packages/mcp/mcp-account/README.md) provides `ctx.mcpAccounts`. A connector's Host row registers its server name, its bundle package, and the copy that names its service; the service registers the account with `ctx.connectorAccounts` under the key `mcp:<server>`.
|
||||
|
||||
| Part | Choice |
|
||||
|---|---|
|
||||
| Source | Reads the manager's `list()` entry for the server and observes `mcp-manager/status`; `refresh` does nothing, because the manager publishes every change |
|
||||
| Operation | A running authorization attempt is the operation and its identity is the operation's, so the browser that started it follows the manager's own attempt; a finished attempt is the result |
|
||||
| Page operations | `connect` starts authorization, also while connected, so the user changes the account or workspace without deleting the grant first; `sign-out` and `retry` sign out and restart through the manager and report their own result once they finish |
|
||||
| Phases | Waiting for the browser and authorizing are connecting; a server that needs authorization again is disconnected, with the reason in its detail; a closed, waiting, disabled, or failed server is unavailable, with Retry only where a restart recovers it |
|
||||
| Copy | The 23 strings every connector shares are Host dictionaries in eight languages; each connector supplies only the strings that name its service |
|
||||
|
||||
The manager's `startAuthorization`, `cancelAuthorization`, and `signOut` are Host methods without a Remote, so no browser names a server to authorize.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**Keep the manager's authorization operations on its Remote.** Rejected: the page would pass a server name the Host already holds, and two paths would start the same attempt.
|
||||
|
||||
**Track an adapter-owned operation for each authorization.** Rejected: the manager already tracks the attempt's identity, phases, and authorization page, so a second tracker would restate it. The registry lets a source answer `start` once the manager has created the attempt.
|
||||
|
||||
**Key each connector's account by its package.** Rejected: the server name is unique among MCP accounts, so the key also refuses a second account for one server, and a server configured in Settings, which no bundle owns, uses the same form.
|
||||
|
||||
## Consequences
|
||||
|
||||
A connector ships no browser code and no page rules; the shared page renders its account. An account that needs reconnection shows as disconnected without a separate warning color, and its status and detail name the reason. Each browser follows the one registry stream, and the Host follows the manager through its status event.
|
||||
@@ -0,0 +1,35 @@
|
||||
# Agent Note:MCP 连接器账号接入连接器账号注册表
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-11-08-mcp-connector-accounts.md) | 中文
|
||||
|
||||
## 问题
|
||||
|
||||
Linear、Notion、腾讯文档等连接器插件在 Host 上向 MCP 管理器注册 OAuth MCP 服务器,并在插件页显示其账号。管理器已经持有授权尝试、grant 和服务器状态,各连接器的状态、按钮和 23 条文案都相同。[连接器账号注册表](2026-11-06-connector-account-registry.zh.md)根据 Host 上的来源和展示函数显示每个账号,因此 MCP 需要一个适配,把管理器对服务器的视图转换为这样的来源和展示函数。
|
||||
|
||||
## 决定
|
||||
|
||||
[`@deepseek-ai/dsh-mcp-account`](../../../../packages/mcp/mcp-account/README.zh.md) 提供 `ctx.mcpAccounts`。连接器的 Host 行注册其服务器名、插件包以及点出服务名称的文案;该服务以 `mcp:<server>` 为键,把账号注册到 `ctx.connectorAccounts`。
|
||||
|
||||
| 部分 | 选择 |
|
||||
|---|---|
|
||||
| 来源 | 读取管理器 `list()` 中该服务器的条目,并观察 `mcp-manager/status`;`refresh` 什么也不做,因为管理器会发布每次变化 |
|
||||
| 操作 | 进行中的授权尝试就是操作,其 id 就是操作的 id,因此发起它的浏览器跟随的是管理器自己的尝试;结束的尝试就是结果 |
|
||||
| 页面操作 | `connect` 发起授权,已连接时也可用,用户不必先删除授权就能更换账号或工作区;`sign-out` 和 `retry` 通过管理器退出登录、重启服务器,结束后报告各自的结果 |
|
||||
| 阶段 | 等待浏览器和授权中属于连接中;需要重新授权的服务器属于未连接,原因写在说明里;已关闭、等待凭据、已停用或失败的服务器属于不可用,只有重启能恢复时才提供“重试” |
|
||||
| 文案 | 各连接器共用的 23 条文案是 Host 上 8 种语言的字典;每个连接器只提供点出其服务名称的文案 |
|
||||
|
||||
管理器的 `startAuthorization`、`cancelAuthorization` 和 `signOut` 是不带 Remote 的 Host 方法,因此浏览器不会指定要授权的服务器。
|
||||
|
||||
## 考虑过的替代方案
|
||||
|
||||
**管理器的授权操作继续走它的 Remote。** 否决:页面要传入 Host 已经知道的服务器名,而且会有两条路径发起同一次尝试。
|
||||
|
||||
**为每次授权维护适配自己的操作。** 否决:管理器已经记录尝试的 id、阶段和授权页,第二套记录只会重复它。注册表允许来源在管理器创建尝试后再回答 `start`。
|
||||
|
||||
**以插件包作为连接器账号的键。** 否决:服务器名在 MCP 账号中唯一,因此这个键也会拒绝同一服务器的第二个账号;没有插件包的、在 Settings 中配置的服务器也使用同样的键。
|
||||
|
||||
## 影响
|
||||
|
||||
连接器不提供任何浏览器代码和页面规则,由共用的页面渲染其账号。需要重新连接的账号显示为未连接,不再单独使用警示色,其状态和说明会点出原因。每个浏览器跟随同一条注册表流,Host 通过管理器的状态事件跟随管理器。
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
# Bilingual-pair consistency record for 2026-11-10-deepseek-request-authentication.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-11-10-deepseek-request-authentication.md
|
||||
/agent-note-deepseek-request-authentication-one-service-releases-the-api-key-or-the-account-sign-in-to-every-deepseek-consumer:
|
||||
en: 0ede9c11789e5fd7
|
||||
zh: c3e552dfe6216df0
|
||||
/agent-note-deepseek-request-authentication-one-service-releases-the-api-key-or-the-account-sign-in-to-every-deepseek-consumer/problem:
|
||||
en: 1470ef8f922d447a
|
||||
zh: ccd66a1b897c88e2
|
||||
/agent-note-deepseek-request-authentication-one-service-releases-the-api-key-or-the-account-sign-in-to-every-deepseek-consumer/decision:
|
||||
en: 316f5dc600e50f33
|
||||
zh: f52cacf521e94159
|
||||
/agent-note-deepseek-request-authentication-one-service-releases-the-api-key-or-the-account-sign-in-to-every-deepseek-consumer/alternatives-considered:
|
||||
en: 3a4f69542b4a91b2
|
||||
zh: 1eb4edce81a858d6
|
||||
/agent-note-deepseek-request-authentication-one-service-releases-the-api-key-or-the-account-sign-in-to-every-deepseek-consumer/consequences:
|
||||
en: 88174cd0c4fca1ee
|
||||
zh: ae56350b8198a0b0
|
||||
@@ -0,0 +1,73 @@
|
||||
# Agent Note: DeepSeek request authentication - one service releases the API key or the account sign-in to every DeepSeek consumer
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-11-10-deepseek-request-authentication.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
DeepSeek APIs accept two kinds of credential, an API key and the account sign-in, and each API accepts one or both: the Messages, Files, and model-listing requests of each model route carry one kind, Search and Fetch accept both, and DeepSeek adds account authentication to its other APIs one at a time. No package owned the choice between the two kinds. `@deepseek-ai/dsh-llm-deepseek`, the protocol transport, exported helpers that read `ctx.credentials`, the launch environment, and `ctx.deepseekAccount`, so the transport depended on both credential services although it only sends the headers a route gives it. The two route plugins resolved their credentials through those helpers and threw their own missing-credential failures from inside `resolveAuth`. The Search and Fetch API providers re-derived each route's base URL and key reference from the Loader entry of the route package with that package's own config resolver, ordered the two credentials by their billing setting, and rendered the request headers; Messages search hard-coded the account route id and applied an order of its own. Both web packages therefore depended on `llm-deepseek`, on both route plugins, and on the Loader, and a consumer of another DeepSeek API would have repeated the selection, the deployment binding, the header rendering, and the invalidation. The account service, which sits below every consumer, owned Agent cancellation after sign-out and lived in the `credentials/` group beside the credential store it only uses. A change to how one route authenticates touched the transport, both web providers, and their tests.
|
||||
|
||||
## Decision
|
||||
|
||||
`@deepseek-ai/dsh-deepseek-auth`, in the `packages/account/` group, provides `ctx.deepseekAuth`. The package holds the Service Definition and the Service Provider of DeepSeek request authentication, and every plugin that calls a DeepSeek API is a Consumer. A consumer describes one request: the credential kinds its API `accepts`, the `billing` its settings choose, the model `route` of the conversation, and a `destination`, either a path under the chosen kind's deployment or one absolute URL. `candidates(request)` returns the kinds in billing order, each bound to the endpoint its credential is sent to, and reads no credential. `authorize(request, signal)` releases the first kind that has a credential as a `DeepSeekAuthorization`: the `kind`, the `endpoint`, the request `headers`, the key `reference` for diagnostics, and for the account sign-in a `reject()` for HTTP 401 and a `revoked` signal that aborts when the account signs out. An authorization carries no bare credential value: a consumer names the headers an API key is sent in through `apiKeyHeaders`, and the account service chooses the header of the sign-in.
|
||||
|
||||
The service owns the billing order. `api-key` and `account` billing try that kind only. `auto` follows the conversation: on the route a plugin connected for the account sign-in, the sign-in and then the API key; on the route a plugin connected for the API key, the API key; on any other route, or outside a conversation, the API key and then the sign-in. The service names no route id: each model route plugin passes the provider route it registers when it connects, and `routeKind(route)` answers the kind connected under that id. A conversation recorded on `deepseek-account` or `deepseek-official` whose plugin is not mounted is ordered as any other route. A kind outside `accepts` is never a candidate.
|
||||
|
||||
Each kind has one deployment at a time. A model route plugin connects its provider route and the deployment its settings name with `connect(kind, route, connection)` inside `ctx.effect()`, and the service calls `connection` for each request. Without a connection the API key is `DEEPSEEK_API_KEY` at `https://api.deepseek.com`, and the sign-in goes to the origin `DEEPSEEK_BASE_URL` names, the official API by default. A credential is released only for a destination under the origin of its kind's deployment that embeds no credentials. A request can carry its own connection of a kind in `connections`, which replaces the connected or default one: a model route passes the configuration generation it captured for one model request, and a consumer with its own endpoint and key passes those. A kind whose connection does not resolve stays among the candidates as an unresolved entry, and `authorize()` stops there with `UNRESOLVED_CONNECTION` and does not try a later kind.
|
||||
|
||||
The API key is read through `resolveCredentialRef` and `credentialRefConfigured` of `@deepseek-ai/dsh-credentials`, which treat a mounted credentials service as authoritative and read the launch environment only without one. `dsh-credentials` also owns `normalizeApiKey`, the Host definition of a key that an HTTP header can carry, which answers the trimmed key or the reason a key cannot be used and words no diagnostic. The service words the diagnostic of an unusable key and reports it as `DeepSeekAuthError` with code `INVALID_CREDENTIAL`, `llm-pi-ai` words its own and reports it as `LlmError`, and `@deepseek-ai/dsh-llm` holds neither a credential interface nor a key check. The account sign-in is what `ctx.deepseekAccount.resolveRequestCredential(endpoint)` releases; it is absent in a composition without the account service.
|
||||
|
||||
`@deepseek-ai/dsh-llm-deepseek` reads no credential. `DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` returns the request headers, an optional `revoked` signal, and an optional failure callback, or `undefined`; `missingCredential(connection, provider)` names the failure of a request without a credential, `MISSING_CREDENTIAL` by default. The transport runs each model request and its file operations under the `revoked` signal and hands the resulting failure to the provider's failure callback, which names it. The listing cache scopes by endpoint and a hash of the credential headers.
|
||||
|
||||
The route plugins are consumers that also connect their deployment, and both require the service. `llm-deepseek-api-key` connects, under its route id, its base URL, its `apiKeyEnv` reference, and its settings namespace as the owner that key diagnostics name; it asks for the key in `x-api-key` with `accepts: ['api-key']` and reports an unusable key as its own `INVALID_CREDENTIAL`. `llm-deepseek-account` connects its base URL under its route id, asks with `accepts: ['account']`, maps HTTP 401 to `ACCOUNT_TOKEN_INVALID` and quota failures to `ACCOUNT_QUOTA`, fails without a credential as `ACCOUNT_SIGN_IN_REQUIRED`, and owns the sign-out policy: it cancels its running Agents on `deepseek-account/signed-out` and registers a running-task report with the account service. A request in flight at sign-out ends with its authorization's `revoked` signal and fails as `ACCOUNT_SIGN_IN_REQUIRED`, and its failure callback cancels the same Agents, so a request that outlives the plugin still ends its turn with the signed-out cause.
|
||||
|
||||
`@deepseek-ai/dsh-deepseek-account` releases request credentials to the authentication service. `resolveRequestCredential(url)` returns the `x-dsh-auth-token` header, a `reject()` that removes the grant while it still matches and contains storage failures, and a `revoked` signal the account service aborts at each sign-out after the `deepseek-account/signed-out` listeners have returned; `registerRunningTaskReport(report)` feeds `hasRunningAccountTasks()`. The account service inspects no Agents and depends on neither `dsh-agent`, `dsh-llm`, nor the authentication service. The package lives in the `packages/account/` group under its unchanged name.
|
||||
|
||||
The web providers declare what their APIs accept. `web-deepseek-api` asks for candidates with `accepts: ['account', 'api-key']`, the capability's billing, the conversation's route, and the path `/v1/tools/search` or `/v1/tools/fetch`; a capability with its own `*BaseURL` or `*ApiKeyEnv` asks with `accepts: ['api-key']` and its own connection, so only that key goes to that endpoint. `web-search-deepseek` passes its search endpoint as an absolute destination and its referenced key as its own connection. In a conversation on the connected account route it asks with `auto` billing, so the sign-in comes first when the search endpoint is under the origin of the account deployment; every other search asks with `api-key` billing. A literal `apiKey` is the provider's own credential: beside it the provider asks only for the sign-in, and sends the literal key when the service releases none. `web-deepseek-api` words its missing-credential and unresolved-settings failures from the candidates. Both web consumers contain a failed `reject()` so the HTTP rejection stays the reported error, run their request under the authorization's `revoked` signal, and report a request that signal ended as `WEB_PROVIDER_ERROR` with sign-in guidance, keeping `WEB_ABORTED` for the caller's cancellation. Neither web package depends on `llm-deepseek`, the route plugins, the Loader, or the account service, and neither reads a credential through `dsh-llm`: `web-search-deepseek` does not depend on it, and `web-deepseek-api` imports only the message text helper `extractTextContent` from it.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**Publishing each route's credential through the model service.** `LlmAdapter.providerCredential(provider)` on `dsh-llm` would answer a route's credential kind, its base URL, and a grant for one endpoint, and consumers would read `ctx.llm.providerCredential('deepseek-official')` and `providerCredential('deepseek-account')`. A lookup keyed by model route leaves every consumer to order the two credentials by billing, to render its own headers from a bare value, and to fall back by itself when a route is not mounted. An API outside the model protocol, such as the speech and document APIs under `/v1/tools/`, has no route to ask and no place to declare the kinds it accepts. The model service would carry a credential interface with one publisher, the DeepSeek adapter, and two web consumers.
|
||||
|
||||
**A shared library over that publication instead of a service.** The model routes authenticate through the same operation as every other consumer, and a library that reads what the routes publish cannot serve the routes themselves.
|
||||
|
||||
**Checking keys through `dsh-llm`, through a copy in the service, or through a validator each consumer passes.** A service shared by every DeepSeek consumer must not depend on the model service, which is one consumer's dependency. A second Host copy of the rule would be kept in step with the first and with the browser's copy by comments only. A validator parameter would make each consumer that accepts a key pass one, and the web packages would keep their `dsh-llm` dependency for it. The check lives in `dsh-credentials`, the layer that reads the key, and each caller words its own failure for the reason the check returns.
|
||||
|
||||
**The diagnostic text of an unusable key in `dsh-credentials`.** One function there would give the service and `llm-pi-ai` the same words. The text tells the user to set the reference on the Models page, so the package that stores credentials would name a page of its consumers. Each of the two callers words the text, and the credential store names no consumer.
|
||||
|
||||
**`dsh-llm` importing the key check from `dsh-credentials`.** Nothing in the model service reads a key. Its only caller of the check was `llm-pi-ai`, which already depends on `dsh-credentials`, so the model service exports no key check and gains no dependency.
|
||||
|
||||
**A `deepseek-api-key` package beside `deepseek-account`.** `deepseek-account` is the account product feature: browser sign-in, the stored grant, profile, balance, notifications, and the Platform session, of which releasing a request credential is a small part. The API key has no such feature. It is a named string in the generic credential store, and its DeepSeek-specific logic is the key source inside the service. A package becomes worthwhile when DeepSeek-specific key behavior appears, such as a balance per key, server-side validation, or several keys.
|
||||
|
||||
**Merging the two model route plugins, or their route ids.** They are two model providers with different settings and catalog sources, the `ACCOUNT_*` failure mapping, and the sign-out policy over running tasks. The route id is the durable record of how a conversation is billed: Session logs carry it, and sign-out cancellation and `auto` billing read it.
|
||||
|
||||
**A fixed table of the two DeepSeek route ids in the service.** `routeKind()` would answer for `deepseek-account` and `deepseek-official` whichever plugins are mounted, and a conversation recorded on the account route would try only the API key while the account route plugin is not mounted. The table would put the route ids of two consumers into the service those consumers depend on. Each route plugin passes its own id when it connects, and a route id whose plugin is not mounted is ordered as any other route.
|
||||
|
||||
**Route plugins that work without the service.** An optional service would leave compositions and tests that mount a route by hand unchanged, but each route would keep a credential path that bypasses the service.
|
||||
|
||||
**One billing order for every consumer.** Messages search outside an account conversation never tries the sign-in. Giving it the general order would change which credential existing conversations send, so the rule stays.
|
||||
|
||||
**A credential fingerprint in the authorization.** Consumers only send requests, so they need headers; cache scoping by credential is the adapter's own concern, which the listing cache meets by hashing the headers it sends.
|
||||
|
||||
**A `credentials-env` provider instead of reference helpers.** A provider that reads the environment would change which composition is authoritative for every consumer; the helpers keep the launch-environment fallback local to the consumers that need it, so such a provider remains an independent option.
|
||||
|
||||
**The account service's inference origin for the sign-in without a connected account route.** Routing that default through `DEEPSEEK_BASE_URL` keeps the keyless billing snapshot and every documented deployment unchanged; the account service still refuses every origin but its own.
|
||||
|
||||
**Moving the account package into `identity/`.** That group defines anonymous, user-independent ids; a signed-in account is the opposite, so it gets a group of its own.
|
||||
|
||||
**Keeping the route plugin's sign-out listener until its tasks end.** Unloading the route then waits for a running turn: disabling the plugin blocks, and every other settings write queues behind that reload, for as long as the turn runs.
|
||||
|
||||
**Cancelling the route's tasks when the route unloads.** A configuration reload or a plugin update would stop turns that no sign-out touched.
|
||||
|
||||
**Returning the sign-out policy to the account service.** The service would again inspect Agents and know route ids, the dependencies this decision removes.
|
||||
|
||||
**Keeping the route's listener or report registered after its plugin unloads.** A registration that outlives the plugin that made it breaks the rule that registrations are effects of their owner, and leaves code of an unloaded plugin running in another scope for as long as the task runs.
|
||||
|
||||
## Consequences
|
||||
|
||||
A consumer of another DeepSeek API declares the kinds that API accepts; it reads no credential, renders no header, and holds no fallback. When an API gains a kind, its consumer widens `accepts`. A new credential kind is a source in the service and a member of `DeepSeekAuthKind`. The transport, the model service, the web providers, and the account service do not depend on one another for credentials, and `hasRunningAccountTasks()` depends on a registered report rather than on Agents the account service can see. The `llm-deepseek` credential helpers and the route plugins' config exports do not exist; the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.3/deepseek-request-auth/guide.md) lists the replacements.
|
||||
|
||||
Every composition that mounts a DeepSeek model route or a DeepSeek web provider mounts the service; without it those plugins wait and register nothing. The `base` and `sdk-minimal` bundles carry its row, and the SDK server mounts it with its fallback route when the composition has none. One deployment per kind means a second `connect()` of a kind throws `DUPLICATE_CONNECTION`. `auto` billing recognizes a route only while the plugin that registers it is connected: a conversation recorded on `deepseek-account` or `deepseek-official` whose plugin is not mounted, and a DeepSeek model reached through another provider plugin, are ordered as any other route, so their Search and Fetch operations send the API key and, without a key, the account sign-in. A route's configuration failure reaches consumers as an unresolved candidate: the Search and Fetch APIs report it as `WEB_PROVIDER_MISCONFIGURED`, Messages search as `WEB_PROVIDER_ERROR`, and neither tries a later credential. An unusable key reaches a web tool's result under the error name `DeepSeekAuthError`.
|
||||
|
||||
A sign-out ends the in-flight model, Files, Search, and Fetch requests that carry the account token, including requests no Agent turn owns, such as a model request outside a turn or an account-billed web search; the account listing request keeps its own deadline. The signal supplements the Agent cancellation of the [account sign-out decision](2026-09-17-account-provider-signout.md), which rejected a login-level signal as a duplicate of that chain: the chain reaches a request only through a mounted listener and a running Agent turn. While the account route is disabled, a task it started that still runs is not reported to the sign-out confirmation, and a sign-out ends it only through a model request in flight. A credential released by an account service that has since been replaced is not withdrawn by the replacement's sign-out; the route plugin's listener still cancels Agent turns.
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
# Agent Note: DeepSeek request authentication - one service releases the API key or the account sign-in to every DeepSeek consumer
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-11-10-deepseek-request-authentication.md) | 中文
|
||||
|
||||
## 问题
|
||||
|
||||
DeepSeek 的 API 接受两种凭据:API 密钥和账号登录。每个 API 接受其中一种或两种:每条模型路由的 Messages、Files 和模型列表请求只带一种,Search 与 Fetch 两种都接受,DeepSeek 还在逐个为其他 API 增加账号鉴权。在两种凭据之间做选择这件事没有所有者。协议传输层 `@deepseek-ai/dsh-llm-deepseek` 导出读取 `ctx.credentials`、启动环境和 `ctx.deepseekAccount` 的辅助函数,因此尽管传输层只发送路由交给它的请求头,它仍依赖两个凭据服务。两个路由插件通过这些函数解析凭据,并在 `resolveAuth` 内部抛出各自的凭据缺失错误。Search 与 Fetch API 提供方用路由包自己的配置解析函数,从路由包的 Loader 条目重新推导每条路由的基础地址和密钥引用,按自己的计费设置排定两种凭据的顺序,并自己组装请求头;Messages 搜索则硬编码账号路由 id,并使用自己的一套顺序。因此两个 Web 包都依赖 `llm-deepseek`、两个路由插件和 Loader,而其他 DeepSeek API 的消费方还得把选择凭据、绑定部署、组装请求头和作废凭据再做一遍。位于所有消费方之下的账号服务拥有退登后的 Agent 取消逻辑,并和它仅仅使用的凭据库一起放在 `credentials/` 组。改变一条路由的鉴权方式要同时触及传输层、两个 Web 提供方及其测试。
|
||||
|
||||
## 决策
|
||||
|
||||
位于 `packages/account/` 组的 `@deepseek-ai/dsh-deepseek-auth` 提供 `ctx.deepseekAuth`。该包同时承担 DeepSeek 请求鉴权的 Service Definition 和 Service Provider,每个调用 DeepSeek API 的插件都是 Consumer。消费方描述一次请求:它的 API 接受的凭据种类 `accepts`、其设置选择的计费方式 `billing`、会话的模型路由 `route`,以及目的地 `destination`,即所选种类的部署之下的一个路径,或一个绝对 URL。`candidates(request)` 按计费顺序返回各个种类,每个种类都绑定到其凭据发往的端点,且不读取任何凭据。`authorize(request, signal)` 把第一个持有凭据的种类释放为 `DeepSeekAuthorization`:`kind`、`endpoint`、请求 `headers`、供诊断使用的密钥 `reference`,账号登录还带有用于 HTTP 401 的 `reject()` 和在账号退登时中止的 `revoked` 信号。授权不携带裸的凭据值:消费方通过 `apiKeyHeaders` 指定 API 密钥放进哪些请求头,账号登录的请求头由账号服务决定。
|
||||
|
||||
计费顺序由该服务拥有。`api-key` 与 `account` 计费只尝试对应的那一种。`auto` 跟随会话:在某个插件为账号登录登记的路由上先尝试账号登录、再尝试 API 密钥;在某个插件为 API 密钥登记的路由上只尝试 API 密钥;在其他路由上或不在会话中时,先尝试 API 密钥、再尝试账号登录。该服务自身不写任何路由 id:每个模型路由插件在登记时传入它注册的提供方路由,`routeKind(route)` 回答在该 id 下登记的种类。记录在 `deepseek-account` 或 `deepseek-official` 上的会话,在对应插件未挂载时按其他路由处理。不在 `accepts` 中的种类永远不会成为候选。
|
||||
|
||||
每个种类同一时间只有一个部署。模型路由插件在 `ctx.effect()` 内用 `connect(kind, route, connection)` 登记自己的提供方路由及其设置所指的部署,服务为每个请求调用 `connection`。没有登记时,API 密钥是发往 `https://api.deepseek.com` 的 `DEEPSEEK_API_KEY`,账号登录发往 `DEEPSEEK_BASE_URL` 所指的 origin,默认为官方 API。凭据只释放给其种类的部署 origin 之下且不内嵌凭据的目的地。请求可以在 `connections` 里携带某一种类自己的连接,它取代已登记的或默认的连接:模型路由传入它为一次模型请求捕获的那一代配置,拥有自己端点和密钥的消费方传入这两项。连接无法解析的种类作为未解析条目留在候选中,`authorize()` 在此以 `UNRESOLVED_CONNECTION` 停止,不再尝试后面的种类。
|
||||
|
||||
API 密钥通过 `@deepseek-ai/dsh-credentials` 的 `resolveCredentialRef` 和 `credentialRefConfigured` 读取,二者把已挂载的凭据服务视为权威,仅在没有该服务时读取启动环境。`dsh-credentials` 还拥有 `normalizeApiKey`,即 Host 端对“能放进 HTTP 请求头的密钥”的定义:它回答去掉首尾空白后的密钥,或密钥不可用的原因,不生成任何诊断文案。该服务为不可用的密钥写出诊断文案,并将其报告为代码 `INVALID_CREDENTIAL` 的 `DeepSeekAuthError`,`llm-pi-ai` 写出自己的文案并报告为 `LlmError`,`@deepseek-ai/dsh-llm` 既不带凭据接口也不带密钥检查。账号登录就是 `ctx.deepseekAccount.resolveRequestCredential(endpoint)` 释放的凭据;组合中没有账号服务时不存在这种凭据。
|
||||
|
||||
`@deepseek-ai/dsh-llm-deepseek` 不读取任何凭据。`DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` 返回请求头、可选的 `revoked` 信号和可选的失败回调,或 `undefined`;`missingCredential(connection, provider)` 命名没有凭据时请求的失败,默认为 `MISSING_CREDENTIAL`。传输层让每次模型请求及其文件操作受 `revoked` 信号约束,并把由此产生的失败交给提供方的失败回调命名。列表缓存以端点和凭据请求头的哈希划分作用域。
|
||||
|
||||
路由插件是同时登记自身部署的消费方,二者都要求该服务已挂载。`llm-deepseek-api-key` 在自己的路由 id 下登记其基础地址、`apiKeyEnv` 引用,以及作为密钥诊断所指属主的设置命名空间;它以 `accepts: ['api-key']` 索取放在 `x-api-key` 里的密钥,并把不可用的密钥报告为自己的 `INVALID_CREDENTIAL`。`llm-deepseek-account` 在自己的路由 id 下登记其基础地址,以 `accepts: ['account']` 索取凭据,把 HTTP 401 映射为 `ACCOUNT_TOKEN_INVALID`、配额失败映射为 `ACCOUNT_QUOTA`,没有凭据时以 `ACCOUNT_SIGN_IN_REQUIRED` 失败,并拥有退登策略:在 `deepseek-account/signed-out` 时取消其运行中的 Agent,并向账号服务注册运行中任务报告。退登时在途的请求随其授权的 `revoked` 信号结束,以 `ACCOUNT_SIGN_IN_REQUIRED` 失败;它的失败回调会取消同一批 Agent,因此比插件存活更久的请求仍会以退登原因结束其回合。
|
||||
|
||||
`@deepseek-ai/dsh-deepseek-account` 向鉴权服务释放请求凭据。`resolveRequestCredential(url)` 返回 `x-dsh-auth-token` 请求头、`reject()` 和 `revoked` 信号;`reject()` 仅在已存储的授权记录仍一致时删除它并隔离存储失败,`revoked` 由账号服务在每次退登时、`deepseek-account/signed-out` 的监听器返回之后中止。`registerRunningTaskReport(report)` 为 `hasRunningAccountTasks()` 提供答案。账号服务不检查任何 Agent,也不依赖 `dsh-agent`、`dsh-llm` 或鉴权服务。包以不变的名字位于 `packages/account/` 组。
|
||||
|
||||
Web 提供方声明各自的 API 接受什么。`web-deepseek-api` 以 `accepts: ['account', 'api-key']`、该能力的计费设置、会话的路由,以及路径 `/v1/tools/search` 或 `/v1/tools/fetch` 索取候选;设置了自己的 `*BaseURL` 或 `*ApiKeyEnv` 的能力以 `accepts: ['api-key']` 和自己的连接索取,因此发往该端点的只有那把密钥。`web-search-deepseek` 把搜索端点作为绝对目的地传入,把它引用的密钥作为自己的连接传入。在已登记的账号路由上的会话里,它以 `auto` 计费索取,因此当搜索端点位于账号部署的 origin 之下时先尝试账号登录;其他搜索都以 `api-key` 计费索取。字面 `apiKey` 是该提供方自己的凭据:有它时提供方只索取账号登录,服务不释放任何凭据时发送字面密钥。`web-deepseek-api` 依据候选来措辞凭据缺失和设置无法解析的失败。两个 Web 消费方都隔离失败的 `reject()` 以保证报告的是 HTTP 拒绝,都让请求受授权的 `revoked` 信号约束,并把被该信号结束的请求报告为带登录指引的 `WEB_PROVIDER_ERROR`,`WEB_ABORTED` 仍只表示调用方取消。两个 Web 包都不依赖 `llm-deepseek`、路由插件、Loader 或账号服务,也都不经 `dsh-llm` 读取凭据:`web-search-deepseek` 不依赖它,`web-deepseek-api` 只从它导入消息文本辅助函数 `extractTextContent`。
|
||||
|
||||
## 考虑过的替代方案
|
||||
|
||||
**通过模型服务发布每条路由的凭据。** `dsh-llm` 上的 `LlmAdapter.providerCredential(provider)` 回答一条路由的凭据种类、基础地址和面向某个端点的授权,消费方读取 `ctx.llm.providerCredential('deepseek-official')` 和 `providerCredential('deepseek-account')`。按模型路由查询意味着每个消费方都要自己按计费排定两种凭据的顺序、自己用裸值组装请求头,并在路由未挂载时自己回退。模型协议之外的 API,例如 `/v1/tools/` 下的语音和文档 API,既没有可以询问的路由,也没有地方声明它接受哪些种类。模型服务还要带上一个凭据接口,而它只有 DeepSeek 适配器一个发布方和两个 Web 消费方。
|
||||
|
||||
**在上述发布之上用公共库代替服务。** 模型路由与其他消费方通过同一个操作鉴权,而读取路由所发布内容的库无法反过来为路由本身服务。
|
||||
|
||||
**通过 `dsh-llm` 检查密钥、在服务里保留一份副本,或由每个消费方传入校验函数。** 所有 DeepSeek 消费方共用的服务不能依赖模型服务,后者只是其中一类消费方的依赖。Host 端的第二份规则只能靠注释与第一份以及浏览器端的那份保持一致。校验函数参数会让每个接受密钥的消费方都传一个,两个 Web 包也要为此继续依赖 `dsh-llm`。检查放在读取密钥的那一层 `dsh-credentials`,每个调用方依据检查返回的原因写出自己的失败。
|
||||
|
||||
**把不可用密钥的诊断文案放在 `dsh-credentials`。** 那里的一个函数能让该服务和 `llm-pi-ai` 使用同样的措辞。但文案要告诉用户在 Models 页面设置该引用,存储凭据的包就会写出其消费方的页面。两个调用方各自写出文案,凭据存储不写任何消费方的名字。
|
||||
|
||||
**让 `dsh-llm` 从 `dsh-credentials` 导入密钥检查。** 模型服务里没有任何代码读取密钥。该检查在其中唯一的调用方是 `llm-pi-ai`,而它已经依赖 `dsh-credentials`,因此模型服务不导出密钥检查,也不新增依赖。
|
||||
|
||||
**在 `deepseek-account` 旁边设一个 `deepseek-api-key` 包。** `deepseek-account` 是账号这项产品功能:浏览器登录、已存储的授权、资料、余额、通知和 Platform 会话,释放请求凭据只占其中一小部分。API 密钥没有这样的功能。它是通用凭据库里一个有名字的字符串,它的 DeepSeek 专属逻辑就是服务内部的密钥来源。等到出现 DeepSeek 专属的密钥行为,例如按密钥查余额、向服务端校验或多把密钥,才值得拆出一个包。
|
||||
|
||||
**合并两个模型路由插件,或合并它们的路由 id。** 它们是两个模型提供方,设置和目录来源不同,还各有 `ACCOUNT_*` 失败映射和针对运行中任务的退登策略。路由 id 是一段会话如何计费的持久记录:会话日志携带它,退登取消和 `auto` 计费读取它。
|
||||
|
||||
**在服务里放一张含两个 DeepSeek 路由 id 的固定表。** 无论挂载了哪些插件,`routeKind()` 都会为 `deepseek-account` 和 `deepseek-official` 作答,记录在账号路由上的会话在账号路由插件未挂载时只尝试 API 密钥。这张表会把两个消费方的路由 id 写进它们所依赖的服务。每个路由插件在登记时传入自己的 id,插件未挂载的路由 id 按其他路由处理。
|
||||
|
||||
**让路由插件在没有该服务时也能工作。** 把服务做成可选依赖可以让手工挂载路由的组合和测试保持不变,但每条路由都要保留一条绕过该服务的取凭据路径。
|
||||
|
||||
**让所有消费方使用同一套计费顺序。** Messages 搜索在账号会话之外从不尝试账号登录。让它采用通用顺序会改变现有会话发送的凭据,因此这条规则保留。
|
||||
|
||||
**在授权中加入凭据指纹。** 消费方只负责发送请求,因此只需要请求头;按凭据划分缓存作用域是适配器自己的事,列表缓存通过哈希它发送的请求头即可满足。
|
||||
|
||||
**用 `credentials-env` 提供方代替引用函数。** 读取环境的提供方会改变每个消费方眼中哪个组合具有权威性;引用函数把启动环境后备保留在需要它的消费方本地,使这样的提供方仍是独立的选项。
|
||||
|
||||
**没有登记账号路由时,账号登录使用账号服务的推理 origin。** 让该默认值经由 `DEEPSEEK_BASE_URL` 可保持无密钥计费快照和所有已记录部署不变;账号服务仍拒绝除自身 origin 以外的一切来源。
|
||||
|
||||
**把账号包并入 `identity/`。** 该组定义匿名、不识别用户的 id;已登录账号与之相反,因此单独成组。
|
||||
|
||||
**让路由插件的退登监听保留到其任务结束。** 这样卸载路由要等待运行中的回合:停用插件会被阻塞,其他设置写入也排在这次重载之后,直到回合结束。
|
||||
|
||||
**路由卸载时取消其任务。** 配置重载或插件更新会停掉与退登无关的回合。
|
||||
|
||||
**把退登策略放回账号服务。** 账号服务将重新检查 Agent 并认识路由 id,而这正是本决策去掉的依赖。
|
||||
|
||||
**插件卸载后仍保留路由的监听或报告注册。** 比注册它的插件存活更久的注册违反“注册是其所有者的 effect”这一规则,并让已卸载插件的代码在任务运行期间留在其他作用域里。
|
||||
|
||||
## 后果
|
||||
|
||||
其他 DeepSeek API 的消费方只声明该 API 接受的种类;它不读取凭据、不组装请求头,也不保留回退逻辑。某个 API 新增一种凭据时,它的消费方扩充 `accepts`。新增凭据种类意味着在服务里加一个来源,并为 `DeepSeekAuthKind` 加一个成员。传输层、模型服务、Web 提供方和账号服务在凭据上互不依赖,`hasRunningAccountTasks()` 依赖注册的报告而非账号服务可见的 Agent。`llm-deepseek` 的凭据辅助函数和路由插件的配置导出不复存在;[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.3/deepseek-request-auth/guide.zh.md)列出了替代方案。
|
||||
|
||||
凡是挂载 DeepSeek 模型路由或 DeepSeek Web 提供方的组合都要挂载该服务;没有它时这些插件一直等待,不注册任何东西。`base` 和 `sdk-minimal` 两个组合包带有它的条目,SDK 服务端在组合里没有它时随后备路由一起挂载它。每个种类一个部署意味着对同一种类第二次 `connect()` 会抛出 `DUPLICATE_CONNECTION`。`auto` 计费只在注册某条路由的插件已登记时才认它:记录在 `deepseek-account` 或 `deepseek-official` 上而对应插件未挂载的会话,以及经由其他提供方插件访问的 DeepSeek 模型,都按其他路由处理,因此它们的 Search 与 Fetch 操作发送 API 密钥,没有密钥时发送账号登录。路由的配置失败以未解析候选的形式到达消费方:Search 与 Fetch API 将其报告为 `WEB_PROVIDER_MISCONFIGURED`,Messages 搜索报告为 `WEB_PROVIDER_ERROR`,二者都不再尝试后面的凭据。不可用的密钥在 Web 工具的结果里以错误名 `DeepSeekAuthError` 出现。
|
||||
|
||||
退登会结束携带账号 token 的在途模型、Files、Search 与 Fetch 请求,包括不属于任何 Agent 回合的请求,例如回合之外的模型请求或按账号计费的 Web 搜索;账号列表请求仍只受自身期限约束。该信号是对[账号退登决策](2026-09-17-account-provider-signout.zh.md)中 Agent 取消链路的补充;那份决策以重复该链路为由否决了登录级信号,而该链路只能经由已挂载的监听和运行中的 Agent 回合到达请求。账号路由被停用期间,它此前启动且仍在运行的任务不会报告给退登确认,退登也只能通过在途的模型请求结束它。已被替换的账号服务释放的凭据不会被替换后服务的退登撤回;路由插件的监听仍会取消 Agent 回合。
|
||||
@@ -1,19 +0,0 @@
|
||||
# Bilingual-pair consistency record for 2026-11-10-llm-route-credential-seam.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-11-10-llm-route-credential-seam.md
|
||||
/agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse:
|
||||
en: d11883f28d5cdd99
|
||||
zh: 860795ae4d93c317
|
||||
/agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/problem:
|
||||
en: 9665e1879893fe76
|
||||
zh: 9da30ad0be6fc38d
|
||||
/agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/decision:
|
||||
en: aaa2d2c7202408d4
|
||||
zh: 134987da042fd07b
|
||||
/agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/alternatives-considered:
|
||||
en: d6b2de393add9887
|
||||
zh: b5351f9a49387bd6
|
||||
/agent-note-route-credentials-deepseek-model-routes-publish-the-credential-consumers-reuse/consequences:
|
||||
en: df942606f0d31fa5
|
||||
zh: cb1f21dd7f60ab7f
|
||||
@@ -1,47 +0,0 @@
|
||||
# Agent Note: Route credentials - DeepSeek model routes publish the credential consumers reuse
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-11-10-llm-route-credential-seam.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
Several packages shared one DeepSeek credential without an owner. `@deepseek-ai/dsh-llm-deepseek`, the protocol transport, exported helpers that read `ctx.credentials`, the launch environment, and `ctx.deepseekAccount`, so the transport depended on both credential services although it only sends the headers a route gives it. The two route plugins resolved their credentials through those helpers and threw their own missing-credential failures from inside `resolveAuth`. The Search and Fetch API providers re-derived each route's base URL and key reference from the Loader entry of the route package with that package's own config resolver, and Messages search hard-coded the account route id, so both web packages depended on `llm-deepseek`, on both route plugins, and on the Loader. The account service, which sits below every consumer, owned Agent cancellation after sign-out and lived in the `credentials/` group beside the credential store it only uses. A change to how one route authenticates touched the transport, both web providers, and their tests.
|
||||
|
||||
## Decision
|
||||
|
||||
`@deepseek-ai/dsh-llm` owns the Service Definition. `LlmAdapter.providerCredential(provider)` publishes a `ProviderCredential`: the route's `kind` (merge-extensible, with `api-key` and `account` declared), its resolved `baseURL`, an optional credential `reference` for diagnostics, `configured(endpoint)` for presence checks that neither validate the credential nor contact the destination, and `resolve(endpoint, signal)` returning a `ProviderCredentialGrant` with the protocol `headers`, the bare `value` for destinations that render it differently, an optional `reject()` for HTTP 401, and an optional `revoked` signal that aborts when the owner withdraws the credential while requests carry it. `LlmRuntime.providerCredential(provider)` forwards to the owning adapter; an unregistered route answers `undefined`, and a route whose configuration does not resolve propagates the adapter's failure. The adapter reads one configuration generation per call, as it does per model request.
|
||||
|
||||
`@deepseek-ai/dsh-llm-deepseek` reads no credential. `DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` returns the grant or `undefined`; `missingCredential(connection, provider)` names the failure of a request without one, `MISSING_CREDENTIAL` by default; `credential` declares the published kind, reference, and presence check. The transport runs each model request and its file operations under the grant's `revoked` signal and hands the resulting failure to the provider's failure callback, which names it. The listing cache scopes by endpoint and a hash of the credential headers.
|
||||
|
||||
The route plugins own credentials. `llm-deepseek-api-key` reads its key through `resolveCredentialRef` and `credentialRefConfigured`, new in `@deepseek-ai/dsh-credentials`, which treat a mounted credentials service as authoritative and read the launch environment only without one; it publishes kind `api-key` with the `apiKeyEnv` reference and releases the key only for destinations under the origin of its base URL. `llm-deepseek-account` reads `ctx.deepseekAccount.resolveRequestCredential(endpoint)`, maps HTTP 401 to `ACCOUNT_TOKEN_INVALID` and quota failures to `ACCOUNT_QUOTA`, fails without a credential as `ACCOUNT_SIGN_IN_REQUIRED`, publishes kind `account`, and owns the sign-out policy: it cancels its running Agents on `deepseek-account/signed-out` and registers a running-task report with the account service. A request in flight at sign-out ends with its grant's `revoked` signal and fails as `ACCOUNT_SIGN_IN_REQUIRED`, and its failure callback cancels the same Agents, so a request that outlives the plugin still ends its turn with the signed-out cause.
|
||||
|
||||
`@deepseek-ai/dsh-deepseek-account` releases request credentials. `resolveRequestCredential(url)` returns the `x-dsh-auth-token` header, the bare token, a `reject()` that removes the grant while it still matches and contains storage failures, and a `revoked` signal the service aborts at each sign-out after the `deepseek-account/signed-out` listeners have returned; `registerRunningTaskReport(report)` feeds `hasRunningAccountTasks()`. The service inspects no Agents and depends on neither `dsh-agent` nor `dsh-llm`. The package lives in the `packages/account/` group under its unchanged name.
|
||||
|
||||
The web providers consume publications. `web-deepseek-api` builds each operation's ordered sources from `ctx.llm.providerCredential('deepseek-official')` and `providerCredential('deepseek-account')`: a route source sends an `api-key` grant's value as a bearer token and any other kind's headers unchanged, and invalidates through the grant's `reject()`. Under each route id it accepts only the kind that route publishes, `api-key` as `deepseek-official` and `account` as `deepseek-account`, so billing by route id never sends the other kind. Without the API-key route it reads `DEEPSEEK_API_KEY` through the reference helpers; without the account route it asks the account service for the origin `DEEPSEEK_BASE_URL` names. `web-search-deepseek` uses the account credential of the initiating Session's route when that route publishes kind `account` and the search endpoint has the origin of the route's base URL, and the reference helpers otherwise; it does not request an account credential published for another origin. Both web consumers contain a failed `reject()`, so the HTTP rejection stays the reported error for every credential kind. Both run their request under the grant's `revoked` signal and report a request it ended as `WEB_PROVIDER_ERROR` with sign-in guidance, keeping `WEB_ABORTED` for the caller's cancellation. Neither web package depends on `llm-deepseek`, the route plugins, or the Loader, and `web-search-deepseek` no longer depends on the account service.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**A `deepseek-auth` package holding the credential seam.** The seam needs a Service Definition only, no Cordis service, and that one Definition role belongs beside `LlmAdapter`; a package for an interface adds a dependency without an owner of behavior.
|
||||
|
||||
**A credential fingerprint in the published credential.** Consumers only send requests, so they need headers and a value; cache scoping by credential is the adapter's own concern, which the listing cache meets by hashing the headers it sends.
|
||||
|
||||
**A `credentials-env` provider instead of reference helpers.** A provider that reads the environment would change which composition is authoritative for every consumer; the helpers keep the launch-environment fallback local to the consumers that need it, so such a provider remains an independent option.
|
||||
|
||||
**The account service's inference origin for the web fallback without the account route.** Routing that fallback through `DEEPSEEK_BASE_URL` keeps the keyless billing snapshot and every documented deployment unchanged; the account service still refuses every origin but its own.
|
||||
|
||||
**Moving the account package into `identity/`.** That group defines anonymous, user-independent ids; a signed-in account is the opposite, so it gets a group of its own.
|
||||
|
||||
**Keeping the route plugin's sign-out listener until its tasks end.** Unloading the route then waits for a running turn: disabling the plugin blocks, and every other settings write queues behind that reload, for as long as the turn runs.
|
||||
|
||||
**Cancelling the route's tasks when the route unloads.** A configuration reload or a plugin update would stop turns that no sign-out touched.
|
||||
|
||||
**Returning the sign-out policy to the account service.** The service would again inspect Agents and know route ids, the dependencies this decision removes.
|
||||
|
||||
**Keeping the route's listener or report registered after its plugin unloads.** A registration that outlives the plugin that made it breaks the rule that registrations are effects of their owner, and leaves code of an unloaded plugin running in another scope for as long as the task runs.
|
||||
|
||||
## Consequences
|
||||
|
||||
Adding a credential kind, or a consumer of a route's credential, touches one route plugin or one consumer, not the transport. The transport, the web providers, and the account service lose their cross-dependencies, and `hasRunningAccountTasks()` depends on a registered report rather than on Agents the account service can see. Consumers that construct `DeepSeekRequestAuth` supply a `value`; the removed helpers and the route plugins' config exports are gone, and the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.md) lists the replacements. A route's configuration failure reaches web consumers through `providerCredential()` as a thrown error, which they report as `WEB_PROVIDER_MISCONFIGURED`.
|
||||
|
||||
A sign-out ends the in-flight model, Files, Search, and Fetch requests that carry the account token, including requests no Agent turn owns, such as a model request outside a turn or an account-billed web search; the account listing request keeps its own deadline. The signal supplements the Agent cancellation of the [account sign-out decision](2026-09-17-account-provider-signout.md), which rejected a login-level signal as a duplicate of that chain: the chain reaches a request only through a mounted listener and a running Agent turn. While the account route is disabled, a task it started that still runs is not reported to the sign-out confirmation, and a sign-out ends it only through a model request in flight. A credential released by an account service that has since been replaced is not withdrawn by the replacement's sign-out; the route plugin's listener still cancels Agent turns.
|
||||
@@ -1,47 +0,0 @@
|
||||
# Agent Note: Route credentials - DeepSeek model routes publish the credential consumers reuse
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-11-10-llm-route-credential-seam.md) | 中文
|
||||
|
||||
## 问题
|
||||
|
||||
多个包共用同一份 DeepSeek 凭据,却没有所有者。协议传输层 `@deepseek-ai/dsh-llm-deepseek` 导出读取 `ctx.credentials`、启动环境和 `ctx.deepseekAccount` 的辅助函数,因此尽管传输层只发送路由交给它的请求头,它仍依赖两个凭据服务。两个路由插件通过这些函数解析凭据,并在 `resolveAuth` 内部抛出各自的凭据缺失错误。Search 与 Fetch API 提供方用路由包自己的配置解析函数,从路由包的 Loader 条目重新推导每条路由的基础地址和密钥引用,Messages 搜索则硬编码账号路由 id,因此两个 Web 包都依赖 `llm-deepseek`、两个路由插件和 Loader。位于所有消费方之下的账号服务拥有退登后的 Agent 取消逻辑,并和它仅仅使用的凭据库一起放在 `credentials/` 组。改变一条路由的鉴权方式要同时触及传输层、两个 Web 提供方及其测试。
|
||||
|
||||
## 决策
|
||||
|
||||
`@deepseek-ai/dsh-llm` 拥有 Service Definition。`LlmAdapter.providerCredential(provider)` 发布一个 `ProviderCredential`:路由的 `kind`(可合并扩展,已声明 `api-key` 与 `account`)、解析后的 `baseURL`、用于诊断的可选凭据 `reference`、不校验凭据、不联系目的地的存在性检查 `configured(endpoint)`,以及返回 `ProviderCredentialGrant` 的 `resolve(endpoint, signal)`;授权包含协议 `headers`、供以其他方式呈现凭据的目标使用的裸 `value`、可选的 HTTP 401 `reject()`,以及可选的 `revoked` 信号;所有者在请求仍携带凭据时撤回凭据,该信号即中止。`LlmRuntime.providerCredential(provider)` 转发给拥有该路由的适配器;未注册的路由回答 `undefined`,配置无法解析的路由则传播适配器的失败。适配器每次调用读取一代配置,与每次模型请求相同。
|
||||
|
||||
`@deepseek-ai/dsh-llm-deepseek` 不读取任何凭据。`DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` 返回授权或 `undefined`;`missingCredential(connection, provider)` 命名没有凭据时请求的失败,默认为 `MISSING_CREDENTIAL`;`credential` 声明发布的种类、引用和存在性检查。传输层让每次模型请求及其文件操作受授权的 `revoked` 信号约束,并把由此产生的失败交给提供方的失败回调命名。列表缓存以端点和凭据请求头的哈希划分作用域。
|
||||
|
||||
路由插件拥有凭据。`llm-deepseek-api-key` 通过 `@deepseek-ai/dsh-credentials` 新增的 `resolveCredentialRef` 和 `credentialRefConfigured` 读取密钥,二者把已挂载的凭据服务视为权威,仅在没有该服务时读取启动环境;它发布种类 `api-key` 并附带 `apiKeyEnv` 引用,且只对其基础地址所在 origin 下的目的地释放密钥。`llm-deepseek-account` 读取 `ctx.deepseekAccount.resolveRequestCredential(endpoint)`,把 HTTP 401 映射为 `ACCOUNT_TOKEN_INVALID`、配额失败映射为 `ACCOUNT_QUOTA`,没有凭据时以 `ACCOUNT_SIGN_IN_REQUIRED` 失败,发布种类 `account`,并拥有退登策略:在 `deepseek-account/signed-out` 时取消其运行中的 Agent,并向账号服务注册运行中任务报告。退登时在途的请求随其授权的 `revoked` 信号结束,以 `ACCOUNT_SIGN_IN_REQUIRED` 失败;它的失败回调会取消同一批 Agent,因此比插件存活更久的请求仍会以退登原因结束其回合。
|
||||
|
||||
`@deepseek-ai/dsh-deepseek-account` 释放请求凭据。`resolveRequestCredential(url)` 返回 `x-dsh-auth-token` 请求头、裸 token、`reject()` 和 `revoked` 信号;`reject()` 仅在授权仍一致时删除它并隔离存储失败,`revoked` 由服务在每次退登时、`deepseek-account/signed-out` 的监听器返回之后中止。`registerRunningTaskReport(report)` 为 `hasRunningAccountTasks()` 提供答案。该服务不检查任何 Agent,也不依赖 `dsh-agent` 或 `dsh-llm`。包以不变的名字位于 `packages/account/` 组。
|
||||
|
||||
Web 提供方消费这些发布的凭据。`web-deepseek-api` 从 `ctx.llm.providerCredential('deepseek-official')` 和 `providerCredential('deepseek-account')` 构造每次操作的有序凭据来源:路由来源把 `api-key` 授权的值作为 Bearer 令牌发送,其他种类的请求头原样发送,并通过授权的 `reject()` 作废。每个路由 id 下只接受该路由发布的种类(`deepseek-official` 下为 `api-key`,`deepseek-account` 下为 `account`),因此按路由 id 计费不会发出另一种凭据。没有 API 密钥路由时,它通过引用函数读取 `DEEPSEEK_API_KEY`;没有账号路由时,它向账号服务索取发往 `DEEPSEEK_BASE_URL` 所指 origin 的凭据。`web-search-deepseek` 在发起会话的路由发布 `account` 种类且搜索端点与该路由的基础地址同源时使用其账号凭据,否则使用引用函数;为其他 origin 发布的账号凭据不会被索取。两个 Web 消费方都会隔离失败的 `reject()`,因此对任何凭据种类,报告的都是 HTTP 拒绝。二者都让请求受授权的 `revoked` 信号约束,把被它结束的请求报告为带登录指引的 `WEB_PROVIDER_ERROR`,`WEB_ABORTED` 仍只表示调用方取消。两个 Web 包都不再依赖 `llm-deepseek`、路由插件或 Loader,`web-search-deepseek` 也不再依赖账号服务。
|
||||
|
||||
## 考虑过的替代方案
|
||||
|
||||
**用一个 `deepseek-auth` 包承载凭据 seam。** 该 seam 只需要 Service Definition,不需要 Cordis 服务,而这一个 Definition 角色应与 `LlmAdapter` 放在一起;为一个接口建包只会增加一个没有行为所有者的依赖。
|
||||
|
||||
**在发布的凭据中加入凭据指纹。** 消费方只负责发送请求,因此只需要请求头和值;按凭据划分缓存作用域是适配器自己的事,列表缓存通过哈希它发送的请求头即可满足。
|
||||
|
||||
**用 `credentials-env` 提供方代替引用函数。** 读取环境的提供方会改变每个消费方眼中哪个组合具有权威性;引用函数把启动环境后备保留在需要它的消费方本地,使这样的提供方仍是独立的选项。
|
||||
|
||||
**没有账号路由时的 Web 后备使用账号服务的推理 origin。** 让该后备经由 `DEEPSEEK_BASE_URL` 可保持无密钥计费快照和所有已记录部署不变;账号服务仍拒绝除自身 origin 以外的一切来源。
|
||||
|
||||
**把账号包并入 `identity/`。** 该组定义匿名、不识别用户的 id;已登录账号与之相反,因此单独成组。
|
||||
|
||||
**让路由插件的退登监听保留到其任务结束。** 这样卸载路由要等待运行中的回合:停用插件会被阻塞,其他设置写入也排在这次重载之后,直到回合结束。
|
||||
|
||||
**路由卸载时取消其任务。** 配置重载或插件更新会停掉与退登无关的回合。
|
||||
|
||||
**把退登策略放回账号服务。** 账号服务将重新检查 Agent 并认识路由 id,而这正是本决策去掉的依赖。
|
||||
|
||||
**插件卸载后仍保留路由的监听或报告注册。** 比注册它的插件存活更久的注册违反“注册是其所有者的 effect”这一规则,并让已卸载插件的代码在任务运行期间留在其他作用域里。
|
||||
|
||||
## 后果
|
||||
|
||||
新增凭据种类或路由凭据的消费方只触及一个路由插件或一个消费方,而不是传输层。传输层、Web 提供方和账号服务之间的交叉依赖消失,`hasRunningAccountTasks()` 依赖注册的报告而非账号服务可见的 Agent。构造 `DeepSeekRequestAuth` 的消费方需提供 `value`;被移除的辅助函数和路由插件的配置导出不复存在,[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.3/llm-route-credential/guide.zh.md)列出了替代方案。路由的配置失败通过 `providerCredential()` 以抛出错误的形式到达 Web 消费方,它们将其报告为 `WEB_PROVIDER_MISCONFIGURED`。
|
||||
|
||||
退登会结束携带账号 token 的在途模型、Files、Search 与 Fetch 请求,包括不属于任何 Agent 回合的请求,例如回合之外的模型请求或按账号计费的 Web 搜索;账号列表请求仍只受自身期限约束。该信号是对[账号退登决策](2026-09-17-account-provider-signout.zh.md)中 Agent 取消链路的补充;那份决策以重复该链路为由否决了登录级信号,而该链路只能经由已挂载的监听和运行中的 Agent 回合到达请求。账号路由被停用期间,它此前启动且仍在运行的任务不会报告给退登确认,退登也只能通过在途的模型请求结束它。已被替换的账号服务释放的凭据不会被替换后服务的退登撤回;路由插件的监听仍会取消 Agent 回合。
|
||||
@@ -0,0 +1,19 @@
|
||||
# Bilingual-pair consistency record for 2026-11-13-ptc-output-truncation.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-11-13-ptc-output-truncation.md
|
||||
/agent-note-ptc-output-truncation-without-execution-cancellation:
|
||||
en: 781fba10ab5fcd45
|
||||
zh: 88276a5a9cdf8c19
|
||||
/agent-note-ptc-output-truncation-without-execution-cancellation/problem:
|
||||
en: a6430b7910bebaa2
|
||||
zh: dff6c3553e22283e
|
||||
/agent-note-ptc-output-truncation-without-execution-cancellation/decision:
|
||||
en: b24a08b0037adab4
|
||||
zh: 92fb390a0e460ba5
|
||||
/agent-note-ptc-output-truncation-without-execution-cancellation/alternatives-considered:
|
||||
en: 717295afe374b2e5
|
||||
zh: cf4fd1365169f9e3
|
||||
/agent-note-ptc-output-truncation-without-execution-cancellation/consequences:
|
||||
en: 420e2556a878b48a
|
||||
zh: bff5f63189562d57
|
||||
@@ -0,0 +1,25 @@
|
||||
# Agent Note: PTC output truncation without execution cancellation
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-11-13-ptc-output-truncation.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
Stopping a program because its logs exceed the output budget can interrupt a sequence of external actions. Earlier effects remain, but the caller cannot tell which later actions ran. Repeating the program to obtain less output can repeat those effects. A full log budget can also hide a subsequent exception by replacing its kind with an output-limit failure.
|
||||
|
||||
## Decision
|
||||
|
||||
Captured output has bounded retention. Exhaustion preserves an ordered prefix, discards subsequent output and sets `outputTruncated`; it does not cancel execution or discard retained variables. Existing deadlines, cancellation, heap limits and control-message limits still apply. Finalization prioritizes the required completion value or bounded failure diagnostic within the combined payload budget. Truncated diagnostics preserve their failure kind. Required completion values remain lossless and fail if they cannot fit.
|
||||
|
||||
This supersedes only captured-output termination and diagnostic reclassification in [typed tool returns](../feature/2026-07-20-ptc-typed-tool-returns.md), and overflow-driven state disposal in [retained PTC](2026-09-23-best-effort-persistent-ptc.md). Those records still own lossless values and retained-state lifetime; [explicit output](2026-11-09-explicit-ptc-output.md) still owns inspection and image projection.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**Terminate on output exhaustion.** It limits output production earlier, but turns a presentation limit into interrupted external work without rollback.
|
||||
|
||||
**Return success with a truncated completion value.** It violates the caller's requirement for complete JSON data. Only captured output and diagnostic text may be shortened.
|
||||
|
||||
## Consequences
|
||||
|
||||
Successful truncated runs remain successful tool results. Callers inspect current state for missing information instead of replaying completed actions. Output suppression does not bound allocations in argument evaluation or native code; existing resource controls retain that responsibility. Tests cover subsequent actions, retained variables, initialization, ordered images, byte limits and later exceptions, deadlines and cancellation.
|
||||
@@ -0,0 +1,25 @@
|
||||
# Agent Note: PTC 输出截断不取消执行
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-11-13-ptc-output-truncation.md) | 中文
|
||||
|
||||
## 问题
|
||||
|
||||
因日志超出输出预算而停止程序,可能打断一系列外部动作。此前的效果仍然保留,但调用方无法判断后续哪些动作已经执行。为了减少输出而重跑程序,可能重复这些效果。日志预算耗尽还可能使后续异常被替换成输出超限失败,掩盖真实类型。
|
||||
|
||||
## 决策
|
||||
|
||||
捕获输出采用有界保留。预算耗尽时保留有序前缀,丢弃后续输出并设置 `outputTruncated`,但不取消执行或丢弃保留变量。原有截止时间、取消、堆限制和控制消息限制继续生效。最终结算在组合负载预算内优先保留必需完成值或有界失败诊断。截断诊断保留原来的失败类型。必需完成值保持无损,无法容纳时仍然失败。
|
||||
|
||||
本决策只取代[类型化工具返回值](../feature/2026-07-20-ptc-typed-tool-returns.zh.md)中的捕获输出超限终止和诊断重新分类,以及[保留状态 PTC](2026-09-23-best-effort-persistent-ptc.zh.md)中的超限清空状态规则。这些记录仍负责无损值和保留状态生命周期;[显式输出](2026-11-09-explicit-ptc-output.zh.md)仍负责检查展示与图片投影。
|
||||
|
||||
## 考虑过的替代方案
|
||||
|
||||
**输出耗尽时终止。** 能更早限制输出生产,但将展示限制变成没有回滚的外部工作中断。
|
||||
|
||||
**截断完成值后返回成功。** 违反调用方对完整 JSON 数据的要求。只有捕获输出和诊断文本可以缩短。
|
||||
|
||||
## 后果
|
||||
|
||||
成功但输出截断的执行仍是成功工具结果。调用方读取当前状态以获取遗漏信息,不重放已完成动作。输出抑制不限制参数求值或原生代码中的分配,这仍由现有资源控制负责。测试覆盖后续动作、保留变量、初始化、有序图片、字节上限以及后续异常、截止到期和取消。
|
||||
@@ -0,0 +1,46 @@
|
||||
# Bilingual-pair consistency record for 2026-11-15-client-config-sync.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-11-15-client-config-sync.md
|
||||
/agent-note-browser-plugin-configuration-sync:
|
||||
en: 92fb1b35ccd50f2b
|
||||
zh: 732f665dd12d0feb
|
||||
/agent-note-browser-plugin-configuration-sync/problem:
|
||||
en: bad5854f1a21feb2
|
||||
zh: df9f2c62aa7f1c8c
|
||||
/agent-note-browser-plugin-configuration-sync/decision:
|
||||
en: a15c7c13f167e5ac
|
||||
zh: a15c7c13f167e5ac
|
||||
/agent-note-browser-plugin-configuration-sync/decision/design-principles:
|
||||
en: 1678ec9cbc83e49e
|
||||
zh: 1548e5e08774de78
|
||||
/agent-note-browser-plugin-configuration-sync/decision/plugin-authoring:
|
||||
en: 201c029071cc3812
|
||||
zh: 03a7245772a95b54
|
||||
/agent-note-browser-plugin-configuration-sync/decision/ownership:
|
||||
en: cb3e66c7d61b706b
|
||||
zh: a255f85e9c411db9
|
||||
/agent-note-browser-plugin-configuration-sync/decision/ordering:
|
||||
en: 5de9319764101262
|
||||
zh: 4a5c5c417cf36d8e
|
||||
/agent-note-browser-plugin-configuration-sync/decision/push-order:
|
||||
en: 5714f023a439e068
|
||||
zh: 5d5ec5d5847fb2d4
|
||||
/agent-note-browser-plugin-configuration-sync/decision/delivery:
|
||||
en: 9b8e644702108ef6
|
||||
zh: 0d4f551c6007e989
|
||||
/agent-note-browser-plugin-configuration-sync/decision/push-channel:
|
||||
en: 5596a32a26042882
|
||||
zh: fbeae944656b39ac
|
||||
/agent-note-browser-plugin-configuration-sync/decision/scope-existing-uses-the-mechanism-can-absorb:
|
||||
en: 79b8c68583897e07
|
||||
zh: 15a0f33fa494ec9a
|
||||
/agent-note-browser-plugin-configuration-sync/verification:
|
||||
en: b7ab56a86ef63b85
|
||||
zh: b5fc8aae610659fc
|
||||
/agent-note-browser-plugin-configuration-sync/alternatives-considered:
|
||||
en: 15ae5cd610d7208c
|
||||
zh: 5f25271e318dbfe1
|
||||
/agent-note-browser-plugin-configuration-sync/consequences:
|
||||
en: f85e3339246a9f84
|
||||
zh: 11cbff9deeb78f88
|
||||
@@ -0,0 +1,215 @@
|
||||
# Agent Note: Browser plugin configuration sync
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-11-15-client-config-sync.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
Host plugin configuration updates live: when only volatile fields change, the Loader commits the references in place and emits `loader/volatile-update` without remounting the plugin. The browser has no matching path:
|
||||
|
||||
| Symptom | Cause |
|
||||
|---|---|
|
||||
| A browser plugin's `apply(ctx, config)` always receives an empty config | The page Loader creates entries with `name` only ([entries.ts](../../../../packages/client/modules/src/client/entries.ts)), so the row's `config` in cordis.yml never reaches the browser |
|
||||
| Packages that need Host configuration each work around it | Some write a page global through `webserver/index-inject`, which takes effect only at page load; others read runtime values through the `configForms` settings mirror |
|
||||
| The plugin-graph push channel does not meet the rules | `/plugins/events` is an `auth: 'anonymous'` route; the browser has two readers, `EventSource` and `__DSH_TRANSPORT__.fetch`, the latter never reconnects; the frame sequence has no one-complete-snapshot-per-generation rule |
|
||||
|
||||
## Decision
|
||||
|
||||
### Design principles
|
||||
|
||||
| Principle | Content |
|
||||
|---|---|
|
||||
| One Config | A plugin has one configuration type, in the package's `src/types.ts`, shared by the Host and Client faces; the schema lives only on the Host face. The browser exports no `Config` and validates no configuration |
|
||||
| Volatile only | The browser receives only the fields the Host schema declares volatile |
|
||||
| Secrets removed | `role('secret')` positions inside volatile fields, including inside volatile objects, arrays, and dictionaries, are removed on the Host and never sent. The Host face of `client/modules` implements this itself, without depending on `@deepseek-ai/dsh-settings` |
|
||||
| Plugins support live updates | A synced configuration change never remounts a browser plugin; the plugin reads references at operation time, or hands them to components as observable sources |
|
||||
| Equal values do nothing | Every layer compares with deep equality; equal values push, write, and notify nothing, and a reconnect snapshot equal to the current values causes no refresh |
|
||||
| What is not synced | Host-only ordinary fields, secrets, and per-browser preferences stay out of this path; values the page HTML pre-injects to avoid a first-paint flash, such as the theme, stay as they are |
|
||||
|
||||
### Plugin authoring
|
||||
|
||||
```ts ignore-check
|
||||
// src/types.ts — shared by both faces; types only
|
||||
import type { Volatile } from '@deepseek-ai/cordis'
|
||||
|
||||
/** Plugin configuration shared by the Host and Client faces. */
|
||||
export interface Config {
|
||||
/** Host-only ordinary field; never synced. */
|
||||
cacheDir: string
|
||||
/** Synced to the browser. */
|
||||
interactiveByDefault: Volatile<boolean>
|
||||
/** Synced as one value. */
|
||||
office: Volatile<{ maxBytes: number }>
|
||||
/** Volatile but `role('secret')`: stripped on the Host; reads as undefined in the browser. */
|
||||
apiKey?: Volatile<string>
|
||||
}
|
||||
```
|
||||
|
||||
```ts ignore-check
|
||||
// src/index.ts — Host face; the only schema
|
||||
export const Config: z<Config> = z.object({
|
||||
cacheDir: z.string().default('.cache'),
|
||||
interactiveByDefault: z.boolean().default(false).volatile(),
|
||||
office: z.object({ maxBytes: z.natural().default(8 << 20) }).volatile(),
|
||||
apiKey: z.string().role('secret').volatile(),
|
||||
})
|
||||
```
|
||||
|
||||
```ts ignore-check
|
||||
// src/client/index.ts — Client face; no Config export
|
||||
import type { SyncedConfig } from '@deepseek-ai/dsh-client-config/types'
|
||||
import type { Config } from '../types.ts'
|
||||
|
||||
export function apply(ctx: Context, config: SyncedConfig<Config>): void {
|
||||
// Every synced field may read undefined; the plugin decides what an absent value means.
|
||||
const tooLarge = (bytes: number) => bytes > (config.office.get()?.maxBytes ?? Number.POSITIVE_INFINITY)
|
||||
ctx.slots.register({
|
||||
name: 'demo.body',
|
||||
inject: (): DemoBodyInjected => ({ hooks: { interactiveByDefault: config.interactiveByDefault }, tooLarge }),
|
||||
}, DemoBody)
|
||||
}
|
||||
```
|
||||
|
||||
```tsx ignore-check
|
||||
// src/client/DemoBody.tsx — the renderer binds the injected source as useInteractiveByDefault
|
||||
export function DemoBody({ useInteractiveByDefault, tooLarge }: InjectFace<DemoBodyInjected>) {
|
||||
const interactive = useInteractiveByDefault(value => value)
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
Types exported by the types-only package `@deepseek-ai/dsh-client-config/types`, which plugins depend on instead of the bootstrap Client Modules package; Client Modules implements them:
|
||||
|
||||
```ts ignore-check
|
||||
/** One synced field: Host-aligned `get()`, and directly an observable source for an injected hook. */
|
||||
export interface SyncedConfigRef<T> extends Volatile<T>, ObservableSnapshot<VolatileSnapshot<T>> {}
|
||||
|
||||
/** The Volatile fields of the shared Config type. */
|
||||
export type SyncedConfig<C> = {
|
||||
readonly [K in keyof C as NonNullable<C[K]> extends Volatile<unknown> ? K : never]-?:
|
||||
NonNullable<C[K]> extends Volatile<infer V> ? SyncedConfigRef<V | undefined> : never
|
||||
}
|
||||
```
|
||||
|
||||
`get` and `getSnapshot` return the same frozen snapshot: `get` matches how the Host reads a volatile reference, and `getSnapshot` with `subscribe` satisfy `ObservableSnapshot`, so the reference itself goes into `hooks` without renderer adaptation. The interface has no write operation; the implementing class stays private to Client Modules.
|
||||
|
||||
Components follow the [client rules](../../../../packages/client/AGENTS.md): the plugin injects field-level sources in a slot inject's `hooks` compartment, and the component reads them only through the renderer-bound `use<Name>`, never touching the source.
|
||||
|
||||
### Ownership
|
||||
|
||||
Runtime ownership stays in `client/modules`; the only new package is the types-only `@deepseek-ai/dsh-client-config` (empty `apply` on both faces). `client/modules` already follows Loader entries, composes the plugin graph, and creates entries in the browser; synced configuration is an input of an entry, so it owns this too:
|
||||
|
||||
| Face | Responsibility |
|
||||
|---|---|
|
||||
| Host (inside the `clientModules` service) | Listens to `loader/volatile-update` on each graph row's own plugin `ctx`; recomputes after the plugin fiber becomes ACTIVE (`internal/status`) or after entry reconciliation; reads the schema's top-level volatile field values from `fiber.effectiveConfig`, removes `role('secret')` positions by the schema, and compares the row's values with the last ones by deep equality, writing them into the graph row's `config` and republishing the graph only when they differ. A change of synced values alone rebuilds no combo artifact |
|
||||
| Client (inside the entry controller) | Keeps the latest synced values of every package that has appeared in the graph; each plugin activation receives a new configuration object (an empty object while the row has no values), as each Host fiber activation resolves new references; on each graph it compares fields as JSON and writes the changes into the current activation's object |
|
||||
| Client (`ctx.config` service) | Read-only: `resolveConfigByPackage<C>(packageName)` returns the object a package's current activation received, for reading another plugin's configuration; the object changes when the plugin is replaced, and the result is `undefined` while no activation runs |
|
||||
|
||||
Client constraints:
|
||||
|
||||
| Constraint | Content |
|
||||
|---|---|
|
||||
| Lazy creation | A field reference is created on first access and cached |
|
||||
| Instance identity | One object per activation, living as long as that activation; code replacement and a re-added row each produce a new object holding the latest values |
|
||||
| No `entry.update` | Synced configuration never takes the Loader update path, so it never triggers a remount, and the browser emits no `loader/volatile-update`; changes notify only through the field references' `subscribe` |
|
||||
| Atomic publication | One graph update sets every changed field before notifying their subscribers, as the Host commits every reference before emitting its event |
|
||||
| No value validation | The authoritative Host schema has already validated the values; the browser checks only that a row's `config` is an object when it parses the graph |
|
||||
| Delivery | The entry controller registers a prepended `internal/config` listener on the page Loader that returns the synced object for managed entries that export no schema; the Loader's interpolation runs inside it and cannot copy the object. A Client face that exports its own `Config` schema keeps Cordis's ordinary configuration, and fails to activate if its row also carries synced values |
|
||||
|
||||
### Ordering
|
||||
|
||||
Host consistency comes from two facts: the schema and the code belong to one module, and activation resolves the raw configuration with that schema; code reloads and configuration reloads run serially through Host hot reload, and only an ACTIVE instance receives volatile changes in place. The Client aligns with the second:
|
||||
|
||||
| Situation | Host | Client |
|
||||
|---|---|---|
|
||||
| Configuration changes while the instance runs | Commits every reference in place, then notifies | Writes into the current activation's object in place, notifying after every field is written |
|
||||
| Configuration changes while a replacement is queued and teardown has not begun | The instance is still ACTIVE and updates in place | Same |
|
||||
| Configuration changes after teardown begins | A non-ACTIVE instance no longer updates in place; the new instance resolves the latest configuration | Teardown releases the old activation, whose object receives no further writes; the new activation starts with the latest values |
|
||||
| The row is removed | The instance is destroyed and receives no configuration | Removal releases the activation; nothing is written while the row is absent from the graph |
|
||||
| The Host-side plugin instance is not ACTIVE | Not applicable | Values follow the Host's configuration as the Host plugin's own effective Config does, including when activation fails; an instance that has not activated yet publishes the values its own schema resolves from its raw configuration |
|
||||
|
||||
A plugin instance that has not activated yet (a new install, an upgrade, a code reload) publishes the values its own schema resolves from its raw configuration, so the graph frame that announces new browser code already carries values of the matching Host schema. Only an incompatible schema change during development (a renamed or removed field) can briefly give old browser code values it does not expect, until the rebuilt bundle arrives.
|
||||
|
||||
### Push order
|
||||
|
||||
When a Host plugin updates its configuration and then pushes other data to the browser, the browser should receive the configuration first. The order is ensured only at the mechanism level, through the steps below; it is not guaranteed in practice. Each stream's source takes its own number of asynchronous steps between a Host event and the item reaching the Gateway write queue, so a stream with fewer steps can be written first even when no plugin adds a wait of its own. Plugins must not rely on this order:
|
||||
|
||||
| Step | Approach |
|
||||
|---|---|
|
||||
| Host enqueue | `clientModules` registers its `loader/volatile-update` listener on the plugin ctx with prepend, so it puts the new graph into every follower queue synchronously before the plugin's own listeners run |
|
||||
| pluginEvents stream | `follow` yields increments from its own generator, with no delegated generator adding a step |
|
||||
| Gateway write | Each connection has one write queue; each stream's items enter it when the source produces them and are written in queue order, without waiting for the previous write to complete; when the queued bytes exceed `streamOutboxBytes`, the whole connection pauses reading every source |
|
||||
| Browser handling | WebSocket messages are handled in arrival order, and configuration writes complete synchronously while a graph frame is handled |
|
||||
|
||||
### Delivery
|
||||
|
||||
First-render values travel in the `__DSH_BOOT__` graph rows; later values travel in the plugin-events stream's `baseline` and `graph` frames, with no separate configuration frame. `@deepseek-ai/dsh-client-modules/types` exports the plugin graph's wire types. Only the owner receives configured values; every other Peer, such as a LiveShare viewer, receives in the boot graph and in every plugin-events frame the values each plugin's schema resolves from an empty Config, so the Host schema remains the only source of defaults and the owner's configured values stay on the Host; a row whose schema rejects an empty Config carries no values there. Remote access policies decide only whether a Peer may follow the graph.
|
||||
|
||||
### Push channel
|
||||
|
||||
`/plugins/events` becomes the authenticated Typert Remote stream `pluginEvents/follow`, which the browser consumes with `RemoteSnapshotStream`:
|
||||
|
||||
| Frame | Content | Browser handling |
|
||||
|---|---|---|
|
||||
| `baseline` | The complete plugin graph, including each row's synced configuration | Entry reconciliation |
|
||||
| `graph` | The complete plugin graph after a structural or synced-configuration change | Entry reconciliation |
|
||||
| `rebuilt` | `{ id, rev }`, one package's code rebuild | Entry code replacement |
|
||||
|
||||
| Item | Content |
|
||||
|---|---|
|
||||
| Authentication | Ordinary Remote gateway authentication and authorization; the anonymous `/plugins/events` route is removed, and the browser face opens the stream while Remote access allows `pluginEvents/follow` |
|
||||
| Transport | Both the `EventSource` and the `__DSH_TRANSPORT__.fetch` readers are removed; shells such as liveshare and webworker connect through the Remote carrier Connection already provides |
|
||||
| Reconnection | `RemoteStream` owns it; every generation starts with `baseline`, and the new snapshot covers anything missed while disconnected |
|
||||
| Desktop | Shares the same Remote stream with Web |
|
||||
| Ownership | The `client/hmr` Host face owns the `pluginEvents` Remote service, in the same package as the bundle stat poll, and declares no `ctx` type merge; `client/modules` is a zero-dependency bootstrap package and takes no typert or gateway dependency |
|
||||
| Browser dependencies | The browser face `$mount`s its own generated `pluginEvents` namespace rather than through the `api-remotes` assembly, so `api-remotes` can be hot-replaced independently; the required dependencies are `modules`, `remote` (the gateway Client face, over Connection), and `remoteAccess` |
|
||||
|
||||
### Scope: existing uses the mechanism can absorb
|
||||
|
||||
This Note migrates no existing use; the [migration Note](../../proposed/architecture/2026-11-15-client-config-sync-migration.md) owns the inventory and order. The mechanism can absorb page globals that deliver Host configuration through `webserver/index-inject`, plugins that read runtime values through `configForms`, and `Config` schemas declared only on a Client face that nothing can configure.
|
||||
|
||||
## Verification
|
||||
|
||||
The following hold and are covered by tests:
|
||||
|
||||
- A browser plugin's `apply` `config` holds the Host's current volatile values on first render; after a volatile field in `cordis.patch.yml` changes, the browser reference updates and subscribed components re-render, with neither the browser nor the Host plugin fiber remounted.
|
||||
- `role('secret')` values in the positions the projection removes, the same as the settings redaction, appear neither in the first-render injection nor in any pushed frame; a non-owner Peer receives only schema defaults, never configured values.
|
||||
- Host-only ordinary fields never appear in the browser.
|
||||
- A configuration reload with unchanged values, and the reconnect baseline after a Host restart, emit no `loader/volatile-update` and notify no subscriber.
|
||||
- No anonymous `/plugins/events` route exists; an unauthenticated request cannot obtain the plugin graph or configuration; after reconnection the browser state matches the Host.
|
||||
- After code hot reload the new activation receives a new `SyncedConfig` object holding the current values, and the old activation receives no new values once its teardown begins.
|
||||
- On the Host, the new graph frame enters the pluginEvents follower queues before the plugin's own `loader/volatile-update` listeners run; the order on the wire is not required.
|
||||
- Tests: unit tests for both faces of `client/modules` (removal, comparison, lazy creation, reference stability, listener registration and removal); a real composition test that boots a profile through the Loader, changes a patch, and asserts browser-visible values; the `client-plugin-live` and `client-config-sync` Web end-to-end tests, including reconnection after a transport restart.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
| Rejected | Reason |
|
||||
|---|---|
|
||||
| A separate browser `ClientConfig` schema | Two schemas drift; the Host schema already carries volatile declarations and validation |
|
||||
| Sending the whole configuration with secrets removed | Leaks ordinary fields such as Host paths and URLs to the browser |
|
||||
| Applying changes to browser entries through `entry.update({ config })` | The browser has no schema, so the Loader cannot tell volatile fields and only remounts |
|
||||
| Changing the vendored Loader to add a global volatile event | Requires a logged vendor modification; listening on each entry's own `ctx` suffices |
|
||||
| Placing the channel in `client/modules` | The bootstrap package would depend on typert and the gateway |
|
||||
| Mounting `pluginEvents` through `api-remotes` | A failed `api-remotes` replacement would cut the plugin update channel |
|
||||
| Declaring "replacement requires a page reload" for Connection and the gateway | Adds a manifest field and a UI branch; a page reload after a failed replacement is accepted |
|
||||
| A unified `useConfig` framework hook in the renderer | Adds a framework-level hook; manual `hooks` injection already serves components |
|
||||
| Reusing the projection and removal functions of `@deepseek-ai/dsh-settings` | The settings architecture will be adjusted after this mechanism, so no dependency yet |
|
||||
| References that are only `ObservableSnapshot` | Inconsistent with the Host's `get()` on volatile references |
|
||||
| One page-lifetime configuration object per package | An old instance being torn down during replacement would still receive new configuration, unlike the Host |
|
||||
| Changing the vendored Loader to emit a commit event for Host enqueue order | A prepended listener already suffices, with no vendor change |
|
||||
| A separate push channel for configuration | Duplicates the plugin-graph channel's authentication, reconnection, and snapshot semantics |
|
||||
| A separate `client/config` runtime package with a publicly writable configuration service | Any plugin could rewrite another plugin's configuration, and entries would have to wait for that service by package name |
|
||||
| Plugins importing the types from `@deepseek-ai/dsh-client-modules/types` | Couples every configured plugin to the bootstrap module-system package and exposes the implementing class |
|
||||
| Emitting `loader/volatile-update` in the browser too | The field references' `subscribe` suffices; the event requires reaching into Cordis's filter mechanism |
|
||||
|
||||
## Consequences
|
||||
|
||||
| Risk | Description |
|
||||
|---|---|
|
||||
| The channel depends on Connection | Plugin-graph sync depends on Connection and the gateway Client face. Hot-replacing them restarts this plugin and reopens the stream, reconciled by the new generation's baseline; if their new code fails to import or activate, the page receives no plugin updates until it reloads (accepted) |
|
||||
| Listeners registered on other plugins' `ctx` | The Host face registers on tracked entries' `ctx`; `clientModules` must withdraw every listener when it unloads |
|
||||
| Self-built references | Client references implement `Volatile` structurally without Cosmokit's internal write protocol, so `isVolatile` does not recognize them |
|
||||
| Empty configuration objects | Browser plugins without synced fields also receive an empty read-only object as `config` |
|
||||
| Push order not guaranteed | The configuration-first order holds only when every stream takes the same asynchronous steps from a Host event to the Gateway write queue; streams written in other ways, with or without waits of their own, may be written first |
|
||||
| Every field may be absent | Each `SyncedConfig` field reads `V \| undefined`: secrets, unprojectable values, and Host values not yet matching the browser code are absent, so plugins handle the absent value at each read |
|
||||
@@ -0,0 +1,215 @@
|
||||
# Agent Note: 前端插件配置同步
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-11-15-client-config-sync.md) | 中文
|
||||
|
||||
## Problem
|
||||
|
||||
Host 上的插件配置可以实时更新:Loader 在只有 volatile 字段变化时原地提交引用并发出 `loader/volatile-update`,不重新挂载插件。浏览器侧没有对应链路:
|
||||
|
||||
| 现象 | 原因 |
|
||||
|---|---|
|
||||
| 前端插件的 `apply(ctx, config)` 总是拿到空配置 | 页面 Loader 创建条目时只传 `name`([entries.ts](../../../../packages/client/modules/src/client/entries.ts)),cordis.yml 中该行的 `config` 不会到达浏览器 |
|
||||
| 需要 Host 配置的包各自绕路 | 有的经 `webserver/index-inject` 写页面全局变量,只在页面加载时生效;有的借 `configForms` 设置镜像读取运行时值 |
|
||||
| 插件图推送通道不合规 | `/plugins/events` 是 `auth: 'anonymous'` 路由;浏览器有 `EventSource` 和 `__DSH_TRANSPORT__.fetch` 两套读取实现,后者断开后不重连;帧序列没有「每代一份完整快照」约束 |
|
||||
|
||||
## Decision
|
||||
|
||||
### 设计原则
|
||||
|
||||
| 原则 | 内容 |
|
||||
|---|---|
|
||||
| 一套 Config | 插件只有一份配置类型,放在包的 `src/types.ts` 并由 Host 与 Client 两面共用;schema 只在 Host 面。浏览器不导出 `Config`,也不做配置校验 |
|
||||
| 只同步 volatile | 浏览器只接收 Host schema 中声明为 volatile 的字段 |
|
||||
| 剔除密钥 | volatile 字段内的 `role('secret')` 字段(包括 volatile 对象、数组、字典内部)在 Host 上剔除,不下发。该逻辑在 `client/modules` Host 面独立实现,不依赖 `@deepseek-ai/dsh-settings` |
|
||||
| 插件自身支持热更新 | 同步配置的变化永远不重新挂载前端插件;插件在操作时读取引用,或把引用作为可订阅数据源交给组件 |
|
||||
| 相等即无事 | 每层都按 deep equal 比较,值相等时不推送、不写入、不通知;重连收到的完整快照与当前值相等时不产生任何刷新 |
|
||||
| 不同步的内容 | Host 专用普通字段、密钥、按浏览器区分的偏好不进入此链路;主题等在页面 HTML 预注入以避免首屏闪烁的值保持原状 |
|
||||
|
||||
### 插件写法
|
||||
|
||||
```ts ignore-check
|
||||
// src/types.ts — shared by both faces; types only
|
||||
import type { Volatile } from '@deepseek-ai/cordis'
|
||||
|
||||
/** Plugin configuration shared by the Host and Client faces. */
|
||||
export interface Config {
|
||||
/** Host-only ordinary field; never synced. */
|
||||
cacheDir: string
|
||||
/** Synced to the browser. */
|
||||
interactiveByDefault: Volatile<boolean>
|
||||
/** Synced as one value. */
|
||||
office: Volatile<{ maxBytes: number }>
|
||||
/** Volatile but `role('secret')`: stripped on the Host; reads as undefined in the browser. */
|
||||
apiKey?: Volatile<string>
|
||||
}
|
||||
```
|
||||
|
||||
```ts ignore-check
|
||||
// src/index.ts — Host face; the only schema
|
||||
export const Config: z<Config> = z.object({
|
||||
cacheDir: z.string().default('.cache'),
|
||||
interactiveByDefault: z.boolean().default(false).volatile(),
|
||||
office: z.object({ maxBytes: z.natural().default(8 << 20) }).volatile(),
|
||||
apiKey: z.string().role('secret').volatile(),
|
||||
})
|
||||
```
|
||||
|
||||
```ts ignore-check
|
||||
// src/client/index.ts — Client face; no Config export
|
||||
import type { SyncedConfig } from '@deepseek-ai/dsh-client-config/types'
|
||||
import type { Config } from '../types.ts'
|
||||
|
||||
export function apply(ctx: Context, config: SyncedConfig<Config>): void {
|
||||
// Every synced field may read undefined; the plugin decides what an absent value means.
|
||||
const tooLarge = (bytes: number) => bytes > (config.office.get()?.maxBytes ?? Number.POSITIVE_INFINITY)
|
||||
ctx.slots.register({
|
||||
name: 'demo.body',
|
||||
inject: (): DemoBodyInjected => ({ hooks: { interactiveByDefault: config.interactiveByDefault }, tooLarge }),
|
||||
}, DemoBody)
|
||||
}
|
||||
```
|
||||
|
||||
```tsx ignore-check
|
||||
// src/client/DemoBody.tsx — the renderer binds the injected source as useInteractiveByDefault
|
||||
export function DemoBody({ useInteractiveByDefault, tooLarge }: InjectFace<DemoBodyInjected>) {
|
||||
const interactive = useInteractiveByDefault(value => value)
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
只放类型的包 `@deepseek-ai/dsh-client-config/types` 导出的类型;插件依赖它而不依赖启动最早的 Client Modules 包,由 Client Modules 实现:
|
||||
|
||||
```ts ignore-check
|
||||
/** One synced field: Host-aligned `get()`, and directly an observable source for an injected hook. */
|
||||
export interface SyncedConfigRef<T> extends Volatile<T>, ObservableSnapshot<VolatileSnapshot<T>> {}
|
||||
|
||||
/** The Volatile fields of the shared Config type. */
|
||||
export type SyncedConfig<C> = {
|
||||
readonly [K in keyof C as NonNullable<C[K]> extends Volatile<unknown> ? K : never]-?:
|
||||
NonNullable<C[K]> extends Volatile<infer V> ? SyncedConfigRef<V | undefined> : never
|
||||
}
|
||||
```
|
||||
|
||||
`get` 与 `getSnapshot` 返回同一个冻结快照:`get` 与 Host 的 volatile 引用写法一致,`getSnapshot` 与 `subscribe` 满足 `ObservableSnapshot`,引用本身即可放进 `hooks`,renderer 不需要额外适配。接口没有写操作;实现类只在 Client Modules 内部。
|
||||
|
||||
组件取值遵循 [client 规则](../../../../packages/client/AGENTS.md):插件在 slot inject 的 `hooks` 中手动注入 key 级数据源,组件只通过 renderer 绑定的 `use<Name>` 读取,不接触数据源本身。
|
||||
|
||||
### 归属
|
||||
|
||||
运行时归属仍在 `client/modules`;唯一新增的包是只放类型的 `@deepseek-ai/dsh-client-config`(两个面的 `apply` 都为空)。`client/modules` 本来就跟踪 Loader 条目、组合插件图并在浏览器创建条目,同步配置是条目的输入,由它一并负责:
|
||||
|
||||
| 面 | 职责 |
|
||||
|---|---|
|
||||
| Host(`clientModules` 服务内部) | 在每个图行插件自身的 `ctx` 上监听 `loader/volatile-update`;插件 fiber 进入 ACTIVE(`internal/status`)或条目对账后重算;从 `fiber.effectiveConfig` 读取 schema 顶层 volatile 字段的值,按 schema 剔除 `role('secret')` 位置,得到该行同步值;与上次值 deep equal 比较,不等才写入图行 `config` 并重新发布图。只变化同步值时不重建 combo 产物 |
|
||||
| Client(条目控制器内部) | 为图中出现过的每个包保存最新同步值;插件每次激活都得到一个新的配置对象(行暂时没有值时是空对象),与 Host fiber 每次激活重新解析出新引用一致;收到图时按字段 JSON 比较,把变化写入当前激活的对象 |
|
||||
| Client(`ctx.config` 服务) | 只读:`resolveConfigByPackage<C>(packageName)` 返回某个包当前激活收到的对象,供读取其他插件的配置;插件被替换后对象随之改变,没有运行中的激活时返回 `undefined` |
|
||||
|
||||
Client 面的约束:
|
||||
|
||||
| 约束 | 内容 |
|
||||
|---|---|
|
||||
| 懒生成 | 字段引用在首次访问时创建并缓存 |
|
||||
| 实例身份 | 每次激活一个对象,与该激活同寿命;代码替换与行重新加入都产生新对象,持有最新值 |
|
||||
| 不调用 `entry.update` | 同步配置不经过 Loader 的更新路径,不会触发重挂载,浏览器不发 `loader/volatile-update`;变化只经字段引用的 `subscribe` 通知 |
|
||||
| 原子发布 | 一次图更新先设置所有变化字段,再通知它们的订阅者,与 Host 先提交全部引用再发事件一致 |
|
||||
| 不校验值 | 值已由 Host 权威 schema 校验;浏览器只在图解析时校验行 `config` 是对象 |
|
||||
| 交付方式 | 条目控制器在页面 Loader 上以 prepend 方式注册 `internal/config` 监听,为不导出 schema 的托管条目返回同步对象,Loader 插值在其内层运行,不会复制该对象。导出自身 `Config` schema 的前端面保持 Cordis 原有配置解析;这类前端面的行若同时带同步值,激活失败 |
|
||||
|
||||
### 时序
|
||||
|
||||
Host 的一致性来自两点:schema 与代码同属一个模块,激活时用该 schema 解析原始配置;代码重载与配置重载由 Host 热重载串行执行,只有 ACTIVE 的实例原地接收 volatile 变化。Client 对齐后一点:
|
||||
|
||||
| 情形 | Host | Client |
|
||||
|---|---|---|
|
||||
| 实例运行中,配置变化 | 原地提交全部引用后通知 | 原地写入当前激活的对象,全部写完后通知 |
|
||||
| 替换已排队、拆除尚未开始时配置变化 | 实例仍 ACTIVE,原地更新 | 同左 |
|
||||
| 拆除开始后配置变化 | 非 ACTIVE 实例不再原地更新,新实例解析最新配置 | 拆除开始时释放旧激活,旧对象不再写入;新激活以最新值开始 |
|
||||
| 行被移除 | 实例被销毁,不再收到配置 | 移除时释放激活;行不在图中期间不写入 |
|
||||
| Host 侧插件实例非 ACTIVE | 不适用 | 同步值与 Host 插件自身的 effective Config 一样跟随 Host 配置,激活失败时也是如此;尚未激活的实例发布其 schema 从原始配置解析出的值 |
|
||||
|
||||
尚未激活的插件实例(新安装、升级、代码热重载)发布用它自己的 schema 从原始配置解析出的值,因此宣布新前端代码的那一帧已带着对应 Host schema 的值。只有开发时不兼容地修改 schema(改名、删字段),才可能在重建的 bundle 到达前,让旧前端代码短暂收到它不认识的值。
|
||||
|
||||
### 推送顺序
|
||||
|
||||
Host 插件更新配置后再向浏览器推送其他数据时,浏览器应先收到配置。这一顺序只在机制上通过以下几处保证,实际上不保证:各流的源从 Host 事件到把数据项放入 gateway 写出队列所经过的异步步骤数各不相同,即使插件没有自行插入等待,步骤更少的流也可能先被写出。插件不得依赖这一顺序:
|
||||
|
||||
| 环节 | 做法 |
|
||||
|---|---|
|
||||
| Host 入队 | `clientModules` 在插件 ctx 上以 prepend 注册 `loader/volatile-update` 监听,在插件自己的监听之前同步把新图放入各 follower 队列 |
|
||||
| pluginEvents 流 | `follow` 在自身生成器内产出增量,不经过额外委托的生成器多走一步 |
|
||||
| gateway 写出 | 每条连接一个写出队列,各流的项在源产出时立即入队并按入队顺序写出,不再逐项等待上一次写入完成;排队字节超过 `streamOutboxBytes` 时整条连接暂停读取所有源 |
|
||||
| 浏览器处理 | 每条 WebSocket 消息按到达顺序处理,配置写入在图帧处理时同步完成 |
|
||||
|
||||
### 下发
|
||||
|
||||
首屏值随 `__DSH_BOOT__` 的图行下发;之后随插件事件流的 `baseline` 与 `graph` 帧下发,不另设配置帧。插件图的线类型由 `@deepseek-ai/dsh-client-modules/types` 导出。只有 owner 收到实际配置的值;其他所有 Peer(例如 LiveShare 查看端)在启动图和每个插件事件帧中收到各插件 schema 对空 Config 解析出的值,因此 Host schema 仍是默认值的唯一来源,owner 实际配置的值留在 Host;schema 拒绝空 Config 的行在这类页面上不带值。Remote access 策略只决定 Peer 能否跟随插件图。
|
||||
|
||||
### 推送通道
|
||||
|
||||
`/plugins/events` 改为常规鉴权的 Typert Remote 流 `pluginEvents/follow`,浏览器用 `RemoteSnapshotStream` 消费:
|
||||
|
||||
| 帧 | 内容 | 浏览器处理 |
|
||||
|---|---|---|
|
||||
| `baseline` | 完整插件图(含各行同步配置) | 条目对账 |
|
||||
| `graph` | 结构或同步配置变化后的完整插件图 | 条目对账 |
|
||||
| `rebuilt` | `{ id, rev }`,单包代码重建 | 条目代码替换 |
|
||||
|
||||
| 项 | 内容 |
|
||||
|---|---|
|
||||
| 鉴权 | 走 Remote 网关的常规认证与授权,删除匿名 `/plugins/events` 路由;浏览器面在 Remote access 允许 `pluginEvents/follow` 时开流 |
|
||||
| 传输 | 删除 `EventSource` 与 `__DSH_TRANSPORT__.fetch` 两套实现;liveshare、webworker 等外壳经 connection 已提供的 Remote 载体接入 |
|
||||
| 重连 | 由 `RemoteStream` 负责;每代先收 `baseline`,断线期间的遗漏由新快照补齐 |
|
||||
| 桌面端 | 与 Web 共用同一 Remote 流 |
|
||||
| 归属 | Remote 服务 `pluginEvents` 由 `client/hmr` Host 面持有,与 bundle stat 轮询同包,不声明 `ctx` 类型合并;`client/modules` 是零依赖的 bootstrap 包,不引入 typert 与 gateway 依赖 |
|
||||
| 浏览器依赖 | 浏览器面自行 `$mount` 本包生成的 `pluginEvents` 命名空间,不经 `api-remotes` 组装,因此 `api-remotes` 可以独立热替换;必需依赖为 `modules`、`remote`(gateway Client 面,其下为 connection)与 `remoteAccess` |
|
||||
|
||||
### 能力边界:可收编的现有用法
|
||||
|
||||
本 Note 不迁移现有用法;[迁移 Note](../../proposed/architecture/2026-11-15-client-config-sync-migration.zh.md) 负责盘点与顺序。本机制具备收编以下用法的能力:经 `webserver/index-inject` 下发 Host 配置的页面全局变量、以 `configForms` 读取运行时值的插件、只在前端声明而无法配置的 `Config`。
|
||||
|
||||
## Verification
|
||||
|
||||
以下行为成立并由测试覆盖:
|
||||
|
||||
- 前端插件 `apply` 的 `config` 参数首屏即为 Host 当前 volatile 值;修改 `cordis.patch.yml` 的 volatile 字段后,浏览器中引用值更新、订阅组件重新渲染,前端与 Host 插件 fiber 都不重挂载。
|
||||
- 投影剔除的 `role('secret')` 位置(与 settings 的剔除范围相同)不出现在首屏注入和任一推送帧中;非 owner 的 Peer 只收到 schema 默认值,收不到实际配置的值。
|
||||
- Host 专用普通字段不出现在浏览器。
|
||||
- 值不变的配置重载、Host 重启后的重连 baseline 都不产生 `loader/volatile-update`,也不通知订阅者。
|
||||
- `/plugins/events` 匿名路由不存在;未认证请求无法获取插件图或配置;断线重连后浏览器状态与 Host 一致。
|
||||
- 代码热重载后新激活拿到持有当前值的新 `SyncedConfig` 对象,旧激活在拆除开始后不再收到新值。
|
||||
- Host 上,新图帧在插件自己的 `loader/volatile-update` 监听执行之前进入 pluginEvents 各 follower 队列;不要求线上的先后顺序。
|
||||
- 测试:`client/modules` 两面单元测试(剔除、比较、懒生成、引用稳定、监听注册与卸载);真实组合测试经 Loader 启动 profile、修改 patch 并断言浏览器可见值;`client-plugin-live` 与 `client-config-sync` 两个 Web 端到端测试,包括传输重启后的重连。
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
| Rejected | 理由 |
|
||||
|---|---|
|
||||
| 另立一份前端 `ClientConfig` schema | 两份 schema 会漂移;volatile 声明与校验已由 Host schema 承担 |
|
||||
| 整份配置去掉密钥后下发 | 会把 Host 路径、URL 等普通字段泄漏到浏览器 |
|
||||
| 前端条目经 `entry.update({ config })` 应用变化 | 前端无 schema,Loader 无法判断 volatile,只会重挂载 |
|
||||
| 修改 vendored Loader 增加全局 volatile 事件 | 需登记 vendor 本地修改;在条目自身 `ctx` 上监听即可满足 |
|
||||
| 通道放进 `client/modules` | bootstrap 包会因此依赖 typert 与 gateway |
|
||||
| 经 `api-remotes` 挂载 `pluginEvents` | `api-remotes` 的替换失败会切断插件更新通道 |
|
||||
| 为 connection 与 gateway 增加「替换需刷新页面」声明 | 新增 manifest 字段与界面分支;接受替换失败时刷新页面 |
|
||||
| renderer 提供统一的 `useConfig` 框架 hook | 新增框架级 hook;手动注入 `hooks` 已满足组件取值 |
|
||||
| 复用 `@deepseek-ai/dsh-settings` 的投影与剔除函数 | settings 架构尚待在本机制之后统一调整,先不建立依赖 |
|
||||
| 引用只保留 `ObservableSnapshot` | 与 Host volatile 引用的 `get()` 写法不一致 |
|
||||
| 每个包一个页面级配置对象 | 替换期间正在退出的旧实例仍会收到新配置,与 Host 不一致 |
|
||||
| 修改 vendored Loader 发出提交事件以保证 Host 入队顺序 | prepend 监听已能满足,不需要 vendor 改动 |
|
||||
| 另开一条配置专用推送通道 | 与插件图通道重复鉴权、重连与快照语义 |
|
||||
| 独立 `client/config` 运行时包提供公开写入的配置服务 | 任何插件都能改写别的插件的配置;条目还需按包名等待该服务 |
|
||||
| 插件从 `@deepseek-ai/dsh-client-modules/types` 导入类型 | 让每个使用配置的插件都依赖启动最早的模块系统包,并暴露实现类 |
|
||||
| 浏览器也发 `loader/volatile-update` | 字段引用的 `subscribe` 已足够,事件需要深入 Cordis 的过滤机制 |
|
||||
|
||||
## Consequences
|
||||
|
||||
| 风险 | 说明 |
|
||||
|---|---|
|
||||
| 通道依赖 connection | 插件图同步依赖 connection 与 gateway Client 面。热替换它们会连带重启本插件并重开流,由新一代 baseline 对账;若其新代码导入或激活失败,页面在刷新前收不到插件更新(已接受) |
|
||||
| 在他人 `ctx` 上注册监听 | Host 面在被跟踪条目的 `ctx` 上注册,`clientModules` 卸载时必须撤销全部监听 |
|
||||
| 自建引用 | Client 面引用是自建的 `Volatile` 结构实现,不使用 cosmokit 内部写入协议,`isVolatile` 不识别它们 |
|
||||
| 空配置对象 | 没有同步字段的前端插件也收到一个空的只读对象作为 `config` |
|
||||
| 推送顺序不保证 | 配置先到只在各流从 Host 事件到 gateway 写出队列经过相同异步步骤时成立;其他写法的流,无论是否自行等待,都可能先被写出 |
|
||||
| 每个字段都可能缺值 | `SyncedConfig` 的每个字段读到 `V \| undefined`:密钥、无法投影的值、尚未与浏览器代码对应的 Host 值都会缺失,插件需在每次读取时处理缺值 |
|
||||
@@ -18,8 +18,8 @@
|
||||
en: 8b10f08e67ca9323
|
||||
zh: e57adb520049f407
|
||||
/agent-note-typed-tool-returns-in-ptc-mode/decision/outer-result-and-output-ledger:
|
||||
en: e48ef4dbe1ac9a1e
|
||||
zh: b87b0c0a3f1c2a4e
|
||||
en: f6fb803d2dc061bb
|
||||
zh: 05432104d5876f99
|
||||
/agent-note-typed-tool-returns-in-ptc-mode/decision/typed-handles-and-lifetime:
|
||||
en: b2b9318c2812e3a4
|
||||
zh: 73cf34bfd487e2f1
|
||||
@@ -33,8 +33,8 @@
|
||||
en: 069a1e170c7d1dfb
|
||||
zh: 14ce5a56e602595c
|
||||
/agent-note-typed-tool-returns-in-ptc-mode/consequences:
|
||||
en: f5726b5e7a2fc73f
|
||||
zh: 0b9aa884db5d920f
|
||||
en: 16cb8d972867b62f
|
||||
zh: d253114975e96fe8
|
||||
/agent-note-typed-tool-returns-in-ptc-mode/known-limitations-and-deferred-work:
|
||||
en: 19828c2e5796df2d
|
||||
zh: 2ef63df81fca7a72
|
||||
@@ -59,9 +59,9 @@ Ordinary binding arguments and JSON resolutions are revalidated as lossless JSON
|
||||
|
||||
Runtime consumers that retain completions receive exact lossless JSON: `undefined` omits the completion and `null` is an explicit result. TypeScript `run_code` requests completion discard and returns captured logs plus optional sandbox facts as its canonical value; selected images enter its rendered content separately.
|
||||
|
||||
`NodePtcRuntime` replaces the former independent log and value caps with configurable `maxOutputBytes`, defaulting to `67_108_864` bytes. The worker charges captured logs by their exact JSON-string serialization and preflights the detached completion or program exception against the remaining combined budget before posting a terminal message. A giant thrown string or stack therefore crosses the worker port only as the fixed `output-limit` diagnostic. The host repeats the hostile-peer ledger for forged traffic and native pipe writes the worker cannot observe. Fixed `PtcRunResult` field names, braces, the bounded error-kind tag, and later presentation whitespace are deliberately outside this variable-payload ledger. Neither stage materializes an over-limit serialized completion. A result at or below the cap is exact. A completion that cannot survive lossless JSON snapshotting fails as `invalid-output`; a value, diagnostic, or combined outcome over the cap fails as `output-limit` rather than becoming inspected or truncated text.
|
||||
`NodePtcRuntime` uses the configurable `maxOutputBytes` combined payload budget, defaulting to `67_108_864` bytes. Required completion values remain lossless JSON: unsupported values fail with `invalid-output`, and values that cannot fit fail with `output-limit`. The [output-truncation decision](../architecture/2026-11-13-ptc-output-truncation.md) owns captured-output retention and diagnostic priority. Fixed `PtcRunResult` field names, braces, bounded metadata and later presentation whitespace remain outside this variable-payload ledger. The host validates untrusted process traffic and native pipe writes independently; neither side serializes oversized completions.
|
||||
|
||||
Logs stream eagerly so a terminated run can retain output already admitted. Native stdout and stderr writes that bypass the worker's patched stream slots use independent pipes, so terminal settlement continues bounded capture until worker termination completes before materializing the result. When the cap is crossed, the runtime returns an explicit bounded failure with the fitting captured prefix. That outer result then traverses the ordinary `run_code` rendering and spill policy, which may save the captured text and expose its configured head/tail preview. The spill layer cannot recover bytes the runtime rejected beyond the hard cap.
|
||||
Logs stream eagerly so a terminated run can retain output already admitted. Native stdout and stderr writes that bypass the worker's patched stream slots use independent pipes, so terminal settlement continues bounded capture until worker termination completes before materializing the result. When the cap is crossed, captured output is truncated to a fitting prefix and marked with `outputTruncated`, while execution continues. Finalization reserves the required completion or diagnostic budget before retaining output; only a required completion that cannot fit causes `output-limit`. That outer result then traverses the ordinary `run_code` rendering and spill policy, which may save the captured text and expose its configured head/tail preview. The spill layer cannot recover bytes the runtime rejected beyond the hard cap.
|
||||
|
||||
Compute time, wall time, worker heap, cancellation, and fresh-worker isolation remain independent limits. The outer ledger never charges intermediate bindings, so snapshotting, flat-wire encoding and decoding, structured-clone cost, and available process or worker memory are their practical bounds.
|
||||
|
||||
@@ -101,7 +101,7 @@ Keyless real-worker integration tests pin the two handle workflows that prose re
|
||||
|
||||
Code programs can compose tools through stable values instead of reverse-engineering Native prose. Native mode retains its existing text and UI presentation, while PTC mode receives output-schema types and exact runtime JSON. Tool authors must treat the canonical value as their programmatic API and put display-only formatting in the renderer.
|
||||
|
||||
The worker performs bounded-depth flat-wire transport and lossless validation but does not make intermediate values cheap or durable. Outer overflow is an explicit failed run, and error handling remains intentionally human-guided rather than a versioned code union.
|
||||
The worker performs bounded-depth flat-wire transport and lossless validation but does not make intermediate values cheap or durable. An oversized required completion is an explicit failed run, and error handling remains intentionally human-guided rather than a versioned code union.
|
||||
|
||||
## Known Limitations and Deferred Work
|
||||
|
||||
|
||||
@@ -59,9 +59,9 @@ PTC mode 通过运行时请求中的 `{ name: "ToolCallError", memberNamePropert
|
||||
|
||||
保留完成值的运行时消费方接收精确无损 JSON:`undefined` 省略完成值,`null` 是显式结果。TypeScript `run_code` 请求丢弃完成值,将捕获日志和可选沙箱信息作为规范值返回;所选图片单独进入渲染内容。
|
||||
|
||||
`NodePtcRuntime` 以可配置的 `maxOutputBytes` 取代彼此独立的日志与值上限,默认值为 `67_108_864` 字节。worker 会将已捕获日志序列化为 JSON 字符串后的精确字节数计入账本,并在发送终态消息前,根据组合账本的剩余额度预检分离后的完成值或程序异常。因此,即使抛出的字符串或堆栈极大,通过 worker 端口的也只会是固定的 `output-limit` 诊断。宿主侧会针对伪造流量以及 worker 无法观察的原生管道写入,重复执行这套面向不可信对端的账本校验。固定的 `PtcRunResult` 字段名、花括号、有界的错误类型标签及后续展示空白有意不计入这份可变负载账本。这两个阶段都不会实际生成超出上限的完成值序列化结果。结果不超过上限时会保持精确。完成值无法通过无损 JSON 快照时,以 `invalid-output` 失败;值、诊断或包含日志的组合结果超过上限时,以 `output-limit` 失败,而不会变成检查格式化后或截断的文本。
|
||||
`NodePtcRuntime` 使用可配置的 `maxOutputBytes` 组合负载预算,默认值为 `67_108_864` 字节。必需完成值保持无损 JSON:不支持的值以 `invalid-output` 失败,无法容纳的值以 `output-limit` 失败。[输出截断决策](../architecture/2026-11-13-ptc-output-truncation.zh.md)负责捕获输出保留和诊断优先级。固定的 `PtcRunResult` 字段名、花括号、有界元数据和后续展示空白仍不计入可变负载账本。宿主独立校验不可信进程通信和原生管道写入;两端都不会序列化过大的完成值。
|
||||
|
||||
日志会在产生时立即流出,因此运行被终止时仍可保留已经纳入额度的输出。绕过 worker 中已改写流写入入口的原生 stdout 和 stderr 写入会经由彼此独立的管道传输,因此运行时在终态结算期间仍会继续在上限内捕获输出,直至 worker 完全终止,然后才组装结果。超过上限后,运行时会返回一个显式的有界失败,并携带可容纳的已捕获前缀。该外层结果随后通过普通的 `run_code` 渲染与 spill 策略;策略可以保存已捕获的文本,并暴露其配置指定的头尾预览。spill 层无法恢复运行时在硬上限之外拒绝的字节。
|
||||
日志会在产生时立即流出,因此运行被终止时仍可保留已经纳入额度的输出。绕过 worker 中已改写流写入入口的原生 stdout 和 stderr 写入会经由彼此独立的管道传输,因此运行时在终态结算期间仍会继续在上限内捕获输出,直至 worker 完全终止,然后才组装结果。超过上限后,捕获输出会截断为可容纳的前缀并标记 `outputTruncated`,执行继续。最终结算先为必需完成值或诊断预留预算,再保留输出;只有无法容纳的必需完成值才会导致 `output-limit`。该外层结果随后通过普通的 `run_code` 渲染与 spill 策略;策略可以保存已捕获的文本,并暴露其配置指定的头尾预览。spill 层无法恢复运行时在硬上限之外拒绝的字节。
|
||||
|
||||
计算时间、墙钟时间、worker 堆内存、取消和每次运行使用全新 worker 的隔离仍是互相独立的限制。外层账本从不计入中间绑定值,因此生成快照、扁平协议格式的编码与解码、结构化克隆开销,以及进程或 worker 的可用内存构成了这些值的实际边界。
|
||||
|
||||
@@ -101,7 +101,7 @@ PTC mode 通过运行时请求中的 `{ name: "ToolCallError", memberNamePropert
|
||||
|
||||
PTC mode 程序可以通过稳定值组合工具,无需逆向解析 Native 自然语言。Native mode 保留现有文本与 UI 展示,PTC mode 则获得输出 schema 类型和精确的运行时 JSON。工具作者必须把规范值视为程序化 API,并将仅用于展示的格式化放入渲染器。
|
||||
|
||||
worker 会以嵌套深度有界的扁平协议格式传输数据并执行无损校验,但不会降低中间值的开销,也不会使其具备持久性。外层输出溢出会显式导致运行失败,错误处理则有意由人类引导,而不是依赖带版本的错误代码联合。
|
||||
worker 会以嵌套深度有界的扁平协议格式传输数据并执行无损校验,但不会降低中间值的开销,也不会使其具备持久性。必需完成值超限会显式导致运行失败,错误处理则有意由人类引导,而不是依赖带版本的错误代码联合。
|
||||
|
||||
## 已知限制与暂缓事项
|
||||
|
||||
|
||||
+6
-6
@@ -9,14 +9,14 @@
|
||||
en: 3238dfb7db7dfdd8
|
||||
zh: ec3bdd9a9da0a321
|
||||
/agent-note-user-authorized-subagent-model-routes/decision:
|
||||
en: 9eeb42f10be1bd28
|
||||
zh: 24e6cca2db77444a
|
||||
en: 36f00a578ea7adbd
|
||||
zh: 431cb3d054765414
|
||||
/agent-note-user-authorized-subagent-model-routes/alternatives-considered:
|
||||
en: e41c17226190ea8b
|
||||
zh: d3b1395fafe75f01
|
||||
en: 72a41079e819f693
|
||||
zh: 0e6c673374932555
|
||||
/agent-note-user-authorized-subagent-model-routes/consequences:
|
||||
en: 26244ba796f6ed70
|
||||
zh: 47e9744719b05f0b
|
||||
en: 856c751fcf2326d9
|
||||
zh: 3f3ee671b0dfd2e3
|
||||
/agent-note-user-authorized-subagent-model-routes/related-decisions:
|
||||
en: 0eead87ec1172d81
|
||||
zh: 4e776a583f5a00a5
|
||||
+5
-6
@@ -12,11 +12,11 @@ Registering an LLM adapter makes its routes reachable, but does not authorize an
|
||||
|
||||
The Host-owned `subagent-model-selection` settings section stores an explicit `enabled` switch and `allowedModels`, an array of exact `{ provider, model }` routes. Enabling requires at least one route; disabling may retain the selected routes for later reuse. The Plugins settings card reads the live adapter directory through `session/modelCatalog`, lets the user stage the switch and routes, and saves both fields in one revision-fenced settings mutation. It stores no adapter-owned display names, descriptions, or reasoning-effort metadata. A stored or staged route absent from the current directory remains visible as unavailable and removable; a provider-local catalog failure does not block other providers or erase saved authorization or an unsaved selection. A connection reset discards the draft because namespace revisions are comparable only within one Host process.
|
||||
|
||||
The Host settings service snapshots the route list for each fresh top-level Session in `subagent/model-selection-policy` when the setting is enabled, before its first model request. Event presence means selection was enabled; the event does not store the global switch. Child Sessions inherit that exact list from their live parent, and resumed Sessions use the recorded event instead of current settings. Settings changes therefore affect only subsequently created top-level Sessions. Without the event, including an explicitly empty restored Session, explicit selection remains restricted to the current parent route.
|
||||
Each delegation and discovery call reads the current setting; [live subagent model-selection setting](2026-11-17-live-subagent-model-selection-setting.md) supersedes the per-Session snapshot this note originally recorded. When the setting is disabled or its service is absent, explicit selection remains restricted to the current parent route.
|
||||
|
||||
The fixed `list_subagent_models` schema does not enumerate the policy. At call time, it lists authorized registered providers and intersects their advertised model catalogs with the recorded route list. Exact lookup requires authorization before resolving model metadata and all supported reasoning efforts, including for ids absent from the catalog. Without a recorded policy, discovery resolves only the parent Agent’s current effective route, even if the catalog omits it. The delegation executor independently checks any explicit provider, model, or effort selection against the same authorization before adapter preflight. A call with no selection fields retains configured or inherited routing.
|
||||
The fixed `list_subagent_models` schema does not enumerate the policy. At call time, it lists authorized registered providers and intersects their advertised model catalogs with the current route list. Exact lookup requires authorization before resolving model metadata and all supported reasoning efforts, including for ids absent from the catalog. When the setting is disabled, discovery resolves only the parent Agent’s current effective route, even if the catalog omits it. The delegation executor independently checks any explicit provider, model, or effort selection against the same authorization before adapter preflight. A call with no selection fields retains configured or inherited routing.
|
||||
|
||||
Model selection has no unrestricted static mode. The default-off Host setting authorizes alternative child routes; without it, the parent route and its supported efforts remain selectable. Each delegation tool’s `modelSelection` option controls only its route fields. One delegation instance per scope enables `modelDiscovery` to own discovery; the setting, discovery, and delegation read the same package-local authorization projection. Web and Desktop presets mount discovery by default, enable spawn route fields, and leave fork route fields disabled to preserve inherited-prefix reuse; custom fork compositions may enable them under the same Session authorization. Tool installation does not sample or expand authorization.
|
||||
Model selection has no unrestricted static mode. The default-off Host setting authorizes alternative child routes; without it, the parent route and its supported efforts remain selectable. Each delegation tool’s `modelSelection` option controls only its route fields. One delegation instance per scope enables `modelDiscovery` to own discovery; discovery and delegation read the same settings service. Web and Desktop presets mount discovery by default, enable spawn route fields, and leave fork route fields disabled to preserve inherited-prefix reuse; custom fork compositions may enable them under the same Host authorization. Tool installation does not sample or expand authorization.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
@@ -28,15 +28,14 @@ Model selection has no unrestricted static mode. The default-off Host setting au
|
||||
|
||||
**Store per-route reasoning-effort allowlists.** Rejected because the user decision concerns child models, while effort ids and compatibility belong to the exact adapter route. Every adapter-supported effort remains available after the route is authorized.
|
||||
|
||||
**Read current settings on every discovery or delegation call.** Rejected because a settings edit would silently change a running Session's model-visible capabilities and execution authority. The durable Session snapshot keeps resume and child inheritance deterministic.
|
||||
**Read current settings on every discovery or delegation call.** Originally rejected because a settings edit would change a running Session's capabilities and execution authority; [live subagent model-selection setting](2026-11-17-live-subagent-model-selection-setting.md) adopts it because users expect the setting to apply immediately.
|
||||
|
||||
## Consequences
|
||||
|
||||
- New adapter registrations and newly advertised models do not expand user authorization.
|
||||
- Adapter removal or catalog lookup failure can make provider discovery unavailable without deleting the saved route decision; an allowed model remains usable when its adapter accepts it even if the advisory catalog omits it.
|
||||
- The allowlist itself consumes no parent-request tokens. Only a `list_subagent_models` result enters the transcript. The `modelSelection` option adds three route fields; `modelDiscovery` adds a fixed discovery schema. Both options default off; shipped headless and SDK profiles carry neither.
|
||||
- The policy event is log-only and is appended while an Agent is composed, before either SDK begins its run subscription. Shipped SDK profiles do not enable this Web-owned preference, so the event changes neither SDK's expected notifications or persisted-session output; package restore tests own its durable projection instead of fabricating an SDK composition solely to emit it.
|
||||
- Unit coverage pins settings validation, malformed durable values, Session sampling and inheritance, shared definitions, parent-route defaults, discovery restrictions, executor denial, and the settings UI’s staged writes and revision checks. The assembled Web scenario pins the real settings document and Plugins card flow.
|
||||
- Unit coverage pins settings validation, live reads in parent and child Sessions, shared definitions, parent-route defaults, discovery restrictions, executor denial, and the settings UI’s staged writes and revision checks. The assembled Web scenario pins the real settings document and Plugins card flow.
|
||||
|
||||
## Related decisions
|
||||
|
||||
|
||||
+5
-6
@@ -12,11 +12,11 @@ Status: implemented
|
||||
|
||||
Host 自有的 `subagent-model-selection` 设置 section 保存显式 `enabled` 开关与 `allowedModels`,后者是由精确 `{ provider, model }` 路由组成的数组。启用时必须至少有一条路由;关闭时可以保留已选路由,供以后重新启用。Plugins 设置卡通过 `session/modelCatalog` 读取实时适配器目录,让用户暂存开关与路由,再在一次带 revision 限制的设置 mutation 中保存两个字段。它不保存适配器自有的显示名称、描述或推理强度元数据。当前目录中缺失的已存或暂存路由仍显示为不可用并允许移除;某个提供方的目录失败不会阻塞其他提供方,也不会清除已存授权或未保存选择。连接重置会丢弃草稿,因为 namespace revision 只能在同一个 Host 进程内比较。
|
||||
|
||||
设置启用时,Host 设置服务为每个新顶层 Session 在首个模型请求前将路由列表记录为 `subagent/model-selection-policy`。事件存在表示选择已启用;事件不保存全局开关。子 Session 从在线父级继承同一精确列表,恢复的 Session 使用已记录事件而非当前设置。因此设置变更只影响之后创建的顶层 Session。没有该事件时,包括显式为空的恢复 Session,显式选择仍仅限当前父级路由。
|
||||
每次委派和发现调用都读取当前设置;[实时读取的 subagent 模型选择设置](2026-11-17-live-subagent-model-selection-setting.zh.md)取代了本 Agent Note 最初记录的逐 Session 快照。设置关闭或其服务缺失时,显式选择仍仅限当前父级路由。
|
||||
|
||||
固定的 `list_subagent_models` schema 不枚举策略。调用时,它列出已授权且已注册的提供方,并取其公布模型目录与已记录路由列表的交集。精确查询先要求授权,再解析模型元数据及全部支持的推理强度,也允许目录未列出的 ID。没有已记录策略时,发现只解析父 Agent 当前生效的路由,即使目录未列出它。委派执行器会在适配器预检前独立校验显式提供方、模型或强度选择是否符合相同授权。没有选择字段的调用保留配置或继承的路由。
|
||||
固定的 `list_subagent_models` schema 不枚举策略。调用时,它列出已授权且已注册的提供方,并取其公布模型目录与当前路由列表的交集。精确查询先要求授权,再解析模型元数据及全部支持的推理强度,也允许目录未列出的 ID。设置关闭时,发现只解析父 Agent 当前生效的路由,即使目录未列出它。委派执行器会在适配器预检前独立校验显式提供方、模型或强度选择是否符合相同授权。没有选择字段的调用保留配置或继承的路由。
|
||||
|
||||
模型选择没有无限制的静态模式。默认关闭的 Host 设置授权其他子级路由;没有该授权时,仍可选择父级路由及其支持的强度。各委派工具的 `modelSelection` 选项只控制自身路由字段。每个作用域的一个委派实例启用 `modelDiscovery` 并负责发现;设置、发现和委派读取包内同一个授权投影。Web 与 Desktop preset 默认挂载发现工具,启用 spawn 路由字段,并为 fork 保持关闭,以保留对继承前缀的复用;自定义 fork 组合可以在相同 Session 授权下启用这些字段。工具安装不采样或扩大授权。
|
||||
模型选择没有无限制的静态模式。默认关闭的 Host 设置授权其他子级路由;没有该授权时,仍可选择父级路由及其支持的强度。各委派工具的 `modelSelection` 选项只控制自身路由字段。每个作用域的一个委派实例启用 `modelDiscovery` 并负责发现;发现和委派读取同一个设置服务。Web 与 Desktop preset 默认挂载发现工具,启用 spawn 路由字段,并为 fork 保持关闭,以保留对继承前缀的复用;自定义 fork 组合可以在相同 Host 授权下启用这些字段。工具安装不采样或扩大授权。
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
@@ -28,15 +28,14 @@ Host 自有的 `subagent-model-selection` 设置 section 保存显式 `enabled`
|
||||
|
||||
**保存每条路由的推理强度允许列表。** 不采用,因为用户决定针对子级模型,而强度 id 与兼容性属于精确适配器路由。路由获准后,仍可使用适配器支持的每种强度。
|
||||
|
||||
**每次发现或委派调用都读取当前设置。** 不采用,因为设置编辑会静默改变运行中 Session 的模型可见能力和执行权限。持久 Session 快照会让恢复与子级继承保持确定。
|
||||
**每次发现或委派调用都读取当前设置。** 最初不采用,因为设置编辑会改变运行中 Session 的能力和执行权限;[实时读取的 subagent 模型选择设置](2026-11-17-live-subagent-model-selection-setting.zh.md)采用了它,因为用户期望设置立即生效。
|
||||
|
||||
## Consequences
|
||||
|
||||
- 新适配器注册和新公布模型不会扩大用户授权。
|
||||
- 适配器移除或目录查询失败可能使提供方发现不可用,但不会删除已存路由决定;只要适配器接受某个获准模型,即使建议性目录省略它,该模型仍可使用。
|
||||
- 允许列表本身不消耗父级请求 token。只有 `list_subagent_models` 结果进入 transcript。`modelSelection` 选项增加三个路由字段;`modelDiscovery` 增加固定发现 schema。两个选项都默认关闭;随附 headless 与 SDK profile 两者都不携带。
|
||||
- 策略事件仅存在于日志,并在 Agent 组合期间、两套 SDK 开始订阅运行前追加。随附 SDK profile 不启用这项 Web 自有偏好,因此该事件不会改变任一 SDK 的预期通知或持久 Session 输出;其持久投影由包级恢复测试负责,不会为了发出该事件而虚构 SDK 组合。
|
||||
- 单元覆盖固定设置校验、异常持久值、Session 取样与继承、共享定义、父级路由默认值、发现限制、执行器拒绝,以及设置 UI 的暂存写入与 revision 检查。组装 Web 场景固定真实设置文档与 Plugins 设置卡流程。
|
||||
- 单元覆盖固定设置校验、父子 Session 中的实时读取、共享定义、父级路由默认值、发现限制、执行器拒绝,以及设置 UI 的暂存写入与 revision 检查。组装 Web 场景固定真实设置文档与 Plugins 设置卡流程。
|
||||
|
||||
## Related decisions
|
||||
|
||||
|
||||
@@ -9,14 +9,14 @@
|
||||
en: 7115cbaefaa11d2d
|
||||
zh: 23aff8797a651a36
|
||||
/agent-note-settings-driven-mcp-server-manager/decision:
|
||||
en: 39cf3ae7e8a5799f
|
||||
zh: 7a26503da73e238f
|
||||
en: ac7cc4c046ca2377
|
||||
zh: 697233f3b09759de
|
||||
/agent-note-settings-driven-mcp-server-manager/alternatives-considered:
|
||||
en: daad4acd963926cc
|
||||
zh: 152f3d35a4fe3309
|
||||
en: 1154a35a2f9af53f
|
||||
zh: 92ad94d6306463bb
|
||||
/agent-note-settings-driven-mcp-server-manager/testing:
|
||||
en: cbfd30400093ade5
|
||||
zh: 018ad32e25c6c7fc
|
||||
/agent-note-settings-driven-mcp-server-manager/consequences:
|
||||
en: 2a11ba309122335a
|
||||
zh: 663670e2bf3c5a37
|
||||
en: 078ddb6329aae177
|
||||
zh: dc2b2f3c457feb53
|
||||
@@ -20,19 +20,21 @@ Installed application plugins also bring their own servers. Each must add its se
|
||||
|
||||
**A flat entry schema, validated cross-field.** The entry is flat with a `transport` discriminant, and write-time validation enforces the per-transport requirements and rejections (missing `command`/`url`, cross-transport fields, malformed templates) at the write — a schema-valid-but-unserviceable entry is never stored, and refusals name the offending field where a union's shape error would not.
|
||||
|
||||
**Children are plugin instances, not library calls.** Each enabled entry mounts `dsh-mcp-client` under the manager's fiber via `ctx.plugin()`. That reuses the tested activation/disposal semantics, makes `serverName` reservations collide correctly with statically composed instances (surfaced as a `failed`/`load` status with the actionable message), and lets manager disposal unwind every instance and its tools through ordinary fiber teardown.
|
||||
**Children are plugin instances, not library calls.** Each enabled entry is a `dsh-mcp-client` instance that the MCP client host mounts under the manager's fiber via `ctx.plugin()`. That reuses the tested activation/disposal semantics, makes `serverName` reservations collide correctly with statically composed instances (surfaced as a `failed`/`load` status with the actionable message), and lets manager disposal unwind every instance and its tools through ordinary fiber teardown.
|
||||
|
||||
**The MCP client host is the manager's only reach into mcp-client.** The manager creates an `McpClientHost` at construction and imports only that class and mcp-client types. The host validates an entry's client fields through each transport's own schema, so refusals still name the field; mounts instances under the manager's fiber; probes; and creates authorization owners from the manager's context. A plugin entry exports what the Loader loads and its Service and error classes, so the host is a Service class rather than a set of functions.
|
||||
|
||||
**Whole-entry identity; `enabled` controls mounting.** A changed entry rebuilds the child instance; disabling or deleting it disposes the child. Reconciliation and `restart` serialize on one operation tail. Probes run independently, and configuration changes cancel affected probes before queued cleanup waits for them. The manager retains a failed cleanup record and refuses a replacement until the Host restarts, preventing overlapping server lifetimes.
|
||||
|
||||
**Status belongs to the child Fiber.** The supervisor publishes a cell read through `connectionStatusOf(fiber)`. It survives reloads of that Fiber and remains readable after disposal, which detaches observers. Fiber identity distinguishes instances across registration scopes without identity tokens in status payloads. The manager aggregates cells into `list()` and the `mcp-manager/status` event, absorbing equal statuses and remaining silent after disposal. Removed entries with incomplete cleanup remain listed with `configured: false`. The first reconcile waits for the manager’s own Fiber activation because strict service reads require an active Fiber.
|
||||
**Status belongs to the child Fiber.** The supervisor publishes a cell that the host's `mount` hands to the manager once the instance activates. It survives reloads of that Fiber and remains readable after disposal, which detaches observers. Fiber identity distinguishes instances across registration scopes without identity tokens in status payloads. The manager aggregates cells into `list()` and the `mcp-manager/status` event, absorbing equal statuses and remaining silent after disposal. Removed entries with incomplete cleanup remain listed with `configured: false`. The first reconcile waits for the manager’s own Fiber activation because strict service reads require an active Fiber.
|
||||
|
||||
**Templates keep secrets out of configuration.** Stored env and header values remain readable; a value that must stay hidden belongs in a template. The manager passes raw templates into the child Fiber. Opt-in mcp-client expansion resolves `${credential:REF}` from the current provider, whose local implementation also reads the inherited environment, so there is no separate environment scheme. Missing values leave non-strict clients waiting for credentials; referenced credential notifications can recover them. A changed value replaces the connection only after cleanup succeeds, while a same-value notification preserves the connection and retry budget. Diagnostics, tool-call failures, and `isError` results keep upstream text with every resolved value replaced by `[redacted]`, so the model can act on a server's error without seeing a secret the instance sent.
|
||||
|
||||
**mcp-client budgets and probe.** `startupTimeoutMs` is optional for standalone clients; the manager explicitly supplies a 30-second default. `probeServer(ctx, config, options)` connects, reads server identity, lists tool names, and closes without reserving a name or registering tools. Its own budget and configurable listing caps are independent of runtime startup. Probe success and transport closure are separate results, so successful discovery cannot hide incomplete cleanup.
|
||||
**mcp-client budgets and probe.** `startupTimeoutMs` is optional for standalone clients; the manager explicitly supplies a 30-second default. The host's `probe(config, options)` connects, reads server identity, lists tool names, and closes without reserving a name or registering tools. Its own budget and configurable listing caps are independent of runtime startup. Probe success and transport closure are separate results, so successful discovery cannot hide incomplete cleanup.
|
||||
|
||||
**The manager is its own Remote surface.** `McpServerManager` is a Typert Remote service: `watch` streams the complete server list on subscription and after every status or entry change, and `restart` and `probe` call the Host operations. Configuration writes remain on the Settings Remote, and the manager exposes no write method, so a browser cannot define a server command.
|
||||
|
||||
OAuth is deliberately out of scope: the credential-record and authorization seams plus the MCP SDK's `OAuthClientProvider` are the intended home, and a `needs-auth` status state is reserved for that change.
|
||||
**OAuth stays on the credential and authorization seams.** The MCP SDK's `OAuthClientProvider` runs inside mcp-client: passive connections use committed grants and enter `waiting-authorization` when none is usable, while explicit sign-in runs through the manager's `startAuthorization` and the authorization seam. Each entry owns one stable `mcp-client/<id>` credential key.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
@@ -48,6 +50,12 @@ OAuth is deliberately out of scope: the credential-record and authorization seam
|
||||
|
||||
**Poll status from the management surface.** Rejected: the Remote plane already forwards Host events; peers that shipped polling (Reasonix) or lacked a status event (OpenCode v1) treat it as a defect to fix.
|
||||
|
||||
**Export validation, probe, status, and authorization values from the mcp-client entry.** Rejected: plugin entries export what the Loader loads and their Service and error classes, not helper values.
|
||||
|
||||
**Load the host as its own mcp-client entry with `host: true` that the manager injects.** Rejected: every composition that loads the manager would need a second row, and the client's configuration would carry a shape that connects no server. Its only gain, a manager that restarts when mcp-client reloads during development, does not justify either.
|
||||
|
||||
**Move the connection machinery into a separate service package.** Rejected: per-server mcp-client instances use the same machinery, so every composition that loads mcp-client would also have to load the new service.
|
||||
|
||||
**A capability seam (Definition/Provider/Consumer) for "MCP management".** Rejected: one implementation and no independently evolving roles; a seam without a second provider is structure without an owner.
|
||||
|
||||
## Testing
|
||||
@@ -60,4 +68,5 @@ mcp-client unit tests cover status transitions, independent startup and probe bu
|
||||
- Liveness relies on transport closure and request failures; a Streamable HTTP server that stalls without closing is noticed when a request fails.
|
||||
- A rebuilt server’s tools remain unavailable until the replacement completes its initial sync. Replacement waits for confirmed transport closure and successful local cleanup.
|
||||
- The manager governs the global plane only; preset-scoped and static instances stay outside its list.
|
||||
- The manager keeps the mcp-client code it loaded until the manager itself reloads; a development reload of mcp-client alone does not restart it.
|
||||
- `startupTimeoutMs` bounds startup attempts, while notification-driven re-sync requests still ride the SDK's request default — recorded as an mcp-client limitation.
|
||||
@@ -20,19 +20,21 @@ Status: implemented
|
||||
|
||||
**扁平条目 schema,跨字段校验。** 条目是带 `transport` 判别字段的扁平结构,写入期校验在写入处强制逐传输要求与拒绝(缺 `command`/`url`、跨传输字段、模板写错)——schema 合法但不可执行的条目永远不会被存下,且拒绝会点名出错字段,union 的形状错误做不到。
|
||||
|
||||
**子实例是插件实例,不是库调用。** 每个启用条目经 `ctx.plugin()` 在管理器 fiber 下挂载 `dsh-mcp-client`。这复用了经过测试的激活/销毁语义,让 `serverName` 预留与静态组合实例正确冲突(以带可操作消息的 `failed`/`load` 状态浮出),并让管理器销毁经普通 fiber 收卷解除每个实例及其工具。
|
||||
**子实例是插件实例,不是库调用。** 每个启用条目都是 MCP 客户端宿主经 `ctx.plugin()` 挂在管理器 fiber 下的 `dsh-mcp-client` 实例。这复用了经过测试的激活/销毁语义,让 `serverName` 预留与静态组合实例正确冲突(以带可操作消息的 `failed`/`load` 状态浮出),并让管理器销毁时经普通 fiber 收卷撤下每个实例及其工具。
|
||||
|
||||
**MCP 客户端宿主是管理器接触 mcp-client 的唯一途径。** 管理器在构造时创建 `McpClientHost`,并且只从 mcp-client 导入这个类和类型。宿主用各传输自己的 schema 校验条目的客户端字段,因此拒绝时仍点名字段;它把实例挂在管理器的 fiber 下、执行探测,并用管理器的 context 创建授权所有者。插件入口只导出 Loader 加载的内容及其 Service 与错误类,因此宿主是一个 Service 类,而不是一组函数。
|
||||
|
||||
**整条目决定实例;`enabled` 控制挂载。** 条目变化会重建子实例,停用或删除条目会销毁子实例。对账与 `restart` 在同一操作队列中串行执行。探测独立运行,配置变更先取消受影响的探测,再由队列中的清理操作等待它们结束。管理器保留清理失败记录,并在 Host 重启前拒绝替换,防止服务器生命周期重叠。
|
||||
|
||||
**状态属于子 Fiber。** 监督器发布经 `connectionStatusOf(fiber)` 读取的状态单元。同一 Fiber 重载时保留该单元,最终销毁时移除观察者,但单元仍可读取。Fiber 身份直接区分不同注册作用域中的实例,无需在状态载荷中加入身份令牌。管理器聚合为 `list()` 和 `mcp-manager/status` 事件,吸收相等状态并在销毁后停止发出事件。配置已删除但清理未完成的条目仍以 `configured: false` 列出。首次对账等待管理器自身 Fiber 激活,因为严格服务读取要求 Fiber 已激活。
|
||||
**状态属于子 Fiber。** 监督器发布状态单元,实例激活后由宿主的 `mount` 交给管理器。同一 Fiber 重载时保留该单元,最终销毁时移除观察者,但单元仍可读取。Fiber 身份直接区分不同注册作用域中的实例,无需在状态载荷中加入身份令牌。管理器聚合为 `list()` 和 `mcp-manager/status` 事件,吸收相等状态并在销毁后停止发出事件。配置已删除但清理未完成的条目仍以 `configured: false` 列出。首次对账等待管理器自身 Fiber 激活,因为严格服务读取要求 Fiber 已激活。
|
||||
|
||||
**模板让密钥不进入配置。** 存储的 env 和 header 值仍可读,必须隐藏的值应使用模板。管理器把原始模板传入子 Fiber。mcp-client 显式启用模板展开后,从当前 provider 解析 `${credential:REF}`;其本地实现也读取继承的环境变量,因此没有单独的环境变量模板。缺失值使非严格客户端等待凭据,相关凭据通知可恢复连接。值变化时,连接只有在清理成功后才会替换;同值通知保留当前连接和重试预算。诊断、工具调用失败与 `isError` 结果保留上游文本,其中每个已解析的值都替换为 `[redacted]`,模型因此能依据服务器的错误行动,又看不到实例发送过的密钥。
|
||||
|
||||
**mcp-client 预算与探测。** 独立客户端的 `startupTimeoutMs` 可省略,管理器明确提供 30 秒默认值。`probeServer(ctx, config, options)` 连接、读取服务器身份、列出工具名并关闭,不预留名称,也不注册工具。探测有独立于运行期启动的预算和可配置的列表上限。探测成功与传输关闭分别报告,因此发现成功不会掩盖清理未完成。
|
||||
**mcp-client 预算与探测。** 独立客户端的 `startupTimeoutMs` 可省略,管理器明确提供 30 秒默认值。宿主的 `probe(config, options)` 连接、读取服务器身份、列出工具名并关闭,不预留名称,也不注册工具。探测有独立于运行期启动的预算和可配置的列表上限。探测成功与传输关闭分别报告,因此发现成功不会掩盖清理未完成。
|
||||
|
||||
**管理器自身即 Remote 面。** `McpServerManager` 是 Typert Remote 服务:`watch` 在订阅时以及每次状态或条目变化后推送完整服务器列表,`restart` 与 `probe` 调用宿主操作。配置写入仍走 Settings Remote,管理器不提供写入方法,因此浏览器无法定义服务器命令。
|
||||
|
||||
OAuth 刻意不在本次范围内:凭据记录与 authorization seam 加 MCP SDK 的 `OAuthClientProvider` 是预期归宿,`needs-auth` 状态位为那次变更保留。
|
||||
**OAuth 留在凭据与 authorization seam 上。** MCP SDK 的 `OAuthClientProvider` 在 mcp-client 内运行:被动连接只使用已提交的授权,没有可用授权时进入 `waiting-authorization`;显式登录经管理器的 `startAuthorization` 与 authorization seam 完成。每个条目拥有一个稳定的 `mcp-client/<id>` 凭据 key。
|
||||
|
||||
## 曾考虑的替代方案
|
||||
|
||||
@@ -48,6 +50,12 @@ OAuth 刻意不在本次范围内:凭据记录与 authorization seam 加 MCP S
|
||||
|
||||
**让管理界面轮询状态。** 否决:Remote 面已转发宿主事件;发货了轮询的同类产品(Reasonix)或缺状态事件的(OpenCode v1)都把它当作待修缺陷。
|
||||
|
||||
**从 mcp-client 入口导出校验、探测、状态与授权的值。** 否决:插件入口只导出 Loader 加载的内容及其 Service 与错误类,不导出辅助值。
|
||||
|
||||
**把宿主作为以 `host: true` 加载、由管理器注入的独立 mcp-client 条目。** 否决:每个加载管理器的组合都得多一行,客户端配置也要多出一种不连接任何服务器的形态。它唯一的好处是开发期 mcp-client 重载时管理器随之重启,不足以抵消这两点。
|
||||
|
||||
**把连接机制移到单独的服务包。** 否决:每台服务器的 mcp-client 实例使用同一套机制,因此所有加载 mcp-client 的组合都得额外加载这个新服务。
|
||||
|
||||
**为「MCP 管理」开 capability seam(Definition/Provider/Consumer)。** 否决:只有一个实现、没有独立演化的角色;没有第二个 provider 的 seam 是无主的结构。
|
||||
|
||||
## 测试
|
||||
@@ -60,4 +68,5 @@ mcp-client 单测覆盖状态迁移、独立的启动与探测预算、模板绑
|
||||
- 存活判断依赖传输关闭与请求失败;停滞但不关闭的 Streamable HTTP 服务器要等到请求失败时才会被发现。
|
||||
- 被重建服务器的工具在替换连接完成首次同步前不可用。替换会等待传输确认关闭且本地清理成功。
|
||||
- 管理器只治理全局面;preset 作用域与静态实例不在其列表内。
|
||||
- 管理器沿用它加载的 mcp-client 代码,直到管理器自身重载;开发期只重载 mcp-client 不会重启管理器。
|
||||
- `startupTimeoutMs` 只为启动尝试设界,通知驱动的重同步请求仍走 SDK 请求默认值——已记录为 mcp-client 的限制。
|
||||
+4
-4
@@ -18,8 +18,8 @@
|
||||
en: e7cae8876e688f92
|
||||
zh: 1d326330c34d128d
|
||||
/agent-note-prompt-to-reload-when-the-host-release-changes-instead-of-hot-replacing-across-releases/decision/wire:
|
||||
en: f15c4106f228f5f6
|
||||
zh: ab80cf4ce62ae84c
|
||||
en: 387deee727dfc538
|
||||
zh: 1cae30f007f842d0
|
||||
/agent-note-prompt-to-reload-when-the-host-release-changes-instead-of-hot-replacing-across-releases/decision/page-side:
|
||||
en: c0610c8f5a0882f3
|
||||
zh: d309cbc53183ec6e
|
||||
@@ -30,5 +30,5 @@
|
||||
en: abb9d7ab9ef1df15
|
||||
zh: 1704732daf5f2886
|
||||
/agent-note-prompt-to-reload-when-the-host-release-changes-instead-of-hot-replacing-across-releases/consequences:
|
||||
en: 815b41dc4f9ffcee
|
||||
zh: b57388264cc459c7
|
||||
en: a21bf34ac3983fbb
|
||||
zh: c6278ef441587a48
|
||||
@@ -60,7 +60,7 @@ BootManifest { ...; release?: WebBootRelease }
|
||||
```
|
||||
|
||||
- [ClientModuleRegistry](../../../../packages/client/modules/src/index.ts) computes the release once at construction and `compose()` writes it into every graph; `release` stays outside `graph.rev`. There is no new config field and the composition is unchanged.
|
||||
- `__DSH_BOOT__` and every SSE `graph` frame carry the field, so one graph frame carries both the Host release and its complete module graph; the client-hmr Host half is unchanged. A rebuilt frame comes from the same Host process as the graph frame before it on that SSE connection, so it inherits that frame's release.
|
||||
- `__DSH_BOOT__` and every plugin-events `baseline` and `graph` frame carry the field, so one graph frame carries both the Host release and its complete module graph; the client-hmr Host half is unchanged. A rebuilt frame comes from the same Host process as the graph frame before it on that stream generation, so it inherits that frame's release.
|
||||
- `parseBootManifest` accepts an absent `release`, rejects a non-string `version` or `commit`, and drops members outside the identity, so equality compares only those two fields. `readRelease` reads only the `release` member of a received graph, so a page compares releases before it validates anything else; a release it cannot read counts as absent. Older pages that do not know the field ignore it.
|
||||
|
||||
### Page side
|
||||
@@ -136,8 +136,7 @@ Order of operations:
|
||||
- While the Host serves another release, plugin updates, including enabling or disabling a plugin on the Host, reach the page only after a reload.
|
||||
- When a Host returns to the page's release, only modules whose revisions differ are replaced. Revisions come from artifact metadata, so a rebuild of identical code still replaces the rebuilt modules once, without a prompt.
|
||||
- A composition without the dialog registered still pauses updates from another release and logs the warning; the user sees no prompt.
|
||||
- The API connection and SSE are independent channels, so an old page can show a protocol error before the dialog appears.
|
||||
- If a restarting Host answers `/plugins/events` with a non-200 status before registering the route, the browser closes that SSE stream for good, and the page cannot detect a release change until it reloads.
|
||||
- After a terminal plugin-events stream failure the page cannot detect a release change until it reloads.
|
||||
- A source launch without dev-web has no commit, so development detection falls back to version changes.
|
||||
- Each tab prompts and remembers independently.
|
||||
- Unit tests pin the gate through `ClientEntries` (same-release replacement, another release applying nothing, the return to the boot release replacing only changed modules, dismissal, absent releases), the manifest parser, the Host-published release, the shared preset's Node-half defines, and the dialog's rendering and callbacks.
|
||||
+2
-3
@@ -60,7 +60,7 @@ BootManifest { ...; release?: WebBootRelease }
|
||||
```
|
||||
|
||||
- [ClientModuleRegistry](../../../../packages/client/modules/src/index.ts) 在构造时计算一次 release,由 `compose()` 写入每个 graph;`release` 不计入 `graph.rev`。不新增配置项,组合配置不变。
|
||||
- `__DSH_BOOT__` 和每个 SSE `graph` 帧都带这个字段,所以一个 graph 帧同时携带 Host 的 release 和完整模块图;client-hmr 的 Host 半侧不变。rebuilt 帧与同一条 SSE 连接上前一个 graph 帧来自同一个 Host 进程,因此沿用那一帧的 release。
|
||||
- `__DSH_BOOT__` 和插件事件流的每个 `baseline`、`graph` 帧都带这个字段,所以一个 graph 帧同时携带 Host 的 release 和完整模块图;client-hmr 的 Host 半侧不变。rebuilt 帧与同一代流上前一个 graph 帧来自同一个 Host 进程,因此沿用那一帧的 release。
|
||||
- `parseBootManifest` 允许 `release` 缺省,拒绝非字符串的 `version` 或 `commit`,并丢弃身份以外的成员,因此相等判断只看这两个字段。`readRelease` 只读取收到的 graph 的 `release` 成员,所以页面先比较 release,再校验其余内容;读不出的 release 视为缺省。不认识该字段的旧页面会忽略它。
|
||||
|
||||
### 页面侧
|
||||
@@ -136,8 +136,7 @@ class ClientEntries {
|
||||
- Host 提供其他 release 期间,插件更新(包括在 Host 上启用或停用插件)要等刷新后才会到达页面。
|
||||
- Host 回到页面的 release 时,只替换 revision 不同的模块。revision 取自产物元数据,所以即使重新构建出的代码完全相同,也会把重建过的模块替换一次,不弹框。
|
||||
- 组合里没有注册确认框时,仍会暂停来自其他 release 的更新并记录警告,用户看不到提示。
|
||||
- API 连接和 SSE 是两条独立通道,旧页面可能在确认框出现之前就已显示协议错误。
|
||||
- 重启中的 Host 若在注册路由前对 `/plugins/events` 返回非 200 状态,浏览器会永久关闭这条 SSE,页面在刷新前检测不到 release 变化。
|
||||
- 插件事件流以终止性错误结束后,页面在刷新前检测不到 release 变化。
|
||||
- 不经 dev-web 的源码启动没有 commit,开发期只能检测到版本号变化。
|
||||
- 每个标签页各自提示、各自记录。
|
||||
- 单元测试通过 `ClientEntries` 固定 gate 的行为(同一 release 的替换、其他 release 不应用任何内容、回到启动 release 只替换变化了的模块、撤回、缺失 release),并覆盖 manifest 解析、Host 发布的 release、共享预设给 Node 半侧的 define,以及确认框的渲染与回调。
|
||||
@@ -27,8 +27,8 @@
|
||||
en: 0dcc97d8105fab60
|
||||
zh: d80d40ae3a0c601d
|
||||
/agent-note-direct-deepseek-search-and-fetch-apis/alternatives-considered:
|
||||
en: 021a4b08ad534b36
|
||||
zh: e98e1f65e50a568b
|
||||
en: e377ad3c0327300e
|
||||
zh: 4b9f7f83f464e657
|
||||
/agent-note-direct-deepseek-search-and-fetch-apis/consequences:
|
||||
en: 7ec21c5b1124e5f8
|
||||
zh: af769dbdb4face9f
|
||||
|
||||
@@ -52,7 +52,7 @@ The independent `dsh-web-search-deepseek` provider sends Messages search request
|
||||
|
||||
**Keep the APIs inside the Messages provider behind a provider-local switch.** A switch inside the Messages provider cannot change fetch routing, so `web_fetch` would stay on HTTP unless the user also edited `web.fetchProvider`; it also ties the APIs' lifecycle to Messages search. Separate registrations let the web service's existing selection choose each provider, without coupling either API to the Messages provider.
|
||||
|
||||
**Share one transport between Messages search and the new APIs.** A shared web transport would couple different request formats and failure mappings. Credential values instead come from the credentials the model routes publish through `ctx.llm.providerCredential()` and from the `dsh-credentials` reference helpers; Messages search and the Search/Fetch API transports remain independent.
|
||||
**Share one transport between Messages search and the new APIs.** A shared web transport would couple different request formats and failure mappings. Credentials instead come from one service, `ctx.deepseekAuth`, which releases the request headers of the API key or the account sign-in; Messages search and the Search/Fetch API transports remain independent.
|
||||
|
||||
**Split Search and Fetch into separate packages.** The guide serves both APIs from one base with one credential; separate packages would duplicate settings that address one deployment. Independent selection does not require separate packages, because each API registers its own provider id. Each operation lives in its own module, so either API can change without the other.
|
||||
|
||||
|
||||
@@ -52,7 +52,7 @@ HTTP 提供方继续负责自身的 URL 校验和资源限制。选择 DeepSeek
|
||||
|
||||
**把两个 API 放在 Messages 提供方内部,由提供方自己的开关切换。** Messages 提供方内的开关无法改变抓取路由,因此除非用户另外修改 `web.fetchProvider`,`web_fetch` 仍会走 HTTP;它还会把两个 API 的生命周期绑在 Messages 搜索上。独立注册让 Web 服务通过现有的提供方选择机制选择各个提供方,不会把任一 API 与 Messages 提供方绑定。
|
||||
|
||||
**让 Messages 搜索与新 API 共用一套传输层。** 共享 Web 传输层会耦合不同的请求格式和失败映射。凭据值改为来自模型路由通过 `ctx.llm.providerCredential()` 发布的凭据以及 `dsh-credentials` 的引用函数;Messages 搜索与 Search/Fetch API 传输层保持独立。
|
||||
**让 Messages 搜索与新 API 共用一套传输层。** 共享 Web 传输层会耦合不同的请求格式和失败映射。凭据改为来自同一个服务 `ctx.deepseekAuth`,它释放 API 密钥或账号登录凭据的请求头;Messages 搜索与 Search/Fetch API 传输层保持独立。
|
||||
|
||||
**把 Search 和 Fetch 拆成两个包。** 指南从同一基础地址、以同一份凭据提供两个 API;拆成两个包会让指向同一部署的设置重复出现。分别选择不需要拆包,因为每个 API 注册自己的提供方 id。每种操作位于独立模块,任一 API 都可以单独修改。
|
||||
|
||||
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
# Bilingual-pair consistency record for 2026-11-17-live-subagent-model-selection-setting.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-11-17-live-subagent-model-selection-setting.md
|
||||
/agent-note-live-subagent-model-selection-setting:
|
||||
en: 01cc7a22f888d43f
|
||||
zh: 7e8db3cb85eb61e5
|
||||
/agent-note-live-subagent-model-selection-setting/problem:
|
||||
en: 63a11d729aada846
|
||||
zh: a54b5069bb176440
|
||||
/agent-note-live-subagent-model-selection-setting/decision:
|
||||
en: e6ea827eaf115283
|
||||
zh: 994dd77261bc9f4c
|
||||
/agent-note-live-subagent-model-selection-setting/alternatives-considered:
|
||||
en: 864544c31f8f92bc
|
||||
zh: 3fbab0d1567228eb
|
||||
/agent-note-live-subagent-model-selection-setting/consequences:
|
||||
en: 3035a4f2981e01b9
|
||||
zh: 4b1f84b26258470c
|
||||
@@ -0,0 +1,30 @@
|
||||
# Agent Note: Live subagent model-selection setting
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-11-17-live-subagent-model-selection-setting.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
[User-authorized subagent model routes](2026-08-24-user-authorized-subagent-model-routes.md) snapshotted the Host allowlist into each fresh top-level Session as `subagent/model-selection-policy`. A user who enabled the setting, added a route, or revoked one in the middle of a Session saw no effect until a new Session started; restored Sessions kept whatever list their creation recorded. The setting's observable meaning depended on when each Session was created, which the settings page could not explain.
|
||||
|
||||
## Decision
|
||||
|
||||
`SubagentModelSelectionConfig.allowedRoutes()` reads the volatile `enabled` value at each call and returns `undefined` immediately when selection is disabled; otherwise it validates `allowedModels` and returns a detached route list. The `subagent` executor and `list_subagent_models` call it through `ctx.get('subagentModelSelection')` for explicit route selection by model-selectable tools and for every discovery call, so an edit applies to the next call in every running, restored, and child Session. When the service is absent or the setting is disabled, explicit selection permits only the current parent route, as before.
|
||||
|
||||
No Session event is appended and no projection is registered. The `subagent/model-selection-policy` declaration remains so released Session logs still validate, but no code reads it; a Session that recorded a policy follows the current setting. An enabled setting with an empty, malformed, or repeated route list fails each call that reads it with `INVALID_MODEL_SELECTION_SETTINGS` rather than rejecting Agent creation. Ordinary delegation and tools with model selection disabled do not read the list.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**Keep the creation-time snapshot.** Rejected because the user-visible setting is a standing authorization, and an edit that silently skips every open Session reads as a broken control. The earlier note's concern that an edit changes a running Session's capabilities is the requested behavior.
|
||||
|
||||
**Record a new policy event whenever the setting changes.** Rejected because it would append to every live Session on each settings save, still miss restored Sessions until they load, and leave two sources that could disagree. The allowlist is not model-visible input: the tool schemas are fixed, and only a `list_subagent_models` result or a delegation error reaches the model, and both are logged as tool results.
|
||||
|
||||
**Honor a recorded policy when present and fall back to the setting.** Rejected because an old Session would then ignore later edits, recreating the inconsistency for exactly the Sessions users resume most.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Revoking a route takes effect at the next call, including for children of a running parent; a route that was allowed earlier in the transcript can now be rejected with `MODEL_ROUTE_NOT_ALLOWED`.
|
||||
- Replaying a Session no longer reproduces its authorization from the log alone; the tool results in the log still show what the model saw.
|
||||
- Agent creation no longer depends on the setting service, so an invalid setting cannot block Sessions without delegation tools.
|
||||
- Unit tests in `packages/subagent/tool-subagent/tests/model-selection-settings.spec.ts` pin live reads, mid-Session edits in parent and child Sessions, and that a recorded policy is ignored.
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
# Agent Note: 实时读取的 subagent 模型选择设置
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-11-17-live-subagent-model-selection-setting.md) | 中文
|
||||
|
||||
## Problem
|
||||
|
||||
[用户授权的 subagent 模型路由](2026-08-24-user-authorized-subagent-model-routes.zh.md)把 Host 允许列表快照到每个新顶层 Session 的 `subagent/model-selection-policy` 中。用户在 Session 进行中启用设置、添加路由或撤销路由后,要到新 Session 开始才会生效;恢复的 Session 保留其创建时记录的列表。设置的可见含义取决于每个 Session 的创建时间,设置页无法解释这一点。
|
||||
|
||||
## Decision
|
||||
|
||||
`SubagentModelSelectionConfig.allowedRoutes()` 在每次调用时读取 volatile 的 `enabled`;选择关闭时立即返回 `undefined`,否则校验 `allowedModels` 并返回独立的路由列表。`subagent` 执行器和 `list_subagent_models` 在允许模型选择的工具显式选择路由时、每次发现调用时通过 `ctx.get('subagentModelSelection')` 调用它,因此设置编辑会对所有运行中、已恢复和子 Session 的下一次调用生效。服务缺失或设置关闭时,显式选择与之前一样只允许当前父级路由。
|
||||
|
||||
不追加 Session 事件,也不注册投影。`subagent/model-selection-policy` 声明保留,使已发布的 Session 日志仍能通过校验,但没有代码读取它;记录过策略的 Session 遵循当前设置。启用但路由列表为空、格式无效或重复时,读取该设置的每次调用都会以 `INVALID_MODEL_SELECTION_SETTINGS` 失败,而不是使 Agent 创建失败。普通委派和关闭模型选择的工具不读取该列表。
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**保留创建时快照。** 不采用,因为用户可见的设置是持续生效的授权,编辑后静默跳过所有已打开的 Session,看起来就是控件失效。旧 Agent Note 担心编辑会改变运行中 Session 的能力,而这正是所需行为。
|
||||
|
||||
**设置变更时记录新的策略事件。** 不采用,因为每次保存设置都要向所有在线 Session 追加事件,已恢复的 Session 在加载前仍会遗漏,并留下两个可能不一致的来源。允许列表不是模型可见输入:工具 schema 固定,只有 `list_subagent_models` 结果或委派错误会到达模型,两者都作为工具结果记录在日志中。
|
||||
|
||||
**存在已记录策略时沿用它,否则回退到设置。** 不采用,因为旧 Session 会因此忽略之后的编辑,恰好在用户最常恢复的 Session 上重现不一致。
|
||||
|
||||
## Consequences
|
||||
|
||||
- 撤销路由在下一次调用时生效,包括运行中父级的子级;transcript 早先允许的路由现在可能以 `MODEL_ROUTE_NOT_ALLOWED` 被拒绝。
|
||||
- 重放 Session 时不能仅凭日志重现其授权;日志中的工具结果仍显示模型看到的内容。
|
||||
- Agent 创建不再依赖设置服务,因此无效设置不会阻塞没有委派工具的 Session。
|
||||
- `packages/subagent/tool-subagent/tests/model-selection-settings.spec.ts` 中的单元测试固定实时读取、父子 Session 中途编辑生效,以及忽略已记录策略。
|
||||
@@ -0,0 +1,19 @@
|
||||
# Bilingual-pair consistency record for 2026-11-17-sidebar-scrollbar-fade-in-css.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-11-17-sidebar-scrollbar-fade-in-css.md
|
||||
/agent-note-the-sidebar-scrollbar-s-delay-and-fade-live-in-a-css-transition:
|
||||
en: 9b7623eb8949b421
|
||||
zh: d70020274d864676
|
||||
/agent-note-the-sidebar-scrollbar-s-delay-and-fade-live-in-a-css-transition/problem:
|
||||
en: 88d0ec7e97d4d94a
|
||||
zh: 23f3baf3e0a8bdf2
|
||||
/agent-note-the-sidebar-scrollbar-s-delay-and-fade-live-in-a-css-transition/decision:
|
||||
en: 5e1bbaf2825ceac7
|
||||
zh: 7c39baf282e8d63b
|
||||
/agent-note-the-sidebar-scrollbar-s-delay-and-fade-live-in-a-css-transition/alternatives-considered:
|
||||
en: 484736bb70e14bbc
|
||||
zh: 9101a98c7f6be310
|
||||
/agent-note-the-sidebar-scrollbar-s-delay-and-fade-live-in-a-css-transition/consequences:
|
||||
en: 63f48085261affd8
|
||||
zh: 88db30f2ee8a8928
|
||||
@@ -0,0 +1,39 @@
|
||||
# Agent Note: The sidebar scrollbar's delay and fade live in a CSS transition
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-11-17-sidebar-scrollbar-fade-in-css.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
The sidebar draws its scrollbar thumb only while the pointer is over the column. [The pointer-revealed scrollbar note](../../archived/feature/2026-08-04-pointer-revealed-sidebar-scrollbars.md) shipped this with a 2-second JavaScript timer after the leave, and the thumb then vanished in one step. Product review asked for a 500ms hold followed by a visible fade (Issue #7921). That note rejected expressing the delay as a CSS transition; this note reverses that rejection.
|
||||
|
||||
## Decision
|
||||
|
||||
ui-theme registers `--dsh-scrollbar-thumb` and `--dsh-scrollbar-thumb-hover` with `@property` as inherited `<color>` properties whose initial value is `transparent`, so a rebinding of the pair can be transitioned. `SidebarRoot` adds `quietBars` as soon as the pointer is outside the column box and keeps no timer. The `.root.quietBars` rule rebinds both properties to `transparent` with `transition: … 200ms linear 500ms`. The base `.root` rule declares no transition, so a reveal is immediate, and a pointer that returns during the delay removes the class before the colour moves. Under `prefers-reduced-motion: reduce`, the quiet rule sets `transition-duration: 0s`: a zero duration with a non-zero delay still starts a transition, so the thumb holds for 500ms and then switches in one frame.
|
||||
|
||||
The transition runs on the column's custom property, not on a scrollbar pseudo-element. The WebKit thumb's `background: var(--dsh-scrollbar-thumb)` and Firefox's per-element `scrollbar-color` read the property's current animated value at each style update. In Chromium, `apps/web/tests/sidebar-scrollbar.e2e.ts` samples the resolved colour once per animation frame and sees the hold followed by the fade; with the reduced-motion rule removed, the reduced-motion case observes intermediate colours and fails.
|
||||
|
||||
The fade is linear over 200ms, the timing SimpleBar uses. An eased 100ms fade of this pale thumb completes most of its change within a few frames and reads as a cut.
|
||||
|
||||
Inside or outside is decided by the column's box on every `pointerenter` and `pointermove` that reaches the column, because the Settings panel is a fixed-position descendant and the column's menus are React portals: a pointer over them fires no `pointerleave` here while their moves still bubble to the column. The column's own `pointerleave` covers a pointer that leaves the window.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**Keep the JavaScript timer and add only a CSS fade.** It needs the same `@property` registration for the fade and keeps a timer, its cancellation, and unmount cleanup in the component. Moving the delay into `transition-delay` removes that state and keeps both timings in one declaration.
|
||||
|
||||
**Leave the properties unregistered.** An unregistered custom property switches in one step, so no transition can hold or fade the colour.
|
||||
|
||||
**Draw an app-owned thumb element and fade its `opacity`.** It gives any fade curve in every engine and costs hit-testing, dragging, wheel, momentum, and hover styling of a replacement scrollbar, which the pointer-revealed scrollbar note already rejected for a cosmetic gain.
|
||||
|
||||
**Hide the bar with `scrollbar-width: none` or `display: none` on `::-webkit-scrollbar`.** It releases the reserved gutter, so revealing the bar would shift every row sideways.
|
||||
|
||||
## Consequences
|
||||
|
||||
The registration is global: every surface that reads the pair now inherits a computed `<color>` instead of the token text, and a value that is not a colour falls back to `transparent` rather than leaving the declaration invalid. Only `.root.quietBars` declares a transition, so other surfaces change neither timing nor colour; the scrollbar geometry golden is unchanged in both palettes.
|
||||
|
||||
The component lost its timer, its document-level listener, and their cleanup. The delay and duration are stated once in the stylesheet, and `scrollbar-quiet-styles.client.spec.ts` pins the exact `transition` value.
|
||||
|
||||
The fade is verified only in Chromium. Safari renders through the same WebKit pseudo-elements; if it does not repaint the thumb during the transition, the thumb holds and then disappears after about 700ms, so the delay still applies without a visible fade.
|
||||
|
||||
A leave during a sidebar collapse or expand hides the thumb at once, because the collapse rule's `transition: width` declaration takes precedence over the quiet rule's.
|
||||
@@ -0,0 +1,39 @@
|
||||
# Agent Note: 侧栏滚动条的延迟与淡出由 CSS 过渡实现
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-11-17-sidebar-scrollbar-fade-in-css.md) | 中文
|
||||
|
||||
## 问题
|
||||
|
||||
侧栏只在指针位于栏内时绘制滚动条滑块。[指针显示滚动条的 Agent Note](../../archived/feature/2026-08-04-pointer-revealed-sidebar-scrollbars.md) 以离开后 2 秒的 JavaScript 定时器实现了这一行为,之后滑块一步消失。产品评审要求离开后保留 500ms,再明显地淡出(Issue #7921)。那篇 Agent Note 否决了用 CSS 过渡表达延迟;本 Agent Note 推翻这一否决。
|
||||
|
||||
## 决策
|
||||
|
||||
ui-theme 通过 `@property` 把 `--dsh-scrollbar-thumb` 与 `--dsh-scrollbar-thumb-hover` 注册为可继承的 `<color>` 属性,初始值为 `transparent`,因此这组变量的重新绑定可以过渡。`SidebarRoot` 在指针一离开栏的矩形范围时就加上 `quietBars`,不再持有定时器。`.root.quietBars` 规则把两个属性重新绑定为 `transparent`,并带有 `transition: … 200ms linear 500ms`。基础 `.root` 规则不声明过渡,因此显示是立即的;指针在延迟期间返回时,class 在颜色变化前就被移除。在 `prefers-reduced-motion: reduce` 下,隐藏规则设置 `transition-duration: 0s`:时长为零而延迟非零时过渡仍会启动,因此滑块保留 500ms 后在一帧内切换。
|
||||
|
||||
过渡发生在栏元素的自定义属性上,而不是滚动条伪元素上。WebKit 滑块的 `background: var(--dsh-scrollbar-thumb)` 与 Firefox 按元素声明的 `scrollbar-color` 在每次样式更新时读取该属性当前的动画值。在 Chromium 中,`apps/web/tests/sidebar-scrollbar.e2e.ts` 逐个动画帧采样解析后的颜色,能观察到先保留、再淡出;删除减弱动态效果规则后,减弱动态效果用例会观察到中间色并失败。
|
||||
|
||||
淡出为 200ms 线性,与 SimpleBar 的时序相同。这种浅色滑块若用 100ms 缓动淡出,大部分变化在几帧内完成,看起来像直接消失。
|
||||
|
||||
栏内或栏外由栏的矩形范围判定,对到达该栏的每次 `pointerenter` 与 `pointermove` 都会判定。原因是设置面板是固定定位的后代,栏的菜单是 React portal:指针位于其上时这里不会触发 `pointerleave`,而它们的移动事件仍会冒泡到栏。栏自身的 `pointerleave` 处理指针离开窗口的情况。
|
||||
|
||||
## 曾考虑的替代方案
|
||||
|
||||
**保留 JavaScript 定时器,只用 CSS 做淡出。** 淡出同样需要 `@property` 注册,而组件还要保留定时器、取消逻辑与卸载清理。把延迟移入 `transition-delay` 去掉了这些状态,两个时序也集中在一条声明里。
|
||||
|
||||
**不注册这两个属性。** 未注册的自定义属性一步切换,任何过渡都无法保留或淡出颜色。
|
||||
|
||||
**由应用自绘滑块元素并淡出其 `opacity`。** 它在所有引擎上都能实现任意淡出曲线,代价是要为替代滚动条承担命中测试、拖动、滚轮、惯性滚动与 hover 样式,指针显示滚动条的 Agent Note 已因收益只是外观而否决了它。
|
||||
|
||||
**用 `scrollbar-width: none` 或对 `::-webkit-scrollbar` 设置 `display: none` 隐藏滚动条。** 这会释放预留的滚动条空间,显示滚动条时每一行都会横向移动。
|
||||
|
||||
## 后果
|
||||
|
||||
注册是全局的:每个读取这组变量的表面现在继承计算后的 `<color>`,而不是 token 文本;不是颜色的值会回落为 `transparent`,而不是让声明失效。只有 `.root.quietBars` 声明了过渡,因此其他表面的时序与颜色都不变;滚动条几何基准快照在两种配色下均未变化。
|
||||
|
||||
组件去掉了定时器、document 级监听及其清理。延迟与时长只在样式表中声明一次,`scrollbar-quiet-styles.client.spec.ts` 固定了完整的 `transition` 值。
|
||||
|
||||
淡出只在 Chromium 中验证过。Safari 通过同样的 WebKit 伪元素绘制;如果它在过渡期间不重绘滑块,滑块会保留并在约 700ms 后消失,延迟依然生效,只是没有可见的淡出。
|
||||
|
||||
在侧栏折叠或展开过程中离开时,滑块会立即隐藏,因为折叠规则的 `transition: width` 声明优先于隐藏规则的声明。
|
||||
@@ -0,0 +1,34 @@
|
||||
# Bilingual-pair consistency record for 2026-11-15-client-config-sync-migration.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/proposed/architecture/2026-11-15-client-config-sync-migration.md
|
||||
/agent-note-migrate-existing-browser-configuration-reads-to-configuration-sync:
|
||||
en: 5f71cf603f0c5013
|
||||
zh: 3976607b283e68dc
|
||||
/agent-note-migrate-existing-browser-configuration-reads-to-configuration-sync/problem:
|
||||
en: 38add9dc3b90ad7e
|
||||
zh: 867e351401f537bc
|
||||
/agent-note-migrate-existing-browser-configuration-reads-to-configuration-sync/proposal:
|
||||
en: 986dd8097aac4d3d
|
||||
zh: 986dd8097aac4d3d
|
||||
/agent-note-migrate-existing-browser-configuration-reads-to-configuration-sync/proposal/inventory:
|
||||
en: 08dae763d773f24a
|
||||
zh: 15b4bd80b4973dff
|
||||
/agent-note-migrate-existing-browser-configuration-reads-to-configuration-sync/proposal/migration-rules:
|
||||
en: 72202ccc050d7e35
|
||||
zh: a809ee548e005fcb
|
||||
/agent-note-migrate-existing-browser-configuration-reads-to-configuration-sync/proposal/order:
|
||||
en: 8b8ded15f43056c0
|
||||
zh: 3ea6067ed0c3310c
|
||||
/agent-note-migrate-existing-browser-configuration-reads-to-configuration-sync/proposal/open-questions:
|
||||
en: 103a6b7dca054eb4
|
||||
zh: 55b0881eca3e08ac
|
||||
/agent-note-migrate-existing-browser-configuration-reads-to-configuration-sync/alternatives-considered:
|
||||
en: a00b894cbcff0c34
|
||||
zh: 7f2a83f36df109ec
|
||||
/agent-note-migrate-existing-browser-configuration-reads-to-configuration-sync/acceptance-criteria:
|
||||
en: 15597a6f656e7268
|
||||
zh: f17a1cfcbef0fcbd
|
||||
/agent-note-migrate-existing-browser-configuration-reads-to-configuration-sync/risks:
|
||||
en: 8f5e523d526b2026
|
||||
zh: 34a61d7c19df8650
|
||||
@@ -0,0 +1,66 @@
|
||||
# Agent Note: Migrate existing browser configuration reads to configuration sync
|
||||
|
||||
Status: proposed
|
||||
|
||||
English | [中文](2026-11-15-client-config-sync-migration.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
Before [browser plugin configuration sync](../../implemented/architecture/2026-11-15-client-config-sync.md), every package whose browser face needs Host configuration implemented its own read. These reads take effect only at page load, duplicate injection code, or use the settings editing channel as a runtime read channel. This Note inventories them and plans their migration; nothing runs before the architecture lands.
|
||||
|
||||
## Proposal
|
||||
|
||||
### Inventory
|
||||
|
||||
| Category | Use | Packages |
|
||||
|---|---|---|
|
||||
| A. Page globals carry Host configuration | `webserver/index-inject` writes `window.__DSH_*__`, read once when the browser loads | `shortcuts`, `ui-sidebar-documentpreview`, `ui-account-notifications`, `ui-settings-models` (onboarding), `ui-settings-account` (contact details), `connection` (recovery parameters) |
|
||||
| B. Runtime values read through `configForms` | The browser subscribes to accepted values of its own or another entry through the settings mirror | `ui-chat`, `ui-conversation`, `locale`, `ui-theme`, `ui-settings-account`, `ui-settings-general`, `ui-agent-preset`, experimental `timeline`, `client-ui-cot-translation`, `client-ui-forge`, `cua` |
|
||||
| C. `Config` declared only on the Client face | The browser exports a schema, but the entry never receives configuration | Done in the architecture PR: `ui-context-menu` `resolutionTimeoutMs` and `ui-conversation` `maxConcurrentFileUploads` are top-level volatile fields of their Host schemas, and the Client schemas are removed |
|
||||
| D. First-paint pre-injection | The page HTML pre-injects values to avoid a first-paint flash | `ui-theme` palette and font sizes |
|
||||
| E. Settings editing | Settings pages edit inherited values, overrides, revisions, and writability | every `ui-settings-*` card |
|
||||
|
||||
### Migration rules
|
||||
|
||||
| Category | Handling |
|
||||
|---|---|
|
||||
| A | Make the fields volatile and move the `Config` type to `src/types.ts`; the browser reads `SyncedConfig`; remove the matching `index-inject` row and global. Confirm per field that its meaning can become "changes at runtime"; `connection` needs its recovery parameters before Connection itself activates and is assessed separately |
|
||||
| B | Plugins reading their own entry read `SyncedConfig`; `configForms` keeps only writes and settings presentation. Reads of another entry's values (for example `ui-agent-preset` reading `ui-settings`) can use the read-only `ctx.config.resolveConfigByPackage(packageName)` |
|
||||
| C | Remove the browser schema and `Config` export, move the type to `src/types.ts`, and declare a volatile schema on the Host face |
|
||||
| D | Unchanged; the runtime part can be migrated separately |
|
||||
| E | Outside this migration; adjusting the settings package and `configForms` is discussed separately once the configuration sync architecture is stable |
|
||||
|
||||
### Order
|
||||
|
||||
1. The architecture Note is implemented and merged.
|
||||
2. Category C (no behavior dependency; exercises the mechanism).
|
||||
3. Category A, one package at a time.
|
||||
4. Category B, own reads first, then cross-plugin reads.
|
||||
5. A separate Note for the overall adjustment of settings and `configForms`.
|
||||
|
||||
### Open questions
|
||||
|
||||
- Which fields each package makes volatile.
|
||||
- Whether cross-plugin reads move to types inferred per package name through declaration merging.
|
||||
- The first-render timing of `connection` recovery parameters and bootstrap rows.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
| Rejected | Reason |
|
||||
|---|---|
|
||||
| Migrating in the architecture PR | Widens the review and mixes mechanism questions with per-package semantics |
|
||||
| Keeping page globals as a long-term parallel channel | Keeps two configuration sources and duplicated injection code |
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- Category A and C packages no longer export a browser `Config` schema or read Host configuration globals.
|
||||
- Category B plugins that read their own configuration no longer rely on `configForms` for runtime reads.
|
||||
- After migration, a Host change to the matching volatile field takes effect without a page reload.
|
||||
|
||||
## Risks
|
||||
|
||||
| Risk | Description |
|
||||
|---|---|
|
||||
| Changed meaning | Values that took effect only at load become runtime-changeable, and plugins must support live updates |
|
||||
| Pinned configuration | Making a field volatile brings it into the settings form's profile row, subject to the pinning rules in [profile-owned live configuration](../../implemented/architecture/2026-09-19-profile-owned-live-configuration.md) |
|
||||
| First-render timing | `connection` needs its recovery parameters before it activates, earlier than synced configuration can take part |
|
||||
@@ -0,0 +1,66 @@
|
||||
# Agent Note: 现有前端配置读取迁移到配置同步
|
||||
|
||||
Status: proposed
|
||||
|
||||
[English](2026-11-15-client-config-sync-migration.md) | 中文
|
||||
|
||||
## Problem
|
||||
|
||||
[前端插件配置同步](../../implemented/architecture/2026-11-15-client-config-sync.zh.md)落地前,浏览器需要 Host 配置的包各自实现了读取方式。这些方式只在页面加载时生效、复制注入代码,或把设置编辑通道当成运行时读取通道。本 Note 盘点这些用法并规划收编;架构落地前不执行。
|
||||
|
||||
## Proposal
|
||||
|
||||
### 盘点
|
||||
|
||||
| 类别 | 用法 | 包 |
|
||||
|---|---|---|
|
||||
| A. 页面全局变量下发 Host 配置 | `webserver/index-inject` 写 `window.__DSH_*__`,前端加载时读一次 | `shortcuts`、`ui-sidebar-documentpreview`、`ui-account-notifications`、`ui-settings-models`(引导)、`ui-settings-account`(联系方式)、`connection`(恢复参数) |
|
||||
| B. 以 `configForms` 读取运行时值 | 前端经设置镜像订阅自身或他人条目的已接受值 | `ui-chat`、`ui-conversation`、`locale`、`ui-theme`、`ui-settings-account`、`ui-settings-general`、`ui-agent-preset`、实验包 `timeline`、`client-ui-cot-translation`、`client-ui-forge`、`cua` |
|
||||
| C. 只在前端声明的 `Config` | 前端导出 schema,但条目从不收到配置 | 已在架构 PR 中完成:`ui-context-menu` 的 `resolutionTimeoutMs` 与 `ui-conversation` 的 `maxConcurrentFileUploads` 已改为 Host 顶层 volatile 字段,前端 schema 已删除 |
|
||||
| D. 首屏预注入 | 页面 HTML 预注入以避免首屏闪烁 | `ui-theme` 调色板与字号 |
|
||||
| E. 设置编辑 | 设置页编辑继承值、覆盖值、修订号、可写性 | 各 `ui-settings-*` 卡片 |
|
||||
|
||||
### 收编规则
|
||||
|
||||
| 类别 | 处理 |
|
||||
|---|---|
|
||||
| A | 字段改为 volatile,`Config` 类型移入 `src/types.ts`;前端改读 `SyncedConfig`;删除对应 `index-inject` 与全局变量。需逐字段确认语义可以变为「运行时可变」;`connection` 恢复参数在 connection 自身激活前就需要,须单独评估 |
|
||||
| B | 读取自身条目的插件改读 `SyncedConfig`;`configForms` 只保留写入与设置页呈现。读取他人条目的值(例如 `ui-agent-preset` 读 `ui-settings`)可改用只读的 `ctx.config.resolveConfigByPackage(packageName)` |
|
||||
| C | 前端删除 schema 与 `Config` 导出,类型移入 `src/types.ts`,Host 面声明 volatile schema |
|
||||
| D | 保持不变;运行时变化部分可另行收编 |
|
||||
| E | 不在本迁移范围;settings 包与 `configForms` 的调整在配置同步架构稳定后另行讨论 |
|
||||
|
||||
### 顺序
|
||||
|
||||
1. 架构 Note 实现完成并合入。
|
||||
2. 类别 C(无行为依赖,验证机制)。
|
||||
3. 类别 A,逐包进行。
|
||||
4. 类别 B,先自身读取、后跨插件读取。
|
||||
5. settings 与 `configForms` 的整体调整另起 Note。
|
||||
|
||||
### 未决
|
||||
|
||||
- 每个包选择哪些字段改为 volatile。
|
||||
- 跨插件读取是否升级为按包名声明合并推导类型。
|
||||
- `connection` 恢复参数与 bootstrap 行的首屏时序。
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
| Rejected | 理由 |
|
||||
|---|---|
|
||||
| 与架构同一 PR 迁移 | 扩大评审面,机制问题与逐包语义问题混在一起 |
|
||||
| 保留页面全局变量作为长期并行通道 | 维持两套配置来源与重复注入代码 |
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- 类别 A、C 的包不再导出前端 `Config` schema 或读取 Host 配置全局变量。
|
||||
- 类别 B 中读取自身配置的插件不再依赖 `configForms` 做运行时读取。
|
||||
- 迁移后 Host 修改对应 volatile 字段无需刷新页面即生效。
|
||||
|
||||
## Risks
|
||||
|
||||
| 风险 | 说明 |
|
||||
|---|---|
|
||||
| 语义变化 | 原本只在加载时生效的值变为运行时可变,插件需支持热更新 |
|
||||
| 配置钉住 | 字段改为 volatile 会使设置表单把它纳入 profile 行,受[实时配置](../../implemented/architecture/2026-09-19-profile-owned-live-configuration.zh.md)中的钉住规则影响 |
|
||||
| 首屏时序 | `connection` 在自身激活前就需要恢复参数,早于同步配置能参与的时间点 |
|
||||
@@ -25,7 +25,7 @@ A shared view-box change affects every consumer at its own CSS size. Inspect bot
|
||||
|
||||
For softness, check CSS dimensions and ancestor transforms, view box and drawing bounds, stroke versus filled contour, device-pixel placement, then color/opacity. Non-16 view boxes are valid; compare identical artwork before attributing sharpness to inline SVG versus sprites.
|
||||
|
||||
Use the [implemented stroke behavior](../../../../packages/client/ui-primitives/README.md#controls-and-icons): source stroke widths scale with the SVG viewport, and filled outlines scale as geometry. Do not add non-scaling strokes or convert filled contours during an ordinary placement or reuse fix. A change to that rendering contract belongs to a separately scoped library change with consumer validation; retain intentional silhouettes and knockouts.
|
||||
Use the [implemented stroke behavior](../../../../packages/client/ui-primitives/README.md#controls-and-icons): Regular line artwork retains a 1 CSS pixel stroke and Medium retains 1.3 CSS pixels as the viewport changes. Shared and inline line artwork use non-scaling strokes; intentional fills scale as geometry. Do not change that rendering behavior or convert filled contours during an ordinary placement or reuse fix. Library rendering changes require consumer validation; retain intentional silhouettes and knockouts.
|
||||
|
||||
Check straight-stroke edges at actual DPR after all scaling: center and width jointly determine coverage. Integer source coordinates alone do not guarantee crisp edges. Round positioned overlays in device pixels only when layout places otherwise crisp artwork between pixels; preserve anchoring and viewport containment. Keep antialiasing on curves/diagonals; do not globally round paths or use `crispEdges` to hide placement errors. Partial coverage is legitimate for 1.3px strokes.
|
||||
|
||||
|
||||
@@ -18,9 +18,9 @@ The [`weighted-approval` workflow](../workflows/weighted-approval.yml) publishes
|
||||
|
||||
The weighted approval workflow exposes two pull-request checks. The `weighted approval publisher` Actions job reports whether evaluation and status publication completed, while the `weighted approval` commit status carries the approval decision on the pull request head. Branch rules must require only the commit status with GitHub Actions as its expected source; a context-only requirement can accept a same-named status from another integration. The publisher marks the head pending before Python setup or lexer installation, so failed setup or an interrupted history fetch cannot leave a previous success in place. Setup and evaluation failures publish an error status. A completed evaluation returns `pending` below two approval points, while the pull request is a draft, or while a write-capable reviewer has an effective `CHANGES_REQUESTED` review; the blocker keeps the status pending even when counted approvals reach the threshold. It returns `success` only when the threshold is met, the pull request is ready, and no such blocker exists. If evaluation fails, the publisher writes an `error` status. The publisher also writes a `weighted approval decision` check run that reports the same decision as a conclusion — `action_required` while the policy is unmet, `success` when it holds, and `failure` on setup or evaluation failures — with the score or blocker in its title. Branch rules do not require that check run, so it never blocks a merge; it names the blocked state beside the status that gates the merge. The check run is published with a token minted from a dedicated approval App (`DSH_APPROVAL_APP_CLIENT_ID`, `DSH_APPROVAL_APP_PRIVATE_KEY`, `DSH_APPROVAL_APP_SLUG`, scope `checks: write`): GitHub attaches a check run created with the job token to the earliest Actions check suite on the head, and when that suite belongs to this `pull_request_target` workflow the merge box omits it, so the App identity makes the association stable. The App publishes only runs whose `app.slug` is the App; job-token runs from earlier evaluations stay untouched and can coexist on a head. When the token or slug is missing, the publisher falls back to the job token and updates job-token runs only, which keeps the label on the Checks page. The App token step runs with `continue-on-error`, so a missing App configuration fails only that step and leaves the job-token fallback; a failed check-run write is logged by the publisher and never changes the status.
|
||||
|
||||
Reviewers whose calculated base repository permission is `write` or `admin` count. The [approval policy](approval-policy.json) gives `@07akioni`, `@imccyu`, `@tianyicui`, `@tianyicui-bot`, `@turtle1999`, and `@turtle2099` two points each; every other write-capable reviewer gets one point. The pull-request author’s own review and reviewers without write permission do not count.
|
||||
Reviewers whose calculated base repository permission is `write` or `admin` count. The [approval policy](approval-policy.json) gives `@07akioni`, `@CreatixChu`, `@imccyu`, `@LegGasai`, `@tianyicui`, `@tianyicui-bot`, `@turtle1999`, and `@turtle2099` two points each; every other write-capable reviewer gets one point. The pull-request author’s own review and reviewers without write permission do not count.
|
||||
|
||||
The PR author contributes `min(100, mergedPRCount) × 11 / 1000` points: 0 merged PRs → 0 points, 50 → 0.55, and 100 or more → 1.1. The publisher counts only merged PRs in this repository using the author’s immutable account ID, excluding the current PR. It stops at 100 matches and rejects incomplete history responses. Counts refresh at the next subscribed evaluation event. Author credit is separate from reviewer approvals and cannot satisfy the two-point requirement alone; the author’s own review remains excluded. Human and bot authors, including Dependabot, use the same rule. Drafts, blocking reviews, and sufficient reviewer points skip history lookup; logs mark credit as not evaluated. Otherwise, logs show author credit and the capped count separately. Below the cap, counting may scan the repository’s entire merged history; a failed required lookup publishes an error.
|
||||
The PR author contributes `min(100, mergedPRCount) × 11 / 1000` points: 0 merged PRs → 0 points, 50 → 0.55, and 100 or more → 1.1. The publisher counts only merged PRs in this repository using the author’s immutable account ID, excluding the current PR. It stops at 100 matches and rejects incomplete history responses. Counts refresh at the next subscribed evaluation event. Author credit is separate from reviewer approvals and cannot satisfy the two-point requirement alone; the author’s own review remains excluded. Human and bot authors, including Dependabot, use the same rule, except that PRs authored by `@turtle2099` receive a fixed 0.2 points without a history lookup. Drafts, blocking reviews, and sufficient reviewer points skip history lookup; logs mark credit as not evaluated. Otherwise, logs show author credit and the capped count, or the fixed credit, separately. Below the cap, counting may scan the repository’s entire merged history; a failed required lookup publishes an error.
|
||||
|
||||
A one-point approval receives weight `min(2, 1 + 4 × ownedLines / totalLines)` from modified or deleted old production-code lines, attributed by `git blame` at the merge base of the live base branch and exact reviewed head. Ownership of 0%, 12.5%, and 25% gives 1, 1.5, and 2 points; higher ownership remains capped at 2. The success threshold remains 2 total points, without rounding the score. New lines do not enter the denominator, and an empty denominator gives no boost. Existing two-point weights remain unchanged. GitHub commit-author accounts identify reviewers across author emails; unlinked authors remain in the denominator without contributing to a reviewer. The publisher logs measured ownership. It skips attribution when reviewer points plus author credit already meet the threshold or a blocking review exists. Displayed scores use at most three decimal places; the decision uses unrounded scores with a tolerance of `1e-12` points for floating-point error. The curve endpoints come from the policy’s default and required points.
|
||||
|
||||
|
||||
@@ -3,7 +3,9 @@
|
||||
"defaultPoints": 1,
|
||||
"reviewerPoints": {
|
||||
"07akioni": 2,
|
||||
"CreatixChu": 2,
|
||||
"imccyu": 2,
|
||||
"LegGasai": 2,
|
||||
"tianyicui": 2,
|
||||
"tianyicui-bot": 2,
|
||||
"turtle1999": 2,
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
/** Author credit from merged pull requests in the same repository. */
|
||||
/** Author credit from merged pull requests in the same repository, or fixed points for listed logins. */
|
||||
const CAP_COUNT = 100
|
||||
/** Author points that replace merged-history credit, keyed by lowercase login. */
|
||||
export const FIXED_AUTHOR_POINTS = new Map([['turtle2099', 0.2]])
|
||||
|
||||
/**
|
||||
* Convert merged PR count to author points, capped at 1.1.
|
||||
|
||||
@@ -5,7 +5,7 @@ import process from 'node:process'
|
||||
import { pathToFileURL } from 'node:url'
|
||||
|
||||
import { productionOwnership, LOGIN } from './blame-ownership.mjs'
|
||||
import { authorCreditPoints, countMergedAuthorPulls } from './author-weight.mjs'
|
||||
import { FIXED_AUTHOR_POINTS, authorCreditPoints, countMergedAuthorPulls } from './author-weight.mjs'
|
||||
|
||||
const API_VERSION = '2026-03-10'
|
||||
const MAX_PULL_REQUEST_RECORDS = 3_000
|
||||
@@ -211,7 +211,7 @@ function timestamp(value, subject) {
|
||||
/**
|
||||
* Evaluate approval points from current reviews and repository permissions.
|
||||
* @param {{event: unknown, policySource: string, api: (path: string, options?: {method?: string, body?: unknown}) => Promise<unknown>, getOwnership?: typeof productionOwnership, getMergedCount?: typeof countMergedAuthorPulls}} options Runtime inputs.
|
||||
* @returns {Promise<{pull: {repository: string, number: number, headSha: string}, state: 'pending' | 'success', description: string, points: number, authorCredit: {mergedCount: number, points: number} | null, requiredPoints: number, approvals: Array<{login: string, points: number, delegatedTo?: string, ownership?: {ownedLines: number, totalLines: number}}>, delegations: Array<{login: string, delegatedTo: string, commentId: number, reviewIds: number[], approved: boolean}>, blockers: string[], ignoredReviewers: string[]}>} Approval decision and status payload fields; approval login owns the points, delegatedTo supplies its decision, delegations contains eligible active commands and their superseded decision review IDs, and null author credit means history was not evaluated.
|
||||
* @returns {Promise<{pull: {repository: string, number: number, headSha: string}, state: 'pending' | 'success', description: string, points: number, authorCredit: {mergedCount: number | null, points: number} | null, requiredPoints: number, approvals: Array<{login: string, points: number, delegatedTo?: string, ownership?: {ownedLines: number, totalLines: number}}>, delegations: Array<{login: string, delegatedTo: string, commentId: number, reviewIds: number[], approved: boolean}>, blockers: string[], ignoredReviewers: string[]}>} Approval decision and status payload fields; approval login owns the points, delegatedTo supplies its decision, delegations contains eligible active commands and their superseded decision review IDs, null author credit means credit was not evaluated, and null mergedCount means fixed author points.
|
||||
*/
|
||||
export async function evaluateApproval({ event, policySource, api, getOwnership = productionOwnership, getMergedCount = countMergedAuthorPulls }) {
|
||||
const pull = pullRequestFromEvent(event)
|
||||
@@ -264,8 +264,9 @@ export async function evaluateApproval({ event, policySource, api, getOwnership
|
||||
let authorCredit = null
|
||||
const reviewerPoints = approvals.reduce((sum, approval) => sum + approval.points, 0)
|
||||
if (blockers.length === 0 && reviewerPoints < policy.requiredPoints) {
|
||||
const mergedCount = await getMergedCount(pull, api)
|
||||
authorCredit = { mergedCount, points: authorCreditPoints(mergedCount) }
|
||||
const fixedPoints = FIXED_AUTHOR_POINTS.get(pull.author.toLowerCase())
|
||||
const mergedCount = fixedPoints === undefined ? await getMergedCount(pull, api) : null
|
||||
authorCredit = { mergedCount, points: fixedPoints ?? authorCreditPoints(mergedCount) }
|
||||
}
|
||||
const pointsBeforeOwnership = reviewerPoints + (authorCredit?.points ?? 0)
|
||||
if (blockers.length === 0 && pointsBeforeOwnership < policy.requiredPoints
|
||||
@@ -338,7 +339,7 @@ export async function runApprovalCheck({ event, policySource, api, checkApi = ap
|
||||
throw error
|
||||
}
|
||||
write(result.authorCredit
|
||||
? `Author credit: ${result.authorCredit.points} (${result.authorCredit.mergedCount} merged PRs).`
|
||||
? `Author credit: ${result.authorCredit.points} (${result.authorCredit.mergedCount === null ? `fixed for @${pull.author}` : `${result.authorCredit.mergedCount} merged PRs`}).`
|
||||
: `Author credit: not evaluated (${pull.draft ? 'draft' : result.blockers.length ? 'blocking review' : 'reviewer points suffice'}).`)
|
||||
write(`Approval score: ${result.points}/${result.requiredPoints}.`)
|
||||
writeList(write, 'Counted approvals', result.approvals.map(({ login, points, ownership, delegatedTo }) =>
|
||||
|
||||
@@ -45,7 +45,9 @@ test('loads the repository approval score policy', () => {
|
||||
assert.equal(policy.defaultPoints, 1)
|
||||
assert.deepEqual([...policy.reviewerPoints], [
|
||||
['07akioni', 2],
|
||||
['creatixchu', 2],
|
||||
['imccyu', 2],
|
||||
['leggasai', 2],
|
||||
['tianyicui', 2],
|
||||
['tianyicui-bot', 2],
|
||||
['turtle1999', 2],
|
||||
@@ -668,6 +670,21 @@ for (const [mergedCount, credit] of [[0, 0], [1, 0.011], [50, 0.55], [99, 1.089]
|
||||
})
|
||||
}
|
||||
|
||||
test('turtle2099 contributes fixed author points without a history lookup', async () => {
|
||||
const output = []
|
||||
const result = await runApprovalCheck({
|
||||
event: pullRequestEvent({ author: 'Turtle2099' }), policySource, runUrl: 'https://github.example/run/1',
|
||||
getMergedCount: async () => { throw new Error('fixed author credit must skip history') },
|
||||
getOwnership: async () => ({ totalLines: 10, reviewerLines: { writer: 2 } }),
|
||||
api: async path => path.includes('/reviews?') ? [review('writer', 'APPROVED')] : { permission: 'write' },
|
||||
write: line => output.push(line),
|
||||
})
|
||||
assert.deepEqual(result.authorCredit, { mergedCount: null, points: 0.2 })
|
||||
assert.equal(result.approvals[0].points, 1.8)
|
||||
assert.equal(result.state, 'success')
|
||||
assert.ok(output.includes('Author credit: 0.2 (fixed for @Turtle2099).'))
|
||||
})
|
||||
|
||||
test('combines author credit and reviewer ownership at the passing threshold', async () => {
|
||||
for (let mergedCount = 0; mergedCount <= 90; mergedCount++) {
|
||||
const result = await evaluateApproval({
|
||||
|
||||
@@ -51,6 +51,7 @@ External packages installed for runtime use or embedded in distributed Host or b
|
||||
| [`@lexical/text`](https://github.com/facebook/lexical) | MIT |
|
||||
| [`@lexical/utils`](https://github.com/facebook/lexical) | MIT |
|
||||
| [`@modelcontextprotocol/client`](https://github.com/modelcontextprotocol/typescript-sdk) | MIT |
|
||||
| [`@modelcontextprotocol/core`](https://github.com/modelcontextprotocol/typescript-sdk) | MIT |
|
||||
| [`@modelcontextprotocol/sdk`](https://github.com/modelcontextprotocol/typescript-sdk) | MIT |
|
||||
| [`@modelcontextprotocol/server`](https://github.com/modelcontextprotocol/typescript-sdk) | MIT |
|
||||
| [`@noble/hashes`](https://github.com/paulmillr/noble-hashes) | MIT |
|
||||
|
||||
@@ -56,6 +56,8 @@ flowchart LR
|
||||
cfg --> plugin_dsh_base_authorization
|
||||
plugin_dsh_base_deepseek_account["deepseek-account<br/>@deepseek-ai/dsh-deepseek-account"]
|
||||
cfg --> plugin_dsh_base_deepseek_account
|
||||
plugin_dsh_base_deepseek_auth["deepseek-auth<br/>@deepseek-ai/dsh-deepseek-auth"]
|
||||
cfg --> plugin_dsh_base_deepseek_auth
|
||||
plugin_dsh_base_credentials["credentials<br/>@deepseek-ai/dsh-credentials-local"]
|
||||
cfg --> plugin_dsh_base_credentials
|
||||
plugin_dsh_base_llm_pi_ai["llm-pi-ai<br/>@deepseek-ai/dsh-llm-pi-ai"]
|
||||
@@ -84,6 +86,8 @@ flowchart LR
|
||||
cfg --> plugin_dsh_base_session_telemetry_otel
|
||||
plugin_dsh_base_subprocess["subprocess<br/>@deepseek-ai/dsh-subprocess-local"]
|
||||
cfg --> plugin_dsh_base_subprocess
|
||||
plugin_dsh_base_cli_account["cli-account<br/>@deepseek-ai/dsh-cli-account"]
|
||||
cfg --> plugin_dsh_base_cli_account
|
||||
plugin_dsh_base_sandbox["sandbox<br/>@deepseek-ai/dsh-sandbox-local"]
|
||||
cfg --> plugin_dsh_base_sandbox
|
||||
plugin_dsh_base_sandbox_policy["sandbox-policy<br/>@deepseek-ai/dsh-sandbox-policy"]
|
||||
@@ -232,6 +236,7 @@ flowchart LR
|
||||
| `settings` | `@deepseek-ai/dsh-settings` |
|
||||
| `authorization` | `@deepseek-ai/dsh-authorization` |
|
||||
| `deepseek-account` | `@deepseek-ai/dsh-deepseek-account` |
|
||||
| `deepseek-auth` | `@deepseek-ai/dsh-deepseek-auth` |
|
||||
| `credentials` | `@deepseek-ai/dsh-credentials-local` |
|
||||
| `llm-pi-ai` | `@deepseek-ai/dsh-llm-pi-ai` |
|
||||
| `session-persistence-jsonl` | `@deepseek-ai/dsh-session-persistence-jsonl` |
|
||||
@@ -246,6 +251,7 @@ flowchart LR
|
||||
| `otel` | `@deepseek-ai/dsh-otel` |
|
||||
| `session-telemetry-otel` | `@deepseek-ai/dsh-session-telemetry-otel` |
|
||||
| `subprocess` | `@deepseek-ai/dsh-subprocess-local` |
|
||||
| `cli-account` | `@deepseek-ai/dsh-cli-account` |
|
||||
| `sandbox` | `@deepseek-ai/dsh-sandbox-local` |
|
||||
| `sandbox-policy` | `@deepseek-ai/dsh-sandbox-policy` |
|
||||
| `bash-sandbox` | `@deepseek-ai/dsh-bash-sandbox` |
|
||||
|
||||
@@ -63,6 +63,7 @@
|
||||
"@deepseek-ai/dsh-schedule": "workspace:*",
|
||||
"@deepseek-ai/dsh-sdk-app": "workspace:*",
|
||||
"@deepseek-ai/dsh-sdk-minimal": "workspace:*",
|
||||
"@deepseek-ai/dsh-session-persistence-sqlite": "workspace:*",
|
||||
"@deepseek-ai/dsh-session-projection": "workspace:*",
|
||||
"@deepseek-ai/dsh-session-reference": "workspace:*",
|
||||
"@deepseek-ai/dsh-skill": "workspace:*",
|
||||
@@ -176,7 +177,8 @@
|
||||
"@types/ws": "8.18.1",
|
||||
"ajv": "^8.20.0",
|
||||
"execa": "^10.0.1",
|
||||
"ws": "8.21.3"
|
||||
"ws": "8.21.3",
|
||||
"@deepseek-ai/dsh-deepseek-auth": "workspace:*"
|
||||
},
|
||||
"exports": {
|
||||
"./profile-boot": {
|
||||
|
||||
@@ -85,14 +85,18 @@ describe('dsh run with Agent Teams enabled', () => {
|
||||
expect(files).toHaveLength(4)
|
||||
const logs = await Promise.all(files.map(file => readFile(join(sessions, file), 'utf8')))
|
||||
const parsed = logs.map(records)
|
||||
const workflowTask = [
|
||||
{ type: 'text', text: 'Agent lead sent a message: ' },
|
||||
{ type: 'text', text: 'TEAM_WORKFLOW_CHILD' },
|
||||
]
|
||||
const workflowChild = parsed.find(log => log.some(record => record.type === 'user/message'
|
||||
&& JSON.stringify((record.data as { content: unknown }).content) === JSON.stringify([{ type: 'text', text: 'TEAM_WORKFLOW_CHILD' }])))
|
||||
&& JSON.stringify((record.data as { content: unknown }).content) === JSON.stringify(workflowTask)))
|
||||
expect(workflowChild).toBeDefined()
|
||||
const workflowDescriptor = workflowChild!.find(record => record.type === 'subagent/descriptor')?.data as Record<string, unknown>
|
||||
expect(workflowDescriptor).toMatchObject({ mode: 'continuable', provider: 'spawn' })
|
||||
expect(workflowChild!.filter(record => record.type === 'user/message'
|
||||
&& (record.data as { source: { kind: string } }).source.kind === 'user').map(record => record.data))
|
||||
.toEqual([expect.objectContaining({ content: [{ type: 'text', text: 'TEAM_WORKFLOW_CHILD' }] })])
|
||||
&& (record.data as { source: { kind: string } }).source.kind === 'agent-message').map(record => record.data))
|
||||
.toEqual([expect.objectContaining({ content: workflowTask })])
|
||||
const root = parsed.find((log) => {
|
||||
const header = log[0]
|
||||
return header?.type === 'session' && typeof header.parentSession !== 'string'
|
||||
@@ -111,7 +115,8 @@ describe('dsh run with Agent Teams enabled', () => {
|
||||
expect(eventTypes).not.toContain('team/message/queued')
|
||||
expect(eventTypes).not.toContain('team/message/delivered')
|
||||
const peerMessages = parsed.flatMap(log => log.filter(record => record.type === 'user/message'
|
||||
&& (record.data as { source: { kind: string } }).source.kind === 'agent-message'))
|
||||
&& (record.data as { source: { kind: string } }).source.kind === 'agent-message'
|
||||
&& (record.data as { source: { senderSessionId: string } }).source.senderSessionId !== root![0]?.id))
|
||||
expect(peerMessages).toHaveLength(2)
|
||||
const taskEvents = root!.filter(record => record.type === 'team/task')
|
||||
expect(taskEvents.filter((record) => {
|
||||
|
||||
@@ -1263,6 +1263,7 @@ describe.skipIf(!existsSync(dshBin))('dsh BUILT bin (node lib/bin.js, no tsx)',
|
||||
['deepseek-llm-api-extensions', '@deepseek-ai/dsh-deepseek-llm-api-extensions'],
|
||||
['session-log-deepseek', '@deepseek-ai/dsh-session-log-deepseek'],
|
||||
['plugin-package-inventory-deepseek', '@deepseek-ai/dsh-plugin-package-inventory-deepseek'],
|
||||
['deepseek-auth', '@deepseek-ai/dsh-deepseek-auth'],
|
||||
['llm-deepseek', '@deepseek-ai/dsh-llm-deepseek-api-key'],
|
||||
['sandbox', '@deepseek-ai/dsh-sandbox-local'],
|
||||
['filesystem', '@deepseek-ai/dsh-fs-local'],
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
{
|
||||
"name": "cua_run_code",
|
||||
"title": "Computer use program",
|
||||
"description": "Run a TypeScript program to observe and operate desktop applications. The global cua object is ready to use; retain application and window objects across calls. Only tools.cua is available inside the program. Call other session tools directly. Use inspect(...values) to display selected text and images. The program contains TypeScript REPL statements; only erasable syntax is accepted, with no enum or namespaces. Type annotations are advisory. Top-level declarations and await are supported; top-level return is not supported. Use inspect(...values) to display output. Do not use console. Use the raw form of a template literal only for short text whose backslashes must stay exactly as written, such as a regular expression; write other text, in particular file contents and commands, as ordinary strings. Write file contents as an array of quoted strings, one line each, joined with newlines; never as one template literal. The program runs in strict mode: assigning an undeclared name throws, so use globalThis for intentional globals; eval and new Function are unavailable. Variables, functions, and imported modules remain in memory for this Agent across calls. Each call runs one program in its own top-level scope. Its top-level let, const, var, class, and function declarations, and the names it received from earlier programs, are copied into the top-level scope of later programs: later programs receive copies of these variables, not references to them, so an object they hold is still shared. In one program, either use a copied name or declare it again; do not declare a name and also use its copied value. Assigning to a copied name, even one declared with const, changes only this program's copy, which later programs receive. Do not declare var inside blocks; a block-level var changes which value later programs copy. Functions and still-running code from earlier programs keep the values they captured, and assignments they make later are not copied; keep shared mutable state in objects. If a program fails before a declaration of an existing name finishes, later programs keep that name's earlier value. Use await import(...) for modules; require and module are unavailable. Relative import specifiers resolve from the working directory of this environment's first program, while process.cwd() and relative file paths follow each program's working directory. Direct filesystem access follows the environment's launch-time sandbox policy; process.env starts empty. Timeout and cancellation results say whether retained variables were preserved or cleared. Restart, sandbox changes, output overflow, or process failure clears them. Recreate missing variables and resources; conversation history does not restore state. Earlier mutations and tool effects are not rolled back. Approved sandbox escalations use a fresh environment and discard its variables afterward. Await tools and cleanup before the program ends; unfinished tools reject. After completion, timeout, or cancellation, new tool calls are rejected and captured output is discarded; background work may still change state. Await child-process completion before the program ends; raw output belongs to the active evaluation. Each program starts in the Session's current directory. Running programs keep their initial directory. A sandbox escalation approves this complete program for one execution only. Nested tools retain their own policies and approvals. Request wider access only after evidence of a denial. Earlier effects may already have completed: inspect them before explicitly retrying. Programs are never replayed automatically.",
|
||||
"description": "Run a TypeScript program to observe and operate desktop applications. The global cua object is ready to use; retain application and window objects across calls. Only tools.cua is available inside the program. Call other session tools directly. Use inspect(...values) to display selected text and images. The program contains TypeScript REPL statements; only erasable syntax is accepted, with no enum or namespaces. Type annotations are advisory. Top-level declarations and await are supported; top-level return is not supported. Use inspect(...values) to display output. Do not use console. Use the raw form of a template literal only for short text whose backslashes must stay exactly as written, such as a regular expression; write other text, in particular file contents and commands, as ordinary strings. Write file contents as an array of quoted strings, one line each, joined with newlines; never as one template literal. The program runs in strict mode: assigning an undeclared name throws, so use globalThis for intentional globals; eval and new Function are unavailable. Variables, functions, and imported modules remain in memory for this Agent across calls. Each call runs one program in its own top-level scope. Its top-level let, const, var, class, and function declarations, and the names it received from earlier programs, are copied into the top-level scope of later programs: later programs receive copies of these variables, not references to them, so an object they hold is still shared. In one program, either use a copied name or declare it again; do not declare a name and also use its copied value. Assigning to a copied name, even one declared with const, changes only this program's copy, which later programs receive. Do not declare var inside blocks; a block-level var changes which value later programs copy. Functions and still-running code from earlier programs keep the values they captured, and assignments they make later are not copied; keep shared mutable state in objects. If a program fails before a declaration of an existing name finishes, later programs keep that name's earlier value. Use await import(...) for modules; require and module are unavailable. Relative import specifiers resolve from the working directory of this environment's first program, while process.cwd() and relative file paths follow each program's working directory. Direct filesystem access follows the environment's launch-time sandbox policy; process.env starts empty. Timeout and cancellation results say whether retained variables were preserved or cleared. Restart, sandbox changes, or process failure clears them. Recreate missing variables and resources; conversation history does not restore state. Earlier mutations and tool effects are not rolled back. Approved sandbox escalations use a fresh environment and discard its variables afterward. Await tools and cleanup before the program ends; unfinished tools reject. After completion, timeout, or cancellation, new tool calls are rejected and captured output is discarded; background work may still change state. Await child-process completion before the program ends; raw output belongs to the active evaluation. Each program starts in the Session's current directory. Running programs keep their initial directory. A sandbox escalation approves this complete program for one execution only. Nested tools retain their own policies and approvals. Request wider access only after evidence of a denial. Earlier effects may already have completed: inspect them before explicitly retrying. Programs are never replayed automatically.",
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
||||
+4
-5
@@ -2,19 +2,18 @@
|
||||
{"type":"subagent/descriptor","data":{"version":3,"mode":"continuable","provider":"spawn","label":"Delegated write probe","agentProvider":"deepseek-official","agentModel":"deepseek-v4-flash","agentReasoningEffort":"low"}}
|
||||
{"type":"sandbox/mode","data":{"mode":"read-only","source":"delegation"}}
|
||||
{"type":"approval/policy","data":{"policy":"never","source":"delegation"}}
|
||||
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Use the write tool exactly once with file_path set to exactly the relative path inherited.txt and content escaped. If the write is denied, reply with the single word CHILD_DENIED and the denial marker line; do not retry and do not request escalation. If it succeeds, reply CHILD_WROTE."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"}]}}
|
||||
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Use the write tool exactly once with file_path set to exactly the relative path inherited.txt and content escaped. If the write is denied, reply with the single word CHILD_DENIED and the denial marker line; do not retry and do not request escalation. If it succeeds, reply CHILD_WROTE."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{sessionId}}"},"role":"user","id":"{{sessionId}}"}]}}
|
||||
{"type":"turn/start","data":{"turn":1}}
|
||||
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}
|
||||
{"type":"step/start","data":{"turn":1,"step":1}}
|
||||
{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"Use the write tool exactly once with file_path set to exactly the relative path inherited.txt and content escaped. If the write is denied, reply with the single word CHILD_DENIED and the denial marker line; do not retry and do not request escalation. If it succeeds, reply CHILD_WROTE."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Use the write tool exactly once with file_path set to exactly the relative path inherited.txt and content escaped. If the write is denied, reply with the single word CHILD_DENIED and the denial marker line; do not retry and do not request escalation. If it succeeds, reply CHILD_WROTE."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{sessionId}}"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it. Messages from other agents begin with \"Agent <name> sent a message:\". Other user messages come from the human user, who reads this conversation directly. You can still message other agents to coordinate, but answer the human user in your reply.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it. Messages from other agents begin with \"Agent <name> sent a message:\". Other user messages come from the human user, who reads this conversation directly. You can still message other agents to coordinate, but answer the human user in your reply."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
|
||||
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","reasoningEffort":"low"},"tools":"{{tools}}"},"reason":"initial"}}
|
||||
{"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}}
|
||||
{"type":"session/title","data":{"title":"Use the write tool exactly","messageSeqs":[8],"source":{"kind":"fallback"}}}
|
||||
{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"child-write","name":"write","arguments":"{\"file_path\": \"inherited.txt\", \"content\": \"escaped\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":0,"dt":[],"id":"child-write","name":"write","args":["{\"file_path\": \"inherited.txt\", \"content\": \"escaped\"}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"child-write","name":"write","arguments":"{\"file_path\": \"inherited.txt\", \"content\": \"escaped\"}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"}
|
||||
{"type":"tool/call","data":{"turn":1,"step":1,"callId":"child-write","name":"write","arguments":"{\"file_path\": \"inherited.txt\", \"content\": \"escaped\"}"}}
|
||||
{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"child-write"},"toolCallId":"child-write","content":[{"type":"text","text":"Error: [sandbox: file access denied under read-only mode]\n[sandbox: escalation available — retry this exact operation once with sandbox_permissions (the narrowest wider mode that suffices) + justification; the approval prompt asks the user]"}],"isError":true,"id":"{{sessionId}}"},"error":{"name":"FsError","code":"FS_SANDBOX_DENIED"}},"sourceEventSeqs":[14],"surfaceOp":"append"}
|
||||
{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"child-write"},"toolCallId":"child-write","content":[{"type":"text","text":"Error: [sandbox: file access denied under read-only mode]\n[sandbox: escalation available — retry this exact operation once with sandbox_permissions (the narrowest wider mode that suffices) + justification; the approval prompt asks the user]"}],"isError":true,"id":"{{sessionId}}"},"error":{"name":"FsError","code":"FS_SANDBOX_DENIED"}},"sourceEventSeqs":[13],"surfaceOp":"append"}
|
||||
{"type":"step/end","data":{"turn":1,"step":1}}
|
||||
{"type":"step/start","data":{"turn":1,"step":2}}
|
||||
{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"text","text":"CHILD_DENIED [sandbox: file access denied under read-only mode]"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["CHILD_DENIED [sandbox: file access denied under read-only mode]"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"CHILD_DENIED [sandbox: file access denied under read-only mode]"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"}
|
||||
|
||||
+3
-4
@@ -2,16 +2,15 @@
|
||||
{"type":"subagent/descriptor","data":{"version":3,"mode":"continuable","provider":"spawn","label":"Return child result","agentProvider":"deepseek-official","agentModel":"deepseek-v4-flash"}}
|
||||
{"type":"sandbox/mode","data":{"mode":"workspace-write","source":"delegation"}}
|
||||
{"type":"approval/policy","data":{"policy":"never","source":"delegation"}}
|
||||
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly CHILD_RESULT and nothing else. Do not call send_message."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"}]}}
|
||||
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Reply with exactly CHILD_RESULT and nothing else. Do not call send_message."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{sessionId}}"},"role":"user","id":"{{sessionId}}"}]}}
|
||||
{"type":"turn/start","data":{"turn":1}}
|
||||
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}
|
||||
{"type":"step/start","data":{"turn":1,"step":1}}
|
||||
{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly CHILD_RESULT and nothing else. Do not call send_message."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Reply with exactly CHILD_RESULT and nothing else. Do not call send_message."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{sessionId}}"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it. Messages from other agents begin with \"Agent <name> sent a message:\". Other user messages come from the human user, who reads this conversation directly. You can still message other agents to coordinate, but answer the human user in your reply.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it. Messages from other agents begin with \"Agent <name> sent a message:\". Other user messages come from the human user, who reads this conversation directly. You can still message other agents to coordinate, but answer the human user in your reply."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
|
||||
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}}
|
||||
{"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}}
|
||||
{"type":"session/title","data":{"title":"Reply with exactly CHILD_RESULT and","messageSeqs":[8],"source":{"kind":"fallback"}}}
|
||||
{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"CHILD_RESULT"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["CHILD_RESULT"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"CHILD_RESULT"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"}
|
||||
{"type":"step/end","data":{"turn":1,"step":1}}
|
||||
{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}}
|
||||
@@ -18,7 +18,7 @@ function latestAssistantCalls(messages) {
|
||||
|
||||
function hasNewCoordinationInput(messages) {
|
||||
const toolIndex = messages.findLastIndex(message => message.role === 'tool')
|
||||
return messages.some((message, index) => index > toolIndex && message.role === 'user'
|
||||
return toolIndex >= 0 && messages.some((message, index) => index > toolIndex && message.role === 'user'
|
||||
&& ['agent-message', 'subagent-settled'].includes(message.source?.kind))
|
||||
}
|
||||
|
||||
@@ -191,13 +191,15 @@ function lead(messages) {
|
||||
class TeamFixtureAdapter extends LlmAdapter {
|
||||
async * stream(options) {
|
||||
const tools = options.tools.map(tool => tool.name)
|
||||
const initial = options.messages.findLast(message => message.role === 'user' && message.source.kind === 'user')
|
||||
const workflowChild = initial?.content[0]?.text === 'TEAM_WORKFLOW_CHILD'
|
||||
const initial = options.messages.find(message => message.role === 'user'
|
||||
&& ['user', 'agent-message'].includes(message.source.kind))
|
||||
const taskContent = initial?.source.kind === 'agent-message' ? initial.content.slice(1) : initial?.content
|
||||
const workflowChild = taskContent?.[0]?.text === 'TEAM_WORKFLOW_CHILD'
|
||||
const context = options.messages.findLast(message => message.source?.kind === 'runtime-context')
|
||||
const section = name => context?.source.sections?.find(candidate => candidate.name === name)?.text
|
||||
const role = section('subagent:identity')
|
||||
const parentId = role?.match(/You are a subagent delegated by agent "([^"]+)"/u)?.[1]
|
||||
const task = initial?.content.filter(block => block.type === 'text').map(block => block.text).join('\n')
|
||||
const task = taskContent?.filter(block => block.type === 'text').map(block => block.text).join('\n')
|
||||
if (!workflowChild && (!tools.includes('subagent') || !tools.includes('workflow') || !tools.includes('team_task_create'))) {
|
||||
throw new Error('Team profile is missing delegation, workflow, or task tools')
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local'
|
||||
import * as ToolBash from '@deepseek-ai/dsh-tool-bash'
|
||||
import * as ToolTodo from '@deepseek-ai/dsh-tool-todo'
|
||||
import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek-api-key'
|
||||
import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
|
||||
import TokenMeter from '@deepseek-ai/dsh-token-meter'
|
||||
import ToolResultPruner from '@deepseek-ai/dsh-compaction-tool-result-pruner'
|
||||
import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl'
|
||||
@@ -70,6 +71,7 @@ export async function codingHarness(workdir: string, options: CodingHarnessOptio
|
||||
systemPrompt: { personaPrefix: options.personaPrefix ?? '' },
|
||||
})
|
||||
await ctx.plugin(AgentLoop, { agents: [] })
|
||||
await ctx.plugin(DeepSeekAuth)
|
||||
await ctx.plugin(LlmDeepSeek, {
|
||||
...options.modelContextWindow === undefined && options.modelMaxTokens === undefined ? {} : {
|
||||
models: [{
|
||||
|
||||
@@ -1116,15 +1116,22 @@ describe('headless stream-json snapshots', () => {
|
||||
const parent = logs.find(log => typeof log.header.parentSession !== 'string')
|
||||
if (parent === undefined) throw new Error('Agent Teams snapshot did not persist its Lead')
|
||||
const rows = parseJsonl(parent.content)
|
||||
const workflowTask = [
|
||||
{ type: 'text', text: 'Agent lead sent a message: ' },
|
||||
{ type: 'text', text: 'TEAM_WORKFLOW_CHILD' },
|
||||
]
|
||||
const workflowChild = logs.find(log => parseJsonl(log.content).some(row => row.type === 'user/message'
|
||||
&& JSON.stringify((row.data as JsonObject).content) === JSON.stringify([{ type: 'text', text: 'TEAM_WORKFLOW_CHILD' }])))
|
||||
&& JSON.stringify((row.data as JsonObject).content) === JSON.stringify(workflowTask)))
|
||||
if (workflowChild === undefined) throw new Error('Team profile did not persist its workflow child')
|
||||
const workflowRows = parseJsonl(workflowChild.content)
|
||||
expect(workflowRows.find(row => row.type === 'subagent/descriptor')?.data)
|
||||
.toMatchObject({ mode: 'continuable', provider: 'spawn' })
|
||||
expect(workflowRows.filter(row => row.type === 'user/message'
|
||||
&& ((row.data as JsonObject).source as JsonObject).kind === 'user').map(row => row.data))
|
||||
.toEqual([expect.objectContaining({ content: [{ type: 'text', text: 'TEAM_WORKFLOW_CHILD' }] })])
|
||||
&& ((row.data as JsonObject).source as JsonObject).kind === 'agent-message').map(row => row.data))
|
||||
.toEqual([expect.objectContaining({
|
||||
content: workflowTask,
|
||||
source: { kind: 'agent-message', form: 'relay', senderSessionId: parent.header.id },
|
||||
})])
|
||||
const teammates = rows.filter(row => row.type === 'subagent/catalog')
|
||||
.flatMap(row => typeof (row.data as JsonObject).label === 'string' && ((row.data as JsonObject).label as string).startsWith('Own deterministic ') ? [(row.data as JsonObject).label as string] : [])
|
||||
const tasks = rows.filter(row => row.type === 'team/task')
|
||||
@@ -1160,6 +1167,7 @@ describe('headless stream-json snapshots', () => {
|
||||
const source = (row.data as JsonObject).source
|
||||
return typeof source === 'object' && source !== null && !Array.isArray(source)
|
||||
&& (source as JsonObject).kind === 'agent-message'
|
||||
&& (source as JsonObject).senderSessionId !== parent.header.id
|
||||
})
|
||||
const openTurnStart = implementerRows.findLastIndex((row, index) => (
|
||||
index < steeredMessageIndex && row.type === 'turn/start'
|
||||
@@ -1176,11 +1184,11 @@ describe('headless stream-json snapshots', () => {
|
||||
const identities = logs.flatMap((log) => {
|
||||
if (log === parent || log === workflowChild) return []
|
||||
const initial = parseJsonl(log.content).find(row => row.type === 'user/message'
|
||||
&& ((row.data as JsonObject).source as JsonObject).kind === 'user')
|
||||
&& ((row.data as JsonObject).source as JsonObject).kind === 'agent-message')
|
||||
if (initial === undefined) throw new Error('Teammate Session has no initial task')
|
||||
const content = (initial.data as JsonObject).content as JsonObject[]
|
||||
// The task block is followed by the standard return guidance naming the Lead.
|
||||
expect(content).toHaveLength(2)
|
||||
expect(content).toHaveLength(3)
|
||||
expect(content[0]).toEqual({ type: 'text', text: 'Agent lead sent a message: ' })
|
||||
const context = parseJsonl(log.content).find(row => row.type === 'user/message'
|
||||
&& ((row.data as JsonObject).source as JsonObject).kind === 'runtime-context')
|
||||
const source = (context?.data as JsonObject)?.source as JsonObject
|
||||
|
||||
@@ -20,6 +20,7 @@ import * as BashEnvPlugin from '@deepseek-ai/dsh-shell-env'
|
||||
import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local'
|
||||
import * as ToolBash from '@deepseek-ai/dsh-tool-bash'
|
||||
import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek-api-key'
|
||||
import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
|
||||
import NodeRuntime from '@deepseek-ai/dsh-ptc-runtime-node'
|
||||
import Sandbox from '@deepseek-ai/dsh-sandbox-local'
|
||||
import SandboxPolicy from '@deepseek-ai/dsh-sandbox-policy'
|
||||
@@ -63,6 +64,7 @@ async function ptcModeHarness(cwd: string): Promise<Context> {
|
||||
tools: { mode: 'ptc' },
|
||||
})
|
||||
await harness.plugin(AgentLoop, { agents: [] })
|
||||
await harness.plugin(DeepSeekAuth)
|
||||
await harness.plugin(LlmDeepSeek)
|
||||
if (harness.get('subprocess') === undefined) await harness.plugin(LocalSubprocessRuntime)
|
||||
await harness.plugin(BashEnvPlugin)
|
||||
@@ -83,6 +85,7 @@ async function workspacePtcModeHarness(): Promise<Context> {
|
||||
await harness.plugin(ToolFs)
|
||||
await harness.plugin(AgentInstructions, { maxBytes: 65536 })
|
||||
await harness.plugin(AgentLoop, { agents: [] })
|
||||
await harness.plugin(DeepSeekAuth)
|
||||
await harness.plugin(LlmDeepSeek, { models: [{ id: 'deepseek-v4-flash' }] })
|
||||
await mountRuntime(harness)
|
||||
return harness
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { executeToolFixture } from '@deepseek-ai/dsh-tool-testkit'
|
||||
import { agentPresetProjectionDefinition } from '@deepseek-ai/dsh-agent-preset-registry'
|
||||
import { subagentModelSelectionProjectionDefinition } from '@deepseek-ai/dsh-tool-subagent/src/model-selection-state.ts'
|
||||
import type {} from '@deepseek-ai/dsh-tool-subagent/model-selection-settings'
|
||||
import { createRequire } from 'node:module'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { mkdir, mkdtemp, readFile, realpath, rm, symlink, writeFile } from 'node:fs/promises'
|
||||
@@ -376,7 +376,7 @@ describe('the shipped Web composition', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('applies the default-off subagent model allowlist only to new sessions', async () => {
|
||||
it('reads the default-off subagent model allowlist live for existing sessions', async () => {
|
||||
await ctx.settings.update(SUBAGENT_MODEL_SELECTION_SETTINGS_NAMESPACE, {
|
||||
enabled: false,
|
||||
allowedModels: [],
|
||||
@@ -393,16 +393,17 @@ describe('the shipped Web composition', () => {
|
||||
sessionId: brandString<SessionId>('preset-model-selection-enabled'),
|
||||
setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'standard').then(() => undefined),
|
||||
})
|
||||
const policy = await ctx.sessionProjections.register(subagentModelSelectionProjectionDefinition)
|
||||
try {
|
||||
expect(toolNames(ctx, disabled.agent)).toContain('list_subagent_models')
|
||||
expect(toolParameterNames(ctx, disabled.agent, 'subagent')).toEqual(expect.arrayContaining([
|
||||
'model', 'provider', 'reasoning_effort',
|
||||
]))
|
||||
expect(policy.stateOf(disabled.agent.session)).toBeNull()
|
||||
expect(policy.stateOf(enabled.agent.session)).toEqual([
|
||||
expect(ctx.subagentModelSelection.allowedRoutes()).toEqual([
|
||||
{ provider: 'deepseek-official', model: 'deepseek-v4-flash' },
|
||||
])
|
||||
for (const agent of [disabled.agent, enabled.agent]) {
|
||||
expect(agent.session.snapshotEvents().some(event => event.type === 'subagent/model-selection-policy')).toBe(false)
|
||||
}
|
||||
expect(toolNames(ctx, enabled.agent)).toContain('list_subagent_models')
|
||||
expect(toolParameterNames(ctx, enabled.agent, 'subagent')).toEqual(expect.arrayContaining([
|
||||
'model', 'provider', 'reasoning_effort',
|
||||
@@ -411,7 +412,6 @@ describe('the shipped Web composition', () => {
|
||||
expect(toolParameterNames(ctx, agent, 'subagent_fork')).toEqual(['description', 'name', 'prompt'])
|
||||
}
|
||||
} finally {
|
||||
await policy.dispose()
|
||||
await ctx.settings.update(SUBAGENT_MODEL_SELECTION_SETTINGS_NAMESPACE, { enabled: false })
|
||||
await enabled.dispose()
|
||||
await disabled.dispose()
|
||||
@@ -1141,7 +1141,7 @@ describe('a user preset declared from the shipped cordis rows', () => {
|
||||
expect(listed.isError).toBe(false)
|
||||
const providers = (JSON.parse(resultText(listed)) as { providers: Array<{ id: string; platform: string }> }).providers
|
||||
expect(providers.filter(provider => provider.platform === 'host').map(provider => provider.id))
|
||||
.toEqual(['Service', 'Event', 'Config', 'Tool'])
|
||||
.toEqual(['Service', 'Event', 'Config', 'Runtime', 'Tool'])
|
||||
|
||||
// The `Tool` provider is the one built over the host context: it
|
||||
// answers with the shared registry's view of the REQUESTING agent,
|
||||
|
||||
@@ -191,11 +191,6 @@ class ResizeObserverStub {
|
||||
unobserve(): void {}
|
||||
}
|
||||
|
||||
class EventSourceStub {
|
||||
addEventListener(): void {}
|
||||
close(): void {}
|
||||
}
|
||||
|
||||
const win = window as FixtureWindow
|
||||
let unmount: (() => Promise<void>) | undefined
|
||||
let mountedRemote: RemoteMock | undefined
|
||||
@@ -244,7 +239,6 @@ export function installAssembledBootEnv(): void {
|
||||
Object.defineProperty(navigator, 'language', { value: 'en-US', configurable: true })
|
||||
document.title = 'DeepSeek Harness'
|
||||
vi.stubGlobal('ResizeObserver', ResizeObserverStub)
|
||||
vi.stubGlobal('EventSource', EventSourceStub)
|
||||
vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) =>
|
||||
setTimeout(() => { callback(0) }, 0) as unknown as number)
|
||||
vi.stubGlobal('cancelAnimationFrame', (id: number) => { clearTimeout(id) })
|
||||
|
||||
@@ -271,7 +271,20 @@ describe.skipIf(MODE === 'record')('web e2e: bonus notice', () => {
|
||||
const opened = await context.newPage()
|
||||
tripwires.push(watchConsole(opened))
|
||||
await opened.addInitScript(() => {
|
||||
Object.defineProperty(globalThis, 'dshDesktop', { value: { protocolVersion: 1 } })
|
||||
// The update carrier stays idle until a scenario publishes a status for the account row.
|
||||
let update: { phase: string; version?: string } = { phase: 'idle' }
|
||||
const updateListeners = new Set<(state: typeof update) => void>()
|
||||
Object.defineProperty(globalThis, '__bonusPublishUpdate', {
|
||||
value: (state: typeof update) => { update = state; for (const listener of updateListeners) listener(state) },
|
||||
})
|
||||
Object.defineProperty(globalThis, 'dshDesktop', { value: { protocolVersion: 1, updates: {
|
||||
status: () => Promise.resolve(update),
|
||||
open: () => Promise.resolve(),
|
||||
subscribe: (listener: (state: typeof update) => void) => {
|
||||
updateListeners.add(listener)
|
||||
return () => { updateListeners.delete(listener) }
|
||||
},
|
||||
} } })
|
||||
// The embedded Platform view is a native child window owned by the Desktop shell.
|
||||
// The double answers immediately and records the calls, so the scenario observes
|
||||
// which page was opened and that returning destroyed the view.
|
||||
@@ -667,6 +680,30 @@ describe.skipIf(MODE === 'record')('web e2e: bonus notice', () => {
|
||||
})
|
||||
expect(transition).toBe('0.25s ease-out')
|
||||
observations.push(`stack.initial cards=3 acks=stack-first widths=260,252 inset=10 offset=-4 transition=${transition}`)
|
||||
// A Desktop update status shares the account row and leaves the card row at full width.
|
||||
const publishUpdate = (state: { phase: string; version?: string }) => stackPage.evaluate((value) => {
|
||||
(globalThis as typeof globalThis & { __bonusPublishUpdate: (next: typeof value) => void }).__bonusPublishUpdate(value)
|
||||
}, state)
|
||||
await publishUpdate({ phase: 'installing', version: '0.1.5' })
|
||||
const updateTag = stackPage.getByText('正在准备重启…', { exact: true })
|
||||
await updateTag.waitFor()
|
||||
const artifactDir = fileURLToPath(new URL('../../../.artifacts', import.meta.url))
|
||||
await mkdir(artifactDir, { recursive: true })
|
||||
await stackPage.screenshot({ path: join(artifactDir, 'bonus-notice-update-tag.png'), clip: { x: 0, y: 560, width: 420, height: 400 } })
|
||||
const taggedBox = await cards.first().boundingBox()
|
||||
const tagBox = await updateTag.boundingBox()
|
||||
const accountBox = await stackPage.getByRole('button', { name: '账号菜单', exact: true }).boundingBox()
|
||||
expect(taggedBox!.x).toBeCloseTo(10, 0)
|
||||
expect(taggedBox!.width).toBeCloseTo(260, 0)
|
||||
expect(taggedBox!.y + taggedBox!.height).toBeLessThanOrEqual(accountBox!.y)
|
||||
expect(tagBox!.y).toBeGreaterThanOrEqual(accountBox!.y)
|
||||
expect(tagBox!.y + tagBox!.height).toBeLessThanOrEqual(accountBox!.y + accountBox!.height)
|
||||
// The card floats over the session list: the list still reaches down to the card's bottom edge.
|
||||
const listBottom = await stackPage.locator('[class*="scrollRegion"]').first().evaluate(element => element.getBoundingClientRect().bottom)
|
||||
expect(listBottom).toBeGreaterThanOrEqual(taggedBox!.y + taggedBox!.height - 1)
|
||||
observations.push('stack.update-tag card=260 left-inset=10 card-above-account-row=true tag-in-account-row=true floats-over-list=true')
|
||||
await publishUpdate({ phase: 'idle' })
|
||||
await updateTag.waitFor({ state: 'detached' })
|
||||
for (const [delta, width, edge] of [[80, 280, 360], [-80, 260, 280]] as const) {
|
||||
const handle = await stackPage.locator('[data-side="sidebar"]').boundingBox()
|
||||
const x = handle!.x + handle!.width / 2
|
||||
@@ -700,8 +737,6 @@ describe.skipIf(MODE === 'record')('web e2e: bonus notice', () => {
|
||||
expect(platform.acks.length).toBe(beforeCollapseAcks)
|
||||
expect(platform.dismissals.length).toBe(beforeCollapseDismissals)
|
||||
observations.push('stack.expanded cards=3 duplicate-acks=0 dismissed=0')
|
||||
const artifactDir = fileURLToPath(new URL('../../../.artifacts', import.meta.url))
|
||||
await mkdir(artifactDir, { recursive: true })
|
||||
await stackPage.screenshot({ path: join(artifactDir, 'bonus-notice-stack-light.png') })
|
||||
await stackPage.emulateMedia({ colorScheme: 'dark' })
|
||||
await expect.poll(() => stackPage.locator('body').getAttribute('data-ds-dark-theme')).not.toBeNull()
|
||||
@@ -736,6 +771,16 @@ describe.skipIf(MODE === 'record')('web e2e: bonus notice', () => {
|
||||
await expect.poll(() => platform.acks.length).toBe(ackStart + 2)
|
||||
expect(platform.acks.slice(ackStart).map(ack => ack.orderId)).toEqual(['a1111111-1111-4111-8111-111111111111', 'a2222222-2222-4222-8222-222222222222'])
|
||||
observations.push('stack.promoted cards=2 acks=stack-first,stack-second width=260 same-node=true')
|
||||
// In a short window the long card scrolls its copy instead of pushing the account row out of view.
|
||||
await stackPage.setViewportSize({ width: 1440, height: 390 })
|
||||
const shortAccount = await stackPage.getByRole('button', { name: '账号菜单', exact: true }).boundingBox()
|
||||
const shortCard = await second.boundingBox()
|
||||
const copyScrolls = await second.getByRole('status').evaluate(element => element.scrollHeight > element.clientHeight)
|
||||
expect(shortAccount!.y + shortAccount!.height).toBeLessThanOrEqual(390)
|
||||
expect(shortCard!.y + shortCard!.height).toBeLessThanOrEqual(shortAccount!.y)
|
||||
expect(copyScrolls).toBe(true)
|
||||
observations.push('stack.short-window account-row-visible=true card-above-account-row=true copy-scrolls=true')
|
||||
await stackPage.setViewportSize({ width: 1440, height: 960 })
|
||||
await second.getByRole('button', { name: '关闭', exact: true }).click()
|
||||
await expect.poll(() => platform.acks.length).toBe(ackStart + 3)
|
||||
expect(platform.acks.slice(ackStart).map(ack => ack.orderId)).toEqual(['a1111111-1111-4111-8111-111111111111', 'a2222222-2222-4222-8222-222222222222', 'a3333333-3333-4333-8333-333333333333'])
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
/** Real profile, Remote, and page Loader: a browser plugin receives its Host face's volatile Config and follows live edits. */
|
||||
import { cp, mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { FiberState } from '@deepseek-ai/cordis'
|
||||
import { chromium } from 'playwright'
|
||||
import { expect, it, onTestFailed, onTestFinished } from 'vitest'
|
||||
import { launchWebScaffold, watchConsole } from './scaffold.ts'
|
||||
import { ZH_BROWSER_LOCALE, saveFailureShot } from './support.ts'
|
||||
|
||||
const FIXTURE = fileURLToPath(new URL('./fixtures/plugins/fixture-synced-config', import.meta.url))
|
||||
const SCHEMASTERY = fileURLToPath(new URL('../../../vendor/schemastery', import.meta.url))
|
||||
const PACKAGE = '@fixture/synced-config'
|
||||
const ROW = 'fixture-synced-config'
|
||||
|
||||
/** What the fixture's Client face records from its synced Config object. */
|
||||
interface Observation {
|
||||
keys: string[]
|
||||
greeting: string
|
||||
account: { label: string }
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the fixture's recorded observation.
|
||||
* @param text - JSON the fixture wrote to `data-synced-config`.
|
||||
* @returns the observation.
|
||||
*/
|
||||
function parseObservation(text: string): Observation {
|
||||
const value = JSON.parse(text) as Partial<Observation> | null
|
||||
if (value === null || !Array.isArray(value.keys) || typeof value.greeting !== 'string' || typeof value.account?.label !== 'string') {
|
||||
throw new Error(`fixture-synced-config recorded an unexpected observation: ${text}`)
|
||||
}
|
||||
return value as Observation
|
||||
}
|
||||
|
||||
it('renders volatile Config without secrets or ordinary fields and updates it in place from a profile edit', async () => {
|
||||
// An installed package carries its own dependencies: the copy links the Schemastery its Host face imports.
|
||||
const installed = await mkdtemp(join(tmpdir(), 'dsh-client-config-sync-'))
|
||||
onTestFinished(() => rm(installed, { recursive: true, force: true }))
|
||||
await cp(FIXTURE, installed, { recursive: true })
|
||||
await mkdir(join(installed, 'node_modules', '@deepseek-ai'), { recursive: true })
|
||||
await symlink(SCHEMASTERY, join(installed, 'node_modules', '@deepseek-ai', 'schemastery'), 'junction')
|
||||
const scaffold = await launchWebScaffold({ profile: { packages: [{ dir: installed, enabled: true }] } })
|
||||
onTestFinished(() => scaffold.close())
|
||||
const browser = await chromium.launch()
|
||||
onTestFinished(() => browser.close())
|
||||
const entry = [...scaffold.ctx.loader.entries()].find(candidate => candidate.options.id === ROW)
|
||||
expect(entry?.fiber?.state).toBe(FiberState.ACTIVE)
|
||||
const hostFiber = entry!.fiber!
|
||||
|
||||
// The first-render HTML carries the projection: volatile values only, the secret subfield removed.
|
||||
const html = await (await scaffold.hostFetch('/')).text()
|
||||
expect(html).toContain('hello-r0')
|
||||
expect(html).not.toContain('secret-token-r0')
|
||||
expect(html).not.toContain('host-only-cache-r0')
|
||||
|
||||
const page = await browser.newPage({ locale: ZH_BROWSER_LOCALE })
|
||||
const console = watchConsole(page)
|
||||
onTestFailed(() => saveFailureShot(page, 'web-e2e-client-config-sync'))
|
||||
let navigations = 0
|
||||
const dataset = async () => {
|
||||
const { applies, config } = await page.evaluate(() => ({
|
||||
applies: document.documentElement.dataset.syncedApplies,
|
||||
config: document.documentElement.dataset.syncedConfig,
|
||||
}))
|
||||
return { applies, config: config === undefined ? undefined : parseObservation(config) }
|
||||
}
|
||||
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
|
||||
page.on('framenavigated', () => { navigations++ })
|
||||
await expect.poll(async () => (await dataset()).applies, { timeout: 20_000 }).toBe('1')
|
||||
const bootRow = await page.evaluate((id) => {
|
||||
const boot = Reflect.get(window, '__DSH_BOOT__') as { entries: { id: string; config?: unknown }[] }
|
||||
return boot.entries.find(row => row.id === id)
|
||||
}, PACKAGE)
|
||||
expect(bootRow?.config).toEqual({ greeting: 'hello-r0', account: { label: 'primary' } })
|
||||
expect(await dataset()).toEqual({
|
||||
applies: '1',
|
||||
config: { keys: ['account', 'greeting'], greeting: 'hello-r0', account: { label: 'primary' } },
|
||||
})
|
||||
|
||||
// A profile edit that changes only volatile values reaches the running activation through its references.
|
||||
const patchFile = join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml')
|
||||
const previous = await readFile(patchFile, 'utf8').catch(() => '')
|
||||
expect(previous.includes(ROW)).toBe(false)
|
||||
await writeFile(patchFile, [
|
||||
`- id: ${ROW}`,
|
||||
' config:',
|
||||
' cacheDir: host-only-cache-r0',
|
||||
' greeting: hello-r1',
|
||||
' account:',
|
||||
' label: secondary',
|
||||
' token: secret-token-r1',
|
||||
'',
|
||||
].join('\n'))
|
||||
await expect.poll(async () => (await dataset()).config, { timeout: 30_000 }).toEqual({
|
||||
keys: ['account', 'greeting'], greeting: 'hello-r1', account: { label: 'secondary' },
|
||||
})
|
||||
expect(scaffold.ctx.clientModules.graph().entries.find(row => row.id === PACKAGE)?.config)
|
||||
.toEqual({ greeting: 'hello-r1', account: { label: 'secondary' } })
|
||||
expect((await dataset()).applies).toBe('1')
|
||||
expect(entry!.fiber).toBe(hostFiber)
|
||||
expect(hostFiber.state).toBe(FiberState.ACTIVE)
|
||||
expect(navigations).toBe(0)
|
||||
expect(console.pageErrors).toEqual([])
|
||||
}, 120_000)
|
||||
@@ -297,20 +297,12 @@ it('synchronizes two pages, disposes effects and restores an offline page from t
|
||||
expect(await target.locator('style[data-plugin="@fixture/live-client"]').count()).toBe(1)
|
||||
}
|
||||
|
||||
const disconnected = other.waitForEvent('requestfailed', request => request.url().includes('/plugins/events'))
|
||||
await otherContext.setOffline(true)
|
||||
// Chromium offline emulation leaves established SSE sockets open. Cycling this
|
||||
// fixture's transport plugin closes them without replacing the Host or profile.
|
||||
// Restarting the Host transport ends every plugin-events stream; each page reopens it and reconciles from the
|
||||
// new baseline, so a later change still reaches both pages.
|
||||
const transport = [...scaffold.ctx.loader.entries()].find(entry => entry.options.name === '@deepseek-ai/dsh-client-hmr')!.fiber!
|
||||
const reconnected = page.waitForResponse(response => response.url().includes('/plugins/events') && response.status() === 200)
|
||||
await transport.restart()
|
||||
await disconnected
|
||||
await reconnected
|
||||
await toggle()
|
||||
await expect.poll(() => live(page).count()).toBe(0)
|
||||
expect(await live(other).count()).toBe(1)
|
||||
await otherContext.setOffline(false)
|
||||
await expect.poll(() => live(other).count(), { timeout: 20_000 }).toBe(0)
|
||||
for (const target of [page, other]) await expect.poll(() => live(target).count(), { timeout: 20_000 }).toBe(0)
|
||||
expect(await draft.inputValue()).toBe('unfinished-draft')
|
||||
expect(navigations).toBe(0)
|
||||
expect(scaffold.ctx.loader.ctx.fiber.uid).toBe(host)
|
||||
|
||||
@@ -143,7 +143,7 @@ it.skipIf(MODE === 'record')('reuses saved native Account Flash translations acr
|
||||
if (account === undefined) throw new Error('Shipped native Account service is absent')
|
||||
// Only credential acquisition is nondeterministic; the Loader-owned native route and wire remain real.
|
||||
const credential = {
|
||||
headers: { 'x-dsh-auth-token': 'paid-browser-fixture-token' }, value: 'paid-browser-fixture-token',
|
||||
headers: { 'x-dsh-auth-token': 'paid-browser-fixture-token' },
|
||||
revoked: new AbortController().signal, reject: () => Promise.resolve(),
|
||||
}
|
||||
const auth = vi.spyOn(account, 'resolveRequestCredential').mockImplementation(async (url: string) =>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/** The completed answer offers creation through a propose_action card; choosing a location does not start it. */
|
||||
/** The completed answer offers creation through an action-card block shown as a card; choosing a location does not start it. */
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
@@ -46,6 +46,9 @@ describe('creation recommendation after an explicit wish', () => {
|
||||
const cardBox = await card.boundingBox()
|
||||
expect(answerBox).not.toBeNull()
|
||||
expect(cardBox!.y).toBeGreaterThanOrEqual(answerBox!.y + answerBox!.height)
|
||||
// The answer's action-card block stays hidden; only the card below shows its proposal.
|
||||
expect(await page.getByText('create_personalized_page').count()).toBe(0)
|
||||
expect(await page.locator('.md-code-block').count()).toBe(0)
|
||||
expect(await card.getByRole('button', { name: 'Create', exact: true }).isEnabled()).toBe(true)
|
||||
await compareOrRefreshGolden(join(directory, 'offered.expected.md'), await captureStableAria(page, '[data-action-card]', scaffold.workspaceCwd), scaffold.mode)
|
||||
const info = card.getByRole('button', { name: 'How creation works and token usage', exact: true })
|
||||
|
||||
@@ -163,7 +163,7 @@ describe('web e2e: the composer model switch is the default for later sessions',
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps command popup search borders transparent in both palettes', async () => {
|
||||
it('keeps command popup searches borderless in both palettes', async () => {
|
||||
const composer = page.locator('[data-composer-input]').first()
|
||||
await page.getByRole('button', { name: '添加文件或调用指令', exact: true }).click()
|
||||
const commandMenuBounds = await page.locator('[data-trigger-menu]').boundingBox()
|
||||
@@ -193,14 +193,15 @@ describe('web e2e: the composer model switch is the default for later sessions',
|
||||
try {
|
||||
return [false, true].map((dark) => {
|
||||
body.toggleAttribute('data-ds-dark-theme', dark)
|
||||
return getComputedStyle(input).borderColor
|
||||
const style = getComputedStyle(input)
|
||||
return { width: style.borderWidth, style: style.borderStyle }
|
||||
})
|
||||
} finally {
|
||||
if (previousTheme === null) body.removeAttribute('data-ds-dark-theme')
|
||||
else body.setAttribute('data-ds-dark-theme', previousTheme)
|
||||
}
|
||||
})
|
||||
expect(borders).toEqual(['rgba(0, 0, 0, 0)', 'rgba(0, 0, 0, 0)'])
|
||||
expect(borders).toEqual([{ width: '0px', style: 'none' }, { width: '0px', style: 'none' }])
|
||||
} finally {
|
||||
await search.press('Escape')
|
||||
await composer.fill('')
|
||||
|
||||
@@ -36,11 +36,13 @@ en.get locale=en_US query=
|
||||
web.notice=赠金已到账 / 已赠送您 4.00 元 DSH 体验赠金。 acks=1
|
||||
stack.hidden cards=3 acks=0
|
||||
stack.initial cards=3 acks=stack-first widths=260,252 inset=10 offset=-4 transition=0.25s ease-out
|
||||
stack.update-tag card=260 left-inset=10 card-above-account-row=true tag-in-account-row=true floats-over-list=true
|
||||
stack.resized sidebar=360 card=280 left-inset=10
|
||||
stack.resized sidebar=280 card=260 left-inset=10
|
||||
stack.rail cards=3 visible=false dismissed=0
|
||||
stack.expanded cards=3 duplicate-acks=0 dismissed=0
|
||||
stack.promoted cards=2 acks=stack-first,stack-second width=260 same-node=true
|
||||
stack.short-window account-row-visible=true card-above-account-row=true copy-scrolls=true
|
||||
stack.dismissed cards=0 acks=stack-first,stack-second,stack-third
|
||||
refresh.retained cards=3 acks=refresh-first same-node=true
|
||||
refresh.localized locale=en_US content-reads=3 list-reads=0 acks=1 same-node=true
|
||||
|
||||
@@ -10,10 +10,10 @@
|
||||
- text: "1"
|
||||
- list:
|
||||
- listitem:
|
||||
- img "变更请求状态:需要处理"
|
||||
- link "Add the pull request panel":
|
||||
- /url: https://github.com/octo/demo/pull/7
|
||||
- text: "#7 feat → main"
|
||||
- button "变更请求状态:需要处理 Add the pull request panel":
|
||||
- img "变更请求状态:需要处理"
|
||||
- text: Add the pull request panel
|
||||
- text: "#7"
|
||||
- button "#7 的操作"
|
||||
- 'button "收起 #7" [expanded]'
|
||||
- button "检查 已加载 1 项检查,仍有更多"
|
||||
|
||||
@@ -7,10 +7,10 @@
|
||||
- text: "1"
|
||||
- list:
|
||||
- listitem:
|
||||
- img "变更请求状态:需要处理"
|
||||
- link "Add the pull request panel":
|
||||
- /url: https://github.com/octo/demo/pull/7
|
||||
- text: "#7 feat → main"
|
||||
- button "变更请求状态:需要处理 Add the pull request panel":
|
||||
- img "变更请求状态:需要处理"
|
||||
- text: Add the pull request panel
|
||||
- text: "#7"
|
||||
- button "#7 的操作"
|
||||
- 'button "收起 #7" [expanded]'
|
||||
- button "检查 已加载 1 项检查,仍有更多"
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
- listitem:
|
||||
- img "变更请求状态:需要处理"
|
||||
- link "Add the pull request panel":
|
||||
- /url: https://github.com/octo/demo/pull/7
|
||||
- text: "#7 feat → main"
|
||||
- button "变更请求状态:需要处理 Add the pull request panel":
|
||||
- img "变更请求状态:需要处理"
|
||||
- text: Add the pull request panel
|
||||
- text: "#7"
|
||||
- button "#7 的操作"
|
||||
- 'button "收起 #7" [expanded]'
|
||||
- button "检查 已加载 1 项检查,仍有更多"
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
/** Client face of the synced-configuration fixture: exports no Config and records what its synced Config object shows. */
|
||||
window.__ModuleLoader__.load({
|
||||
id: '@fixture/synced-config',
|
||||
factory() {
|
||||
return {
|
||||
apply(ctx, config) {
|
||||
const data = document.documentElement.dataset
|
||||
data.syncedApplies = String(Number(data.syncedApplies ?? 0) + 1)
|
||||
// References are read at operation time; `Object.keys` lists the fields the Host sent.
|
||||
const publish = () => {
|
||||
data.syncedConfig = JSON.stringify({
|
||||
keys: Object.keys(config).sort(),
|
||||
greeting: config.greeting.get(),
|
||||
account: config.account.get(),
|
||||
})
|
||||
}
|
||||
publish()
|
||||
let notifications = 0
|
||||
const notified = () => {
|
||||
notifications++
|
||||
data.syncedNotifications = String(notifications)
|
||||
publish()
|
||||
}
|
||||
ctx.effect(() => config.greeting.subscribe(notified))
|
||||
ctx.effect(() => config.account.subscribe(notified))
|
||||
},
|
||||
}
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,9 @@
|
||||
- insert:
|
||||
- id: fixture-synced-config
|
||||
name: '@fixture/synced-config'
|
||||
config:
|
||||
cacheDir: host-only-cache-r0
|
||||
greeting: hello-r0
|
||||
account:
|
||||
label: primary
|
||||
token: secret-token-r0
|
||||
@@ -0,0 +1,15 @@
|
||||
/** Host face of the synced-configuration fixture: the only Config schema, with an ordinary field and two volatile fields. */
|
||||
import z from '@deepseek-ai/schemastery'
|
||||
|
||||
/** Ordinary `cacheDir` stays on the Host; volatile `greeting` and `account` reach the browser without `account.token`. */
|
||||
export const Config = z.object({
|
||||
cacheDir: z.string().required(),
|
||||
greeting: z.string().required().volatile(),
|
||||
account: z.object({
|
||||
label: z.string().required(),
|
||||
token: z.string().role('secret').required(),
|
||||
}).volatile(),
|
||||
})
|
||||
|
||||
/** Nothing to mount on the Host. */
|
||||
export function apply() {}
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "@fixture/synced-config",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "index.js",
|
||||
"exports": {
|
||||
".": "./index.js",
|
||||
"./client": "./client.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@deepseek-ai/schemastery": "*"
|
||||
},
|
||||
"dsh": {
|
||||
"bundle": {
|
||||
"patch": "./cordis.patch.yml"
|
||||
},
|
||||
"client": {
|
||||
"platform": "web"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -776,7 +776,7 @@ async function expectNumberedReference({ scaffold, page, project, tripwire }: Pa
|
||||
await page.getByRole('button', { name: TOGGLE_ATTENTION, exact: true }).waitFor({ timeout: 20_000 })
|
||||
await showSessionPanel(page)
|
||||
const change = page.locator(`[data-forge-change="${PULL}"]`)
|
||||
await change.getByRole('link', { name: 'Add the pull request panel', exact: true }).waitFor({ timeout: 20_000 })
|
||||
await change.locator('[data-forge-opens]').filter({ hasText: 'Add the pull request panel' }).waitFor({ timeout: 20_000 })
|
||||
await change.getByText('等待评审', { exact: true }).waitFor()
|
||||
await compareOrRefreshGolden(join(EXPECTED, 'reference.expected.md'),
|
||||
await captureStableAria(page, `[data-forge-change="${PULL}"]`, scaffold.workspaceCwd), MODE)
|
||||
@@ -884,7 +884,7 @@ it.skipIf(MODE === 'record')('starts a Session in a worktree before its first me
|
||||
await page.getByRole('tooltip').filter({ hasText: `工作树(基于 release):${abbreviateHomePath(directory, homedir())}` }).waitFor()
|
||||
await page.mouse.move(0, 0)
|
||||
const change = panel.locator(`[data-forge-change="${PULL}"]`)
|
||||
const title = change.getByRole('link', { name: 'Add the pull request panel', exact: true })
|
||||
const title = change.locator('[data-forge-opens]').filter({ hasText: 'Add the pull request panel' })
|
||||
await title.waitFor({ timeout: 20_000 })
|
||||
// The only open change request starts expanded.
|
||||
await change.getByText('等待评审', { exact: true }).waitFor()
|
||||
@@ -954,6 +954,42 @@ it.skipIf(MODE === 'record')('starts a Session in a worktree before its first me
|
||||
expect(tripwire.warnings).toEqual([])
|
||||
})
|
||||
|
||||
it.skipIf(MODE === 'record')('creates the requested worktree for the first message, not for the notice an access mode change queues before it', async () => {
|
||||
const { scaffold, page, project, tripwire } = await requestReleaseWorktree('web-e2e-forge-panel-access-mode')
|
||||
await page.locator('button[aria-label^="访问模式"]').first().click()
|
||||
await page.getByRole('menuitem', { name: '完全权限', exact: true }).click()
|
||||
const confirmation = page.getByRole('dialog', { name: '确认启用完全权限?' })
|
||||
await confirmation.getByRole('checkbox', { name: '我已了解风险,并愿意继续' }).check()
|
||||
await confirmation.getByRole('button', { name: '启用完全权限' }).click()
|
||||
await page.locator('button[aria-label="访问模式,当前:完全权限"]').waitFor()
|
||||
// The switch queues its approval notice for the next step, which opens no turn. A hold would run as maintenance of
|
||||
// the Agent until the worktree exists, and the Session would then work in it.
|
||||
const noticed = () => scaffold.ctx.agents.list()
|
||||
.find(candidate => candidate.inbox.nextStep.some(message => message.source.kind === 'user-approval'))
|
||||
await expect.poll(() => noticed() !== undefined).toBe(true)
|
||||
const agent = noticed()
|
||||
if (agent === undefined) throw new Error('The access mode change must queue its notice')
|
||||
await agent.runMaintenance(() => Promise.resolve())
|
||||
expect(scaffold.ctx.workingDirectory.get(agent.session)).toBe(project)
|
||||
|
||||
const { settled } = await sendPrompt(page, scaffold)
|
||||
const sessionId = await settled
|
||||
await page.getByText('LIGHTHOUSE', { exact: true }).waitFor()
|
||||
expect(sessionId).toBe(agent.session.id)
|
||||
|
||||
// The prompt opens the first turn, and its hold creates the worktree.
|
||||
const events = await readPersistedEvents(scaffold, sessionId)
|
||||
const queued = (target: 'next-step' | 'next-turn', kind: string): number => events.findIndex(event => event.type === 'agent/inbox/spliced'
|
||||
&& event.data.target === target && event.data.inserted.some(message => message.source.kind === kind))
|
||||
const created = events.findIndex(event => pluginRecordOf(event)?.type === 'plugin:worktree/created')
|
||||
expect(queued('next-step', 'user-approval')).toBeGreaterThan(-1)
|
||||
expect(queued('next-turn', 'user')).toBeGreaterThan(queued('next-step', 'user-approval'))
|
||||
expect(created).toBeGreaterThan(queued('next-turn', 'user'))
|
||||
expect(created).toBeLessThan(events.findIndex(event => event.type === 'turn/start'))
|
||||
expect(tripwire.pageErrors).toEqual([])
|
||||
expect(tripwire.warnings).toEqual([])
|
||||
})
|
||||
|
||||
it.skipIf(MODE === 'record')('keeps the first message waiting when the worktree cannot be created, tries again, and sends it without the worktree', async () => {
|
||||
const { scaffold, page, project, tripwire } = await requestReleaseWorktree('web-e2e-forge-panel-failure')
|
||||
await git(project, 'branch', '--quiet', '-D', 'release')
|
||||
@@ -1004,7 +1040,7 @@ it.skipIf(MODE === 'record')('marks a draft change request ready for review and
|
||||
scaffold.ctx.forgeSession.track(session, DRAFT)
|
||||
await showSessionPanel(page)
|
||||
const change = page.locator(`[data-forge-change="${DRAFT}"]`)
|
||||
await change.getByRole('link', { name: 'Add the merge button', exact: true }).waitFor({ timeout: 20_000 })
|
||||
await change.locator('[data-forge-opens]').filter({ hasText: 'Add the merge button' }).waitFor({ timeout: 20_000 })
|
||||
|
||||
// The only open change request starts expanded, so its Merge action shows once it is ready.
|
||||
await chooseCardAction(page, change, '#9', '标记为可评审')
|
||||
@@ -1137,7 +1173,7 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an
|
||||
scaffold.ctx.forgeSession.track(session, PULL)
|
||||
await showSessionPanel(page)
|
||||
const change = page.locator(`[data-forge-change="${PULL}"]`)
|
||||
await change.getByRole('link', { name: 'Add the pull request panel', exact: true }).waitFor({ timeout: 20_000 })
|
||||
await change.locator('[data-forge-opens]').filter({ hasText: 'Add the pull request panel' }).waitFor({ timeout: 20_000 })
|
||||
await card.getByRole('button', { name: '本地变更 · 4 个文件,新增 4 行,删除 1 行', exact: true }).waitFor()
|
||||
// The open change request of the checked-out branch replaces the offer to create one.
|
||||
await card.getByRole('button', { name: '本地变更操作', exact: true }).click()
|
||||
@@ -1150,7 +1186,8 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an
|
||||
await card.getByRole('button', { name: '本地变更 · 4 个文件,新增 4 行,删除 1 行', exact: true }).click()
|
||||
await local.getByText('暂存区与 HEAD 比较', { exact: true }).waitFor()
|
||||
await showSessionPanel(page)
|
||||
await change.getByRole('button', { name: '查看 #7 的变更:新增 128 行,删除 14 行', exact: true }).click()
|
||||
// A press on the card's line opens the changes, as its Changes row and its View changes item do.
|
||||
await change.locator('[data-forge-opens="changes"]').click()
|
||||
const view = page.locator('[data-forge-changes="change"]')
|
||||
const panelFile = view.locator('[data-forge-diff-file="src/panel.ts"]')
|
||||
const title = await view.getByText('Add the pull request panel', { exact: true }).boundingBox()
|
||||
@@ -1774,9 +1811,9 @@ it.skipIf(MODE === 'record')('aligns localized status rows by their glyphs in th
|
||||
width: document.documentElement.clientWidth,
|
||||
}
|
||||
})
|
||||
// The glyph starts 30px into the card, where the card's title starts.
|
||||
expect(geometry.iconInset).toBe(8)
|
||||
expect(geometry.rowInset).toBeGreaterThanOrEqual(6)
|
||||
expect(geometry.rowInset).toBeLessThanOrEqual(7)
|
||||
expect(geometry.rowInset).toBe(22)
|
||||
offsets.add(geometry.valueOffset)
|
||||
expect(geometry.gap).toBeGreaterThanOrEqual(8)
|
||||
expect(geometry.right).toBeLessThanOrEqual(geometry.width)
|
||||
@@ -2507,7 +2544,7 @@ it.skipIf(MODE === 'record')('summarizes checks, reviewers, and the merge state
|
||||
await showSessionPanel(page)
|
||||
const card = page.locator(`[data-forge-change="${PULL}"]`)
|
||||
// The card chooses its default expansion once its first status arrives, which names the title.
|
||||
await card.getByRole('link', { name: 'Add the pull request panel', exact: true }).waitFor({ timeout: 20_000 })
|
||||
await card.locator('[data-forge-opens]').filter({ hasText: 'Add the pull request panel' }).waitFor({ timeout: 20_000 })
|
||||
if (await card.getAttribute('data-expanded') === null) await card.getByRole('button', { name: '展开 #7', exact: true }).click()
|
||||
const checks = card.locator('[data-forge-checks]')
|
||||
await expect.poll(() => checks.textContent(), { timeout: 20_000 }).toBe('检查3 项失败 · 1 项进行中')
|
||||
|
||||
@@ -2,13 +2,61 @@
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { join } from 'node:path'
|
||||
import { chromium } from 'playwright'
|
||||
import sharp from 'sharp'
|
||||
import { expect, it, onTestFailed, onTestFinished } from 'vitest'
|
||||
import { launchWebScaffold } from './scaffold.ts'
|
||||
import { newEnglishPage, saveFailureShot } from './support.ts'
|
||||
import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './support.ts'
|
||||
|
||||
const FIXTURE = fileURLToPath(new URL('./fixtures/plugins/fixture-icon-skin', import.meta.url))
|
||||
const ICON = 'svg[data-icon="dsw-icon-search-outline-regular"]'
|
||||
|
||||
it.each(['light', 'dark'] as const)('renders a 16px permission trigger and 14px menu icons with fixed 1px strokes in %s mode', async (colorScheme) => {
|
||||
const scaffold = await launchWebScaffold()
|
||||
onTestFinished(() => scaffold.close())
|
||||
const browser = await chromium.launch()
|
||||
onTestFinished(() => browser.close())
|
||||
const page = await browser.newPage({ deviceScaleFactor: 2, locale: 'en-US', colorScheme })
|
||||
onTestFailed(() => saveFailureShot(page, `permission-pixel-grid-${colorScheme}`))
|
||||
await page.goto(scaffold.authenticatedUrl)
|
||||
await connectFreshWorkspace(page, scaffold.workspaceCwd)
|
||||
await page.evaluate(() => document.fonts.ready)
|
||||
const trigger = page.getByRole('button', { name: /^Access mode, current:/ })
|
||||
const triggerBox = await trigger.locator('svg').first().boundingBox()
|
||||
expect(triggerBox && [triggerBox.width, triggerBox.height]).toEqual([16, 16])
|
||||
await trigger.click()
|
||||
const icon = page.getByRole('menuitem', { name: 'Workspace Write', exact: true }).locator('svg').first()
|
||||
// Isolate edge coverage from the menu's translucent material without changing placement.
|
||||
await icon.evaluate((svg, dark) => {
|
||||
svg.style.color = dark ? 'white' : 'black'
|
||||
svg.style.backgroundColor = dark ? 'black' : 'white'
|
||||
}, colorScheme === 'dark')
|
||||
const box = await icon.boundingBox()
|
||||
if (box === null) throw new Error('Permission icon is not visible')
|
||||
expect([box.width, box.height]).toEqual([14, 14])
|
||||
expect([box.x * 2, box.y * 2]).toEqual([Math.round(box.x * 2), Math.round(box.y * 2)])
|
||||
const { data, info } = await sharp(await page.screenshot()).removeAlpha().raw().toBuffer({ resolveWithObject: true })
|
||||
const ink = (x: number, y: number) => {
|
||||
const intensity = data[((Math.round(box.y * 2) + y) * info.width + Math.round(box.x * 2) + x) * info.channels]! / 255
|
||||
return colorScheme === 'dark' ? intensity : 1 - intensity
|
||||
}
|
||||
// Scaling the 16-unit geometry to 14px changes edge coverage; integrated
|
||||
// ink must still measure one CSS pixel instead of shrinking to 0.875px.
|
||||
const verticalCoverage = Array.from({ length: 7 }, (_, x) => ink(x + 1, 10)).reduce((sum, value) => sum + value, 0)
|
||||
const horizontalCoverage = Array.from({ length: 6 }, (_, y) => ink(14, y + 9)).reduce((sum, value) => sum + value, 0)
|
||||
expect(verticalCoverage / 2).toBeCloseTo(1, 2)
|
||||
expect(horizontalCoverage / 2).toBeCloseTo(1, 2)
|
||||
|
||||
await page.keyboard.press('Escape')
|
||||
await page.getByRole('button', { name: 'Account menu', exact: true }).click()
|
||||
const accountMenu = page.getByRole('menu').filter({ has: page.getByRole('menuitem', { name: 'Settings', exact: true }) })
|
||||
const accountIcons = accountMenu.getByRole('menuitem').locator('svg')
|
||||
await expect.poll(() => accountIcons.count()).toBe(3)
|
||||
for (const accountIcon of await accountIcons.all()) {
|
||||
const accountBox = await accountIcon.boundingBox()
|
||||
expect(accountBox && [accountBox.width, accountBox.height]).toEqual([14, 14])
|
||||
}
|
||||
})
|
||||
|
||||
it('renders product icons from the sprite and swaps in a theme plugin replacement', async () => {
|
||||
const scaffold = await launchWebScaffold({ extraInstallAnchors: [join(FIXTURE, 'package.json')] })
|
||||
onTestFinished(() => scaffold.close())
|
||||
@@ -40,3 +88,66 @@ it('renders product icons from the sprite and swaps in a theme plugin replacemen
|
||||
await expect.poll(geometry).toEqual(defaults)
|
||||
await expect.poll(() => disc.count()).toBe(0)
|
||||
})
|
||||
|
||||
it.each([1, 2])('keeps icon stroke widths at device pixel ratio %s', async (deviceScaleFactor) => {
|
||||
const scaffold = await launchWebScaffold()
|
||||
onTestFinished(() => scaffold.close())
|
||||
const browser = await chromium.launch()
|
||||
onTestFinished(() => browser.close())
|
||||
const page = await browser.newPage({ deviceScaleFactor, locale: 'en-US' })
|
||||
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
|
||||
await page.locator('symbol[id="dsw-icon-plus-outline-regular"]').waitFor({ state: 'attached', timeout: 20_000 })
|
||||
|
||||
for (const dark of [false, true]) {
|
||||
for (const [weight, expectedWidth] of [['regular', 1], ['medium', 1.3]] as const) {
|
||||
for (const size of [14, 16, 20]) {
|
||||
await page.evaluate(({ size, weight, dark }) => {
|
||||
document.querySelector('[data-stroke-sample]')?.remove()
|
||||
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
|
||||
svg.setAttribute('data-stroke-sample', '')
|
||||
// CSS sizing must work even when the component's width/height attributes remain at 16.
|
||||
svg.setAttribute('width', '16')
|
||||
svg.setAttribute('height', '16')
|
||||
svg.style.cssText = `position:fixed;left:0;top:0;z-index:2147483647;display:block;width:${size}px;height:${size}px;color:${dark ? 'white' : 'black'};background:${dark ? 'black' : 'white'}`
|
||||
const use = document.createElementNS('http://www.w3.org/2000/svg', 'use')
|
||||
use.setAttribute('href', `#dsw-icon-plus-outline-${weight}`)
|
||||
svg.append(use)
|
||||
document.body.append(svg)
|
||||
}, { size, weight, dark })
|
||||
const { data, info } = await sharp(await page.locator('[data-stroke-sample]').screenshot()).removeAlpha().raw().toBuffer({ resolveWithObject: true })
|
||||
// Integrate coverage across the vertical stem, away from the horizontal bar.
|
||||
const row = Math.floor(info.height / 4)
|
||||
let coverage = 0
|
||||
for (let x = 0; x < info.width; x++) {
|
||||
const intensity = data[(row * info.width + x) * info.channels]! / 255
|
||||
coverage += dark ? intensity : 1 - intensity
|
||||
}
|
||||
expect(Math.abs(coverage / deviceScaleFactor - expectedWidth), `${size}px ${weight}, dark=${dark}`).toBeLessThan(0.04)
|
||||
}
|
||||
}
|
||||
for (const size of [12, 14]) {
|
||||
await page.evaluate(({ size, dark }) => {
|
||||
const svg = document.querySelector<SVGSVGElement>('[data-stroke-sample]')!
|
||||
svg.style.width = `${size}px`
|
||||
svg.style.height = `${size}px`
|
||||
svg.style.color = dark ? 'white' : 'black'
|
||||
svg.style.backgroundColor = dark ? 'black' : 'white'
|
||||
svg.querySelector('use')!.setAttribute('href', '#dsw-icon-browse-outline-regular')
|
||||
}, { size, dark })
|
||||
const { data, info } = await sharp(await page.locator('[data-stroke-sample]').screenshot()).removeAlpha().raw().toBuffer({ resolveWithObject: true })
|
||||
const ink = (x: number, y: number) => {
|
||||
const intensity = data[(y * info.width + x) * info.channels]! / 255
|
||||
return dark ? intensity : 1 - intensity
|
||||
}
|
||||
const scale = size * deviceScaleFactor / 16
|
||||
// The mixed glyph's filled side walls scale; its separate inner line does not.
|
||||
const row = Math.floor(7.5 * scale)
|
||||
const walls = Array.from({ length: info.width }, (_, x) => ink(x, row)).reduce((sum, value) => sum + value, 0)
|
||||
expect(Math.abs(walls / deviceScaleFactor / 2 - size / 16)).toBeLessThan(0.04)
|
||||
const column = Math.floor(7 * scale)
|
||||
let line = 0
|
||||
for (let y = Math.ceil(4 * scale); y <= Math.floor(7.5 * scale); y++) line += ink(column, y)
|
||||
expect(Math.abs(line / deviceScaleFactor - 1)).toBeLessThan(0.04)
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,79 @@
|
||||
/** Typed `@` mentions render as file and folder chips only when the Session's filesystem has the path. */
|
||||
import { mkdir, readFile, writeFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { chromium, type Browser, type Page } from 'playwright'
|
||||
import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
|
||||
import {
|
||||
captureStableAria, compareOrRefreshGolden, fixtureUserPrompts, launchWebScaffold, readPersistedEvents,
|
||||
watchConsole, webSnapshotMode, type WebScaffold,
|
||||
} from './scaffold.ts'
|
||||
import { connectFreshWorkspace, newEnglishPage, saveFailureShot, writeComposerDraft } from './support.ts'
|
||||
|
||||
const DIR = fileURLToPath(new URL('../../../snapshots/web/mention-path-presence', import.meta.url))
|
||||
const FIXTURE = join(DIR, 'session.v4.jsonl')
|
||||
const MODE = webSnapshotMode()
|
||||
const PROMPT = '@ceshi @随便写点文字 @LICENSE @docs/ mail@host'
|
||||
|
||||
describe.skipIf(MODE === 'record')('web e2e: mention path presence', () => {
|
||||
let scaffold: WebScaffold
|
||||
let browser: Browser
|
||||
let page: Page
|
||||
let tripwire: ReturnType<typeof watchConsole>
|
||||
|
||||
beforeAll(async () => {
|
||||
scaffold = await launchWebScaffold({
|
||||
replayFixture: FIXTURE,
|
||||
compareReplaySession: true,
|
||||
paceMs: 10,
|
||||
extraOverlayPath: fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)),
|
||||
})
|
||||
await mkdir(join(scaffold.workspaceCwd, 'workspace', 'docs'), { recursive: true })
|
||||
await writeFile(join(scaffold.workspaceCwd, 'workspace', 'LICENSE'), 'Reference fixture license.\n')
|
||||
browser = await chromium.launch()
|
||||
page = await newEnglishPage(browser)
|
||||
tripwire = watchConsole(page)
|
||||
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
|
||||
await page.waitForSelector('[class*="frame"]')
|
||||
await connectFreshWorkspace(page, scaffold.workspaceCwd)
|
||||
})
|
||||
|
||||
afterAll(async () => {
|
||||
try {
|
||||
await browser?.close()
|
||||
} finally {
|
||||
await scaffold?.close()
|
||||
}
|
||||
})
|
||||
|
||||
it('decorates typed mentions of existing paths and keeps other @ text verbatim across reload', async () => {
|
||||
onTestFailed(() => saveFailureShot(page, 'mention-path-presence'))
|
||||
const composer = page.locator('[data-composer-input][contenteditable="true"]').last()
|
||||
await writeComposerDraft(page, composer, PROMPT)
|
||||
// The trailing token is not a mention, so no completion is open to take the Enter.
|
||||
await page.getByRole('listbox', { name: 'Trigger suggestions' }).waitFor({ state: 'hidden' })
|
||||
expect(await composer.locator('[data-composer-chip]').count()).toBe(0)
|
||||
|
||||
const settled = scaffold.whenTurnSettled()
|
||||
await composer.press('Enter')
|
||||
const sessionId = await settled
|
||||
const persisted = (await readPersistedEvents(scaffold, sessionId))
|
||||
.find(event => event.type === 'user/message' && event.data.source.kind === 'user')
|
||||
expect(persisted).toMatchObject({ data: { content: [{ type: 'text', text: PROMPT }] } })
|
||||
expect(fixtureUserPrompts(await readFile(FIXTURE, 'utf8'))).toEqual([PROMPT])
|
||||
|
||||
for (const reload of [false, true]) {
|
||||
if (reload) await page.reload({ waitUntil: 'load' })
|
||||
const bubble = page.locator('[data-chat-flow-kind="user"]')
|
||||
await expect.poll(() => bubble.locator('[data-ref-chip]').allTextContents()).toEqual(['LICENSE', 'docs'])
|
||||
expect(await bubble.textContent()).toContain('@ceshi @随便写点文字 ')
|
||||
expect(await bubble.textContent()).toContain(' mail@host')
|
||||
await bubble.getByRole('button', { name: 'LICENSE', exact: true }).click()
|
||||
await page.getByText('Reference fixture license.', { exact: true }).waitFor()
|
||||
}
|
||||
await compareOrRefreshGolden(join(DIR, 'ui.expected.md'),
|
||||
await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd), MODE)
|
||||
expect(tripwire.pageErrors).toEqual([])
|
||||
expect(tripwire.warnings).toEqual([])
|
||||
})
|
||||
})
|
||||
Loaded 100 of 1155 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user