Merge remote-tracking branch 'origin/master' into refactor/deepseek-auth

# Conflicts:
#	docs/capability-seams.i18n.yaml
This commit is contained in:
LegGasai committed 2026-11-17 16:15:48 +08:00
commit 62a2f77b2b
514 files changed
+13194 -2554

No files matched your search

@@ -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
@@ -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)负责保留状态的超时和取消恢复。普通异常保留此前发生的修改。保留的函数使用当前执行的宿主绑定;较早执行中的异步任务不能获取后续执行的工具权限或向其输出。
## 考虑过的替代方案
@@ -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
@@ -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
@@ -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-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 会以嵌套深度有界的扁平协议格式传输数据并执行无损校验,但不会降低中间值的开销,也不会使其具备持久性。必需完成值超限会显式导致运行失败,错误处理则有意由人类引导,而不是依赖带版本的错误代码联合。
## 已知限制与暂缓事项
@@ -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.
@@ -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,以及确认框的渲染与回调。
@@ -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` 在自身激活前就需要恢复参数,早于同步配置能参与的时间点 |
+2 -2
View File
@@ -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,
+3 -1
View File
@@ -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.
+6 -5
View File
@@ -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({
+1
View File
@@ -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:*",
+9 -4
View File
@@ -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) => {
@@ -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": {
@@ -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"}
@@ -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')
}
@@ -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
+1 -1
View File
@@ -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,
-6
View File
@@ -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) })
+48 -3
View File
@@ -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'])
+106
View File
@@ -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)
+3 -11
View File
@@ -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)
@@ -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"
}
}
}
+45 -8
View File
@@ -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 项进行中')
@@ -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([])
})
})
+12 -10
View File
@@ -159,19 +159,21 @@ it.each([false, true])('keeps the same revision, Session and page across a serve
})
socket.on('framereceived', ({ payload }) => {
if (typeof payload !== 'string') return
const message = JSON.parse(payload) as { type?: string; streamId: string; value?: { type?: string }; error?: unknown }
const message = JSON.parse(payload) as {
type?: string
streamId: string
value?: { type?: string; graph?: typeof graphs[number] }
error?: unknown
}
if (message.type === 'error') streamErrors.push(message.error)
if (message.type === 'item' && message.value?.type === 'ready') readyFrames++
if (message.type === 'item' && endpoints.get(message.streamId) === 'session/follow'
&& message.value?.type === 'snapshot') sessionBaselines++
if (message.type !== 'item') return
const endpoint = endpoints.get(message.streamId)
if (message.value?.type === 'ready') readyFrames++
if (endpoint === 'session/follow' && message.value?.type === 'snapshot') sessionBaselines++
// Every plugin-events stream generation opens with a baseline graph; later graph changes arrive as `graph`.
if (endpoint === 'pluginEvents/follow' && message.value?.graph !== undefined) graphs.push(message.value.graph)
})
})
const network = await page.context().newCDPSession(page)
await network.send('Network.enable')
network.on('Network.eventSourceMessageReceived', (event) => {
const message = JSON.parse(event.data) as { type?: string; graph: typeof graphs[number] }
if (message.type === 'graph') graphs.push(message.graph)
})
onTestFailed(async () => {
await saveFailureShot(page, 'web-server-restart-' + scenarioId)
await writeFile(join(REPO_ROOT, '.artifacts', 'server-restart-' + scenarioId + '.json'), JSON.stringify({ errors, streamErrors, graphs, server: server.logs() }, null, 2))
+20 -2
View File
@@ -184,7 +184,11 @@ async function assertMaskFade(frame: Locator, from: number, to: number): Promise
})
}
/** Sample both width transitions on the same clock to detect detached sidebar controls. */
/**
* Sample both width transitions on the same clock to detect detached sidebar controls.
* Returns only after this sample's transitions can no longer dispatch an end event, so
* the caller's next posture change starts from a window that no pending event settles.
*/
async function assertFoldResize(toggle: Locator, from: number, to: number): Promise<void> {
await expect.poll(() => toggle.evaluate((button, target) => {
const frame = button.closest<HTMLElement>('[data-animating]')
@@ -208,7 +212,14 @@ async function assertFoldResize(toggle: Locator, from: number, to: number): Prom
const start = at(0)
const middle = at(0.5)
const end = at(1)
for (const transition of transitions) transition.finish()
// Cancel instead of finish: a finished transition queues its transitionend for a
// later rendering update, and an end event arriving after the caller's next posture
// change settles the new window, drops data-animating and cancels the transition the
// next assertFoldResize looks for. A cancelled transition dispatches transitioncancel,
// which AppFrame does not observe, so this sample leaves no end event pending. Both
// values stay at the end state: cancelling drops the transition effect, and the
// computed grid lands on the same target the finished transition would show.
for (const transition of transitions) transition.cancel()
frame.style.removeProperty('--ds-transition-duration-slow')
return { endpoints: [start.width, end.width], start, middle }
})
@@ -216,6 +227,13 @@ async function assertFoldResize(toggle: Locator, from: number, to: number): Prom
expect(sample.middle.width).toBeGreaterThan(Math.min(from, to))
expect(sample.middle.width).toBeLessThan(Math.max(from, to))
expect(sample.middle.gap).toBeCloseTo(sample.start.gap, 1)
// AppFrame removes data-animating either from a transitionend or from its own 600 ms
// fallback, which is the only remaining settle path once the transitions are cancelled.
// Wait for that settle so the caller's next posture change starts from a clear window.
await expect.poll(
() => toggle.evaluate(button => button.closest('[data-animating]') === null),
{ timeout: 5_000 },
).toBe(true)
}
it('overlays the conversation and closes after navigation without losing its sidebar content', async () => {
+4 -4
View File
@@ -48,7 +48,7 @@ const LABEL = 'event-sourcing researcher'
const CHILD_NAME = 'agent-1'
const ONE_SHOT_LABEL = 'event-sourcing reviewer'
const NESTED_LABEL = 'example editor'
const CHILD_TITLE = 'Explain event sourcing in one'
const CHILD_TITLE = 'Now give the same explanation'
const PARENT_PROMPT = 'Ask a research subagent to explain event sourcing.'
const INITIAL_PROMPT = 'Explain event sourcing in one sentence.'
/** The grandchild's own first message; its arrival is what says its history finished loading. */
@@ -693,7 +693,7 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
await (await showSubagentsSection(page)).getByRole('treeitem', { name: new RegExp(LABEL) })
.getByRole('button', { name: `Open ${LABEL} in sidebar`, exact: true }).click()
const sidebarChat = page.locator('[data-sidebar-chat]')
await sidebarChat.getByText(/^Explain event sourcing in one sentence\./).waitFor({ timeout: 15_000 })
await sidebarChat.getByRole('button', { name: /^Task message received/ }).waitFor({ timeout: 15_000 })
await compareOrRefreshGolden(
SIDEBAR_CHAT_EXPECTED,
await captureStableAria(page, '[data-sidebar-chat]', scaffold.workspaceCwd),
@@ -715,7 +715,7 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-open'))
await (await showSubagentsSection(page)).getByRole('treeitem', { name: new RegExp(LABEL) }).getByText(LABEL, { exact: true }).click()
await expect.poll(
() => page.getByText(/^Explain event sourcing in one sentence\./).count(),
() => page.getByRole('button', { name: /^Task message received/ }).count(),
{ timeout: 15_000 },
).toBe(1)
if (scaffold.ctx.agents.get(childId) !== undefined) {
@@ -773,7 +773,7 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
await expect.poll(() => requested, { timeout: 15_000 }).toBe(true)
expect(await page.getByText('This subagent is read-only for now', { exact: true }).count()).toBe(0)
expect(await page.getByRole('navigation', { name: 'Session hierarchy' }).count()).toBe(0)
expect(await page.getByText(/^Explain event sourcing in one sentence\./).count()).toBe(0)
expect(await page.getByRole('button', { name: /^Task message received/ }).count()).toBe(0)
releaseCatalog()
await page.getByRole('button', { name: `Switch subagent: ${LABEL}` }).waitFor({ timeout: 15_000 })
const input = page.getByRole('textbox', { name: 'Message or run a task, / commands, @ files or sessions' })
+3 -3
View File
@@ -21,8 +21,8 @@ it('places the inherited-history divider between the parent turn and the child p
const paths = await Promise.all(['session.v4.jsonl', 'session.1.v4.jsonl']
.map(file => selectedSessionFixture(join(DIR, file))))
const childPrompt = parseSessionLog(await readFile(paths[1]!, 'utf8')).findLast(event =>
event.type === 'user/message' && event.data.source.kind === 'user')
if (childPrompt?.type !== 'user/message') throw new Error('child fixture has no user prompt')
event.type === 'user/message' && event.data.source.kind === 'agent-message')
if (childPrompt?.type !== 'user/message') throw new Error('child fixture has no delegated task')
const scaffold = await launchWebScaffold({
replayFixture: paths[0]!, replayChildFixtures: [paths[1]!], compareReplaySession: false,
})
@@ -43,7 +43,7 @@ it('places the inherited-history divider between the parent turn and the child p
const activation = await scaffold.ctx.subagents.startActivation({
provider: 'fork', label: LABEL, delivery: 'caller',
signal: new AbortController().signal, parent, prompt: [...childPrompt.data.content],
signal: new AbortController().signal, parent, prompt: childPrompt.data.content.slice(1),
})
try {
await activation.result
+116 -37
View File
@@ -1,9 +1,11 @@
/** Forked Web agents inherit the standard preset and refuse every reminder tool. */
/** Recorded Web subagent composition, tool restrictions, and human-message attribution. */
import { readFile, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { expect, it } from 'vitest'
import { createUserMessage } from '@deepseek-ai/dsh-llm'
import { brandString } from '@deepseek-ai/dsh-brand'
import type { SubagentPromptRequestId } from '@deepseek-ai/dsh-subagent'
import { createUserMessage, type ContentBlock } from '@deepseek-ai/dsh-llm'
import { parseSessionLog, prepareSessionSnapshotFixtureForComparison } from '@deepseek-ai/dsh-llm-replay'
import type { Session } from '@deepseek-ai/dsh-session'
import {
@@ -27,7 +29,7 @@ const MODE = webSnapshotMode()
it.skipIf(MODE === 'record')('replays inherited schedule tools and refusals in a seeded Web fork', async () => {
const paths = await Promise.all(['session.v4.jsonl', 'session.1.v4.jsonl']
.map(file => selectedSessionFixture(join(DIR, file))))
let expected = await Promise.all(paths.map(path => readFile(path, 'utf8')))
const expected = await Promise.all(paths.map(path => readFile(path, 'utf8')))
const scaffold = await launchWebScaffold({
replayFixture: paths[0]!, replayChildFixtures: [paths[1]!], compareReplaySession: false,
})
@@ -42,13 +44,12 @@ it.skipIf(MODE === 'record')('replays inherited schedule tools and refusals in a
parent.followup(createUserMessage({ content: [{ type: 'text', text: prompt }], source: { kind: 'user' } }))
await parent.whenIdle()
const childPrompt = parseSessionLog(expected[1]!).findLast(event => event.type === 'user/message'
&& event.data.source.kind === 'user')
if (childPrompt?.type !== 'user/message') throw new Error('child fixture has no user prompt')
const childPrompt = fixtureChildInputs(expected[1]!)[0]
if (childPrompt === undefined) throw new Error('child fixture has no delegated task')
const activation = await scaffold.ctx.subagents.startActivation({
provider: 'fork', label: 'Check child reminder refusal', delivery: 'caller',
signal: new AbortController().signal,
parent, prompt: [...childPrompt.data.content],
parent, prompt: childPrompt,
})
try {
await activation.result
@@ -62,22 +63,6 @@ it.skipIf(MODE === 'record')('replays inherited schedule tools and refusals in a
expect(child.inheritedEventCount).toBeGreaterThan(0)
expect(child.requestHeader()).toEqual(parent.session.requestHeader())
for (const session of sessions) {
expect(await readPersistedEvents(scaffold, session.id)).toEqual(session.snapshotEvents())
}
const raw = sessions.map(session => normalizeWebSessionVolatiles(rawSessionLog(session), scaffold.workspaceCwd))
const context = { sessionIds: sessions.map(session => String(session.id)), cwd: scaffold.workspaceCwd }
const schemas = parseToolSchemasSnapshot(await readFile(join(PIN, 'tool-schemas.expected.json'), 'utf8'))
const promptPin = await readFile(join(PIN, 'system-prompt.expected.md'), 'utf8')
for (const log of raw) {
const headers = normalizedToolSchemas(log, context)
expect(headers.length).toBeGreaterThan(0)
for (const tools of headers) expect(tools).toEqual(schemas.initial)
for (const prompt of normalizedSystemPrompts(log, context)) {
expect(formatSystemPromptSnapshot(prompt.split(REPO_ROOT).join('{{sourceRoot}}')
.split(scaffold.baseUrl).join('{{webUrl}}'))).toBe(promptPin)
}
}
const results = child.snapshotEvents().slice(child.inheritedEventCount)
.filter(event => event.type === 'tool/result')
expect(results.map(event => event.data.message.content)).toEqual(Array.from({ length: 4 }, () => [
@@ -85,21 +70,115 @@ it.skipIf(MODE === 'record')('replays inherited schedule tools and refusals in a
]))
expect((await scaffold.ctx.schedule.list({ active: true })).items).toEqual([])
if (MODE === 'refresh') {
const replacements = refreshFixtureReplacements(raw.map((content, index) => ({
id: sessions[index]!.id, createdAt: sessions[index]!.header.createdAt, content,
})), expected)
expected = redactSessionSnapshotIds(stabilizeFixtureMessageIds(raw.map((log, index) =>
tokenizeSessionFixtureCwd(scrubSessionSnapshot(stabilizeRefreshLog(
prepareSessionSnapshotFixtureForComparison(log), expected[index]!, replacements, context,
))).split(scaffold.harnessHome).join('{{harnessHome}}')), expected))
await Promise.all(expected.map((log, index) => writeFile(
recordedSessionFixturePath(paths[index]!, sessions[index]!.header.version), log,
)))
}
expect(normalizeSessionSnapshots(raw, context))
.toEqual(normalizeSessionSnapshots(expected, fixtureContext(expected[0]!)))
await assertSubagentSessions(scaffold, sessions, paths, expected)
} finally {
await scaffold.close()
}
})
const HUMAN_DIR = fileURLToPath(new URL('../../../snapshots/web/subagent-human-message', import.meta.url))
it.skipIf(MODE === 'record')('distinguishes the delegated task from a direct human message after a Web subagent cold resume', async () => {
const paths = await Promise.all(['session.v4.jsonl', 'session.1.v4.jsonl']
.map(file => selectedSessionFixture(join(HUMAN_DIR, file))))
const expected = await Promise.all(paths.map(path => readFile(path, 'utf8')))
const scaffold = await launchWebScaffold({
replayFixture: paths[0]!, replayChildFixtures: [paths[1]!], compareReplaySession: false,
})
try {
const { sessionId } = await scaffold.ctx.sessionController.create({ cwd: scaffold.workspaceCwd })
const parent = scaffold.ctx.agents.get(sessionId)!
parent.followup(createUserMessage({
content: [{ type: 'text', text: fixtureUserPrompts(expected[0]!)[0]! }],
source: { kind: 'user', rpcId: brandString<SubagentPromptRequestId>('root-question') },
}))
await parent.whenIdle()
let child: Session | undefined
scaffold.ctx.on('subagent/start', (info) => { child = scaffold.ctx.agents.get(info.id)!.session })
const inputs = fixtureChildInputs(expected[1]!)
const activation = await scaffold.ctx.subagents.startActivation({
provider: 'fork', label: 'Identify direct human messages', delivery: 'caller',
parent, prompt: inputs[0]!, signal: new AbortController().signal,
})
try {
await activation.result
} finally {
await activation.dispose()
}
expect(scaffold.ctx.agents.get(activation.childId)).toBeUndefined()
const settled = Promise.withResolvers<undefined>()
scaffold.ctx.on('subagent/end', (info) => {
if (info.id === activation.childId) settled.resolve(undefined)
})
const content = inputs[1]!.map((block) => {
if (block.type !== 'text') throw new Error('human fixture input must be text')
return block
})
const receipt = await scaffold.ctx.subagents.prompt({
childSessionId: activation.childId,
requestId: brandString<SubagentPromptRequestId>('human-question'), delivery: 'steer', content,
}, new AbortController().signal)
await settled.promise
await parent.whenIdle()
await scaffold.ctx.sessions.flush(parent.session)
if (child === undefined) throw new Error('subagent start did not expose its Session')
const received = child.deriveMessages().find(message => message.id === receipt.messageId)
expect(received).toMatchObject({
source: { kind: 'user', rpcId: 'human-question' },
content,
})
await assertSubagentSessions(scaffold, [parent.session, child], paths, expected)
} finally {
await scaffold.close()
}
})
/** Compare durable parent/child logs and the shared Web request-header pins. */
async function assertSubagentSessions(
scaffold: Awaited<ReturnType<typeof launchWebScaffold>>,
sessions: Session[],
paths: string[],
expected: string[],
): Promise<void> {
for (const session of sessions) {
expect(await readPersistedEvents(scaffold, session.id)).toEqual(session.snapshotEvents())
}
const raw = sessions.map(session => normalizeWebSessionVolatiles(rawSessionLog(session), scaffold.workspaceCwd))
const context = { sessionIds: sessions.map(session => String(session.id)), cwd: scaffold.workspaceCwd }
const schemas = parseToolSchemasSnapshot(await readFile(join(PIN, 'tool-schemas.expected.json'), 'utf8'))
const promptPin = await readFile(join(PIN, 'system-prompt.expected.md'), 'utf8')
for (const log of raw) {
const headers = normalizedToolSchemas(log, context)
expect(headers.length).toBeGreaterThan(0)
for (const tools of headers) expect(tools).toEqual(schemas.initial)
for (const prompt of normalizedSystemPrompts(log, context)) {
expect(formatSystemPromptSnapshot(prompt.split(REPO_ROOT).join('{{sourceRoot}}')
.split(scaffold.baseUrl).join('{{webUrl}}'))).toBe(promptPin)
}
}
if (MODE === 'refresh') {
const replacements = refreshFixtureReplacements(raw.map((content, index) => ({
id: sessions[index]!.id, createdAt: sessions[index]!.header.createdAt, content,
})), expected)
expected = redactSessionSnapshotIds(stabilizeFixtureMessageIds(raw.map((log, index) =>
tokenizeSessionFixtureCwd(scrubSessionSnapshot(stabilizeRefreshLog(
prepareSessionSnapshotFixtureForComparison(log), expected[index]!, replacements, context,
))).split(scaffold.harnessHome).join('{{harnessHome}}')), expected))
await Promise.all(expected.map((log, index) => writeFile(
recordedSessionFixturePath(paths[index]!, sessions[index]!.header.version), log,
)))
}
expect(normalizeSessionSnapshots(raw, context))
.toEqual(normalizeSessionSnapshots(expected, fixtureContext(expected[0]!)))
}
/** Read the child's admitted inputs, removing the parent prefix when recreating its initial task. */
function fixtureChildInputs(log: string): ContentBlock[][] {
const events = parseSessionLog(log)
const start = events.findLastIndex(event => event.type === 'subagent/descriptor')
return events.slice(start + 1).flatMap(event => event.type === 'agent/inbox/spliced'
? event.data.inserted.map(message => message.source.kind === 'agent-message'
? message.content.slice(1)
: [...message.content])
: [])
}
+13 -4
View File
@@ -212,7 +212,7 @@ describe.skipIf(MODE === 'record')('web e2e: composer interrupt for a running co
await (await showSessionPanel(page)).getByRole('treeitem', { name: new RegExp(LABEL) }).press('Enter')
const input = page.locator('[data-composer-input]').first()
await input.waitFor({ timeout: 15_000 })
await page.getByText(/^Explain event sourcing in one sentence\./)
await page.getByRole('button', { name: /^Task message received/ })
.waitFor({ timeout: 15_000 })
expect(await input.isDisabled()).toBe(false)
const stop = page.getByRole('button', { name: 'Stop generating' })
@@ -363,9 +363,18 @@ describe.skipIf(MODE === 'record')('web e2e: composer interrupt for a running co
&& event.data.source.kind === 'user'
? event.data.content.flatMap(block => block.type === 'text' ? [block.text] : [])
: [])
expect(userTexts[0]).toBe(INITIAL)
expect(userTexts[1]).toMatch(/^Your final answer is delivered automatically if your parent is still online\./)
expect(userTexts.slice(2)).toEqual([REARM, REARM_WAKE, EDITED_FOLLOWUP, WAKING])
expect(userTexts).toEqual([REARM, REARM_WAKE, EDITED_FOLLOWUP, WAKING])
const delegatedTask = events.find(event => event.type === 'user/message'
&& event.data.source.kind === 'agent-message')
const taskContent = delegatedTask?.type === 'user/message' ? delegatedTask.data.content : undefined
expect(taskContent).toHaveLength(3)
expect(taskContent?.slice(0, 2)).toEqual([
{ type: 'text', text: 'Agent lead sent a message: ' },
{ type: 'text', text: INITIAL },
])
const guidance = taskContent?.[2]
expect(guidance?.type === 'text' && guidance.text)
.toMatch(/^Your final answer is delivered automatically if your parent is still online\./)
const imageMessage = events.find(event => event.type === 'user/message'
&& event.data.content.some(block => block.type === 'image'))
expect(imageMessage?.type === 'user/message' && imageMessage.data.content.map(block => block.type)).toEqual(['image'])
+12 -3
View File
@@ -183,9 +183,18 @@ describe.skipIf(MODE === 'record')('web e2e: subagents/interruptByUser over the
&& event.data.source.kind === 'user'
? event.data.content.flatMap(block => block.type === 'text' ? [block.text] : [])
: [])
expect(userTexts[0]).toBe(INITIAL)
expect(userTexts[1]).toMatch(/^Your final answer is delivered automatically if your parent is still online\./)
expect(userTexts.slice(2)).toEqual([FOLLOWUP, WAKING])
expect(userTexts).toEqual([FOLLOWUP, WAKING])
const delegatedTask = events.find(event => event.type === 'user/message'
&& event.data.source.kind === 'agent-message')
const taskContent = delegatedTask?.type === 'user/message' ? delegatedTask.data.content : undefined
expect(taskContent).toHaveLength(3)
expect(taskContent?.slice(0, 2)).toEqual([
{ type: 'text', text: 'Agent lead sent a message: ' },
{ type: 'text', text: INITIAL },
])
const guidance = taskContent?.[2]
expect(guidance?.type === 'text' && guidance.text)
.toMatch(/^Your final answer is delivered automatically if your parent is still online\./)
const turnEndKinds = events
.filter(event => event.type === 'turn/end')
.map(event => (event).data.reason.kind)
+4 -2
View File
@@ -173,7 +173,8 @@ describe.skipIf(MODE === 'record')('web e2e: durable workflow run in Chat', () =
await page.setViewportSize({ width: 1280, height: 800 })
await member.click()
await page.getByText(CHILD_PROMPT, { exact: true }).waitFor({ timeout: 15_000 })
await page.getByRole('button', { name: /^Task message received/ }).click()
await page.getByText(`Agent lead sent a message: ${CHILD_PROMPT}`, { exact: true }).waitFor({ timeout: 15_000 })
const sessions = page.getByRole('tree', { name: 'Sessions' })
await sessions.getByRole('treeitem', { name: /Use the workflow tool exactly/ }).click()
@@ -221,7 +222,8 @@ describe.skipIf(MODE === 'record')('web e2e: durable workflow run in Chat', () =
const catalog = (await showSessionPanel(page)).getByRole('tree', { name: 'Subagent sessions' })
await catalog.getByRole('treeitem', { name: /snapshot-flow child 1/ }).press('Enter')
await page.getByText(CHILD_PROMPT, { exact: true }).waitFor({ timeout: 15_000 })
await page.getByRole('button', { name: /^Task message received/ }).click()
await page.getByText(`Agent lead sent a message: ${CHILD_PROMPT}`, { exact: true }).waitFor({ timeout: 15_000 })
expect(await page.locator('[data-composer-input][contenteditable="true"]').count()).toBe(1)
}, 60_000)
+2
View File
@@ -129,6 +129,7 @@
"tests/plugin-install-github.e2e.ts",
"tests/plugin-install-silent-failure.e2e.ts",
"tests/client-plugin-live.e2e.ts",
"tests/client-config-sync.e2e.ts",
"tests/icon-skin.e2e.ts",
"tests/draft-initialization.e2e.ts",
"tests/settings-chrome.e2e.ts",
@@ -201,6 +202,7 @@
"tests/markdown-file-links.e2e.ts",
"tests/user-text-secret-mask.e2e.ts",
"tests/reference-composer.e2e.ts",
"tests/mention-path-presence.e2e.ts",
"tests/markdown-wide-table.e2e.ts",
"tests/thinking-markdown.e2e.ts",
"tests/math-rendering.e2e.ts",
+2 -2
View File
@@ -6,5 +6,5 @@
en: 41d772192075e133
zh: 5ef3da69b4de1d8a
/capability-seams-and-core-services:
en: cdb67d50687e835f
zh: c0f394692ea9dd63
en: ed07ace42d0688a8
zh: 583265fbcce148db
+5
View File
@@ -314,6 +314,8 @@ flowchart LR
pkg_web_app["web-app"]
svc_webApp["ctx.webApp<br/>Served Web GUI"]
pkg_harness_dev_context["harness-dev-context"]
pkg_client_config["client-config"]
svc_config["ctx.config<br/>Browser synced configuration lookup"]
svc_clientModules["ctx.clientModules<br/>Client plugin graph host"]
pkg_workflow["workflow"]
svc_workflowEngine["ctx.workflowEngine<br/>Workflow script engine"]
@@ -354,10 +356,12 @@ flowchart LR
pkg_bash_local --> svc_shell
pkg_bash_sandbox --> svc_shell
pkg_browser_use --> svc_browserUse
pkg_client_config --> svc_config
pkg_client_connection --> svc_connection
pkg_client_connection --> svc_connection_authentication
pkg_client_file_upload --> svc_fileUploads
pkg_client_modules --> svc_clientModules
pkg_client_modules --> svc_config
pkg_client_product_analytics --> svc_productAnalytics
pkg_client_ui_connector_account --> svc_connectorAccounts
pkg_client_ui_plugin_manager --> svc_pluginRegistryProbe
@@ -788,6 +792,7 @@ flowchart LR
| `ctx.directoryPicker` | `seam` | [`host-directory-picker`](../packages/host/directory-picker) | [`host-directory-picker-native`](../packages/host/directory-picker-native), [`host-directory-picker-browse`](../packages/host/directory-picker-browse) | [`api-workspace-controller`](../packages/api/workspace-controller) | - | Discriminated interaction capability: the native backend opens one OS chooser on the host display, the browse backend serves listing/creation primitives for the in-app browser; dual-face backends fill ui-workspace directory-flow slots from their browser halves (no wire advertisement). |
| `ctx.webServer` | `core` | [`host-webserver`](../packages/host/webserver) | - | [`client-connection`](../packages/client/connection), [`client-modules`](../packages/client/modules), [`client-hmr`](../packages/client/hmr) | - | Plain node:http carrier: named-route registry, index transform taps, and the static dist fallback; web-transport plugins register their own routes. |
| `ctx.webApp` | `core` | [`web-app`](../packages/bundle/web-app) | - | [`harness-dev-context`](../packages/context/harness-dev-context) | - | The web-runtime row advertises one URL for its Web GUI: the configured publicUrl, otherwise the listener origin; DSH_WEB_URL, the startup URL, and harness-dev-context read the same value. |
| `ctx.config` | `service` | [`client-config`](../packages/client/config) | [`client-modules`](../packages/client/modules) | - | - | Types-only declaration; the client-modules plugin face provides the read-only lookup of each package's current synced Config. |
| `ctx.clientModules` | `core` | [`client-modules`](../packages/client/modules) | - | [`client-hmr`](../packages/client/hmr) | - | Composes the __DSH_BOOT__ entry graph from an incremental dsh.client scan, serves plugin bundles, and notifies rebuilt/graph-changed subscribers. |
| `ctx.workflowEngine` | `seam` | [`workflow`](../packages/workflow/workflow) | [`workflow-ptc`](../packages/workflow/workflow-ptc) | [`tool-workflow`](../packages/workflow/tool-workflow), [`tool-ralph`](../packages/experimental/tool-ralph) | - | One engine per context, as in bash, with no named-provider registry; the general workflow and fixed Ralph consumers start runs whose agent() calls fan out through ctx.subagents. |
| `ctx.webhookRuntime` | `core` | [`webhook`](../packages/experimental/webhook) | - | [`webhook-github`](../packages/experimental/webhook-github) | - | Provider adapters dispatch authenticated deliveries; trusted plugins register independent process-local rules, and the runtime turns non-null results into ordinary Workspace-backed Sessions without delivery or completion state. |
+5
View File
@@ -316,6 +316,8 @@ flowchart LR
pkg_web_app["web-app"]
svc_webApp["ctx.webApp<br/>Served Web GUI"]
pkg_harness_dev_context["harness-dev-context"]
pkg_client_config["client-config"]
svc_config["ctx.config<br/>Browser synced configuration lookup"]
svc_clientModules["ctx.clientModules<br/>Client plugin graph host"]
pkg_workflow["workflow"]
svc_workflowEngine["ctx.workflowEngine<br/>Workflow script engine"]
@@ -356,10 +358,12 @@ flowchart LR
pkg_bash_local --> svc_shell
pkg_bash_sandbox --> svc_shell
pkg_browser_use --> svc_browserUse
pkg_client_config --> svc_config
pkg_client_connection --> svc_connection
pkg_client_connection --> svc_connection_authentication
pkg_client_file_upload --> svc_fileUploads
pkg_client_modules --> svc_clientModules
pkg_client_modules --> svc_config
pkg_client_product_analytics --> svc_productAnalytics
pkg_client_ui_connector_account --> svc_connectorAccounts
pkg_client_ui_plugin_manager --> svc_pluginRegistryProbe
@@ -790,6 +794,7 @@ flowchart LR
| `ctx.directoryPicker` | `seam` | [`host-directory-picker`](../packages/host/directory-picker) | [`host-directory-picker-native`](../packages/host/directory-picker-native), [`host-directory-picker-browse`](../packages/host/directory-picker-browse) | [`api-workspace-controller`](../packages/api/workspace-controller) | - | 带判别标记的交互能力:原生后端在 Host 显示设备上打开一个操作系统选择器,浏览后端为应用内浏览器提供列表与创建原语;双端后端通过其浏览器侧填充 ui-workspace 目录流程的 slot(不通过协议发布)。 |
| `ctx.webServer` | `core` | [`host-webserver`](../packages/host/webserver) | - | [`client-connection`](../packages/client/connection), [`client-modules`](../packages/client/modules), [`client-hmr`](../packages/client/hmr) | - | 普通的 node:http 载体:具名路由注册表、索引转换 tap,以及静态 dist 回退;Web 传输插件注册自己的路由。 |
| `ctx.webApp` | `core` | [`web-app`](../packages/bundle/web-app) | - | [`harness-dev-context`](../packages/context/harness-dev-context) | - | web-runtime 行为其 Web GUI 公告一个 URL:配置了 publicUrl 时用它,否则用监听器 origin;DSH_WEB_URL、启动 URL 与 harness-dev-context 读取同一个值。 |
| `ctx.config` | `service` | [`client-config`](../packages/client/config) | [`client-modules`](../packages/client/modules) | - | - | 只有类型的声明;client-modules 插件面提供对各包当前同步 Config 的只读查询。 |
| `ctx.clientModules` | `core` | [`client-modules`](../packages/client/modules) | - | [`client-hmr`](../packages/client/hmr) | - | 通过增量 `dsh.client` 扫描组合 __DSH_BOOT__ 入口图,提供插件组合包,并通知重建/图变更订阅方。 |
| `ctx.workflowEngine` | `seam` | [`workflow`](../packages/workflow/workflow) | [`workflow-ptc`](../packages/workflow/workflow-ptc) | [`tool-workflow`](../packages/workflow/tool-workflow), [`tool-ralph`](../packages/experimental/tool-ralph) | - | 每个上下文使用一个引擎,与 bash 相同,且没有具名提供方注册表;通用工作流与固定 Ralph 消费方启动运行,其中的 agent() 调用通过 ctx.subagents 扇出。 |
| `ctx.webhookRuntime` | `core` | [`webhook`](../packages/experimental/webhook) | - | [`webhook-github`](../packages/experimental/webhook-github) | - | 提供方适配器分派已认证交付;可信插件注册独立的进程本地规则,runtime 把非 null 结果转换为普通的 Workspace-backed Session,不保留交付或完成状态。 |
+25 -5
View File
@@ -222,7 +222,7 @@ export interface Config {
## `@deepseek-ai/dsh-api-gateway`
- `inject`: `typert` · `remoteAccess`
- `source`: [`packages/api/gateway/src/index.ts:157`](../packages/api/gateway/src/index.ts)
- `source`: [`packages/api/gateway/src/index.ts:158`](../packages/api/gateway/src/index.ts)
```ts config-catalog
/** Gateway transport configuration. */
@@ -231,6 +231,11 @@ export interface Config {
readonly websocketHeartbeatIntervalMs?: number
/** Buffered uplink frame bytes one logical stream may hold before it fails with `gateway/uplink-overflow`. @default 262144 */
readonly streamInboxBytes?: number
/**
* Encoded downlink bytes one WebSocket connection may have queued and unwritten before every logical stream on it
* pauses reading its source. Items leave in the order their streams produced them. @default 1048576
*/
readonly streamOutboxBytes?: number
/** Per-message compression for the Remote stream WebSocket; `'none'` disables the extension. @default 'deflate' */
readonly websocketCompression?: 'none' | 'deflate'
}
@@ -539,8 +544,8 @@ export interface ConnectionRecoveryConfig {
## `@deepseek-ai/dsh-client-hmr`
- `inject`: `clientModules` · `webServer`
- `source`: [`packages/client/hmr/src/index.ts:30`](../packages/client/hmr/src/index.ts)
- `inject`: `clientModules`
- `source`: [`packages/client/hmr/src/index.ts:26`](../packages/client/hmr/src/index.ts)
```ts config-catalog
/** Plugin config, validated by the same-named schemastery schema. */
@@ -2953,7 +2958,7 @@ export interface Config {
timeoutMs?: number
/** Maximum numeric elapsed budget accepted by resolve. */
maxTimeoutMs?: number
/** Combined serialized logs, completion and diagnostic byte cap. */
/** Combined serialized output and completion or diagnostic cap; terminal data takes priority over captured output. */
maxOutputBytes?: number
/** V8 old-generation heap limit in MiB; native allocations are excluded. */
maxOldGenerationSizeMb?: number
@@ -3269,7 +3274,7 @@ export type SessionLogCompressionLevel = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
## `@deepseek-ai/dsh-session-persistence-jsonl`
- `source`: [`packages/session/session-persistence-jsonl/src/index.ts:95`](../packages/session/session-persistence-jsonl/src/index.ts)
- `source`: [`packages/session/session-persistence-jsonl/src/index.ts:107`](../packages/session/session-persistence-jsonl/src/index.ts)
```ts config-catalog
/** Plugin config for the JSONL backend's root, physical encoding, and listing concurrency. */
@@ -3297,6 +3302,20 @@ export type JsonlCompression = 'zstd' | 'none'
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-session-persistence-jsonl -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-session-persistence-sqlite -->
<a id="deepseek-aidsh-session-persistence-sqlite"></a>
## `@deepseek-ai/dsh-session-persistence-sqlite`
- `refs`: [`JsonlConfigOptions`](#deepseek-aidsh-session-persistence-jsonl)
- `source`: [`packages/session/session-persistence-sqlite/src/index.ts:11`](../packages/session/session-persistence-sqlite/src/index.ts)
```ts config-catalog
/** Storage root and JSONL settings used when importing legacy Sessions. */
export type Config = JsonlConfigOptions
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-session-persistence-sqlite -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-session-projection-cache -->
<a id="deepseek-aidsh-session-projection-cache"></a>
@@ -5231,6 +5250,7 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co
| `@deepseek-ai/dsh-api-remotes` | `typertGateway` | [`packages/api/remotes/src/index.ts`](../packages/api/remotes/src/index.ts) |
| `@deepseek-ai/dsh-authorization` | `credentials` | [`packages/credentials/authorization/src/index.ts`](../packages/credentials/authorization/src/index.ts) |
| `@deepseek-ai/dsh-browser-use` | — | [`packages/browser-use/browser-use/src/index.ts`](../packages/browser-use/browser-use/src/index.ts) |
| `@deepseek-ai/dsh-client-config` | — | [`packages/client/config/src/index.ts`](../packages/client/config/src/index.ts) |
| `@deepseek-ai/dsh-client-file-upload` | `agents` · `attachments` · `commands` · `connection` | [`packages/client/file-upload/src/index.ts`](../packages/client/file-upload/src/index.ts) |
| `@deepseek-ai/dsh-client-locale` | — | [`packages/client/locale/src/index.ts`](../packages/client/locale/src/index.ts) |
| `@deepseek-ai/dsh-client-modules` | `loader` | [`packages/client/modules/src/index.ts`](../packages/client/modules/src/index.ts) |
+25 -5
View File
@@ -224,7 +224,7 @@ export interface Config {
## `@deepseek-ai/dsh-api-gateway`
- `inject`: `typert` · `remoteAccess`
- `source`: [`packages/api/gateway/src/index.ts:157`](../packages/api/gateway/src/index.ts)
- `source`: [`packages/api/gateway/src/index.ts:158`](../packages/api/gateway/src/index.ts)
```ts config-catalog
/** Gateway transport configuration. */
@@ -233,6 +233,11 @@ export interface Config {
readonly websocketHeartbeatIntervalMs?: number
/** Buffered uplink frame bytes one logical stream may hold before it fails with `gateway/uplink-overflow`. @default 262144 */
readonly streamInboxBytes?: number
/**
* Encoded downlink bytes one WebSocket connection may have queued and unwritten before every logical stream on it
* pauses reading its source. Items leave in the order their streams produced them. @default 1048576
*/
readonly streamOutboxBytes?: number
/** Per-message compression for the Remote stream WebSocket; `'none'` disables the extension. @default 'deflate' */
readonly websocketCompression?: 'none' | 'deflate'
}
@@ -541,8 +546,8 @@ export interface ConnectionRecoveryConfig {
## `@deepseek-ai/dsh-client-hmr`
- `inject`: `clientModules` · `webServer`
- `source`: [`packages/client/hmr/src/index.ts:30`](../packages/client/hmr/src/index.ts)
- `inject`: `clientModules`
- `source`: [`packages/client/hmr/src/index.ts:26`](../packages/client/hmr/src/index.ts)
```ts config-catalog
/** Plugin config, validated by the same-named schemastery schema. */
@@ -2955,7 +2960,7 @@ export interface Config {
timeoutMs?: number
/** Maximum numeric elapsed budget accepted by resolve. */
maxTimeoutMs?: number
/** Combined serialized logs, completion and diagnostic byte cap. */
/** Combined serialized output and completion or diagnostic cap; terminal data takes priority over captured output. */
maxOutputBytes?: number
/** V8 old-generation heap limit in MiB; native allocations are excluded. */
maxOldGenerationSizeMb?: number
@@ -3271,7 +3276,7 @@ export type SessionLogCompressionLevel = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
## `@deepseek-ai/dsh-session-persistence-jsonl`
- `source`: [`packages/session/session-persistence-jsonl/src/index.ts:95`](../packages/session/session-persistence-jsonl/src/index.ts)
- `source`: [`packages/session/session-persistence-jsonl/src/index.ts:107`](../packages/session/session-persistence-jsonl/src/index.ts)
```ts config-catalog
/** Plugin config for the JSONL backend's root, physical encoding, and listing concurrency. */
@@ -3299,6 +3304,20 @@ export type JsonlCompression = 'zstd' | 'none'
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-session-persistence-jsonl -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-session-persistence-sqlite -->
<a id="deepseek-aidsh-session-persistence-sqlite"></a>
## `@deepseek-ai/dsh-session-persistence-sqlite`
- `refs`: [`JsonlConfigOptions`](#deepseek-aidsh-session-persistence-jsonl)
- `source`: [`packages/session/session-persistence-sqlite/src/index.ts:11`](../packages/session/session-persistence-sqlite/src/index.ts)
```ts config-catalog
/** Storage root and JSONL settings used when importing legacy Sessions. */
export type Config = JsonlConfigOptions
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-session-persistence-sqlite -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-session-projection-cache -->
<a id="deepseek-aidsh-session-projection-cache"></a>
@@ -5233,6 +5252,7 @@ export interface Config {
| `@deepseek-ai/dsh-api-remotes` | `typertGateway` | [`packages/api/remotes/src/index.ts`](../packages/api/remotes/src/index.ts) |
| `@deepseek-ai/dsh-authorization` | `credentials` | [`packages/credentials/authorization/src/index.ts`](../packages/credentials/authorization/src/index.ts) |
| `@deepseek-ai/dsh-browser-use` | — | [`packages/browser-use/browser-use/src/index.ts`](../packages/browser-use/browser-use/src/index.ts) |
| `@deepseek-ai/dsh-client-config` | — | [`packages/client/config/src/index.ts`](../packages/client/config/src/index.ts) |
| `@deepseek-ai/dsh-client-file-upload` | `agents` · `attachments` · `commands` · `connection` | [`packages/client/file-upload/src/index.ts`](../packages/client/file-upload/src/index.ts) |
| `@deepseek-ai/dsh-client-locale` | — | [`packages/client/locale/src/index.ts`](../packages/client/locale/src/index.ts) |
| `@deepseek-ai/dsh-client-modules` | `loader` | [`packages/client/modules/src/index.ts`](../packages/client/modules/src/index.ts) |
+6 -6
View File
@@ -73,9 +73,9 @@ Application listeners are outside this package matrix. Desktop Host subscribes t
| `schedule/resolve-agent` | `waterfall` | [`packages/schedule/schedule/src/index.ts:72`](../packages/schedule/schedule/src/index.ts) | [`schedule`](../packages/schedule/schedule) (`waterfall`) | `server` |
| `session-telemetry/record` | `waterfall` | [`packages/session/session-telemetry/src/index.ts:44`](../packages/session/session-telemetry/src/index.ts) | [`session-telemetry`](../packages/session/session-telemetry) (`waterfall`) | - |
| `session/created` | `emit` | [`packages/core/session/src/index.ts:56`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | `server`, `session-controller`, [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry) |
| `session/disposed` | `emit` | [`packages/core/session/src/index.ts:65`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `file-upload`, `forge-session`, [`office-kit`](../packages/document/office-kit), `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-title`](../packages/session/session-title), `ui-trajectory`, [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `session/event` | `emit` | [`packages/core/session/src/index.ts:79`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`timeline`](../packages/experimental/timeline), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-session-status`, `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `session/flush` | `parallel` | [`packages/core/session/src/index.ts:87`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-telemetry`](../packages/session/session-telemetry) |
| `session/disposed` | `emit` | [`packages/core/session/src/index.ts:65`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `file-upload`, `forge-session`, [`office-kit`](../packages/document/office-kit), `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-title`](../packages/session/session-title), `ui-trajectory`, [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `session/event` | `emit` | [`packages/core/session/src/index.ts:79`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`timeline`](../packages/experimental/timeline), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-session-status`, `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `session/flush` | `parallel` | [`packages/core/session/src/index.ts:87`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`session-telemetry`](../packages/session/session-telemetry) |
| `settings/document-updated` | `emit` | [`packages/settings/settings/src/types.ts:75`](../packages/settings/settings/src/types.ts) | [`settings`](../packages/settings/settings) (`emit`) | `remotes` |
| `skills/change` | `emit` | [`packages/skill/skill/src/index.ts:299`](../packages/skill/skill/src/index.ts) | [`skill`](../packages/skill/skill) (`events.dispatch`) | - |
| `subagent/end` | `emit` | [`packages/subagent/subagent/src/index.ts:166`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), `server` |
@@ -119,12 +119,12 @@ Application listeners are outside this package matrix. Desktop Host subscribes t
| --- | --- | --- |
| `agent/request` | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`timeline`](../packages/experimental/timeline) |
| `connection/reset` | `gateway` (`emit`) | `terminal-controller`, `ui-settings` |
| `internal/config` | - | [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`mcp-manager`](../packages/mcp/mcp-manager) |
| `internal/config` | - | [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`mcp-manager`](../packages/mcp/mcp-manager), `modules` |
| `internal/dispatch` | - | [`terminal-bash`](../packages/terminal/terminal-bash) |
| `internal/plugin` | - | `computer-use-cua-driver-native`, `inspector`, `loader`, [`lsp-stdio`](../packages/lsp/lsp-stdio), [`mcp-client`](../packages/mcp/mcp-client), [`mcp-manager`](../packages/mcp/mcp-manager), `modules` |
| `internal/service` | - | `client-ui-forge`, `gateway` |
| `internal/status` | - | [`agent`](../packages/core/agent), `claude-code-mods`, `inspector`, `translator`, [`web`](../packages/web/web) |
| `loader/volatile-update` | - | [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`mcp-manager`](../packages/mcp/mcp-manager), [`plugin-market`](../packages/boot/plugin-market), `product-analytics`, `speech-to-text`, [`timeline`](../packages/experimental/timeline) |
| `internal/status` | - | [`agent`](../packages/core/agent), `claude-code-mods`, `inspector`, `modules`, `translator`, [`web`](../packages/web/web) |
| `loader/volatile-update` | - | [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`mcp-manager`](../packages/mcp/mcp-manager), `modules`, [`plugin-market`](../packages/boot/plugin-market), `product-analytics`, `speech-to-text`, [`timeline`](../packages/experimental/timeline) |
| `locale/change` | `locale` (`emit`) | `locale` |
| `slots/changed` | `ui-renderer` (`emit`) | - |
| `theme/change` | `ui-theme` (`emit`) | `ui-layout`, `ui-theme` |
+6 -6
View File
@@ -75,9 +75,9 @@
| `schedule/resolve-agent` | `waterfall` | [`packages/schedule/schedule/src/index.ts:72`](../packages/schedule/schedule/src/index.ts) | [`schedule`](../packages/schedule/schedule) (`waterfall`) | `server` |
| `session-telemetry/record` | `waterfall` | [`packages/session/session-telemetry/src/index.ts:44`](../packages/session/session-telemetry/src/index.ts) | [`session-telemetry`](../packages/session/session-telemetry) (`waterfall`) | - |
| `session/created` | `emit` | [`packages/core/session/src/index.ts:56`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | `server`, `session-controller`, [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry) |
| `session/disposed` | `emit` | [`packages/core/session/src/index.ts:65`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `file-upload`, `forge-session`, [`office-kit`](../packages/document/office-kit), `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-title`](../packages/session/session-title), `ui-trajectory`, [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `session/event` | `emit` | [`packages/core/session/src/index.ts:79`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`timeline`](../packages/experimental/timeline), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-session-status`, `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `session/flush` | `parallel` | [`packages/core/session/src/index.ts:87`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-telemetry`](../packages/session/session-telemetry) |
| `session/disposed` | `emit` | [`packages/core/session/src/index.ts:65`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `file-upload`, `forge-session`, [`office-kit`](../packages/document/office-kit), `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-title`](../packages/session/session-title), `ui-trajectory`, [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `session/event` | `emit` | [`packages/core/session/src/index.ts:79`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`timeline`](../packages/experimental/timeline), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-session-status`, `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `session/flush` | `parallel` | [`packages/core/session/src/index.ts:87`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`session-telemetry`](../packages/session/session-telemetry) |
| `settings/document-updated` | `emit` | [`packages/settings/settings/src/types.ts:75`](../packages/settings/settings/src/types.ts) | [`settings`](../packages/settings/settings) (`emit`) | `remotes` |
| `skills/change` | `emit` | [`packages/skill/skill/src/index.ts:299`](../packages/skill/skill/src/index.ts) | [`skill`](../packages/skill/skill) (`events.dispatch`) | - |
| `subagent/end` | `emit` | [`packages/subagent/subagent/src/index.ts:166`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), `server` |
@@ -121,12 +121,12 @@
| --- | --- | --- |
| `agent/request` | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`timeline`](../packages/experimental/timeline) |
| `connection/reset` | `gateway` (`emit`) | `terminal-controller`, `ui-settings` |
| `internal/config` | - | [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`mcp-manager`](../packages/mcp/mcp-manager) |
| `internal/config` | - | [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`mcp-manager`](../packages/mcp/mcp-manager), `modules` |
| `internal/dispatch` | - | [`terminal-bash`](../packages/terminal/terminal-bash) |
| `internal/plugin` | - | `computer-use-cua-driver-native`, `inspector`, `loader`, [`lsp-stdio`](../packages/lsp/lsp-stdio), [`mcp-client`](../packages/mcp/mcp-client), [`mcp-manager`](../packages/mcp/mcp-manager), `modules` |
| `internal/service` | - | `client-ui-forge`, `gateway` |
| `internal/status` | - | [`agent`](../packages/core/agent), `claude-code-mods`, `inspector`, `translator`, [`web`](../packages/web/web) |
| `loader/volatile-update` | - | [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`mcp-manager`](../packages/mcp/mcp-manager), [`plugin-market`](../packages/boot/plugin-market), `product-analytics`, `speech-to-text`, [`timeline`](../packages/experimental/timeline) |
| `internal/status` | - | [`agent`](../packages/core/agent), `claude-code-mods`, `inspector`, `modules`, `translator`, [`web`](../packages/web/web) |
| `loader/volatile-update` | - | [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`mcp-manager`](../packages/mcp/mcp-manager), `modules`, [`plugin-market`](../packages/boot/plugin-market), `product-analytics`, `speech-to-text`, [`timeline`](../packages/experimental/timeline) |
| `locale/change` | `locale` (`emit`) | `locale` |
| `slots/changed` | `ui-renderer` (`emit`) | - |
| `theme/change` | `ui-theme` (`emit`) | `ui-layout`, `ui-theme` |
+6
View File
@@ -156,6 +156,7 @@ flowchart TD
pkg_web_app["web-app"]
end
subgraph group_client["packages/client"]
pkg_client_config["client-config"]
pkg_client_connection["client-connection"]
pkg_client_file_upload["client-file-upload"]
pkg_client_hmr["client-hmr"]
@@ -420,6 +421,7 @@ flowchart TD
pkg_session_log_deepseek["session-log-deepseek"]
pkg_session_persistence["session-persistence"]
pkg_session_persistence_jsonl["session-persistence-jsonl"]
pkg_session_persistence_sqlite["session-persistence-sqlite"]
pkg_session_projection["session-projection"]
pkg_session_projection_cache["session-projection-cache"]
pkg_session_stats["session-stats"]
@@ -615,6 +617,8 @@ flowchart TD
pkg_sandbox_windows_acl --> pkg_subprocess
pkg_session_persistence_jsonl --> pkg_session
pkg_session_persistence_jsonl --> pkg_session_persistence
pkg_session_persistence_sqlite --> pkg_session
pkg_session_persistence_sqlite --> pkg_session_persistence
pkg_session_projection_cache --> pkg_session
pkg_session_projection_cache --> pkg_session_projection
pkg_session_projection_cache --> pkg_storage_domain
@@ -1631,6 +1635,7 @@ flowchart TD
| [`base`](../packages/bundle/base) | `bundle` | — |
| [`sdk-app`](../packages/bundle/sdk-app) | `bundle` | — |
| [`sdk-minimal`](../packages/bundle/sdk-minimal) | `bundle` | — |
| [`client-config`](../packages/client/config) | `client` | — |
| [`client-file-upload`](../packages/client/file-upload) | `client` | — |
| [`client-hmr`](../packages/client/hmr) | `client` | — |
| [`client-locale`](../packages/client/locale) | `client` | — |
@@ -1809,6 +1814,7 @@ flowchart TD
| [`sandbox-local`](../packages/sandbox/sandbox-local) | `sandbox` | [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`session`](../packages/core/session) |
| [`sandbox-windows-acl`](../packages/sandbox/sandbox-windows-acl) | `sandbox` | [`skill`](../packages/skill/skill), [`subprocess`](../packages/subprocess/subprocess) |
| [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl) | `session` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) |
| [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite) | `session` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) |
| [`session-projection-cache`](../packages/session/session-projection-cache) | `session` | [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`storage-domain`](../packages/storage/storage-domain) |
| [`session-stats`](../packages/session/session-stats) | `session` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection) |
| [`session-turn-outline`](../packages/session/session-turn-outline) | `session` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection) |
+6
View File
@@ -158,6 +158,7 @@ flowchart TD
pkg_web_app["web-app"]
end
subgraph group_client["packages/client"]
pkg_client_config["client-config"]
pkg_client_connection["client-connection"]
pkg_client_file_upload["client-file-upload"]
pkg_client_hmr["client-hmr"]
@@ -422,6 +423,7 @@ flowchart TD
pkg_session_log_deepseek["session-log-deepseek"]
pkg_session_persistence["session-persistence"]
pkg_session_persistence_jsonl["session-persistence-jsonl"]
pkg_session_persistence_sqlite["session-persistence-sqlite"]
pkg_session_projection["session-projection"]
pkg_session_projection_cache["session-projection-cache"]
pkg_session_stats["session-stats"]
@@ -617,6 +619,8 @@ flowchart TD
pkg_sandbox_windows_acl --> pkg_subprocess
pkg_session_persistence_jsonl --> pkg_session
pkg_session_persistence_jsonl --> pkg_session_persistence
pkg_session_persistence_sqlite --> pkg_session
pkg_session_persistence_sqlite --> pkg_session_persistence
pkg_session_projection_cache --> pkg_session
pkg_session_projection_cache --> pkg_session_projection
pkg_session_projection_cache --> pkg_storage_domain
@@ -1633,6 +1637,7 @@ flowchart TD
| [`base`](../packages/bundle/base) | `bundle` | — |
| [`sdk-app`](../packages/bundle/sdk-app) | `bundle` | — |
| [`sdk-minimal`](../packages/bundle/sdk-minimal) | `bundle` | — |
| [`client-config`](../packages/client/config) | `client` | — |
| [`client-file-upload`](../packages/client/file-upload) | `client` | — |
| [`client-hmr`](../packages/client/hmr) | `client` | — |
| [`client-locale`](../packages/client/locale) | `client` | — |
@@ -1811,6 +1816,7 @@ flowchart TD
| [`sandbox-local`](../packages/sandbox/sandbox-local) | `sandbox` | [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`session`](../packages/core/session) |
| [`sandbox-windows-acl`](../packages/sandbox/sandbox-windows-acl) | `sandbox` | [`skill`](../packages/skill/skill), [`subprocess`](../packages/subprocess/subprocess) |
| [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl) | `session` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) |
| [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite) | `session` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) |
| [`session-projection-cache`](../packages/session/session-projection-cache) | `session` | [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`storage-domain`](../packages/storage/storage-domain) |
| [`session-stats`](../packages/session/session-stats) | `session` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection) |
| [`session-turn-outline`](../packages/session/session-turn-outline) | `session` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection) |
+37 -4
View File
@@ -35,6 +35,8 @@ interface WebBootEntry {
immediately?: boolean
/** Non-baseline module specifiers this row requests; omitted when it requests none. */
external?: string[]
/** Browser-synced values of the plugin's top-level volatile Config fields, secrets removed; omitted when it has none. */
config?: SyncedConfigValues
}
```
@@ -139,11 +141,19 @@ The web plugin table service: incremental `dsh.client` scan + wire composition +
```ts cordis-catalog
/**
* Current composed entry graph (stable object between changes).
* @returns the graph served as `window.__DSH_BOOT__`.
* Current composed entry graph (stable object between changes), carrying the configured synced values.
* @returns the graph served as the owner's `window.__DSH_BOOT__`.
*/
graph(): WebBootGraph
/**
* The current graph as one Peer may see it: the owner receives the configured synced values, and every other Peer
* receives each row's schema defaults in their place.
* @param principal - the Peer's principal; undefined for the owner or an in-process caller.
* @returns the graph served to that Peer at first render and in plugin-events frames.
*/
graphFor(principal: Principal | undefined): WebBootGraph
/**
* Absolute path of an entry's client bundle.
* @param id - entry id (package name).
@@ -194,13 +204,36 @@ rebuilt(id: string): string | undefined
onRebuilt(listener: (id: string, rev: string) => void): () => void
/**
* Fires after any flush that recomposed the graph (row added/removed, or a
* rebuilt rev change). Pull model: listeners re-read {@link graph}.
* Fires after the graph's rows or rev change: a flush that recomposed the
* graph (row added/removed, or a rebuilt rev change), or a republication of
* synced configuration alone, which leaves the batch artifacts unchanged.
* Pull model: listeners re-read {@link graph}.
* @param listener - notified with no payload.
* @returns the unsubscriber.
*/
onGraphChanged(listener: () => void): () => void
```
Types: [Principal](typert.md)
Source: [`packages/client/modules/src/index.ts`](../../packages/client/modules/src/index.ts)
<a id="ctxconfig--syncedconfigservice"></a>
### `ctx.config` — `SyncedConfigService`
Read-only access to other packages' synced Config; a plugin receives its own through `apply`.
```ts cordis-catalog
/**
* The synced Config object of a package's current plugin activation, as that activation's `apply` received it. Each
* activation receives a new object, so the result changes when the plugin is replaced. The caller states the
* package's shared Config type.
* @param packageName - package name of the graph row.
* @returns the object, or undefined while no activation of the package is running.
*/
resolveConfigByPackage<C>(packageName: string): SyncedConfig<C> | undefined
```
Source: [`packages/client/config/src/types.ts`](../../packages/client/config/src/types.ts)
<!-- END GENERATED cordis-surface -->
+37 -4
View File
@@ -35,6 +35,8 @@ interface WebBootEntry {
immediately?: boolean
/** Non-baseline module specifiers this row requests; omitted when it requests none. */
external?: string[]
/** Browser-synced values of the plugin's top-level volatile Config fields, secrets removed; omitted when it has none. */
config?: SyncedConfigValues
}
```
@@ -139,11 +141,19 @@ The web plugin table service: incremental `dsh.client` scan + wire composition +
```ts cordis-catalog
/**
* Current composed entry graph (stable object between changes).
* @returns the graph served as `window.__DSH_BOOT__`.
* Current composed entry graph (stable object between changes), carrying the configured synced values.
* @returns the graph served as the owner's `window.__DSH_BOOT__`.
*/
graph(): WebBootGraph
/**
* The current graph as one Peer may see it: the owner receives the configured synced values, and every other Peer
* receives each row's schema defaults in their place.
* @param principal - the Peer's principal; undefined for the owner or an in-process caller.
* @returns the graph served to that Peer at first render and in plugin-events frames.
*/
graphFor(principal: Principal | undefined): WebBootGraph
/**
* Absolute path of an entry's client bundle.
* @param id - entry id (package name).
@@ -194,13 +204,36 @@ rebuilt(id: string): string | undefined
onRebuilt(listener: (id: string, rev: string) => void): () => void
/**
* Fires after any flush that recomposed the graph (row added/removed, or a
* rebuilt rev change). Pull model: listeners re-read {@link graph}.
* Fires after the graph's rows or rev change: a flush that recomposed the
* graph (row added/removed, or a rebuilt rev change), or a republication of
* synced configuration alone, which leaves the batch artifacts unchanged.
* Pull model: listeners re-read {@link graph}.
* @param listener - notified with no payload.
* @returns the unsubscriber.
*/
onGraphChanged(listener: () => void): () => void
```
Types: [Principal](typert.zh.md)
Source: [`packages/client/modules/src/index.ts`](../../packages/client/modules/src/index.ts)
<a id="ctxconfig--syncedconfigservice"></a>
### `ctx.config` — `SyncedConfigService`
Read-only access to other packages' synced Config; a plugin receives its own through `apply`.
```ts cordis-catalog
/**
* The synced Config object of a package's current plugin activation, as that activation's `apply` received it. Each
* activation receives a new object, so the result changes when the plugin is replaced. The caller states the
* package's shared Config type.
* @param packageName - package name of the graph row.
* @returns the object, or undefined while no activation of the package is running.
*/
resolveConfigByPackage<C>(packageName: string): SyncedConfig<C> | undefined
```
Source: [`packages/client/config/src/types.ts`](../../packages/client/config/src/types.ts)
<!-- END GENERATED cordis-surface -->
+2 -2
View File
@@ -33,5 +33,5 @@
en: 142ff3bed547efcf
zh: a73ca5ea4743d3e8
/session-persistence/the-backend:
en: adcd78909565b046
zh: a09bcb6ec0ebad9e
en: ec220159c6fcdb55
zh: c2023bc5e09f5b7f
+6 -3
View File
@@ -336,9 +336,10 @@ The optional `eventCount`/`sizeBytes` fields remain cheap backend observations f
## The backend
The shipped provider implements the abstract `SessionPersistence` contract (`create`/`open`/`stat`/`list`, with per-session `SessionHandle`s carrying `read`/`append`/`flush`/`close` and optional cancellation throughout) and passes the shared persistence contract suite:
The shipped providers implement the abstract `SessionPersistence` contract (`create`/`open`/`stat`/`list`, with per-session `SessionHandle`s carrying `read`/`append`/`flush`/`close` and optional cancellation throughout) and pass the shared persistence contract suite:
- **[dsh-session-persistence-jsonl](../../packages/session/session-persistence-jsonl)** — an append-only logical JSONL log per session, stored as checksummed concatenated Zstandard frames by default or raw lines by configuration, with crash-safe atomic materialization, per-batch `fsync` appends, and torn-tail truncation before the first new append. `stat`/`list` carry `sizeBytes` and a best-effort `fs.stat`-derived revision.
- **[dsh-session-persistence-sqlite](../../packages/session/session-persistence-sqlite)** — logical JSON event storage with indexed metadata and predecessor-linked Segments. The optional provider imports existing JSONL on first open and coordinates concurrent readers with a single writer per Session; `stat`/`list` do not import history.
<!-- BEGIN GENERATED cordis-surface (gen-cordis-catalog.ts) — do not edit between markers -->
@@ -392,8 +393,10 @@ abstract create(header: SessionHeader, options?: SessionPersistenceCreateOptions
/**
* Open an existing stored session.
*
* `read` never takes ownership and works while another handle (or process)
* holds write ownership. `write` atomically claims single-writer ownership;
* Returned `read` handles retain no write ownership and work while another
* handle (or process) holds write ownership. A first legacy read open may
* acquire ownership temporarily to import history into the selected backend.
* `write` atomically claims single-writer ownership;
* an existing active owner rejects.
* @param id - the stored session to open.
* @param access - `read` or `write`.
+6 -3
View File
@@ -336,9 +336,10 @@ interface SessionPersistenceSnapshot {
## 后端
随产品交付的 provider 实现抽象 `SessionPersistence` 约定(`create`/`open`/`stat`/`list`,逐会话 `SessionHandle` 承载 `read`/`append`/`flush`/`close`,全程可选支持取消),并通过共享的持久化契约套件:
随产品交付的多个 provider 实现抽象 `SessionPersistence` 约定(`create`/`open`/`stat`/`list`,逐会话 `SessionHandle` 承载 `read`/`append`/`flush`/`close`,全程可选支持取消),并通过共享的持久化契约套件:
- **[dsh-session-persistence-jsonl](../../packages/session/session-persistence-jsonl)**——逐会话仅追加的逻辑 JSONL 日志,默认存储为带 checksum 的连续 Zstandard frame,也可配置为原始行;具备崩溃安全的原子实体化、逐批 `fsync` 的 append,以及在第一次新 append 之前截断撕裂尾部。`stat`/`list` 携带 `sizeBytes` 与尽力而为的、由 `fs.stat` 派生的修订号。
- **[dsh-session-persistence-sqlite](../../packages/session/session-persistence-sqlite)**——带索引元数据及前驱关联 Segment 的逻辑 JSON 事件存储。此可选提供者在首次打开时导入现有 JSONL,并协调并发读者及每个 Session 的唯一写者;`stat`/`list` 不导入历史。
<!-- BEGIN GENERATED cordis-surface (gen-cordis-catalog.ts) — do not edit between markers -->
@@ -392,8 +393,10 @@ abstract create(header: SessionHeader, options?: SessionPersistenceCreateOptions
/**
* Open an existing stored session.
*
* `read` never takes ownership and works while another handle (or process)
* holds write ownership. `write` atomically claims single-writer ownership;
* Returned `read` handles retain no write ownership and work while another
* handle (or process) holds write ownership. A first legacy read open may
* acquire ownership temporarily to import history into the selected backend.
* `write` atomically claims single-writer ownership;
* an existing active owner rejects.
* @param id - the stored session to open.
* @param access - `read` or `write`.
+2 -2
View File
@@ -12,8 +12,8 @@
en: a387577007373804
zh: a330173368db598d
/ptc-runtime/captured-output-and-the-failure-taxonomy:
en: ef553620e77bd638
zh: 40ff2f5ba3de5ed5
en: 8d30aeb0fbd6001d
zh: 5eb1cbc7f67bfae0
/ptc-runtime/the-service:
en: 67e0b628723fa962
zh: 885994929216aa78
+4 -2
View File
@@ -101,6 +101,8 @@ interface PtcRunResult {
* the outer result.
*/
output: PtcOutput[]
/** Captured output or diagnostic text was truncated; execution still follows its normal completion, timeout and cancellation rules. */
outputTruncated?: boolean
/** Present iff the run failed; see {@link PtcRunFailure} for the taxonomy. */
error?: PtcRunFailure
}
@@ -202,7 +204,7 @@ declare class PtcInspectableValue {
## Captured output and the failure taxonomy
`output` contains text and image entries in emission order: `{ type: 'text', text }` or `{ type: 'image', attachment }`. Text entries retain emitted newline characters; concatenate adjacent text without separators. Each source channel preserves emission order; interleaving across independent channels is backend-dependent. Host bindings return `PtcImage` descriptors containing the attachment reference and a readable execution-world `path`; the program receives an `Image` with that path and the stored pixel dimensions. The Node provider caps serialized text, image descriptors, and completion or diagnostic payloads together; overflow is an explicit failure.
`output` contains text and image entries in emission order: `{ type: 'text', text }` or `{ type: 'image', attachment }`. Text entries retain emitted newline characters; concatenate adjacent text without separators. Each source channel preserves emission order; interleaving across independent channels is backend-dependent. Host bindings return `PtcImage` descriptors containing the attachment reference and a readable execution-world `path`; the program receives an `Image` with that path and the stored pixel dimensions. The Node provider caps serialized text, image descriptors, and completion or diagnostic payloads together; captured-output truncation is reported independently through `outputTruncated`, while required completion values remain lossless. See the [Node provider](../../packages/ptc-runtime/ptc-runtime-node/README.md) for budget priority and execution semantics.
```ts public-api
/** A stored image readable from the program's execution environment. */
@@ -239,7 +241,7 @@ Failure kinds are **orthogonal outcomes reported independently** (per [defensive
* - `'abort'` — {@link PtcRunRequest.signal} fired.
* - `'worker-exit'` — the execution substrate died without settling (e.g. OOM).
* - `'invalid-output'` — the completion value was not lossless JSON.
* - `'output-limit'` — the serialized outer logs/value/diagnostic exceeded the configured cap.
* - `'output-limit'` — the required completion value exceeded the configured cap.
* - `'protocol'` — the program sent invalid or over-budget control traffic.
* - `'sandbox-unavailable'` — required confinement could not be established.
*/
+4 -2
View File
@@ -101,6 +101,8 @@ interface PtcRunResult {
* the outer result.
*/
output: PtcOutput[]
/** Captured output or diagnostic text was truncated; execution still follows its normal completion, timeout and cancellation rules. */
outputTruncated?: boolean
/** Present iff the run failed; see {@link PtcRunFailure} for the taxonomy. */
error?: PtcRunFailure
}
@@ -202,7 +204,7 @@ declare class PtcInspectableValue {
## 捕获的输出与失败分类体系
`output` 按发出顺序保存文本和图片条目:文本使用 `{ type: 'text', text }`,图片使用 `{ type: 'image', attachment }`。文本条目保留实际输出的换行,相邻文本直接拼接,不额外插入分隔符。每个来源通道都保留发出顺序;独立通道之间的交错顺序由后端决定。宿主绑定返回 `PtcImage` 描述符,包含附件引用和可在执行环境读取的 `path`;程序收到带有该路径和存储像素尺寸的 `Image`。Node 提供方对序列化文本、图片描述符、完成值或诊断一起计量;超限会显式失败。
`output` 按发出顺序保存文本和图片条目:文本使用 `{ type: 'text', text }`,图片使用 `{ type: 'image', attachment }`。文本条目保留实际输出的换行,相邻文本直接拼接,不额外插入分隔符。每个来源通道都保留发出顺序;独立通道之间的交错顺序由后端决定。宿主绑定返回 `PtcImage` 描述符,包含附件引用和可在执行环境读取的 `path`;程序收到带有该路径和存储像素尺寸的 `Image`。Node 提供方对序列化文本、图片描述符、完成值或诊断一起计量;捕获输出截断通过 `outputTruncated` 独立报告,要求返回的完成值保持无损。预算优先级与执行语义见 [Node 提供方](../../packages/ptc-runtime/ptc-runtime-node/README.zh.md)。
```ts public-api
/** A stored image readable from the program's execution environment. */
@@ -239,7 +241,7 @@ type PtcOutput = { type: 'text'; text: string } | { type: 'image'; attachment: I
* - `'abort'` — {@link PtcRunRequest.signal} fired.
* - `'worker-exit'` — the execution substrate died without settling (e.g. OOM).
* - `'invalid-output'` — the completion value was not lossless JSON.
* - `'output-limit'` — the serialized outer logs/value/diagnostic exceeded the configured cap.
* - `'output-limit'` — the required completion value exceeded the configured cap.
* - `'protocol'` — the program sent invalid or over-budget control traffic.
* - `'sandbox-unavailable'` — required confinement could not be established.
*/
+1 -1
View File
@@ -86,7 +86,7 @@ interface SubagentStartRequest {
readonly agentPreset?: string
/** Optional short display label persisted with a session-backed child. */
readonly label?: string
/** Content delivered as the child's user message. */
/** Initial task; local continuable children record it as a message from the parent agent. */
readonly prompt: ContentBlock[]
/**
* The spawning agent. Its effective directory supplies the default cwd;
+1 -1
View File
@@ -86,7 +86,7 @@ interface SubagentStartRequest {
readonly agentPreset?: string
/** Optional short display label persisted with a session-backed child. */
readonly label?: string
/** Content delivered as the child's user message. */
/** Initial task; local continuable children record it as a message from the parent agent. */
readonly prompt: ContentBlock[]
/**
* The spawning agent. Its effective directory supplies the default cwd;
+2 -2
View File
@@ -15,8 +15,8 @@
en: e0143916bb634762
zh: e0143916bb634762
/tool-schema-catalog/deepseek-ai-dsh-plugin-manager/plugin-manager:
en: 2fbe2e5b88e81a54
zh: a9de46c13bda53d8
en: 8ad01461754a9c3b
zh: 67eb5c02a821643a
/tool-schema-catalog/deepseek-ai-dsh-plugin-market:
en: 1ec7b4cbc3d98e28
zh: 1ec7b4cbc3d98e28
+1 -1
View File
@@ -60,7 +60,7 @@ This table connects model-visible tool names to the plugin package and service s
### `plugin_manager`
List plugins or bundles in the current profile, enable or disable them, install a bundle, or remove an installed bundle. Every action requires danger-full-access permission or approval for this call. Approval does not change the session permission mode. Changes affect every session in this profile. List first to obtain exact identifiers. Package installation can execute allowed build scripts. Live profiles apply changes immediately, including upgrades of installed packages; a change result that is not applied carries nextStep, which says what to do or tell the user. Unmet DSH version requirements (engines.dsh, else DSH peer dependencies) block installation and activation. Version exemptions risk crashes and data loss: warn the user and obtain explicit permission for the exact plugin and runtime versions before granting one.
List plugins or bundles in the current profile, enable or disable them, install a bundle, or remove an installed bundle. Every action requires danger-full-access permission or approval for this call. Approval does not change the session permission mode. Changes affect every session in this profile. List first to obtain exact identifiers. Package installation can execute allowed build scripts. The application field of a change result is authoritative: applied means the change is in effect and needs no restart; any other value carries nextStep, which says what to do or tell the user. Unmet DSH version requirements (engines.dsh, else DSH peer dependencies) block installation and activation. Version exemptions risk crashes and data loss: warn the user and obtain explicit permission for the exact plugin and runtime versions before granting one.
```json
{
+1 -1
View File
@@ -64,7 +64,7 @@
### `plugin_manager`
列出当前 profile 中的插件或组合包,启用或禁用它们,安装组合包或移除已安装的组合包。每项操作都要求 danger-full-access 权限或本次调用的批准。批准不改变会话权限模式。变更影响该 profile 的所有会话。先列出条目以获取准确标识。包安装可能运行已获批准的构建脚本。支持热更新的 profile 立即应用变更,包括已安装包的升级;未直接应用的变更结果带有 nextStep,说明下一步要做什么或告诉用户什么。不兼容的 DSH peer 依赖会阻止安装和激活。版本豁免可能导致崩溃和数据丢失:授权前必须警告用户,并获得用户对精确插件版本与运行时版本组合的明确许可。
列出当前 profile 中的插件或组合包,启用或禁用它们,安装组合包或移除已安装的组合包。每项操作都要求 danger-full-access 权限或本次调用的批准。批准不改变会话权限模式。变更影响该 profile 的所有会话。先列出条目以获取准确标识。包安装可能运行已获批准的构建脚本。变更结果的 application 字段具有权威性:applied 表示变更已生效,无需重启;其他取值都带有 nextStep,说明下一步要做什么或告诉用户什么。不兼容的 DSH peer 依赖会阻止安装和激活。版本豁免可能导致崩溃和数据丢失:授权前必须警告用户,并获得用户对精确插件版本与运行时版本组合的明确许可。
```json
{
@@ -0,0 +1,16 @@
# Bilingual-pair consistency record for guide.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 docs/upgrade-guide/v0.2.2-rc.3/client-hmr-plugin-events-stream/guide.md
/:
en: fc0f253f60ad41b4
zh: 4b7f02f9260c672a
/plugin-events-stream-and-synced-browser-configuration:
en: 2cd6093e448761ba
zh: 66910abc17effed8
/plugin-events-stream-and-synced-browser-configuration/change:
en: 691f405846b33bbe
zh: b413c6be43ff2ee1
/plugin-events-stream-and-synced-browser-configuration/migration:
en: a8c0674e9b91d83c
zh: 557341db53da1025
@@ -0,0 +1,25 @@
---
kind: upgrade-guide
description: "`@deepseek-ai/dsh-client-hmr` removes `GET /plugins/events` and `EVENTS_ENDPOINT` for the authenticated `pluginEvents/follow` Remote stream, and browser plugins receive synced configuration in `apply`."
---
# Plugin events stream and synced browser configuration
English | [中文](guide.zh.md)
## Change
`@deepseek-ai/dsh-client-hmr` no longer registers the anonymous Server-Sent Events route `GET /plugins/events` and no longer exports `EVENTS_ENDPOINT`. Graph and rebuilt frames travel on the authenticated Typert Remote stream `pluginEvents/follow`: each stream generation opens with a `baseline` frame holding the full graph, followed by `graph` and `rebuilt` frames. Frame types come from `@deepseek-ai/dsh-client-hmr/types`. The browser face opens the stream over Connection and the API Gateway Client face while `remoteAccess` allows `pluginEvents/follow`; it no longer reads `window.__DSH_TRANSPORT__.fetch` or uses `EventSource`. A Peer whose Remote access does not allow `pluginEvents/follow`, such as a live-share viewer, no longer receives live graph or rebuilt updates.
Each graph row carries the plugin's [synced configuration](../../../../packages/client/modules/README.md#synced-plugin-configuration). A browser plugin whose Client face exports no `Config` schema receives a `SyncedConfig` object in `apply`, empty when its Host face declares no volatile fields, where it previously received `undefined`. A Client face that exports its own `Config` schema fails to activate when its graph row also carries synced values.
Affected: custom shells, scripts, and tests that read `/plugins/events` or import `EVENTS_ENDPOINT`; shells that supplied the plugin-events transport through `__DSH_TRANSPORT__.fetch`; deployments relying on viewer Peers following plugin changes; browser plugins that test their `apply` config for `undefined` or export a Client `Config` alongside volatile Host fields.
## Migration
1. Replace reads of `/plugins/events` and imports of `EVENTS_ENDPOINT` with a Remote client that mounts `@deepseek-ai/dsh-client-hmr/remote` and follows `pluginEvents.follow(signal)`; treat each `baseline` frame as a replacement of all earlier state, as [`src/client/index.ts`](../../../../packages/client/hmr/src/client/index.ts) does.
2. In a custom shell, provide the Remote carrier through Connection and the API Gateway Client face instead of a `__DSH_TRANSPORT__.fetch` handler for this endpoint.
3. Grant `pluginEvents/follow` in the Remote access policy of every Peer that must follow plugin changes; Peers without it reload the page to see them.
4. In browser plugins, stop treating an `undefined` `apply` config as "no configuration"; read fields through `SyncedConfig` from `@deepseek-ai/dsh-client-config/types`.
5. For a plugin with volatile Host fields, remove the Client face `Config` schema export and keep the only schema on the Host face, with the shared interface in `src/types.ts`.
6. Confirm: open the Web page, enable or disable a plugin, and check that the page updates without reload and that the browser sends no `/plugins/events` request.
@@ -0,0 +1,25 @@
---
kind: upgrade-guide
description: "`@deepseek-ai/dsh-client-hmr` 删除 `GET /plugins/events` 和 `EVENTS_ENDPOINT`,改用经过鉴权的 `pluginEvents/follow` Remote 流,浏览器插件在 `apply` 中接收同步配置。"
---
# 插件事件流与浏览器同步配置
[English](guide.md) | 中文
## 变更
`@deepseek-ai/dsh-client-hmr` 不再注册匿名 Server-Sent Events 路由 `GET /plugins/events`,也不再导出 `EVENTS_ENDPOINT`。图帧与重建帧改由经过鉴权的 Typert Remote 流 `pluginEvents/follow` 传递:每一代流先发一个包含完整图的 `baseline` 帧,之后发送 `graph` 与 `rebuilt` 帧。帧类型来自 `@deepseek-ai/dsh-client-hmr/types`。浏览器半侧在 `remoteAccess` 允许 `pluginEvents/follow` 时,经 Connection 与 API Gateway Client 半侧打开这条流;它不再读取 `window.__DSH_TRANSPORT__.fetch`,也不再使用 `EventSource`。Remote access 不允许 `pluginEvents/follow` 的 Peer(例如 live share 观看者)不再收到实时的图更新与重建更新。
图的每一行携带该插件的[同步配置](../../../../packages/client/modules/README.zh.md#synced-plugin-configuration)。Client 半侧未导出 `Config` schema 的浏览器插件在 `apply` 中接收一个 `SyncedConfig` 对象,Host 半侧未声明 volatile 字段时该对象为空,此前接收的是 `undefined`。Client 半侧导出自己 `Config` schema 的插件,若其图行同时携带同步值,则激活失败。
受影响者:读取 `/plugins/events` 或导入 `EVENTS_ENDPOINT` 的自定义 shell、脚本和测试;通过 `__DSH_TRANSPORT__.fetch` 提供插件事件传输的 shell;依赖观看者 Peer 跟随插件变更的部署;检查 `apply` 配置是否为 `undefined`,或在 Host volatile 字段之外还导出 Client `Config` 的浏览器插件。
## 迁移
1. 把对 `/plugins/events` 的读取和 `EVENTS_ENDPOINT` 的导入替换为挂载 `@deepseek-ai/dsh-client-hmr/remote` 并跟随 `pluginEvents.follow(signal)` 的 Remote 客户端;与 [`src/client/index.ts`](../../../../packages/client/hmr/src/client/index.ts) 一样,把每个 `baseline` 帧视为对之前全部状态的替换。
2. 在自定义 shell 中,经 Connection 与 API Gateway Client 半侧提供 Remote carrier,而不是为该端点提供 `__DSH_TRANSPORT__.fetch` 处理函数。
3. 在每个需要跟随插件变更的 Peer 的 Remote access 策略中授予 `pluginEvents/follow`;没有该权限的 Peer 需重新加载页面才能看到变更。
4. 在浏览器插件中,不再把 `undefined` 的 `apply` 配置当作“没有配置”;通过 `@deepseek-ai/dsh-client-config/types` 中的 `SyncedConfig` 读取字段。
5. 对带有 Host volatile 字段的插件,删除 Client 半侧的 `Config` schema 导出,只在 Host 半侧保留 schema,共享接口放在 `src/types.ts`。
6. 确认:打开 Web 页面,启用或禁用一个插件,检查页面无需重新加载即更新,且浏览器不再发出 `/plugins/events` 请求。
@@ -0,0 +1,16 @@
# Bilingual-pair consistency record for guide.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 docs/upgrade-guide/v0.2.2-rc.3/ptc-output-limit/guide.md
/:
en: 0f89c66e70c37465
zh: a80ca7a5c6b392bc
/ptc-output-truncation:
en: 7655f9eb80930413
zh: 4664b640aa95291b
/ptc-output-truncation/change:
en: 55abb1d0227dc89a
zh: 6a93f97e22ca90e0
/ptc-output-truncation/migration:
en: dfa6e80718350ca7
zh: c06d1e686dff1938
@@ -0,0 +1,23 @@
---
kind: upgrade-guide
description: "PTC display-output overflow truncates output while execution continues."
---
# PTC output truncation
English | [中文](guide.zh.md)
## Change
The Node PTC runtime discards subsequent display output after `maxOutputBytes` is exhausted and continues execution under the original timeout and cancellation rules. Truncation alone no longer terminates the process or clears retained variables. This also applies to environment initialization.
`PtcRunResult.outputTruncated` marks truncated captured output or diagnostics independently of `error`. A later exception, timeout or cancellation keeps its actual failure kind. Required JSON completion values take priority over captured output and remain lossless; a completion that cannot fit still fails with `output-limit`.
`run_code` and tools created by `createRunCodeTool` return success when the program completes normally, with `outputTruncated: true` and a visible truncation notice. Failed runs retain their usual error codes and mention truncation. Historical Session records remain unchanged.
## Migration
1. Treat truncation as incomplete output, not evidence that execution stopped. Read current state for missing information; do not repeat completed actions merely to recover logs.
2. Update runtime consumers to inspect `outputTruncated` separately from `error`. A successful required completion value remains complete even if captured output was truncated.
3. Update custom Node bootstrap deployments together with the host: the private protocol revision is 5 and includes output suppression without cancellation. Bootstraps announcing revision 3 or 4 are rejected before program dispatch.
4. Verify actions before and after output overflow both complete, retained variables survive, and later exceptions, timeouts and cancellation still report their original outcomes. To display a CUA screenshot, use `inspect(await window.getScreenshot())`.
@@ -0,0 +1,23 @@
---
kind: upgrade-guide
description: "PTC 展示输出超限后截断输出,程序继续执行。"
---
# PTC 输出截断
[English](guide.md) | 中文
## 变更
Node PTC 运行时在耗尽 `maxOutputBytes` 后丢弃后续展示输出,执行仍遵循原有超时和取消规则。截断本身不再终止进程或清空保留变量,环境初始化也适用。
`PtcRunResult.outputTruncated` 标记捕获输出或诊断被截断,与 `error` 独立。后续异常、超时或取消保留实际失败类型。要求返回的 JSON 完成值优先于捕获输出,并保持无损;无法容纳的完成值仍以 `output-limit` 失败。
`run_code` 和通过 `createRunCodeTool` 创建的工具在程序正常结束时返回成功,携带 `outputTruncated: true` 和可见的截断提示。失败执行保留原有错误码,并说明输出截断。历史 Session 记录保持不变。
## 迁移
1. 将截断视为输出不完整,而非执行停止的证据。需要遗漏信息时读取当前状态;不要仅为恢复日志而重复已完成的动作。
2. 更新运行时消费者,分别检查 `outputTruncated` 和 `error`。即使捕获输出被截断,成功返回的必需完成值仍然完整。
3. 自定义 Node bootstrap 部署需与宿主一起更新:私有协议版本为 5,包含不取消执行的输出抑制操作。声明版本 3 或 4 的 bootstrap 会在程序分发前被拒绝。
4. 验证超限前后的动作均会完成,保留变量仍可使用,且后续异常、超时和取消仍报告原来的结果。展示 CUA 截图时使用 `inspect(await window.getScreenshot())`。
@@ -3,14 +3,14 @@
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.3/ptc-tool-result-inspection/guide.md
/:
en: 31e27f1eb83f9740
zh: 85c7c3637222f1d8
/ptc-tool-result-inspection-and-bootstrap-protocol-4:
en: 2509c4fe8d208eb8
zh: 5f5dfd41fd29cd55
/ptc-tool-result-inspection-and-bootstrap-protocol-4/change:
en: a374fea86e00efb1
zh: fa50515f25ef048e
/ptc-tool-result-inspection-and-bootstrap-protocol-4/migration:
en: bfb868b271b5113d
zh: 597c95d985891d43
en: 26e38cbd61901bf1
zh: 9a172ed6093c0c44
/ptc-tool-result-inspection-and-bootstrap-protocol-5:
en: 5b9fde7497bdcff2
zh: 54aed9165dffc06e
/ptc-tool-result-inspection-and-bootstrap-protocol-5/change:
en: 0dca4571f5c1cb2f
zh: 9576d20ace4233b7
/ptc-tool-result-inspection-and-bootstrap-protocol-5/migration:
en: ec68709618b442e3
zh: 8e579e9607f51b6c
@@ -1,9 +1,9 @@
---
kind: upgrade-guide
description: "Direct inspection of unchanged PTC object and array tool results uses tool-rendered text, and custom Node bootstraps require protocol 4."
description: "Direct inspection of unchanged PTC object and array tool results uses tool-rendered text, and custom Node bootstraps require protocol 5."
---
# PTC tool-result inspection and bootstrap protocol 4
# PTC tool-result inspection and bootstrap protocol 5
English | [中文](guide.zh.md)
@@ -15,7 +15,7 @@ Non-empty associated text occupies a separate output group. `inspect('result:',
Field selections, copies, modified results, and results nested inside another value still use generic formatting. Scalar results, Images, and mixed text/image outputs keep their behavior. This affects programs and checks that depend on the exact text produced by inspecting a complete tool result. Inspectable containers may retain Image fields: direct inspection shows the supplied text; inspect the image field separately to display it.
The Node bootstrap protocol changes from 3 to 4. `HostMethods.invoke` replies now use `{ value: flatWire, inspection?: string }`. Custom `launch.bootstrapPath` deployments must update their bootstrap; the bundled bootstrap updates with the host.
The Node bootstrap protocol changes from 3 to 5. `HostMethods.invoke` replies now use `{ value: flatWire, inspection?: string }`. Custom `launch.bootstrapPath` deployments must update their bootstrap; the bundled bootstrap updates with the host.
## Migration
@@ -30,5 +30,5 @@ The Node bootstrap protocol changes from 3 to 4. `HostMethods.invoke` replies no
2. For an array result, use `inspect([...result])` to display its elements with generic formatting. Update any expected output that relied on the previous full-result object formatting.
3. If you implement a third-party `PtcRuntime`, recognize `PtcInspectableValue` binding results from `@deepseek-ai/dsh-ptc-runtime`. Deliver `.value` as the program's object or array, and associate `.text` with that unchanged value for direct `inspect`. Do not expose the wrapper or add inspection metadata to program fields.
4. If you configure `launch.bootstrapPath`, deploy the matching `@deepseek-ai/dsh-ptc-runtime-node` bootstrap and its dependencies in that execution environment. Use the package's built `lib/process.js`, or `lib/persistent-process.js` for a REPL default. A custom protocol implementation must handle the new reply envelope as well as announce protocol 4; changing the version alone is insufficient.
4. If you configure `launch.bootstrapPath`, deploy the matching `@deepseek-ai/dsh-ptc-runtime-node` bootstrap and its dependencies in that execution environment. Use the package's built `lib/process.js`, or `lib/persistent-process.js` for a REPL default. A custom protocol implementation must handle the new reply envelope and [output suppression](../ptc-output-limit/guide.md), and announce protocol 5; changing the version alone is insufficient.
5. Run the example above. Confirm that the first inspection shows the tool's rendered file text, while the other two show object and array data. For a custom provider, also confirm that field access and `JSON.stringify(result)` use the original data. For a custom bootstrap, confirm that a PTC program starts without a protocol-mismatch error.
@@ -1,9 +1,9 @@
---
kind: upgrade-guide
description: "直接展示未修改的 PTC 工具对象和数组结果时使用工具渲染文本,自定义 Node bootstrap 须升级到协议 4。"
description: "直接展示未修改的 PTC 工具对象和数组结果时使用工具渲染文本,自定义 Node bootstrap 须升级到协议 5。"
---
# PTC 工具结果展示与 bootstrap 协议 4
# PTC 工具结果展示与 bootstrap 协议 5
[English](guide.md) | 中文
@@ -15,7 +15,7 @@ PTC 工具保留声明的 JSON 返回值。无论是否附带展示元数据,
字段选择、拷贝、修改后的结果,以及嵌套在其他值中的结果,仍使用通用格式。标量结果、Image 和混合文本与图片的输出保持原有行为。依赖完整工具结果展示文本的程序和检查会受到影响。可展示的容器可以保留 Image 字段:直接展示容器时输出附带文本;单独展示图片字段时输出该图片。
Node bootstrap 协议从 3 升至 4。`HostMethods.invoke` 的回复现在使用 `{ value: flatWire, inspection?: string }`。自定义 `launch.bootstrapPath` 部署必须更新 bootstrap;内置 bootstrap 随宿主一同更新。
Node bootstrap 协议从 3 升至 5。`HostMethods.invoke` 的回复现在使用 `{ value: flatWire, inspection?: string }`。自定义 `launch.bootstrapPath` 部署必须更新 bootstrap;内置 bootstrap 随宿主一同更新。
## 迁移
@@ -30,5 +30,5 @@ Node bootstrap 协议从 3 升至 4。`HostMethods.invoke` 的回复现在使用
2. 对数组结果,使用 `inspect([...result])` 以通用格式展示元素。更新依赖此前完整结果对象格式的预期输出。
3. 如果实现了第三方 `PtcRuntime`,请识别绑定返回的 `@deepseek-ai/dsh-ptc-runtime` 包中的 `PtcInspectableValue`。将 `.value` 作为程序的对象或数组,并为该未修改的原值关联 `.text`,供直接 `inspect` 使用。不要暴露包装对象,也不要向程序字段添加展示元数据。
4. 如果配置了 `launch.bootstrapPath`,请在执行环境中部署匹配版本的 `@deepseek-ai/dsh-ptc-runtime-node` bootstrap 及其依赖。使用包内构建产物 `lib/process.js`,或默认采用 REPL 的 `lib/persistent-process.js`。自定义协议实现必须处理新的回复信封并声明协议 4;只改版本号并不足够。
4. 如果配置了 `launch.bootstrapPath`,请在执行环境中部署匹配版本的 `@deepseek-ai/dsh-ptc-runtime-node` bootstrap 及其依赖。使用包内构建产物 `lib/process.js`,或默认采用 REPL 的 `lib/persistent-process.js`。自定义协议实现必须处理新的回复信封和[输出抑制](../ptc-output-limit/guide.zh.md),并声明协议 5;只改版本号并不足够。
5. 运行上面的示例。确认第一次展示工具渲染的文件文本,后两次分别展示对象和数组数据。对于自定义提供方,还须确认字段访问和 `JSON.stringify(result)` 使用原有数据。对于自定义 bootstrap,确认 PTC 程序启动时不再报告协议不匹配。
@@ -0,0 +1,16 @@
# Bilingual-pair consistency record for guide.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 docs/upgrade-guide/v0.2.2-rc.3/subagent-initial-task-source/guide.md
/:
en: 643defc5c1f7c556
zh: d0eb87e9f9b8ab04
/subagent-initial-tasks-are-agent-messages:
en: d1488b39c6a3de61
zh: 0fd2612274767091
/subagent-initial-tasks-are-agent-messages/change:
en: bace0953390241ba
zh: 208b75e8f024d83f
/subagent-initial-tasks-are-agent-messages/migration:
en: 87f787e243c43531
zh: fd05bf541be3ea63
@@ -0,0 +1,20 @@
---
kind: upgrade-guide
description: "In-process continuable subagents record their initial delegated task as an agent-message from the parent agent instead of a user message."
---
# Subagent initial tasks are agent messages
English | [中文](guide.zh.md)
## Change
In-process continuable subagents started by `subagent-spawn-in-process` or `subagent-fork-in-process` record the initial delegated task as a message from the parent agent. Its `user/message` source changes from `{ "kind": "user" }` to `{ "kind": "agent-message", "form": "relay", "senderSessionId": "<parent Session id>" }`, and its content starts with a text block `Agent <parent name> sent a message: ` before the task blocks. Child Session logs, SDK Session event notifications, and Python SDK results show the new form. Sessions written earlier keep the old form.
Consumers that treat `user` sources as human input no longer apply to the task: `$skill` mentions in it do not load skills, Session references in it are not expanded, Markdown export and the turn outline omit it, and a child without human messages gets no fallback title. Direct human messages to a child keep the `user` source and their original content.
## Migration
1. Where code finds a child's task as its first `user`-source message, match an `agent-message` source whose `senderSessionId` equals the child Session's `parentSession`, and drop the first content block to read the task text. Keep accepting `user` for Sessions written before the upgrade.
2. Where a delegated task relies on `$skill` to load a skill, name the skill in the task and let the child call the `skill` tool.
3. Confirm by starting a continuable child and checking that its first non-context `user/message` has the `agent-message` source and the sender prefix.
@@ -0,0 +1,20 @@
---
kind: upgrade-guide
description: "进程内可续聊子 agent 的初始委派任务改为记录成来自父 agent 的 agent-message,不再是 user 消息。"
---
# 子 agent 初始任务改为 agent 消息
[English](guide.md) | 中文
## 变更
由 `subagent-spawn-in-process` 或 `subagent-fork-in-process` 启动的进程内可续聊子 agent,把初始委派任务记录为来自父 agent 的消息。其 `user/message` 的 source 从 `{ "kind": "user" }` 变为 `{ "kind": "agent-message", "form": "relay", "senderSessionId": "<父级 Session id>" }`,正文在任务内容块之前多一个文本块 `Agent <parent name> sent a message: `。子 Session 日志、SDK Session 事件通知和 Python SDK 结果都使用新形式。升级前写入的 Session 保持旧形式。
把 `user` 来源当作真人输入的使用方不再作用于该任务:任务中的 `$skill` 不再加载 skill,任务中的 Session 引用不再展开,Markdown 导出与 turn 大纲不包含该任务,没有真人消息的子会话不再生成回退标题。真人直接发给子 agent 的消息保持 `user` 来源和原文。
## 迁移
1. 如果代码把子会话的第一条 `user` 来源消息当作任务,改为匹配 `senderSessionId` 等于子 Session `parentSession` 的 `agent-message` 来源,并去掉第一个内容块后读取任务文本。对升级前写入的 Session 仍接受 `user`。
2. 如果委派任务依赖 `$skill` 加载 skill,改为在任务中写明 skill 名称,由子 agent 调用 `skill` 工具。
3. 启动一个可续聊子 agent,确认其第一条非上下文 `user/message` 使用 `agent-message` 来源并带有发送方前缀。
+2 -2
View File
@@ -15,8 +15,8 @@
en: d9859219cdb0f367
zh: 2a3cfa8cb786e327
/deepseek-ai-dsh-api-gateway/host-service-typertgatewayservice-ctx-key-typertgateway:
en: 6ee072ffebd2eb38
zh: 6a8723d13f443d51
en: 99788727be88f6db
zh: 750fd190bc1b8de0
/deepseek-ai-dsh-api-gateway/client-service-clientremote-ctx-key-remote:
en: 610e48ec8d772f85
zh: 627da164fc8297ba
+1 -1
View File
@@ -38,7 +38,7 @@ Resources are read from validated arguments: Typert-compiled codecs drop undecla
A cancellation-aware Remote method declares `signal: AbortSignal` as its final Host parameter. The signal is descriptor metadata rather than a wire argument: Connection supplies it to the Gateway, and the Gateway injects it after decoded business parameters. SRC recognizes the reserved final name, while strict generation additionally requires the global `AbortSignal` type.
A stream Remote uses `@Remote({ mode: 'stream' })` and returns an `Iterable` or `AsyncIterable`. `ctx.typertGateway.stream()` applies the same endpoint, argument, lookup, and cancellation checks as unary invocation, then returns a cancellation-aware iterable over the business items. The Client opens the Gateway-owned `/api/remote.mux` WebSocket when its plugin activates and keeps it connected while idle. Connection owns the retry schedule; before each retry it asks the mux to cancel any candidate or active socket and make exactly one fresh physical attempt. The Host sends Ping control frames at the configured `websocketHeartbeatIntervalMs` interval (two seconds by default), and the browser answers Pong at the WebSocket protocol layer, so idle network intermediaries see traffic without any Remote stream frame. A Pong, any received frame, or a downlink write that does not complete at once counts as peer activity; with the default `'deflate'`, a frame whose JSON text reaches the compression threshold is deflated asynchronously, so its completion always counts. A socket with no activity across two Ping intervals is terminated, so a congested link that delays the Pong behind data stays connected. With `websocketCompression` at its `'deflate'` default, an upgrade that offers `permessage-deflate` negotiates the extension, and the Host compresses its own outbound frames whose JSON text reaches 1,024 characters; shorter frames stay uncompressed, uplink frames are compressed at the peer's discretion, and `'none'` accepts the same upgrades without the extension. Independently cancellable logical streams share that socket; an in-process Connection carrier provides equivalent streams directly without opening it.
A stream Remote uses `@Remote({ mode: 'stream' })` and returns an `Iterable` or `AsyncIterable`. `ctx.typertGateway.stream()` applies the same endpoint, argument, lookup, and cancellation checks as unary invocation, then returns a cancellation-aware iterable over the business items. The Client opens the Gateway-owned `/api/remote.mux` WebSocket when its plugin activates and keeps it connected while idle. Connection owns the retry schedule; before each retry it asks the mux to cancel any candidate or active socket and make exactly one fresh physical attempt. The Host sends Ping control frames at the configured `websocketHeartbeatIntervalMs` interval (two seconds by default), and the browser answers Pong at the WebSocket protocol layer, so idle network intermediaries see traffic without any Remote stream frame. A Pong, any received frame, or a downlink write that does not complete at once counts as peer activity; with the default `'deflate'`, a frame whose JSON text reaches the compression threshold is deflated asynchronously, so its completion always counts. A socket with no activity across two Ping intervals is terminated, so a congested link that delays the Pong behind data stays connected. With `websocketCompression` at its `'deflate'` default, an upgrade that offers `permessage-deflate` negotiates the extension, and the Host compresses its own outbound frames whose JSON text reaches 1,024 characters; shorter frames stay uncompressed, uplink frames are compressed at the peer's discretion, and `'none'` accepts the same upgrades without the extension. Independently cancellable logical streams share that socket. Each downlink item enters one connection-wide write queue as soon as its stream's source produces it, so items of different streams are written in the order the sources produced them; a stream does not wait for its own previous item to be written. When the queued, unwritten bytes exceed `streamOutboxBytes` (1048576 by default), every stream on the connection pauses reading its source until the queue drains. The order covers only what the sources produce: a source that adds asynchronous steps before it yields an item produces it later. An in-process Connection carrier provides equivalent streams directly without opening the socket.
When the launcher supplies `ctx.appReady`, Gateway registers the WebSocket upgrade route only after successful application startup. Earlier connection attempts remain carrier failures handled by Connection's retry policy, so a restarting Host cannot accept streams while its controllers are still initializing. Unloading cancels a pending readiness subscription and closes any registered carrier. Embedded Hosts without `appReady` register immediately and own their startup ordering; in-process invocation is unchanged.
+1 -1
View File
@@ -38,7 +38,7 @@ Connection 可用时,Host 入口会在 Connection 共享的 `/api` FetchHandle
支持取消的 Remote 方法会把 `signal: AbortSignal` 声明为最后一个 Host 参数。signal 是 descriptor 元数据,而不是 wire 参数:Connection 将它提供给 Gateway,Gateway 则在已解码的业务参数之后注入它。SRC 识别这个保留的末位参数名,严格生成还要求它具有全局 `AbortSignal` 类型。
流式 Remote 使用 `@Remote({ mode: 'stream' })` 并返回 `Iterable` 或 `AsyncIterable`。`ctx.typertGateway.stream()` 执行与一元调用相同的 endpoint、参数、lookup 和取消校验,再返回可取消的业务项 iterable。Client 插件激活时打开 Gateway 自有的 `/api/remote.mux` WebSocket,并让它在空闲时保持连接。Connection 拥有重试调度;每次 retry 前,它要求 mux 取消候选或活动 socket,并且只做一次全新的物理连接尝试。Host 按配置的 `websocketHeartbeatIntervalMs` 间隔(默认 2 秒)发送 Ping 控制帧,浏览器在 WebSocket 协议层自动回复 Pong,使空闲网络中间层持续看到流量,而不新增 Remote 流帧。Pong、收到的任意帧,或未一次性完成的下行写入,都视为对端活动;默认 `'deflate'` 下,JSON 文本达到压缩阈值的帧异步 deflate,因此其完成总是计入。连续两个 Ping 间隔没有活动的 socket 会被终止,因此 Pong 被数据阻塞在拥塞链路上时连接仍会保持。`websocketCompression` 保持默认的 `'deflate'` 时,携带 `permessage-deflate` 的升级会协商该扩展,Host 压缩自己发出的、JSON 文本达到 1024 个字符 的帧;更短的帧不压缩,上行帧是否压缩由对端决定,设为 `'none'` 时接受同样的升级但不带该扩展。可独立取消的逻辑流共享这条连接;进程内 Connection 载体直接提供等价的流,不打开该 WebSocket。
流式 Remote 使用 `@Remote({ mode: 'stream' })` 并返回 `Iterable` 或 `AsyncIterable`。`ctx.typertGateway.stream()` 执行与一元调用相同的 endpoint、参数、lookup 和取消校验,再返回可取消的业务项 iterable。Client 插件激活时打开 Gateway 自有的 `/api/remote.mux` WebSocket,并让它在空闲时保持连接。Connection 拥有重试调度;每次 retry 前,它要求 mux 取消候选或活动 socket,并且只做一次全新的物理连接尝试。Host 按配置的 `websocketHeartbeatIntervalMs` 间隔(默认 2 秒)发送 Ping 控制帧,浏览器在 WebSocket 协议层自动回复 Pong,使空闲网络中间层持续看到流量,而不新增 Remote 流帧。Pong、收到的任意帧,或未一次性完成的下行写入,都视为对端活动;默认 `'deflate'` 下,JSON 文本达到压缩阈值的帧异步 deflate,因此其完成总是计入。连续两个 Ping 间隔没有活动的 socket 会被终止,因此 Pong 被数据阻塞在拥塞链路上时连接仍会保持。`websocketCompression` 保持默认的 `'deflate'` 时,携带 `permessage-deflate` 的升级会协商该扩展,Host 压缩自己发出的、JSON 文本达到 1024 个字符 的帧;更短的帧不压缩,上行帧是否压缩由对端决定,设为 `'none'` 时接受同样的升级但不带该扩展。可独立取消的逻辑流共享这条连接。每个下行项在其流的源产出时立即进入整条连接共用的写出队列,因此不同流的项按各源产出的先后写出;一条流不会等自己的上一项写完。排队且尚未写出的字节超过 `streamOutboxBytes`(默认 1048576)时,这条连接上的所有流暂停读取各自的源,直到队列消化。这一顺序只覆盖源产出的先后:源在产出某项之前多做了异步步骤,这一项就产出得更晚。进程内 Connection 载体直接提供等价的流,不打开该 WebSocket。
启动器提供 `ctx.appReady` 时,Gateway 仅在应用成功启动后注册 WebSocket 升级路由。此前的连接尝试仍属于载体故障,由 Connection 的重试策略处理,因此重启中的 Host 不会在控制器仍在初始化时接受流。卸载会取消尚未触发的就绪订阅,并关闭已注册的载体。不提供 `appReady` 的嵌入式 Host 会立即注册,并自行负责启动顺序;进程内调用不变。
+9
View File
@@ -147,6 +147,7 @@ type ConnectionRpcError = Extract<ConnectionRpcResult, { readonly ok: false }>['
const NEVER_ABORTED_SIGNAL = new AbortController().signal
const DEFAULT_WEBSOCKET_HEARTBEAT_INTERVAL_MS = 2_000
const DEFAULT_STREAM_INBOX_BYTES = 262_144
const DEFAULT_STREAM_OUTBOX_BYTES = 1_048_576
const EMPTY_ASYNC_ITERABLE: AsyncIterable<never> = {
[Symbol.asyncIterator]: () => ({ next: () => Promise.resolve({ value: undefined, done: true }) }),
}
@@ -159,6 +160,11 @@ export interface Config {
readonly websocketHeartbeatIntervalMs?: number
/** Buffered uplink frame bytes one logical stream may hold before it fails with `gateway/uplink-overflow`. @default 262144 */
readonly streamInboxBytes?: number
/**
* Encoded downlink bytes one WebSocket connection may have queued and unwritten before every logical stream on it
* pauses reading its source. Items leave in the order their streams produced them. @default 1048576
*/
readonly streamOutboxBytes?: number
/** Per-message compression for the Remote stream WebSocket; `'none'` disables the extension. @default 'deflate' */
readonly websocketCompression?: 'none' | 'deflate'
}
@@ -166,6 +172,7 @@ export interface Config {
interface ResolvedConfig extends Config {
readonly websocketHeartbeatIntervalMs: number
readonly streamInboxBytes: number
readonly streamOutboxBytes: number
readonly websocketCompression: 'none' | 'deflate'
}
@@ -216,6 +223,7 @@ export class TypertGatewayService extends Service implements TypertGateway {
websocketHeartbeatIntervalMs: z.number().step(1).min(1).max(MAX_TIMER_DELAY_MS)
.default(DEFAULT_WEBSOCKET_HEARTBEAT_INTERVAL_MS),
streamInboxBytes: z.number().step(1).min(1).default(DEFAULT_STREAM_INBOX_BYTES),
streamOutboxBytes: z.number().step(1).min(1).default(DEFAULT_STREAM_OUTBOX_BYTES),
websocketCompression: z.union([z.const('none'), z.const('deflate')]).default('deflate'),
})
@@ -260,6 +268,7 @@ export class TypertGatewayService extends Service implements TypertGateway {
{
heartbeatIntervalMs: resolved.websocketHeartbeatIntervalMs,
streamInboxBytes: resolved.streamInboxBytes,
streamOutboxBytes: resolved.streamOutboxBytes,
compression: resolved.websocketCompression === 'deflate',
},
)
+57 -4
View File
@@ -47,6 +47,8 @@ export interface RemoteStreamMuxServerOptions {
readonly heartbeatIntervalMs: number
/** Buffered uplink frame bytes one logical stream may hold before it fails. */
readonly streamInboxBytes: number
/** Queued, unwritten downlink bytes one connection may hold before its streams pause reading their sources. */
readonly streamOutboxBytes: number
/** Whether accepted connections negotiate the `permessage-deflate` extension. */
readonly compression: boolean
}
@@ -56,6 +58,7 @@ export class RemoteStreamMuxServer {
private readonly server: WebSocketServer
private readonly heartbeatIntervalMs: number
private readonly streamInboxBytes: number
private readonly streamOutboxBytes: number
private readonly compression: boolean
private readonly connections = new Set<Promise<void>>()
private readonly missedHeartbeats = new WeakMap<WebSocket, number>()
@@ -64,7 +67,7 @@ export class RemoteStreamMuxServer {
/**
* @param open - Gateway stream dispatcher.
* @param failure - Gateway error-to-wire mapper.
* @param options - heartbeat interval, uplink inbox bound, and compression setting for accepted connections.
* @param options - heartbeat interval, uplink inbox bound, downlink backlog bound, and compression setting for accepted connections.
*/
constructor(
private readonly open: RemoteStreamOpener,
@@ -73,6 +76,7 @@ export class RemoteStreamMuxServer {
) {
this.heartbeatIntervalMs = options.heartbeatIntervalMs
this.streamInboxBytes = options.streamInboxBytes
this.streamOutboxBytes = options.streamOutboxBytes
this.compression = options.compression
this.server = new WebSocketServer({
noServer: true,
@@ -101,7 +105,7 @@ export class RemoteStreamMuxServer {
const bound: BoundStreamOpener = (endpoint, payload, uplink, control, window) =>
this.open(endpoint, payload, uplink, peer, control, window)
const connection = new RemoteStreamMuxConnection(
websocket, bound, this.failure, this.streamInboxBytes, this.compression, alive,
websocket, bound, this.failure, this.streamInboxBytes, this.streamOutboxBytes, this.compression, alive,
)
const done = connection.run().catch((error: unknown) => {
console.error('[api-gateway] Remote stream connection failed:', error)
@@ -158,15 +162,24 @@ interface ActiveStream {
done: Promise<void>
}
/**
* One WebSocket's logical streams. Every downlink frame enters one connection-wide write queue at the moment its
* stream's source produces it, so frames leave in production order across streams; a stream does not wait for its
* own previous frame to be written. Only the connection backlog pauses sources.
*/
class RemoteStreamMuxConnection {
private readonly streams = new Map<string, ActiveStream>()
private writes = Promise.resolve()
/** Encoded bytes queued and not yet written. */
private queuedBytes = 0
private drained: PromiseWithResolvers<void> | undefined
constructor(
private readonly socket: WebSocket,
private readonly open: BoundStreamOpener,
private readonly failure: RemoteStreamFailureMapper,
private readonly streamInboxBytes: number,
private readonly streamOutboxBytes: number,
private readonly compression: boolean,
private readonly alive: () => void,
) {}
@@ -198,6 +211,9 @@ class RemoteStreamMuxConnection {
})
})
await closed
// Sources paused on the backlog resume and observe their stop.
this.drained?.resolve()
this.drained = undefined
const active = [...this.streams.values()]
for (const stream of active) stream.stop(new Error('Remote stream socket closed'))
await Promise.all(active.map(stream => stream.done))
@@ -272,9 +288,17 @@ class RemoteStreamMuxConnection {
maxBytes: this.streamInboxBytes,
frameOverheadBytes: Buffer.byteLength(JSON.stringify({ type: 'item', streamId, value: null }), 'utf8') - 'null'.length,
})
let written: Promise<void> = Promise.resolve()
let writeFailure: { readonly error: unknown } | undefined
for await (const value of source) {
await this.send({ type: 'item', streamId, value })
if (writeFailure !== undefined) throw writeFailure.error
written = this.send({ type: 'item', streamId, value })
written.catch((error: unknown) => { writeFailure ??= { error } })
await this.backlogDrained(active.abort.signal)
// A cancelled stream stops at once; it does not wait for other streams to drain the connection backlog.
if (active.abort.signal.aborted) break
}
if (!active.abort.signal.aborted) await written
outcome = { failed: false }
} catch (error) {
outcome = { failed: true, error }
@@ -312,15 +336,43 @@ class RemoteStreamMuxConnection {
}
}
/**
* Resolve once the connection backlog is within its bound, the socket has closed, or the stream is cancelled.
* @param signal - the waiting stream's cancellation.
*/
private async backlogDrained(signal: AbortSignal): Promise<void> {
while (this.queuedBytes > this.streamOutboxBytes && this.socket.readyState === WebSocket.OPEN && !signal.aborted) {
this.drained ??= Promise.withResolvers<void>()
const cancelled = Promise.withResolvers<void>()
const onAbort = (): void => { cancelled.resolve() }
signal.addEventListener('abort', onAbort, { once: true })
await Promise.race([this.drained.promise, cancelled.promise])
signal.removeEventListener('abort', onAbort)
}
}
/**
* Queue one frame behind every frame queued before it on this connection.
* @throws Error synchronously when the frame is not JSON serializable; nothing is queued.
*/
private send(message: RemoteStreamServerMessage): Promise<void> {
let text: string
try {
text = JSON.stringify(message)
} catch (cause) {
return Promise.reject(new Error('api gateway: Remote stream item is not JSON serializable', { cause }))
throw new Error('api gateway: Remote stream item is not JSON serializable', { cause })
}
const bytes = Buffer.byteLength(text, 'utf8')
this.queuedBytes += bytes
const settled = (): void => {
this.queuedBytes -= bytes
if (this.queuedBytes > this.streamOutboxBytes) return
this.drained?.resolve()
this.drained = undefined
}
const delivery = this.writes.then(() => new Promise<void>((resolve, reject) => {
if (this.socket.readyState !== WebSocket.OPEN) {
settled()
reject(new Error('api gateway: Remote stream socket is closed'))
return
}
@@ -328,6 +380,7 @@ class RemoteStreamMuxConnection {
this.socket.send(text, {
compress: this.compression && text.length >= 1024,
}, (error) => {
settled()
if (error) {
reject(error)
return
@@ -416,21 +416,27 @@ describe('Typert Remote streams', () => {
expect(() => { startup.commit() }).not.toThrow()
})
it('validates the WebSocket heartbeat timer range, the stream inbox bound, and the compression mode', () => {
it('validates the WebSocket heartbeat timer range, the stream inbox and outbox bounds, and the compression mode', () => {
expect(TypertGatewayService.Config({})).toEqual({
websocketHeartbeatIntervalMs: 2_000,
streamInboxBytes: 262_144,
streamOutboxBytes: 1_048_576,
websocketCompression: 'deflate',
})
expect(TypertGatewayService.Config({
websocketHeartbeatIntervalMs: MAX_TIMER_DELAY_MS,
streamInboxBytes: 1,
streamOutboxBytes: 1,
websocketCompression: 'none',
})).toEqual({
websocketHeartbeatIntervalMs: MAX_TIMER_DELAY_MS,
streamInboxBytes: 1,
streamOutboxBytes: 1,
websocketCompression: 'none',
})
for (const streamOutboxBytes of [0, 1.5]) {
expect(() => TypertGatewayService.Config({ streamOutboxBytes })).toThrow()
}
for (const websocketHeartbeatIntervalMs of [0, 1.5, MAX_TIMER_DELAY_MS + 1]) {
expect(() => TypertGatewayService.Config({ websocketHeartbeatIntervalMs })).toThrow()
}
Loaded 100 of 514 files, more files were not shown because too many files have changed in this diff. Show more