diff --git a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.i18n.yaml index f29cf535f2..7f34aedf3f 100644 --- a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md index bc24420a59..6de1fd1ab8 100644 --- a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md +++ b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md @@ -46,7 +46,7 @@ A `require.async("./client..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///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/??/client.js,/client.js&rev=` points to `/plugins/??/client.js.map,/client.js.map&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 diff --git a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.zh.md b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.zh.md index bebd131c85..7e1e7d1d40 100644 --- a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.zh.md @@ -46,7 +46,7 @@ Host 会快照每个已构建插件入口 bundle,并把每个调度阶段的 共享 tsdown 预设为每个插件入口与 chunk 产出 map,并把第一方源码路径重写成浏览器可识别的仓库形式 `/packages///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/??/client.js,/client.js&rev=` 指向 `/plugins/??/client.js.map,/client.js.map&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 diff --git a/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.i18n.yaml index ee3f5d9048..e1b5d0b632 100644 --- a/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.md b/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.md index c311f397dc..1998b28e64 100644 --- a/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.md +++ b/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.md @@ -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 diff --git a/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.zh.md b/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.zh.md index f91dfff11b..c9fe0a24a5 100644 --- a/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.zh.md @@ -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)负责保留状态的超时和取消恢复。普通异常保留此前发生的修改。保留的函数使用当前执行的宿主绑定;较早执行中的异步任务不能获取后续执行的工具权限或向其输出。 ## 考虑过的替代方案 diff --git a/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.i18n.yaml index fdbd7de7cb..86b1b861c4 100644 --- a/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.md b/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.md index b4c4c539ee..90f71ebcdf 100644 --- a/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.md +++ b/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.md @@ -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 diff --git a/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.zh.md b/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.zh.md index a5344f8b01..4b46aceeee 100644 --- a/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.zh.md +++ b/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.zh.md @@ -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 插件无需刷新页面即可挂载。 ## 考虑过的替代方案 diff --git a/.agents/notes/implemented/architecture/2026-11-13-ptc-output-truncation.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-13-ptc-output-truncation.i18n.yaml new file mode 100644 index 0000000000..5a5d96d0a1 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-13-ptc-output-truncation.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/architecture/2026-11-13-ptc-output-truncation.md b/.agents/notes/implemented/architecture/2026-11-13-ptc-output-truncation.md new file mode 100644 index 0000000000..cb9f11e50f --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-13-ptc-output-truncation.md @@ -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. diff --git a/.agents/notes/implemented/architecture/2026-11-13-ptc-output-truncation.zh.md b/.agents/notes/implemented/architecture/2026-11-13-ptc-output-truncation.zh.md new file mode 100644 index 0000000000..f38b8d0bfb --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-13-ptc-output-truncation.zh.md @@ -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 数据的要求。只有捕获输出和诊断文本可以缩短。 + +## 后果 + +成功但输出截断的执行仍是成功工具结果。调用方读取当前状态以获取遗漏信息,不重放已完成动作。输出抑制不限制参数求值或原生代码中的分配,这仍由现有资源控制负责。测试覆盖后续动作、保留变量、初始化、有序图片、字节上限以及后续异常、截止到期和取消。 diff --git a/.agents/notes/implemented/architecture/2026-11-15-client-config-sync.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-15-client-config-sync.i18n.yaml new file mode 100644 index 0000000000..aad42e312a --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-15-client-config-sync.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/architecture/2026-11-15-client-config-sync.md b/.agents/notes/implemented/architecture/2026-11-15-client-config-sync.md new file mode 100644 index 0000000000..5282c80450 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-15-client-config-sync.md @@ -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 + /** Synced as one value. */ + office: Volatile<{ maxBytes: number }> + /** Volatile but `role('secret')`: stripped on the Host; reads as undefined in the browser. */ + apiKey?: Volatile +} +``` + +```ts ignore-check +// src/index.ts — Host face; the only schema +export const Config: z = 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): 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) { + 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 extends Volatile, ObservableSnapshot> {} + +/** The Volatile fields of the shared Config type. */ +export type SyncedConfig = { + readonly [K in keyof C as NonNullable extends Volatile ? K : never]-?: + NonNullable extends Volatile ? SyncedConfigRef : 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`, 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(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 | diff --git a/.agents/notes/implemented/architecture/2026-11-15-client-config-sync.zh.md b/.agents/notes/implemented/architecture/2026-11-15-client-config-sync.zh.md new file mode 100644 index 0000000000..4afa3940b9 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-15-client-config-sync.zh.md @@ -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 + /** Synced as one value. */ + office: Volatile<{ maxBytes: number }> + /** Volatile but `role('secret')`: stripped on the Host; reads as undefined in the browser. */ + apiKey?: Volatile +} +``` + +```ts ignore-check +// src/index.ts — Host face; the only schema +export const Config: z = 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): 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) { + 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 extends Volatile, ObservableSnapshot> {} + +/** The Volatile fields of the shared Config type. */ +export type SyncedConfig = { + readonly [K in keyof C as NonNullable extends Volatile ? K : never]-?: + NonNullable extends Volatile ? SyncedConfigRef : never +} +``` + +`get` 与 `getSnapshot` 返回同一个冻结快照:`get` 与 Host 的 volatile 引用写法一致,`getSnapshot` 与 `subscribe` 满足 `ObservableSnapshot`,引用本身即可放进 `hooks`,renderer 不需要额外适配。接口没有写操作;实现类只在 Client Modules 内部。 + +组件取值遵循 [client 规则](../../../../packages/client/AGENTS.md):插件在 slot inject 的 `hooks` 中手动注入 key 级数据源,组件只通过 renderer 绑定的 `use` 读取,不接触数据源本身。 + +### 归属 + +运行时归属仍在 `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(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 值都会缺失,插件需在每次读取时处理缺值 | diff --git a/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.i18n.yaml b/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.i18n.yaml index a690ccf5df..a91fc751b4 100644 --- a/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.md b/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.md index bd58e32ff8..d27a69753f 100644 --- a/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.md +++ b/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.md @@ -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 diff --git a/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.zh.md b/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.zh.md index d25e3637e1..3e1591ca18 100644 --- a/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.zh.md +++ b/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.zh.md @@ -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 会以嵌套深度有界的扁平协议格式传输数据并执行无损校验,但不会降低中间值的开销,也不会使其具备持久性。必需完成值超限会显式导致运行失败,错误处理则有意由人类引导,而不是依赖带版本的错误代码联合。 ## 已知限制与暂缓事项 diff --git a/.agents/notes/implemented/feature/2026-10-14-host-release-change-refresh-prompt.i18n.yaml b/.agents/notes/implemented/feature/2026-10-14-host-release-change-refresh-prompt.i18n.yaml index 4124137839..749b8adffb 100644 --- a/.agents/notes/implemented/feature/2026-10-14-host-release-change-refresh-prompt.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-10-14-host-release-change-refresh-prompt.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/feature/2026-10-14-host-release-change-refresh-prompt.md b/.agents/notes/implemented/feature/2026-10-14-host-release-change-refresh-prompt.md index 33ac74d954..43728342e9 100644 --- a/.agents/notes/implemented/feature/2026-10-14-host-release-change-refresh-prompt.md +++ b/.agents/notes/implemented/feature/2026-10-14-host-release-change-refresh-prompt.md @@ -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. diff --git a/.agents/notes/implemented/feature/2026-10-14-host-release-change-refresh-prompt.zh.md b/.agents/notes/implemented/feature/2026-10-14-host-release-change-refresh-prompt.zh.md index f8e8f85f71..c668e9615b 100644 --- a/.agents/notes/implemented/feature/2026-10-14-host-release-change-refresh-prompt.zh.md +++ b/.agents/notes/implemented/feature/2026-10-14-host-release-change-refresh-prompt.zh.md @@ -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,以及确认框的渲染与回调。 diff --git a/.agents/notes/proposed/architecture/2026-11-15-client-config-sync-migration.i18n.yaml b/.agents/notes/proposed/architecture/2026-11-15-client-config-sync-migration.i18n.yaml new file mode 100644 index 0000000000..012f82ab67 --- /dev/null +++ b/.agents/notes/proposed/architecture/2026-11-15-client-config-sync-migration.i18n.yaml @@ -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 diff --git a/.agents/notes/proposed/architecture/2026-11-15-client-config-sync-migration.md b/.agents/notes/proposed/architecture/2026-11-15-client-config-sync-migration.md new file mode 100644 index 0000000000..ba52a8881c --- /dev/null +++ b/.agents/notes/proposed/architecture/2026-11-15-client-config-sync-migration.md @@ -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 | diff --git a/.agents/notes/proposed/architecture/2026-11-15-client-config-sync-migration.zh.md b/.agents/notes/proposed/architecture/2026-11-15-client-config-sync-migration.zh.md new file mode 100644 index 0000000000..4714b909ff --- /dev/null +++ b/.agents/notes/proposed/architecture/2026-11-15-client-config-sync-migration.zh.md @@ -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` 在自身激活前就需要恢复参数,早于同步配置能参与的时间点 | diff --git a/.github/review-ownership/README.md b/.github/review-ownership/README.md index 79103f593a..2bf7804c71 100644 --- a/.github/review-ownership/README.md +++ b/.github/review-ownership/README.md @@ -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. diff --git a/.github/review-ownership/approval-policy.json b/.github/review-ownership/approval-policy.json index 9ecc46ff5b..ebd0453a99 100644 --- a/.github/review-ownership/approval-policy.json +++ b/.github/review-ownership/approval-policy.json @@ -3,7 +3,9 @@ "defaultPoints": 1, "reviewerPoints": { "07akioni": 2, + "CreatixChu": 2, "imccyu": 2, + "LegGasai": 2, "tianyicui": 2, "tianyicui-bot": 2, "turtle1999": 2, diff --git a/.github/review-ownership/author-weight.mjs b/.github/review-ownership/author-weight.mjs index 21b9cafcae..0fda0c4b8a 100644 --- a/.github/review-ownership/author-weight.mjs +++ b/.github/review-ownership/author-weight.mjs @@ -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. diff --git a/.github/review-ownership/check-approval.mjs b/.github/review-ownership/check-approval.mjs index d876e8e8c3..2f27f5aff1 100644 --- a/.github/review-ownership/check-approval.mjs +++ b/.github/review-ownership/check-approval.mjs @@ -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, 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 }) => diff --git a/.github/review-ownership/check-approval.test.mjs b/.github/review-ownership/check-approval.test.mjs index cf5f74583e..945323dcf5 100644 --- a/.github/review-ownership/check-approval.test.mjs +++ b/.github/review-ownership/check-approval.test.mjs @@ -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({ diff --git a/apps/cli/package.json b/apps/cli/package.json index fd325d9d23..0c5c178a22 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -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:*", diff --git a/apps/cli/tests/agent-team-headless.e2e.ts b/apps/cli/tests/agent-team-headless.e2e.ts index 026a54903c..c32f92c614 100644 --- a/apps/cli/tests/agent-team-headless.e2e.ts +++ b/apps/cli/tests/agent-team-headless.e2e.ts @@ -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 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) => { diff --git a/apps/cli/tests/profiles/cua-mcp/expected/tools.json b/apps/cli/tests/profiles/cua-mcp/expected/tools.json index 79ad346b20..3b0395878f 100644 --- a/apps/cli/tests/profiles/cua-mcp/expected/tools.json +++ b/apps/cli/tests/profiles/cua-mcp/expected/tools.json @@ -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": { diff --git a/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/child.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/child.expected.jsonl index 9e3ec3e15c..6ec383b0be 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/child.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/child.expected.jsonl @@ -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":"\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: \"\", 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"}],"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: \"\", 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":"\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: \"\", 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 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"}],"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: \"\", 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 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"} diff --git a/apps/cli/tests/profiles/headless/tests/expected/subagent-settlement/child.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/subagent-settlement/child.expected.jsonl index 498fb3440a..75dbb725de 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/subagent-settlement/child.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/subagent-settlement/child.expected.jsonl @@ -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":"\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: \"\", 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"}],"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: \"\", 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":"\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: \"\", 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 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"}],"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: \"\", 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 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"}}} diff --git a/apps/cli/tests/profiles/headless/tests/fixtures/team-llm.mjs b/apps/cli/tests/profiles/headless/tests/fixtures/team-llm.mjs index a2d5cc5ea1..a150fa124f 100644 --- a/apps/cli/tests/profiles/headless/tests/fixtures/team-llm.mjs +++ b/apps/cli/tests/profiles/headless/tests/fixtures/team-llm.mjs @@ -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') } diff --git a/apps/cli/tests/profiles/headless/tests/headless.expected.e2e.ts b/apps/cli/tests/profiles/headless/tests/headless.expected.e2e.ts index 69c95ef485..1960f024bf 100644 --- a/apps/cli/tests/profiles/headless/tests/headless.expected.e2e.ts +++ b/apps/cli/tests/profiles/headless/tests/headless.expected.e2e.ts @@ -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 diff --git a/apps/cli/tests/web-agent-presets.e2e.ts b/apps/cli/tests/web-agent-presets.e2e.ts index efdb68d158..267f28236e 100644 --- a/apps/cli/tests/web-agent-presets.e2e.ts +++ b/apps/cli/tests/web-agent-presets.e2e.ts @@ -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, diff --git a/apps/web/tests/assembled-boot.ts b/apps/web/tests/assembled-boot.ts index 3ecaa90a4d..a45ff68471 100644 --- a/apps/web/tests/assembled-boot.ts +++ b/apps/web/tests/assembled-boot.ts @@ -191,11 +191,6 @@ class ResizeObserverStub { unobserve(): void {} } -class EventSourceStub { - addEventListener(): void {} - close(): void {} -} - const win = window as FixtureWindow let unmount: (() => Promise) | 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) }) diff --git a/apps/web/tests/bonus-notice.e2e.ts b/apps/web/tests/bonus-notice.e2e.ts index 330c3e3505..a63c46d54d 100644 --- a/apps/web/tests/bonus-notice.e2e.ts +++ b/apps/web/tests/bonus-notice.e2e.ts @@ -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']) diff --git a/apps/web/tests/client-config-sync.e2e.ts b/apps/web/tests/client-config-sync.e2e.ts new file mode 100644 index 0000000000..f132739954 --- /dev/null +++ b/apps/web/tests/client-config-sync.e2e.ts @@ -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 | 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) diff --git a/apps/web/tests/client-plugin-live.e2e.ts b/apps/web/tests/client-plugin-live.e2e.ts index 0e4ff0df1d..9b451d8de1 100644 --- a/apps/web/tests/client-plugin-live.e2e.ts +++ b/apps/web/tests/client-plugin-live.e2e.ts @@ -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) diff --git a/apps/web/tests/expected/bonus-notice/notice-flow.expected.md b/apps/web/tests/expected/bonus-notice/notice-flow.expected.md index 08f4861da9..70f6a209b7 100644 --- a/apps/web/tests/expected/bonus-notice/notice-flow.expected.md +++ b/apps/web/tests/expected/bonus-notice/notice-flow.expected.md @@ -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 diff --git a/apps/web/tests/expected/forge-panel/local-and-pr.expected.md b/apps/web/tests/expected/forge-panel/local-and-pr.expected.md index a7d2ea13e9..db99eee5fa 100644 --- a/apps/web/tests/expected/forge-panel/local-and-pr.expected.md +++ b/apps/web/tests/expected/forge-panel/local-and-pr.expected.md @@ -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 项检查,仍有更多" diff --git a/apps/web/tests/expected/forge-panel/panel.expected.md b/apps/web/tests/expected/forge-panel/panel.expected.md index 95e486e57f..74c59154a4 100644 --- a/apps/web/tests/expected/forge-panel/panel.expected.md +++ b/apps/web/tests/expected/forge-panel/panel.expected.md @@ -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 项检查,仍有更多" diff --git a/apps/web/tests/expected/forge-panel/reference.expected.md b/apps/web/tests/expected/forge-panel/reference.expected.md index 3c93cb264e..e26c6524e9 100644 --- a/apps/web/tests/expected/forge-panel/reference.expected.md +++ b/apps/web/tests/expected/forge-panel/reference.expected.md @@ -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 项检查,仍有更多" diff --git a/apps/web/tests/fixtures/plugins/fixture-synced-config/client.js b/apps/web/tests/fixtures/plugins/fixture-synced-config/client.js new file mode 100644 index 0000000000..ee4d0c28ef --- /dev/null +++ b/apps/web/tests/fixtures/plugins/fixture-synced-config/client.js @@ -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)) + }, + } + }, +}) diff --git a/apps/web/tests/fixtures/plugins/fixture-synced-config/cordis.patch.yml b/apps/web/tests/fixtures/plugins/fixture-synced-config/cordis.patch.yml new file mode 100644 index 0000000000..aa75328148 --- /dev/null +++ b/apps/web/tests/fixtures/plugins/fixture-synced-config/cordis.patch.yml @@ -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 diff --git a/apps/web/tests/fixtures/plugins/fixture-synced-config/index.js b/apps/web/tests/fixtures/plugins/fixture-synced-config/index.js new file mode 100644 index 0000000000..893707aa9a --- /dev/null +++ b/apps/web/tests/fixtures/plugins/fixture-synced-config/index.js @@ -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() {} diff --git a/apps/web/tests/fixtures/plugins/fixture-synced-config/package.json b/apps/web/tests/fixtures/plugins/fixture-synced-config/package.json new file mode 100644 index 0000000000..188f4b8557 --- /dev/null +++ b/apps/web/tests/fixtures/plugins/fixture-synced-config/package.json @@ -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" + } + } +} diff --git a/apps/web/tests/forge-panel.e2e.ts b/apps/web/tests/forge-panel.e2e.ts index 04fd421940..0a78f18d6d 100644 --- a/apps/web/tests/forge-panel.e2e.ts +++ b/apps/web/tests/forge-panel.e2e.ts @@ -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 项进行中') diff --git a/apps/web/tests/mention-path-presence.e2e.ts b/apps/web/tests/mention-path-presence.e2e.ts new file mode 100644 index 0000000000..ccd07b8871 --- /dev/null +++ b/apps/web/tests/mention-path-presence.e2e.ts @@ -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 + + 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([]) + }) +}) diff --git a/apps/web/tests/server-restart.e2e.ts b/apps/web/tests/server-restart.e2e.ts index d5b3c180cb..1df9d3a390 100644 --- a/apps/web/tests/server-restart.e2e.ts +++ b/apps/web/tests/server-restart.e2e.ts @@ -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)) diff --git a/apps/web/tests/sidebar-drawer.e2e.ts b/apps/web/tests/sidebar-drawer.e2e.ts index 99b5c3fd43..4a5caf7249 100644 --- a/apps/web/tests/sidebar-drawer.e2e.ts +++ b/apps/web/tests/sidebar-drawer.e2e.ts @@ -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 { await expect.poll(() => toggle.evaluate((button, target) => { const frame = button.closest('[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 () => { diff --git a/apps/web/tests/subagent-conversation.e2e.ts b/apps/web/tests/subagent-conversation.e2e.ts index f91d40d033..08c099c287 100644 --- a/apps/web/tests/subagent-conversation.e2e.ts +++ b/apps/web/tests/subagent-conversation.e2e.ts @@ -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' }) diff --git a/apps/web/tests/subagent-fork-divider.e2e.ts b/apps/web/tests/subagent-fork-divider.e2e.ts index 6d083d8cd1..696c1d9a3d 100644 --- a/apps/web/tests/subagent-fork-divider.e2e.ts +++ b/apps/web/tests/subagent-fork-divider.e2e.ts @@ -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 diff --git a/apps/web/tests/subagent-fork-schedule.snapshot.ts b/apps/web/tests/subagent-fork-schedule.snapshot.ts index 00678b48f4..63ec172b38 100644 --- a/apps/web/tests/subagent-fork-schedule.snapshot.ts +++ b/apps/web/tests/subagent-fork-schedule.snapshot.ts @@ -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('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() + 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('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>, + sessions: Session[], + paths: string[], + expected: string[], +): Promise { + 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]) + : []) +} diff --git a/apps/web/tests/subagent-interrupt-ui.e2e.ts b/apps/web/tests/subagent-interrupt-ui.e2e.ts index f74d79932c..e7fd7953ae 100644 --- a/apps/web/tests/subagent-interrupt-ui.e2e.ts +++ b/apps/web/tests/subagent-interrupt-ui.e2e.ts @@ -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']) diff --git a/apps/web/tests/subagent-interrupt.e2e.ts b/apps/web/tests/subagent-interrupt.e2e.ts index 3a9afe046b..7d2a19cccf 100644 --- a/apps/web/tests/subagent-interrupt.e2e.ts +++ b/apps/web/tests/subagent-interrupt.e2e.ts @@ -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) diff --git a/apps/web/tests/workflow-run.e2e.ts b/apps/web/tests/workflow-run.e2e.ts index 039d0f7cbb..158be75438 100644 --- a/apps/web/tests/workflow-run.e2e.ts +++ b/apps/web/tests/workflow-run.e2e.ts @@ -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) diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index 02033a002f..a569e4fd0a 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -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", diff --git a/docs/capability-seams.i18n.yaml b/docs/capability-seams.i18n.yaml index dc4f6cd357..b8902cbced 100644 --- a/docs/capability-seams.i18n.yaml +++ b/docs/capability-seams.i18n.yaml @@ -6,5 +6,5 @@ en: 41d772192075e133 zh: 5ef3da69b4de1d8a /capability-seams-and-core-services: - en: cdb67d50687e835f - zh: c0f394692ea9dd63 + en: ed07ace42d0688a8 + zh: 583265fbcce148db diff --git a/docs/capability-seams.md b/docs/capability-seams.md index 9c51d96a06..d30884b274 100644 --- a/docs/capability-seams.md +++ b/docs/capability-seams.md @@ -314,6 +314,8 @@ flowchart LR pkg_web_app["web-app"] svc_webApp["ctx.webApp
Served Web GUI"] pkg_harness_dev_context["harness-dev-context"] + pkg_client_config["client-config"] + svc_config["ctx.config
Browser synced configuration lookup"] svc_clientModules["ctx.clientModules
Client plugin graph host"] pkg_workflow["workflow"] svc_workflowEngine["ctx.workflowEngine
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. | diff --git a/docs/capability-seams.zh.md b/docs/capability-seams.zh.md index 39001a25d1..f75b2421de 100644 --- a/docs/capability-seams.zh.md +++ b/docs/capability-seams.zh.md @@ -316,6 +316,8 @@ flowchart LR pkg_web_app["web-app"] svc_webApp["ctx.webApp
Served Web GUI"] pkg_harness_dev_context["harness-dev-context"] + pkg_client_config["client-config"] + svc_config["ctx.config
Browser synced configuration lookup"] svc_clientModules["ctx.clientModules
Client plugin graph host"] pkg_workflow["workflow"] svc_workflowEngine["ctx.workflowEngine
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,不保留交付或完成状态。 | diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 99011a0abd..cae44693a8 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -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' ``` + + + +## `@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 +``` + + @@ -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) | diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 4c27733dc1..6428e0fd44 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -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' ``` + + + +## `@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 +``` + + @@ -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) | diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index bfc13cd6be..60a5ce5574 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -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` | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index df30a6f1af..29b1de15d1 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -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` | diff --git a/docs/module-graph.md b/docs/module-graph.md index 23e7098c22..c0f1e4cde8 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -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) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index 9833137b64..487dcb11e7 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -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) | diff --git a/docs/subsystems/client-modules.md b/docs/subsystems/client-modules.md index 5b058a2508..5ca5a8fe92 100644 --- a/docs/subsystems/client-modules.md +++ b/docs/subsystems/client-modules.md @@ -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) + + + +### `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(packageName: string): SyncedConfig | undefined +``` + +Source: [`packages/client/config/src/types.ts`](../../packages/client/config/src/types.ts) diff --git a/docs/subsystems/client-modules.zh.md b/docs/subsystems/client-modules.zh.md index 9b2af16fda..417484bf26 100644 --- a/docs/subsystems/client-modules.zh.md +++ b/docs/subsystems/client-modules.zh.md @@ -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) + + + +### `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(packageName: string): SyncedConfig | undefined +``` + +Source: [`packages/client/config/src/types.ts`](../../packages/client/config/src/types.ts) diff --git a/docs/subsystems/persistence.i18n.yaml b/docs/subsystems/persistence.i18n.yaml index 054615f66d..be5f045275 100644 --- a/docs/subsystems/persistence.i18n.yaml +++ b/docs/subsystems/persistence.i18n.yaml @@ -33,5 +33,5 @@ en: 142ff3bed547efcf zh: a73ca5ea4743d3e8 /session-persistence/the-backend: - en: adcd78909565b046 - zh: a09bcb6ec0ebad9e + en: ec220159c6fcdb55 + zh: c2023bc5e09f5b7f diff --git a/docs/subsystems/persistence.md b/docs/subsystems/persistence.md index bca5126a2c..0ad93cac68 100644 --- a/docs/subsystems/persistence.md +++ b/docs/subsystems/persistence.md @@ -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. @@ -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`. diff --git a/docs/subsystems/persistence.zh.md b/docs/subsystems/persistence.zh.md index ce458e1487..017516866c 100644 --- a/docs/subsystems/persistence.zh.md +++ b/docs/subsystems/persistence.zh.md @@ -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` 不导入历史。 @@ -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`. diff --git a/docs/subsystems/ptc-runtime.i18n.yaml b/docs/subsystems/ptc-runtime.i18n.yaml index 4f9e3495c7..0dab5c4dd6 100644 --- a/docs/subsystems/ptc-runtime.i18n.yaml +++ b/docs/subsystems/ptc-runtime.i18n.yaml @@ -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 diff --git a/docs/subsystems/ptc-runtime.md b/docs/subsystems/ptc-runtime.md index 94ba67192c..df82f02cbe 100644 --- a/docs/subsystems/ptc-runtime.md +++ b/docs/subsystems/ptc-runtime.md @@ -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. */ diff --git a/docs/subsystems/ptc-runtime.zh.md b/docs/subsystems/ptc-runtime.zh.md index e8a13600f2..159ce8781b 100644 --- a/docs/subsystems/ptc-runtime.zh.md +++ b/docs/subsystems/ptc-runtime.zh.md @@ -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. */ diff --git a/docs/subsystems/subagent.md b/docs/subsystems/subagent.md index 488ef66ac4..cfec4f4d09 100644 --- a/docs/subsystems/subagent.md +++ b/docs/subsystems/subagent.md @@ -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; diff --git a/docs/subsystems/subagent.zh.md b/docs/subsystems/subagent.zh.md index 8f1d6b74a2..7a625e74ef 100644 --- a/docs/subsystems/subagent.zh.md +++ b/docs/subsystems/subagent.zh.md @@ -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; diff --git a/docs/tool-catalog.i18n.yaml b/docs/tool-catalog.i18n.yaml index 295d316f5a..45ea6b9620 100644 --- a/docs/tool-catalog.i18n.yaml +++ b/docs/tool-catalog.i18n.yaml @@ -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 diff --git a/docs/tool-catalog.md b/docs/tool-catalog.md index 1cfadcda2b..8e0fff8d44 100644 --- a/docs/tool-catalog.md +++ b/docs/tool-catalog.md @@ -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 { diff --git a/docs/tool-catalog.zh.md b/docs/tool-catalog.zh.md index b5a6441be7..19b9815194 100644 --- a/docs/tool-catalog.zh.md +++ b/docs/tool-catalog.zh.md @@ -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 { diff --git a/docs/upgrade-guide/v0.2.2-rc.3/client-hmr-plugin-events-stream/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.3/client-hmr-plugin-events-stream/guide.i18n.yaml new file mode 100644 index 0000000000..865b86f2a9 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.3/client-hmr-plugin-events-stream/guide.i18n.yaml @@ -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 diff --git a/docs/upgrade-guide/v0.2.2-rc.3/client-hmr-plugin-events-stream/guide.md b/docs/upgrade-guide/v0.2.2-rc.3/client-hmr-plugin-events-stream/guide.md new file mode 100644 index 0000000000..702c95e6b0 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.3/client-hmr-plugin-events-stream/guide.md @@ -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. diff --git a/docs/upgrade-guide/v0.2.2-rc.3/client-hmr-plugin-events-stream/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.3/client-hmr-plugin-events-stream/guide.zh.md new file mode 100644 index 0000000000..2b301590d0 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.3/client-hmr-plugin-events-stream/guide.zh.md @@ -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` 请求。 diff --git a/docs/upgrade-guide/v0.2.2-rc.3/ptc-output-limit/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.3/ptc-output-limit/guide.i18n.yaml new file mode 100644 index 0000000000..6b79d8c579 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.3/ptc-output-limit/guide.i18n.yaml @@ -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 diff --git a/docs/upgrade-guide/v0.2.2-rc.3/ptc-output-limit/guide.md b/docs/upgrade-guide/v0.2.2-rc.3/ptc-output-limit/guide.md new file mode 100644 index 0000000000..1316d9f3cd --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.3/ptc-output-limit/guide.md @@ -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())`. diff --git a/docs/upgrade-guide/v0.2.2-rc.3/ptc-output-limit/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.3/ptc-output-limit/guide.zh.md new file mode 100644 index 0000000000..0d9693edcf --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.3/ptc-output-limit/guide.zh.md @@ -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())`。 diff --git a/docs/upgrade-guide/v0.2.2-rc.3/ptc-tool-result-inspection/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.3/ptc-tool-result-inspection/guide.i18n.yaml index 1ede92245b..40b4015bfb 100644 --- a/docs/upgrade-guide/v0.2.2-rc.3/ptc-tool-result-inspection/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.3/ptc-tool-result-inspection/guide.i18n.yaml @@ -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 diff --git a/docs/upgrade-guide/v0.2.2-rc.3/ptc-tool-result-inspection/guide.md b/docs/upgrade-guide/v0.2.2-rc.3/ptc-tool-result-inspection/guide.md index 3e2d476945..aa53d7d125 100644 --- a/docs/upgrade-guide/v0.2.2-rc.3/ptc-tool-result-inspection/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.3/ptc-tool-result-inspection/guide.md @@ -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. diff --git a/docs/upgrade-guide/v0.2.2-rc.3/ptc-tool-result-inspection/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.3/ptc-tool-result-inspection/guide.zh.md index ad472ea7d5..bb2476db26 100644 --- a/docs/upgrade-guide/v0.2.2-rc.3/ptc-tool-result-inspection/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.3/ptc-tool-result-inspection/guide.zh.md @@ -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 程序启动时不再报告协议不匹配。 diff --git a/docs/upgrade-guide/v0.2.2-rc.3/subagent-initial-task-source/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.3/subagent-initial-task-source/guide.i18n.yaml new file mode 100644 index 0000000000..ae4bdde74e --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.3/subagent-initial-task-source/guide.i18n.yaml @@ -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 diff --git a/docs/upgrade-guide/v0.2.2-rc.3/subagent-initial-task-source/guide.md b/docs/upgrade-guide/v0.2.2-rc.3/subagent-initial-task-source/guide.md new file mode 100644 index 0000000000..197daff7c2 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.3/subagent-initial-task-source/guide.md @@ -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": "" }`, and its content starts with a text block `Agent 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. diff --git a/docs/upgrade-guide/v0.2.2-rc.3/subagent-initial-task-source/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.3/subagent-initial-task-source/guide.zh.md new file mode 100644 index 0000000000..b2fcea8bdc --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.3/subagent-initial-task-source/guide.zh.md @@ -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 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` 来源并带有发送方前缀。 diff --git a/packages/api/gateway/README.i18n.yaml b/packages/api/gateway/README.i18n.yaml index 4caa0e8c59..9fa55c92ae 100644 --- a/packages/api/gateway/README.i18n.yaml +++ b/packages/api/gateway/README.i18n.yaml @@ -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 diff --git a/packages/api/gateway/README.md b/packages/api/gateway/README.md index 20f87506d0..1652849636 100644 --- a/packages/api/gateway/README.md +++ b/packages/api/gateway/README.md @@ -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. diff --git a/packages/api/gateway/README.zh.md b/packages/api/gateway/README.zh.md index 008b6af7bb..5e6c04eb05 100644 --- a/packages/api/gateway/README.zh.md +++ b/packages/api/gateway/README.zh.md @@ -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 会立即注册,并自行负责启动顺序;进程内调用不变。 diff --git a/packages/api/gateway/src/index.ts b/packages/api/gateway/src/index.ts index bcde443e70..7d154e4d06 100644 --- a/packages/api/gateway/src/index.ts +++ b/packages/api/gateway/src/index.ts @@ -147,6 +147,7 @@ type ConnectionRpcError = Extract[' 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 = { [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', }, ) diff --git a/packages/api/gateway/src/stream-server.ts b/packages/api/gateway/src/stream-server.ts index 6f8e6b5124..f7c53ad389 100644 --- a/packages/api/gateway/src/stream-server.ts +++ b/packages/api/gateway/src/stream-server.ts @@ -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>() private readonly missedHeartbeats = new WeakMap() @@ -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 } +/** + * 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() private writes = Promise.resolve() + /** Encoded bytes queued and not yet written. */ + private queuedBytes = 0 + private drained: PromiseWithResolvers | 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 = 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 { + while (this.queuedBytes > this.streamOutboxBytes && this.socket.readyState === WebSocket.OPEN && !signal.aborted) { + this.drained ??= Promise.withResolvers() + const cancelled = Promise.withResolvers() + 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 { 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((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 diff --git a/packages/api/gateway/tests/gateway-stream.host.spec.ts b/packages/api/gateway/tests/gateway-stream.host.spec.ts index 244f82e383..b90e1c2b89 100644 --- a/packages/api/gateway/tests/gateway-stream.host.spec.ts +++ b/packages/api/gateway/tests/gateway-stream.host.spec.ts @@ -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() } diff --git a/packages/api/gateway/tests/stream-server.host.spec.ts b/packages/api/gateway/tests/stream-server.host.spec.ts index fcf5047c95..f94a4725a1 100644 --- a/packages/api/gateway/tests/stream-server.host.spec.ts +++ b/packages/api/gateway/tests/stream-server.host.spec.ts @@ -226,6 +226,28 @@ describe('Remote stream mux server carrier lifecycle', () => { expect(String(closeEvent[1])).toBe('Remote stream failure could not be delivered') }) + it('stops a stream at its next item after an earlier item failed to write', async () => { + let release!: () => void + const released = new Promise((resolve) => { release = resolve }) + const produced: string[] = [] + const entry = await startMux(async () => (async function *() { + await released + for (const value of ['first', 'second', 'third']) { + produced.push(value) + yield value + await new Promise((resolve) => { setImmediate(resolve) }) + } + })()) + const client = await connect(entry.url) + client.send(openFrame('write-failure-next')) + await vi.waitFor(() => { expect(acceptedSocket(entry.mux)).toBeDefined() }) + failWrites(acceptedSocket(entry.mux)) + const closed = once(client, 'close') + release() + expect((await closed)[0]).toBe(1011) + expect(produced).toEqual(['first', 'second']) + }) + it('closes the carrier when the end frame cannot be written', async () => { const entry = await startMux(async () => (async function *(): AsyncIterable {})()) const client = await connect(entry.url) @@ -351,6 +373,170 @@ describe('Remote stream mux server carrier lifecycle', () => { }) }) +describe('Remote stream mux server downlink order', () => { + /** Hold every server write until released, recording the frames in write order. */ + function holdWrites(serverSocket: WebSocket): { written: string[]; release: () => void } { + const mutable = serverSocket as { + send(data: string, options: unknown, callback: (error?: Error) => void): void + } + const original = mutable.send.bind(serverSocket) + const written: string[] = [] + const held: (() => void)[] = [] + let holding = true + mutable.send = (data, options, callback): void => { + written.push(String((JSON.parse(data) as { value?: unknown }).value)) + const write = (): void => { original(data, options, callback) } + if (holding) held.push(write) + else write() + } + return { written, release: () => { holding = false; for (const write of held.splice(0)) write() } } + } + + /** A source that yields each pushed value until its stream is cancelled; pushes made while it waits wake it in push order. */ + function pushSource(): { source: (signal: AbortSignal) => AsyncIterable; push: (value: string) => void } { + const queue: string[] = [] + let wake: (() => void) | undefined + return { + push: (value) => { queue.push(value); wake?.() }, + source: async function *(signal) { + signal.addEventListener('abort', () => { wake?.() }, { once: true }) + while (!signal.aborted) { + const value = queue.shift() + if (value !== undefined) yield value + else await new Promise((resolve) => { wake = resolve }) + } + }, + } + } + + it('writes frames of different streams in production order while an earlier write is still pending', async () => { + const sources = { a: pushSource(), b: pushSource() } + let opened = 0 + const allOpen = Promise.withResolvers() + const entry = await startMux(async (endpoint, _payload, _uplink, _peer, control) => { + if (++opened === 2) allOpen.resolve(undefined) + return sources[endpoint === 'fixture/a' ? 'a' : 'b'].source(control.signal) + }) + const client = await connect(entry.url) + const frames = collectFrames(client) + client.send(openFrame('a', 'fixture/a')) + client.send(openFrame('b', 'fixture/b')) + await allOpen.promise + await new Promise((resolve) => { setImmediate(resolve) }) + const held = holdWrites(acceptedSocket(entry.mux)) + sources.a.push('a1') + await vi.waitFor(() => { expect(held.written).toEqual(['a1']) }) + // The first write is still pending; stream a's next frame is produced before stream b's. + sources.a.push('a2') + sources.b.push('b1') + await new Promise((resolve) => { setImmediate(resolve) }) + held.release() + await vi.waitFor(() => { expect(frames.map(frame => frame.value)).toEqual(['a1', 'a2', 'b1']) }) + client.close() + await once(client, 'close') + }) + + it('keeps every stream paused until the whole connection backlog drains', async () => { + const sources = { a: pushSource(), b: pushSource() } + let opened = 0 + const allOpen = Promise.withResolvers() + const entry = await startMux(async (endpoint, _payload, _uplink, _peer, control) => { + if (++opened === 2) allOpen.resolve(undefined) + return sources[endpoint === 'fixture/a' ? 'a' : 'b'].source(control.signal) + }, 2_000, 262_144, true, undefined, 1) + const client = await connect(entry.url) + const frames = collectFrames(client) + client.send(openFrame('a', 'fixture/a')) + client.send(openFrame('b', 'fixture/b')) + await allOpen.promise + // Both sources reach their first wait before anything is pushed. + await new Promise((resolve) => { setImmediate(resolve) }) + const held = holdWrites(acceptedSocket(entry.mux)) + sources.a.push('a1') + sources.b.push('b1') + sources.a.push('a2') + await new Promise((resolve) => { setImmediate(resolve) }) + held.release() + await vi.waitFor(() => { expect(frames.map(frame => frame.value)).toEqual(['a1', 'b1', 'a2']) }) + client.close() + await once(client, 'close') + }) + + it('ends a cancelled stream at once while another stream keeps the connection backlog over its bound', async () => { + const sources = { a: pushSource(), b: pushSource() } + const ended = Promise.withResolvers() + let opened = 0 + const allOpen = Promise.withResolvers() + const entry = await startMux(async (endpoint, _payload, _uplink, _peer, control) => { + if (++opened === 2) allOpen.resolve(undefined) + if (endpoint === 'fixture/a') return sources.a.source(control.signal) + return (async function *() { + try { + yield * sources.b.source(control.signal) + } finally { + ended.resolve(undefined) + } + })() + }, 2_000, 262_144, true, undefined, 1) + const client = await connect(entry.url) + client.send(openFrame('a', 'fixture/a')) + client.send(openFrame('b', 'fixture/b')) + await allOpen.promise + await new Promise((resolve) => { setImmediate(resolve) }) + const held = holdWrites(acceptedSocket(entry.mux)) + sources.a.push('a1') + sources.b.push('b1') + await vi.waitFor(() => { expect(held.written).toEqual(['a1']) }) + await new Promise((resolve) => { setImmediate(resolve) }) + // a1 is still held and b1 queued behind it, so the backlog stays over its bound while stream b is cancelled. + client.send(JSON.stringify({ type: 'cancel', streamId: 'b' })) + await ended.promise + held.release() + client.close() + await once(client, 'close') + }) + + it('fails a stream whose item cannot be encoded without queuing a frame for it', async () => { + const entry = await startMux(async () => (async function *() { yield 10n })()) + const client = await connect(entry.url) + const frames = collectFrames(client) + client.send(openFrame('bigint')) + await vi.waitFor(() => { + expect(frames).toEqual([{ + type: 'error', streamId: 'bigint', + error: { code: 'internal', message: 'api gateway: Remote stream item is not JSON serializable', details: {} }, + }]) + }) + client.close() + await once(client, 'close') + }) + + it('pauses every stream while the connection backlog exceeds its bound and resumes when it drains', async () => { + const source = pushSource() + const pulled: string[] = [] + const entry = await startMux(async (_endpoint, _payload, _uplink, _peer, control) => (async function *() { + for await (const value of source.source(control.signal)) { + pulled.push(value) + yield value + } + })(), 2_000, 262_144, true, undefined, 1) + const client = await connect(entry.url) + const frames = collectFrames(client) + client.send(openFrame('bounded')) + await vi.waitFor(() => { expect(acceptedSocket(entry.mux)).toBeDefined() }) + const held = holdWrites(acceptedSocket(entry.mux)) + source.push('x1') + source.push('x2') + await vi.waitFor(() => { expect(held.written).toEqual(['x1']) }) + await new Promise((resolve) => { setImmediate(resolve) }) + expect(pulled).toEqual(['x1']) + held.release() + await vi.waitFor(() => { expect(frames.map(frame => frame.value)).toEqual(['x1', 'x2']) }) + client.close() + await once(client, 'close') + }) +}) + describe('Remote stream mux server Peer binding', () => { it('closes an upgrade at once when the admitted Peer scope is already disposed', async () => { const peer = await fixturePeer() @@ -667,11 +853,13 @@ async function startMux( streamInboxBytes = 262_144, compression = true, peer?: PeerScope, + streamOutboxBytes = 1_048_576, ): Promise { const admitted = peer ?? await fixturePeer() const mux = new RemoteStreamMuxServer(open, mapFailure, { heartbeatIntervalMs, streamInboxBytes, + streamOutboxBytes, compression, }) const http = createServer() diff --git a/packages/boot/plugin-manager/src/tools.ts b/packages/boot/plugin-manager/src/tools.ts index 5c09ecca0d..4ff58935bd 100644 --- a/packages/boot/plugin-manager/src/tools.ts +++ b/packages/boot/plugin-manager/src/tools.ts @@ -86,7 +86,7 @@ export const inject = ['tools', 'pluginManager', 'sandboxPolicy'] export function apply(ctx: Context): void { ctx.tools.register(defineTool({ name: 'plugin_manager', - description: '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.', + description: '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.', parameters: { action: { type: 'string', required: true, enum: ['list_plugins', 'list_bundles', 'set_plugin', 'set_bundle', 'install_bundle', 'remove_bundle', 'list_version_exemptions', 'set_version_exemption'], description: 'Management operation.' }, target: { type: 'string', description: 'Plugin entry id, bundle package name, or installation spec, according to action. For an Official catalog entry, pass list_bundles installTarget.spec to install_bundle.' }, diff --git a/packages/bundle/web-app/cordis.patch.yml b/packages/bundle/web-app/cordis.patch.yml index 7d977cb888..b8e829ae07 100644 --- a/packages/bundle/web-app/cordis.patch.yml +++ b/packages/bundle/web-app/cordis.patch.yml @@ -214,10 +214,11 @@ - id: harness-dev-context name: '@deepseek-ai/dsh-harness-dev-context' - # The client-plugin reload chain, always mounted: it is idle until a - # rebuild watcher (pnpm run dev:web) actually rewrites client bundles. It - # is a row rather than a child of web-runtime because its node half is a - # client-side package, which a host-side bundle cannot import. + # The plugin-events stream, always mounted: it delivers graph changes, + # synced configuration, and rebuilt bundles (the last only while a rebuild + # watcher such as pnpm run dev:web rewrites client bundles). It is a row + # rather than a child of web-runtime because its node half is a client-side + # package, which a host-side bundle cannot import. - id: client-hmr name: '@deepseek-ai/dsh-client-hmr' diff --git a/packages/client/config/README.i18n.yaml b/packages/client/config/README.i18n.yaml new file mode 100644 index 0000000000..4df7511484 --- /dev/null +++ b/packages/client/config/README.i18n.yaml @@ -0,0 +1,37 @@ +# Bilingual-pair consistency record for README.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 packages/client/config/README.md +/: + en: b1b4983cf77dfb64 + zh: f0fa8e1768282924 +/deepseek-ai-dsh-client-config: + en: e62a65f2b2584f33 + zh: 7321f65efcf87c4f +/deepseek-ai-dsh-client-config/summary: + en: 7de2db28a3a02961 + zh: e216c6e28756b37b +/deepseek-ai-dsh-client-config/table-of-contents: + en: d152484eb41ac6b4 + zh: 09388d293f9be9cb +/deepseek-ai-dsh-client-config/use-this-package: + en: f3b26e6717641ce1 + zh: bd9db5843968e118 +/deepseek-ai-dsh-client-config/understand-the-implementation: + en: 84cb86065c15a770 + zh: 675b8559bf14b413 +/deepseek-ai-dsh-client-config/further-exploration: + en: f91f84cf3575375f + zh: dfac4f201eaafd82 +/deepseek-ai-dsh-client-config/model-experience: + en: 0eb698f5627362b0 + zh: 5d73fdb6cf8f246c +/deepseek-ai-dsh-client-config/model-experience/kv-cache-effect: + en: ca75c51c89c2c9b0 + zh: 2064958b0754647e +/deepseek-ai-dsh-client-config/known-limitations-and-deferred-work: + en: cd8d4c6d8ae328a0 + zh: 62d462921cb015d6 +/deepseek-ai-dsh-client-config/known-limitations-and-deferred-work/dev-note: + en: e67f633dc6fe7773 + zh: e88aeb617ffb74ea diff --git a/packages/client/config/README.md b/packages/client/config/README.md new file mode 100644 index 0000000000..beaecbfdb6 --- /dev/null +++ b/packages/client/config/README.md @@ -0,0 +1,82 @@ +--- +description: "Types of browser-synced plugin configuration" +kind: "package-reference" +--- + +# @deepseek-ai/dsh-client-config + +English | [中文](README.zh.md) + +## Summary + +The types a browser plugin uses to read its live Host configuration. A plugin declares its Config once, with a Host schema; its Client face receives the top-level volatile fields as a `SyncedConfig` through `apply` and reads other packages' synced Config through `ctx.config`. This package holds types only; [Client Modules](../modules/README.md#synced-plugin-configuration) projects, delivers, and updates the values. + +## Table of Contents + +- [Use this package](#use-this-package) +- [Understand the implementation](#understand-the-implementation) +- [Further Exploration](#further-exploration) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Use this package + +A plugin package lists this package in `devDependencies` and imports from `@deepseek-ai/dsh-client-config/types` with `import type` only: + +| Type | Use | +|---|---| +| `SyncedConfig` | The `apply` config of a Client face whose shared Config type is `C`: one `SyncedConfigRef` per top-level `Volatile` field. Every field may read `undefined` (a secret, an unprojectable value, or a Host build not yet matching the browser code), so the plugin handles the absent value at each read | +| `SyncedConfigRef` | One field: `get()` reads the current frozen value as the Host reads a volatile reference, and `getSnapshot` with `subscribe` make it the observable source injected into a slot's `hooks` compartment. It has no write operation | +| `SyncedConfigValues` | The JSON values of one plugin's synced fields, as graph rows carry them | +| `SyncedConfigService` | `ctx.config.resolveConfigByPackage(packageName)`, a read-only lookup of another package's current activation object; importing the types also declares `ctx.config` | + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +The package exports types through `./types` and both faces, and its Host and Client `apply` register nothing. Client Modules implements every type: the Host face projects values into graph rows, and the page entry controller hands each plugin activation its object and provides `ctx.config`. Plugins therefore depend on these types instead of on the bootstrap Client Modules package. + +
+ +----- + + +## Further Exploration + +- [Agent Note: browser plugin configuration sync](../../../.agents/notes/implemented/architecture/2026-11-15-client-config-sync.md) +- [Client Modules synced plugin configuration](../modules/README.md#synced-plugin-configuration) + +----- + + +## Model Experience + +None, as the package declares browser configuration types and registers nothing model-facing. + +#### KV Cache effect + +None; this package neither assembles nor sends a provider request. + +## Known Limitations and Deferred Work + + + +- `resolveConfigByPackage` trusts the caller's Config type argument; a wrong type is not detected. + + +### Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/client/config/README.zh.md b/packages/client/config/README.zh.md new file mode 100644 index 0000000000..2a4e43bec6 --- /dev/null +++ b/packages/client/config/README.zh.md @@ -0,0 +1,82 @@ +--- +description: "浏览器同步插件配置的类型" +kind: "package-reference" +--- + +# @deepseek-ai/dsh-client-config + +[English](README.md) | 中文 + +## 概述 + +浏览器插件读取自身实时 Host 配置所用的类型。插件只声明一份 Config 并配一个 Host schema;其 Client 面通过 `apply` 以 `SyncedConfig` 收到顶层 volatile 字段,并通过 `ctx.config` 读取其他包的同步配置。本包只包含类型;值的投影、下发与更新由 [Client Modules](../modules/README.zh.md#synced-plugin-configuration) 负责。 + +## 目录 + +- [使用本包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [进一步探索](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与延期工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用本包 + +插件包把本包列入 `devDependencies`,只用 `import type` 从 `@deepseek-ai/dsh-client-config/types` 导入: + +| 类型 | 用途 | +|---|---| +| `SyncedConfig` | 共享 Config 类型为 `C` 的 Client 面的 `apply` 配置:每个顶层 `Volatile` 字段对应一个 `SyncedConfigRef`。每个字段都可能读到 `undefined`(密钥、无法投影的值,或尚未与浏览器代码对应的 Host 构建),插件在每次读取时处理缺值 | +| `SyncedConfigRef` | 单个字段:`get()` 读取当前冻结值,写法与 Host 读取 volatile 引用一致;`getSnapshot` 与 `subscribe` 使它可以直接作为可观察数据源注入 slot 的 `hooks`。它没有写操作 | +| `SyncedConfigValues` | 图行携带的单个插件同步字段的 JSON 值 | +| `SyncedConfigService` | `ctx.config.resolveConfigByPackage(packageName)`,只读地查询另一个包当前激活的对象;导入这些类型也同时声明了 `ctx.config` | + +----- + + +## 理解实现 + +
+实现细节——点击展开 + +本包通过 `./types` 与两个面导出类型,Host 与 Client 的 `apply` 都不注册任何内容。所有类型由 Client Modules 实现:Host 面把值投影进图行,页面条目控制器把对象交给每次插件激活并提供 `ctx.config`。因此插件依赖这些类型,而不是依赖启动最早的 Client Modules 包。 + +
+ +----- + + +## 进一步探索 + +- [Agent Note:前端插件配置同步](../../../.agents/notes/implemented/architecture/2026-11-15-client-config-sync.zh.md) +- [Client Modules 同步插件配置](../modules/README.zh.md#synced-plugin-configuration) + +----- + + +## 模型体验 + +无,本包声明浏览器配置类型,不注册任何面向模型的内容。 + +#### KV Cache 影响 + +无;本包既不组装也不发送 provider 请求。 + +## 已知限制与延期工作 + + + +- `resolveConfigByPackage` 信任调用方给出的 Config 类型参数,类型写错不会被发现。 + + +### 开发备注 + +
+维护者工作上下文——点击展开 + +无。 + +
diff --git a/packages/client/config/locale/de.json b/packages/client/config/locale/de.json new file mode 100644 index 0000000000..9923227d40 --- /dev/null +++ b/packages/client/config/locale/de.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Typen für synchronisierte Konfiguration", + "description": "Typen zum Lesen der Live-Host-Konfiguration in Browser-Plugins." + } +} diff --git a/packages/client/config/locale/en.json b/packages/client/config/locale/en.json new file mode 100644 index 0000000000..9d2545045d --- /dev/null +++ b/packages/client/config/locale/en.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Synced configuration types", + "description": "Types for reading live Host configuration in browser plugins." + } +} diff --git a/packages/client/config/locale/es.json b/packages/client/config/locale/es.json new file mode 100644 index 0000000000..56b2228770 --- /dev/null +++ b/packages/client/config/locale/es.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Tipos de configuración sincronizada", + "description": "Tipos para leer la configuración en vivo del Host en los plugins del navegador." + } +} diff --git a/packages/client/config/locale/fr.json b/packages/client/config/locale/fr.json new file mode 100644 index 0000000000..91d3c8efcd --- /dev/null +++ b/packages/client/config/locale/fr.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Types de configuration synchronisée", + "description": "Types pour lire la configuration en direct de l’Host dans les plugins du navigateur." + } +} diff --git a/packages/client/config/locale/ja.json b/packages/client/config/locale/ja.json new file mode 100644 index 0000000000..b7401bec41 --- /dev/null +++ b/packages/client/config/locale/ja.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "同期設定の型", + "description": "ブラウザープラグインがライブの Host 設定を読み取るための型。" + } +} diff --git a/packages/client/config/locale/pt.json b/packages/client/config/locale/pt.json new file mode 100644 index 0000000000..7ceeeca489 --- /dev/null +++ b/packages/client/config/locale/pt.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Tipos de configuração sincronizada", + "description": "Tipos para ler a configuração ao vivo do Host em plugins do navegador." + } +} diff --git a/packages/client/config/locale/ru.json b/packages/client/config/locale/ru.json new file mode 100644 index 0000000000..43e7f38637 --- /dev/null +++ b/packages/client/config/locale/ru.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Типы синхронизированной конфигурации", + "description": "Типы для чтения актуальной конфигурации Host в браузерных плагинах." + } +} diff --git a/packages/client/config/locale/zh.json b/packages/client/config/locale/zh.json new file mode 100644 index 0000000000..3729979770 --- /dev/null +++ b/packages/client/config/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "同步配置类型", + "description": "浏览器插件读取实时 Host 配置所用的类型。" + } +} diff --git a/packages/client/config/package.json b/packages/client/config/package.json new file mode 100644 index 0000000000..110580e5c7 --- /dev/null +++ b/packages/client/config/package.json @@ -0,0 +1,60 @@ +{ + "name": "@deepseek-ai/dsh-client-config", + "description": "Types of browser-synced plugin configuration", + "version": "0.2.2-rc.3", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/client/config" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./types": { + "types": "./lib/types/types.d.ts" + }, + "./client": { + "types": "./lib/types/client/index.d.ts", + "default": "./lib/client.js" + }, + "./locale/*.json": "./locale/*.json", + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "dsh": { + "client": { + "inject": [], + "platform": "web" + } + }, + "scripts": { + "bundle": "tsdown", + "watch": "tsdown --watch" + }, + "license": "MIT", + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:~" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-client-store": "workspace:*", + "@deepseek-ai/dsh-util-values": "workspace:*" + }, + "files": [ + "locale/*.json", + "lib/index.js", + "lib/client.js", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "lib/**/*.js.map", + "src" + ] +} diff --git a/packages/client/config/src/client/index.ts b/packages/client/config/src/client/index.ts new file mode 100644 index 0000000000..895b2816b9 --- /dev/null +++ b/packages/client/config/src/client/index.ts @@ -0,0 +1,5 @@ +/** Client face of the synced configuration types package; `@deepseek-ai/dsh-client-modules` provides the runtime. */ +export type * from '../types.ts' + +/** Register nothing in the browser. */ +export function apply(): void {} diff --git a/packages/client/config/src/index.ts b/packages/client/config/src/index.ts new file mode 100644 index 0000000000..b80c7fc15e --- /dev/null +++ b/packages/client/config/src/index.ts @@ -0,0 +1,5 @@ +/** Host face of the synced configuration types package; the types live in `./types` and no Host behavior exists. */ +export type * from './types.ts' + +/** Register nothing on the Host. */ +export function apply(): void {} diff --git a/packages/client/config/src/types.ts b/packages/client/config/src/types.ts new file mode 100644 index 0000000000..1553730bf6 --- /dev/null +++ b/packages/client/config/src/types.ts @@ -0,0 +1,49 @@ +/** + * Types of browser-synced plugin configuration. A plugin declares its Config once, with a Host schema; its Client face + * receives the top-level volatile fields as a {@link SyncedConfig} through `apply`. `@deepseek-ai/dsh-client-modules` + * implements these types; plugins import them from here only. + * @module @deepseek-ai/dsh-client-config/types + */ +import type { Volatile, VolatileSnapshot } from '@deepseek-ai/cordis' +import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' +import type { JsonValue } from '@deepseek-ai/dsh-util-values' + +/** JSON values of one plugin's synced Config fields, keyed by field name. */ +export type SyncedConfigValues = { readonly [field: string]: JsonValue } + +/** + * One synced Config field. `get()` reads it as the Host face reads a volatile reference; the reference is also the + * observable source a plugin injects into a slot's `hooks` compartment. Its snapshot keeps its identity until the value + * changes, and every changed field of one update is set before any subscriber runs. It has no write operation. + */ +export interface SyncedConfigRef extends Volatile, ObservableSnapshot> {} + +/** + * Browser view of a plugin's shared Config type: its top-level `Volatile` fields, each a {@link SyncedConfigRef}. + * Every field may read `undefined`: the Host never sends a `role('secret')` field, keeps a field it cannot project + * unsent, and may send values of a Host build that does not yet match the running browser code. The plugin handles + * the absent value at each read. + */ +export type SyncedConfig = { + readonly [K in keyof C as NonNullable extends Volatile ? K : never]-?: + NonNullable extends Volatile ? SyncedConfigRef : never +} + +/** Read-only access to other packages' synced Config; a plugin receives its own through `apply`. */ +export interface SyncedConfigService { + /** + * 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(packageName: string): SyncedConfig | undefined +} + +declare module '@deepseek-ai/cordis' { + interface Context { + /** Read-only lookup of other packages' synced Config, provided by the client-modules plugin face. */ + config: SyncedConfigService + } +} diff --git a/packages/client/config/tests/apply.client.spec.ts b/packages/client/config/tests/apply.client.spec.ts new file mode 100644 index 0000000000..bcd696fec6 --- /dev/null +++ b/packages/client/config/tests/apply.client.spec.ts @@ -0,0 +1,9 @@ +/** The types package registers nothing: both faces' `apply` return without effects. */ +import { expect, it } from 'vitest' +import { apply as clientApply } from '../src/client/index.ts' +import { apply as hostApply } from '../src/index.ts' + +it('registers nothing on either face', () => { + expect(hostApply).not.toThrow() + expect(clientApply).not.toThrow() +}) diff --git a/packages/client/config/tsconfig.json b/packages/client/config/tsconfig.json new file mode 100644 index 0000000000..337ff3d33d --- /dev/null +++ b/packages/client/config/tsconfig.json @@ -0,0 +1,13 @@ +{ + "extends": "../../../tsconfig.base.client.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": ["src"], + "references": [ + { "path": "../../../vendor/cordis" }, + { "path": "../store" }, + { "path": "../../util/values" } + ] +} diff --git a/packages/client/config/tsdown.config.ts b/packages/client/config/tsdown.config.ts new file mode 100644 index 0000000000..7aa03cebc1 --- /dev/null +++ b/packages/client/config/tsdown.config.ts @@ -0,0 +1,3 @@ +import { clientBundle } from '../tsdown.client.ts' + +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/hmr/README.i18n.yaml b/packages/client/hmr/README.i18n.yaml index 63402bfa3b..2604e22138 100644 --- a/packages/client/hmr/README.i18n.yaml +++ b/packages/client/hmr/README.i18n.yaml @@ -9,8 +9,8 @@ en: 3f8aceed1a3a4221 zh: d48ff0e88eefa046 /deepseek-ai-dsh-client-hmr/summary: - en: 4ea7a901735da086 - zh: 77fd5083661ceff5 + en: b27f1dc15a6e9f90 + zh: 76c4c84a18637def /deepseek-ai-dsh-client-hmr/table-of-contents: en: d152484eb41ac6b4 zh: 09388d293f9be9cb @@ -33,8 +33,8 @@ en: e5cdd3f10a344b10 zh: 70c8efd12531039d /deepseek-ai-dsh-client-hmr/understand-the-implementation/design-concept: - en: 90f8d06719b177bd - zh: c5a770ddcacc0f87 + en: 3925d19184d37198 + zh: 9917f64db546fe03 /deepseek-ai-dsh-client-hmr/understand-the-implementation/the-browser-swap: en: 269ff43822114dc8 zh: 8604c39c8050858a @@ -45,8 +45,8 @@ en: cc2114489f83dc70 zh: 6268962333946c82 /deepseek-ai-dsh-client-hmr/understand-the-implementation/source-map: - en: 67728b630b30b9aa - zh: 55861de2169ecafe + en: e8ae5ad4073c5774 + zh: ee0c6e11f2e78f45 /deepseek-ai-dsh-client-hmr/further-exploration: en: 684aff651f59a12d zh: 671bcfc50918508e @@ -57,8 +57,8 @@ en: ca75c51c89c2c9b0 zh: de54f3467ef3b9be /deepseek-ai-dsh-client-hmr/known-limitations-and-deferred-work: - en: 0003a3d701a7f7b1 - zh: 9be135531742cf86 + en: 98abf5b8b1a9c32a + zh: 579fd09b1946966c /deepseek-ai-dsh-client-hmr/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/client/hmr/README.md b/packages/client/hmr/README.md index 93cdef6c0e..0ca27432ef 100644 --- a/packages/client/hmr/README.md +++ b/packages/client/hmr/README.md @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -`dsh-client-hmr` keeps open Web pages in sync with the Host plugin graph and reloads rebuilt browser bundles. Ordinary plugin enable/disable changes take effect without reloading the page or restarting the Host. Code rebuilds replace the affected plugin with fresh component state. The model sees no new input or output. +`dsh-client-hmr` keeps open Web pages in sync with the Host plugin graph, including synced plugin configuration, and reloads rebuilt browser bundles. Ordinary plugin enable/disable changes and synced configuration changes take effect without reloading the page or restarting the Host. Code rebuilds replace the affected plugin with fresh component state. The model sees no new input or output. ## Table of Contents @@ -59,7 +59,7 @@ This section explains how the reload chain is built; observable behavior is cove ### Design concept -The Host half watches each package's stamped entry artifact and serves `/plugins/events`. It forwards existing graph-change and rebuilt notifications; every new connection receives the current full graph. A graph describes the browser’s desired entries and carries no Host cleanup-completion guarantee. Host activation and cleanup remain owned by the Host lifecycle. The entry's mtime, ctime, and size identify the revision without hashing its contents; unchanged metadata requires no content read. Host restarts over unchanged artifacts keep the same revisions, so reconnecting the graph stream does not replace browser plugins. The browser half delegates both frame kinds to Client Modules, which serializes entry changes and waits for browser resource cleanup. +The Host half watches each package's stamped entry artifact and serves the authenticated `pluginEvents/follow` Remote stream. Every stream generation opens with a `baseline` frame holding the current full graph, whose rows carry each plugin's [synced configuration](../modules/README.md#synced-plugin-configuration), followed by `graph` and `rebuilt` increments. A graph describes the browser’s desired entries and carries no Host cleanup-completion guarantee. Host activation and cleanup remain owned by the Host lifecycle. The entry's mtime, ctime, and size identify the revision without hashing its contents; unchanged metadata requires no content read. Host restarts over unchanged artifacts keep the same revisions, so reconnecting the graph stream does not replace browser plugins. The browser half mounts its own `pluginEvents` namespace, so the stream does not depend on the api-remotes assembly, and consumes it through `RemoteSnapshotStream` while Remote access allows `pluginEvents/follow`. It delegates graph and rebuilt frames to Client Modules, which applies synced configuration, serializes entry changes, and waits for browser resource cleanup. Carrier loss and a Host-side stream end reconnect, and the new baseline replaces any frames missed meanwhile. ### The browser swap @@ -77,9 +77,10 @@ Download failures leave the running plugin active. After the old fiber is torn d | File | Role | |---|---| -| [`src/index.ts`](src/index.ts) | Node half: bundle stat-poll, `rebuilt` reporting, `/plugins/events` SSE channel | -| [`src/client/index.ts`](src/client/index.ts) | Browser half: SSE subscription through the page's `__DSH_TRANSPORT__.fetch` when a shell provides one (the worker preview's tunnel), otherwise through `EventSource`, and delegation to the shared entry controller | -| [`src/events.ts`](src/events.ts) | Shared frame types (`graph` / `rebuilt`) and the endpoint constant | +| [`src/index.ts`](src/index.ts) | Node half: bundle stat-poll and `rebuilt` reporting; mounts the Remote service | +| [`src/plugin-events.ts`](src/plugin-events.ts) | Host `pluginEvents` Remote service: baseline and ordered increments per stream generation | +| [`src/client/index.ts`](src/client/index.ts) | Browser half: mounts the `pluginEvents` namespace, follows the stream, and forwards frames to the entry controller | +| [`src/types.ts`](src/types.ts) | Shared frame types (`baseline` / `graph` / `rebuilt`) | @@ -115,7 +116,7 @@ These limits define what the reload driver does not preserve or restore. They ar - **Reload is coarse by design** — a fresh fiber and fresh components; React state inside the reloaded plugin is lost while the data layer (connection/runtime fibers, Session objects) is untouched. react-refresh-grade state preservation conflicts with re-executing the bundle and is deliberately out. - **No failure rollback** — after the old fiber is torn down, a failed replacement does not restore the previous bundle. -- **Web transport only** — Electron installation and backend restart handling do not use this SSE path. Entry reconciliation itself is transport-independent. +- **The stream depends on its carrier** — it runs over Connection and the API Gateway Client face. When replacing either of them fails to import or activate, this plugin cannot activate and the page stops receiving plugin changes until it reloads. Electron installation does not use this stream; entry reconciliation itself is transport-independent. ### Dev Note diff --git a/packages/client/hmr/README.zh.md b/packages/client/hmr/README.zh.md index cb893bd851..b38d3bf410 100644 --- a/packages/client/hmr/README.zh.md +++ b/packages/client/hmr/README.zh.md @@ -9,7 +9,7 @@ kind: "package-reference" ## 概述 -`dsh-client-hmr` 让已打开的 Web 页面与 Host 插件图保持同步,并重载重建后的浏览器 bundle。普通插件的启停无需刷新页面或重启 Host 即可生效。代码重建会替换受影响插件并重置其组件状态。模型不会收到新的输入或输出。 +`dsh-client-hmr` 让已打开的 Web 页面与 Host 插件图及同步的插件配置保持一致,并重载重建后的浏览器 bundle。普通插件的启停与同步配置的变化无需刷新页面或重启 Host 即可生效。代码重建会替换受影响插件并重置其组件状态。模型不会收到新的输入或输出。 ## 目录 @@ -59,7 +59,7 @@ kind: "package-reference" ### 设计理念 -Host 半侧监听每个包带完成标记的入口产物,并提供 `/plugins/events`。它转发现有的图变化与重建通知;每个新连接都会收到当前完整图。图描述浏览器的目标条目,不保证 Host 清理已经完成。Host 的激活与清理仍由 Host 生命周期管理。入口的 mtime、ctime 和大小共同标识 revision,无需对其内容求哈希;元数据未变时无需读取内容。Host 重启时若产物未变,revision 保持不变,因此图流重连不会替换浏览器插件。浏览器半侧将两种帧都交给 Client Modules,由它串行处理条目变更并等待浏览器资源清理。 +Host 半侧监听每个包带完成标记的入口产物,并提供经过鉴权的 `pluginEvents/follow` Remote 流。每一代流先发一个 `baseline` 帧,包含当前完整图,图的每一行携带该插件的[同步配置](../modules/README.zh.md#synced-plugin-configuration),之后发送 `graph` 与 `rebuilt` 增量。图描述浏览器的目标条目,不保证 Host 清理已经完成。Host 的激活与清理仍由 Host 生命周期管理。入口的 mtime、ctime 和大小共同标识 revision,无需对其内容求哈希;元数据未变时无需读取内容。Host 重启时若产物未变,revision 保持不变,因此图流重连不会替换浏览器插件。浏览器半侧自行挂载 `pluginEvents` 命名空间,因此这条流不依赖 api-remotes 组装;在 Remote access 允许 `pluginEvents/follow` 时通过 `RemoteSnapshotStream` 消费。它把图帧与重建帧交给 Client Modules,由它应用同步配置、串行处理条目变更并等待浏览器资源清理。连接丢失或 Host 侧流结束会重连,新的 baseline 覆盖期间遗漏的帧。 ### 浏览器侧替换 @@ -77,9 +77,10 @@ fiber 的激活 epoch 会串联其服务提供方的 uid,因此替换提供方 | 文件 | 职责 | |---|---| -| [`src/index.ts`](src/index.ts) | node 半侧:bundle stat 轮询、`rebuilt` 上报、`/plugins/events` SSE 通道 | -| [`src/client/index.ts`](src/client/index.ts) | 浏览器半侧:页面有外壳提供的 `__DSH_TRANSPORT__.fetch`(worker preview 的隧道)时经它订阅 SSE,否则用 `EventSource`;并调用共享条目控制器 | -| [`src/events.ts`](src/events.ts) | 共享帧类型(`graph` / `rebuilt`)与端点常量 | +| [`src/index.ts`](src/index.ts) | node 半侧:bundle stat 轮询与 `rebuilt` 上报;挂载 Remote 服务 | +| [`src/plugin-events.ts`](src/plugin-events.ts) | Host `pluginEvents` Remote 服务:每一代流的 baseline 与有序增量 | +| [`src/client/index.ts`](src/client/index.ts) | 浏览器半侧:挂载 `pluginEvents` 命名空间、跟随该流,并把帧交给条目控制器 | +| [`src/types.ts`](src/types.ts) | 共享帧类型(`baseline` / `graph` / `rebuilt`) | @@ -115,7 +116,7 @@ fiber 的激活 epoch 会串联其服务提供方的 uid,因此替换提供方 - **重载有意保持粗粒度**——全新 fiber 与全新组件;被重载插件内的 React 状态会丢失,而数据层(连接 fiber、运行时 fiber、Session 对象)不受影响。react-refresh 级状态保留与重新执行 bundle 冲突,因此有意排除。 - **失败时不回滚**——旧 fiber 被卸载后,替换失败不会恢复先前的 bundle。 -- **仅负责 Web 传输**——Electron 的安装和后端重启流程不使用此 SSE 路径。条目对账本身不依赖传输。 +- **流依赖其承载链路**——它运行在 Connection 与 API Gateway Client 面之上。替换二者之一时若导入或激活失败,本插件无法激活,页面在刷新前收不到插件变化。Electron 的安装不使用这条流;条目对账本身不依赖传输。 ### 开发备注 diff --git a/packages/client/hmr/package.json b/packages/client/hmr/package.json index 47a546bdc8..f532774873 100644 --- a/packages/client/hmr/package.json +++ b/packages/client/hmr/package.json @@ -1,6 +1,6 @@ { "name": "@deepseek-ai/dsh-client-hmr", - "description": "Web client graph synchronization and rebuilt-bundle reload transport", + "description": "Web client graph and rebuilt-bundle delivery over an authenticated Remote stream", "version": "0.2.2-rc.3", "publishConfig": { "access": "public" @@ -18,17 +18,33 @@ "types": "./lib/types/index.d.ts", "default": "./lib/index.js" }, + "./types": { + "types": "./lib/types/types.d.ts" + }, "./client": { "types": "./lib/types/client/index.d.ts", "default": "./lib/client.js" }, + "./typert": { + "types": "./lib/typert.host.d.ts", + "default": "./lib/typert.host.js" + }, + "./remote": { + "types": "./lib/typert.remote-client.d.ts", + "default": "./lib/typert.remote-client.js" + }, "./src/*": "./src/*", "./package.json": "./package.json", "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { + "external": [ + "@deepseek-ai/dsh-api-gateway/client" + ], "inject": [ + "@deepseek-ai/dsh-api-gateway", + "@deepseek-ai/dsh-api-remote-access", "@deepseek-ai/dsh-client-modules" ], "platform": "web", @@ -37,17 +53,20 @@ }, "license": "MIT", "dependencies": { - "@deepseek-ai/schemastery": "workspace:~" + "@deepseek-ai/dsh-deque": "workspace:*", + "@deepseek-ai/dsh-typert-protocol": "workspace:*", + "@deepseek-ai/schemastery": "workspace:~", + "zod": "4.6.6" }, "peerDependencies": { "@deepseek-ai/cordis": "workspace:~" }, "devDependencies": { - "@deepseek-ai/cordis-plugin-loader": "workspace:~", - "@deepseek-ai/dsh-client-modules": "workspace:*", - "@deepseek-ai/dsh-host-webserver": "workspace:*", "@deepseek-ai/cordis": "workspace:~", - "eventsource-parser": "^3.1.0" + "@deepseek-ai/cordis-plugin-loader": "workspace:~", + "@deepseek-ai/dsh-api-gateway": "workspace:*", + "@deepseek-ai/dsh-api-remote-access": "workspace:*", + "@deepseek-ai/dsh-client-modules": "workspace:*" }, "files": [ "locale/*.json", @@ -56,6 +75,11 @@ "lib/types/**/*.d.ts", "lib/types/**/*.d.ts.map", "lib/**/*.js.map", + "lib/typert.host.js", + "lib/typert.host.d.ts", + "lib/typert.remote-client.js", + "lib/typert.remote-client.d.ts", + "lib/typert.remote-client.d.ts.map", "src" ] } diff --git a/packages/client/hmr/src/client/index.ts b/packages/client/hmr/src/client/index.ts index 1e44b3db64..3e514fc816 100644 --- a/packages/client/hmr/src/client/index.ts +++ b/packages/client/hmr/src/client/index.ts @@ -1,87 +1,114 @@ -/** Web SSE transport for page-owned client entry reconciliation and rebuilt code replacement. */ +/** Remote-stream transport for page-owned client entry reconciliation, rebuilt code replacement, and synced configuration. */ import type { Context } from '@deepseek-ai/cordis' -import { EventSourceParserStream } from 'eventsource-parser/stream' -import type { PluginsEventParseResult } from '../events.ts' -import { EVENTS_ROUTE, parsePluginsEventFrame } from '../events.ts' +import { RemoteSnapshotStream, RemoteStreamCarrierError, type RemoteStreamCarrierFailure } from '@deepseek-ai/dsh-api-gateway/client' +import type {} from '@deepseek-ai/dsh-api-remote-access/client' +import type {} from '@deepseek-ai/dsh-client-modules/client' +// This package mounts its own namespace, so the channel does not depend on the api-remotes assembly being replaceable. +import pluginEventsRemote from '@deepseek-ai/dsh-client-hmr/remote' +import type { PluginsEventBaseline, PluginsEventFrame, PluginsEventIncrement } from '../types.ts' -export type { PluginsEventFrame } from '../events.ts' +export type * from '../types.ts' /** Cordis plugin name. */ export const name = 'client-hmr' -/** Required service: the client module system whose entry controller handles received frames. */ -export const inject = ['modules'] +/** Required services: the module system whose entry controller handles frames, the Remote carrier, and Remote access. */ +export const inject = ['modules', 'remote', 'remoteAccess'] -/** Request carrier a shell installs when it owns the page transport, such as the worker preview's tunnel. */ -type PageTransportFetch = (input: string, init: RequestInit) => Promise +const CARRIER_LOST: RemoteStreamCarrierFailure['code'] = 'gateway/carrier-lost' +/** Remote failures a Host reload produces while it withdraws `pluginEvents` with the socket still open. */ +const RELOADING: ReadonlySet = new Set(['gateway/invocation-unavailable', 'gateway/service-unavailable']) -/** Page global carrying the shell transport; absent in the served web app. */ -interface PageTransportGlobal { - __DSH_TRANSPORT__?: { fetch?: PageTransportFetch } +/** + * Open one generation, reporting an endpoint the Host has withdrawn while it reloads as a carrier loss, so the stream + * reconnects instead of ending. + * @param open - opens the generation's frames. + * @yields the generation's frames. + */ +async function *reconnectWhileReloading(open: () => AsyncIterable): AsyncIterable { + try { + yield * open() + } catch (error) { + if (error instanceof Error && 'code' in error && RELOADING.has(String(error.code))) { + throw new RemoteStreamCarrierError('Plugin events are unavailable while the Host reloads', { cause: error }) + } + throw error + } +} + +/** The generated `pluginEvents` client method this plugin calls. */ +interface PluginEventsNamespace { + follow(signal: AbortSignal): AsyncIterable +} + +/** Receivers of one followed stream. */ +interface PluginEventSinks { + /** A generation's complete graph. */ + readonly baseline: (frame: PluginsEventBaseline) => void + /** One increment after the baseline. */ + readonly increment: (frame: PluginsEventIncrement) => void + /** A terminal stream failure; graph changes stop until the page reloads. */ + readonly failed: (error: unknown) => void } /** - * Read the document-relative events route through a shell-owned transport until it closes or `signal` aborts. - * @param fetch - The shell's request carrier. - * @param signal - Aborts the stream when the plugin disposes. - * @param receive - Handles one SSE `data` payload. - * @throws Error when the Host refuses the stream or the stream ends while the plugin is active. + * Follow `pluginEvents/follow` as a reconnecting baseline-and-increment stream. + * @param ctx - context carrying the Remote carrier and the mounted `pluginEvents` namespace. + * @param sinks - frame receivers. + * @returns the disposer that stops the stream and waits until no frame can arrive. */ -async function readPageTransportEvents(fetch: PageTransportFetch, signal: AbortSignal, receive: (data: string) => void): Promise { - const response = await fetch(EVENTS_ROUTE, { method: 'GET', headers: { accept: 'text/event-stream' }, signal }) - if (!response.ok || response.body === null) { - throw new Error(`client-hmr: ${EVENTS_ROUTE} answered ${String(response.status)}`) - } - const reader = response.body.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).getReader() - for (;;) { - const { done, value } = await reader.read() - if (done) break - receive(value.data) - } - if (!signal.aborted) throw new Error(`client-hmr: ${EVENTS_ROUTE} closed; client graph changes stop until the page reloads`) +function followPluginEvents(ctx: Context, sinks: PluginEventSinks): () => Promise { + // `$mount` registered the namespace as its own service; only this plugin mounts it, so it is read by name rather + // than through a declared injection. + const namespace = ctx.get('remote.pluginEvents') as PluginEventsNamespace | undefined + if (namespace === undefined) throw new Error('client-hmr: the mounted pluginEvents namespace is not registered') + const stream = ctx.remote.$stream({ + name: 'Plugin events', + open: signal => reconnectWhileReloading(() => namespace.follow(signal)), + // A Host-side end (the service restarting) reconnects rather than ending the logical stream. + ended: (): RemoteStreamCarrierFailure => Object.assign(new Error('Plugin events stream ended'), { code: CARRIER_LOST }), + }) + const control = new RemoteSnapshotStream(stream, { + name: 'Plugin events', + isSnapshot: (frame): frame is PluginsEventBaseline => frame.type === 'baseline', + replace: sinks.baseline, + update: sinks.increment, + failed: sinks.failed, + }) + control.start() + return () => control.dispose() } /** - * Forward graph snapshots and rebuilds to the page's shared serial controller. The event stream arrives through the - * shell transport when the page has one, otherwise through the browser `EventSource`. - * @param ctx - Plugin context with the client module system. + * Forward each stream generation's graph and rebuilds to the page's serial entry controller, which also applies each + * row's synced configuration, while Remote access allows the stream. + * @param ctx - Plugin context with the client module system and Remote carrier. + * @returns the disposer of this plugin's `pluginEvents` namespace. */ -export function apply(ctx: Context): void { +export async function apply(ctx: Context): Promise<() => Promise> { + const unmount = await ctx.remote.$mount(pluginEventsRemote) const entries = ctx.modules.entries - const handle = (frame: Extract['frame']): void => { - const run = frame.type === 'graph' - ? Promise.resolve().then(() => entries.sync(frame.graph)) - : entries.reload(frame.id, frame.rev) - void run.catch((error: unknown) => { ctx.logger.error(error) }) + // A malformed graph throws synchronously from sync(); both paths report through the same rejection. + const run = (task: () => Promise): void => { + void Promise.resolve().then(task).catch((error: unknown) => { ctx.logger.error(error) }) } - const receive = (data: string): void => { - let value: unknown - try { - value = JSON.parse(data) - } catch { - // Wire boundary: a malformed transport frame is dropped loudly. - ctx.logger.warn(`client-hmr: unparseable event frame: ${data}`) - return - } - const parsed = parsePluginsEventFrame(value) - if (parsed.kind === 'invalid') { - ctx.logger.warn(`client-hmr: invalid event frame: ${data}`) - } else if (parsed.kind === 'frame') { - handle(parsed.frame) - } + const sinks: PluginEventSinks = { + baseline: (frame) => { run(() => entries.sync(frame.graph)) }, + increment: (frame) => { + switch (frame.type) { + case 'graph': + run(() => entries.sync(frame.graph)) + break + case 'rebuilt': + run(() => entries.reload(frame.id, frame.rev)) + break + default: + // Forward compatibility: a newer Host's increment type is ignored. + break + } + }, + failed: (error) => { ctx.logger.error('client-hmr: plugin events stopped; client graph changes stop until the page reloads', error) }, } - - ctx.effect(() => { - const transport = (globalThis as PageTransportGlobal).__DSH_TRANSPORT__ - if (transport?.fetch !== undefined) { - const controller = new AbortController() - void readPageTransportEvents(transport.fetch, controller.signal, receive).catch((error: unknown) => { - if (!controller.signal.aborted) ctx.logger.error(error) - }) - return () => { controller.abort() } - } - const source = new EventSource(EVENTS_ROUTE) - source.addEventListener('message', (event: MessageEvent) => { receive(event.data) }) - return () => { source.close() } - }, 'client-hmr: event source') + ctx.remoteAccess.whenAccess('pluginEvents/follow', () => followPluginEvents(ctx, sinks)) + return unmount } diff --git a/packages/client/hmr/src/events.ts b/packages/client/hmr/src/events.ts deleted file mode 100644 index b041b67a48..0000000000 --- a/packages/client/hmr/src/events.ts +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Wire protocol of the `/plugins/events` SSE channel — single source for - * both halves of this package. Frames still cross a wire boundary: the - * browser half validates them at its JSON parse point; sharing the type keeps - * the two ends from drifting, not from parsing. - */ - -import type { WebBootGraph } from '@deepseek-ai/dsh-client-modules' - -/** One SSE frame: the settled graph on connection or change, or one rebuilt bundle notice. */ -export type PluginsEventFrame = - | { type: 'graph'; graph: WebBootGraph } - | { type: 'rebuilt'; id: string; rev: string } - -/** Browser wire-parse result: known frame, forward-compatible unknown type, or malformed payload. */ -export type PluginsEventParseResult = - | { kind: 'frame'; frame: { type: 'graph'; graph: unknown } | Extract } - | { kind: 'unknown' } - | { kind: 'invalid' } - -/** - * Validate the frame envelope; the module controller parses the complete graph before updating its index. - * @param value - Parsed JSON value from the EventSource message. - * @returns the known frame, an unknown-type marker, or an invalid marker. - */ -export function parsePluginsEventFrame(value: unknown): PluginsEventParseResult { - if (typeof value !== 'object' || value === null) return { kind: 'invalid' } - const record = value as Record - switch (record.type) { - case 'rebuilt': - return typeof record.id === 'string' && typeof record.rev === 'string' - ? { kind: 'frame', frame: { type: 'rebuilt', id: record.id, rev: record.rev } } - : { kind: 'invalid' } - case 'graph': - return typeof record.graph === 'object' && record.graph !== null - ? { kind: 'frame', frame: { type: 'graph', graph: record.graph } } - : { kind: 'invalid' } - default: - return typeof record.type === 'string' ? { kind: 'unknown' } : { kind: 'invalid' } - } -} - -/** System SSE endpoint pushing graph/rebuilt frames (wire protocol constant). */ -export const EVENTS_ENDPOINT = '/plugins/events' - -/** - * Document-relative form of {@link EVENTS_ENDPOINT} used by the browser half. - * See .agents/notes/implemented/architecture/2026-09-14-web-document-relative-app-routes.md. - */ -export const EVENTS_ROUTE = EVENTS_ENDPOINT.slice(1) diff --git a/packages/client/hmr/src/index.ts b/packages/client/hmr/src/index.ts index bfef8803a0..c07826c697 100644 --- a/packages/client/hmr/src/index.ts +++ b/packages/client/hmr/src/index.ts @@ -1,30 +1,26 @@ /** * Host transport for Web client graph changes and rebuilt bundles. One interval * stat-polls every graph row's client bundle (polling by design: network mounts - * deliver no inotify events), reports changes through - * `clientModules.rebuilt(id)`, and serves the `/plugins/events` SSE channel - * broadcasting graph/rebuilt frames to the browser half (src/client/). + * deliver no inotify events) and reports changes through + * `clientModules.rebuilt(id)`; the `pluginEvents` Remote stream delivers graph, + * rebuild, and synced configuration changes to the browser half (src/client/). * The Web composition mounts this transport for live graph updates; * a development rebuild watcher also supplies bundle changes. */ import { statSync } from 'node:fs' -import type { ServerResponse } from 'node:http' import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' -// Type imports carry the clientModules/webServer Context merges. +// Type import carries the clientModules Context merge. import type { ClientArtifactBaseline } from '@deepseek-ai/dsh-client-modules' -import type {} from '@deepseek-ai/dsh-host-webserver' -import type { PluginsEventFrame } from './events.ts' -import { EVENTS_ENDPOINT } from './events.ts' +import { PluginEvents } from './plugin-events.ts' -export type { PluginsEventFrame } from './events.ts' -export { EVENTS_ENDPOINT } from './events.ts' +export type * from './types.ts' /** Cordis plugin name. */ export const name = 'client-hmr' -/** Required services: the client graph and Web route registry. */ -export const inject = ['clientModules', 'webServer'] +/** Required service: the client graph. */ +export const inject = ['clientModules'] /** Plugin config, validated by the same-named schemastery schema. */ export interface Config { @@ -36,11 +32,6 @@ export const Config: z = z.object({ pollIntervalMs: z.number().step(1).min(1).default(500), }) -/** Serialize one frame as an SSE data line. */ -function sseData(frame: PluginsEventFrame): string { - return `data: ${JSON.stringify(frame)}\n\n` -} - type WatchedBundleStat = Omit type WatchedBundle = { @@ -61,7 +52,7 @@ function sameBundleStat(left: WatchedBundleStat, right: WatchedBundleStat): bool } /** - * Mount bundle watches and graph/rebuilt SSE delivery. + * Mount bundle watches and the plugin-events Remote service. * @param ctx - host plugin context carrying clientModules and webServer. * @param config - validated {@link Config}. */ @@ -155,55 +146,5 @@ export function apply(ctx: Context, config: Config): void { } }, 'client-hmr: bundle watches') - // --- /plugins/events SSE channel ---------------------------------------- - const connections = new Set() - - const publishGraph = (): void => { - const line = sseData({ type: 'graph', graph: ctx.clientModules.graph() }) - for (const res of connections) res.write(line) - } - - const connect = (res: ServerResponse): void => { - res.writeHead(200, { - 'content-type': 'text/event-stream', - 'cache-control': 'no-cache', - 'connection': 'keep-alive', - }) - // Comment line on open so clients/proxies see a live channel even when - // no rebuild ever happens; EventSource frame parsing skips it naturally. - res.write(': connected\n\n') - connections.add(res) - res.write(sseData({ type: 'graph', graph: ctx.clientModules.graph() })) - res.on('close', () => { connections.delete(res) }) - } - - ctx.effect(() => { - const disposeRoute = ctx.webServer.register({ - kind: 'exact', - path: EVENTS_ENDPOINT, - auth: 'anonymous', - handler: (req, res) => { - // Named routes match ahead of the carrier's method gate; keep the old - // global 405 semantics for non-GET hits on this endpoint. - if (req.method !== 'GET' && req.method !== 'HEAD') { - res.writeHead(405) - res.end() - return - } - connect(res) - }, - }) - const unsubscribeGraph = ctx.clientModules.onGraphChanged(publishGraph) - const unsubscribe = ctx.clientModules.onRebuilt((id, rev) => { - const line = sseData({ type: 'rebuilt', id, rev }) - for (const res of connections) res.write(line) - }) - return () => { - unsubscribeGraph() - unsubscribe() - disposeRoute() - for (const res of connections) res.destroy() - connections.clear() - } - }, 'client-hmr: /plugins/events channel') + ctx.plugin(PluginEvents) } diff --git a/packages/client/hmr/src/plugin-events.ts b/packages/client/hmr/src/plugin-events.ts new file mode 100644 index 0000000000..edf2217756 --- /dev/null +++ b/packages/client/hmr/src/plugin-events.ts @@ -0,0 +1,101 @@ +/** Host `pluginEvents` Remote service: an authenticated baseline-and-increment stream of graph and rebuild changes. */ +import type { Context } from '@deepseek-ai/cordis' +import { Deque } from '@deepseek-ai/dsh-deque' +import { principalOf, Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' +import type { Principal } from '@deepseek-ai/dsh-typert-protocol' +import type {} from '@deepseek-ai/dsh-client-modules' +import type { PluginsEventFrame, PluginsEventIncrement } from './types.ts' + +/** Ordered increments of one stream generation; closing wakes the waiting reader. */ +class Follower { + private readonly frames = new Deque() + private wake: (() => void) | undefined + closed = false + + /** @param principal - the calling Peer's principal; undefined for the owner. */ + constructor(readonly principal: Principal | undefined) {} + + push(frame: PluginsEventIncrement): void { + this.frames.pushBack(frame) + this.wake?.() + } + + close(): void { + this.closed = true + this.wake?.() + } + + /** @returns the oldest queued increment, if any. */ + take(): PluginsEventIncrement | undefined { + return this.frames.popFront() + } + + /** @returns a promise settled by the next push or close. */ + wait(): Promise { + return new Promise((resolve) => { this.wake = resolve }) + } +} + +/** + * Streams start from the current graph; listeners attach before the baseline is read. Every Peer the Remote access + * policies admit may follow; each frame carries the graph as that Peer may see it, so only the owner receives configured + * synced values and every other Peer receives schema defaults. + */ +export class PluginEvents extends TypertRemoteService { + static inject = ['clientModules'] + + private readonly followers = new Set() + + /** @param ctx - Host context with the Web client graph. */ + constructor(ctx: Context) { + super(ctx, 'pluginEvents', { namespace: 'pluginEvents' }) + ctx.effect(() => { + const offGraph = ctx.clientModules.onGraphChanged(() => { this.publishGraph() }) + const offRebuilt = ctx.clientModules.onRebuilt((id, rev) => { this.publish({ type: 'rebuilt', id, rev }) }) + return () => { + offGraph() + offRebuilt() + for (const follower of this.followers) follower.close() + this.followers.clear() + } + }, 'client-hmr: plugin event followers') + } + + /** + * Follow Web client graph and rebuild changes; every generation starts with a complete baseline. + * @param signal - generation cancellation. + * @returns the baseline followed by ordered increments; the stream ends when the service unloads. + */ + @Remote({ mode: 'stream' }) + async *follow(signal: AbortSignal): AsyncIterable { + signal.throwIfAborted() + const follower = new Follower(principalOf(this.ctx.invocation)) + this.followers.add(follower) + const abort = (): void => { follower.close() } + signal.addEventListener('abort', abort, { once: true }) + try { + yield { type: 'baseline', graph: this.ctx.clientModules.graphFor(follower.principal) } + // The increments are yielded from this generator itself, with no delegated generator adding a step before each + // reaches the Gateway's write queue. + while (!follower.closed) { + const frame = follower.take() + if (frame !== undefined) yield frame + else await follower.wait() + } + } finally { + signal.removeEventListener('abort', abort) + this.followers.delete(follower) + follower.close() + } + } + + private publish(frame: PluginsEventIncrement): void { + for (const follower of this.followers) follower.push(frame) + } + + private publishGraph(): void { + for (const follower of this.followers) follower.push({ type: 'graph', graph: this.ctx.clientModules.graphFor(follower.principal) }) + } +} + +export default PluginEvents diff --git a/packages/client/hmr/src/types.ts b/packages/client/hmr/src/types.ts new file mode 100644 index 0000000000..4d7ff2a2b1 --- /dev/null +++ b/packages/client/hmr/src/types.ts @@ -0,0 +1,22 @@ +/** + * Wire protocol of the `pluginEvents/follow` Remote stream, shared by both faces. Each stream generation opens with + * one `baseline` frame holding the complete graph, including each row's synced configuration, followed by increments. + */ +import type { WebBootGraph } from '@deepseek-ai/dsh-client-modules/types' + +/** Complete state opening every stream generation. */ +export interface PluginsEventBaseline { + type: 'baseline' + /** Current Web client graph. */ + graph: WebBootGraph +} + +/** One increment after the baseline. */ +export type PluginsEventIncrement = + /** The graph after a structural or synced configuration change. */ + | { type: 'graph'; graph: WebBootGraph } + /** One rebuilt bundle. */ + | { type: 'rebuilt'; id: string; rev: string } + +/** Every frame of the stream. */ +export type PluginsEventFrame = PluginsEventBaseline | PluginsEventIncrement diff --git a/packages/client/hmr/tests/events.client.spec.ts b/packages/client/hmr/tests/events.client.spec.ts deleted file mode 100644 index 5fa07b800e..0000000000 --- a/packages/client/hmr/tests/events.client.spec.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { parsePluginsEventFrame } from '../src/events.ts' - -describe('plugin event wire parser', () => { - it('accepts complete rebuilt and graph frames', () => { - expect(parsePluginsEventFrame({ type: 'rebuilt', id: 'plugin', rev: 'next' })).toEqual({ - kind: 'frame', - frame: { type: 'rebuilt', id: 'plugin', rev: 'next' }, - }) - const graph = { rev: 'graph', entries: [], batches: [] } - expect(parsePluginsEventFrame({ type: 'graph', graph })).toEqual({ - kind: 'frame', - frame: { type: 'graph', graph }, - }) - }) - - it('separates forward-compatible unknown types from malformed known frames', () => { - expect(parsePluginsEventFrame({ type: 'future', payload: true })).toEqual({ kind: 'unknown' }) - for (const value of [null, [], {}, { type: 'rebuilt', id: 'plugin' }, { type: 'graph', graph: null }]) { - expect(parsePluginsEventFrame(value)).toEqual({ kind: 'invalid' }) - } - }) -}) diff --git a/packages/client/hmr/tests/generated-remote-stub.ts b/packages/client/hmr/tests/generated-remote-stub.ts new file mode 100644 index 0000000000..43231c5f9a --- /dev/null +++ b/packages/client/hmr/tests/generated-remote-stub.ts @@ -0,0 +1,26 @@ +/** + * Resolvable stand-in for the generated `./remote` contribution when this package has no built `lib/`. + * It declares the one stream endpoint the Client face mounts, so whole-client specs exercise the real + * `$mount` path; its item schema accepts any JSON value instead of the generated frame validation. + */ +import { createTypertRemoteInfo } from '@deepseek-ai/dsh-typert-protocol/remote-info' +import { z } from 'zod' + +export default createTypertRemoteInfo({ + package: '@deepseek-ai/dsh-client-hmr', + methods: { + 'pluginEvents/follow': { + service: 'pluginEvents', + mode: 'stream', + invocation: { kind: 'direct' }, + parameters: [], + cancellation: { parameter: 'signal' }, + result: { + mode: 'strict', + typeSymbol: '@deepseek-ai/dsh-client-hmr/types#PluginsEventFrame', + create: () => z.json(), + jsonSchema: {}, + }, + }, + }, +}, z) diff --git a/packages/client/hmr/tests/node-half.client.spec.ts b/packages/client/hmr/tests/node-half.host.spec.ts similarity index 64% rename from packages/client/hmr/tests/node-half.client.spec.ts rename to packages/client/hmr/tests/node-half.host.spec.ts index fb212b71c8..bbc48a1dd5 100644 --- a/packages/client/hmr/tests/node-half.client.spec.ts +++ b/packages/client/hmr/tests/node-half.host.spec.ts @@ -1,18 +1,15 @@ /** * Node half of the HMR plugin: bundle watches follow the graph, stat changes - * report through clientModuleHost.rebuilt, and everything dies with the fiber. + * report through clientModuleHost.rebuilt, and everything dies with the fiber, + * including the plugin-events Remote service. */ -import { EventEmitter } from 'node:events' -import type { ServerResponse, IncomingMessage } from 'node:http' import { mkdtempSync, rmSync, statSync, unlinkSync, utimesSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import Loader from '@deepseek-ai/cordis-plugin-loader' import { Context } from '@deepseek-ai/cordis' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { ClientArtifactBaseline, ClientModuleRegistry, WebBootGraph } from '@deepseek-ai/dsh-client-modules' -import type { WebRoute, WebServer } from '@deepseek-ai/dsh-host-webserver' -import { apply, Config, EVENTS_ENDPOINT, inject } from '../src/index.ts' +import { apply, Config, inject } from '../src/index.ts' const POLL_MS = 20 @@ -75,24 +72,9 @@ function fakeClientModuleHost(rows: Map, options: FakeHostOption return fake as FakeHost } -// Structural fake: the plugin only touches register(); the service class -// carries private state a literal cannot (and need not) reproduce. -function fakeHttpServer(routes: WebRoute[]): WebServer { - const fake: Pick = { - register(route: WebRoute) { - routes.push(route) - return () => { routes.splice(routes.indexOf(route), 1) } - }, - tapIndex: () => () => {}, - port: 0, - } - return fake as WebServer -} - -async function mount(clientModuleHost: FakeHost, webServer: WebServer) { +async function mount(clientModuleHost: FakeHost) { const ctx = new Context() ctx.provide('clientModules', clientModuleHost) - ctx.provide('webServer', webServer) const fiber = ctx.plugin( { inject: [...inject], Config, apply }, { pollIntervalMs: POLL_MS }, @@ -106,11 +88,9 @@ describe('hmr node half', () => { const bundle = join(dir, 'a.js') writeFileSync(bundle, 'v1') const clientModuleHost = fakeClientModuleHost(new Map([['pkg-a', bundle]])) - const routes: WebRoute[] = [] - const fiber = await mount(clientModuleHost, fakeHttpServer(routes)) + const fiber = await mount(clientModuleHost) - expect(routes).toHaveLength(1) - expect(routes[0]).toMatchObject({ kind: 'exact', path: EVENTS_ENDPOINT }) + expect(fiber.ctx.get('pluginEvents')).toBeDefined() expect(clientModuleHost.rebuiltCalls).toEqual([]) // Nudge mtime past stat granularity so the poller sees a content signal. @@ -128,7 +108,7 @@ describe('hmr node half', () => { await vi.waitFor(() => { expect(clientModuleHost.rebuiltCalls).toContain('pkg-a') }, { timeout: 3_000 }) await fiber.dispose() - expect(routes).toHaveLength(0) + expect(fiber.ctx.get('pluginEvents')).toBeUndefined() // Watcher gone: further file changes report nothing. clientModuleHost.rebuiltCalls.length = 0 writeFileSync(bundle, 'v4-after-dispose') @@ -142,7 +122,7 @@ describe('hmr node half', () => { writeFileSync(early, 'v1') const rows = new Map([['pkg-early', early]]) const clientModuleHost = fakeClientModuleHost(rows) - const fiber = await mount(clientModuleHost, fakeHttpServer([])) + const fiber = await mount(clientModuleHost) clientModuleHost.rebuiltCalls.length = 0 writeFileSync(late, 'v1') @@ -175,7 +155,7 @@ describe('hmr node half', () => { }, }) - const fiber = await mount(clientModuleHost, fakeHttpServer([])) + const fiber = await mount(clientModuleHost) expect(clientModuleHost.rebuiltCalls).toEqual(['pkg-a']) clientModuleHost.rebuiltCalls.length = 0 @@ -191,7 +171,7 @@ describe('hmr node half', () => { utimesSync(bundle, fixedTime, fixedTime) const baseline = statSync(bundle) const clientModuleHost = fakeClientModuleHost(new Map([['pkg-a', bundle]])) - const fiber = await mount(clientModuleHost, fakeHttpServer([])) + const fiber = await mount(clientModuleHost) try { expect(clientModuleHost.rebuiltCalls).toEqual([]) // Filesystem ctime can advance more coarsely than Date.now(); the fixture needs a distinct value. @@ -214,7 +194,7 @@ describe('hmr node half', () => { utimesSync(bundle, fixedTime, fixedTime) const baseline = statSync(bundle) const clientModuleHost = fakeClientModuleHost(new Map([['pkg-a', bundle]])) - const fiber = await mount(clientModuleHost, fakeHttpServer([])) + const fiber = await mount(clientModuleHost) clientModuleHost.rebuiltCalls.length = 0 unlinkSync(bundle) @@ -246,94 +226,9 @@ describe('hmr node half', () => { }, }) - const fiber = await mount(clientModuleHost, fakeHttpServer([])) + const fiber = await mount(clientModuleHost) await vi.waitFor(() => { expect(clientModuleHost.rebuiltCalls).toEqual(['pkg-a', 'pkg-a']) }, { timeout: 3_000 }) await fiber.dispose() }) }) - - -it('broadcasts the desired graph without waiting for Host activation or cleanup', async () => { - const ctx = new Context() - await ctx.plugin(Loader) - const bundle = join(dir, 'a.js') - writeFileSync(bundle, 'a') - const rows = new Map([['a', bundle]]) - const host = fakeClientModuleHost(rows) - const routes: WebRoute[] = [] - ctx.provide('clientModules', host) - ctx.provide('webServer', fakeHttpServer(routes)) - let release!: () => void - let cleaned!: () => void - let started!: () => void - const starting = new Promise((resolve) => { started = resolve }) - const activation = new Promise((resolve) => { release = resolve }) - const cleanup = new Promise((resolve) => { cleaned = resolve }) - let disposed = false - ctx.loader.internal = { version: 'client', import: async () => ({ - apply: async (pluginCtx: Context) => { - pluginCtx.effect(() => async () => { await cleanup; disposed = true }) - started() - await activation - }, - }) } as never - const entryId = await ctx.loader.create({ name: 'owned' }) - await starting - const fiber = ctx.plugin({ inject, Config, apply }, { pollIntervalMs: POLL_MS }) - await fiber.await() - const route = routes[0]! - const connect = async () => { - const lines: string[] = [] - const response = Object.assign(new EventEmitter(), { - writeHead: vi.fn(), write: (line: string) => { lines.push(line) }, - destroy: vi.fn(), end: vi.fn(), - }) - await route.handler({ method: 'GET' } as IncomingMessage, response as unknown as ServerResponse) - return { lines, response } - } - try { - const first = await connect() - expect(first.lines).toHaveLength(2) - const frame = JSON.parse(first.lines[1]!.slice(6)) as { graph: WebBootGraph } - expect(frame.graph.entries.map(row => row.id)).toEqual(['a']) - const second = await connect() - expect(second.lines[1]).toBe(first.lines[1]) - expect(first.lines).toHaveLength(2) - release() - const owned = ctx.loader.resolve(entryId).fiber! - await owned.await() - const child = owned.ctx.plugin({ apply() {} }) - await child.await() - expect(child.entry).toBe(owned.entry) - await child.dispose() - await child.await() - await ctx.loader.await() - await new Promise(resolve => setImmediate(resolve)) - expect(second.lines).toHaveLength(2) - first.response.emit('close') - ctx.loader.remove(entryId) - rows.clear() - host.fireGraphChanged() - expect(second.lines).toHaveLength(3) - expect(disposed).toBe(false) - expect((JSON.parse(second.lines[2]!.slice(6)) as { graph: WebBootGraph }).graph.entries).toEqual([]) - const third = await connect() - expect(third.lines[1]).toBe(second.lines[2]) - expect(second.lines).toHaveLength(3) - cleaned() - while (owned.inertia !== undefined) await owned.inertia - expect(disposed).toBe(true) - expect(second.lines).toHaveLength(3) - await fiber.dispose() - host.fireGraphChanged() - expect(second.lines).toHaveLength(3) - expect(second.response.destroy).toHaveBeenCalledOnce() - expect(third.response.destroy).toHaveBeenCalledOnce() - } finally { - release() - cleaned() - await fiber.dispose() - await ctx.fiber.dispose() - } -}) diff --git a/packages/client/hmr/tests/plugin-events.host.spec.ts b/packages/client/hmr/tests/plugin-events.host.spec.ts new file mode 100644 index 0000000000..3f57c81a8b --- /dev/null +++ b/packages/client/hmr/tests/plugin-events.host.spec.ts @@ -0,0 +1,101 @@ +/** The plugin-events Remote stream opens each generation with a complete baseline and then forwards ordered increments. */ +import { Context } from '@deepseek-ai/cordis' +import { afterEach, expect, it } from 'vitest' +import type { ClientModuleRegistry, WebBootGraph } from '@deepseek-ai/dsh-client-modules' +import { PluginEvents } from '../src/plugin-events.ts' +import type { PluginsEventFrame } from '../src/types.ts' + +const roots: Context[] = [] +afterEach(async () => { await Promise.all(roots.splice(0).map(ctx => ctx.fiber.dispose())) }) + +function graph(rev: string, config = 'configured'): WebBootGraph { + return { rev, entries: [{ id: 'a', url: 'a.js', rev, config: { value: config } }], batches: [] } +} + +/** Structural fake: the service reads only these members. */ +async function harness() { + const ctx = new Context() + roots.push(ctx) + let current = graph('g1') + const graphListeners = new Set<() => void>() + const rebuiltListeners = new Set<(id: string, rev: string) => void>() + const modules: Pick = { + graph: () => current, + graphFor: principal => principal === undefined ? current : graph(current.rev, 'default'), + onGraphChanged: (listener) => { graphListeners.add(listener); return () => { graphListeners.delete(listener) } }, + onRebuilt: (listener) => { rebuiltListeners.add(listener); return () => { rebuiltListeners.delete(listener) } }, + } + ctx.provide('clientModules', modules as ClientModuleRegistry) + const fiber = ctx.plugin(PluginEvents) + await fiber.await() + // No Context merge is declared for the service; its Remote namespace is the public face. + const service = ctx.get('pluginEvents') as PluginEvents + return { + fiber, + follow: (signal: AbortSignal) => service.follow(signal)[Symbol.asyncIterator](), + /** Follow as the Remote call of one non-owner Peer. */ + followAs: (kind: string, signal: AbortSignal) => { + const invocation = { peer: { principal: { kind } } } + return (ctx.extend({ invocation }).get('pluginEvents') as PluginEvents).follow(signal)[Symbol.asyncIterator]() + }, + setGraph(next: WebBootGraph) { current = next; for (const listener of graphListeners) listener() }, + rebuilt(id: string, rev: string) { for (const listener of rebuiltListeners) listener(id, rev) }, + listeners: () => graphListeners.size + rebuiltListeners.size, + } +} + +async function take(iterator: AsyncIterator, count: number): Promise { + const frames: PluginsEventFrame[] = [] + for (let index = 0; index < count; index++) { + const next = await iterator.next() + if (next.done === true) break + frames.push(next.value) + } + return frames +} + +it('sends a baseline, then graph and rebuilt increments in order', async () => { + const h = await harness() + const controller = new AbortController() + const iterator = h.follow(controller.signal) + expect(await take(iterator, 1)).toEqual([{ type: 'baseline', graph: graph('g1') }]) + h.setGraph(graph('g2')) + h.rebuilt('a', 'r2') + expect(await take(iterator, 2)).toEqual([ + { type: 'graph', graph: graph('g2') }, + { type: 'rebuilt', id: 'a', rev: 'r2' }, + ]) + controller.abort() + expect(await iterator.next()).toEqual({ done: true, value: undefined }) +}) + +it('ends open streams and releases its listeners when unloaded', async () => { + const h = await harness() + const iterator = h.follow(new AbortController().signal) + await take(iterator, 1) + const pending = iterator.next() + await h.fiber.dispose() + expect(await pending).toEqual({ done: true, value: undefined }) + expect(h.listeners()).toBe(0) +}) + +it('rejects a follow whose signal is already aborted', async () => { + const h = await harness() + const controller = new AbortController() + controller.abort() + await expect(h.follow(controller.signal).next()).rejects.toThrow() +}) + +it('sends a non-owner Peer the graph with schema defaults while the owner receives configured values', async () => { + const h = await harness() + const controller = new AbortController() + const owner = h.follow(controller.signal) + const viewer = h.followAs('viewer', controller.signal) + expect(await take(owner, 1)).toEqual([{ type: 'baseline', graph: graph('g1') }]) + expect(await take(viewer, 1)).toEqual([{ type: 'baseline', graph: graph('g1', 'default') }]) + h.setGraph(graph('g2')) + h.rebuilt('a', 'r2') + expect(await take(owner, 2)).toEqual([{ type: 'graph', graph: graph('g2') }, { type: 'rebuilt', id: 'a', rev: 'r2' }]) + expect(await take(viewer, 2)).toEqual([{ type: 'graph', graph: graph('g2', 'default') }, { type: 'rebuilt', id: 'a', rev: 'r2' }]) + controller.abort() +}) diff --git a/packages/client/hmr/tests/transport.client.spec.ts b/packages/client/hmr/tests/transport.client.spec.ts index 40c78b86bf..7fbbb11d5c 100644 --- a/packages/client/hmr/tests/transport.client.spec.ts +++ b/packages/client/hmr/tests/transport.client.spec.ts @@ -1,127 +1,140 @@ -/** Web transport delegates module and entry changes to the page-owned controller. */ +/** The Web transport follows the plugin-events Remote stream into the page's entry controller. */ import { Context } from '@deepseek-ai/cordis' -import type { ClientModuleLoader } from '@deepseek-ai/dsh-client-modules/client' import { afterEach, expect, it, vi } from 'vitest' import { apply, inject } from '../src/client/index.ts' +import type { PluginsEventFrame } from '../src/types.ts' -afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks() }) +afterEach(() => { vi.restoreAllMocks() }) -/** Provide the module system face this transport drives: its entry controller's sync and reload. */ -function provideModules(ctx: Context, sync: (...args: never[]) => unknown, reload: (...args: never[]) => unknown): void { - ctx.provide('modules', { entries: { sync, reload } } as unknown as ClientModuleLoader) +async function collect(items: AsyncIterable): Promise { + const out: unknown[] = [] + for await (const item of items) out.push(item) + return out } -it('forwards full graphs and rebuilt frames, contains wire errors and closes its EventSource', async () => { - const ctx = new Context() - const sync = vi.fn(async () => {}) - const reload = vi.fn(async () => {}) - provideModules(ctx, sync, reload) - const warnings = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {}) - const errors = vi.spyOn(ctx.logger, 'error').mockImplementation(() => {}) - let receive!: (event: { data: string }) => void - const close = vi.fn() - vi.stubGlobal('EventSource', class { - close = close - addEventListener(_name: string, listener: typeof receive) { receive = listener } - }) - const fiber = ctx.plugin({ apply, inject }) - try { - await fiber.await() - const graph = { rev: 'r', entries: [], batches: [] } - receive({ data: JSON.stringify({ type: 'graph', graph }) }) - receive({ data: JSON.stringify({ type: 'rebuilt', id: 'a', rev: 'r1' }) }) - await vi.waitFor(() => { expect(sync).toHaveBeenCalledWith(graph) }) - expect(reload).toHaveBeenCalledWith('a', 'r1') - receive({ data: '{' }) - receive({ data: JSON.stringify({ type: 'graph', graph: null }) }) - receive({ data: JSON.stringify({ type: 'future' }) }) - expect(warnings).toHaveBeenCalledTimes(2) - sync.mockRejectedValueOnce(new Error('invalid graph')) - receive({ data: JSON.stringify({ type: 'graph', graph: {} }) }) - await vi.waitFor(() => { expect(errors).toHaveBeenCalledWith(expect.objectContaining({ message: 'invalid graph' })) }) - } finally { - await fiber.dispose() - await ctx.fiber.dispose() +/** A pushable stand-in for one logical Remote stream: items carry a generation number and an accept callback. */ +function fakeStream() { + const queue: { generation: number; value: PluginsEventFrame }[] = [] + let wake: (() => void) | undefined + let ended = false + const disposed = vi.fn() + const stream = { + async *[Symbol.asyncIterator]() { + while (!ended) { + const item = queue.shift() + if (item === undefined) { + await new Promise((resolve) => { wake = resolve }) + continue + } + yield { ...item, signal: new AbortController().signal, accept: () => {} } + } + }, + restart: () => {}, + dispose: async () => { disposed(); ended = true; wake?.() }, } - expect(close).toHaveBeenCalledOnce() -}) - -it('reads the event stream through the page transport when the shell provides one', async () => { - const ctx = new Context() - const sync = vi.fn(async () => {}) - const reload = vi.fn(async () => {}) - provideModules(ctx, sync, reload) - const graph = { rev: 'r', entries: [], batches: [] } - const encoder = new TextEncoder() - let signal: AbortSignal | undefined - const fetch = vi.fn((_input: string, init: RequestInit) => { - signal = init.signal ?? undefined - const body = new ReadableStream({ - start(controller) { - controller.enqueue(encoder.encode(': connected\n\n')) - controller.enqueue(encoder.encode(`data: ${JSON.stringify({ type: 'graph', graph })}\n\n`)) - controller.enqueue(encoder.encode(`data: ${JSON.stringify({ type: 'rebuilt', id: 'a', rev: 'r1' })}\n\n`)) - // The tunnel ends the body when the caller aborts. - init.signal?.addEventListener('abort', () => { controller.close() }) - }, - }) - return Promise.resolve(new Response(body, { status: 200, headers: { 'content-type': 'text/event-stream' } })) - }) - vi.stubGlobal('__DSH_TRANSPORT__', { fetch }) - const eventSource = vi.fn() - vi.stubGlobal('EventSource', eventSource) - const errors = vi.spyOn(ctx.logger, 'error').mockImplementation(() => {}) - const fiber = ctx.plugin({ apply, inject }) - try { - await fiber.await() - await vi.waitFor(() => { expect(sync).toHaveBeenCalledWith(graph) }) - await vi.waitFor(() => { expect(reload).toHaveBeenCalledWith('a', 'r1') }) - expect(fetch).toHaveBeenCalledWith('plugins/events', expect.objectContaining({ method: 'GET' })) - expect(eventSource).not.toHaveBeenCalled() - expect(signal?.aborted).toBe(false) - } finally { - await fiber.dispose() - await ctx.fiber.dispose() + return { + stream, + disposed, + push(generation: number, value: PluginsEventFrame) { queue.push({ generation, value }); wake?.() }, } - expect(signal?.aborted).toBe(true) - await Promise.resolve() - expect(errors).not.toHaveBeenCalled() -}) +} -it.each([ - ['a refused stream', () => new Response('missing', { status: 404 }), 'plugins/events answered 404'], - ['a stream without a body', () => new Response(null, { status: 200 }), 'plugins/events answered 200'], - ['a stream that ends while the plugin runs', () => new Response(': connected\n\n', { status: 200 }), 'plugins/events closed'], -])('reports %s on the page transport', async (_label, respond, message) => { +function harness() { const ctx = new Context() - provideModules(ctx, vi.fn(), vi.fn()) - const errors = vi.spyOn(ctx.logger, 'error').mockImplementation(() => {}) - vi.stubGlobal('__DSH_TRANSPORT__', { fetch: () => Promise.resolve(respond()) }) - const fiber = ctx.plugin({ apply, inject }) - try { - await fiber.await() - await vi.waitFor(() => { - expect(errors).toHaveBeenCalledWith(expect.objectContaining({ message: expect.stringContaining(message) as string })) - }) - } finally { - await fiber.dispose() - await ctx.fiber.dispose() - } -}) + const sync = vi.fn(async (_graph: unknown) => {}) + const reload = vi.fn(async (_id: string, _rev: string) => {}) + ctx.provide('modules', { entries: { sync, reload } } as never) + const stream = fakeStream() + const unmount = vi.fn(async () => {}) + const opened: { name: string; open: (signal: AbortSignal) => AsyncIterable; ended: () => Error & { code?: string } }[] = [] + const follow = vi.fn(async function *(_signal: AbortSignal): AsyncIterable { yield 'frame' }) + const pluginEvents = { follow } + ctx.provide('remote', { + $mount: vi.fn(async () => unmount), + $stream: (streamOptions: (typeof opened)[number]) => { opened.push(streamOptions); return stream.stream }, + pluginEvents, + } as never) + const revoke: (() => unknown)[] = [] + ctx.provide('remoteAccess', { + whenAccess: (_action: string, callback: () => () => unknown) => { revoke.push(callback()); return () => {} }, + } as never) + // `$mount` provides the generated namespace as its own service under `remote.pluginEvents`. + const provideNamespace = (): void => { ctx.provide('remote.pluginEvents', pluginEvents as never) } + return { ctx, sync, reload, stream, unmount, opened, follow, revoke, provideNamespace } +} -it('stays silent when disposal aborts a page-transport request in flight', async () => { - const ctx = new Context() - provideModules(ctx, vi.fn(), vi.fn()) - const errors = vi.spyOn(ctx.logger, 'error').mockImplementation(() => {}) - const fetch = vi.fn((_input: string, init: RequestInit) => new Promise((_resolve, reject) => { - init.signal?.addEventListener('abort', () => { reject(new DOMException('aborted', 'AbortError')) }) - })) - vi.stubGlobal('__DSH_TRANSPORT__', { fetch }) - const fiber = ctx.plugin({ apply, inject }) +const baseline: PluginsEventFrame = { type: 'baseline', graph: { rev: 'g1', entries: [], batches: [] } } + +it('forwards the baseline and increments to the entry controller while access allows the stream, and unmounts its namespace', async () => { + const h = harness() + h.provideNamespace() + const fiber = h.ctx.plugin({ apply, inject }) await fiber.await() - await vi.waitFor(() => { expect(fetch).toHaveBeenCalledOnce() }) + const options = h.opened[0]! + expect(options.name).toBe('Plugin events') + const signal = new AbortController().signal + expect(await collect(options.open(signal))).toEqual(['frame']) + expect(h.follow).toHaveBeenCalledWith(signal) + // An endpoint the Host withdrew while reloading reconnects; any other failure stays as it is. + for (const code of ['gateway/invocation-unavailable', 'gateway/service-unavailable']) { + h.follow.mockImplementationOnce(() => { throw Object.assign(new Error('withdrawn'), { code }) }) + await expect(collect(options.open(signal))).rejects.toMatchObject({ code: 'gateway/carrier-lost' }) + } + const denied = Object.assign(new Error('denied'), { code: 'gateway/forbidden' }) + h.follow.mockImplementationOnce(() => { throw denied }) + await expect(collect(options.open(signal))).rejects.toBe(denied) + const plain = new Error('plain') + h.follow.mockImplementationOnce(() => { throw plain }) + await expect(collect(options.open(signal))).rejects.toBe(plain) + // A normal generation end reconnects rather than ending the logical stream. + expect(options.ended().code).toBe('gateway/carrier-lost') + h.stream.push(1, baseline) + h.stream.push(1, { type: 'graph', graph: { rev: 'g2', entries: [], batches: [] } }) + h.stream.push(1, { type: 'rebuilt', id: 'a', rev: 'r2' }) + await vi.waitFor(() => { expect(h.reload).toHaveBeenCalledWith('a', 'r2') }) + expect(h.sync.mock.calls.map(([graph]) => (graph as { rev: string }).rev)).toEqual(['g1', 'g2']) + await h.revoke[0]!() + expect(h.stream.disposed).toHaveBeenCalledOnce() await fiber.dispose() - await ctx.fiber.dispose() - await Promise.resolve() - expect(errors).not.toHaveBeenCalled() + expect(h.unmount).toHaveBeenCalledOnce() + await h.ctx.fiber.dispose() +}) + +it('reports controller failures, including a synchronous parse failure, and ignores unknown increments', async () => { + const h = harness() + const errors = vi.spyOn(h.ctx.logger, 'error').mockImplementation(() => {}) + h.sync.mockImplementationOnce(() => { throw new Error('bad graph') }) + h.reload.mockRejectedValueOnce(new Error('bad reload')) + h.provideNamespace() + const fiber = h.ctx.plugin({ apply, inject }) + await fiber.await() + h.stream.push(1, baseline) + h.stream.push(1, { type: 'future' } as never) + h.stream.push(1, { type: 'rebuilt', id: 'a', rev: 'r2' }) + await vi.waitFor(() => { expect(errors).toHaveBeenCalledTimes(2) }) + expect(errors.mock.calls.map(([error]) => (error as Error).message)).toEqual(['bad graph', 'bad reload']) + await fiber.dispose() + await h.ctx.fiber.dispose() +}) + +it('fails loudly when the mounted namespace service is missing', async () => { + const h = harness() + const errors = vi.spyOn(h.ctx.logger, 'error').mockImplementation(() => {}) + const fiber = h.ctx.plugin({ apply, inject }) + await expect(fiber.await()).rejects.toThrow('the mounted pluginEvents namespace is not registered') + errors.mockRestore() + await h.ctx.fiber.dispose() +}) + +it('logs a terminal stream failure', async () => { + const h = harness() + h.provideNamespace() + const errors = vi.spyOn(h.ctx.logger, 'error').mockImplementation(() => {}) + const fiber = h.ctx.plugin({ apply, inject }) + await fiber.await() + h.stream.push(1, { type: 'graph', graph: { rev: 'g', entries: [], batches: [] } }) + await vi.waitFor(() => { expect(errors).toHaveBeenCalledOnce() }) + expect(errors.mock.calls[0]![0]).toContain('plugin events stopped') + await fiber.dispose() + await h.ctx.fiber.dispose() }) diff --git a/packages/client/hmr/tsconfig.client.json b/packages/client/hmr/tsconfig.client.json new file mode 100644 index 0000000000..2bc09cb73e --- /dev/null +++ b/packages/client/hmr/tsconfig.client.json @@ -0,0 +1,26 @@ +{ + "extends": "../../../tsconfig.base.client.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types", + "tsBuildInfoFile": "lib/tsconfig.client.tsbuildinfo" + }, + "include": [ + "src/client", + "src/types.ts" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../api/gateway/tsconfig.client.json" + }, + { + "path": "../../api/remote-access/tsconfig.client.json" + }, + { + "path": "../modules" + } + ] +} diff --git a/packages/client/hmr/tsconfig.host.json b/packages/client/hmr/tsconfig.host.json new file mode 100644 index 0000000000..b502ad0868 --- /dev/null +++ b/packages/client/hmr/tsconfig.host.json @@ -0,0 +1,30 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types", + "tsBuildInfoFile": "lib/tsconfig.host.tsbuildinfo" + }, + "files": [ + "src/index.ts", + "src/types.ts", + "src/plugin-events.ts" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../modules" + }, + { + "path": "../../typert/protocol" + }, + { + "path": "../../util/deque" + } + ] +} diff --git a/packages/client/hmr/tsconfig.json b/packages/client/hmr/tsconfig.json index 00226929f0..2eca820546 100644 --- a/packages/client/hmr/tsconfig.json +++ b/packages/client/hmr/tsconfig.json @@ -1,35 +1,11 @@ { - "extends": "../../../tsconfig.base.json", - "compilerOptions": { - "rootDir": "src", - "outDir": "lib/types", - "lib": [ - "ES2024", - "DOM", - "DOM.Iterable" - ], - "types": [ - "node" - ] - }, - "include": [ - "src" - ], + "files": [], "references": [ { - "path": "../../../vendor/cordis" + "path": "./tsconfig.host.json" }, { - "path": "../../../vendor/loader" - }, - { - "path": "../modules" - }, - { - "path": "../../host/webserver" - }, - { - "path": "../../../vendor/schemastery" + "path": "./tsconfig.client.json" } ] } diff --git a/packages/client/hmr/tsdown.config.ts b/packages/client/hmr/tsdown.config.ts index 7aa03cebc1..620261533c 100644 --- a/packages/client/hmr/tsdown.config.ts +++ b/packages/client/hmr/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle(import.meta.dirname, ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js'], { hostPhase: true }) diff --git a/packages/client/modules/README.i18n.yaml b/packages/client/modules/README.i18n.yaml index f7ba81c650..0a0c62f370 100644 --- a/packages/client/modules/README.i18n.yaml +++ b/packages/client/modules/README.i18n.yaml @@ -27,8 +27,11 @@ en: 1383d68472b3c057 zh: 94dd7d9abbdbccf3 /deepseek-ai-dsh-client-modules/use-this-package/live-plugin-composition: - en: 4487b06ddced3b71 - zh: 26d0181fcf0229ca + en: 09ed5277078f44ee + zh: 3643210476149b2a +/deepseek-ai-dsh-client-modules/use-this-package/synced-plugin-configuration: + en: ef9d9ee6fe9b7577 + zh: cf09d615cb09df90 /deepseek-ai-dsh-client-modules/use-this-package/host-release-changes: en: 5c0aa6f1d8df8e1c zh: 34005131c9bdce3b @@ -60,8 +63,8 @@ en: a0d8dbb15e079ec0 zh: 7d215cb85fa8b2c7 /deepseek-ai-dsh-client-modules/understand-the-implementation/source-map: - en: ece84808fa9f61f8 - zh: 95a65a7adfca9146 + en: fcd79e193d5f2857 + zh: 1a7a9f67d7998561 /deepseek-ai-dsh-client-modules/further-exploration: en: 7e5b283efe4f1d16 zh: 79472b64a0d759fe @@ -72,8 +75,8 @@ en: ca75c51c89c2c9b0 zh: de54f3467ef3b9be /deepseek-ai-dsh-client-modules/known-limitations-and-deferred-work: - en: 97127ddc35daf6d4 - zh: 1417b06046b01067 + en: a33318c5e4558b13 + zh: 438988c0c6c49e2e /deepseek-ai-dsh-client-modules/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/client/modules/README.md b/packages/client/modules/README.md index 78a7dad1e0..364f0cc3bf 100644 --- a/packages/client/modules/README.md +++ b/packages/client/modules/README.md @@ -46,6 +46,13 @@ The application combo scripts carry only each plugin's `client.js` entry and reg An open Web page follows the Host's complete module graph through the HMR transport. Enabling an ordinary plugin adds its Loader entry; disabling it removes the entry and waits for its asynchronous effects before evicting unused modules and styles. Re-enabling loads one instance with its styles. Other Loader contributors and shared modules still needed by active entries remain loaded. The Plugins page shows page-local synchronization failures and offers retry without changing Host enablement. + +### Synced plugin configuration + +A plugin's top-level `.volatile()` Config fields reach its browser face. The package puts its Config interface in `src/types.ts` for both faces and keeps the only Schemastery schema on its Host face; ordinary fields and every `role('secret')` position, including positions inside a volatile object, dictionary, or array, stay on the Host. Each graph row carries the values in `config`, so they arrive with the boot graph and with every later graph. Only the owner's page receives the 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, and a row whose schema rejects an empty Config carries no values there. + +The browser face exports no `Config`; its `apply(ctx, config: SyncedConfig)` receives one `SyncedConfigRef` per field, both from the types-only package [`@deepseek-ai/dsh-client-config/types`](../config/README.md). `config.field.get()` reads the current frozen value at operation time, as on the Host. A component reads it through a hook: the plugin injects the reference in a slot `inject` `hooks` compartment, such as `hooks: { fontSize: config.fontSize }`, and the component calls `useFontSize(value => value)`. Every field may read `undefined`, so the plugin handles the absent value at each read; a secret field is one case, as the Host never sends it. Changes compare each field as JSON; every changed field is set before any subscriber runs, and the plugin is never remounted. As each Host activation resolves its own volatile references, each plugin activation receives its own Config object holding the latest values; once its teardown begins (code replacement, row removal, or an unload after a required service is withdrawn) it receives no further values. A plugin without synced fields receives an empty object. `ctx.config.resolveConfigByPackage(packageName)` returns the read-only object of another package's current activation, or `undefined` while none runs. On the Host the graph frame carrying new values is queued before the plugin's own `loader/volatile-update` listeners run; this orders the mechanism only, and plugins must not rely on the browser receiving configuration before their other data. A Client face that exports its own `Config` schema keeps ordinary Cordis configuration and fails to activate when its row also carries synced values. + ### Host release changes @@ -107,7 +114,10 @@ The host contributes structured index rows that inject, into ``: the `wind | [`src/assets.ts`](src/assets.ts) | Package-asset media types, export, content revision, revisioned file name, and browser reference shared by the build preset, the asset route, and gates | | [`src/client/index.ts`](src/client/index.ts) | Browser half: bootstrap export, `ctx.modules` enrollment | | [`src/client/system.ts`](src/client/system.ts) | `ClientModuleSystem`: load/materialize/invalidate machinery | -| [`src/client/entries.ts`](src/client/entries.ts) | Page entry reconciliation, retries and code replacement | +| [`src/client/entries.ts`](src/client/entries.ts) | Page entry reconciliation, retries, code replacement, and synced Config delivery | +| [`src/client/synced-config.ts`](src/client/synced-config.ts) | The `SyncedConfigRef` implementation and the per-package synced Config object | +| [`src/config-projection.ts`](src/config-projection.ts) | Host projection of volatile Config fields with secrets removed | +| [`src/config-sync.ts`](src/config-sync.ts) | Host publication of each graph row's synced values and their `loader/volatile-update` watches | | [`src/client/entry-lifecycle.ts`](src/client/entry-lifecycle.ts) | Loader fiber teardown through the registry | | [`src/client/manifest.ts`](src/client/manifest.ts) | Wire types, boot-manifest parsing, and the `dsh.client` declaration parser | @@ -146,7 +156,7 @@ These limits define what the module system does not do. They are current package - **Metadata-based revisions** — revisions identify filesystem generations, not content equality. Metadata-only changes can reload a plugin; changes invisible in mtime, ctime, and size cannot be distinguished. - **Flat module graph by design** — every bundle is one module node whose edges point only at table leaves; the interface (`loadCache`/`edges`/`invalidate`) already supports a general module graph, so the externalization granularity can change without an interface change. -- **Host release detection rides the graph stream** — a page learns another Host release only from a graph frame. When a restarting Host answers `/plugins/events` with a non-200 status before registering the route, the browser closes that stream for good, and the page neither updates plugins nor detects a release change until it reloads. +- **Host release detection rides the graph stream** — a page learns another Host release only from a graph frame of the [plugin-events stream](../hmr/README.md). While that stream cannot run, for example after a terminal stream failure, the page neither updates plugins nor detects a release change until it reloads. - **Source launch has no build step for the Host half** — a Host started from TypeScript source reads the commit that `pnpm run dev:web` places in its environment; a source launch without it publishes the version alone. - **Bootstrap and code replacement limits** — the page retains its modules bootstrap and static platform identities. Removing or replacing the bootstrap requires a page reload; live replacement requests report a page-local error while retaining its fiber and exports; replacing package code and all existing consumers is outside ordinary enable/disable synchronization. - **Lazy delivery retains requested bodies** — the Host holds each bundle and lazy response plan; a script or map body remains cached after its first `GET`, and HMR additionally retains one prior startup generation. Memory grows only for response bodies that clients request while preserving one-generation race tolerance. diff --git a/packages/client/modules/README.zh.md b/packages/client/modules/README.zh.md index 9a25d0372c..df2bef5b73 100644 --- a/packages/client/modules/README.zh.md +++ b/packages/client/modules/README.zh.md @@ -46,6 +46,13 @@ application combo 脚本只携带每个插件的 `client.js` 入口,并在启 已打开的 Web 页面通过 HMR 传输跟随 Host 的完整模块图。启用普通插件会添加其 Loader 条目;停用会移除条目,并在其异步 effect 完成清理后回收未使用的模块与样式。再次启用会加载一个带样式的实例。其他 Loader 贡献方的条目及活动条目仍需使用的共享模块会保留。插件页面显示当前页面的同步失败,并提供不改变 Host 启用状态的重试。 + +### 同步插件配置 + +插件 Config 顶层的 `.volatile()` 字段会到达其浏览器面。包把 Config 接口放在 `src/types.ts` 供两个面共用,唯一的 Schemastery schema 只放在 Host 面;普通字段和所有 `role('secret')` 位置(包括 volatile 对象、字典、数组内部的位置)留在 Host。每个图行在 `config` 中携带这些值,因此它们随启动图和之后的每张图一起到达。只有 owner 的页面收到实际配置的值;其他所有 Peer(例如 LiveShare 查看端)在启动图和每个插件事件帧中收到各插件 schema 对空 Config 解析出的值,schema 拒绝空 Config 的行在这类页面上不带值。 + +浏览器面不导出 `Config`;它的 `apply(ctx, config: SyncedConfig)` 为每个字段收到一个 `SyncedConfigRef`,二者都来自只放类型的包 [`@deepseek-ai/dsh-client-config/types`](../config/README.zh.md)。`config.field.get()` 在执行操作时读取当前冻结值,写法与 Host 相同。组件通过 hook 读取:插件在 slot `inject` 的 `hooks` 中注入引用,例如 `hooks: { fontSize: config.fontSize }`,组件调用 `useFontSize(value => value)`。每个字段都可能读到 `undefined`,插件需在每次读取时处理缺值;密钥字段是其中一种情况,因为 Host 从不下发它。变化按字段做 JSON 比较,所有变化字段都设置完后才通知订阅者,插件从不重新挂载。与 Host 每次激活重新解析 volatile 引用一样,插件每次激活都得到一个持有最新值的新 Config 对象;该激活开始拆除后(代码替换、行移除,或必需服务撤回后的卸载)不再收到新值。没有同步字段的插件收到一个空对象。`ctx.config.resolveConfigByPackage(packageName)` 返回另一个包当前激活的只读对象,没有运行中的激活时返回 `undefined`。Host 上,携带新值的图帧在插件自己的 `loader/volatile-update` 监听执行之前入队;这只在机制上排序,插件不得依赖浏览器先收到配置、后收到其他数据。导出自身 `Config` schema 的 Client 面保持 Cordis 原有配置解析;其行若同时带同步值,激活失败。 + ### Host release 变化 @@ -107,7 +114,10 @@ bundle 路由随注入的 `webServer` 生命周期注册:服务就绪时注册 | [`src/assets.ts`](src/assets.ts) | 包资源的媒体类型、导出、内容 revision、带 revision 的文件名与浏览器引用,由构建预设、资源路由和门禁共用 | | [`src/client/index.ts`](src/client/index.ts) | 浏览器半侧:bootstrap 导出、`ctx.modules` 登记 | | [`src/client/system.ts`](src/client/system.ts) | `ClientModuleSystem`:加载/物化/失效机制 | -| [`src/client/entries.ts`](src/client/entries.ts) | 页面条目对账、重试与代码替换 | +| [`src/client/entries.ts`](src/client/entries.ts) | 页面条目对账、重试、代码替换与同步 Config 交付 | +| [`src/client/synced-config.ts`](src/client/synced-config.ts) | `SyncedConfigRef` 的实现与每个包的同步 Config 对象 | +| [`src/config-projection.ts`](src/config-projection.ts) | Host 侧投影 volatile Config 字段并剔除密钥 | +| [`src/config-sync.ts`](src/config-sync.ts) | Host 侧发布每个图行的同步值,并监听其 `loader/volatile-update` | | [`src/client/entry-lifecycle.ts`](src/client/entry-lifecycle.ts) | 通过注册表清理 Loader fiber | | [`src/client/manifest.ts`](src/client/manifest.ts) | 协议类型、启动清单解析与 `dsh.client` 声明解析器 | @@ -146,7 +156,7 @@ bundle 路由随注入的 `webServer` 生命周期注册:服务就绪时注册 - **基于元数据的 revision**——revision 标识文件系统代际,而非内容相等性。仅元数据变化也可能重载插件;mtime、ctime 和大小都无法反映的变化无法区分。 - **有意采用扁平模块图**——每个 bundle 是一个模块节点,其边只指向表中的叶节点;接口(`loadCache`/`edges`/`invalidate`)已经支持通用模块图,因此可以改变 externalization 粒度而不更改接口。 -- **Host release 检测依赖图事件流**——页面只能从图帧得知 Host 换了 release。重启中的 Host 若在注册路由之前对 `/plugins/events` 返回非 200 状态,浏览器会永久关闭该事件流,页面在刷新前既不更新插件,也检测不到 release 变化。 +- **Host release 检测依赖图事件流**——页面只能从[插件事件流](../hmr/README.zh.md)的图帧得知 Host 换了 release。该流无法运行时(例如流以终止性错误结束后),页面在刷新前既不更新插件,也检测不到 release 变化。 - **源码启动时 Host 半侧没有构建步骤**——从 TypeScript 源码启动的 Host 读取 `pnpm run dev:web` 放入其环境的 commit;没有该值的源码启动只发布版本号。 - **Bootstrap 与代码替换限制**——页面保留 modules bootstrap 和静态平台模块的身份。移除或替换 bootstrap 需要刷新页面;动态替换请求会报告页面本地错误,并保留其 fiber 与导出;替换包代码及其所有现有消费者不属于普通启停同步。 - **惰性提供会保留已请求的 body**——Host 在内存中保留每个 bundle 与惰性响应计划;脚本或 map body 在首次 `GET` 后保留缓存,HMR 还会保留上一代启动响应。内存仅随客户端实际请求的响应 body 增长,同时保留一代竞态容忍。 diff --git a/packages/client/modules/package.json b/packages/client/modules/package.json index 218305021b..9d0fb61a44 100644 --- a/packages/client/modules/package.json +++ b/packages/client/modules/package.json @@ -18,6 +18,9 @@ "types": "./lib/types/index.d.ts", "default": "./lib/index.js" }, + "./types": { + "types": "./lib/types/types.d.ts" + }, "./client": { "types": "./lib/types/client/index.d.ts", "default": "./lib/client.js" @@ -44,7 +47,11 @@ "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-package-manifest": "workspace:*", "@deepseek-ai/dsh-client-store": "workspace:*", - "@deepseek-ai/dsh-client-script-realm": "workspace:*" + "@deepseek-ai/dsh-client-script-realm": "workspace:*", + "@deepseek-ai/schemastery": "workspace:~", + "@deepseek-ai/dsh-util-values": "workspace:*", + "@deepseek-ai/dsh-client-config": "workspace:*", + "@deepseek-ai/dsh-typert-protocol": "workspace:*" }, "files": [ "locale/*.json", diff --git a/packages/client/modules/src/client/entries.ts b/packages/client/modules/src/client/entries.ts index f2f27d1f32..087632acf1 100644 --- a/packages/client/modules/src/client/entries.ts +++ b/packages/client/modules/src/client/entries.ts @@ -7,6 +7,7 @@ import type { BootManifest, ClientModuleLoader } from './manifest.ts' import { ReleaseChangeGate, type ClientReleaseChange } from './release-change.ts' import { notifySubscribers } from './notify.ts' import { tearDownEntryFiber } from './entry-lifecycle.ts' +import { SyncedConfigEntry } from './synced-config.ts' /** Page-local failures do not change the Host's bundle enablement. */ export interface ClientEntryState { @@ -51,6 +52,8 @@ export class ClientEntries { /** Admits only Host graphs of the page's boot release. */ private readonly release: ReleaseChangeGate private readonly managed = new Map() + /** Latest synced values per package that has appeared in the graph, and the Config object of its current activation. */ + private readonly synced = new Map() private readonly revisions = new Map() private loader: Loader | undefined private queue: Promise = Promise.resolve() @@ -90,6 +93,29 @@ export class ClientEntries { if (this.loader !== undefined) throw new Error('client-modules: entries already started') this.loader = loader this.desired = manifest + this.applyConfig(manifest) + // Prepended so the Loader's interpolation runs inside this listener and cannot copy the returned object. + loader.ctx.on('internal/config', (fiber, next) => { + const config: unknown = next() + // As the Loader's own listener does, skip fibers that are not an entry's root plugin (a child plugin inherits + // its parent's entry) and keep their explicit config. + if (fiber.entry === undefined || fiber.parent.fiber.entry === fiber.entry) return config + const id = fiber.entry.options.name + const synced = this.synced.get(id) + if (synced === undefined) return config + // A Client face with its own schema keeps Cordis's ordinary configuration; it must not also receive synced values. + if (fiber.runtime?.Config === undefined) { + // Resolving a candidate for the running instance (as `fiber.update()` does) keeps its object, as the Host keeps + // an active instance's volatile references; only an activation receives a new one. + if (synced.config !== undefined && fiber.effectiveConfig === synced.config) return synced.config + const activation = synced.activate() + // However the instance unloads (replacement, removal, a withdrawn dependency), its object stops receiving values. + fiber.ctx.effect(() => () => { synced.release(activation) }, 'client-modules: synced configuration activation') + return activation + } + if (synced.empty) return config + throw new Error(`client-modules: the Client face of ${id} exports a Config schema; synced configuration requires the Host schema alone`) + }, { prepend: true }) loader.ctx.effect(() => () => { this.stopped = true this.generation++ @@ -116,6 +142,8 @@ export class ClientEntries { const manifest = parseBootManifest(graph) if (entryTargets(manifest) !== entryTargets(this.desired)) this.generation++ this.desired = manifest + // Configuration is not code: it applies at once, before queued entry work creates or replaces any entry. + if (this.loader !== undefined) this.applyConfig(manifest) const generation = this.generation return this.enqueue(() => this.reconcile(generation)) } @@ -159,6 +187,34 @@ export class ClientEntries { }, id) } + /** + * 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. + * @param packageName - graph row id. + * @returns the object, or undefined while no activation of the package is running. + */ + resolveConfigByPackage(packageName: string): object | undefined { + return this.synced.get(packageName)?.config + } + + /** An activation's teardown begins: like a Host fiber that is no longer active, it receives no later values. */ + private releaseConfig(id: string): void { + this.synced.get(id)?.release() + } + + /** + * Write each row's values into its package's current activation. A row absent from the graph keeps its values: its + * entry is being removed, and removal releases the activation without writing to it. + */ + private applyConfig(manifest: BootManifest): void { + for (const row of manifest.plugins) { + const values = row.config ?? {} + const synced = this.synced.get(row.id) + if (synced === undefined) this.synced.set(row.id, new SyncedConfigEntry(values)) + else synced.update(values) + } + } + private publish(snapshot: ClientEntryState): void { this.snapshot = snapshot notifySubscribers(this.listeners, 'synchronization') @@ -195,6 +251,7 @@ export class ClientEntries { this.index.invalidateForReplacement(id, rev) await this.modules.prefetch(id) if (!this.current(generation)) return + this.releaseConfig(id) await tearDownEntryFiber(entry) this.index.releaseReplaced(id) if (!this.current(generation)) return @@ -218,6 +275,7 @@ export class ClientEntries { for (const [id, entry] of this.managed) { if (wanted.has(id)) continue const fiber = entry.fiber + this.releaseConfig(id) loader.remove(entry.id) this.managed.delete(id) this.revisions.delete(id) diff --git a/packages/client/modules/src/client/index.ts b/packages/client/modules/src/client/index.ts index 8e4d023b2c..2a989e866a 100644 --- a/packages/client/modules/src/client/index.ts +++ b/packages/client/modules/src/client/index.ts @@ -14,6 +14,7 @@ import type { Context } from '@deepseek-ai/cordis' import type { Loader } from '@deepseek-ai/cordis-plugin-loader' import { ClientModuleSystem } from './system.ts' import { parseBootManifest } from './manifest.ts' +import type { SyncedConfig, SyncedConfigService } from '@deepseek-ai/dsh-client-config/types' import type { ClientBootstrapModule, ClientModuleCreateOptions, ClientModuleLoader, ClientModuleLoaderTarget, } from './manifest.ts' @@ -52,11 +53,11 @@ export function createClientModuleSystem( }) } -/** Required service: the Loader whose internal module system this plugin publishes. */ +/** Required service: the Loader whose internal module system and synced configuration this plugin publishes. */ export const inject = ['loader'] /** - * Enroll the kernel-built module system as `ctx.modules`. + * Enroll the kernel-built module system as `ctx.modules` and its synced configuration lookup as `ctx.config`. * @param ctx - client root context. */ export function apply(ctx: Context): void { @@ -66,4 +67,8 @@ export function apply(ctx: Context): void { throw new Error('client-modules: the Loader has no client module system') } ctx.reflect.provide('modules', modules) + const config: SyncedConfigService = { + resolveConfigByPackage: (packageName: string) => modules.entries.resolveConfigByPackage(packageName) as SyncedConfig | undefined, + } + ctx.reflect.provide('config', config) } diff --git a/packages/client/modules/src/client/manifest.ts b/packages/client/modules/src/client/manifest.ts index c9dd84d1c2..4bcc7d84ca 100644 --- a/packages/client/modules/src/client/manifest.ts +++ b/packages/client/modules/src/client/manifest.ts @@ -28,6 +28,7 @@ * composes the wire. */ +import type { SyncedConfigValues } from '@deepseek-ai/dsh-client-config/types' import type {} from '@deepseek-ai/cordis' import type { DshClientManifest, ClientModuleMetaFactory, @@ -69,6 +70,8 @@ export 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 } /** Initial scheduling phase for one revisioned combo script. */ @@ -134,6 +137,8 @@ export interface BootPluginRow { inject: string[] /** Stage-one prefetch tier (false when the wire omits it). */ immediately: boolean + /** Synced Config values; undefined when the row has none. */ + config?: SyncedConfigValues } /** The parsed boot manifest: one wire, two consumer views. */ @@ -275,10 +280,14 @@ export function parseBootManifest(wire: unknown): BootManifest { inject: inject === undefined ? [] : [...inject], external: external === undefined ? [] : [...external], }) + if (row.config !== undefined && (typeof row.config !== 'object' || row.config === null || Array.isArray(row.config))) { + throw new Error(`client-modules: boot manifest entry ${where} config must be an object`) + } plugins.push({ id: row.id, inject: inject === undefined ? [] : [...inject], immediately: row.immediately === true, + ...(row.config === undefined ? {} : { config: row.config as SyncedConfigValues }), }) } diff --git a/packages/client/modules/src/client/synced-config.ts b/packages/client/modules/src/client/synced-config.ts new file mode 100644 index 0000000000..b77e48b3ff --- /dev/null +++ b/packages/client/modules/src/client/synced-config.ts @@ -0,0 +1,160 @@ +/** + * Browser-synced plugin configuration. Each plugin activation receives its own Config object of + * `SyncedConfigRef`s, as a Host activation resolves its own volatile references; only the page's entry + * controller writes values, and it stops writing to an activation once that activation's teardown begins. + */ +import type { VolatileSnapshot } from '@deepseek-ai/cordis' +import type { SyncedConfigRef, SyncedConfigValues } from '@deepseek-ai/dsh-client-config/types' +import { notifySubscribers } from './notify.ts' + +/** Controller-side access to one reference: set without notifying, then notify once every field is set. */ +interface RefPort { + set(value: unknown): void + notify(): void +} + +/** The page's implementation of one {@link SyncedConfigRef}; only the activation that created it writes, through its port. */ +class SyncedConfigReference implements SyncedConfigRef { + #value: VolatileSnapshot + readonly #listeners = new Set<() => void>() + + /** + * @param value - frozen initial value. + * @param attach - receives the controller's port; called once during construction. + */ + constructor(value: VolatileSnapshot, attach: (port: RefPort) => void) { + this.#value = value + attach({ + set: (next) => { this.#value = next as VolatileSnapshot }, + notify: () => { notifySubscribers(this.#listeners, 'synced configuration') }, + }) + } + + /** @returns the current frozen value; undefined when the Host sends none. */ + readonly get: () => VolatileSnapshot = () => this.#value + /** @returns the same value as {@link get}. */ + readonly getSnapshot: () => VolatileSnapshot = () => this.#value + /** + * Observe value changes; every changed field of one update is set before any subscriber runs. + * @param listener - called after each change. + * @returns the disposer. + */ + readonly subscribe: (listener: () => void) => () => void = (listener) => { + this.#listeners.add(listener) + return () => { this.#listeners.delete(listener) } + } +} + +/** Structural equality of JSON values; object key order does not matter. */ +function sameJson(left: unknown, right: unknown): boolean { + if (left === right) return true + if (typeof left !== 'object' || typeof right !== 'object' || left === null || right === null) return false + if (Array.isArray(left) !== Array.isArray(right)) return false + const leftKeys = Object.keys(left) + return leftKeys.length === Object.keys(right).length + && leftKeys.every(key => Object.hasOwn(right, key) && sameJson(Reflect.get(left, key), Reflect.get(right, key))) +} + +function freeze(value: unknown): unknown { + if (value !== null && typeof value === 'object') { + for (const child of Object.values(value)) freeze(child) + Object.freeze(value) + } + return value +} + +/** The Config object of one plugin activation. */ +class SyncedConfigActivation { + private values: SyncedConfigValues + private readonly ports = new Map() + private readonly refs = new Map>() + /** Read-only object whose properties create field references on first access. */ + readonly config: object + + constructor(values: SyncedConfigValues) { + this.values = values + // An extensible empty target keeps the Proxy invariants satisfied for fields that appear later. + this.config = new Proxy({}, { + set: () => false, + defineProperty: () => false, + deleteProperty: () => false, + get: (_target, property) => typeof property === 'string' ? this.ref(property) : undefined, + has: (_target, property) => typeof property === 'string' && Object.hasOwn(this.values, property), + ownKeys: () => Object.keys(this.values), + getOwnPropertyDescriptor: (_target, property) => typeof property === 'string' && Object.hasOwn(this.values, property) + ? { configurable: true, enumerable: true, value: this.ref(property) } + : undefined, + }) + } + + /** Set every changed field, then notify the changed fields' subscribers. */ + write(values: SyncedConfigValues): void { + const previous = this.values + const changed = [...new Set([...Object.keys(previous), ...Object.keys(values)])] + .filter(field => !sameJson(previous[field], values[field])) + if (changed.length === 0) return + this.values = values + const ports = changed.flatMap((field) => { + const port = this.ports.get(field) + return port === undefined ? [] : [{ port, value: values[field] }] + }) + for (const { port, value } of ports) port.set(value) + for (const { port } of ports) port.notify() + } + + private ref(field: string): SyncedConfigReference { + let ref = this.refs.get(field) + if (ref === undefined) { + ref = new SyncedConfigReference(this.values[field], (port) => { this.ports.set(field, port) }) + this.refs.set(field, ref) + } + return ref + } +} + +/** Latest synced values of one package and the Config object of its current plugin activation. */ +export class SyncedConfigEntry { + private values: SyncedConfigValues + private current: SyncedConfigActivation | undefined + + /** @param values - Host-validated values; they are frozen and not checked against any schema. */ + constructor(values: SyncedConfigValues) { + this.values = freeze(structuredClone(values)) as SyncedConfigValues + } + + /** Whether no field currently has a value. */ + get empty(): boolean { + return Object.keys(this.values).length === 0 + } + + /** The current activation's Config object; undefined between a teardown and the next activation. */ + get config(): object | undefined { + return this.current?.config + } + + /** + * Start an activation: a new Config object holding the latest values; the previous activation stops receiving writes. + * @returns the object to hand to the activation's `apply`. + */ + activate(): object { + this.current = new SyncedConfigActivation(this.values) + return this.current.config + } + + /** + * An activation's teardown has begun; later values wait for the next activation. + * @param config - the ending activation's object; omitted, the current activation ends. + */ + release(config?: object): void { + if (config === undefined || this.current?.config === config) this.current = undefined + } + + /** + * Replace the values; the current activation receives the changed fields, if one is running. + * @param values - the package's complete values; absent fields read undefined. + */ + update(values: SyncedConfigValues): void { + this.values = freeze(structuredClone(values)) as SyncedConfigValues + this.current?.write(this.values) + } +} diff --git a/packages/client/modules/src/config-projection.ts b/packages/client/modules/src/config-projection.ts new file mode 100644 index 0000000000..89f8d4aa5c --- /dev/null +++ b/packages/client/modules/src/config-projection.ts @@ -0,0 +1,120 @@ +/** + * Projection of one running plugin's Config onto the values the browser may receive: top-level volatile fields only, + * with every `role('secret')` position removed, including positions inside volatile objects, dictionaries, and arrays. + */ +import { isDeepStrictEqual } from 'node:util' +import type { Volatile } from '@deepseek-ai/cordis' +import type { JsonValue } from '@deepseek-ai/dsh-util-values' +import type { SyncedConfigValues } from '@deepseek-ai/dsh-client-config/types' + +/** Schemastery node fields the projection reads; a Schemastery schema satisfies it structurally. */ +export interface SchemaNode { + type: string + meta: { role?: unknown; volatile?: unknown } + dict?: Record + inner?: SchemaNode + list?: SchemaNode[] +} + +/** A volatile field of a parsed Config is a reference; detected structurally so this package needs no Cosmokit copy. */ +function isReference(value: unknown): value is Volatile { + return typeof value === 'object' && value !== null && typeof Reflect.get(value, 'get') === 'function' +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +/** + * Read a child field Schemastery always sets for the node types that use it. + * @param node - schema node. + * @param key - `dict` for objects, `inner` for dictionaries, arrays, and transforms, `list` for unions and intersections. + * @returns the field. + */ +function part(node: SchemaNode, key: K): NonNullable { + const value = node[key] + /* v8 ignore next -- Schemastery constructs every object, dict, array, transform, union, and intersect node with this field. */ + if (value === undefined) throw new TypeError(`client-modules: ${node.type} schema has no ${key}`) + return value +} + +/** Every union branch is applied, so a field any branch declares secret is removed. */ +function stripSecrets(node: SchemaNode, value: unknown): unknown { + if (value === undefined || node.meta.role === 'secret') return undefined + switch (node.type) { + case 'object': { + if (!isRecord(value)) return value + // As the settings redaction does, keys this branch does not declare stay, so union and intersection members do not + // drop each other's fields. + const dict = part(node, 'dict') + const undeclared = Object.entries(value).filter(([key]) => !(key in dict)) + return { ...Object.fromEntries(undeclared), ...collect(Object.entries(dict).map(([key, child]) => [key, child, value[key]])) } + } + case 'dict': { + const inner = part(node, 'inner') + return isRecord(value) ? collect(Object.entries(value).map(([key, entry]) => [key, inner, entry])) : value + } + case 'array': + // A secret array item is dropped from the list rather than replaced by a placeholder. + return Array.isArray(value) ? value.map(entry => stripSecrets(part(node, 'inner'), entry)).filter(entry => entry !== undefined) : value + case 'union': + case 'intersect': + return part(node, 'list').reduce((current, child) => stripSecrets(child, current), value) + case 'transform': + return stripSecrets(part(node, 'inner'), value) + default: + return value + } +} + +/** Rebuild an object from stripped properties, omitting those that strip to undefined. */ +function collect(properties: [string, SchemaNode, unknown][]): Record { + const rebuilt: Record = {} + for (const [key, child, entry] of properties) { + const stripped = stripSecrets(child, entry) + if (stripped !== undefined) rebuilt[key] = stripped + } + return rebuilt +} + +/** Top-level object fields of a Config schema; intersections contribute the fields of each object member. */ +function topFields(node: SchemaNode): [string, SchemaNode][] { + if (node.type === 'object') return Object.entries(part(node, 'dict')) + if (node.type === 'intersect') return part(node, 'list').flatMap(topFields) + return [] +} + +/** + * Whether a Config schema declares a top-level volatile field, the only fields synced to the browser. + * @param schema - the plugin's Host Config schema. + * @returns true when at least one top-level field is volatile. + */ +export function hasSyncedFields(schema: SchemaNode): boolean { + return topFields(schema).some(([, node]) => node.meta.volatile === true) +} + +/** + * Project a running plugin's effective Config onto its browser-synced values. + * @param schema - the plugin's Host Config schema. + * @param effective - the fiber's effective Config, whose volatile fields are references. + * @param id - package name, used in diagnostics. + * @returns the synced values, or undefined when the schema declares no top-level volatile field. + * @throws TypeError when a synced value is not lossless JSON. + */ +export function syncedValues(schema: SchemaNode, effective: unknown, id: string): SyncedConfigValues | undefined { + const fields = topFields(schema).filter(([, node]) => node.meta.volatile === true) + if (fields.length === 0) return undefined + const source = isRecord(effective) ? effective : {} + const values: Record = {} + for (const [key, node] of fields) { + const raw = source[key] + const stripped = stripSecrets(node, isReference(raw) ? raw.get() : raw) + if (stripped === undefined) continue + const json = JSON.parse(JSON.stringify(stripped)) as JsonValue + if (!isDeepStrictEqual(json, stripped)) { + throw new TypeError(`client-modules: ${id} Config field ${key} is not lossless JSON and cannot be synced to the browser`) + } + values[key] = json + } + return values +} diff --git a/packages/client/modules/src/config-sync.ts b/packages/client/modules/src/config-sync.ts new file mode 100644 index 0000000000..f21acc34f7 --- /dev/null +++ b/packages/client/modules/src/config-sync.ts @@ -0,0 +1,160 @@ +/** + * Host-side publication of browser-synced plugin configuration: each graph row carries the projected volatile values + * of its Loader entry's plugin, and a change of those values republishes the graph. + */ +import { isDeepStrictEqual } from 'node:util' +import { FiberState } from '@deepseek-ai/cordis' +import type { Context, Fiber } from '@deepseek-ai/cordis' +import type { Entry } from '@deepseek-ai/cordis-plugin-loader' +import type z from '@deepseek-ai/schemastery' +import type { SyncedConfigValues } from '@deepseek-ai/dsh-client-config/types' +import type { Principal } from '@deepseek-ai/dsh-typert-protocol' +import type { WebBootEntry, WebBootGraph } from './client/manifest.ts' +import { hasSyncedFields, syncedValues } from './config-projection.ts' + +/** Synced values per graph row, owned by the client module registry. */ +export class SyncedConfigPublisher { + /** Last published values per row; undefined for a plugin without top-level volatile fields. */ + private readonly values = new Map() + /** + * Values the row's schema resolves from an empty Config, served to every non-owner Peer; undefined when the schema + * declares no top-level volatile field or cannot resolve an empty Config. + */ + private readonly defaults = new Map() + /** Loader entry name per row of the last composed graph. */ + private rows = new Map() + /** Current root plugin fiber per Loader entry name; of entries sharing a name, the one seen last. */ + private readonly fibers = new Map() + /** `loader/volatile-update` listener disposer per Loader entry name. */ + private readonly watches = new Map void>() + + /** + * @param ctx - the registry's context; the publisher's listeners leave with it. + * @param entries - the Loader entries present when the registry starts. + * @param changed - recomposes and republishes the graph after a row's values change. + */ + constructor(private readonly ctx: Context, entries: Iterable, private readonly changed: () => void) { + for (const entry of entries) if (entry.fiber !== undefined) this.track(entry.options.name, entry.fiber.ctx.fiber) + // A new plugin instance (install, upgrade, code reload) is seen at creation, so the graph that announces its code + // already carries values its schema resolves; a status change re-reads values after a (re)start. + const seen = (fiber: Fiber): void => { + const entry = fiber.entry + // Only an entry's live root plugin, by the Loader's own test: a child plugin inherits its parent's entry, and a + // replaced instance (its uid cleared at disposal) may report its teardown after its successor exists. The + // successor is not yet `entry.fiber` here, because the Loader assigns that after construction returns. + if (entry === undefined || fiber.parent.fiber.entry === entry) return + const name = entry.options.name + if (fiber.uid === null) { + if (this.fibers.get(name) !== fiber) return + // The selected instance is gone; a live entry of the same name, sharing its source, supplies the values. + const live = [...ctx.loader.entries()] + .map(candidate => candidate.options.name === name ? candidate.fiber?.ctx.fiber : undefined) + .find(candidate => candidate !== undefined && candidate.uid !== null) + if (live === undefined) return + fiber = live + } + this.track(name, fiber) + this.republish(name) + } + ctx.on('internal/plugin', seen) + ctx.on('internal/status', seen) + ctx.effect(() => () => { + for (const dispose of this.watches.values()) dispose() + this.watches.clear() + }, 'client-modules: synced configuration watches') + } + + /** + * Attach current synced values to composed rows, and drop the values of rows that left the graph. + * @param entries - composed rows. + * @param records - the registry table, keyed by row id, naming the Loader entry that supplies each row. + * @returns the rows, each with its values when it has any. + */ + apply(entries: WebBootEntry[], records: ReadonlyMap): WebBootEntry[] { + this.rows = new Map([...records].map(([id, record]) => [id, record.loaderName])) + for (const id of this.values.keys()) if (!this.rows.has(id)) this.values.delete(id) + for (const id of this.defaults.keys()) if (!this.rows.has(id)) this.defaults.delete(id) + for (const [id, loaderName] of this.rows) this.refresh(id, loaderName) + return entries.map(({ config: _published, ...row }) => { + const config = this.values.get(row.id) + return config === undefined ? row : { ...row, config } + }) + } + + /** + * The graph one Peer receives, at first render and in every plugin-events frame. The owner receives the configured + * values; every other Peer receives each row's schema defaults instead, so the owner's values stay on the Host. + * @param graph - the composed graph. + * @param principal - the Peer's principal; undefined for the owner or an in-process caller. + * @returns the graph itself for the owner, otherwise a copy whose row values are the schema defaults. + */ + graphFor(graph: WebBootGraph, principal: Principal | undefined): WebBootGraph { + /* oxlint-disable typescript/no-unnecessary-condition -- other packages merge non-owner principal kinds into the map + this program sees with only the owner kind. */ + if (principal === undefined || principal.kind === 'owner') return graph + /* oxlint-enable typescript/no-unnecessary-condition */ + return { + ...graph, + entries: graph.entries.map(({ config: _config, ...row }) => { + const config = this.defaults.get(row.id) + return config === undefined ? row : { ...row, config } + }), + } + } + + private track(name: string, fiber: Fiber): void { + this.fibers.set(name, fiber) + // `loader/volatile-update` reaches only listeners on the updated fiber's own context, and a listener there lasts one + // activation, so each activation registers it again. Prepended: the graph frame carrying the new values is queued + // before the plugin's own listeners can push data that depends on them. + if (fiber.state !== FiberState.ACTIVE) return + this.watches.get(name)?.() + this.watches.set(name, fiber.ctx.on('loader/volatile-update', () => { this.republish(name) }, { prepend: true })) + } + + private republish(name: string): void { + let changed = false + for (const [id, loaderName] of this.rows) if (loaderName === name && this.refresh(id, loaderName)) changed = true + if (changed) this.changed() + } + + /** + * Recompute one row's values; equal values (deep equality) change nothing. + * @returns whether the row's values changed. + */ + private refresh(id: string, loaderName: string): boolean { + const fiber = this.fibers.get(loaderName) + /* v8 ignore next -- a table row comes from a Loader entry whose root fiber was tracked at startup or creation. */ + if (fiber === undefined) return false + const runtimeSchema = fiber.runtime?.Config + // A plugin without synced fields is never resolved here. + const schema = runtimeSchema !== undefined && 'toJSON' in runtimeSchema && hasSyncedFields(runtimeSchema as z) + ? runtimeSchema as z + : undefined + this.defaults.set(id, schema === undefined ? undefined : this.defaultValues(schema, fiber, id)) + let values: SyncedConfigValues | undefined + try { + // Before activation there is no effective Config; resolving the raw config with the instance's own schema gives + // the object activation will receive. + values = schema === undefined ? undefined : syncedValues(schema, fiber.effectiveConfig ?? fiber.resolveConfig(fiber.rawConfig), id) + } catch (error) { + // Containment: one plugin's unsyncable value keeps its last published values and leaves the other rows intact. + this.ctx.logger.error(error) + return false + } + if (isDeepStrictEqual(this.values.get(id), values)) return false + this.values.set(id, values) + return true + } + + private defaultValues(schema: z, fiber: Fiber, id: string): SyncedConfigValues | undefined { + try { + return syncedValues(schema, fiber.resolveConfig({}), id) + } catch (error) { + // A schema with a required field that has no default rejects an empty Config; such a row then carries no values + // for a non-owner Peer, and its plugin reads every field as absent there. + this.ctx.logger.debug(error) + return undefined + } + } +} diff --git a/packages/client/modules/src/index.ts b/packages/client/modules/src/index.ts index 4581333515..b3afc6fea5 100644 --- a/packages/client/modules/src/index.ts +++ b/packages/client/modules/src/index.ts @@ -39,8 +39,10 @@ import { Service } from '@deepseek-ai/cordis' import type { Context } from '@deepseek-ai/cordis' import type { Entry } from '@deepseek-ai/cordis-plugin-loader' import type { IndexInjection } from '@deepseek-ai/dsh-host-webserver' +import type { Principal } from '@deepseek-ai/dsh-typert-protocol' import { PACKAGE_ASSET_SEGMENT, packageAssetMediaType } from './assets.ts' import { exactPackageSpecifier, parseDshClient, stripClientSuffix } from './client/manifest.ts' +import { SyncedConfigPublisher } from './config-sync.ts' import type { WebBootBatch, WebBootBatchPhase, WebBootEntry, WebBootGraph, WebBootRelease } from './client/manifest.ts' export { stripClientSuffix } from './client/manifest.ts' @@ -662,6 +664,7 @@ export class ClientModuleRegistry extends Service { private previousBatchResponses = new Map() private flushQueued = false private composed: WebBootGraph + private readonly syncedConfig: SyncedConfigPublisher /** * Build the service: subscribe, seed, and run the activation flush. @@ -692,7 +695,14 @@ export class ClientModuleRegistry extends Service { // Activation pass: the initial scan IS the incremental path over the // current entries, flushed synchronously (nothing async between subscribe, // seed, and flush). - for (const entry of ctx.loader.entries()) this.dirty.add(entry.options.name) + const entries = [...ctx.loader.entries()] + for (const entry of entries) this.dirty.add(entry.options.name) + this.syncedConfig = new SyncedConfigPublisher(ctx, entries, () => { + // Only rows and rev change: the batch artifacts and the prior batch generation stay. + const rows = this.syncedConfig.apply(this.composed.entries, this.table) + this.composed = { ...this.composed, entries: rows, rev: shortHash(JSON.stringify({ entries: rows, batches: this.composed.batches })) } + this.notifyGraphChanged() + }) this.composed = this.compose() const failures: Error[] = [] this.flush(err => failures.push(err)) @@ -707,19 +717,29 @@ export class ClientModuleRegistry extends Service { ) } ctx.inject(['webServer'], registerWebCarrier) - ctx.on('webserver/index-inject', (table) => { - table.push(...bootInjections(this.composed)) + ctx.on('webserver/index-inject', (table, peer) => { + table.push(...bootInjections(this.graphFor(peer.principal))) }) } /** - * 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 { return this.composed } + /** + * 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 { + return this.syncedConfig.graphFor(this.composed, principal) + } + /** * Absolute path of an entry's client bundle. * @param id - entry id (package name). @@ -808,8 +828,10 @@ export class ClientModuleRegistry extends Service { } /** - * 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. */ @@ -868,10 +890,11 @@ export class ClientModuleRegistry extends Service { this.batchResponses = batchResponses this.responses = responses const batches = artifacts.map(artifact => artifact.descriptor) + const rows = this.syncedConfig.apply(entries, this.table) return { - rev: shortHash(JSON.stringify({ entries, batches })), + rev: shortHash(JSON.stringify({ entries: rows, batches })), release: this.release, - entries, + entries: rows, batches, } } @@ -1289,7 +1312,7 @@ export class ClientModuleRegistry extends Service { } } // Anything else under /plugins (including unadvertised combinations and - // /plugins/events when the HMR row is absent) is an unknown resource. + // an unknown path) is an unknown resource. return { status: 404 } } diff --git a/packages/client/modules/src/types.ts b/packages/client/modules/src/types.ts new file mode 100644 index 0000000000..c90db962ae --- /dev/null +++ b/packages/client/modules/src/types.ts @@ -0,0 +1,5 @@ +/** Web client graph types shared by the Host and Client faces and by Remote wire declarations. */ +export type { + BootManifest, BootModuleRow, BootPluginRow, WebBootBatch, WebBootBatchPhase, WebBootEntry, WebBootGraph, + WebBootRelease, +} from './client/manifest.ts' diff --git a/packages/client/modules/tests/entries.client.spec.ts b/packages/client/modules/tests/entries.client.spec.ts index cc2b53d8ff..1826deaa99 100644 --- a/packages/client/modules/tests/entries.client.spec.ts +++ b/packages/client/modules/tests/entries.client.spec.ts @@ -2,7 +2,9 @@ import { Context } from '@deepseek-ai/cordis' import Loader from '@deepseek-ai/cordis-plugin-loader' import { afterEach, describe, expect, it, vi } from 'vitest' +import z from '@deepseek-ai/schemastery' import { createClientModuleSystem } from '../src/client/index.ts' +import type { SyncedConfigRef } from '@deepseek-ai/dsh-client-config/types' import type { ClientBundleRegistration, ClientModuleLoaderTarget, WebBootRelease, WebBootEntry, WebBootGraph } from '../src/client/index.ts' type Factory = ClientBundleRegistration['factory'] @@ -86,6 +88,149 @@ function visible(id: string, effects: { mounted: number; disposed: number; hits: } describe('client manifest entries', () => { + it('hands each activation its own synced Config object and updates changed fields without remounting', async () => { + interface Synced { size: SyncedConfigRef; office: SyncedConfigRef<{ maxBytes: number }> } + const received: Synced[] = [] + const b = await bench(graph(row('bootstrap'), row('a', 'r0', { config: { size: 1, office: { maxBytes: 8 } } })), { + a: () => ({ apply(_ctx: Context, config: Synced) { received.push(config) } }), + }) + const config = received[0]! + expect(b.modules.entries.resolveConfigByPackage('a')).toBe(config) + expect(b.modules.entries.resolveConfigByPackage('missing')).toBeUndefined() + expect(Object.keys(config)).toEqual(['size', 'office']) + expect('size' in config).toBe(true) + expect('missing' in config).toBe(false) + expect('toString' in config).toBe(false) + expect(Object.getOwnPropertyDescriptor(config, 'hasOwnProperty')).toBeUndefined() + expect(Object.getOwnPropertyDescriptor(config, 'missing')).toBeUndefined() + expect(Reflect.get(config, Symbol.iterator)).toBeUndefined() + expect(Reflect.set(config, 'size', 1)).toBe(false) + expect(Reflect.defineProperty(config, 'size', { value: 1 })).toBe(false) + expect(Reflect.deleteProperty(config, 'size')).toBe(false) + const size = config.size + expect(config.size).toBe(size) + expect(Object.getOwnPropertyDescriptor(config, 'size')?.value).toBe(size) + expect(size.get()).toBe(1) + const office = config.office.getSnapshot() + expect(Object.isFrozen(office)).toBe(true) + const sizeListener = vi.fn() + const officeListener = vi.fn() + const unsubscribe = size.subscribe(sizeListener) + config.office.subscribe(officeListener) + + await b.modules.entries.sync(graph(row('bootstrap'), row('a', 'r0', { config: { office: { maxBytes: 8 }, size: 1 } }))) + expect(sizeListener).not.toHaveBeenCalled() + + await b.modules.entries.sync(graph(row('bootstrap'), row('a', 'r0', { config: { size: 2, office: { maxBytes: 8 } } }))) + expect(size.get()).toBe(2) + expect(size.getSnapshot()).toBe(2) + expect(sizeListener).toHaveBeenCalledOnce() + expect(officeListener).not.toHaveBeenCalled() + expect(config.office.getSnapshot()).toBe(office) + + // Every changed field is set before any subscriber runs. + const seen: unknown[] = [] + size.subscribe(() => { seen.push([size.get(), config.office.get()]) }) + await b.modules.entries.sync(graph(row('bootstrap'), row('a', 'r0', { config: { size: 4, office: { maxBytes: 9 } } }))) + expect(seen).toEqual([[4, { maxBytes: 9 }]]) + unsubscribe() + + // Removal releases the activation: like a Host fiber that is no longer active, it receives no later values. + await b.modules.entries.sync(graph(row('bootstrap'))) + expect(b.modules.entries.resolveConfigByPackage('a')).toBeUndefined() + expect(size.get()).toBe(4) + await b.modules.entries.sync(graph(row('bootstrap'), row('a', 'r0', { config: { size: 5 } }))) + expect(size.get()).toBe(4) + // A re-added row's new activation receives a new object with the latest values. + expect(received).toHaveLength(2) + expect(received[1]).not.toBe(config) + expect(received[1]!.size.get()).toBe(5) + expect(b.modules.entries.resolveConfigByPackage('a')).toBe(received[1]) + + // Code replacement: a value arriving before teardown begins updates the still-active activation, as on the Host; + // the replacement then starts with the latest values, and the released activation receives nothing later. + const second = received[1]! + const replacing = b.modules.entries.reload('a', 'r1') + await b.modules.entries.sync(graph(row('bootstrap'), row('a', 'r1', { config: { size: 6 } }))) + await replacing + expect(received).toHaveLength(3) + expect(second.size.get()).toBe(6) + expect(received[2]!.size.get()).toBe(6) + await b.modules.entries.sync(graph(row('bootstrap'), row('a', 'r1', { config: { size: 7 } }))) + expect(received[2]!.size.get()).toBe(7) + expect(second.size.get()).toBe(6) + }) + + it('stops writing to an activation that unloads because a required service was withdrawn', async () => { + interface Synced { size: SyncedConfigRef } + const received: Synced[] = [] + const b = await bench(graph(row('bootstrap'), row('a', 'r0', { config: { size: 1 } })), { + a: () => ({ inject: ['dependency'], apply(_ctx: Context, config: Synced) { received.push(config) } }), + }) + const dispose = b.ctx.provide('dependency', {}) + await vi.waitFor(() => { expect(received).toHaveLength(1) }) + const first = received[0]! + expect(b.modules.entries.resolveConfigByPackage('a')).toBe(first) + dispose() + await b.ctx.loader.await() + await b.modules.entries.sync(graph(row('bootstrap'), row('a', 'r0', { config: { size: 2 } }))) + expect(first.size.get()).toBe(1) + expect(b.modules.entries.resolveConfigByPackage('a')).toBeUndefined() + }) + + it('keeps the running activation\'s object when a candidate config is resolved for it', async () => { + interface Synced { size: SyncedConfigRef } + const received: Synced[] = [] + const b = await bench(graph(row('bootstrap'), row('a', 'r0', { config: { size: 1 } })), { + a: () => ({ apply(_ctx: Context, config: Synced) { received.push(config) } }), + }) + const fiber = [...b.ctx.loader.entries()].find(entry => entry.options.name === 'a')!.fiber!.ctx.fiber + expect(fiber.resolveConfig(fiber.rawConfig)).toBe(received[0]) + await b.modules.entries.sync(graph(row('bootstrap'), row('a', 'r0', { config: { size: 2 } }))) + expect(received[0]!.size.get()).toBe(2) + }) + + it('gives a row without values an empty object that later values fill without another apply', async () => { + const configs: unknown[] = [] + const b = await bench(graph(row('bootstrap'), row('a')), { + a: () => ({ apply(_ctx: Context, config: unknown) { configs.push(config) } }), + }) + const config = configs[0] as { size: SyncedConfigRef } + expect(Object.keys(config)).toEqual([]) + expect(config.size.get()).toBeUndefined() + await b.modules.entries.sync(graph(row('bootstrap'), row('a', 'r0', { config: { size: 1 } }))) + expect(configs).toEqual([config]) + expect(config.size.get()).toBe(1) + }) + + it('keeps ordinary configuration for a Client Config schema and rejects one that also receives synced values', async () => { + const own: unknown[] = [] + const b = await bench(graph(row('bootstrap'), row('own'), row('schema', 'r0', { config: { size: 1 } })), { + own: () => ({ Config: z.object({ limit: z.natural().default(3) }), apply(_ctx: Context, config: unknown) { own.push(config) } }), + schema: () => ({ Config: z.object({}), apply() {} }), + }) + expect(own).toEqual([{ limit: 3 }]) + const schemaFiber = [...b.ctx.loader.entries()].find(entry => entry.options.name === 'schema')!.fiber! + await expect(schemaFiber.await()).rejects.toThrow('exports a Config schema') + // A fiber outside the managed entries resolves its own config. + const plain = await b.ctx.plugin({ apply(_ctx: Context, config: unknown) { own.push(config) } }, { plain: true }) + expect(plain.state).toBe(2) + expect(own.at(-1)).toEqual({ plain: true }) + }) + + it('keeps a child plugin\'s explicit config inside a managed entry', async () => { + const child: unknown[] = [] + await bench(graph(row('bootstrap'), row('a', 'r0', { config: { size: 1 } })), { + a: () => ({ apply(ctx: Context) { ctx.plugin({ apply(_ctx: Context, config: unknown) { child.push(config) } }, { input: 1 }) } }), + }) + expect(child).toEqual([{ input: 1 }]) + }) + + it('rejects a graph row whose config is not an object', async () => { + const b = await bench(graph(row('bootstrap')), {}) + expect(() => b.modules.entries.sync(graph(row('bootstrap', 'r0', { config: [] as never })))).toThrow('config must be an object') + }) + it('adds, drains removal and re-enables one module record; unrelated entries survive', async () => { const effects = { mounted: 0, disposed: 0, hits: 0 } const cleanup = deferred() diff --git a/packages/client/modules/tests/node-half.client.spec.ts b/packages/client/modules/tests/node-half.client.spec.ts index e7a55ddfb0..06a9ec69d9 100644 --- a/packages/client/modules/tests/node-half.client.spec.ts +++ b/packages/client/modules/tests/node-half.client.spec.ts @@ -7,7 +7,7 @@ import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' import { pathToFileURL } from 'node:url' import { runInNewContext } from 'node:vm' -import { Context, FiberState, type Fiber } from '@deepseek-ai/cordis' +import { Context, FiberState } from '@deepseek-ai/cordis' import { afterEach, describe, expect, it, vi } from 'vitest' import { renderIndexInjections, type WebServer, type WebResourceRoute, type WebRoute } from '@deepseek-ai/dsh-host-webserver' import * as modulesClient from '../src/client/index.ts' @@ -178,7 +178,8 @@ function constructWithRoute( for (const packageName of packageNames) { yield { options: { name: packageName }, - fiber: {}, + // The Loader addresses an entry's plugin instance as `entry.fiber.ctx.fiber`. + fiber: { ctx: { fiber: {} } }, disabled: false, parent: { tree: { ctx: { baseUrl: options.entryBaseUrl ?? ctx.baseUrl } } }, } @@ -1289,7 +1290,8 @@ describe('client bundle activation', () => { function emitLoaderEntryChange(context: Context, name: string): void { context.emit('internal/plugin', { entry: { options: { name } }, - } as unknown as Fiber) + parent: { fiber: {} }, + } as never) } describe('shared module declarations', () => { diff --git a/packages/client/modules/tests/package-assets.client.spec.ts b/packages/client/modules/tests/package-assets.client.spec.ts index 1e63c951ac..ca0572e806 100644 --- a/packages/client/modules/tests/package-assets.client.spec.ts +++ b/packages/client/modules/tests/package-assets.client.spec.ts @@ -142,7 +142,7 @@ async function composeHost(): Promise { internal, *entries() { for (const name of [NO_EXPORT_ID, ASSETS_ID]) { - yield { options: { name }, fiber: {}, disabled: false, parent: { tree: { ctx: { baseUrl } } } } + yield { options: { name }, fiber: { ctx: { fiber: {} } }, disabled: false, parent: { tree: { ctx: { baseUrl } } } } } }, }) diff --git a/packages/client/modules/tests/synced-config.client.spec.ts b/packages/client/modules/tests/synced-config.client.spec.ts new file mode 100644 index 0000000000..db3bb9f79b --- /dev/null +++ b/packages/client/modules/tests/synced-config.client.spec.ts @@ -0,0 +1,256 @@ +/** Host side of synced configuration: projection, secret removal, and graph publication from a real Loader. */ +import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { pathToFileURL } from 'node:url' +import { Context } from '@deepseek-ai/cordis' +import Loader from '@deepseek-ai/cordis-plugin-loader' +import type { Entry } from '@deepseek-ai/cordis-plugin-loader' +import z from '@deepseek-ai/schemastery' +import { afterEach, expect, it, vi } from 'vitest' +import { ClientModuleRegistry } from '../src/index.ts' +import type { WebBootGraph } from '../src/client/manifest.ts' +import { syncedValues } from '../src/config-projection.ts' +import { SyncedConfigEntry } from '../src/client/synced-config.ts' + +const roots: Context[] = [] +let dir: string | undefined +afterEach(async () => { + await Promise.all(roots.splice(0).map(ctx => ctx.fiber.dispose())) + if (dir !== undefined) rmSync(dir, { recursive: true, force: true }) + dir = undefined +}) + +const Schema = z.object({ + cacheDir: z.string().default('.cache'), + size: z.natural().default(1).volatile(), + apiKey: z.string().role('secret').volatile(), + office: z.object({ maxBytes: z.natural().default(8), token: z.string().role('secret') }).volatile(), + tokens: z.array(z.string().role('secret')).default([]).volatile(), + headers: z.dict(z.string().role('secret')).default({}).volatile(), + choice: z.union([z.object({ kind: z.const('a'), secret: z.string().role('secret') }), z.string()]).default('plain').volatile(), + wrapped: z.transform(z.natural().default(2), value => value).volatile(), +}) + +it('projects top-level volatile fields and removes every secret position', () => { + const effective = Schema({ + size: 3, apiKey: 'k', office: { maxBytes: 9, token: 't' }, tokens: ['x'], headers: { a: 'h' }, + choice: { kind: 'a', secret: 's' }, wrapped: 2, extra: 1, + }) + expect(syncedValues(Schema, effective, 'pkg')).toEqual({ + size: 3, office: { maxBytes: 9 }, tokens: [], headers: {}, choice: { kind: 'a' }, wrapped: 2, + }) + expect(syncedValues(z.object({ ordinary: z.string().default('x') }), {}, 'pkg')).toBeUndefined() + expect(syncedValues(z.string(), 'x', 'pkg')).toBeUndefined() +}) + +it('reads intersection members, tolerates non-object values, and rejects lossy JSON', () => { + const Joined = z.intersect([ + z.object({ a: z.natural().default(1).volatile() }), + z.object({ b: z.object({ c: z.string().role('secret') }).volatile(), d: z.dict(z.string()).volatile(), e: z.array(z.string()).volatile() }), + ]) + expect(syncedValues(Joined, { a: 1, b: 'scalar', d: 'scalar', e: 'scalar' }, 'pkg')).toEqual({ a: 1, b: 'scalar', d: 'scalar', e: 'scalar' }) + expect(syncedValues(Joined, null, 'pkg')).toEqual({}) + expect(() => syncedValues(Joined, { a: Number.NaN }, 'pkg')).toThrow('pkg Config field a is not lossless JSON') +}) + +/** A resolvable built browser package under a temporary node_modules. */ +function writePackage(name: string): void { + dir ??= realpathSync(mkdtempSync(join(tmpdir(), 'dsh-synced-config-'))) + const root = join(dir, 'node_modules', ...name.split('/')) + mkdirSync(join(root, 'lib'), { recursive: true }) + writeFileSync(join(root, 'package.json'), JSON.stringify({ + name, exports: { './client': './lib/client.js', './package.json': './package.json' }, dsh: { client: { platform: 'web' } }, + })) + writeFileSync(join(root, 'lib', 'client.js'), 'module.exports = {}\n') +} + +/** A real Loader whose rows import the given plugins, and the graph service over it. */ +async function harness(plugins: Record, configs: Record = {}, disabled: string[] = []) { + for (const name of Object.keys(plugins)) writePackage(name) + const ctx = new Context() + roots.push(ctx) + ctx.baseUrl = pathToFileURL(dir!).href + '/' + await ctx.plugin(Loader) + ctx.loader.internal = { version: 'v2', import: async (name: string) => plugins[name] } as never + const entries: Record = {} + for (const name of Object.keys(plugins)) { + entries[name] = ctx.loader.resolve(await ctx.loader.create({ + name, disabled: disabled.includes(name), ...(configs[name] === undefined ? {} : { config: configs[name] }), + })) + } + await ctx.loader.await() + const fiber = ctx.plugin(ClientModuleRegistry) + await fiber.await() + const service = ctx.get('clientModules')! + const config = (id: string) => service.graph().entries.find(row => row.id === id)?.config + const changes = vi.fn() + service.onGraphChanged(changes) + return { ctx, service, entries, fiber, config, changes, plugins } +} + +const initial = { size: 3, office: { maxBytes: 8 }, tokens: [], headers: {}, choice: 'plain' } + +it('publishes volatile updates once, skips equal values, and keeps unsynced rows without config', async () => { + const h = await harness({ + '@fixture/pkg': { Config: Schema, apply: () => {} }, + '@fixture/plain': { apply: () => {} }, + '@fixture/off': { Config: Schema, apply: () => {} }, + }, { '@fixture/pkg': { size: 3, apiKey: 'k' }, '@fixture/plain': {} }, ['@fixture/off']) + expect(h.config('@fixture/pkg')).toEqual(initial) + expect(h.service.graph().entries.find(row => row.id === '@fixture/plain')).not.toHaveProperty('config') + const before = h.service.graph() + await h.entries['@fixture/pkg']!.update({ config: { size: 3, apiKey: 'changed' } }) + expect(h.changes).not.toHaveBeenCalled() + expect(h.service.graph()).toBe(before) + await h.entries['@fixture/pkg']!.update({ config: { size: 4, apiKey: 'changed' } }) + expect(h.changes).toHaveBeenCalledOnce() + expect(h.config('@fixture/pkg')).toEqual({ ...initial, size: 4 }) + expect(h.service.graph().rev).not.toBe(before.rev) +}) + +it('republishes after an ordinary change restarts the plugin and drops values of a removed row', async () => { + const h = await harness({ '@fixture/pkg': { Config: Schema, apply: () => {} } }, { '@fixture/pkg': { size: 3 } }) + await h.entries['@fixture/pkg']!.update({ config: { size: 5, cacheDir: 'other' } }) + await h.ctx.loader.await() + await vi.waitFor(() => { expect(h.config('@fixture/pkg')).toEqual({ ...initial, size: 5 }) }) + h.ctx.loader.remove(h.entries['@fixture/pkg']!.id) + await h.ctx.loader.await() + await vi.waitFor(() => { expect(h.service.graph().entries).toEqual([]) }) + await h.fiber.dispose() +}) + +it('publishes values its own schema resolves for a plugin that has not activated yet', async () => { + const h = await harness({ '@fixture/waiting': { inject: ['absent'], Config: Schema, apply: () => {} } }, { + '@fixture/waiting': { size: 3 }, + }) + expect(h.entries['@fixture/waiting']!.fiber!.ctx.fiber.effectiveConfig).toBeUndefined() + expect(h.config('@fixture/waiting')).toEqual(initial) +}) + +it('publishes values for an entry created after startup that has not activated yet', async () => { + const h = await harness({ '@fixture/pkg': { Config: Schema, apply: () => {} } }, { '@fixture/pkg': { size: 3 } }) + writePackage('@fixture/late') + h.plugins['@fixture/late'] = { inject: ['absent'], Config: Schema, apply: () => {} } + await h.ctx.loader.create({ name: '@fixture/late', config: { size: 7 } }) + await vi.waitFor(() => { expect(h.config('@fixture/late')).toEqual({ ...initial, size: 7 }) }) +}) + +const bootConfigOf = (ctx: Context, id: string) => (principal: { kind: string }): unknown => { + const table: { kind: string; name?: string; value?: unknown }[] = [] + ctx.emit('webserver/index-inject', table as never, { principal } as never) + const graph = table.find(row => row.name === '__DSH_BOOT__')!.value as { entries: { id: string; config?: unknown }[] } + return graph.entries.find(row => row.id === id)!.config +} + +it('serves configured values to the owner and schema defaults to every other Peer, at first render and through graphFor', async () => { + const h = await harness({ '@fixture/pkg': { Config: Schema, apply: () => {} } }, { '@fixture/pkg': { size: 3 } }) + const bootConfig = bootConfigOf(h.ctx, '@fixture/pkg') + const defaults = { ...initial, size: 1 } + const rowOf = (graph: WebBootGraph) => graph.entries.find(row => row.id === '@fixture/pkg')!.config + expect(bootConfig({ kind: 'owner' })).toEqual(initial) + expect(bootConfig({ kind: 'viewer' })).toEqual(defaults) + expect(h.service.graphFor(undefined)).toBe(h.service.graph()) + expect(h.service.graphFor({ kind: 'owner' })).toBe(h.service.graph()) + expect(rowOf(h.service.graphFor({ kind: 'viewer' } as never))).toEqual(defaults) + // A Remote access grant does not change which values a non-owner receives. + h.ctx.provide('remoteAccess', { snapshotFor: () => ({ type: 'baseline', owner: false, grants: [] }) } as never) + expect(bootConfig({ kind: 'viewer' })).toEqual(defaults) +}) + +it('serves no values to a non-owner Peer when the schema rejects an empty Config', async () => { + const Required = z.object({ size: z.natural().required().volatile() }) + const h = await harness({ '@fixture/required': { Config: Required, apply: () => {} } }, { '@fixture/required': { size: 3 } }) + const debug = vi.spyOn(h.ctx.logger, 'debug').mockImplementation(() => {}) + await h.entries['@fixture/required']!.update({ config: { size: 4 } }) + const bootConfig = bootConfigOf(h.ctx, '@fixture/required') + expect(bootConfig({ kind: 'owner' })).toEqual({ size: 4 }) + expect(bootConfig({ kind: 'viewer' })).toBeUndefined() + expect(debug).toHaveBeenCalled() +}) + +it('keeps the batch artifacts and the prior batch generation when only synced values change', async () => { + const h = await harness({ '@fixture/pkg': { Config: Schema, apply: () => {} } }, { '@fixture/pkg': { size: 3 } }) + const status = async (url: string) => (await h.service.fetchBundle(new Request(new URL(url, 'http://localhost/').href))).status + const first = h.service.graph().batches[0]!.url + writeFileSync(join(dir!, 'node_modules', '@fixture', 'pkg', 'lib', 'client.js'), 'module.exports = { generation: 2000 }\n') + h.service.rebuilt('@fixture/pkg') + const second = h.service.graph() + expect(second.batches[0]!.url).not.toBe(first) + await h.entries['@fixture/pkg']!.update({ config: { size: 4 } }) + expect(h.config('@fixture/pkg')).toEqual({ ...initial, size: 4 }) + expect(h.service.graph().batches).toBe(second.batches) + expect(await status(first)).toBe(200) +}) + +it('falls back to a live entry of the same name when the selected instance is removed', async () => { + const h = await harness({ '@fixture/other': { apply: () => {} }, '@fixture/pkg': { Config: Schema, apply: () => {} } }, { + '@fixture/pkg': { size: 1 }, + }) + // A disabled entry of the same name has no instance to fall back to. + await h.ctx.loader.create({ name: '@fixture/pkg', disabled: true }) + const second = h.ctx.loader.resolve(await h.ctx.loader.create({ name: '@fixture/pkg', config: { size: 2 } })) + await h.ctx.loader.await() + await vi.waitFor(() => { expect(h.config('@fixture/pkg')).toEqual({ ...initial, size: 2 }) }) + h.ctx.loader.remove(second.id) + await h.ctx.loader.await() + await vi.waitFor(() => { expect(h.config('@fixture/pkg')).toEqual({ ...initial, size: 1 }) }) + await h.entries['@fixture/pkg']!.update({ config: { size: 3 } }) + expect(h.config('@fixture/pkg')).toEqual({ ...initial, size: 3 }) + // With no live entry left, the last values stay until the row leaves the graph. + h.ctx.loader.remove(h.entries['@fixture/pkg']!.id) + await h.ctx.loader.await() +}) + +it('keeps the last values of a row whose value cannot be synced', async () => { + const h = await harness({ '@fixture/lossy': { Config: z.object({ n: z.any().volatile() }), apply: () => {} } }, { '@fixture/lossy': { n: 1 } }) + const errors = vi.spyOn(h.ctx.logger, 'error').mockImplementation(() => {}) + expect(h.config('@fixture/lossy')).toEqual({ n: 1 }) + await h.entries['@fixture/lossy']!.update({ config: { n: Number.POSITIVE_INFINITY } }) + expect(errors).toHaveBeenCalledWith(expect.objectContaining({ message: expect.stringContaining('@fixture/lossy Config field n') as string })) + expect(h.config('@fixture/lossy')).toEqual({ n: 1 }) +}) + +it('keeps the fields each union branch or intersection member does not declare', () => { + const a = z.object({ a: z.string() }) + const b = z.object({ b: z.string() }) + const schema = z.object({ + either: z.union([a, b]).volatile(), + both: z.intersect([a, b]).volatile(), + hidden: z.union([z.object({ kind: z.const('x'), token: z.string().role('secret') }), b]).volatile(), + }) + expect(syncedValues(schema, { either: { a: 'one' }, both: { a: 'one', b: 'two' }, hidden: { kind: 'x', token: 't' } }, 'pkg')) + .toEqual({ either: { a: 'one' }, both: { a: 'one', b: 'two' }, hidden: { kind: 'x' } }) +}) + +it('compares field values as JSON, so an empty array and an empty object differ while reordered keys do not', () => { + const entry = new SyncedConfigEntry({ list: [], map: { a: 1, b: 2 } }) + expect(entry.config).toBeUndefined() + type Ref = { get(): unknown; subscribe(listener: () => void): () => void } + const config = entry.activate() as { list: Ref; map: Ref } + expect(entry.config).toBe(config) + const list = vi.fn() + const map = vi.fn() + config.list.subscribe(list) + config.map.subscribe(map) + entry.update({ list: {}, map: { b: 2, a: 1 }, extra: 1 }) + expect(config.list.get()).toEqual({}) + expect(list).toHaveBeenCalledOnce() + expect(map).not.toHaveBeenCalled() + expect(entry.empty).toBe(false) + entry.release() + expect(entry.config).toBeUndefined() + entry.update({}) + expect(entry.empty).toBe(true) + expect(config.list.get()).toEqual({}) +}) + +it('queues the new graph before the plugin\'s own volatile-update listeners run', async () => { + const order: string[] = [] + const h = await harness({ + '@fixture/ordered': { Config: Schema, apply: (ctx: Context) => { ctx.on('loader/volatile-update', () => { order.push('plugin') }) } }, + }, { '@fixture/ordered': { size: 1 } }) + h.service.onGraphChanged(() => { order.push('graph') }) + await h.entries['@fixture/ordered']!.update({ config: { size: 2 } }) + expect(order).toEqual(['graph', 'plugin']) +}) diff --git a/packages/client/modules/tsconfig.json b/packages/client/modules/tsconfig.json index 29b30c0509..7cfab229e2 100644 --- a/packages/client/modules/tsconfig.json +++ b/packages/client/modules/tsconfig.json @@ -13,6 +13,10 @@ {"path": "../../host/webserver"}, {"path": "../../util/package-manifest"}, {"path": "../script-realm"}, - {"path": "../store"} + {"path": "../store"}, + {"path": "../../../vendor/schemastery"}, + {"path": "../../util/values"}, + {"path": "../config"}, + {"path": "../../typert/protocol"} ] } diff --git a/packages/client/ui-account-notifications/README.i18n.yaml b/packages/client/ui-account-notifications/README.i18n.yaml index 1ce8f44b0d..64245870b9 100644 --- a/packages/client/ui-account-notifications/README.i18n.yaml +++ b/packages/client/ui-account-notifications/README.i18n.yaml @@ -9,14 +9,14 @@ en: c8d24427c7fcd3aa zh: 5c0cf16f36ae6165 /deepseek-ai-dsh-client-ui-account-notifications/summary: - en: 46cf31a87b0b765c - zh: 04f6b33570b046f7 + en: 81f1f0bcf51bad6b + zh: 84a2a8bcc593f581 /deepseek-ai-dsh-client-ui-account-notifications/table-of-contents: en: af856ba79fe31b8e zh: c9b0188689359236 /deepseek-ai-dsh-client-ui-account-notifications/use-this-package: - en: c466836df88d4ae1 - zh: 036e859139daa51d + en: b138ea2fb39d73af + zh: 71382a554aeae5ea /deepseek-ai-dsh-client-ui-account-notifications/model-experience: en: 5fed5504300020e6 zh: efd8e7c32b699e7e @@ -27,5 +27,5 @@ en: 0d59eea475321fd0 zh: 1cf67a196e76b832 /deepseek-ai-dsh-client-ui-account-notifications/known-limitations-and-deferred-work/dev-note: - en: 64006edb418180b1 - zh: 12f7d7ab2cbccd43 + en: a7d8cbb5b6313e02 + zh: 83f0d8d6cd988d2e diff --git a/packages/client/ui-account-notifications/README.md b/packages/client/ui-account-notifications/README.md index 10a0eeaadb..5d68a10b23 100644 --- a/packages/client/ui-account-notifications/README.md +++ b/packages/client/ui-account-notifications/README.md @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -Show server-authored account notifications beside the account menu. Displayed cards survive later list omissions and refresh their content when the interface language changes. +Show server-authored account notifications above the account menu. Displayed cards survive later list omissions and refresh their content when the interface language changes. ## Table of Contents @@ -20,13 +20,13 @@ Show server-authored account notifications beside the account menu. Displayed ca ## Use this package -The Web bundle includes this plugin with [account settings](../ui-settings-account/README.md). It contributes to `settings.launcher.notifications`; the account menu supplies visibility and the action that opens Account settings. The notification plugin owns cards, polling, localized content, and interaction reports. +The Web bundle includes this plugin with [account settings](../ui-settings-account/README.md). It contributes to `settings.launcher.notifications`; account settings fills the settings shell's row above the account launcher with this slot and supplies visibility and the action that opens Account settings. The notification plugin owns cards, polling, localized content, and interaction reports. Startup with a stored account, sign-in, and each Settings entry start a new polling cycle with an immediate request. `notificationPollIntervalMs` on the `ui-account-notifications` row supplies the initial delay, defaulting to 600,000 ms. A successful list response replaces it with `next_poll_after` seconds, including empty lists. The delay starts after the request settles; failures retain the latest delay, and restarting restores the configured initial value. Polling continues in the background. Account settings owns the sole account stream and exposes its current state and lifecycle events through `accountUi` and `account-ui/change`. Login-progress updates retain cards and polling. Credential replacement, disconnection, access revocation, sign-out, and plugin disposal clear cards, stop polling, and discard late replies. Notification requests do not wait for profile or avatar data. Notification state is not stored in the browser. -Cards render inside the sidebar above the account launcher and below menus and dialogs without taking focus. Their width follows the expanded launcher up to 280px, leaving 10px on the left and at least 10px on the right. Collapsing the sidebar hides the cards; expanding it restores them without another display report. Closing a card promotes the next with a 250ms position and scale transition, disabled by reduced-motion preferences. +Cards float over the sidebar list, anchored 4px above the account launcher row, below menus and dialogs, without taking focus or space from the list. Status indicators beside the launcher do not narrow them. Title and body text taller than 40% of the viewport scrolls inside the card, so a long notice does not cover the whole sidebar. Their width follows the expanded sidebar up to 280px, leaving 10px on the left and at least 10px on the right. Collapsing the sidebar hides the cards; expanding it restores them without another display report. Closing a card promotes the next with a 250ms position and scale transition, disabled by reduced-motion preferences. Notifications wait for Desktop and model-credential onboarding to finish. Only the foreground card is interactive and reports `displayed`, once per mount after a painted frame while it intersects the viewport and the sidebar and document are visible. The Settings overlay does not exclude that frame. A displayed foreground card remains until close or expiry even when a later list omits it; waiting cards follow server order. @@ -54,4 +54,4 @@ No model request prefix changes. ### Dev Note -The package tests cover lifecycle ownership; the Web notification scenario checks the assembled account menu. +The package tests cover lifecycle ownership; the Web notification scenario checks the assembled sidebar account rows. diff --git a/packages/client/ui-account-notifications/README.zh.md b/packages/client/ui-account-notifications/README.zh.md index adbae8cac4..e1b68d603e 100644 --- a/packages/client/ui-account-notifications/README.zh.md +++ b/packages/client/ui-account-notifications/README.zh.md @@ -9,7 +9,7 @@ kind: "package-reference" ## 概述 -在账号菜单旁展示服务端提供的账号通知。已展示卡片不会因后续列表省略而消失,并在界面语言切换时刷新内容。 +在账号菜单上方展示服务端提供的账号通知。已展示卡片不会因后续列表省略而消失,并在界面语言切换时刷新内容。 ## 目录 @@ -20,13 +20,13 @@ kind: "package-reference" ## 使用此包 -Web 组合将本插件与[账号设置](../ui-settings-account/README.zh.md)一同加载。本插件向 `settings.launcher.notifications` 注册内容;账号菜单提供可见性和打开账号设置的操作。通知插件负责卡片、轮询、本地化内容和交互上报。 +Web 组合将本插件与[账号设置](../ui-settings-account/README.zh.md)一同加载。本插件向 `settings.launcher.notifications` 注册内容;账号设置在设置外壳位于账号入口上方的行中渲染该插槽,并提供可见性和打开账号设置的操作。通知插件负责卡片、轮询、本地化内容和交互上报。 带有已存账号的启动、登录及每次进入设置页都会启动新一轮轮询,并立即请求。`ui-account-notifications` 行中的 `notificationPollIntervalMs` 提供初始间隔,默认 600,000 ms。成功的列表响应通过 `next_poll_after` 秒替换间隔,空列表也相同。从请求结束时开始计时;失败沿用最近间隔,重启轮询恢复配置的初始值。轮询在后台继续。 账号设置拥有唯一的账号流,通过 `accountUi` 和 `account-ui/change` 提供当前状态及生命周期事件。登录进度更新沿用卡片和轮询。凭据替换、断连、权限撤销、退出登录和插件卸载会清空卡片、停止轮询并丢弃迟到响应。通知请求不等待资料或头像。通知状态不写入浏览器存储。 -卡片在侧栏内部、账号入口上方渲染,位于菜单和对话框之下,不抢占焦点。宽度跟随展开的账号入口,最大为 280px,左侧留 10px、右侧至少留 10px。收起侧栏会隐藏卡片;展开后恢复卡片,不重复上报展示。关闭卡片后,下一张通过 250ms 的位置和缩放过渡补位;偏好减少动态效果时禁用过渡。 +卡片浮在侧栏列表之上,锚定在账号入口行上方 4px,位于菜单和对话框之下,不抢占焦点,也不占用列表空间。入口旁的状态指示器不会挤压卡片。标题和正文高度超过视口 40% 时在卡片内滚动,避免长通知遮住整个侧栏。宽度跟随展开的侧栏,最大为 280px,左侧留 10px、右侧至少留 10px。收起侧栏会隐藏卡片;展开后恢复卡片,不重复上报展示。关闭卡片后,下一张通过 250ms 的位置和缩放过渡补位;偏好减少动态效果时禁用过渡。 通知等待 Desktop 和模型凭据引导完成。只有前排卡片可交互并上报 `displayed`:卡片与视口相交、侧栏和文档可见并完成一帧绘制后,同一次挂载只上报一次。设置蒙层不排除该帧。已展示的前排卡片保留至关闭或过期,即使后续列表不再返回它;待展示卡片遵循服务端顺序。 @@ -54,4 +54,4 @@ Web 组合将本插件与[账号设置](../ui-settings-account/README.zh.md)一 ### 开发备注 -包内测试覆盖生命周期所有权;Web 通知场景验证组合后的账号菜单。 +包内测试覆盖生命周期所有权;Web 通知场景验证组合后的侧栏账号行。 diff --git a/packages/client/ui-account-notifications/src/client/AccountNotifications.module.css b/packages/client/ui-account-notifications/src/client/AccountNotifications.module.css index cd508405b9..84461ffac2 100644 --- a/packages/client/ui-account-notifications/src/client/AccountNotifications.module.css +++ b/packages/client/ui-account-notifications/src/client/AccountNotifications.module.css @@ -1,10 +1,12 @@ /* Each deeper card is centered 4px above the preceding card and narrows by the design's 252/260 ratio. The foreground alone determines the stack height. */ .stack { position: relative; isolation: isolate; width: 100%; max-width: 280px; } -.card { position: relative; box-sizing: border-box; width: 100%; padding: 20px; border: 0; border-radius: 16px; background: var(--dsw-specific-input-major); box-shadow: var(--dsw-elevation-panel); color: var(--dsw-alias-label-secondary); font-size: 14px; line-height: 22px; z-index: calc(0 - var(--notice-depth)); transform: translateY(calc(-4px * var(--notice-depth))) scaleX(var(--notice-scale)); transform-origin: center top; transition: transform 250ms ease-out; } +.card { position: relative; box-sizing: border-box; width: 100%; padding: 20px; border: 0; border-radius: 16px; background: var(--dsw-specific-input-major); box-shadow: var(--dsw-elevation-panel); --dsh-scrollbar-thumb: var(--dsw-alias-scrollbar-bg-l2); --dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l2); color: var(--dsw-alias-label-secondary); font-size: 14px; line-height: 22px; z-index: calc(0 - var(--notice-depth)); transform: translateY(calc(-4px * var(--notice-depth))) scaleX(var(--notice-scale)); transform-origin: center top; transition: transform 250ms ease-out; } .card[data-front="false"] { position: absolute; inset: 0; height: 100%; overflow: hidden; pointer-events: none; } @media (prefers-reduced-motion: reduce) { .card { transition: none; } } -.copy { display: flex; flex-direction: column; gap: 2px; overflow-wrap: anywhere; } +/* Long server copy scrolls inside the card so a tall notice does not cover the whole sidebar; + the card rebinds the l2 scrollbar colors for its elevated surface (ui-theme styles/scrollbar.css). */ +.copy { display: flex; flex-direction: column; gap: 2px; max-height: 40vh; overflow-y: auto; overflow-wrap: anywhere; } .copy p { margin: 0; white-space: pre-wrap; } .actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 12px; } .action { max-width: 100%; height: auto; min-height: 28px; white-space: normal; overflow-wrap: anywhere; } diff --git a/packages/client/ui-account-notifications/src/client/AccountNotifications.tsx b/packages/client/ui-account-notifications/src/client/AccountNotifications.tsx index 1776aee512..43065372b7 100644 --- a/packages/client/ui-account-notifications/src/client/AccountNotifications.tsx +++ b/packages/client/ui-account-notifications/src/client/AccountNotifications.tsx @@ -1,4 +1,4 @@ -/** Notification extension rendered inside the sidebar account menu. */ +/** Notification extension rendered in the sidebar row above the account menu. */ import { useEffect, useRef, type CSSProperties } from 'react' import { Button, IconCloseOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' import type { HostObservable, InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' @@ -23,7 +23,7 @@ export interface AccountNotificationsInjected { export type AccountNotificationsProps = PropsRuntime<'settings.launcher.notifications'> & InjectFace & PropsLocale<'account.notifications'> -/** @param props - account-menu availability and notification content. @returns the anchored notification stack. */ +/** @param props - account availability and notification content. @returns the notification stack. */ export function AccountNotifications({ active, openAccount, useNotices, shown, ctaClicked, dismiss, t }: AccountNotificationsProps) { const notices = useNotices(value => value) return active && null) - await runtime.mount({ inject: [...injectConversation], apply: applyConversation }) + await runtime.mount({ inject: [...injectConversation], apply: applyConversation }, syncedConfig({ busyEnter: 'queue', maxConcurrentFileUploads: 2 })) const registerGroups = withProcessGroups ? undefined : vi.spyOn(runtime.ctx.uiConversation.groups, 'register').mockImplementation(() => () => {}) const chat = await runtime.mount({ inject: [...injectChat], apply: applyChat }) diff --git a/packages/client/ui-chat/tests/chat-apply.client.spec.tsx b/packages/client/ui-chat/tests/chat-apply.client.spec.tsx index 7a6a7c5bcd..1864682b88 100644 --- a/packages/client/ui-chat/tests/chat-apply.client.spec.tsx +++ b/packages/client/ui-chat/tests/chat-apply.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { apply as applyMenus, inject as injectMenus } from '@deepseek-ai/dsh-client-ui-context-menu/client' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { describe, expect, it, onTestFinished, vi } from 'vitest' @@ -77,7 +78,7 @@ async function bench() { runtime.ctx.provide('locale', locale) runtime.slots.installLocale(locale) runtime.ctx.provide('shortcuts', { catalog: createSnapshotStore([]) }) - await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }, syncedConfig({ resolutionTimeoutMs: 1000 })) await runtime.root.declare({ 'main': { kind: 'keyed', scope: 'root' }, 'shell.overlay': { kind: 'list', scope: 'root' }, @@ -87,7 +88,7 @@ async function bench() { const conversation = await runtime.mount({ inject: [...injectConversation], apply: applyConversation, - }) + }, syncedConfig({ busyEnter: 'queue', maxConcurrentFileUploads: 2 })) const provide = vi.spyOn(runtime.ctx.uiSession, 'provide') const chat = await runtime.mount({ inject: [...injectChat], apply: applyChat }) const sourceDescriptor = provide.mock.calls[0]?.[0] diff --git a/packages/client/ui-chat/tests/fence-slot.client.spec.tsx b/packages/client/ui-chat/tests/fence-slot.client.spec.tsx index 44d054ada8..0464c6d74a 100644 --- a/packages/client/ui-chat/tests/fence-slot.client.spec.tsx +++ b/packages/client/ui-chat/tests/fence-slot.client.spec.tsx @@ -1,5 +1,6 @@ // @vitest-environment jsdom /** Chat's Markdown fence Slot over the assembled Conversation and Chat plugins. */ +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { apply as applyMenus, inject as injectMenus } from '@deepseek-ai/dsh-client-ui-context-menu/client' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest' @@ -106,7 +107,7 @@ async function renderChat(events: readonly SessionEventLikeEntry[]) { runtime.ctx.provide('locale', locale) runtime.slots.installLocale(locale) runtime.ctx.provide('shortcuts', { catalog: createSnapshotStore([]) }) - await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }, syncedConfig({ resolutionTimeoutMs: 1000 })) await runtime.sessions.add({ id: SID, summary: { title: 'F', displayTitle: 'F', cwd: '/proj' }, @@ -118,7 +119,7 @@ async function renderChat(events: readonly SessionEventLikeEntry[]) { 'main': { kind: 'keyed', scope: 'root' }, 'settings.general.item': { kind: 'list', scope: 'root' }, }, AppRoot) - await runtime.mount({ inject: [...injectConversation], apply: applyConversation }) + await runtime.mount({ inject: [...injectConversation], apply: applyConversation }, syncedConfig({ busyEnter: 'queue', maxConcurrentFileUploads: 2 })) await runtime.mount({ inject: [...injectChat], apply: applyChat }) return runtime.renderRoot() } diff --git a/packages/client/ui-chat/tests/quota-notice.client.spec.tsx b/packages/client/ui-chat/tests/quota-notice.client.spec.tsx index 5e0f5cd8e3..95775d73f5 100644 --- a/packages/client/ui-chat/tests/quota-notice.client.spec.tsx +++ b/packages/client/ui-chat/tests/quota-notice.client.spec.tsx @@ -3,6 +3,7 @@ * that outlives the Chat panel, and history scrollback never does. */ // @vitest-environment jsdom +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { apply as applyMenus, inject as injectMenus } from '@deepseek-ai/dsh-client-ui-context-menu/client' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { afterEach, describe, expect, it } from 'vitest' @@ -70,12 +71,12 @@ async function bench() { runtime.ctx.provide('locale', locale) runtime.slots.installLocale(locale) runtime.ctx.provide('shortcuts', { catalog: createSnapshotStore([]) }) - await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }, syncedConfig({ resolutionTimeoutMs: 1000 })) await runtime.declare({ 'shell.overlay': { kind: 'list', scope: 'root' }, 'conversation.approval.detail': { kind: 'single', scope: 'session' }, }) - const conversation = await runtime.mount({ inject: [...injectConversation], apply: applyConversation }) + const conversation = await runtime.mount({ inject: [...injectConversation], apply: applyConversation }, syncedConfig({ busyEnter: 'queue', maxConcurrentFileUploads: 2 })) let descriptor: Parameters[0] | undefined const provide = runtime.ctx.uiSession.provide.bind(runtime.ctx.uiSession) runtime.ctx.uiSession.provide = (next) => { descriptor ??= next; return provide(next) } diff --git a/packages/client/ui-chat/tests/user-content.client.spec.tsx b/packages/client/ui-chat/tests/user-content.client.spec.tsx index 360c7cc4e4..1acb0d3dc8 100644 --- a/packages/client/ui-chat/tests/user-content.client.spec.tsx +++ b/packages/client/ui-chat/tests/user-content.client.spec.tsx @@ -77,9 +77,11 @@ async function bench() { }, UserText) ctx.slots.register({ name: 'conversation.user.text.node', key: 'text' }, PlainUserText) ctx.slots.register({ name: 'conversation.user.text.node', key: 'session' }, SessionReference) + // Every path mention in these units is Host-confirmed; ui-reference owns presence coverage. + const keyedHooks = { pathPresence: () => ({ getSnapshot: () => 'present' as const, subscribe: () => () => {} }) } ctx.slots.register({ name: 'conversation.user.text.node', key: 'file', locale: 'reference', - inject: () => ({ openFile, resolveFilePath: path => path }) }, FileReference) - ctx.slots.register({ name: 'conversation.user.text.node', key: 'folder' }, FolderReference) + inject: () => ({ openFile, resolveFilePath: (path: string) => path, keyedHooks }) }, FileReference) + ctx.slots.register({ name: 'conversation.user.text.node', key: 'folder', inject: () => ({ keyedHooks }) }, FolderReference) ctx.slots.register({ name: 'conversation.user.text.node', key: 'skill', inject: () => ({ openSkill }) }, SkillReference) ctx.slots.inject('conversation.chat.user.images', () => ctx.slots.register({ name: 'conversation.chat.user.images' }, function ImageProbe(props) { imageCalls.push(props) diff --git a/packages/client/ui-context-menu/README.i18n.yaml b/packages/client/ui-context-menu/README.i18n.yaml index da161da095..33fc925b51 100644 --- a/packages/client/ui-context-menu/README.i18n.yaml +++ b/packages/client/ui-context-menu/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 725b47765ee8f30b /deepseek-ai-dsh-client-ui-context-menu/use-this-package: - en: 892cfb46cfcddcc0 - zh: c534b44e7ef53522 + en: e07cd4cb97b6c77e + zh: 97bba9f554dce3c7 /deepseek-ai-dsh-client-ui-context-menu/use-this-package/register-actions: en: 11bea09005de2678 zh: d56e25d2d93022aa diff --git a/packages/client/ui-context-menu/README.md b/packages/client/ui-context-menu/README.md index 704d8f5043..40137c1d10 100644 --- a/packages/client/ui-context-menu/README.md +++ b/packages/client/ui-context-menu/README.md @@ -25,7 +25,7 @@ Add actions to right-click menus without importing a React component. Targets re ## Use this package -The Web application bundle mounts this Client plugin. External Client plugins declare the package in `dsh.client.inject`, import its `/client` types, and inject the `contextMenus` service. `resolutionTimeoutMs` bounds each provider’s preparation (1000ms by default); timed-out providers are aborted and omitted with visible failure feedback. +The Web application bundle mounts this Client plugin. External Client plugins declare the package in `dsh.client.inject`, import its `/client` types, and inject the `contextMenus` service. `resolutionTimeoutMs` bounds each provider’s preparation (1000ms by default); timed-out providers are aborted and omitted with visible failure feedback. It is a volatile field of the Host entry's Config, so a change in `cordis.yml` reaches open pages without remounting the plugin and applies from the next menu preparation. The plugin injects `useContextMenu` into every Slot scope through `ctx.slots.provideRoot`. Call `const { getTriggerProps } = useContextMenu()` once in the component and spread `getTriggerProps(target, handlers?)` onto each trigger. The factory is an ordinary function and can run in loops. It handles right-click, Shift+F10, the ContextMenu key, viewport coordinates, and focus without scrolling. Existing handlers run first; `preventDefault()` keeps their ownership and prevents duplicate handling by composed or nested bindings. Repeated, composing, and unrelated key events remain untouched. Pass `undefined` to retain native behavior, or a target resolver to read business state when the gesture begins. The resolved object is captured before focus changes. Plain children receive event props or a factory through props or an existing delegate; no additional React Context is needed. Special editors and canvases can call `ctx.contextMenus.open()` directly. diff --git a/packages/client/ui-context-menu/README.zh.md b/packages/client/ui-context-menu/README.zh.md index 1fc68c3a1e..952d5896d2 100644 --- a/packages/client/ui-context-menu/README.zh.md +++ b/packages/client/ui-context-menu/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用本包 -Web 应用 bundle 挂载此客户端插件。外部客户端插件在 `dsh.client.inject` 声明本包,导入 `/client` 类型,并注入 `contextMenus` 服务。`resolutionTimeoutMs` 限制每个提供方的准备时长(默认 1000ms);超时后取消并忽略该提供方,显示失败提示。 +Web 应用 bundle 挂载此客户端插件。外部客户端插件在 `dsh.client.inject` 声明本包,导入 `/client` 类型,并注入 `contextMenus` 服务。`resolutionTimeoutMs` 限制每个提供方的准备时长(默认 1000ms);超时后取消并忽略该提供方,显示失败提示。它是 Host 条目 Config 中的 volatile 字段,因此在 `cordis.yml` 中修改后,已打开的页面无需重新挂载插件,从下一次准备菜单起生效。 插件通过 `ctx.slots.provideRoot` 向每个 Slot 作用域注入 `useContextMenu`。组件调用一次 `const { getTriggerProps } = useContextMenu()`,再将 `getTriggerProps(target, handlers?)` 展开到各个触发元素上。该工厂是普通函数,可以在循环中调用;它统一处理右键、Shift+F10、ContextMenu 键、视口坐标及无滚动聚焦。已有处理器先运行,`preventDefault()` 保留其处理权,并防止组合或嵌套绑定重复处理。重复、输入法组合及无关按键保持原状。传入 `undefined` 保留原生行为,也可传入目标解析函数,在手势开始时读取业务状态。解析后的对象会在焦点变化前捕获。普通子组件通过 props 或现有 delegate 接收事件 props 或工厂,无需额外 React Context。特殊编辑器和 Canvas 可直接调用 `ctx.contextMenus.open()`。 diff --git a/packages/client/ui-context-menu/package.json b/packages/client/ui-context-menu/package.json index e9c383ed59..9f56f52474 100644 --- a/packages/client/ui-context-menu/package.json +++ b/packages/client/ui-context-menu/package.json @@ -44,8 +44,10 @@ "peerDependencies": { "@deepseek-ai/cordis": "workspace:~" }, + "dependencies": { + "@deepseek-ai/schemastery": "workspace:~" + }, "devDependencies": { - "@deepseek-ai/schemastery": "workspace:~", "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-client-locale": "workspace:*", "@deepseek-ai/dsh-client-store": "workspace:*", @@ -59,7 +61,8 @@ "@deepseek-ai/dsh-client-test-runtime": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-client-ui-dockkit": "workspace:*", - "@deepseek-ai/dsh-client-shortcuts": "workspace:*" + "@deepseek-ai/dsh-client-shortcuts": "workspace:*", + "@deepseek-ai/dsh-client-config": "workspace:*" }, "files": [ "locale/*.json", diff --git a/packages/client/ui-context-menu/src/client/index.ts b/packages/client/ui-context-menu/src/client/index.ts index b4244c4153..8d5f16a5f3 100644 --- a/packages/client/ui-context-menu/src/client/index.ts +++ b/packages/client/ui-context-menu/src/client/index.ts @@ -4,7 +4,8 @@ import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import type { Context } from '@deepseek-ai/cordis' import type {} from '@deepseek-ai/dsh-client-ui-layout/client' import type {} from '@deepseek-ai/dsh-client-locale/client' -import z from '@deepseek-ai/schemastery' +import type { SyncedConfig } from '@deepseek-ai/dsh-client-config/types' +import type { ContextMenuConfig } from '../types.ts' import { MENU_TRANSITION_MS } from '@deepseek-ai/dsh-client-ui-primitives' import { menuTargetKey } from './target-key.ts' import { MenuRegistry } from './registry.ts' @@ -44,15 +45,13 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { interface LocaleNamespaceMap { /** Menu operation feedback. */ contextMenu: 'failed' | 'back' } } -/** Maximum time to prepare each contribution before omitting its pending actions. */ -export interface Config { resolutionTimeoutMs?: number } -/** Validated Client menu preparation budget. */ -export const Config: z = z.object({ resolutionTimeoutMs: z.natural().min(1).default(1000) }) +/** Preparation budget while the Host sends none; the value the Client used before the field moved to the Host. */ +const ABSENT_RESOLUTION_TIMEOUT_MS = 1000 /** Required overlay and localization services. */ export const inject = ['slots', 'locale', 'shortcuts'] -/** @param ctx - plugin-owned Client context. @param config - validated preparation budget. */ -export function apply(ctx: Context, config: Config = Config({})): void { +/** @param ctx - plugin-owned Client context. @param config - Host-synced preparation budget, read when each menu prepares. */ +export function apply(ctx: Context, config: SyncedConfig): void { ctx.effect(() => ctx.locale.register('contextMenu', dictionaries), 'context menu: locale') const t = ctx.locale.bind('contextMenu') const handle = createMenuStore() @@ -81,7 +80,7 @@ export function apply(ctx: Context, config: Config = Config({})): void { }, } } }) } - const registry = new MenuRegistry((message) => { notify(message ?? t('failed')) }, config.resolutionTimeoutMs) + const registry = new MenuRegistry((message) => { notify(message ?? t('failed')) }, () => config.resolutionTimeoutMs.get() ?? ABSENT_RESOLUTION_TIMEOUT_MS) const cancelOpening = (): void => { clearTimeout(openingTimer); finishOpening?.(); finishOpening = undefined active?.unsubscribe(); active?.resolution.dispose(); active = undefined diff --git a/packages/client/ui-context-menu/src/client/registry.ts b/packages/client/ui-context-menu/src/client/registry.ts index af89692538..b4d580dd3a 100644 --- a/packages/client/ui-context-menu/src/client/registry.ts +++ b/packages/client/ui-context-menu/src/client/registry.ts @@ -20,7 +20,10 @@ export class MenuRegistry { private readonly providers = new Map() private readonly occurrences = new Set<() => void>() private disposed = false - constructor(private readonly failed: (message?: string) => void, private readonly timeoutMs?: number) {} + constructor( + private readonly failed: (message?: string) => void, + private readonly timeoutMs: () => number | undefined = () => undefined, + ) {} /** * Register actions for subsequent openings. @@ -110,9 +113,10 @@ export class MenuRegistry { const result = provider.resolve(target, signal) if (result instanceof Promise) clear() preparing = result instanceof Promise ? new Promise((settle) => { - const timer = this.timeoutMs === undefined ? undefined : setTimeout(() => { + const timeoutMs = this.timeoutMs() + const timer = timeoutMs === undefined ? undefined : setTimeout(() => { deadline.abort(); this.failed() - }, this.timeoutMs) + }, timeoutMs) const finish = (): void => { clearTimeout(timer); signal.removeEventListener('abort', finish); settle() } signal.addEventListener('abort', finish, { once: true }) void result.then(accept).catch(() => { if (!signal.aborted) this.failed() }).finally(finish) diff --git a/packages/client/ui-context-menu/src/index.ts b/packages/client/ui-context-menu/src/index.ts index 77258040c7..c639cbcea8 100644 --- a/packages/client/ui-context-menu/src/index.ts +++ b/packages/client/ui-context-menu/src/index.ts @@ -1,4 +1,14 @@ -/** Host Loader entry; menus belong to the Client. */ +/** Host Loader entry declaring the browser menu preparation budget; menus belong to the Client. */ +import z from '@deepseek-ai/schemastery' +import type { ContextMenuConfig } from './types.ts' + +/** Live preparation budget; the browser receives it through its synced Config. */ +export type Config = ContextMenuConfig + +/** Live preparation budget synced to the browser. */ +export const Config = z.object({ + resolutionTimeoutMs: z.natural().min(1).default(1000).volatile(), +}) /** Register the browser plugin without Host behavior. */ export function apply(): void {} diff --git a/packages/client/ui-context-menu/src/types.ts b/packages/client/ui-context-menu/src/types.ts new file mode 100644 index 0000000000..20e045cfeb --- /dev/null +++ b/packages/client/ui-context-menu/src/types.ts @@ -0,0 +1,8 @@ +/** Context-menu plugin configuration shared by the Host and Client faces; types only. */ +import type { Volatile } from '@deepseek-ai/cordis' + +/** Live preparation budget; the browser receives it through its synced Config. */ +export interface ContextMenuConfig { + /** Maximum time in milliseconds to prepare each contribution before omitting its pending actions. */ + resolutionTimeoutMs: Volatile +} diff --git a/packages/client/ui-context-menu/tests/button.client.spec.tsx b/packages/client/ui-context-menu/tests/button.client.spec.tsx index 9b381ff29b..7c4c46d9c5 100644 --- a/packages/client/ui-context-menu/tests/button.client.spec.tsx +++ b/packages/client/ui-context-menu/tests/button.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { act, cleanup, fireEvent } from '@testing-library/react' import { afterEach, expect, it, onTestFinished, vi } from 'vitest' import { SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime' @@ -35,7 +36,7 @@ it('shows late registered kinds without preparing actions and withdraws them wit ) const view = runtime.renderRoot() expect(view.queryByRole('button')).toBeNull() - const plugin = await runtime.mount({ inject, apply }) + const plugin = await runtime.mount({ inject, apply }, syncedConfig({ resolutionTimeoutMs: 1000 })) expect(view.queryByRole('button')).toBeNull() const resolve = vi.fn(() => new Promise(() => {})) const row = await runtime.mount({ inject: ['contextMenus'], apply: (ctx: Context) => { ctx.effect(() => ctx.contextMenus.register({ @@ -67,7 +68,7 @@ it('shows the label tooltip on the compact toolbar button but not on row buttons {renderFactorySlot('contextMenu.button', { target: target('header'), label: 'Header menu', size: 'sm' })} {renderFactorySlot('contextMenu.button', { target: target('row'), label: 'Row menu' })} ) - await runtime.mount({ inject, apply }) + await runtime.mount({ inject, apply }, syncedConfig({ resolutionTimeoutMs: 1000 })) await runtime.mount({ inject: ['contextMenus'], apply: (ctx: Context) => { ctx.effect(() => ctx.contextMenus.register({ id: 'header', target: 'header', order: 0, resolve: () => [], })) } }) @@ -99,7 +100,7 @@ it('toggles moved buttons by target identity, replaces other targets, and preser {renderSlot('shell.overlay', {})} }) - await runtime.mount({ inject, apply }) + await runtime.mount({ inject, apply }, syncedConfig({ resolutionTimeoutMs: 1000 })) await runtime.mount({ inject: ['contextMenus'], apply: (ctx: Context) => { ctx.effect(() => ctx.contextMenus.register({ id: 'header', target: 'header', order: 0, resolve: () => [{ id: 'open', label: 'Open' }], })) } }) @@ -170,7 +171,7 @@ it('keeps an open button expanded after its owner updates display metadata in th update = setCurrent return renderFactorySlot('contextMenu.button', { target: current, label: 'Entity menu' }) }) - await runtime.mount({ inject, apply }) + await runtime.mount({ inject, apply }, syncedConfig({ resolutionTimeoutMs: 1000 })) await runtime.mount({ inject: ['contextMenus'], apply: (ctx: Context) => { ctx.effect(() => ctx.contextMenus.register({ id: 'entity', target: 'entity', order: 0, resolve: () => [], })) } }) diff --git a/packages/client/ui-context-menu/tests/overlay.client.spec.tsx b/packages/client/ui-context-menu/tests/overlay.client.spec.tsx index b84e470bbe..718d3edad6 100644 --- a/packages/client/ui-context-menu/tests/overlay.client.spec.tsx +++ b/packages/client/ui-context-menu/tests/overlay.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { act, cleanup, fireEvent, render, waitFor } from '@testing-library/react' import { afterEach, expect, it, onTestFinished, vi } from 'vitest' import { bindSnapshotSelector, SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime' @@ -97,7 +98,7 @@ it('dispatches captured icon keys in rows, submenus and footers and retires rend runtime.slots.installLocale(locale) await runtime.root.declare({ 'shell.overlay': { kind: 'list', scope: 'root' } }, ({ renderSlot }) => <>{renderSlot('shell.overlay', {})}) - const menuPlugin = await runtime.mount({ inject, apply }) + const menuPlugin = await runtime.mount({ inject, apply }, syncedConfig({ resolutionTimeoutMs: 1000 })) const run = vi.fn() const contribution = await runtime.mount({ inject: ['contextMenus'], apply(ctx) { ctx.effect(() => ctx.contextMenus.register({ id: 'icons', target: 'session', order: 0, resolve: () => [ diff --git a/packages/client/ui-context-menu/tests/plugin.client.spec.ts b/packages/client/ui-context-menu/tests/plugin.client.spec.ts index 4d2ab784ba..81d8ebc835 100644 --- a/packages/client/ui-context-menu/tests/plugin.client.spec.ts +++ b/packages/client/ui-context-menu/tests/plugin.client.spec.ts @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import type { MenuAction } from '../src/client/types.ts' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { Context } from '@deepseek-ai/cordis' @@ -28,7 +29,7 @@ it('lets an external contribution open another menu and withdraws its actions wh }, } as never) ctx.provide('locale', { register: () => () => {}, bind: () => (key: string) => key } as never) - const menuFiber = ctx.plugin({ inject, apply }) + const menuFiber = ctx.plugin({ inject, apply }, syncedConfig({ resolutionTimeoutMs: 1000 })) await menuFiber.await() expect(hostApply).not.toThrow() const run = vi.fn() @@ -101,7 +102,8 @@ it('waits for metadata, toggles nearby repeated gestures, replaces occurrences, register: (entry: { store: ReturnType }) => { store = entry.store.create(); return () => {} }, } as never) ctx.provide('locale', { register: () => () => {}, bind: () => (key: string) => key } as never) - const fiber = ctx.plugin({ inject, apply }) + // No budget from the Host: preparation uses the 1000ms the Client used before the field moved to the Host. + const fiber = ctx.plugin({ inject, apply }, syncedConfig({})) await fiber.await() let finish!: (actions: readonly MenuAction[]) => void ctx.contextMenus.register({ target: 'pluginDocument', id: 'slow', order: 0, @@ -148,7 +150,7 @@ it('keeps trigger focus through replacement and ignores non-dismissal events and register: (entry: { inject: () => MenuOverlayInjected }) => { overlay = entry.inject(); return () => {} }, } as never) ctx.provide('locale', { register: () => () => {}, bind: () => (key: string) => key } as never) - const fiber = ctx.plugin({ inject, apply }) + const fiber = ctx.plugin({ inject, apply }, syncedConfig({ resolutionTimeoutMs: 1000 })) await fiber.await() const notify = ctx.contextMenus.notify.bind(ctx.contextMenus) ctx.contextMenus.register({ target: 'pluginDocument', id: 'plain', order: 0, resolve: () => [{ id: 'copy', label: 'Copy' }] }) @@ -194,7 +196,7 @@ it('leaves unbound keyboard gestures native', async () => { inject: () => () => {}, } as never) ctx.provide('locale', { register: () => () => {}, bind: () => (key: string) => key } as never) - const fiber = ctx.plugin({ inject, apply }) + const fiber = ctx.plugin({ inject, apply }, syncedConfig({ resolutionTimeoutMs: 1000 })) await fiber.await() try { const event = new KeyboardEvent('keydown', { key: 'ContextMenu', bubbles: true, cancelable: true }) diff --git a/packages/client/ui-context-menu/tests/registry.client.spec.ts b/packages/client/ui-context-menu/tests/registry.client.spec.ts index 20f77e808b..ea7c2ea7d0 100644 --- a/packages/client/ui-context-menu/tests/registry.client.spec.ts +++ b/packages/client/ui-context-menu/tests/registry.client.spec.ts @@ -175,7 +175,7 @@ describe('menu contribution lifecycle', () => { it('omits a provider that misses its deadline and ignores its late result', async () => { vi.useFakeTimers() - const failed = vi.fn(), registry = new MenuRegistry(failed, 50) + const failed = vi.fn(), registry = new MenuRegistry(failed, () => 50) const waiting = deferred() let signal!: AbortSignal registry.register({ id: 'slow', target: 'extension', order: 0, resolve: (_target, value) => { signal = value; return waiting.promise } }) diff --git a/packages/client/ui-context-menu/tests/trigger.client.spec.tsx b/packages/client/ui-context-menu/tests/trigger.client.spec.tsx index 507911379f..2af1690b61 100644 --- a/packages/client/ui-context-menu/tests/trigger.client.spec.tsx +++ b/packages/client/ui-context-menu/tests/trigger.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { act, cleanup, createEvent, fireEvent, render } from '@testing-library/react' import { afterEach, expect, it, onTestFinished, vi } from 'vitest' import { createPortal } from 'react-dom' @@ -85,7 +86,7 @@ it('injects the hook through the root Slot and withdraws both its prop and retai retained = useContextMenu().getTriggerProps(target('injected')) return }) - const plugin = await runtime.mount({ inject, apply }) + const plugin = await runtime.mount({ inject, apply }, syncedConfig({ resolutionTimeoutMs: 1000 })) const view = runtime.renderRoot() expect(received).toBe(true) act(() => { fireEvent.contextMenu(view.getByRole('button')) }) diff --git a/packages/client/ui-context-menu/tsconfig.json b/packages/client/ui-context-menu/tsconfig.json index e12f61a4c8..572b52f447 100644 --- a/packages/client/ui-context-menu/tsconfig.json +++ b/packages/client/ui-context-menu/tsconfig.json @@ -8,6 +8,9 @@ "src" ], "references": [ + { + "path": "../config" + }, { "path": "../../../vendor/cordis" }, diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index 89ea06d3e0..3ab67ca713 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -21,8 +21,8 @@ en: 4a094cd97426ad18 zh: 5faadddb7e2b0a43 /deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props: - en: 4919c08c24d2453b - zh: 45566252950a1ed1 + en: e06ba99fdd2f3e1c + zh: 0fb899d6cedb351a /deepseek-ai-dsh-client-ui-conversation/temporary-composer-entries: en: 59cd63057dfb6eeb zh: b2e2c86e810b7bb8 diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index 528c8e368c..acfb61d3f5 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -132,7 +132,7 @@ Clicking unused space inside an editable composer preserves its current caret or Each composer attempt carries its original occurrence time, gesture, delivery intent, and Session model/run-state snapshot through asynchronous command arbitration. The snapshot also records whether the Session is still blank and the Agent preset id the Session records. The ordinary-message notification fires once before reference serialization, including attachment-only submissions; handled or claimed commands do not notify. Snapshot and notification failures cannot block sending. On Desktop, the notification reports `send_button_click`, which carries `is_new_session` (true while the Session is blank) and `agent_preset`, the preset category: `creator` for `cordis`; `ptc`, `minimal`, and `standard` under their own ids; `other` for any other preset. `agent_preset` is omitted while the Session records no preset. Custom preset ids are not sent. -A default send waits for the Host: Enter captures the draft text, its reference chips, and its attachments in the attempt, and the composer enters `sending`, with the editor and attachment rail read-only and Send showing progress, until the Host accepts the prompt, as its receipt or an Inbox row carrying its request id shows, whichever arrives first. Only then do the draft, its attachments, the occurrence table, and the undo history clear in one transaction, before the echo renders; a refusal or failure returns the composer to `plain` with the draft and attachments unchanged, so one message is in flight at a time. When a read-only input phase ends with focus on the document body, desktop returns focus to the editor and mobile moves it to the composer card without reopening the keyboard. A control the user focused during that phase keeps focus. `sendSession` registers a Session submission echo (`session.beginSubmission`) with the delivery mode before serializing, preserving selected image and file order; Session publishes it in `pendingSubmissions` once the Host accepts the prompt and derives the placement from that mode and its running state at registration, so idle sends use the transcript, busy Queue sends use QueueDock, and busy Steer sends use the pending-steering surface. It then yields one paint and cites the staged receipts of files and uploaded images; an image without an upload, as in a continuable subagent's draft, is encoded through the browser's native `FileReader` data-URL path. Command submissions use the same receipts for generic files, so sending `/goal` or `/plan` never reads those browser files again. The prompt reuses the submission `requestId`; Session retires the echo once at its display handoff, correlated by that `rpcId`. Command submissions keep the frozen `submitting` phase. An observed retirement immediately exposes each image preview through the durable cache, replaces it with the canonical URL after fetching the admitted attachment, revokes each URL after its use ends, and releases file cards; an accepted prompt whose echo retires unobserved releases its attachments, and Session scope disposal releases the attachments of a message the Host has not accepted. Selected generic files, and the images of an ordinary Session's draft, enter one FIFO background-upload queue as soon as they are added, and Send waits until each has a receipt; `maxConcurrentFileUploads` defaults to two active Worker transports, the Conversation service retains queued and active operations plus byte progress across Session navigation, and removing a draft skips its queued transfer or aborts its active transport. Where the browser shell exposes `__DSH_HOST_PATHS__` (the Desktop application), dropped or pasted folders and dropped, picked, or pasted non-image files with a real path become `@path` chips; images keep uploading. Drag-and-drop and paste identify directories through the browser entry API; when that API is absent or returns no entry, pasted items retain ordinary file handling. The file picker cannot select directories. References require the `ui-reference` plugin and the original paths to remain readable by the model's file tools. Paths inside the workspace are relative; others remain absolute. The whole batch is validated before insertion, retains source order and selected text, and uses whitespace-separated, closed-quote mentions. A browser without the bridge refuses dropped or pasted folders; a Desktop folder without a reported path is rejected separately. Continuable subagents accept pasted and dropped PNG, JPEG, WebP, and GIF images with the same projected limits and send them inline, because the Host stages uploads only for ordinary Sessions; a batch containing a generic file, unsupported image format, or directory is refused before intake. Their sends register the same local echo; the continuation request carries the echo's `requestId`, which the Host records as the child message's `rpcId`. +A default send waits for the Host: Enter captures the draft text, its reference chips, and its attachments in the attempt, and the composer enters `sending`, with the editor and attachment rail read-only and Send showing progress, until the Host accepts the prompt, as its receipt or an Inbox row carrying its request id shows, whichever arrives first. Only then do the draft, its attachments, the occurrence table, and the undo history clear in one transaction, before the echo renders; a refusal or failure returns the composer to `plain` with the draft and attachments unchanged, so one message is in flight at a time. When a read-only input phase ends with focus on the document body, desktop returns focus to the editor and mobile moves it to the composer card without reopening the keyboard. A control the user focused during that phase keeps focus. `sendSession` registers a Session submission echo (`session.beginSubmission`) with the delivery mode before serializing, preserving selected image and file order; Session publishes it in `pendingSubmissions` once the Host accepts the prompt and derives the placement from that mode and its running state at registration, so idle sends use the transcript, busy Queue sends use QueueDock, and busy Steer sends use the pending-steering surface. It then yields one paint and cites the staged receipts of files and uploaded images; an image without an upload, as in a continuable subagent's draft, is encoded through the browser's native `FileReader` data-URL path. Command submissions use the same receipts for generic files, so sending `/goal` or `/plan` never reads those browser files again. The prompt reuses the submission `requestId`; Session retires the echo once at its display handoff, correlated by that `rpcId`. Command submissions keep the frozen `submitting` phase. An observed retirement immediately exposes each image preview through the durable cache, replaces it with the canonical URL after fetching the admitted attachment, revokes each URL after its use ends, and releases file cards; an accepted prompt whose echo retires unobserved releases its attachments, and Session scope disposal releases the attachments of a message the Host has not accepted. Selected generic files, and the images of an ordinary Session's draft, enter one FIFO background-upload queue as soon as they are added, and Send waits until each has a receipt; `maxConcurrentFileUploads`, a volatile field of the Host entry's Config, defaults to two active Worker transports and a raised value starts queued transfers at once, the Conversation service retains queued and active operations plus byte progress across Session navigation, and removing a draft skips its queued transfer or aborts its active transport. Where the browser shell exposes `__DSH_HOST_PATHS__` (the Desktop application), dropped or pasted folders and dropped, picked, or pasted non-image files with a real path become `@path` chips; images keep uploading. Drag-and-drop and paste identify directories through the browser entry API; when that API is absent or returns no entry, pasted items retain ordinary file handling. The file picker cannot select directories. References require the `ui-reference` plugin and the original paths to remain readable by the model's file tools. Paths inside the workspace are relative; others remain absolute. The whole batch is validated before insertion, retains source order and selected text, and uses whitespace-separated, closed-quote mentions. A browser without the bridge refuses dropped or pasted folders; a Desktop folder without a reported path is rejected separately. Continuable subagents accept pasted and dropped PNG, JPEG, WebP, and GIF images with the same projected limits and send them inline, because the Host stages uploads only for ordinary Sessions; a batch containing a generic file, unsupported image format, or directory is refused before intake. Their sends register the same local echo; the continuation request carries the echo's `requestId`, which the Host records as the child message's `rpcId`. Every mounted composer, including a subagent conversation open in the right Sidebar, joins one document-level paste route. A paste whose clipboard carries files, while focus is outside any input, text area, or editable element, enters the composer that most recently held focus, or the main Conversation's composer before any other composer has held focus or while the focused one cannot accept files; a paste inside a focused editor stays with that editor, and clipboard text without files is never inserted this way. A composer in a hidden or inert subtree, such as a collapsed Sidebar or an unselected tab, is never addressed, and while a modal dialog or menu is open only a composer inside it can be. When no addressable composer can accept files, the paste keeps the browser's default handling. diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index c43343c7be..f727eeb1cd 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -132,7 +132,7 @@ Session 首次绑定或缓存的 Session 成为 current 时,shell 会在渲染 每次输入框提交都携带原始发生时间、操作来源、投递意图以及会话模型和运行状态快照,贯穿异步命令裁决。快照还记录会话是否仍为空白,以及会话记录的 Agent preset id。普通消息通知在引用序列化前发出一次,纯附件提交也遵循这一规则;已处理或认领的命令不发出通知。快照读取与通知消费异常不能阻断发送。在桌面端,该通知报告 `send_button_click`,携带 `is_new_session`(会话为空白时为 true)和表示 preset 类别的 `agent_preset`:`cordis` 记为 `creator`;`ptc`、`minimal` 与 `standard` 沿用各自的 id;其他 preset 记为 `other`。会话未记录 preset 时省略 `agent_preset`。不发送自定义 preset 的 id。 -默认发送等待 Host 接收:Enter 把草稿文字、引用胶囊和附件一起记入本次 attempt,composer 进入 `sending`,编辑器和附件栏只读,Send 显示发送中,直到 Host 接收该提示词(以回执或带有该请求 id 的 Inbox 行为准,先到者生效)。之后才在回显渲染之前、在同一事务里清空草稿、其附件、occurrence 表和撤销历史;被拒绝或失败时 composer 回到 `plain`,草稿和附件保持不变,因此同一时刻只有一条消息在途。只读输入阶段结束时,如果焦点停在页面 body 上,桌面端将焦点恢复到编辑器,移动端则将焦点移到输入卡片,避免重新弹出键盘。用户在此期间聚焦的其他控件会保留焦点。`sendSession` 在序列化之前用投递模式注册 Session 提交回显(`session.beginSubmission`),保留图片与文件的选择顺序;Host 接收提示词后,Session 才在 `pendingSubmissions` 中公开它,并按注册时的模式与运行状态推导位置,因此空闲发送进入 transcript(文本记录),繁忙时 Queue 进入 QueueDock,繁忙时 Steer 进入 pending-steering 区域。随后让出一帧,文件和已上传的图片引用已暂存凭证;没有上传的图片(例如 continuable 子代理草稿里的图片)经浏览器原生 `FileReader` data-URL 路径编码。命令提交也用同一凭证表示通用文件,因此发送 `/goal` 或 `/plan` 时不会再次读取这些浏览器文件。提示词复用提交 `requestId`;Session 按同一 `rpcId` 关联展示接管,并仅退休回显一次。命令提交保持冻结的 `submitting` 阶段。回显以 observed 退休时,durable 图片缓存立即公开每个预览 URL,读取 admitted 附件后用规范化 URL 替换预览,并在各 URL 停止使用后撤销,同时释放文件卡;已被接收但回显未被观察到就退休的提示词会释放其附件,Session scope 销毁时会释放尚未被 Host 接收的消息的附件。选中的通用文件以及普通 Session 草稿里的图片在加入时就进入同一个先进先出的后台上传队列,发送会等到每一项都取得凭证;`maxConcurrentFileUploads` 默认允许两个 Worker transport 同时运行,Conversation 服务在切换 Session 时继续持有排队和运行中的传输操作及字节进度,移除草稿会跳过排队中的传输或中止正在运行的传输。浏览器 shell 暴露 `__DSH_HOST_PATHS__` 时(桌面应用),拖入或粘贴的文件夹以及拖入、选择或粘贴的带真实路径的非图片文件会成为 `@路径` chip;图片仍然上传。拖放和粘贴通过浏览器 entry API 识别目录;该 API 不可用或没有返回 entry 时,粘贴项沿用普通文件处理。文件选择器不能选择目录。引用需要启用 `ui-reference` 插件,原路径也必须仍可由模型的文件工具读取。工作区内的路径使用相对形式,其他路径保留绝对形式。整批文件先校验再插入,保留来源顺序和已选中的文字,引用之间有空白分隔,含空格的路径使用闭合引号。没有该桥的浏览器会拒绝拖入或粘贴的文件夹,桌面端无法获取文件夹路径时单独报错。continuable 子代理允许粘贴和拖入 PNG、JPEG、WebP、GIF 图片,沿用相同的投影限制并以内联方式发送,因为 Host 只为普通 Session 暂存上传;包含通用文件、不支持的图片格式或目录的批次会在进入草稿前整批拒绝。它们的发送同样注册本地回显;continuation 请求携带回显的 `requestId`,Host 把它记录为子会话消息的 `rpcId`。 +默认发送等待 Host 接收:Enter 把草稿文字、引用胶囊和附件一起记入本次 attempt,composer 进入 `sending`,编辑器和附件栏只读,Send 显示发送中,直到 Host 接收该提示词(以回执或带有该请求 id 的 Inbox 行为准,先到者生效)。之后才在回显渲染之前、在同一事务里清空草稿、其附件、occurrence 表和撤销历史;被拒绝或失败时 composer 回到 `plain`,草稿和附件保持不变,因此同一时刻只有一条消息在途。只读输入阶段结束时,如果焦点停在页面 body 上,桌面端将焦点恢复到编辑器,移动端则将焦点移到输入卡片,避免重新弹出键盘。用户在此期间聚焦的其他控件会保留焦点。`sendSession` 在序列化之前用投递模式注册 Session 提交回显(`session.beginSubmission`),保留图片与文件的选择顺序;Host 接收提示词后,Session 才在 `pendingSubmissions` 中公开它,并按注册时的模式与运行状态推导位置,因此空闲发送进入 transcript(文本记录),繁忙时 Queue 进入 QueueDock,繁忙时 Steer 进入 pending-steering 区域。随后让出一帧,文件和已上传的图片引用已暂存凭证;没有上传的图片(例如 continuable 子代理草稿里的图片)经浏览器原生 `FileReader` data-URL 路径编码。命令提交也用同一凭证表示通用文件,因此发送 `/goal` 或 `/plan` 时不会再次读取这些浏览器文件。提示词复用提交 `requestId`;Session 按同一 `rpcId` 关联展示接管,并仅退休回显一次。命令提交保持冻结的 `submitting` 阶段。回显以 observed 退休时,durable 图片缓存立即公开每个预览 URL,读取 admitted 附件后用规范化 URL 替换预览,并在各 URL 停止使用后撤销,同时释放文件卡;已被接收但回显未被观察到就退休的提示词会释放其附件,Session scope 销毁时会释放尚未被 Host 接收的消息的附件。选中的通用文件以及普通 Session 草稿里的图片在加入时就进入同一个先进先出的后台上传队列,发送会等到每一项都取得凭证;`maxConcurrentFileUploads` 是 Host 条目 Config 中的 volatile 字段,默认允许两个 Worker transport 同时运行,调高后立即启动排队中的传输,Conversation 服务在切换 Session 时继续持有排队和运行中的传输操作及字节进度,移除草稿会跳过排队中的传输或中止正在运行的传输。浏览器 shell 暴露 `__DSH_HOST_PATHS__` 时(桌面应用),拖入或粘贴的文件夹以及拖入、选择或粘贴的带真实路径的非图片文件会成为 `@路径` chip;图片仍然上传。拖放和粘贴通过浏览器 entry API 识别目录;该 API 不可用或没有返回 entry 时,粘贴项沿用普通文件处理。文件选择器不能选择目录。引用需要启用 `ui-reference` 插件,原路径也必须仍可由模型的文件工具读取。工作区内的路径使用相对形式,其他路径保留绝对形式。整批文件先校验再插入,保留来源顺序和已选中的文字,引用之间有空白分隔,含空格的路径使用闭合引号。没有该桥的浏览器会拒绝拖入或粘贴的文件夹,桌面端无法获取文件夹路径时单独报错。continuable 子代理允许粘贴和拖入 PNG、JPEG、WebP、GIF 图片,沿用相同的投影限制并以内联方式发送,因为 Host 只为普通 Session 暂存上传;包含通用文件、不支持的图片格式或目录的批次会在进入草稿前整批拒绝。它们的发送同样注册本地回显;continuation 请求携带回显的 `requestId`,Host 把它记录为子会话消息的 `rpcId`。 每个已挂载的 composer(包括在右侧栏打开的子代理对话)都加入同一条文档级粘贴路由。焦点不在任何输入框、文本区域或可编辑元素内时,剪贴板带有文件的粘贴会进入最近一次获得焦点的 composer;在其他 composer 获得焦点之前,或最近聚焦的 composer 当前无法接收文件时,则进入主 Conversation 的 composer。已聚焦编辑器内的粘贴仍由该编辑器处理,不含文件的剪贴板文字不会经此插入。位于隐藏或 inert 子树中的 composer(例如折叠的侧栏或未选中的标签页)不会成为目标;打开模态对话框或菜单时,只有其中的 composer 可以成为目标。没有可作为目标的 composer 能接收文件时,粘贴保留浏览器的默认处理。 diff --git a/packages/client/ui-conversation/package.json b/packages/client/ui-conversation/package.json index abfcd2fdab..737e3aa960 100644 --- a/packages/client/ui-conversation/package.json +++ b/packages/client/ui-conversation/package.json @@ -102,7 +102,8 @@ "@deepseek-ai/dsh-session-projection": "workspace:*", "@deepseek-ai/dsh-brand": "workspace:*", "zod": "4.6.6", - "@deepseek-ai/dsh-client-ui-context-menu": "workspace:*" + "@deepseek-ai/dsh-client-ui-context-menu": "workspace:*", + "@deepseek-ai/dsh-client-config": "workspace:*" }, "files": [ "locale/*.json", diff --git a/packages/client/ui-conversation/src/client/apply.ts b/packages/client/ui-conversation/src/client/apply.ts index 4f292f0ece..b7b32009ed 100644 --- a/packages/client/ui-conversation/src/client/apply.ts +++ b/packages/client/ui-conversation/src/client/apply.ts @@ -2,7 +2,8 @@ import type {} from '@deepseek-ai/dsh-client-ui-context-menu/client' /** Registers the target-neutral Conversation assembly, shell, input, and docks. */ import type {} from '@deepseek-ai/dsh-client-product-analytics/client' import type { Context } from '@deepseek-ai/cordis' -import z from '@deepseek-ai/schemastery' +import type { SyncedConfig } from '@deepseek-ai/dsh-client-config/types' +import type { ConversationConfig } from '../types.ts' import type { ISessions, SessionBinding } from '@deepseek-ai/dsh-api-session-controller/client' import { IconPaperclipOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' import { createSnapshotStore, type BoundActions } from '@deepseek-ai/dsh-client-store' @@ -67,16 +68,6 @@ export const inject = [ 'slots', 'sessions', 'fileUpload', 'uiSession', 'uiSession.sessionStatus', 'uiWorkspace', 'locale', 'configForms', ] -/** Conversation runtime configuration. */ -export interface Config { - /** Maximum generic-file uploads allowed to run concurrently in browser Workers. */ - maxConcurrentFileUploads?: number -} - -/** Validated Conversation runtime configuration. */ -export const Config: z = z.object({ - maxConcurrentFileUploads: z.natural().min(1).default(2), -}) // Stable no-session sources keep the renderer's observable-hook cache and // hook order unchanged across current-Session transitions. @@ -158,12 +149,12 @@ function concreteConversation(ctx: Context): ConversationController { /** * Mount the Conversation core and target-neutral presentation. * @param ctx - Client root context. + * @param config - Host-synced live configuration. */ -export function apply(ctx: Context, config: Config = Config({})): void { +export function apply(ctx: Context, config: SyncedConfig): void { const sessions = ctx.sessions const slots = ctx.slots - // Schemastery's field default is materialized before Cordis calls apply. - const maxConcurrentFileUploads = config.maxConcurrentFileUploads as number + const fileUploadLimit = config.maxConcurrentFileUploads const workspaceNavigation = ctx.get('uiWorkspace') as WorkspaceNavigation const uiConversation = new UiConversation(ctx, sessions) uiConversation.userText.register(sessionReferenceRule) @@ -602,7 +593,7 @@ export function apply(ctx: Context, config: Config = Config({})): void { ctx.plugin(ConversationController, { input: inputHub, blocks: composerBlocks, - maxConcurrentFileUploads, + maxConcurrentFileUploads: fileUploadLimit, }) ctx.plugin(todoDockEntry) ctx.plugin(queueDockEntry) diff --git a/packages/client/ui-conversation/src/client/index.ts b/packages/client/ui-conversation/src/client/index.ts index 8a1b95e941..b2ce918f76 100644 --- a/packages/client/ui-conversation/src/client/index.ts +++ b/packages/client/ui-conversation/src/client/index.ts @@ -24,8 +24,7 @@ export type { UserTextDocumentInput, UserTextEvaluator, UserTextId, UserTextNode, UserTextRule, UserTextTransformContext, } from './contract/user-text.ts' export type { UserTextRegistry } from './conversation/user-text-registry.ts' -export { apply, Config, inject } from './apply.ts' -export type { Config as ConversationConfig } from './apply.ts' +export { apply, inject } from './apply.ts' export { UiConversation } from './conversation/assembly.ts' export type { ConversationBinding } from './conversation/assembly.ts' export type { ConversationGroupRegistry } from './conversation/group-registry.ts' diff --git a/packages/client/ui-conversation/src/client/service.ts b/packages/client/ui-conversation/src/client/service.ts index 98454ba0f0..e4eb324030 100644 --- a/packages/client/ui-conversation/src/client/service.ts +++ b/packages/client/ui-conversation/src/client/service.ts @@ -20,7 +20,7 @@ import type {} from '@deepseek-ai/dsh-client-file-upload/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { FileAttachmentRef, ImageMediaType } from '@deepseek-ai/dsh-attachment' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' -import type { SnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { ObservableSnapshot, SnapshotStore } from '@deepseek-ai/dsh-client-store' import type { ComposerAttachment, ComposerFileAttachment, ComposerImageAttachment, DraftFileUpload, } from './contract/slots.ts' @@ -149,6 +149,9 @@ export class UnsupportedImageMediaTypeError extends Error { } } +/** Upload concurrency while the Host sends no limit; the value the Client used before the field moved to the Host. */ +const ABSENT_UPLOAD_LIMIT = 2 + /** Scope-addressed conversation service (root singleton, provided as `conversation`). */ export class ConversationController extends Service implements IConversation { /** The per-session input machine registry (SessionInputResolver face). */ @@ -172,7 +175,7 @@ export class ConversationController extends Service implements IConversation { readonly settle: () => void }> = [] private activeFileUploads = 0 - private readonly maxConcurrentFileUploads: number + private readonly maxConcurrentFileUploads: ObservableSnapshot /** * @param ctx - owning root context (the plugin apply context; the service @@ -184,12 +187,14 @@ export class ConversationController extends Service implements IConversation { constructor(ctx: Context, config: { input: SessionInputResolver blocks: ComposerBlocks - maxConcurrentFileUploads: number + /** Live upload concurrency limit, absent until the Host sends one; a raised limit starts queued uploads at once. */ + maxConcurrentFileUploads: ObservableSnapshot }) { super(ctx, 'conversation') this.input = config.input this.blocks = config.blocks this.maxConcurrentFileUploads = config.maxConcurrentFileUploads + ctx.effect(() => config.maxConcurrentFileUploads.subscribe(() => { this.pumpFileUploads() }), 'conversation: upload concurrency') ctx.effect(() => async () => { const operations = [...this.fileUploadOperations.values()] for (const operation of operations) operation.controller.abort() @@ -458,7 +463,7 @@ export class ConversationController extends Service implements IConversation { /** Start queued upload Workers until the configured concurrency is occupied. */ private pumpFileUploads(): void { - while (this.activeFileUploads < this.maxConcurrentFileUploads) { + while (this.activeFileUploads < (this.maxConcurrentFileUploads.getSnapshot() ?? ABSENT_UPLOAD_LIMIT)) { const task = this.fileUploadQueue.shift() if (task === undefined) return this.activeFileUploads += 1 diff --git a/packages/client/ui-conversation/src/index.ts b/packages/client/ui-conversation/src/index.ts index 90c4366a1a..23b557467b 100644 --- a/packages/client/ui-conversation/src/index.ts +++ b/packages/client/ui-conversation/src/index.ts @@ -1,9 +1,9 @@ /** Browser conversation preferences. */ import type {} from '@deepseek-ai/dsh-settings' -import type { Volatile, Context } from '@deepseek-ai/cordis' -import type { BusyEnterBehavior } from './submission-settings.ts' +import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' +import type { ConversationConfig } from './types.ts' import { BUSY_ENTER_FIELD } from './submission-settings.ts' import { ConversationSettingsFields } from './submission-settings.ts' @@ -13,15 +13,13 @@ export { DEFAULT_BUSY_ENTER_BEHAVIOR, type BusyEnterBehavior, type ConversationSettings, } from './submission-settings.ts' -/** Runtime preferences projected to the browser. */ -export interface Config { - /** Enter key behavior while a turn is running. */ - busyEnter: Volatile -} +/** Live preferences; the browser receives every field through its synced Config. */ +export type Config = ConversationConfig /** Live preferences projected to the browser. */ export const Config = z.object({ [BUSY_ENTER_FIELD]: ConversationSettingsFields[BUSY_ENTER_FIELD].volatile(), + maxConcurrentFileUploads: z.natural().min(1).default(2).volatile(), }) /** Register browser conversation preferences. diff --git a/packages/client/ui-conversation/src/types.ts b/packages/client/ui-conversation/src/types.ts new file mode 100644 index 0000000000..e7138d1959 --- /dev/null +++ b/packages/client/ui-conversation/src/types.ts @@ -0,0 +1,11 @@ +/** Conversation plugin configuration shared by the Host and Client faces; types only. */ +import type { Volatile } from '@deepseek-ai/cordis' +import type { BusyEnterBehavior } from './submission-settings.ts' + +/** Live preferences; the browser receives every field through its synced Config. */ +export interface ConversationConfig { + /** Enter key behavior while a turn is running. */ + busyEnter: Volatile + /** Maximum generic-file uploads allowed to run concurrently in browser Workers. */ + maxConcurrentFileUploads: Volatile +} diff --git a/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx b/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx index e6384343ef..b5d57c4efd 100644 --- a/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx +++ b/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { apply as applyMenus, inject as injectMenus } from '@deepseek-ai/dsh-client-ui-context-menu/client' import { render, cleanup } from '@testing-library/react' import { $getRoot, $isTextNode, PASTE_COMMAND } from 'lexical' @@ -110,7 +111,7 @@ async function bench(renderQuote = false) { runtime.ctx.provide('locale', locale) runtime.slots.installLocale(locale) runtime.ctx.provide('shortcuts', { catalog: createSnapshotStore([]) }) - await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }, syncedConfig({ resolutionTimeoutMs: 1000 })) await runtime.root.declare({ 'main': { kind: 'keyed', scope: 'root' }, 'quote-probe': { kind: 'single', scope: 'session' }, @@ -120,7 +121,7 @@ async function bench(renderQuote = false) { ) : null) - const feature = await runtime.mount({ inject: [...inject], apply }) + const feature = await runtime.mount({ inject: [...inject], apply }, syncedConfig({ busyEnter: 'queue', maxConcurrentFileUploads: 2 })) if (renderQuote) await runtime.mount(messageQuotes) runtime.renderRoot() const entryOf = (key: 'main.conversation' | 'conversation.session' | 'conversation.session.header' | 'conversation.composer.bar') => diff --git a/packages/client/ui-conversation/tests/apply-wiring.client.spec.tsx b/packages/client/ui-conversation/tests/apply-wiring.client.spec.tsx index 154d31ec9f..907b6ec015 100644 --- a/packages/client/ui-conversation/tests/apply-wiring.client.spec.tsx +++ b/packages/client/ui-conversation/tests/apply-wiring.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { apply as applyMenus, inject as injectMenus } from '@deepseek-ai/dsh-client-ui-context-menu/client' import { describe, expect, it, vi } from 'vitest' import { @@ -27,14 +28,14 @@ async function bench(options: { declareConversation?: boolean } = {}) { runtime.ctx.provide('locale', locale) runtime.slots.installLocale(locale) runtime.ctx.provide('shortcuts', { catalog: createSnapshotStore([]) }) - await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }, syncedConfig({ resolutionTimeoutMs: 1000 })) if (options.declareConversation !== false) { await runtime.root.declare({ 'main': { kind: 'keyed', scope: 'root' }, 'settings.general.item': { kind: 'list', scope: 'root' }, }, (_props: { renderSlot?: unknown }) => null) } - const feature = await runtime.mount({ inject: [...inject], apply }) + const feature = await runtime.mount({ inject: [...inject], apply }, syncedConfig({ busyEnter: 'queue', maxConcurrentFileUploads: 2 })) if (options.declareConversation !== false) runtime.renderRoot() return { runtime, feature, developerTools } } diff --git a/packages/client/ui-conversation/tests/assembly-surfaces.client.spec.tsx b/packages/client/ui-conversation/tests/assembly-surfaces.client.spec.tsx index c8e96efdbc..b2506a1eab 100644 --- a/packages/client/ui-conversation/tests/assembly-surfaces.client.spec.tsx +++ b/packages/client/ui-conversation/tests/assembly-surfaces.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { apply as applyMenus, inject as injectMenus } from '@deepseek-ai/dsh-client-ui-context-menu/client' /** Conversation assembly acceptance independent of Tool presentation. */ import './control-row-dom.ts' @@ -88,7 +89,7 @@ async function bench(opts?: { blank?: boolean }) { runtime.ctx.provide('locale', locale) runtime.slots.installLocale(locale) runtime.ctx.provide('shortcuts', { catalog: createSnapshotStore([]) }) - await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }, syncedConfig({ resolutionTimeoutMs: 1000 })) await runtime.sessions.add({ id: SID, summary: { title: 'S', displayTitle: 'S', cwd: '/proj' }, @@ -100,7 +101,7 @@ async function bench(opts?: { blank?: boolean }) { }) openSession(SID) await runtime.root.declare(LAYOUT_CHILDREN, AppRoot) - await runtime.mount({ inject: [...inject], apply }) + await runtime.mount({ inject: [...inject], apply }, syncedConfig({ busyEnter: 'queue', maxConcurrentFileUploads: 2 })) return runtime } @@ -113,9 +114,9 @@ describe('resident composer', () => { runtime.ctx.provide('locale', locale) runtime.slots.installLocale(locale) runtime.ctx.provide('shortcuts', { catalog: createSnapshotStore([]) }) - await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }, syncedConfig({ resolutionTimeoutMs: 1000 })) await runtime.root.declare(LAYOUT_CHILDREN, AppRoot) - await runtime.mount({ inject: [...inject], apply }) + await runtime.mount({ inject: [...inject], apply }, syncedConfig({ busyEnter: 'queue', maxConcurrentFileUploads: 2 })) runtime.slots.register({ name: 'conversation.hero.workspace' }, WorkspaceProbe) const view = runtime.renderRoot() const textarea = view.container.querySelector('[data-composer-input]') @@ -142,12 +143,12 @@ describe('resident composer', () => { runtime.ctx.provide('locale', locale) runtime.slots.installLocale(locale) runtime.ctx.provide('shortcuts', { catalog: createSnapshotStore([]) }) - await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }, syncedConfig({ resolutionTimeoutMs: 1000 })) await runtime.workspaces.update((draft) => { draft.items = [{ workspaceId: 'w1', title: 'Proj', path: '/proj', sessionIds: [SID] }] as never }) await runtime.root.declare(LAYOUT_CHILDREN, AppRoot) - await runtime.mount({ inject: [...inject], apply }) + await runtime.mount({ inject: [...inject], apply }, syncedConfig({ busyEnter: 'queue', maxConcurrentFileUploads: 2 })) runtime.slots.register({ name: 'conversation.hero.workspace' }, WorkspaceProbe) const view = runtime.renderRoot() @@ -211,7 +212,7 @@ describe('prompt rejection through the assembled composer', () => { runtime.ctx.provide('locale', locale) runtime.slots.installLocale(locale) runtime.ctx.provide('shortcuts', { catalog: createSnapshotStore([]) }) - await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }, syncedConfig({ resolutionTimeoutMs: 1000 })) const prompt = vi.fn(async () => ({ ok: false, error: new RemoteError('session/agent-busy', 'prompt rejected before acceptance', { reason: 'busy' }), @@ -223,7 +224,7 @@ describe('prompt rejection through the assembled composer', () => { }) openSession(SID) await runtime.root.declare(LAYOUT_CHILDREN, AppRoot) - await runtime.mount({ inject: [...inject], apply }) + await runtime.mount({ inject: [...inject], apply }, syncedConfig({ busyEnter: 'queue', maxConcurrentFileUploads: 2 })) const view = runtime.renderRoot() const composer = view.container.querySelector('[data-composer-input]')! diff --git a/packages/client/ui-conversation/tests/config.host.spec.ts b/packages/client/ui-conversation/tests/config.host.spec.ts index 25420eff00..5eb8088838 100644 --- a/packages/client/ui-conversation/tests/config.host.spec.ts +++ b/packages/client/ui-conversation/tests/config.host.spec.ts @@ -18,9 +18,11 @@ describe('ui-conversation host', () => { await ctx.plugin(SessionProjectionRegistry) const configuration = await liveConfig(ctx, HostPlugin) const { fiber } = configuration - expect(plainConfig(configuration.fiber.effectiveConfig)).toEqual({ busyEnter: DEFAULT_BUSY_ENTER_BEHAVIOR }) + expect(plainConfig(configuration.fiber.effectiveConfig)).toEqual({ + busyEnter: DEFAULT_BUSY_ENTER_BEHAVIOR, maxConcurrentFileUploads: 2, + }) await configuration.update({ busyEnter: 'steer' }) - expect(plainConfig(configuration.fiber.effectiveConfig)).toEqual({ busyEnter: 'steer' }) + expect(plainConfig(configuration.fiber.effectiveConfig)).toEqual({ busyEnter: 'steer', maxConcurrentFileUploads: 2 }) await expect(configuration.update({ busyEnter: 'invalid' })).rejects.toThrow() await fiber.dispose() }) diff --git a/packages/client/ui-conversation/tests/draft-attachment-retention.client.spec.ts b/packages/client/ui-conversation/tests/draft-attachment-retention.client.spec.ts index f758d2def7..df098003bb 100644 --- a/packages/client/ui-conversation/tests/draft-attachment-retention.client.spec.ts +++ b/packages/client/ui-conversation/tests/draft-attachment-retention.client.spec.ts @@ -3,6 +3,7 @@ // a removed Session releases them, and a page unload reports what it discarded. import { AttachmentId } from '@deepseek-ai/dsh-attachment' import { brandString } from '@deepseek-ai/dsh-brand' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import type { FileUploadValue } from '@deepseek-ai/dsh-client-file-upload/client' import { makeTranslate, SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime' import type { SessionId } from '@deepseek-ai/dsh-session/types' @@ -59,7 +60,7 @@ async function bench(prepare?: () => void) { await runtime.ctx.plugin(ConversationController, { input: hub, blocks: new ComposerBlockRegistry(), - maxConcurrentFileUploads: 2, + maxConcurrentFileUploads: createSnapshotStore(2), }).await() const root = runtime.ctx.get('conversation') as ConversationController const shellNow = () => hub.shellFor(runtime.sessions.binding(SESSION)!) diff --git a/packages/client/ui-conversation/tests/service-orchestration.client.spec.ts b/packages/client/ui-conversation/tests/service-orchestration.client.spec.ts index 9b93ef4240..51f14c108a 100644 --- a/packages/client/ui-conversation/tests/service-orchestration.client.spec.ts +++ b/packages/client/ui-conversation/tests/service-orchestration.client.spec.ts @@ -3,6 +3,7 @@ // TestSessions mints tagged scopes through the production createScope, so the // service's scopeOf/binding path runs against production resolution (no local // tag probe). +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import type { UserMessage } from '@deepseek-ai/dsh-llm/types' import type { MessageId } from '@deepseek-ai/dsh-llm/types' import { Context } from '@deepseek-ai/cordis' @@ -31,7 +32,7 @@ const UPLOAD_IMAGES = true /** `createDrafts` mode of a draft whose images travel inline, as a subagent continuation's do. */ const INLINE_IMAGES = false -async function bench(maxConcurrentFileUploads = 2) { +async function bench(maxConcurrentFileUploads: number | 'absent' = 2) { const runtime = await SlotTestRuntime.create() runtime.fileUpload.upload = (sessionId: SessionId, ...args: unknown[]) => { const session = runtime.sessions.behavior(sessionId) as { @@ -62,16 +63,17 @@ async function bench(maxConcurrentFileUploads = 2) { // config.input is required (the apply shares its hub with the inject // factories); the bench passes its own instance explicitly. const hub = new InputHub(runtime.ctx, makeTranslate(zh, {})) + const uploadLimit = createSnapshotStore(maxConcurrentFileUploads === 'absent' ? undefined : maxConcurrentFileUploads) const fiber = runtime.ctx.plugin(ConversationController, { input: hub, blocks: new ComposerBlockRegistry(), - maxConcurrentFileUploads, + maxConcurrentFileUploads: uploadLimit, }) await fiber.await() const root = runtime.ctx.get('conversation') as ConversationController const scoped = runtime.sessions.scope('s1')!.get('conversation') as ConversationController const shell = hub.shellFor(runtime.sessions.binding('s1')!) - return { runtime, fiber, root, scoped, hub, shell, prompt, updateQueue, cancel, loadOlder, reference } + return { runtime, fiber, root, scoped, hub, shell, prompt, updateQueue, cancel, loadOlder, reference, uploadLimit } } describe('ConversationController', () => { @@ -320,7 +322,8 @@ describe('ConversationController', () => { }) it('bounds upload Workers, advances on settlement, and skips a queued file removed by the user', async () => { - const b = await bench(2) + // With no limit from the Host, two uploads run at once, as before the limit moved to the Host. + const b = await bench('absent') const session = b.runtime.sessions.binding('s1')!.session type UploadResult = { ok: true @@ -369,6 +372,21 @@ describe('ConversationController', () => { await b.runtime.dispose() }) + it('starts a queued upload at once when the Host raises the upload limit', async () => { + const b = await bench(2) + const session = b.runtime.sessions.binding('s1')!.session + const uploadFile = vi.fn((_data: Uint8Array, _name?: string, signal?: AbortSignal) => new Promise((_resolve, reject) => { + signal?.addEventListener('abort', () => { reject(new Error('upload aborted')) }, { once: true }) + })) + ;(session as { uploadFile?: unknown }).uploadFile = uploadFile + b.root.createDrafts(session.sessionId, ['one', 'two', 'three'].map(name => + new File([Uint8Array.of(1)], `${name}.txt`, { type: 'text/plain' })), UPLOAD_IMAGES) + await vi.waitFor(() => { expect(uploadFile).toHaveBeenCalledTimes(2) }) + b.uploadLimit.set(3) + await vi.waitFor(() => { expect(uploadFile).toHaveBeenCalledTimes(3) }) + await b.runtime.dispose() + }) + it('keeps one upload alive and observable while another Session is open', async () => { const b = await bench() const session = b.runtime.sessions.binding('s1')!.session @@ -606,7 +624,7 @@ describe('ConversationController', () => { await bare.plugin(ConversationController, { input: new InputHub(bare, makeTranslate(zh, {})), blocks: new ComposerBlockRegistry(), - maxConcurrentFileUploads: 2, + maxConcurrentFileUploads: createSnapshotStore(2), }).await() const orphan = bare.get('conversation') as ConversationController await expect(orphan.send('x')).rejects.toThrow(/sessions service unavailable/) diff --git a/packages/client/ui-conversation/tests/stop-shortcut.client.spec.ts b/packages/client/ui-conversation/tests/stop-shortcut.client.spec.ts index f1f93856f1..4bb28dc0c1 100644 --- a/packages/client/ui-conversation/tests/stop-shortcut.client.spec.ts +++ b/packages/client/ui-conversation/tests/stop-shortcut.client.spec.ts @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { afterEach, describe, expect, it, vi } from 'vitest' import type { SessionPendingInteractionBase } from '@deepseek-ai/dsh-client-ui-session/client' import type { Shortcuts, ShortcutContext, ShortcutGesture } from '@deepseek-ai/dsh-client-shortcuts/client' @@ -30,7 +31,7 @@ async function bench() { await reference.ready const hub = new InputHub(runtime.ctx, makeTranslate(zh, {})) const fiber = runtime.ctx.plugin(ConversationController, { - input: hub, blocks: new ComposerBlockRegistry(), maxConcurrentFileUploads: 2, + input: hub, blocks: new ComposerBlockRegistry(), maxConcurrentFileUploads: createSnapshotStore(2), }) await fiber.await() const conversation = new UiConversation(runtime.ctx, runtime.sessions) diff --git a/packages/client/ui-conversation/tests/user-text-component-fixture.client.tsx b/packages/client/ui-conversation/tests/user-text-component-fixture.client.tsx index c5383f3091..116f68f039 100644 --- a/packages/client/ui-conversation/tests/user-text-component-fixture.client.tsx +++ b/packages/client/ui-conversation/tests/user-text-component-fixture.client.tsx @@ -53,6 +53,8 @@ export function createUserTextFixture(actions: UserTextFixtureActions = {}): (in const openFile = actions.openFile ?? (() => { throw new Error('This fixture has no file navigation action') }) const openSkill = actions.openSkill ?? (() => { throw new Error('This fixture has no skill navigation action') }) const t = makeTranslate(referenceZh, commonZh) + // Composition units treat every path mention as Host-confirmed; ui-reference owns presence coverage. + const usePathPresence = () => 'present' as const const renderSlot: UserTextProps['renderSlot'] = (name: string, input: object, options?: { fallback?: ReactNode }) => { if (name !== 'conversation.user.text.node') throw new Error(`Unexpected UserText Slot: ${name}`) const owner = input as UserTextNodeOwnerProps & { node: UserTextNode } @@ -62,8 +64,8 @@ export function createUserTextFixture(actions: UserTextFixtureActions = {}): (in case 'secret': return createElement(SecretText, { ...owner, t } as ComponentProps) case 'text': return createElement(PlainUserText, owner as ComponentProps) case 'session': return createElement(SessionReference, owner as ComponentProps) - case 'file': return createElement(FileReference, { ...owner, openFile, t, useContextMenu: contextMenuHook(), resolveFilePath: (path: string) => path } as ComponentProps) - case 'folder': return createElement(FolderReference, owner as ComponentProps) + case 'file': return createElement(FileReference, { ...owner, openFile, usePathPresence, t, useContextMenu: contextMenuHook(), resolveFilePath: (path: string) => path } as ComponentProps) + case 'folder': return createElement(FolderReference, { ...owner, usePathPresence } as ComponentProps) case 'skill': return createElement(SkillReference, { ...owner, openSkill } as ComponentProps) case 'command': return createElement(GoalCommandReference, owner as ComponentProps) default: return options?.fallback ?? null diff --git a/packages/client/ui-conversation/tsconfig.client.json b/packages/client/ui-conversation/tsconfig.client.json index 759d52d183..dcac12eda3 100644 --- a/packages/client/ui-conversation/tsconfig.client.json +++ b/packages/client/ui-conversation/tsconfig.client.json @@ -9,6 +9,9 @@ "src" ], "references": [ + { + "path": "../config" + }, { "path": "../../../vendor/schemastery" }, diff --git a/packages/client/ui-conversation/tsconfig.host.json b/packages/client/ui-conversation/tsconfig.host.json index ec30b21bfe..aed18a8dc9 100644 --- a/packages/client/ui-conversation/tsconfig.host.json +++ b/packages/client/ui-conversation/tsconfig.host.json @@ -7,6 +7,7 @@ }, "files": [ "src/submission-settings.ts", + "src/types.ts", "src/index.ts" ], "references": [ diff --git a/packages/client/ui-reference/README.i18n.yaml b/packages/client/ui-reference/README.i18n.yaml index 2386cfb242..01fd4ab09c 100644 --- a/packages/client/ui-reference/README.i18n.yaml +++ b/packages/client/ui-reference/README.i18n.yaml @@ -20,6 +20,9 @@ /deepseek-ai-dsh-client-ui-reference/use-this-package/what-a-pick-inserts: en: 0b41c33743e5b422 zh: 551896094c03f57e +/deepseek-ai-dsh-client-ui-reference/use-this-package/sent-file-and-folder-mentions: + en: 87c27115eae5a660 + zh: a9a20431928072ec /deepseek-ai-dsh-client-ui-reference/use-this-package/failure-behavior: en: 386bbd9dc0a2c322 zh: 3014a367157532b7 @@ -30,8 +33,8 @@ en: 6c77da1e946f72e1 zh: b7b8e1e1d4f5a102 /deepseek-ai-dsh-client-ui-reference/understand-the-implementation/serialization: - en: c3fe8963ed80e403 - zh: ba3e057cd63e9189 + en: 1126dd5a1189cde8 + zh: 87866765edd7e343 /deepseek-ai-dsh-client-ui-reference/further-exploration: en: 157b1bcf84b5c11b zh: 6b7e4f3326b19036 @@ -42,8 +45,8 @@ en: ff23f8026f7c6050 zh: 6b0841800076bcd2 /deepseek-ai-dsh-client-ui-reference/known-limitations-and-deferred-work: - en: e79991a25b11e342 - zh: 15064e8374c8e63d + en: f51b285964650dd2 + zh: 5a237964dff7f98a /deepseek-ai-dsh-client-ui-reference/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/client/ui-reference/README.md b/packages/client/ui-reference/README.md index 1647f5b162..d8c07581bf 100644 --- a/packages/client/ui-reference/README.md +++ b/packages/client/ui-reference/README.md @@ -33,6 +33,10 @@ A file closes completion as an atomic inline reference displayed with a file gly A session pick inserts an atomic inline reference whose hidden `ref` and clipboard representation is the canonical `@[label](dsh-session:…)` mention returned by the Host; its visible form is a chat-bubble glyph plus the session title. Sending carries the mention through `session.prompt`, and the session-reference service validates it and captures model context at `agent/pre-step`. +### Sent file and folder mentions + +In sent messages, queued rows, and local echoes, an `@path` or `@"path"` token renders as a file or folder reference only after the Session's filesystem confirms the path exists. Until then, and for a path that does not exist, such as a hand-typed `@notes`, the original text stays verbatim; email addresses never match. A candidate picked and sent in the same Session during one page load counts as confirmed, so its echo shows the reference immediately. + ### Failure behavior One unavailable or failed candidate domain yields no rows for that domain while the other still lists. A session-reference preparation failure occurs after prompt acceptance and terminates that agent turn. @@ -61,7 +65,7 @@ Candidate requests require an existing retained Client Session and share one tem File picks preserve the natural text defined by the shared `@path` grammar as the hidden serialized and clipboard form. Session picks use the canonical `@[label](dsh-session:…)` mention; serialization never reconstructs identity from the visible title. -The plugin also registers file and folder matchers with [UserText](../ui-conversation/README.md#sent-user-text) and owns their `conversation.user.text.node` renderers. Each query returns the next complete reference at an original-text offset without file discovery; the shared evaluator resolves overlaps by source position. Interactive file nodes receive a Session-bound `openFile` injection; navigation failures keep the reference visible and offer a local retry/close dialog. Folder nodes remain labels. +The plugin also registers file and folder matchers with [UserText](../ui-conversation/README.md#sent-user-text) and owns their `conversation.user.text.node` renderers. Each query returns the next complete candidate reference at an original-text offset without file discovery; the shared evaluator resolves overlaps by source position. Both node renderers subscribe to a Session-bound `pathPresence` keyed Hook backed by `workspaceFiles/stat`: a stat result or a `workspace-file/not-regular-file` failure (a directory, a symbolic link whatever it points to, or another non-regular entry) confirms the path, `workspace-file/not-found` rejects it, and any other failure leaves it unconfirmed for the next subscriber to retry. The plugin owns these answers, keeps one per Session and path, and aborts outstanding stats on disposal; a settling pick records its path as confirmed. Presence does not read the [`file` resource](../../api/workspace-files/README.md) through `useResource`: that provider keeps one Host change subscription open per Session and path while a reader is mounted, and a mention needs a single answer. Interactive file nodes also receive a Session-bound `openFile` injection; navigation failures keep the reference visible and offer a local retry/close dialog. Folder nodes remain labels. @@ -97,6 +101,7 @@ These limits define when the reference source cannot help; they are current pack - **Candidate failure is intentionally quiet** — one unavailable or failed Remote discovery call yields no rows for that domain. A session-reference preparation failure occurs after prompt acceptance and terminates that agent turn. - **No browser-side file scan** — Web completion requires a mounted Host `ctx.fileReferences` provider; the browser cannot fall back to its own filesystem. +- **Sent references do not follow file changes** — a path's confirmed or missing answer lasts for the page load; creating or removing the path later changes how its mentions render only after reload. - **Session search remains metadata-only** — discovery filters session id, cwd, and the latest log-backed title through `ctx.sessionReferenceResolver`; message bodies and full transcripts are not searched. diff --git a/packages/client/ui-reference/README.zh.md b/packages/client/ui-reference/README.zh.md index 9b16dd48d7..3697fbcf17 100644 --- a/packages/client/ui-reference/README.zh.md +++ b/packages/client/ui-reference/README.zh.md @@ -33,6 +33,10 @@ Web 用户需要从同一个 `@` 补全菜单提及文件、文件夹或会话 选择会话会插入一个原子的行内引用,其隐藏 `ref` 与剪贴板表示均为宿主返回的规范 `@[label](dsh-session:…)` mention;可见形式为聊天气泡图标加会话标题。发送会经 `session.prompt` 携带该 mention,session-reference 服务会在 `agent/pre-step` 校验它并捕获模型上下文。 +### 已发送的文件与目录引用 + +在已发送消息、排队行和本地回显中,`@path` 或 `@"path"` token 只有在 Session 的文件系统确认该路径存在后才渲染为文件或目录引用。确认之前,以及路径不存在时(例如手写的 `@notes`),原文保持不变;邮箱地址永远不会匹配。在同一 Session、同一次页面加载内从候选中选择并发送的路径视为已确认,因此其回显会立即显示引用。 + ### 失败行为 某个候选领域不可用或失败时,该领域不产生任何行,另一领域仍正常列出。会话引用准备失败发生在提示词接受后,并会终止该 agent 轮次。 @@ -61,7 +65,7 @@ Web 用户需要从同一个 `@` 补全菜单提及文件、文件夹或会话 文件选择把共享 `@path` 语法所定义的自然文本保留为隐藏的序列化与剪贴板形式。会话选择使用规范的 `@[label](dsh-session:…)` mention;序列化永远不会根据可见标题重建身份。 -插件还向 [UserText](../ui-conversation/README.zh.md#sent-user-text) 注册文件和目录匹配器,并拥有它们的 `conversation.user.text.node` renderer。每次查询返回原文偏移之后的下一个完整引用,不执行文件发现;共享计算器按原文位置裁定重叠。可交互的文件节点通过 Injection 接收绑定 Session 的 `openFile`;导航失败时保留引用,提供局部重试/关闭对话框。目录节点仍为标签。 +插件还向 [UserText](../ui-conversation/README.zh.md#sent-user-text) 注册文件和目录匹配器,并拥有它们的 `conversation.user.text.node` renderer。每次查询返回原文偏移之后的下一个完整候选引用,不执行文件发现;共享计算器按原文位置裁定重叠。两个节点 renderer 都订阅绑定 Session 的 `pathPresence` 键控 Hook,其背后是 `workspaceFiles/stat`:stat 成功或 `workspace-file/not-regular-file` 失败(目录、无论指向何处的符号链接或其他非普通条目)即确认路径存在,`workspace-file/not-found` 判定不存在,其他失败则保持未确认,由下一个订阅者重试。插件持有这些结果,每个 Session 与路径保留一份,并在卸载时中止未完成的 stat;选定 pick 会把其路径记为已确认。存在性不通过 `useResource` 读取 [`file` 资源](../../api/workspace-files/README.zh.md):该 provider 在有读取方挂载期间为每个 Session 与路径保持一个 Host 变更订阅,而一次提及只需要一个结果。可交互的文件节点还通过 Injection 接收绑定 Session 的 `openFile`;导航失败时保留引用,提供局部重试/关闭对话框。目录节点仍为标签。 @@ -97,6 +101,7 @@ Web 用户需要从同一个 `@` 补全菜单提及文件、文件夹或会话 - **候选失败有意保持静默**:Remote 发现调用不可用或失败时,该领域不产生候选行。会话引用准备失败发生在提示词接受后,并会终止该 agent 轮次。 - **浏览器侧不扫描文件**:Web 补全需要挂载宿主 `ctx.fileReferences` 提供方;浏览器无法回退到自身文件系统。 +- **已发送引用不跟随文件变化**:路径的确认或不存在结果在一次页面加载内保持不变;之后创建或删除该路径,只有刷新页面后才会改变其引用的渲染。 - **会话搜索仍仅使用元数据**:发现流程通过 `ctx.sessionReferenceResolver` 筛选 session id、cwd 与以日志为依据的最新标题;不搜索消息主体或完整 transcript。 diff --git a/packages/client/ui-reference/src/client/FileReference.tsx b/packages/client/ui-reference/src/client/FileReference.tsx index ceeb7cc6fc..4049a467b0 100644 --- a/packages/client/ui-reference/src/client/FileReference.tsx +++ b/packages/client/ui-reference/src/client/FileReference.tsx @@ -1,13 +1,22 @@ /** File navigation feedback belongs to the individual inline reference that requested it. */ import { useState } from 'react' import type { UserTextNodeProps } from '@deepseek-ai/dsh-client-ui-conversation/client' -import type { InjectFace, PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' -import { Button, Modal, ReferenceChip } from '@deepseek-ai/dsh-client-ui-primitives' +import type { HostObservable, InjectFace, PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' +import { Button, Modal, ReferenceChip, UserTextRun } from '@deepseek-ai/dsh-client-ui-primitives' import type { NS } from './locales.ts' +import type { PathPresence } from './path-presence.ts' import type {} from './user-text-rules.ts' +/** Host-confirmed presence of mention paths in the rendering Session. */ +export interface PathPresenceInjected { + readonly keyedHooks: { + /** Presence of one decoded mention path; subscribing starts its Host stat. */ + readonly pathPresence: (path: string) => HostObservable + } +} + /** Session-authorized synchronous navigation; document reading belongs to the preview host. */ -export interface FileReferenceInjected { +export interface FileReferenceInjected extends PathPresenceInjected { /** * Open or reveal a file in the current Sidebar using the originating Session's authority. * @param path - decoded path from the reference. @@ -20,15 +29,21 @@ export interface FileReferenceInjected { type FileReferenceProps = UserTextNodeProps<'file'> & InjectFace & PropsLocale +type FolderReferenceProps = UserTextNodeProps<'folder'> & InjectFace + /** - * Render a file chip and contain synchronous navigation failures without hiding the reference. - * @param props - JSON node, interaction policy, Session-authorized navigation, and locale seat. - * @returns an inline chip and, after a navigation failure, its body-portaled dialog. + * Render a file chip once the Host confirms its path exists, and contain synchronous navigation failures without hiding the reference. + * @param props - JSON node, interaction policy, Session-authorized navigation and presence, and locale seat. + * @returns the original spelling until confirmation; afterwards an inline chip and, after a navigation failure, its body-portaled dialog. */ -export function FileReference({ node, raw, interactive, openFile, resolveFilePath, sessionId, useContextMenu, t }: FileReferenceProps) { +export function FileReference({ + node, raw, interactive, openFile, resolveFilePath, sessionId, useContextMenu, usePathPresence, t, +}: FileReferenceProps) { const { getTriggerProps } = useContextMenu() const [failedPath, setFailedPath] = useState(null) const { path, label } = node.data + const presence = usePathPresence(path) + if (presence !== 'present') return const close = () => { setFailedPath(null) } const open = () => { try { @@ -62,10 +77,12 @@ export function FileReference({ node, raw, interactive, openFile, resolveFilePat } /** - * Render a directory as a label, even when the containing text permits file navigation. - * @param props - resolved directory data and the original reference spelling. - * @returns an inline non-interactive chip. + * Render a directory as a label once the Host confirms its path exists, even when the containing text permits file navigation. + * @param props - directory data, the original reference spelling, and Session-scoped presence. + * @returns the original spelling until confirmation, then an inline non-interactive chip. */ -export function FolderReference({ node, raw }: UserTextNodeProps<'folder'>) { - return +export function FolderReference({ node, raw, usePathPresence }: FolderReferenceProps) { + return usePathPresence(node.data.path) === 'present' + ? + : } diff --git a/packages/client/ui-reference/src/client/index.ts b/packages/client/ui-reference/src/client/index.ts index ab66cffa5e..8287af2713 100644 --- a/packages/client/ui-reference/src/client/index.ts +++ b/packages/client/ui-reference/src/client/index.ts @@ -11,6 +11,11 @@ * workspace is not the current one. A session is dated from the Host session * list, so the `@` menu and the session list never disagree about its age. * + * A file or folder mention in sent text renders as a chip only after the + * Session's filesystem confirms the path exists; picking a listed candidate + * confirms it, and any other mention stays original text until a Host stat + * answers. + * * @module @deepseek-ai/dsh-client-ui-reference/client */ // Type-only: pulls the generated Remote API and ctx.remote merge through the Client assembly boundary. @@ -23,8 +28,11 @@ import type { Context as ClientContext } from '@deepseek-ai/cordis' import type { ISessions } from '@deepseek-ai/dsh-api-session-controller/client' import { relativeTime } from '@deepseek-ai/dsh-client-ui-primitives' import type { UserTextNodeProps } from '@deepseek-ai/dsh-client-ui-conversation/client' -import { FileReference, FolderReference, type FileReferenceInjected } from './FileReference.tsx' -import { fileReferenceRule, folderReferenceRule } from './user-text-rules.ts' +import { + FileReference, FolderReference, type FileReferenceInjected, type PathPresenceInjected, +} from './FileReference.tsx' +import { createPathPresence, type MentionSessionId } from './path-presence.ts' +import { fileReferenceRule, folderReferenceRule, mentionPath } from './user-text-rules.ts' export type {} from './user-text-rules.ts' import type { ClientSessionContext, InputTriggerCrumb, InputTriggerServiceContract, InputTriggerSource, @@ -45,7 +53,7 @@ declare module '@deepseek-ai/dsh-api-session-controller/client' { /** Required services: the trigger registry, the Remote namespaces, and the copy. */ export const inject = [ 'inputTriggers', 'locale', 'sessions', 'remote', 'remote.fileReferences', - 'remote.sessionReferenceResolver', 'sidebarRight', 'slots', 'uiConversation', + 'remote.sessionReferenceResolver', 'remote.workspaceFiles', 'sidebarRight', 'slots', 'uiConversation', ] /** @@ -56,12 +64,18 @@ export function apply(ctx: ClientContext): void { ctx.effect(() => ctx.locale.register(NS, { zh, en, ja, es, fr, de, ru, pt }), 'ui-reference: dictionaries') const t = ctx.locale.bind(NS) const sessions = ctx.get('sessions') as ISessions + const presence = createPathPresence((sessionId, path, signal) => ctx.remote.workspaceFiles.stat(sessionId, path, signal)) + ctx.effect(() => () => { presence.dispose() }, 'ui-reference: mention path stats') + const presenceFor = (sessionId: MentionSessionId): PathPresenceInjected => ({ + keyedHooks: { pathPresence: path => presence.source(sessionId, path) }, + }) ctx.uiConversation.userText.register(fileReferenceRule) ctx.uiConversation.userText.register(folderReferenceRule) ctx.slots.inject('conversation.user.text.node', function* () { yield ctx.slots.register({ name: 'conversation.user.text.node', key: 'file', priority: 100, locale: NS, inject: (sessionId: UserTextNodeProps<'file'>['sessionId']): FileReferenceInjected => ({ + ...presenceFor(sessionId), resolveFilePath: path => resolveWorkspacePath(sessions.list.getSnapshot().byId[sessionId]?.cwd, path), openFile: (path) => { const cwd = sessions.list.getSnapshot().byId[sessionId]?.cwd @@ -69,7 +83,9 @@ export function apply(ctx: ClientContext): void { }, }), }, FileReference) - yield ctx.slots.register({ name: 'conversation.user.text.node', key: 'folder', priority: 100 }, FolderReference) + yield ctx.slots.register({ + name: 'conversation.user.text.node', key: 'folder', priority: 100, inject: presenceFor, + }, FolderReference) }) const source: InputTriggerSource = { trigger: '@', @@ -129,7 +145,7 @@ export function apply(ctx: ClientContext): void { header(_session: ClientSessionContext, req) { return crumbsFor(req.query, req.quoted === true, req.drilled, t) }, - onPick({ candidate, action }) { + onPick({ candidate, session, action }) { const value = parseCandidate(candidate.value) if (value?.kind === 'file') { // A directory row carries two verbs: the settling pick resolves the @@ -139,6 +155,8 @@ export function apply(ctx: ClientContext): void { if (value.fileKind === 'directory' && action === 'drill') { return { text: value.mention, continue: true } } + // The Host has just listed this path, so its sent echo renders as a chip without a stat. + presence.confirm(session.sessionId, mentionPath(value.mention)) return { insert: { source: 'reference', @@ -164,7 +182,7 @@ export function apply(ctx: ClientContext): void { }, openReference(session, { ref, appearance }) { if (appearance !== 'file') return false - const path = ref.startsWith('@"') ? ref.slice(2, -1) : ref.slice(1) + const path = mentionPath(ref) const cwd = sessions.list.getSnapshot().byId[session.sessionId]?.cwd ctx.sidebarRight.openResource(fileAddressFor(session.sessionId, cwd, path)) return true diff --git a/packages/client/ui-reference/src/client/path-presence.ts b/packages/client/ui-reference/src/client/path-presence.ts new file mode 100644 index 0000000000..886bb2db10 --- /dev/null +++ b/packages/client/ui-reference/src/client/path-presence.ts @@ -0,0 +1,140 @@ +/** + * Session-scoped Host confirmation that a mentioned path exists. + * + * Each Session and path pair is stat'ed at most once while the owning plugin + * is live. Only a definitive Host answer is retained; any other failure leaves + * the pair unconfirmed, and the next subscriber asks again. Retained answers + * are not refreshed when the path is created or removed later. Entries live as + * long as the plugin, one per distinct mention the client has rendered. Each + * unconfirmed pair starts its own Host request when first subscribed; nothing + * bounds how many are outstanding at once. + */ +import type { UserTextNodeProps } from '@deepseek-ai/dsh-client-ui-conversation/client' +import type { WorkspaceFileStat } from '@deepseek-ai/dsh-api-remotes/client' +import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots' +import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' + +/** Session whose filesystem resolves a mention. */ +export type MentionSessionId = UserTextNodeProps<'file'>['sessionId'] + +/** Host answer for one mentioned path; `undefined` means unconfirmed. */ +export type PathPresence = 'present' | 'absent' + +/** + * Session-authorized stat of one path, absolute or relative to the Session's workspace root. + * @param sessionId - Session whose filesystem resolves the path. + * @param path - path as the mention spells it. + * @param signal - cancellation owned by the presence sources. + * @returns the regular file's metadata, or the Host's typed failure. + */ +export type PathStat = ( + sessionId: MentionSessionId, + path: string, + signal: AbortSignal, +) => Promise> + +/** Presence sources shared by every mention one plugin instance renders. */ +export interface PathPresenceSources { + /** + * Observe one path; the first subscription to an unconfirmed path starts its Host stat. + * @param sessionId - Session whose filesystem resolves the path. + * @param path - decoded mention path. + * @returns the same source for the same pair until disposal. + */ + source(sessionId: MentionSessionId, path: string): HostObservable + /** + * Record a path the Host has just listed, such as a picked completion candidate. + * @param sessionId - Session whose filesystem listed the path. + * @param path - decoded mention path. + */ + confirm(sessionId: MentionSessionId, path: string): void + /** Abort outstanding stats; later subscriptions start none. */ + dispose(): void +} + +interface Entry { + presence: PathPresence | undefined + probing: boolean + readonly listeners: Set<() => void> + readonly source: HostObservable +} + +/** + * Classify one stat. A directory, a symbolic link whatever it points to, or + * another non-regular entry still exists; failures that do not describe the + * path leave it unconfirmed. + * @param result - Host stat result. + * @returns the definitive presence, or undefined. + */ +function presenceOf(result: RemoteResult): PathPresence | undefined { + if (result.ok) return 'present' + switch (result.error.code) { + case 'workspace-file/not-regular-file': + return 'present' + case 'workspace-file/not-found': + return 'absent' + default: + return undefined + } +} + +/** + * Create presence sources over one stat function. + * @param stat - Session-authorized Host stat. + * @returns sources the caller disposes with its plugin. + */ +export function createPathPresence(stat: PathStat): PathPresenceSources { + const lifetime = new AbortController() + const entries = new Map() + + const publish = (entry: Entry, presence: PathPresence) => { + entry.presence = presence + for (const listener of [...entry.listeners]) listener() + } + + const probe = (entry: Entry, sessionId: MentionSessionId, path: string) => { + if (entry.probing || entry.presence !== undefined || lifetime.signal.aborted) return + entry.probing = true + // Cancellation and carrier faults resolve as failures. Only a Remote + // assembly fault rejects: it stays an unhandled rejection so the fault is + // reported, and the pair stays unconfirmed for the next subscriber. + void stat(sessionId, path, lifetime.signal).then((result) => { + const presence = presenceOf(result) + // A confirmation recorded while this stat was outstanding is newer. + if (presence === undefined || entry.presence !== undefined || lifetime.signal.aborted) return + publish(entry, presence) + }).finally(() => { entry.probing = false }) + } + + const entryFor = (sessionId: MentionSessionId, path: string): Entry => { + const key = JSON.stringify([sessionId, path]) + const existing = entries.get(key) + if (existing !== undefined) return existing + const entry: Entry = { + presence: undefined, + probing: false, + listeners: new Set(), + source: { + getSnapshot: () => entry.presence, + subscribe: (listener) => { + entry.listeners.add(listener) + probe(entry, sessionId, path) + return () => { entry.listeners.delete(listener) } + }, + }, + } + entries.set(key, entry) + return entry + } + + return { + source: (sessionId, path) => entryFor(sessionId, path).source, + confirm(sessionId, path) { + const entry = entryFor(sessionId, path) + if (entry.presence !== 'present') publish(entry, 'present') + }, + dispose() { + lifetime.abort() + }, + } +} diff --git a/packages/client/ui-reference/src/client/user-text-rules.ts b/packages/client/ui-reference/src/client/user-text-rules.ts index b227660c86..060918ba6c 100644 --- a/packages/client/ui-reference/src/client/user-text-rules.ts +++ b/packages/client/ui-reference/src/client/user-text-rules.ts @@ -1,4 +1,7 @@ -/** Forward file and folder recognition in original text, without Facts or discovery. */ +/** + * Forward file and folder mention candidates in original text, without Facts or discovery. + * The node components decide whether a candidate names an existing path. + */ import type { UserTextRule } from '@deepseek-ai/dsh-client-ui-conversation/client' interface PathReferenceData { @@ -13,6 +16,15 @@ declare module '@deepseek-ai/dsh-client-ui-conversation/client' { } } +/** + * Decode the path a complete `@path` or `@"quoted path"` mention names. + * @param mention - mention spelling starting with `@`, without trailing sentence punctuation. + * @returns the path that file and folder nodes carry. + */ +export function mentionPath(mention: string): string { + return mention.slice(1).replace(/^"|"$/gu, '') +} + function nextPath(text: string, from: number, folder: boolean) { const tokens = /(? = {}, opening: Pick = {}, + stat: PathStat = vi.fn(() => new Promise(() => {})), ) { const ctx = new Context() ctx.provide('sidebarRight', { openResource: vi.fn() }) @@ -119,6 +123,7 @@ async function bench( new RemoteService(ctx) ctx.provide('remote.fileReferences', { list: files }) ctx.provide('remote.sessionReferenceResolver', { candidates: sessions }) + ctx.provide('remote.workspaceFiles', { stat }) ctx.provide('locale', new LocaleRuntime(ctx)) const sessionStore = new TestSessions(async (action) => { await action() }, ctx) onTestFinished(async () => { @@ -139,11 +144,17 @@ async function bench( return { ctx, fiber, source, sessions: sessionStore, owner } } +/** The Session-bound presence face a file or folder text node entry injects. */ +function injectedPresence(ctx: Context, key: 'file' | 'folder'): (id: SessionId) => PathPresenceInjected { + const entry = ctx.slots.entries('conversation.user.text.node').find(candidate => candidate.options.key === key)! + return entry.inject as NonNullable & ((id: SessionId) => PathPresenceInjected) +} + describe('apply', () => { it('declares its services and releases the @ reference registration on disposal', async () => { expect(inject).toEqual([ 'inputTriggers', 'locale', 'sessions', 'remote', 'remote.fileReferences', - 'remote.sessionReferenceResolver', 'sidebarRight', 'slots', 'uiConversation', + 'remote.sessionReferenceResolver', 'remote.workspaceFiles', 'sidebarRight', 'slots', 'uiConversation', ]) const { fiber } = await bench() let registered: InputTriggerSource | undefined @@ -166,6 +177,7 @@ describe('apply', () => { new RemoteService(ctx) ctx.provide('remote.fileReferences', { list: () => Promise.resolve({ ok: true, value: [] }) }) ctx.provide('remote.sessionReferenceResolver', { candidates: () => Promise.resolve({ ok: true, value: [] }) }) + ctx.provide('remote.workspaceFiles', { stat: vi.fn() }) ctx.provide('locale', new LocaleRuntime(ctx)) const sessions = new TestSessions(async (action) => { await action() }, ctx) onTestFinished(() => sessions.disposeScopes()) @@ -671,6 +683,23 @@ describe('pick and codec', () => { await expect(source.codec?.serialize(mention, new AbortController().signal)).resolves.toBe(mention) }) + it('confirms settled file and folder picks for the picking Session; a drill confirms nothing', async () => { + const stat = vi.fn(() => new Promise(() => {})) + const { ctx, source } = await bench(undefined, undefined, {}, {}, stat) + const [directory, file] = await source.candidates(session, request('')) + const folderFace = injectedPresence(ctx, 'folder') + const fileFace = injectedPresence(ctx, 'file') + drill(source, directory!) + expect(folderFace(session.sessionId).keyedHooks.pathPresence('src/').getSnapshot()).toBeUndefined() + pick(source, directory!) + pick(source, file!) + expect(folderFace(session.sessionId).keyedHooks.pathPresence('src/').getSnapshot()).toBe('present') + expect(fileFace(session.sessionId).keyedHooks.pathPresence('docs/a b.md').getSnapshot()).toBe('present') + expect(folderFace(sid('other')).keyedHooks.pathPresence('src/').getSnapshot()).toBeUndefined() + folderFace(session.sessionId).keyedHooks.pathPresence('src/').subscribe(vi.fn()) + expect(stat).not.toHaveBeenCalled() + }) + it('ignores candidates that do not carry a source-owned value', async () => { const { source } = await bench() expect(pick(source, { name: 'foreign candidate' })).toBeUndefined() @@ -678,6 +707,17 @@ describe('pick and codec', () => { }) describe('reference preview', () => { + it('stats each mention through its rendering Session and aborts outstanding stats on disposal', async () => { + const stat = vi.fn(() => new Promise(() => {})) + const { ctx, fiber } = await bench(undefined, undefined, {}, {}, stat) + injectedPresence(ctx, 'file')(session.sessionId).keyedHooks.pathPresence('LICENSE').subscribe(vi.fn()) + injectedPresence(ctx, 'folder')(sid('other')).keyedHooks.pathPresence('docs/').subscribe(vi.fn()) + expect(stat.mock.calls.map(([id, path]) => [id, path])).toEqual([['target', 'LICENSE'], ['other', 'docs/']]) + expect(stat.mock.calls.some(([, , signal]) => signal.aborted)).toBe(false) + await fiber.dispose() + expect(stat.mock.calls.every(([, , signal]) => signal.aborted)).toBe(true) + }) + it('binds each inline file action to its originating Session', async () => { const { ctx, sessions } = await bench() const entry = ctx.slots.entries('conversation.user.text.node').find(candidate => candidate.options.key === 'file')! diff --git a/packages/client/ui-reference/tests/file-reference.client.spec.tsx b/packages/client/ui-reference/tests/file-reference.client.spec.tsx index d033443112..aac310c2ca 100644 --- a/packages/client/ui-reference/tests/file-reference.client.spec.tsx +++ b/packages/client/ui-reference/tests/file-reference.client.spec.tsx @@ -12,17 +12,41 @@ import { brandString } from '@deepseek-ai/dsh-brand' afterEach(cleanup) type Props = ComponentProps +type Presence = ReturnType -function props(openFile: Props['openFile']): Props { +function presenceHook(presence: Record): Props['usePathPresence'] { + const hook = (path: string) => presence[path] + return hook as Props['usePathPresence'] +} + +const PRESENT = presenceHook({ 'docs/a b.md': 'present', 'docs/': 'present' }) + +function props(openFile: Props['openFile'], usePathPresence = PRESENT): Props { return { node: { id: 'file', start: 0, end: 14, data: { path: 'docs/a b.md', label: 'a b.md' } }, - raw: '@"docs/a b.md"', interactive: true, openFile, t: makeTranslate(en), + raw: '@"docs/a b.md"', interactive: true, openFile, usePathPresence, t: makeTranslate(en), useContextMenu: contextMenuHook(), sessionId: brandString('original'), resolveFilePath: path => `/workspace/${path}`, } as Props } describe('FileReference', () => { + it('keeps the original spelling until the Host confirms the path exists', () => { + const openFile = vi.fn() + const folder = { id: 'folder', start: 0, end: 6, data: { path: 'docs/', label: 'docs' } } as const + for (const presence of [undefined, 'absent'] as const) { + const usePathPresence = presenceHook({ 'docs/a b.md': presence, 'docs/': presence }) + const view = render(<> + + + ) + expect(view.container.textContent).toBe('@"docs/a b.md"@docs/') + expect(view.container.querySelector('[data-ref-chip]')).toBeNull() + view.unmount() + } + expect(openFile).not.toHaveBeenCalled() + }) + it('opens the decoded path and leaves summaries and folders non-interactive', () => { const openFile = vi.fn() const input = props(openFile) diff --git a/packages/client/ui-reference/tests/path-presence.client.spec.ts b/packages/client/ui-reference/tests/path-presence.client.spec.ts new file mode 100644 index 0000000000..cc13fa4659 --- /dev/null +++ b/packages/client/ui-reference/tests/path-presence.client.spec.ts @@ -0,0 +1,136 @@ +import { describe, expect, it, vi } from 'vitest' +import type { RemoteFailure, RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import type { WorkspaceFileStat } from '@deepseek-ai/dsh-api-remotes/client' +import { RemoteError } from '@deepseek-ai/dsh-client-test-runtime' +import { createPathPresence, type MentionSessionId, type PathStat } from '../src/client/path-presence.ts' + +const sid = (value: string): MentionSessionId => value as MentionSessionId +const STAT: WorkspaceFileStat = { absolutePath: '/w/LICENSE', version: 'v1' } + +interface StatCall { + readonly sessionId: MentionSessionId + readonly path: string + readonly signal: AbortSignal + readonly resolve: (result: RemoteResult) => void +} + +function deferredStat() { + const calls: StatCall[] = [] + const stat = vi.fn((sessionId, path, signal) => new Promise((resolve) => { + calls.push({ sessionId, path, signal, resolve }) + })) + return { stat, calls } +} + +const failure = (error: RemoteFailure): RemoteResult => ({ ok: false, error }) + +describe('createPathPresence', () => { + it('shares one stat per Session and path and publishes the Host answer to every subscriber', async () => { + const { stat, calls } = deferredStat() + const presence = createPathPresence(stat) + const source = presence.source(sid('a'), 'LICENSE') + expect(presence.source(sid('a'), 'LICENSE')).toBe(source) + expect(presence.source(sid('b'), 'LICENSE')).not.toBe(source) + expect(source.getSnapshot()).toBeUndefined() + expect(stat).not.toHaveBeenCalled() + const first = vi.fn() + const second = vi.fn() + const unsubscribe = source.subscribe(first) + source.subscribe(second) + expect(calls.map(call => [call.sessionId, call.path])).toEqual([['a', 'LICENSE']]) + unsubscribe() + calls[0]!.resolve({ ok: true, value: STAT }) + await vi.waitFor(() => { expect(source.getSnapshot()).toBe('present') }) + expect(first).not.toHaveBeenCalled() + expect(second).toHaveBeenCalledOnce() + source.subscribe(vi.fn()) + expect(stat).toHaveBeenCalledOnce() + }) + + it('treats a non-regular entry as present, a missing entry as absent, and retries any other failure', async () => { + const { stat, calls } = deferredStat() + const presence = createPathPresence(stat) + const folder = presence.source(sid('a'), 'docs/') + const missing = presence.source(sid('a'), 'ceshi') + const offline = presence.source(sid('a'), 'notes.md') + folder.subscribe(vi.fn()) + missing.subscribe(vi.fn()) + offline.subscribe(vi.fn()) + calls[0]!.resolve(failure(new RemoteError('workspace-file/not-regular-file', 'directory', { path: 'docs/', kind: 'directory' }))) + calls[1]!.resolve(failure(new RemoteError('workspace-file/not-found', 'missing', { path: 'ceshi' }))) + calls[2]!.resolve(failure(new RemoteError('gateway/internal', 'offline', {}))) + await vi.waitFor(() => { expect(missing.getSnapshot()).toBe('absent') }) + expect(folder.getSnapshot()).toBe('present') + expect(offline.getSnapshot()).toBeUndefined() + offline.subscribe(vi.fn()) + expect(calls.map(call => call.path)).toEqual(['docs/', 'ceshi', 'notes.md', 'notes.md']) + calls[3]!.resolve({ ok: true, value: STAT }) + await vi.waitFor(() => { expect(offline.getSnapshot()).toBe('present') }) + }) + + it('lets a picked confirmation stand over an older outstanding stat and over an earlier absence', async () => { + const { stat, calls } = deferredStat() + const presence = createPathPresence(stat) + const source = presence.source(sid('a'), 'new.md') + const listener = vi.fn() + source.subscribe(listener) + presence.confirm(sid('a'), 'new.md') + presence.confirm(sid('a'), 'new.md') + expect(source.getSnapshot()).toBe('present') + expect(listener).toHaveBeenCalledOnce() + calls[0]!.resolve(failure(new RemoteError('workspace-file/not-found', 'missing', { path: 'new.md' }))) + await Promise.resolve() + await Promise.resolve() + expect(source.getSnapshot()).toBe('present') + + const created = presence.source(sid('a'), 'later.md') + created.subscribe(vi.fn()) + calls[1]!.resolve(failure(new RemoteError('workspace-file/not-found', 'missing', { path: 'later.md' }))) + await vi.waitFor(() => { expect(created.getSnapshot()).toBe('absent') }) + presence.confirm(sid('a'), 'later.md') + expect(created.getSnapshot()).toBe('present') + const picked = presence.source(sid('a'), 'picked.md') + presence.confirm(sid('a'), 'picked.md') + picked.subscribe(vi.fn()) + expect(stat).toHaveBeenCalledTimes(2) + }) + + it('reports a rejected stat as an unhandled rejection and asks again for the next subscriber', async () => { + const fault = new Error('client api: workspaceFiles/stat has no active Connection') + const stat = vi.fn() + .mockRejectedValueOnce(fault) + .mockResolvedValueOnce({ ok: true, value: STAT }) + const rejections: unknown[] = [] + const onUnhandled = (reason: unknown): void => { rejections.push(reason) } + process.on('unhandledRejection', onUnhandled) + try { + const presence = createPathPresence(stat) + const source = presence.source(sid('a'), 'LICENSE') + source.subscribe(vi.fn()) + await vi.waitFor(() => { expect(rejections).toEqual([fault]) }) + expect(source.getSnapshot()).toBeUndefined() + source.subscribe(vi.fn()) + expect(stat).toHaveBeenCalledTimes(2) + await vi.waitFor(() => { expect(source.getSnapshot()).toBe('present') }) + } finally { + process.off('unhandledRejection', onUnhandled) + } + }) + + it('aborts outstanding stats on disposal, drops their answers, and starts no further stats', async () => { + const { stat, calls } = deferredStat() + const presence = createPathPresence(stat) + const source = presence.source(sid('a'), 'LICENSE') + const listener = vi.fn() + source.subscribe(listener) + presence.dispose() + expect(calls[0]!.signal.aborted).toBe(true) + calls[0]!.resolve({ ok: true, value: STAT }) + await Promise.resolve() + await Promise.resolve() + expect(source.getSnapshot()).toBeUndefined() + expect(listener).not.toHaveBeenCalled() + presence.source(sid('a'), 'other.md').subscribe(vi.fn()) + expect(stat).toHaveBeenCalledOnce() + }) +}) diff --git a/packages/client/ui-settings-account/README.i18n.yaml b/packages/client/ui-settings-account/README.i18n.yaml index b7dd7357d5..15e31d3f3d 100644 --- a/packages/client/ui-settings-account/README.i18n.yaml +++ b/packages/client/ui-settings-account/README.i18n.yaml @@ -15,14 +15,14 @@ en: c26f81e8adf0128b zh: e11ab371f51f66bc /deepseek-ai-dsh-client-ui-settings-account/use-this-package: - en: 9e61a6adc39fddbc - zh: fbcb4852ca4eded1 + en: 7a0e9f683d496167 + zh: 63a7278d96ecdd71 /deepseek-ai-dsh-client-ui-settings-account/use-this-package/desktop-onboarding: - en: 7ae4e68f9491b068 - zh: f7478269bf8d28b3 + en: b17e3d33f66af025 + zh: 780f813205d955d9 /deepseek-ai-dsh-client-ui-settings-account/understand-the-implementation: - en: a0da9e739f2aa682 - zh: 27aa6d13dba6f4b4 + en: 916a0c6e3d735da9 + zh: 0310dca3463e2201 /deepseek-ai-dsh-client-ui-settings-account/further-exploration: en: f5ca95916ef486dc zh: 1e238d8299e0d838 diff --git a/packages/client/ui-settings-account/README.md b/packages/client/ui-settings-account/README.md index 0585faf254..5017d0ed39 100644 --- a/packages/client/ui-settings-account/README.md +++ b/packages/client/ui-settings-account/README.md @@ -52,7 +52,7 @@ The account card’s More account information link has no underline and opens th Sign out first queries running account-token tasks and opens a confirmation dialog. The warning describes interruption when such tasks exist; otherwise it explains that data is retained and the account can be signed in again. Cancel, close, and Escape dismiss without signing out. Failed impact queries still open confirmation with an explicit unknown-task warning; failed sign-out keeps the dialog available for retry. -Account notification polling and presentation belong to [ui-account-notifications](../ui-account-notifications/README.md). The account menu positions the notification slot above its launcher inside the sidebar, keeps its DOM mounted while the rail hides it, and publishes account lifecycle and refresh events. +Account notification polling and presentation belong to [ui-account-notifications](../ui-account-notifications/README.md). The plugin fills the settings shell's `settings.notice` row above the launcher row with the notification slot, and publishes account lifecycle and refresh events. ### Desktop onboarding @@ -61,12 +61,12 @@ The Desktop preload marker enables the introduction after account credentials ar The welcome page requires Get started. The credit page always appears. A positive balance confirmed at first entry selects Continue as the primary action and Add credits as the secondary action. This choice stays fixed until the onboarding controller is recreated and is never persisted; late balance results cannot change the buttons. Only a confirmed absence of positive credit adds a confirmation before continuing without recharge; pending or failed queries do not block continuing. Purpose descriptions remain unchanged when selected. Returning from the native top-up view keeps the credit page and re-reads profile and balance in the background after any read already running, whether loading or payment succeeded. That read does not recompute the funded-mode choice, so a completed recharge leaves the buttons as first entered while continuing still evaluates the refreshed balance. Next confirms only a known zero balance; Skip uses the credit warning on the credit page and the setup warning on the question pages. Office-only use completes with compact presentation; development or both purposes also ask for process detail. Back preserves selections, and explicit skip from any supported step applies standard process, compact performance/usage, and disabled Coding Tools. This flow creates no workspace or demonstration task. -Access: the account stream, quota notice, settings launcher, account settings section, and models sign-in entry exist only while the current Peer may call `account/watch`; Desktop onboarding and the platform page are not gated. Losing that access discards the account reads that grant started, closes a pending authorization tab, and clears the account view, details, picture, and sign-in dialog state; a later grant shows the account section again once its first frame arrives. The owner always has access. +Access: the account stream, quota notice, settings launcher, notification row, account settings section, and models sign-in entry exist only while the current Peer may call `account/watch`; Desktop onboarding and the platform page are not gated. Losing that access discards the account reads that grant started, closes a pending authorization tab, and clears the account view, details, picture, and sign-in dialog state; a later grant shows the account section again once its first frame arrives. The owner always has access. ## Understand the implementation -The Account section appears first in Settings only while signed in; it is hidden before account state loads and after sign-out. The plugin owns one Host snapshot stream shared through framework hooks by settings.section and settings.launcher. The launcher opens Settings and offers Sign out only while an account credential is stored. Platform failures leave the menu available for retry. It maintains no independent credential state. +The Account section appears first in Settings only while signed in; it is hidden before account state loads and after sign-out. The plugin owns one Host snapshot stream shared through framework hooks by settings.section, settings.launcher, and settings.notice. The launcher opens Settings and offers Sign out only while an account credential is stored. Platform failures leave the menu available for retry. It maintains no independent credential state. The desktop controller writes progress to `ui-settings-account` through Host settings. Completion first applies `ui-chat.transcriptView` and `ui-chat.performanceUsage` together, then calls the shared Coding Tools preference to persist `ui-settings.enabled`, and finally saves the done marker; a rejected write keeps the flow available for retry. Successful completion reveals the workspace through a 180ms fade; choices and ordinary navigation preview immediately while writes run in order. A failed final queued write restores saved progress and allows retry. Completion waits for queued choices and retains the page until preferences persist; reduced motion skips the fade. Onboarding choices compact, standard, and detailed apply directly to the corresponding Chat work-detail modes. API-key entry and explicit skip select standard; onboarding does not select verbose. Complete Figma illustration layers ship as transparent, lossless 3× WebP [package assets](../AGENTS.md#dependency-declaration); welcome layers are merged with local sidebar blur; recharge uses a 70% opaque foreground window with local blur of the covered illustration, and headings use the bundled Montserrat brand font; English headings and descriptions use Light (300), except the DeepSeek Harness brand within headings uses Medium (500); card titles retain Regular (400) when selected. English footer navigation uses Light (300). Confirmed onboarding sets a 960px minimum window width and enlarges narrower windows; completion releases the minimum without restoring the previous size. Loading or already-completed onboarding does not resize the window. Empty footer navigation space passes pointer events through to the primary action. Cards exclude native window dragging and own the keyboard focus outline for their checkbox. The account package owns its onboarding overlay and control geometry. Each step and the confirmation dialog has a separate component; the flow coordinates navigation, transitions, and recharge. The overlay hides the workspace while initial account and progress state loads. Question headings and cards follow the Figma positions at 1440 × 920 and 960 × 600, independently of their action buttons. On macOS, the shell resets inherited window regions on each element, and a first-child drag band leaves an 8px native resize margin. The stage’s `data-window-drag-controls` scope excludes its interactive controls, later dialogs exclude their own boxes, and a native Platform page disables the underlying onboarding band. The upper workspace popup illustration has an opaque background in both languages and themes; the underlying sidebar omits its selected-row highlight. Welcome keeps its illustration at its original size, repositions and clips the artwork in narrow windows, and reveals the complete illustration on wide windows. The [historical onboarding decision](../../../.agents/notes/archived/feature/2026-09-16-desktop-onboarding.md) owns persistence and presentation trade-offs. diff --git a/packages/client/ui-settings-account/README.zh.md b/packages/client/ui-settings-account/README.zh.md index 4ea576d157..c06df24cbd 100644 --- a/packages/client/ui-settings-account/README.zh.md +++ b/packages/client/ui-settings-account/README.zh.md @@ -52,7 +52,7 @@ Chat 通过 `shell.overlay` 中的宿主把已绑定 Session 的实时欠费交 退出登录先查询正在使用账号 token 的任务,再打开确认弹窗。有此类任务时提示执行将被打断,否则提示数据保留且可重新登录。取消、关闭和 Escape 均不退登。影响查询失败仍打开确认弹窗,并明确提示无法确认任务状态;退登失败保留弹窗以便重试。 -账号通知的轮询与展示由 [ui-account-notifications](../ui-account-notifications/README.zh.md) 负责。账号菜单在侧栏内部将通知插槽定位于入口上方,收起为窄栏时隐藏但保留其 DOM,并发布账号生命周期和刷新事件。 +账号通知的轮询与展示由 [ui-account-notifications](../ui-account-notifications/README.zh.md) 负责。插件在设置外壳位于入口行上方的 `settings.notice` 行中渲染通知插槽,并发布账号生命周期和刷新事件。 ### Desktop 引导 @@ -61,12 +61,12 @@ Desktop preload 标记在账号凭证已存储后启用引导。进度属于本 欢迎页必须点击“开始设置”。额度页始终展示。首次进入时若已确认有正余额,则主操作为“继续”,次操作为“去充值”。该选择在引导控制器重建前保持固定且不持久化,后到的余额结果不会改变按钮。仅在确认不存在正余额时,继续而不充值才需确认;查询中或失败时不阻止继续。用途卡片选中后描述不变。从原生充值视图返回后保留额度页,并在等待任何已在进行的读取结束后于后台重读资料与余额,不受页面加载或支付结果影响。该读取不会重新计算该选择,因此充值成功后按钮仍保持首次进入时的状态,而继续前行仍按刷新后的余额判断。“下一步”仅在确认零余额时提示;额度页的“跳过”使用充值提示,答题页使用设置提示。仅选办公用途时以简洁展示完成;选择开发或两种用途时还会询问过程详情。上一步保留已有选择,任意可跳过步骤均采用标准工作过程、简洁性能与用量以及关闭代码工作工具的默认值。此流程不创建工作区或示例任务。 -访问控制:账号状态流、额度提醒、设置启动器、账号设置分区与模型登录入口只在当前 Peer 可以调用 `account/watch` 时存在;桌面引导与平台页面不受此控制。失去该权限时,这一轮发出的账号读取作废,待授权的浏览器标签页关闭,账号视图、详情、头像与登录对话框状态清空;之后再次授权时,账号分区等新流的第一帧到达后才重新出现。owner 始终有权限。 +访问控制:账号状态流、额度提醒、设置启动器、通知行、账号设置分区与模型登录入口只在当前 Peer 可以调用 `account/watch` 时存在;桌面引导与平台页面不受此控制。失去该权限时,这一轮发出的账号读取作废,待授权的浏览器标签页关闭,账号视图、详情、头像与登录对话框状态清空;之后再次授权时,账号分区等新流的第一帧到达后才重新出现。owner 始终有权限。 ## 理解实现 -仅登录后在设置导航首位显示账号页;账号状态加载完成前以及退出登录后隐藏该页。 插件持有一条 Host 快照流,通过框架 hook 供 settings.section 和 settings.launcher 共享。入口菜单可打开设置,并仅在已存储账号凭证时提供退出登录。Platform 请求失败时保留菜单,以供重试。插件不维护独立凭证状态。 +仅登录后在设置导航首位显示账号页;账号状态加载完成前以及退出登录后隐藏该页。 插件持有一条 Host 快照流,通过框架 hook 供 settings.section、settings.launcher 和 settings.notice 共享。入口菜单可打开设置,并仅在已存储账号凭证时提供退出登录。Platform 请求失败时保留菜单,以供重试。插件不维护独立凭证状态。 桌面控制器通过 Host 设置将进度写入 `ui-settings-account`。完成时先一并应用 `ui-chat.transcriptView` 与 `ui-chat.performanceUsage`,再通过共享代码工作工具偏好保存 `ui-settings.enabled`,最后保存完成标记;写入被拒绝时保留引导以供重试。成功完成后通过 180ms 淡出显露工作区;选择和普通翻页立即预览,写入在后台按顺序执行。队列最后一次写入失败时恢复已保存进度,并允许重试。完成操作会等待选择队列及偏好保存成功,再关闭页面;减少动态效果偏好会跳过淡出。onboarding 选项 compact、standard、detailed 直接应用到对应的 Chat 工作过程模式。API Key 进入与显式跳过均采用 standard;onboarding 不选择 verbose。完整 Figma 示意图层以透明、无损编码的 3× WebP [包资源](../AGENTS.md#dependency-declaration)形式提供;欢迎页图层合并并烘焙侧栏局部模糊;充值页前景窗口不透明度为 70%,仅烘焙其覆盖插图区域的模糊,标题使用已打包的 Montserrat 品牌字体,英文标题和描述使用 Light(300),标题中的 DeepSeek Harness 使用 Medium(500);卡片标题选中前后均使用 Regular(400)。英文底部导航使用 Light(300)。确认进入引导后,窗口最小宽度设为 960px,较窄窗口自动放大;完成后解除宽度限制,但不恢复原尺寸。加载中或已完成引导的启动不改变窗口尺寸。底部导航空白区域透过鼠标事件,避免遮挡主操作。卡片区域不参与原生窗口拖动,复选框的键盘焦点仅在卡片外框展示。账号包负责引导覆盖层和控件尺寸样式。每个步骤和确认弹窗各有独立组件,流程组件协调导航、切换动画和充值。初始账号与进度加载期间,覆盖层隐藏工作区。答题标题和卡片独立于操作按钮,位置对齐 Figma 的 1440 × 920 和 960 × 600 断点。在 macOS 上,Shell 为每个元素重置继承的窗口区域,位于内容之前的拖拽层保留 8px 原生缩放边缘。内容层的 `data-window-drag-controls` 范围排除交互控件,后续弹窗排除自身矩形;原生平台页面打开时禁用底层引导拖拽层。上方工作区弹窗插画在两种语言和主题下均使用不透明背景,下层侧边栏不绘制选中行高亮。欢迎页保持示意图的原始尺寸,在窄窗口内调整插图位置并裁切,在宽窗口内展示完整插图。[历史引导决策](../../../.agents/notes/archived/feature/2026-09-16-desktop-onboarding.md)记录持久化与展示方面的取舍。 diff --git a/packages/client/ui-settings-account/src/client/AccountMenu.module.css b/packages/client/ui-settings-account/src/client/AccountMenu.module.css index 773e791722..a18e586f6a 100644 --- a/packages/client/ui-settings-account/src/client/AccountMenu.module.css +++ b/packages/client/ui-settings-account/src/client/AccountMenu.module.css @@ -1,6 +1,5 @@ -.root { position: relative; flex: 1; min-width: 0; } +.root { flex: 1; min-width: 0; } .root[data-inset='true'] { margin-inline: 2px; } -.notifications { position: absolute; inset-inline: 0; bottom: calc(100% + 4px); z-index: 1; } .anchor { width: 100%; } .trigger { user-select: none; display: flex; align-items: center; width: 100%; height: 44px; gap: 8px; padding: 6px calc(var(--dsh-sidebar-row-padding) - var(--dsh-sidebar-paint-inset)); border: 0; border-inline: var(--dsh-sidebar-paint-inset) solid transparent; box-sizing: border-box; border-radius: var(--dsw-radius-md); background: transparent; background-clip: padding-box; color: var(--dsw-alias-label-primary); font: inherit; font-size: 14px; cursor: pointer; } .trigger[data-signed-out='false']:not([data-collapsed='true']) { padding: 6px; border-inline: 0; background-clip: border-box; } diff --git a/packages/client/ui-settings-account/src/client/AccountMenu.tsx b/packages/client/ui-settings-account/src/client/AccountMenu.tsx index 58838a5c6c..5e3b77f2f5 100644 --- a/packages/client/ui-settings-account/src/client/AccountMenu.tsx +++ b/packages/client/ui-settings-account/src/client/AccountMenu.tsx @@ -1,9 +1,9 @@ /** Sidebar account launcher and locally authoritative sign-out action. */ -import { useCallback, useEffect, useRef, useState } from 'react' +import { useEffect, useRef, useState } from 'react' import { Toast, Menu, IconEllipsisOutlineMedium, IconPaperPlaneOutlineMedium, IconSettingsOutlineMedium, IconUserOutlineMedium, } from '@deepseek-ai/dsh-client-ui-primitives' -import type { InjectFace, PropsLocale, PropsRuntime, PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots' +import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' import type { AccountSectionInjected } from './AccountSection.tsx' import { SignOutDialog } from './SignOutDialog.tsx' import { SignInDialog } from './SignInDialog.tsx' @@ -13,7 +13,7 @@ import type {} from './account-ui.ts' import css from './AccountMenu.module.css' /** Account launcher composed by the settings shell. */ -export type AccountMenuProps = PropsRuntime<'settings.launcher'> & PropsRenderSlots<'settings.launcher.notifications'> & PropsLocale<'settings.account'> & InjectFace +export type AccountMenuProps = PropsRuntime<'settings.launcher'> & PropsLocale<'settings.account'> & InjectFace /** The signed-in label stays empty while the profile loads. * @param props - sidebar geometry, settings navigation and account operations. @@ -21,7 +21,7 @@ export type AccountMenuProps = PropsRuntime<'settings.launcher'> & PropsRenderSl */ export function AccountMenu({ subscribeSessionExpired, subscribeModelSignInRequired, wide, settingsShortcut, openSettings, openOnboarding, settingsOpen, - useAccount, useTheme, signOut, hasRunningAccountTasks, refreshAccount, renderSlot, + useAccount, useTheme, signOut, hasRunningAccountTasks, refreshAccount, contactUs, showLogin, start, cancel, avatarFailed, t, }: AccountMenuProps) { // The launcher outlives the panel, so a false-to-true edge is one Settings entry: @@ -53,13 +53,9 @@ export function AccountMenu({ } // The plugin's start publishes `loginFailed` before it rejects, so the dialog owns the report. const beginSignIn = (): void => { setOpen(false); void start().catch(() => undefined) } - const openAccount = useCallback(() => { openSettings('account') }, [openSettings]) return
{signInNotice > 0 && { setSignInNotice(0) }} />} {expiryNotice && { setExpiryNotice(false) }} />} - { setOpen(value => !value) }}> diff --git a/packages/client/ui-settings-account/src/client/AccountNotices.module.css b/packages/client/ui-settings-account/src/client/AccountNotices.module.css new file mode 100644 index 0000000000..02c9ac99f3 --- /dev/null +++ b/packages/client/ui-settings-account/src/client/AccountNotices.module.css @@ -0,0 +1,2 @@ +/* Matches the signed-in launcher inset so the card edges align with the account row. */ +.root { margin-inline: 2px; } diff --git a/packages/client/ui-settings-account/src/client/AccountNotices.tsx b/packages/client/ui-settings-account/src/client/AccountNotices.tsx new file mode 100644 index 0000000000..42ecc5bb5b --- /dev/null +++ b/packages/client/ui-settings-account/src/client/AccountNotices.tsx @@ -0,0 +1,21 @@ +/** Account notification row above the sidebar account launcher. */ +import type { InjectFace, PropsRenderSlots, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +import type { AccountSectionInjected } from './AccountSection.tsx' +import type {} from './account-ui.ts' +import css from './AccountNotices.module.css' + +/** Notice row composed by the settings shell. */ +export type AccountNoticesProps = PropsRuntime<'settings.notice'> + & PropsRenderSlots<'settings.launcher.notifications'> & InjectFace + +/** + * @param props - settings navigation and account state. + * @returns the account notification extension, active only when signed in outside onboarding. + */ +export function AccountNotices({ openSettings, useAccount, renderSlot }: AccountNoticesProps) { + const account = useAccount(state => state) + const active = account.view?.status === 'credential-stored' && !account.desktopOnboardingVisible && !account.onboarding + return
{renderSlot('settings.launcher.notifications', { + active, openAccount: () => { openSettings('account') }, + })}
+} diff --git a/packages/client/ui-settings-account/src/client/account-ui.ts b/packages/client/ui-settings-account/src/client/account-ui.ts index e2c6e696ee..8ad0e24662 100644 --- a/packages/client/ui-settings-account/src/client/account-ui.ts +++ b/packages/client/ui-settings-account/src/client/account-ui.ts @@ -20,9 +20,9 @@ export interface AccountUi { clientMetadata(locale: string): AccountClientMetadata } -/** Account-menu presentation facts supplied to its notification extension. */ +/** Account presentation facts supplied to its notification extension. */ export interface AccountNotificationsOwnerProps { - /** Whether the account menu can display notifications outside onboarding. */ + /** Whether a signed-in account can display notifications outside onboarding. */ active: boolean /** Open the account section in the existing settings shell. */ openAccount: () => void @@ -43,7 +43,7 @@ declare module '@deepseek-ai/cordis' { declare module '@deepseek-ai/dsh-client-ui-slots' { interface SlotMap { - /** Notifications anchored at the account menu; the contribution owns its markup and lifecycle. */ + /** Notifications in the row above the account launcher; the contribution owns its markup and lifecycle. */ 'settings.launcher.notifications': { kind: 'single'; scope: 'root'; owner: AccountNotificationsOwnerProps } } } diff --git a/packages/client/ui-settings-account/src/client/index.ts b/packages/client/ui-settings-account/src/client/index.ts index a8ac2c89fa..e680e1cb32 100644 --- a/packages/client/ui-settings-account/src/client/index.ts +++ b/packages/client/ui-settings-account/src/client/index.ts @@ -20,6 +20,7 @@ import { BrowserLogin } from './browser-login.ts' import { AccountOnboarding } from './AccountOnboarding.tsx' import { AccountPlatformHost, type AccountPlatformHostInjected } from './AccountPlatformHost.tsx' import { AccountMenu } from './AccountMenu.tsx' +import { AccountNotices } from './AccountNotices.tsx' import { createPlatformPages, type PlatformPages } from './platform-pages.ts' import { AccountSection, type AccountSnapshot, type AccountSectionInjected } from './AccountSection.tsx' import { accountClientMetadata } from './client-metadata.ts' @@ -313,8 +314,11 @@ export function apply(ctx: Context): void { } ctx.remoteAccess.whenAccess('account/watch', () => ctx.slots.inject('settings.launcher', () => ctx.slots.register({ name: 'settings.launcher', locale: 'settings.account', inject: () => operations, - children: { 'settings.launcher.notifications': { kind: 'single', scope: 'root' } }, }, AccountMenu))) + ctx.remoteAccess.whenAccess('account/watch', () => ctx.slots.inject('settings.notice', () => ctx.slots.register({ + name: 'settings.notice', inject: () => operations, + children: { 'settings.launcher.notifications': { kind: 'single', scope: 'root' } }, + }, AccountNotices))) ctx.remoteAccess.whenAccess('account/watch', () => ctx.slots.inject('settings.section', () => { let unregister: (() => void) | undefined const update = () => { diff --git a/packages/client/ui-settings-account/tests/access-revocation.client.spec.ts b/packages/client/ui-settings-account/tests/access-revocation.client.spec.ts index 3e55d655d9..01a599b981 100644 --- a/packages/client/ui-settings-account/tests/access-revocation.client.spec.ts +++ b/packages/client/ui-settings-account/tests/access-revocation.client.spec.ts @@ -92,22 +92,22 @@ it('withdraws every account surface and the account stream on revocation, and re }, } const surfaces = (): Record => Object.fromEntries( - ['settings.launcher', 'shell.quota-notice', 'settings.models.sign-in', 'settings.section'].map(name => [name, registered.get(name)]), + ['settings.launcher', 'settings.notice', 'shell.quota-notice', 'settings.models.sign-in', 'settings.section'].map(name => [name, registered.get(name)]), ) try { apply(ctx as never) expect(new Set(guards.map(guard => guard.action))).toEqual(new Set(['account/watch'])) grant(guards) await streams[0]!.accepted - expect(surfaces()).toEqual({ 'settings.launcher': 1, 'shell.quota-notice': 1, 'settings.models.sign-in': 1, 'settings.section': 1 }) + expect(surfaces()).toEqual({ 'settings.launcher': 1, 'settings.notice': 1, 'shell.quota-notice': 1, 'settings.models.sign-in': 1, 'settings.section': 1 }) revoke(guards) expect(streams[0]!.signal.aborted).toBe(true) - expect(surfaces()).toEqual({ 'settings.launcher': 0, 'shell.quota-notice': 0, 'settings.models.sign-in': 0, 'settings.section': 0 }) + expect(surfaces()).toEqual({ 'settings.launcher': 0, 'settings.notice': 0, 'shell.quota-notice': 0, 'settings.models.sign-in': 0, 'settings.section': 0 }) grant(guards) await streams[1]!.accepted - expect(surfaces()).toEqual({ 'settings.launcher': 1, 'shell.quota-notice': 1, 'settings.models.sign-in': 1, 'settings.section': 1 }) + expect(surfaces()).toEqual({ 'settings.launcher': 1, 'settings.notice': 1, 'shell.quota-notice': 1, 'settings.models.sign-in': 1, 'settings.section': 1 }) } finally { revoke(guards) for (const dispose of lifetime.reverse()) dispose() diff --git a/packages/client/ui-settings-account/tests/account.client.spec.tsx b/packages/client/ui-settings-account/tests/account.client.spec.tsx index 85c85677d9..dd93b8fa79 100644 --- a/packages/client/ui-settings-account/tests/account.client.spec.tsx +++ b/packages/client/ui-settings-account/tests/account.client.spec.tsx @@ -10,6 +10,7 @@ import { createPlatformPages, type PlatformPages } from '../src/client/platform- import { AccountPlatformHost } from '../src/client/AccountPlatformHost.tsx' import { AccountSection, type AccountSectionInjected, type AccountSnapshot } from '../src/client/AccountSection.tsx' import type { AccountMenuProps } from '../src/client/AccountMenu.tsx' +import type { AccountNoticesProps } from '../src/client/AccountNotices.tsx' import type { AccountNotificationsOwnerProps } from '../src/client/account-ui.ts' import type {} from '../src/client/index.ts' import { en, zh, type AccountKey } from '../src/client/locales.ts' @@ -92,14 +93,12 @@ function SharedPlatformHost({ Globals, pages, platform, copy, refreshAccount }: * @param settingsOpen - whether the settings panel covers the sidebar. * @returns the sidebar launcher with its framework hooks wired to the test face. */ -async function accountMenu(operations: AccountSectionInjected, snapshot: () => AccountSnapshot, settingsOpen: boolean, - renderSlot: AccountMenuProps['renderSlot'] = () => null, - openSettings: AccountMenuProps['openSettings'] = () => {}, wide = true) { +async function accountMenu(operations: AccountSectionInjected, snapshot: () => AccountSnapshot, settingsOpen: boolean) { const { AccountMenu } = await import('../src/client/AccountMenu.tsx') - return selector(snapshot())} wide={wide} + return selector(snapshot())} wide useTheme={selector => selector(operations.hooks.theme.getSnapshot())} - openOnboarding={() => {}} openSettings={openSettings} t={key => en[key as AccountKey]} /> + openOnboarding={() => {}} openSettings={() => {}} t={key => en[key as AccountKey]} /> } it.each([en, zh])('renders account cards without inventing profile or balance data', async (copy) => { @@ -129,7 +128,7 @@ it.each([en, zh].flatMap(copy => ([false, true, 'unknown'] as const).map(running const operations = mount({ status: 'credential-stored', attempt: null }, copy) cleanup() const { AccountMenu } = await import('../src/client/AccountMenu.tsx') - render( null} {...({} as GlobalStandardProps)} {...operations} settingsOpen={false} signOut={signOut} + render( { if (running === 'unknown') throw new Error('offline'); return running }} useAccount={selector => selector(operations.hooks.account.getSnapshot())} useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide openOnboarding={() => {}} openSettings={openSettings} @@ -156,7 +155,7 @@ it.each([en, zh])('updates the Settings menu keycaps and accessible combination const operations = mount({ status: 'signed-out', attempt: null }, copy) cleanup() const { AccountMenu } = await import('../src/client/AccountMenu.tsx') - const props: AccountMenuProps = { renderSlot: () => null, + const props: AccountMenuProps = { ...({} as GlobalStandardProps), ...operations, wide: true, settingsOpen: false, useAccount: selector => selector(operations.hooks.account.getSnapshot()), useTheme: selector => selector(operations.hooks.theme.getSnapshot()), @@ -185,7 +184,7 @@ it.each([en, zh])('offers settings, contact and sign-in from the signed-out acco const openSettings = vi.fn() const operations = operationsOf({ status: 'signed-out', attempt: null }) const { AccountMenu } = await import('../src/client/AccountMenu.tsx') - render( null} {...({} as GlobalStandardProps)} {...operations} settingsOpen={false} + render( selector(operations.hooks.account.getSnapshot())} useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide openOnboarding={() => {}} openSettings={openSettings} t={key => key in copy ? copy[key as AccountKey] : key} />) @@ -205,7 +204,7 @@ it.each([en, zh])('offers settings, contact and sign-in from the signed-out acco it.each([true, false])('keeps the account inset local through sign-in changes with wide=%s', async (wide) => { const { AccountMenu } = await import('../src/client/AccountMenu.tsx') let operations = operationsOf({ status: 'signed-out', attempt: null }) - const props: AccountMenuProps = { renderSlot: () => null, + const props: AccountMenuProps = { ...({} as GlobalStandardProps), ...operations, wide, settingsOpen: false, useAccount: selector => selector(operations.hooks.account.getSnapshot()), useTheme: selector => selector(operations.hooks.theme.getSnapshot()), @@ -237,7 +236,7 @@ it('reports a failed start in the login dialog, not as a sidebar alert', async ( snapshot = { ...snapshot, loginVisible: true, loginFailed: true } return Promise.reject(new Error('account start failed')) }) - const view = render( null} {...({} as GlobalStandardProps)} {...operations} settingsOpen={false} + const view = render( selector(snapshot)} useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide openOnboarding={() => {}} openSettings={() => {}} @@ -246,7 +245,7 @@ it('reports a failed start in the login dialog, not as a sidebar alert', async ( await act(async () => { fireEvent.click(screen.getByRole('menuitem', { name: en.signIn })) }) expect(start).toHaveBeenCalledOnce() expect(screen.queryByRole('alert')).toBeNull() - view.rerender( null} {...({} as GlobalStandardProps)} {...operations} settingsOpen={false} + view.rerender( selector(snapshot)} useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide openOnboarding={() => {}} openSettings={() => {}} @@ -263,7 +262,7 @@ it('keeps the confirmation dialog open after a failed sign-out', async () => { cleanup() const { AccountMenu } = await import('../src/client/AccountMenu.tsx') const signOut = vi.fn((): Promise => Promise.reject(new Error('account sign-out failed'))) - render( null} {...({} as GlobalStandardProps)} {...operations} settingsOpen={false} + render( selector(operations.hooks.account.getSnapshot())} useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide @@ -426,7 +425,7 @@ it.each([ }) cleanup() const { AccountMenu } = await import('../src/client/AccountMenu.tsx') - render( null} {...({} as GlobalStandardProps)} {...operations} settingsOpen={false} + render( selector(operations.hooks.account.getSnapshot())} useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide openSettings={() => {}} openOnboarding={() => {}} t={key => en[key as AccountKey]} />) @@ -439,7 +438,7 @@ it('shows the same shared picture outcome in settings and the sidebar', async () profile: { status: 'ready', value: { id: null, name: 'User', contact: null, avatarUrl: 'https://example.test/avatar.png' } }, }, undefined, avatar) const { AccountMenu } = await import('../src/client/AccountMenu.tsx') - render( null} {...({} as GlobalStandardProps)} {...operations} settingsOpen={false} + render( selector(operations.hooks.account.getSnapshot())} useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide openSettings={() => {}} openOnboarding={() => {}} t={key => en[key as AccountKey]} />) @@ -510,7 +509,7 @@ it.each([en, zh])('shows a localized toast when the account credential expires', const { AccountMenu } = await import('../src/client/AccountMenu.tsx') let expire: (() => void) | undefined const unsubscribe = vi.fn() - const element = null} {...({} as GlobalStandardProps)} {...operations} + const element = { expire = listener; return unsubscribe }} useAccount={selector => selector(operations.hooks.account.getSnapshot())} useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide openOnboarding={() => {}} openSettings={() => {}} @@ -609,7 +608,7 @@ it('dismisses a collapsed menu and hands its login dialog to the API-key onboard const { AccountMenu } = await import('../src/client/AccountMenu.tsx') const openOnboarding = vi.fn() let snapshot = operations.hooks.account.getSnapshot() - const props = { ...({} as GlobalStandardProps), ...operations, renderSlot: () => null, wide: false, settingsOpen: false, + const props = { ...({} as GlobalStandardProps), ...operations, wide: false, settingsOpen: false, openSettings: vi.fn(), openOnboarding, useAccount: (select: (value: AccountSnapshot) => T) => select(snapshot), useTheme: (select: (value: ThemeSnapshot) => T) => select(operations.hooks.theme.getSnapshot()), @@ -698,7 +697,7 @@ it.each([en, zh])('shows live model sign-in guidance without replaying it after const unsubscribe = vi.fn(() => { listener = undefined }) operations.subscribeModelSignInRequired = (next) => { listener = next; return unsubscribe } const { AccountMenu } = await import('../src/client/AccountMenu.tsx') - const element = null} {...({} as GlobalStandardProps)} {...operations} + const element = selector(operations.hooks.account.getSnapshot())} useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide openOnboarding={() => {}} openSettings={() => {}} @@ -720,12 +719,13 @@ it.each([en, zh])('shows live model sign-in guidance without replaying it after }) it.each(['desktopOnboardingVisible', 'onboarding'] as const)('hides the notification slot until %s ends', async (field) => { + const { AccountNotices } = await import('../src/client/AccountNotices.tsx') const operations = operationsOf({ status: 'credential-stored', attempt: null }) let snapshot: AccountSnapshot = { ...operations.hooks.account.getSnapshot(), [field]: true } let active: boolean | undefined let openAccount: (() => void) | undefined const openSettings = vi.fn() - const renderSlot: AccountMenuProps['renderSlot'] = (name, owner) => { + const renderSlot: AccountNoticesProps['renderSlot'] = (name, owner) => { expect(name).toBe('settings.launcher.notifications') const value: object = owner const props = value as AccountNotificationsOwnerProps @@ -733,25 +733,29 @@ it.each(['desktopOnboardingVisible', 'onboarding'] as const)('hides the notifica openAccount = props.openAccount return null } - const view = render(await accountMenu(operations, () => snapshot, false, renderSlot, openSettings)) + const notices = () => selector(snapshot)} + useTheme={selector => selector(operations.hooks.theme.getSnapshot())} openSettings={openSettings} /> + const view = render(notices()) expect(active).toBe(false) snapshot = { ...snapshot, [field]: false } - view.rerender(await accountMenu(operations, () => snapshot, false, renderSlot, openSettings)) + view.rerender(notices()) expect(active).toBe(true) openAccount?.() expect(openSettings).toHaveBeenCalledExactlyOnceWith('account') }) -it('keeps notification DOM inside the launcher while the collapsed rail hides it', async () => { - const operations = operationsOf({ status: 'credential-stored', attempt: null }) - const snapshot = () => operations.hooks.account.getSnapshot() - const renderSlot: AccountMenuProps['renderSlot'] = () =>
Notification
- const view = render(await accountMenu(operations, snapshot, false, renderSlot)) - const notice = screen.getByRole('status') - expect(view.container.contains(notice)).toBe(true) - view.rerender(await accountMenu(operations, snapshot, false, renderSlot, undefined, false)) - expect(screen.queryByRole('status')).toBeNull() - expect(notice.isConnected).toBe(true) - view.rerender(await accountMenu(operations, snapshot, false, renderSlot)) - expect(screen.getByRole('status')).toBe(notice) +it('keeps the notification slot inactive while signed out', async () => { + const { AccountNotices } = await import('../src/client/AccountNotices.tsx') + const operations = operationsOf({ status: 'signed-out', attempt: null }) + const owners: AccountNotificationsOwnerProps[] = [] + const renderSlot: AccountNoticesProps['renderSlot'] = (_name, owner) => { + const value: object = owner + owners.push(value as AccountNotificationsOwnerProps) + return null + } + render( selector(operations.hooks.account.getSnapshot())} + useTheme={selector => selector(operations.hooks.theme.getSnapshot())} openSettings={() => {}} />) + expect(owners.at(-1)?.active).toBe(false) }) diff --git a/packages/client/ui-settings-account/tests/quota-notice-hold.client.spec.tsx b/packages/client/ui-settings-account/tests/quota-notice-hold.client.spec.tsx index 7393ce1d5a..d00a17cf35 100644 --- a/packages/client/ui-settings-account/tests/quota-notice-hold.client.spec.tsx +++ b/packages/client/ui-settings-account/tests/quota-notice-hold.client.spec.tsx @@ -3,6 +3,7 @@ * The account takeover inside the shipped composition: the frame-wide notice * chain, the account settings page, and the one shared native Platform host. */ +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { apply as applyMenus, inject as injectMenus } from '@deepseek-ai/dsh-client-ui-context-menu/client' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { afterEach, describe, expect, it, vi } from 'vitest' @@ -111,7 +112,7 @@ async function bench() { const locale = new LocaleRuntime(runtime.ctx) runtime.ctx.provide('locale', locale) runtime.ctx.provide('shortcuts', { catalog: createSnapshotStore([]) }) - await runtime.mount({ apply: applyMenus, inject: injectMenus }) + await runtime.mount({ apply: applyMenus, inject: injectMenus }, syncedConfig({ resolutionTimeoutMs: 1000 })) runtime.slots.installLocale(locale) runtime.ctx.effect(() => locale.register('settings.account', { en, zh }), 'spec: account dictionaries') await runtime.declare({ @@ -119,7 +120,7 @@ async function bench() { 'settings.section': { kind: 'list', scope: 'root' }, 'conversation.approval.detail': { kind: 'single', scope: 'session' }, }) - await runtime.mount({ inject: [...injectConversation], apply: applyConversation }) + await runtime.mount({ inject: [...injectConversation], apply: applyConversation }, syncedConfig({ busyEnter: 'queue', maxConcurrentFileUploads: 2 })) let descriptor: Parameters[0] | undefined const provide = runtime.ctx.uiSession.provide.bind(runtime.ctx.uiSession) runtime.ctx.uiSession.provide = (next) => { descriptor ??= next; return provide(next) } diff --git a/packages/client/ui-settings-general/README.i18n.yaml b/packages/client/ui-settings-general/README.i18n.yaml index 1bbfb63a97..a56b70ab37 100644 --- a/packages/client/ui-settings-general/README.i18n.yaml +++ b/packages/client/ui-settings-general/README.i18n.yaml @@ -27,8 +27,8 @@ en: 7600861d064dbc99 zh: a52ba446016e3a21 /deepseek-ai-dsh-client-ui-settings-general/understand-the-implementation: - en: 4d25df8fe0e60b20 - zh: cecd02d3b6e47b24 + en: 2ba62c7be5b79052 + zh: 9220e867a0e88076 /deepseek-ai-dsh-client-ui-settings-general/understand-the-implementation/ledger-projections: en: fd99444278ab8530 zh: 2efc5831c7e19be1 diff --git a/packages/client/ui-settings-general/README.md b/packages/client/ui-settings-general/README.md index 8e5c7ef0d3..a12ef36089 100644 --- a/packages/client/ui-settings-general/README.md +++ b/packages/client/ui-settings-general/README.md @@ -68,7 +68,7 @@ Desktop also contributes an **Update channel** row to General when the preload e ## Understand the implementation -The shell declares settings.launcher for an account-owned sidebar menu and retains the Settings button as its fallback. The launcher receives settingsOpen, whose false-to-true edge marks one Settings entry, so a registrant acts once per entry instead of on every re-render inside one open. Closing the dialog returns focus to the active launcher. In the expanded sidebar, the fallback uses the navigation rows' compact icon-label alignment and inset hover fill. Contributed launchers own their insets; the shell keeps its row full-width and its status indicator's trailing edge independent of account state. The collapsed rail retains its centered 36 × 36 px control. The launcher can pass a section ID to openSettings to open that section directly; an absent ID uses the default section. +The shell declares settings.launcher for an account-owned sidebar menu and retains the Settings button as its fallback. The launcher receives settingsOpen, whose false-to-true edge marks one Settings entry, so a registrant acts once per entry instead of on every re-render inside one open. Closing the dialog returns focus to the active launcher. In the expanded sidebar, the fallback uses the navigation rows' compact icon-label alignment and inset hover fill. Contributed launchers own their insets; the shell keeps its row full-width and its status indicator's trailing edge independent of account state. The collapsed rail retains its centered 36 × 36 px control. The launcher can pass a section ID to openSettings to open that section directly; an absent ID uses the default section. The shell also declares settings.notice and renders it in a zero-height, full-width row above the launcher row; its content floats over the sidebar list, so status indicators beside the launcher do not narrow its content; the collapsed rail hides that row without unmounting it.
Implementation internals — click to expand diff --git a/packages/client/ui-settings-general/README.zh.md b/packages/client/ui-settings-general/README.zh.md index 4012c252d6..d3db7fcf87 100644 --- a/packages/client/ui-settings-general/README.zh.md +++ b/packages/client/ui-settings-general/README.zh.md @@ -68,7 +68,7 @@ Web 与桌面端的通用设置底部显示当前发布版本,使用构建注 ## 理解实现 -外壳声明 settings.launcher,供账号功能提供侧边栏菜单,并以设置按钮作为回退。入口接收 settingsOpen,其 false→true 边沿代表一次进入设置页,因此注册方在每次进入时执行一次,而不是在同一次打开中的每次重渲染执行。关闭对话框后,焦点返回当前入口。侧栏展开时,回退按钮采用导航行的紧凑图文对齐及内缩悬停底色。贡献入口自行拥有内缩;外壳保持行宽占满可用空间,状态指示器的尾侧边缘不随账号状态移动。折叠轨道保留居中的 36 × 36 px 控件。 入口可以向 openSettings 传入分区 ID,直接打开对应分区;未传 ID 时使用默认分区。 +外壳声明 settings.launcher,供账号功能提供侧边栏菜单,并以设置按钮作为回退。入口接收 settingsOpen,其 false→true 边沿代表一次进入设置页,因此注册方在每次进入时执行一次,而不是在同一次打开中的每次重渲染执行。关闭对话框后,焦点返回当前入口。侧栏展开时,回退按钮采用导航行的紧凑图文对齐及内缩悬停底色。贡献入口自行拥有内缩;外壳保持行宽占满可用空间,状态指示器的尾侧边缘不随账号状态移动。折叠轨道保留居中的 36 × 36 px 控件。 入口可以向 openSettings 传入分区 ID,直接打开对应分区;未传 ID 时使用默认分区。外壳还声明 settings.notice,并在入口行上方零高度的满宽行中渲染它,其内容浮在侧栏列表之上,因此入口旁的状态指示器不会挤压其内容;折叠轨道隐藏该行但不卸载它。
实现细节——点击展开 diff --git a/packages/client/ui-settings-general/src/client/SettingsRoot.module.css b/packages/client/ui-settings-general/src/client/SettingsRoot.module.css index 29c3d52c45..4bc579e344 100644 --- a/packages/client/ui-settings-general/src/client/SettingsRoot.module.css +++ b/packages/client/ui-settings-general/src/client/SettingsRoot.module.css @@ -8,6 +8,20 @@ margin: 4px 0; } +/* The notice row takes no height: its content floats above the sidebar list at + the row's full width, so status indicators in the trigger row do not narrow it. */ +.noticeRow { + position: relative; + height: 0; +} + +.notice { + position: absolute; + inset-inline: 0; + bottom: 0; + z-index: 1; +} + .triggerRow.railRow { width: 36px; margin: 8px 0 10px; diff --git a/packages/client/ui-settings-general/src/client/SettingsRoot.tsx b/packages/client/ui-settings-general/src/client/SettingsRoot.tsx index e461d65868..96bddf9410 100644 --- a/packages/client/ui-settings-general/src/client/SettingsRoot.tsx +++ b/packages/client/ui-settings-general/src/client/SettingsRoot.tsx @@ -221,14 +221,17 @@ export function SettingsRoot(props: SettingsRootComponentProps) { connectionIndicator = 'recovered' } + const openSettings = (sectionId?: string): void => { + if (sectionId === undefined) actions.open() + else actions.openSection(sectionId) + } + return ( <> +
{renderSlot('settings.launcher', { - wide, settingsOpen: open, openSettings: (sectionId) => { - if (sectionId === undefined) actions.open() - else actions.openSection(sectionId) - }, + wide, settingsOpen: open, openSettings, ...(shortcut?.keys.length ? { settingsShortcut: { keys: shortcut.keys, aria: shortcut.aria } } : {}), openOnboarding: (id) => { close(); setRequestedOnboarding(id) }, }, { fallback: diff --git a/packages/client/ui-settings-general/src/client/index.ts b/packages/client/ui-settings-general/src/client/index.ts index 5303fb46ba..ee3bb86d99 100644 --- a/packages/client/ui-settings-general/src/client/index.ts +++ b/packages/client/ui-settings-general/src/client/index.ts @@ -236,6 +236,7 @@ export function apply(ctx: ClientContext): void { store: shellStore, children: { 'settings.launcher': { kind: 'single', scope: 'root' }, + 'settings.notice': { kind: 'single', scope: 'root' }, 'settings.trigger': { kind: 'single', scope: 'root' }, 'settings.header': { kind: 'single', scope: 'root' }, 'settings.action': { kind: 'list', scope: 'root' }, diff --git a/packages/client/ui-settings-general/src/client/shell-contract.ts b/packages/client/ui-settings-general/src/client/shell-contract.ts index 6c548e1e1d..1150d3f48c 100644 --- a/packages/client/ui-settings-general/src/client/shell-contract.ts +++ b/packages/client/ui-settings-general/src/client/shell-contract.ts @@ -67,6 +67,7 @@ export type SettingsRootComponentProps = PropsRuntime<'sidebar.settings'> & PropsRenderSlots< | 'settings.launcher' + | 'settings.notice' | 'settings.trigger' | 'settings.header' | 'settings.action' diff --git a/packages/client/ui-settings-general/tests/settings-root.client.spec.tsx b/packages/client/ui-settings-general/tests/settings-root.client.spec.tsx index b728799793..0d37968a37 100644 --- a/packages/client/ui-settings-general/tests/settings-root.client.spec.tsx +++ b/packages/client/ui-settings-general/tests/settings-root.client.spec.tsx @@ -42,6 +42,7 @@ type Step = { id: string; order: number } /** Slot-content stand-ins: the shell renders whatever the seats contribute. */ const SEAT_CONTENT: Record = { 'settings.trigger': 'Settings', + 'settings.notice': 'Account notice', 'settings.header': 'Settings Title', 'settings.action': 'Open configuration file', 'settings.close': 'Close', @@ -165,6 +166,7 @@ function mount({ desktopUpdate = next view.rerender() } + const setWide = (next: boolean) => { view.rerender() } const setShortcuts = (next: readonly ShortcutCatalogEntry[]) => { shortcuts = next view.rerender() @@ -178,7 +180,7 @@ function mount({ } return { view, renderSlot, renderFactorySlot, bump, listeners, reconnect, - setConnectionState, setDesktopUpdate, setShortcuts, setOnboardingActive, + setConnectionState, setDesktopUpdate, setShortcuts, setOnboardingActive, setWide, } } @@ -558,3 +560,24 @@ it('passes current Settings key labels to the launcher and removes them when unb setShortcuts([{ ...row, keys: [], aria: undefined, binding: null, modified: true }]) expect(launcher()).not.toHaveProperty('settingsShortcut') }) + +it('renders the notice row before the launcher row and opens the requested section', () => { + const { renderSlot } = mount({ rows: [{ id: 'general', order: 0, label: 'General' }, { id: 'account', order: 1, label: 'Account' }] }) + const notice = screen.getByText('Account notice').parentElement! + expect(notice.nextElementSibling?.contains(screen.getByRole('button', { name: 'Settings' }))).toBe(true) + const owner = renderSlot.mock.calls.find(call => call[0] === 'settings.notice')! + act(() => { (owner[1] as { openSettings: (sectionId?: string) => void }).openSettings('account') }) + expect(screen.getByTestId('section-account')).toBeTruthy() +}) + +it('hides the notice row in the collapsed rail and keeps the same node', () => { + const { setWide } = mount() + const notice = screen.getByText('Account notice').parentElement! + expect(notice.hidden).toBe(false) + setWide(false) + expect(screen.getByText('Account notice').parentElement).toBe(notice) + expect(notice.hidden).toBe(true) + setWide(true) + expect(screen.getByText('Account notice').parentElement).toBe(notice) + expect(notice.hidden).toBe(false) +}) diff --git a/packages/client/ui-settings-general/tests/shell.client.spec.ts b/packages/client/ui-settings-general/tests/shell.client.spec.ts index 8e36d7bde4..c728b1e704 100644 --- a/packages/client/ui-settings-general/tests/shell.client.spec.ts +++ b/packages/client/ui-settings-general/tests/shell.client.spec.ts @@ -28,6 +28,7 @@ function injectedOf(c: TestClient): SettingsRootInjected { /** The slots this package declares, through the shell or the `settings.section.view` Factory. */ const CHILD_SPECS = { 'settings.launcher': { kind: 'single', scope: 'root' }, + 'settings.notice': { kind: 'single', scope: 'root' }, 'settings.trigger': { kind: 'single', scope: 'root' }, 'settings.header': { kind: 'single', scope: 'root' }, 'settings.action': { kind: 'list', scope: 'root' }, diff --git a/packages/client/ui-settings/README.i18n.yaml b/packages/client/ui-settings/README.i18n.yaml index 5a1a4df3b2..6c4ca00638 100644 --- a/packages/client/ui-settings/README.i18n.yaml +++ b/packages/client/ui-settings/README.i18n.yaml @@ -30,8 +30,8 @@ en: 9767f17ca0f02ae3 zh: 8e475d6d3d670702 /deepseek-ai-dsh-client-ui-settings/understand-the-implementation: - en: 84b6449030ffabe7 - zh: 958382ead3ab0407 + en: 6741f576de0585c2 + zh: 5b621d137e52b63e /deepseek-ai-dsh-client-ui-settings/understand-the-implementation/the-describe-mirror: en: 0cd270ddcac46776 zh: 4e03bf1d153b3f04 diff --git a/packages/client/ui-settings/README.md b/packages/client/ui-settings/README.md index a575d5b5e2..6cb716d1dc 100644 --- a/packages/client/ui-settings/README.md +++ b/packages/client/ui-settings/README.md @@ -55,7 +55,7 @@ A committed write folds its answer into the shared mirror. Refused writes refres ## Understand the implementation -The optional `settings.launcher` contribution receives sidebar geometry, whether the open Settings panel covers the sidebar, the settings navigation callbacks, and the effective Settings key labels and accessible combination. The shell omits shortcut presentation for an unbound command and retains its plain Settings trigger when no launcher is registered. The launcher can pass a section ID to openSettings to open that section directly; an absent ID uses the default section. +The optional `settings.launcher` contribution receives sidebar geometry, whether the open Settings panel covers the sidebar, the settings navigation callbacks, and the effective Settings key labels and accessible combination. The shell omits shortcut presentation for an unbound command and retains its plain Settings trigger when no launcher is registered. The launcher can pass a section ID to openSettings to open that section directly; an absent ID uses the default section. The optional `settings.notice` contribution receives openSettings and renders in a zero-height, full-width row above the launcher row, floating over the sidebar list; the shell hides that row in the collapsed rail without unmounting it.
Implementation internals — click to expand diff --git a/packages/client/ui-settings/README.zh.md b/packages/client/ui-settings/README.zh.md index 3503c75b9d..ba4e030086 100644 --- a/packages/client/ui-settings/README.zh.md +++ b/packages/client/ui-settings/README.zh.md @@ -55,7 +55,7 @@ kind: "package-reference" ## 理解实现 -可选的 `settings.launcher` 贡献接收侧栏布局、设置面板是否覆盖侧栏、设置导航回调,以及有效的设置键位标签和无障碍组合。命令未绑定时,外壳不传快捷键展示信息;未注册入口时,外壳保留普通设置按钮。 入口可以向 openSettings 传入分区 ID,直接打开对应分区;未传 ID 时使用默认分区。 +可选的 `settings.launcher` 贡献接收侧栏布局、设置面板是否覆盖侧栏、设置导航回调,以及有效的设置键位标签和无障碍组合。命令未绑定时,外壳不传快捷键展示信息;未注册入口时,外壳保留普通设置按钮。 入口可以向 openSettings 传入分区 ID,直接打开对应分区;未传 ID 时使用默认分区。可选的 `settings.notice` 贡献接收 openSettings,渲染在入口行上方零高度的满宽行中,浮在侧栏列表之上;折叠轨道中外壳隐藏该行但不卸载它。
实现细节——点击展开 diff --git a/packages/client/ui-settings/src/client/contract/slots.ts b/packages/client/ui-settings/src/client/contract/slots.ts index f9b89e70a6..7c2c5aedcf 100644 --- a/packages/client/ui-settings/src/client/contract/slots.ts +++ b/packages/client/ui-settings/src/client/contract/slots.ts @@ -30,6 +30,12 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { interface SlotMap { /** Optional sidebar account launcher; opens the shell-owned settings panel. */ 'settings.launcher': { kind: 'single'; scope: 'root'; owner: SettingsLauncherOwnerProps } + /** + * Optional content anchored above the launcher row at the launcher row's + * full width. The row takes no height, so the content floats over the + * sidebar list; the shell hides it in the rail without unmounting it. + */ + 'settings.notice': { kind: 'single'; scope: 'root'; owner: SettingsNoticeOwnerProps } /** * The sidebar-foot trigger row content: icon + label, supplied as slot @@ -167,6 +173,12 @@ export interface SettingsOnboardingOwnerProps { openSection: (id: string) => void } +/** Settings navigation for the row above the launcher row. */ +export interface SettingsNoticeOwnerProps { + /** @param sectionId - section to open; absent uses the shell's default section. */ + openSettings: (sectionId?: string) => void +} + /** Sidebar launcher geometry and settings navigation. */ export interface SettingsLauncherOwnerProps { /** Whether the sidebar shows labels. */ diff --git a/packages/client/ui-settings/src/client/index.ts b/packages/client/ui-settings/src/client/index.ts index 6b23b57d2d..7f6e7d7bef 100644 --- a/packages/client/ui-settings/src/client/index.ts +++ b/packages/client/ui-settings/src/client/index.ts @@ -14,7 +14,7 @@ import { SettingsDescribeMirror } from './settings-mirror.ts' export type { SettingsLauncherOwnerProps, SettingsGeneralItemOwnerProps, SettingsHeaderOwnerProps, SettingsOnboardingOwnerProps, - SettingsSectionIconOwnerProps, SettingsSectionOwnerProps, SettingsSectionViewProps, SettingsTriggerOwnerProps, + SettingsNoticeOwnerProps, SettingsSectionIconOwnerProps, SettingsSectionOwnerProps, SettingsSectionViewProps, SettingsTriggerOwnerProps, } from './contract/slots.ts' export type { ConfigForms } from './config-form.ts' export type { ConfigForm, ConfigFormSnapshot } from './config-form-types.ts' diff --git a/packages/client/ui-sidebar-right/tests/seat.client.spec.tsx b/packages/client/ui-sidebar-right/tests/seat.client.spec.tsx index 3d1f634711..1380ed4bab 100644 --- a/packages/client/ui-sidebar-right/tests/seat.client.spec.tsx +++ b/packages/client/ui-sidebar-right/tests/seat.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { apply as applyMenus, inject as injectMenus } from '@deepseek-ai/dsh-client-ui-context-menu/client' /** Sidebar presentation and tab subscriptions through the production slot renderer. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -81,7 +82,7 @@ async function mountSeat(viewportWidth = 1440, canShow = true, entryCount = 0, o const catalog = createSnapshotStore([]) runtime.ctx.provide('shortcuts', { register: () => () => {}, catalog } as never) runtime.slots.installLocale(locale) - await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }, syncedConfig({ resolutionTimeoutMs: 1000 })) await runtime.declare({ 'sidebar-right.test.opener': { kind: 'single', scope: 'session' }, 'rightbar': { kind: 'single', scope: 'root' }, diff --git a/packages/client/ui-tool/tests/assembly-surfaces.client.spec.tsx b/packages/client/ui-tool/tests/assembly-surfaces.client.spec.tsx index 5dc1711ca4..c2172a1ab4 100644 --- a/packages/client/ui-tool/tests/assembly-surfaces.client.spec.tsx +++ b/packages/client/ui-tool/tests/assembly-surfaces.client.spec.tsx @@ -1,3 +1,4 @@ +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { apply as applyMenus, inject as injectMenus } from '@deepseek-ai/dsh-client-ui-context-menu/client' import { toolSessionEvents } from './tool-fixtures.client.ts' @@ -104,7 +105,7 @@ async function bench(nodes: ToolResultNode[]) { runtime.ctx.provide('locale', locale) runtime.slots.installLocale(locale) runtime.ctx.provide('shortcuts', { catalog: createSnapshotStore([]) }) - await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }, syncedConfig({ resolutionTimeoutMs: 1000 })) await runtime.sessions.add({ id: SID, summary: { title: 'S', displayTitle: 'S', cwd: '/proj' }, @@ -116,7 +117,7 @@ async function bench(nodes: ToolResultNode[]) { }) await runtime.sessions.retainFor(runtime.ctx, SID, { source: 'mainView' }).ready await runtime.root.declare(LAYOUT_CHILDREN, AppRoot) - await runtime.mount({ inject: [...injectConversation], apply: applyConversation }) + await runtime.mount({ inject: [...injectConversation], apply: applyConversation }, syncedConfig({ busyEnter: 'queue', maxConcurrentFileUploads: 2 })) await runtime.mount({ inject: [...injectChat], apply: applyChat }) await runtime.mount({ inject: [...injectTool], apply: applyTool }) return runtime diff --git a/packages/client/ui-tool/tests/chat-ptc-subcalls.client.spec.tsx b/packages/client/ui-tool/tests/chat-ptc-subcalls.client.spec.tsx index 91cf3bc474..5e6968e33d 100644 --- a/packages/client/ui-tool/tests/chat-ptc-subcalls.client.spec.tsx +++ b/packages/client/ui-tool/tests/chat-ptc-subcalls.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { apply as applyMenus, inject as injectMenus } from '@deepseek-ai/dsh-client-ui-context-menu/client' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -143,7 +144,7 @@ async function bench(snapshot: ChatSnapshot) { locale.register(CONVERSATION_NS, { zh: conversationZh, en: conversationEn }) runtime.slots.installLocale(locale) runtime.ctx.provide('shortcuts', { catalog: createSnapshotStore([]) }) - await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }, syncedConfig({ resolutionTimeoutMs: 1000 })) await runtime.root.declare(ROOT_CHILDREN, AppRoot) await runtime.mount({ inject: [...injectChat], apply: applyChat }) diff --git a/packages/client/ui-tool/tests/toolview-slot.client.spec.tsx b/packages/client/ui-tool/tests/toolview-slot.client.spec.tsx index 0d16e96f13..0c68634e68 100644 --- a/packages/client/ui-tool/tests/toolview-slot.client.spec.tsx +++ b/packages/client/ui-tool/tests/toolview-slot.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { apply as applyMenus, inject as injectMenus } from '@deepseek-ai/dsh-client-ui-context-menu/client' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' @@ -100,7 +101,7 @@ async function bench(nodes: ToolResultNode[]) { runtime.ctx.provide('locale', locale) runtime.slots.installLocale(locale) runtime.ctx.provide('shortcuts', { catalog: createSnapshotStore([]) }) - await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }, syncedConfig({ resolutionTimeoutMs: 1000 })) await runtime.sessions.add({ id: SID, summary: { title: 'S', displayTitle: 'S', cwd: '/w' }, @@ -112,7 +113,7 @@ async function bench(nodes: ToolResultNode[]) { }) await runtime.sessions.retainFor(runtime.ctx, SID, { source: 'mainView' }).ready await runtime.root.declare(LAYOUT_CHILDREN, AppRoot) - await runtime.mount({ inject: [...injectConversation], apply: applyConversation }) + await runtime.mount({ inject: [...injectConversation], apply: applyConversation }, syncedConfig({ busyEnter: 'queue', maxConcurrentFileUploads: 2 })) await runtime.mount({ inject: [...injectChat], apply: applyChat }) await runtime.mount({ inject: [...injectTool], apply: applyTool }) return { runtime, slots: runtime.slots, layout, openWorkspacePath, sidebarRight } @@ -381,7 +382,7 @@ describe('registrant declaration injection', () => { runtime.ctx.provide('locale', locale) runtime.slots.installLocale(locale) runtime.ctx.provide('shortcuts', { catalog: createSnapshotStore([]) }) - await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }, syncedConfig({ resolutionTimeoutMs: 1000 })) await runtime.root.declare(LAYOUT_CHILDREN, AppRoot) // Third-party posture, mounted BEFORE ui-conversation. Plugin apply runs, @@ -403,7 +404,7 @@ describe('registrant declaration injection', () => { expect(runtime.slots.entries('tool.call.toolview')).toHaveLength(0) // Mounting the package declares the slot and activates the waiting entry. - await runtime.mount({ inject: [...injectConversation], apply: applyConversation }) + await runtime.mount({ inject: [...injectConversation], apply: applyConversation }, syncedConfig({ busyEnter: 'queue', maxConcurrentFileUploads: 2 })) await runtime.mount({ inject: [...injectChat], apply: applyChat }) await runtime.mount({ inject: [...injectTool], apply: applyTool }) expect(runtime.slots.entries('tool.call.toolview').map(e => e.options.key)) diff --git a/packages/client/ui-workspace/tests/access-assembly.client.spec.tsx b/packages/client/ui-workspace/tests/access-assembly.client.spec.tsx index 1adc908ff6..216348dd92 100644 --- a/packages/client/ui-workspace/tests/access-assembly.client.spec.tsx +++ b/packages/client/ui-workspace/tests/access-assembly.client.spec.tsx @@ -7,6 +7,7 @@ * remote-access snapshot owner itself and renders the real slot tree, so the Workspace access Hooks * are the renderer's bindings over one non-owner snapshot. */ +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { act, cleanup, screen } from '@testing-library/react' import type { AccessEffect, RemoteEndpoint, TypertResourceKind } from '@deepseek-ai/dsh-api-remote-access/client' @@ -79,7 +80,7 @@ async function bench(access: ClientAccessState, options: { ungroupedSession?: Se { 'sidebar.workspaces': { kind: 'single', scope: 'root', inject: SECTION_INJECT } } as never, SidebarFrame as never, ) - await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }, syncedConfig({ resolutionTimeoutMs: 1000 })) await runtime.mount({ inject: [...inject], apply }) return runtime } diff --git a/packages/client/ui-workspace/tests/host-home-staleness.client.spec.tsx b/packages/client/ui-workspace/tests/host-home-staleness.client.spec.tsx index 26a7fe523e..2d245f47f8 100644 --- a/packages/client/ui-workspace/tests/host-home-staleness.client.spec.tsx +++ b/packages/client/ui-workspace/tests/host-home-staleness.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { apply as applyMenus, inject as injectMenus } from '@deepseek-ai/dsh-client-ui-context-menu/client' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' /** @@ -41,7 +42,7 @@ async function bench() { const locale = new LocaleRuntime(runtime.ctx) runtime.ctx.provide('locale', locale) runtime.slots.installLocale(locale) - await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }, syncedConfig({ resolutionTimeoutMs: 1000 })) await runtime.workspaces.update((draft) => { draft.items = [{ workspaceId: 'w1' as WorkspaceId, title: 'Project', path: '/home/u/Documents/project', diff --git a/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx b/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx index fedc107546..ed0ada567b 100644 --- a/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx +++ b/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { apply as applyMenus, inject as injectMenus } from '@deepseek-ai/dsh-client-ui-context-menu/client' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' /** @@ -49,7 +50,7 @@ async function createRuntime(): Promise { const locale = new LocaleRuntime(runtime.ctx) runtime.ctx.provide('locale', locale) runtime.slots.installLocale(locale) - await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }, syncedConfig({ resolutionTimeoutMs: 1000 })) return runtime } diff --git a/packages/client/ui-workspace/tests/workspace-picker-factory.client.spec.tsx b/packages/client/ui-workspace/tests/workspace-picker-factory.client.spec.tsx index c6e361a813..ae59b2fbe6 100644 --- a/packages/client/ui-workspace/tests/workspace-picker-factory.client.spec.tsx +++ b/packages/client/ui-workspace/tests/workspace-picker-factory.client.spec.tsx @@ -9,6 +9,7 @@ * listed Workspaces, the occupancy-gated add entry, and the creation hop * before `onPick`. */ +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { act, cleanup, fireEvent, screen } from '@testing-library/react' import { useRef, useState } from 'react' @@ -95,7 +96,7 @@ async function bench(): Promise { sessionIds: [], createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z', }] as never }) - await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }, syncedConfig({ resolutionTimeoutMs: 1000 })) await runtime.mount({ inject: [...inject], apply }) await runtime.root.declare({} as never, ImportDialog as never) runtime.renderRoot() diff --git a/packages/core/agent-loop/tests/fixtures/serial-created.mjs b/packages/core/agent-loop/tests/fixtures/serial-created.mjs index e3e659f15c..310d3485a5 100644 --- a/packages/core/agent-loop/tests/fixtures/serial-created.mjs +++ b/packages/core/agent-loop/tests/fixtures/serial-created.mjs @@ -39,8 +39,8 @@ export function apply(ctx, config = {}) { if (!rejected || !signal.aborted) throw new Error('expected queue-clear rejection and activity cancellation') agent.inbox.remove(pending.id) for (const message of messages) { - const ordinary = message.source.kind === 'user' - agent.send(message, ordinary ? 'next-turn' : 'next-step', ordinary) + const waking = message.source.kind === 'user' || message.source.kind === 'agent-message' + agent.send(message, waking ? 'next-turn' : 'next-step', waking) } return next() }) diff --git a/packages/core/tool-executor-ptc/README.i18n.yaml b/packages/core/tool-executor-ptc/README.i18n.yaml index 009b299646..0acdbc39dc 100644 --- a/packages/core/tool-executor-ptc/README.i18n.yaml +++ b/packages/core/tool-executor-ptc/README.i18n.yaml @@ -21,8 +21,8 @@ en: 78708b3779d999a9 zh: ad6173f9f01630de /deepseek-ai-dsh-tool-executor-ptc/understand-the-implementation/ptc-mode: - en: 4da0f9293816b976 - zh: c5f77ea403d30ff5 + en: 630c852375ac0d30 + zh: 7b18b1aaae07d659 /deepseek-ai-dsh-tool-executor-ptc/further-exploration: en: ee69078c38c655a9 zh: fb0873407f23c8c5 diff --git a/packages/core/tool-executor-ptc/README.md b/packages/core/tool-executor-ptc/README.md index 6adeaa3400..0d01bbd4ad 100644 --- a/packages/core/tool-executor-ptc/README.md +++ b/packages/core/tool-executor-ptc/README.md @@ -72,7 +72,9 @@ New sub-calls use `:ptc:` ids. Consumers treat these ids as opaque an TypeScript bindings for `read_image` and CUA screenshot operations return an `Image` with a readable `path`, `width`, and `height`. Other tool values are substituted all or nothing: when `{ type: 'image', attachment }` entries reference every image of the finalized result and the program can read each one, those entries become `Image`s, as admitted MCP image blocks do, and the result's text and images reach the model only through `inspect`; otherwise the value stays raw and the complete result content reaches the model as additional context. Passing it to `inspect` places its durable attachment among the captured text in the `run_code` result. Images nested in arrays and objects are displayed with their containing value. On program failure, inspected output accompanies the original diagnostic; outer result replacements remain authoritative. If an output policy removes a screenshot or read_image image, the binding rejects with ToolCallError and includes the retained text notice. Additional contexts retain their producing tool’s attribution. -When the caller cancels and the runtime reports `abort`, `run_code` waits for cleanup and returns the native tool cancellation result: `AbortError` / `ABORTED`, with `Error: tool call aborted` as its content. Retained runtimes append their cancellation diagnostic, including whether variables were preserved or cleared. The Agent records the specific cancellation cause in `turn/end`, including a hook's reason. Other runtime failures retain `CODE_RUN_FAILED` and their diagnostics, even if the caller also cancels. A runtime rejection keeps a `PtcRuntimeError` code and otherwise becomes `CODE_RUN_FAILED` with the rejection as `cause`. A blank `description`, an invalid `timeoutMs`, or `timeoutMs` or `sandbox_permissions` on a runtime that does not support it fails as `ToolArgsError` with `INVALID_ARGS`; a call after executor disposal fails with `CODE_RUN_UNAVAILABLE`; and a missing runtime, `workingDirectory`, or `sandboxPolicy` fails as `ToolContextUnavailableError`. Cancellation can discard retained runtime state and does not undo completed tool effects. +`run_code` and tools created by `createRunCodeTool` report `outputTruncated: true` when captured output or diagnostic text was truncated. With the Node runtime, display-output overflow discards subsequent output while execution continues under the original timeout and cancellation rules. A normally completed program remains a successful tool result, with a truncation notice directing the model to read current state without repeating completed actions. A later failure keeps its actual error kind and truncation notice. Retained images and settled subcall records remain available. + +When the caller cancels and the runtime reports `abort`, `run_code` waits for cleanup and returns the native tool cancellation result: `AbortError` / `ABORTED`, with `Error: tool call aborted` as its content. Retained runtimes append their cancellation diagnostic, including whether variables were preserved or cleared. The Agent records the specific cancellation cause in `turn/end`, including a hook's reason. Runtime failures retain `CODE_RUN_FAILED` and their diagnostics, even if the caller also cancels. A runtime rejection keeps a `PtcRuntimeError` code and otherwise becomes `CODE_RUN_FAILED` with the rejection as `cause`. A blank `description`, an invalid `timeoutMs`, or `timeoutMs` or `sandbox_permissions` on a runtime that does not support it fails as `ToolArgsError` with `INVALID_ARGS`; a call after executor disposal fails with `CODE_RUN_UNAVAILABLE`; and a missing runtime, `workingDirectory`, or `sandboxPolicy` fails as `ToolContextUnavailableError`. Cancellation can discard retained runtime state and does not undo completed tool effects. `run_code` accepts `timeoutMs` when the mounted runtime supports an override; its schema reports the configured default and maximum, and the runtime's usage instructions. The Node default is 120,000 ms with a 600,000 ms cap, including nested tool and approval waits. A wider `sandbox_permissions` mode requires a non-empty `justification` and approval before the program starts. The schema asks the model to write that reason in the current user's language. The grant applies to that complete execution; standing Session policy and nested tools retain their own authority. Programs are never replayed automatically: inspect earlier effects before explicitly retrying a denied program. Retained PTC environments follow the standing file policy. PTC observes committed Session mode changes and immediately cancels affected calls in all Node modes. Later PTC calls wait for their nested-tool cleanup before resolving the latest policy. The runtime owns process invalidation and cleanup; permission setters remain synchronous. One-time escalations omit the state owner and complete in a temporary environment; standing variables remain available to ordinary calls. diff --git a/packages/core/tool-executor-ptc/README.zh.md b/packages/core/tool-executor-ptc/README.zh.md index 5662d9f5b5..876dd44b19 100644 --- a/packages/core/tool-executor-ptc/README.zh.md +++ b/packages/core/tool-executor-ptc/README.zh.md @@ -72,7 +72,9 @@ PTC 执行器公开保留的 `run_code` 传输,以及确定性的 TypeScript S TypeScript 中的 `read_image` 与 CUA 截图操作返回 `Image`,其中包含可读取的 `path`、`width` 和 `height`。其他工具的返回值按全有或全无的方式替换:当 `{ type: 'image', attachment }` 条目引用了最终结果中的每张图片且程序能读取每张图片时,这些条目会变为 `Image`,与已接受的 MCP 图片块相同,结果的文本与图片仅通过 `inspect` 进入模型;否则返回值保持原样,完整的结果内容作为额外上下文进入模型。将其传给 `inspect` 后,持久附件会按顺序与文本一起进入 `run_code` 结果。数组和对象内嵌的图片会随所在值一起展示。程序失败时,已 inspect 的输出随原始诊断一起呈现;外层替换的结果保持生效。输出策略移除截图或 read_image 图片时,绑定以 ToolCallError 拒绝,并包含保留的文本提示。额外上下文保留生成工具的归属。 -调用方取消且运行时报告 `abort` 时,`run_code` 等待清理完成,并返回原生工具的取消结果:`AbortError` / `ABORTED`,内容为 `Error: tool call aborted`。保留状态的运行时会附加取消诊断,包括变量被保留还是清空。Agent 在 `turn/end` 中记录具体取消原因,包括 hook 的理由。其他运行时失败保留 `CODE_RUN_FAILED` 及其诊断,即使调用方同时取消。运行时拒绝保留 `PtcRuntimeError` 的 code,否则变为 `CODE_RUN_FAILED` 并以该拒绝为 `cause`。`description` 为空白、`timeoutMs` 无效,或运行时不支持却传入 `timeoutMs` 或 `sandbox_permissions` 时,以带 `INVALID_ARGS` 的 `ToolArgsError` 失败;执行器释放后的调用以 `CODE_RUN_UNAVAILABLE` 失败;缺少运行时、`workingDirectory` 或 `sandboxPolicy` 时以 `ToolContextUnavailableError` 失败。取消可能丢弃保留的运行时状态,也不会撤销已完成的工具操作。 +`run_code` 和通过 `createRunCodeTool` 创建的工具在捕获输出或诊断文本被截断时报告 `outputTruncated: true`。使用 Node 运行时时,展示输出超限会丢弃后续输出,执行仍受原有超时和取消规则约束。正常结束的程序仍是成功工具结果,并提示输出已截断,应读取当前状态而不重复已完成的动作。后续失败保留实际错误类型和截断提示。已保留的图片与已结算的子调用记录仍然可用。 + +调用方取消且运行时报告 `abort` 时,`run_code` 等待清理完成,并返回原生工具的取消结果:`AbortError` / `ABORTED`,内容为 `Error: tool call aborted`。保留状态的运行时会附加取消诊断,包括变量被保留还是清空。Agent 在 `turn/end` 中记录具体取消原因,包括 hook 的理由。运行时失败保留 `CODE_RUN_FAILED` 及其诊断,即使调用方同时取消。运行时拒绝保留 `PtcRuntimeError` 的 code,否则变为 `CODE_RUN_FAILED` 并以该拒绝为 `cause`。`description` 为空白、`timeoutMs` 无效,或运行时不支持却传入 `timeoutMs` 或 `sandbox_permissions` 时,以带 `INVALID_ARGS` 的 `ToolArgsError` 失败;执行器释放后的调用以 `CODE_RUN_UNAVAILABLE` 失败;缺少运行时、`workingDirectory` 或 `sandboxPolicy` 时以 `ToolContextUnavailableError` 失败。取消可能丢弃保留的运行时状态,也不会撤销已完成的工具操作。 当已挂载运行时支持覆盖时,`run_code` 接受 `timeoutMs`;其 schema 报告配置的默认值和上限以及运行时使用说明。Node 默认值为 120,000 ms,上限为 600,000 ms,包含嵌套工具和审批等待。更宽的 `sandbox_permissions` 模式要求非空 `justification`,并在程序启动前获得审批。schema 提示模型使用当前用户的语言撰写理由。授权仅用于该次完整执行;常驻 Session 策略与嵌套工具保留各自权限。程序不会自动重放:显式重试被拒程序前,应检查先前已发生的效果。 保留状态的 PTC 环境遵循会话文件策略。PTC 观察已提交的 Session 模式变化,并立即取消所有 Node 模式下受影响的调用。后续 PTC 调用等待这些调用的嵌套工具清理后,再解析最新策略。运行时负责进程失效和清理,权限设置保持同步。单次提权省略状态所有者,在临时环境中执行;普通调用仍可访问原环境的变量。 diff --git a/packages/core/tool-executor-ptc/src/ptc.ts b/packages/core/tool-executor-ptc/src/ptc.ts index ac1a7000e6..700002eced 100644 --- a/packages/core/tool-executor-ptc/src/ptc.ts +++ b/packages/core/tool-executor-ptc/src/ptc.ts @@ -161,7 +161,7 @@ function isCancellation(error: unknown, signal: AbortSignal): boolean { } /** Canonical value returned by the outer PTC mode transport. */ -type RunCodeOutput = { logs: string[]; sandbox?: PtcRunSandbox } +type RunCodeOutput = { logs: string[]; outputTruncated?: boolean; sandbox?: PtcRunSandbox } /** Render captured text, selected images, and the applied file policy in emission order. */ function renderRunOutput( @@ -183,6 +183,7 @@ function renderRunOutput( } appendText(remaining.join('')) const details: string[] = [] + if (value.outputTruncated) details.push('Program completed. Output was truncated; read current state for missing information without repeating completed actions.') if (value.sandbox?.enforcement === 'partial') details.push('File sandbox enforcement is partial on this host.') if (value.sandbox?.denied) details.push(`The ${value.sandbox.mode} file sandbox denied an operation.${guidance}`) appendText(details.filter(text => text.length > 0).join('\n')) @@ -278,6 +279,7 @@ export function createRunCodeTransport( additionalProperties: false, properties: { logs: { type: 'array', required: true, items: { type: 'string' } }, + outputTruncated: { type: 'boolean' }, sandbox: { type: 'object', additionalProperties: false, @@ -703,7 +705,8 @@ export function createRunCodeTransport( ? runController.signal.reason : undefined let failure: HarnessError if (result.error.kind === 'abort' && exec.signal.aborted && limitError === undefined) { - const message = runtime.retainsState ? `tool call aborted: ${result.error.message}` : 'tool call aborted' + const message = (runtime.retainsState ? `tool call aborted: ${result.error.message}` : 'tool call aborted') + + (result.outputTruncated ? '\nOutput was truncated.' : '') failure = new HarnessError(message, TOOL_ABORTED) failure.name = 'AbortError' } else { @@ -713,7 +716,8 @@ export function createRunCodeTransport( : `${logsText.endsWith('\n') ? '' : '\n'}File sandbox: ${result.sandbox.mode}${result.sandbox.enforcement === undefined ? '' : `; enforcement: ${result.sandbox.enforcement}`}${result.sandbox.denied ? '; operation denied' : ''}.` const failureText = limitError === undefined || limitError.message === result.error.message ? result.error.message : `${limitError.message}\n${result.error.message}` - failure = new CodeRunFailedError(`code run failed (${result.error.kind}): ${failureText}${logsText}${sandboxText}${result.sandbox?.denied ? escalationGuidance(runtime.sandboxMode) : ''}`) + const truncation = result.outputTruncated ? '\nOutput was truncated.' : '' + failure = new CodeRunFailedError(`code run failed (${result.error.kind}): ${failureText}${logsText}${sandboxText}${result.sandbox?.denied ? escalationGuidance(runtime.sandboxMode) : ''}${truncation}`) } if (hasImages) inspections.set(exec, { failure: { @@ -726,6 +730,7 @@ export function createRunCodeTransport( } const value: RunCodeOutput = { logs, + ...result.outputTruncated ? { outputTruncated: true } : {}, ...result.sandbox === undefined ? {} : { sandbox: result.sandbox }, } if (hasImages) inspections.set(exec, { value, output: result.output }) diff --git a/packages/core/tool-executor-ptc/tests/exports.built.e2e.ts b/packages/core/tool-executor-ptc/tests/exports.built.e2e.ts index 3a98e242c1..1465a392ab 100644 --- a/packages/core/tool-executor-ptc/tests/exports.built.e2e.ts +++ b/packages/core/tool-executor-ptc/tests/exports.built.e2e.ts @@ -43,6 +43,9 @@ try { } await assert.rejects(definition.execute({ code: 'probe', description: 'Check shared error identity' }, execution), error => error instanceof ptc.CodeRunFailedError && error.code === 'CODE_RUN_FAILED') + runtime.run = async () => ({ output: [], outputTruncated: true }) + assert.deepEqual(await definition.execute({ code: 'probe', description: 'Check successful truncated output' }, execution), + { logs: [], outputTruncated: true }) runtime.run = async (spec) => { assert.deepEqual(Object.keys(spec.bindings[0].functions), ['private_probe']) assert.equal(spec.discardCompletion, true) diff --git a/packages/core/tool-executor-ptc/tests/ptc.spec.ts b/packages/core/tool-executor-ptc/tests/ptc.spec.ts index e0383fcb6d..5eacd4f27a 100644 --- a/packages/core/tool-executor-ptc/tests/ptc.spec.ts +++ b/packages/core/tool-executor-ptc/tests/ptc.spec.ts @@ -1991,6 +1991,40 @@ describe('the run_code dispatch bridge', () => { expect(text).toBe(`Error: code run failed (timeout): execution timed out ${phase} (300ms); retained variables were cleared${logs.length > 0 ? '\nCaptured output:\ngot this far' : ''}`) }) + it.each([ + ['output-limit', 'CODE_RUN_FAILED'], + ['invalid-output', 'CODE_RUN_FAILED'], + ['exception', 'CODE_RUN_FAILED'], + ['timeout', 'CODE_RUN_FAILED'], + ['worker-exit', 'CODE_RUN_FAILED'], + ['protocol', 'CODE_RUN_FAILED'], + ['sandbox-unavailable', 'CODE_RUN_FAILED'], + ['abort', 'CODE_RUN_FAILED'], + ] as const)('preserves completed subcalls when the runtime reports %s', async (kind, code) => { + const { ctx, runtime } = await setup({ mode: 'ptc' }) + onTestFinished(async () => { await ctx.fiber.dispose() }) + const { agent, events } = fakeAgent() + const calls = registerEcho(ctx) + runtime.behavior = async (request) => { + await request.bindings[0]!.functions.echo!({ value: 'action dispatched' }) + return { output: [{ type: 'text', text: 'before failure' }], outputTruncated: true, error: { kind, message: 'fixture failure' } } + } + + const result = await runCode(ctx, 'program', { agent }) + + expect(result.isError).toBe(true) + expect(result.error).toMatchObject({ info: { name: 'CodeRunFailedError', code } }) + const first = result.content[0] + if (first?.type !== 'text') throw new Error('Missing failure diagnostic') + expect(first.text).toContain('Captured output:\nbefore failure') + expect(events.filter(event => event.type === 'tool/ptc-dispatch')).toHaveLength(1) + expect(events.find(event => event.type === 'tool/ptc-dispatch')?.data).toMatchObject({ + isError: false, content: [{ type: 'text', text: 'echo:action dispatched' }], + }) + expect(calls).toEqual([{ value: 'action dispatched' }]) + expect(first.text).toBe(`Error: code run failed (${kind}): fixture failure\nCaptured output:\nbefore failure\nOutput was truncated.`) + }) + it('CodeRunFailedError is a HarnessError with the CODE_RUN_FAILED code', () => { const error = new CodeRunFailedError('boom') expect(error.code).toBe('CODE_RUN_FAILED') @@ -2433,18 +2467,18 @@ describe('the run_code dispatch bridge', () => { expect(calls).toEqual([]) }) - it.each(['preserved', 'cleared'])('reports retained variables were %s after caller cancellation', async (state) => { + it.each(['preserved', 'cleared'])('reports retained variables were %s after caller cancellation with truncated output', async (state) => { const { ctx, runtime } = await setup({ mode: 'ptc' }) vi.spyOn(runtime, 'retainsState', 'get').mockReturnValue(true) const controller = new AbortController() const message = `execution canceled; retained variables were ${state}` runtime.behavior = async () => { controller.abort({ kind: 'user' }) - return { output: [], error: { kind: 'abort', message } } + return { output: [], outputTruncated: true, error: { kind: 'abort', message } } } const result = await runCode(ctx, 'program', { signal: controller.signal }) expect(result.error).toEqual({ - message: `tool call aborted: ${message}`, + message: `tool call aborted: ${message}\nOutput was truncated.`, info: { name: 'AbortError', code: TOOL_ABORTED }, }) }) diff --git a/packages/core/tool-executor-ptc/tests/run-code.spec.ts b/packages/core/tool-executor-ptc/tests/run-code.spec.ts index f440b91571..82310dc12c 100644 --- a/packages/core/tool-executor-ptc/tests/run-code.spec.ts +++ b/packages/core/tool-executor-ptc/tests/run-code.spec.ts @@ -196,6 +196,30 @@ describe('registered program tool factory', () => { }) }) + it.each([false, true])('retains inspected images from private program tools, output overflow=%s', async (overflow) => { + type Attachment = Extract['attachment'] + const image: ContentBlock = { type: 'image', attachment: { + attachmentId: brandString('sha256:inspected'), + mediaType: 'image/png', width: 1, height: 1, bytes: 1, + } } + const { runtime, execute } = await setup(privateTool(vi.fn(async () => 'private result'))) + runtime.behavior = async () => ({ + output: [{ type: 'text', text: 'before image' }, image], + ...overflow ? { outputTruncated: true } : {}, + }) + + const result = (await execute()).results[0]!.result + + expect(result.isError).toBe(false) + expect(result.content.slice(0, 2)).toEqual([{ type: 'text', text: 'before image' }, image]) + if (overflow) { + expect(result.value).toMatchObject({ outputTruncated: true }) + expect(result.content[2]).toMatchObject({ + type: 'text', text: expect.stringContaining('Program completed. Output was truncated;') as string, + }) + } + }) + it('cancels on owner disposal and awaits nested cleanup before releasing the factory', async () => { const entered = Promise.withResolvers() const aborted = Promise.withResolvers() diff --git a/packages/experimental/client-ui-forge/README.i18n.yaml b/packages/experimental/client-ui-forge/README.i18n.yaml index 0116a96b2a..7295d3362e 100644 --- a/packages/experimental/client-ui-forge/README.i18n.yaml +++ b/packages/experimental/client-ui-forge/README.i18n.yaml @@ -15,11 +15,11 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-client-ui-forge/use-this-package: - en: f63d4a049eea1ede - zh: e61269b6df6afcd4 + en: b077aea8c5f4cb0c + zh: 6ca6d6ead647d870 /deepseek-ai-dsh-experimental-client-ui-forge/understand-the-implementation: - en: 43e18d718e1bda7b - zh: c58f6b5bda5c0c45 + en: a88671f87adb5e84 + zh: a31d5f186c40683f /deepseek-ai-dsh-experimental-client-ui-forge/further-exploration: en: fa4d8c579ffc49ff zh: 5856ed7469e4585b diff --git a/packages/experimental/client-ui-forge/README.md b/packages/experimental/client-ui-forge/README.md index b1f17893c1..d7d5add8d6 100644 --- a/packages/experimental/client-ui-forge/README.md +++ b/packages/experimental/client-ui-forge/README.md @@ -37,7 +37,7 @@ Panel text follows the application language: Chinese, English, Japanese, Spanish - **Checkout row** — names the checked-out branch, or Not on a branch with the abbreviated commit on a detached HEAD, and the kind of checkout, which is the worktree the Session created with its base, another worktree, or the project directory; its tooltip, shown after 500ms of hover, adds the path with the Host home shortened to `~`, and a branch name the row clips crawls into view while the pointer rests on the row. The row and its More button open the directory menu of the checkout root. For a removed worktree it shows a warning glyph and offers Restore. When Git cannot be read, the row says so, and its info button shows the failure after 500ms of hover, at once on keyboard focus, or on a press; outside a Git checkout there is no row. - **Connection row** — when the Session's panel stream ends, also before it delivered a first state, a status row at the end of the Environment section says the status stopped updating and that the Git and change request details may be out of date; Retry opens the stream again and the row goes away. - **Session list** — after a Session row's time, a branch glyph shows while the Session works in the worktree the panel created for it, and a glyph shows the state of its most urgent change request: one needing attention first, then open, draft, not yet polled, merged, and closed. The glyph of an open change request keeps the row's subdued color, with its head branch end filled in the color of running, passed, or failed checks; merged and closed ones keep their state colors. The row's hover card names the worktree branch and what it started from, then up to three change requests with their number, title, state, and checks, and how many more there are. A restart shows the states known before it until the next poll. -- **Change requests section** — shows while the Session has bound change requests or the repository's host needs sign-in. Its title carries their count. A status row above the cards asks to sign in to the host: with the sign-in command the provider names, such as `gh auth login --hostname github.com`, which crawls into view on hover, and Copy; when the provider names none, and when the sign-in check fails, with the host's reason behind an info button, as the checkout row shows its failure. The section shows with this row alone while the Session binds no change request. Each change request card shows a glyph for its state, its title on one line, which crawls into view on hover and opens it in the browser, and its number; the glyph tells open, draft, merged, and closed apart, and marks an open one that is not a draft with failed checks, requested changes, or conflicts as needing attention, as the toggle's yellow dot does. The card's More menu offers Open in browser, Copy change request link, View changes for a change request a provider serves, Ready for review for an open draft, and Remove from this Session, whose toast offers Undo. Cancelled checks have a separate count; a collapsed card names cancellations when no listed check failed. A collapsed card adds the checks of an open change request and the most urgent of requested changes, conflicts, or draft, or when a merged or closed one ended, on one line: while the line with failed checks does not fit, they take the shorter wording without their count, and a line that still does not fit ends in an ellipsis and crawls into view with the title. An expanded card shows the head and base branches, then one row per fact, each a glyph and its value. For an open change request, the rows are the checks, whose menu groups the failed, running, and cancelled checks with their durations and links, lists the passed and skipped ones on request, and offers Rerun failed when the user may rerun checks and a failed check names a rerun none of whose checks is still running; the review decision with the first three reviewers' avatars and how many more, whose menu lists each reviewer with their kind and latest outcome, notes an outcome given before the latest commit, and, when the user may request reviews, re-requests a review from a reviewer or requests one from someone else through a search that lists the host's suggestions first; the merge state, which names a head behind its base and, when the user may update it, offers Update branch, whose menu chooses merge or rebase, pins the displayed head when opened, and disables Confirm update once a poll names another head; the changed lines, formatted in the selected UI language, with the unresolved threads, whose count ends in `+` when the provider counted only some threads, in a row that opens the changes view; and the linked issues the host closes when the change request merges, each linking to its page. The thread count and an issue's title show in a tooltip after 500ms of hover. A merged or closed one shows when it ended and the changed lines. Rerun failed, a review request, Update branch, Ready for review, and Merge report their outcome in a toast, which asks to check the change request in the browser when the host did not confirm the outcome, and new commits since the displayed head stop a rerun or an update. A change request the host would merge now offers Merge below its rows, whose menu lists the methods the repository allows with the user's usual one chosen and pins the displayed head when opened. Confirm merge uses that head; a polled head change disables confirmation until the menu is reopened after review. A toast reports each outcome, and new commits since that head stop the merge. When the Session binds exactly one change request, its card starts expanded whatever its state; with several, every card starts collapsed. A card the user expands or collapses keeps that choice across updates and while the panel is hidden, for as long as the Session stays open; a card the user never toggled follows the default. +- **Change requests section** — shows while the Session has bound change requests or the repository's host needs sign-in. Its title carries their count. A status row above the cards asks to sign in to the host: with the sign-in command the provider names, such as `gh auth login --hostname github.com`, which crawls into view on hover, and Copy; when the provider names none, and when the sign-in check fails, with the host's reason behind an info button, as the checkout row shows its failure. The section shows with this row alone while the Session binds no change request. Each change request is a compact card, a filled block on the panel's row columns: one line with a glyph for its state, its title, its number, and a glyph for the outcome of its checks. A press on the line opens the change request's changes in the right sidebar; with Cmd or Ctrl held, with the middle button, and for a change request no provider serves or has read yet, it opens the host's page. The state glyph tells open, draft, merged, and closed apart, and marks an open one that is not a draft with failed checks, requested changes, or conflicts as needing attention, as the toggle's yellow dot does. The card's More menu, which shows on hover or focus as on the panel's other rows, offers View changes for a change request a provider serves, Open in browser, Copy change request link, Ready for review for an open draft, and Remove from this Session, whose toast offers Undo. While collapsed, the line reads its status in words to assistive technology, and the card's hover card shows the full title, the number with draft state and the head and base branches, and that status: the checks of an open change request and the most urgent of requested changes, conflicts, or draft, or when a merged or closed one ended; a failed read or an unserved URL stands there instead. Cancelled checks have a separate count, which the status names when no listed check failed. The checks glyphs share one ring: a check for passed, a cross for failed, a half fill while they run, and a dash otherwise. An expanded card shows one row per fact below its line, each a glyph and its value. For an open change request, the rows are the checks, whose menu groups the failed, running, and cancelled checks with their durations and links, lists the passed and skipped ones on request, and offers Rerun failed when the user may rerun checks and a failed check names a rerun none of whose checks is still running; the review decision with the first three reviewers' avatars and how many more, whose menu lists each reviewer with their kind and latest outcome, notes an outcome given before the latest commit, and, when the user may request reviews, re-requests a review from a reviewer or requests one from someone else through a search that lists the host's suggestions first; the merge state, which names a head behind its base and, when the user may update it, offers Update branch, whose menu chooses merge or rebase, pins the displayed head when opened, and disables Confirm update once a poll names another head; the changed lines, formatted in the selected UI language, with the unresolved threads, whose count ends in `+` when the provider counted only some threads, in a row that opens the changes view; and the linked issues the host closes when the change request merges, each linking to its page. The thread count and an issue's title show in a tooltip after 500ms of hover. A merged or closed one shows when it ended and the changed lines. Rerun failed, a review request, Update branch, Ready for review, and Merge report their outcome in a toast, which asks to check the change request in the browser when the host did not confirm the outcome, and new commits since the displayed head stop a rerun or an update. A change request the host would merge now offers Merge below its rows, whose menu lists the methods the repository allows with the user's usual one chosen and pins the displayed head when opened. Confirm merge uses that head; a polled head change disables confirmation until the menu is reopened after review. A toast reports each outcome, and new commits since that head stop the merge. The list shows three cards; with more, the panel's fold control after them shows the rest and folds them again, and the Session keeps that choice while it stays open. When the Session binds exactly one change request, its card starts expanded whatever its state; with several, every card starts collapsed. A card the user expands or collapses keeps that choice across updates and while the panel is hidden, for as long as the Session stays open; a card the user never toggled follows the default. - **Local changes row** — whenever the `branch` scope changes files, independently of bound change requests, the row names the number of changed files with the added and deleted lines and opens the changes view. Its More menu offers View changes and, when the code host repository is recognized and no open change request (including drafts) has the checked-out branch as its head, Create change request, which sends the Session a user message in the UI language that asks the Agent to create a change request for these changes; a toast reports whether it was sent. - **Changes view** — The Changes row and View changes item of a change request card and the local changes row open a right-sidebar tab that lists the changed files, closing the Session panel while it floats over the conversation. The local tab is named Local changes and shows Branch by default: the working tree and untracked files against the fork point. Its header names the checked-out branch, or the abbreviated commit on a detached HEAD, and the base branch, which opens a searchable menu: first Default, the base commit of the worktree the Session created, else the merge base of HEAD with the default branch of the code host remote, then remote-tracking and then local branches, each most recently committed first, without the checked-out branch and, outside a created worktree, without the remote-tracking branch Default already names. Typing filters the listed rows at once and lists the branches whose names contain the text, ignoring case, after a short pause; Enter chooses the first row. Choosing another branch compares with the merge base of HEAD and that branch. The tab keeps the choice while other scopes show; closing the tab or reloading the application returns it to Default. When the chosen branch is gone, its name is struck through, and when it shares no history with HEAD, the view says so as well; both offer Use the default base branch instead of Retry. A narrow view hides the note that uncommitted changes count, then the checked-out branch. Uncommitted compares them with HEAD, Unstaged with the index, and Staged compares the index with HEAD. A change request view shows the host's diff at its head and says how many commits the checked-out branch has beyond that head when it is the change request's head branch. The toolbar jumps to a file, totals the changed lines, refreshes, and switches between two columns and one and between wrapped and cut long lines. Its icon buttons and the header's Open in browser name their action after 500ms of hover or at once on keyboard focus. The toolbar and the header each keep one line: as the toolbar narrows, the line totals, expanding all files, two columns, and wrapping move into a More menu first, then the test file switch, with the viewed progress label shortened to a bare count beside its ring, and then refresh, while header buttons keep their labels on one line and the menus and title shorten. Visited changes tabs stay mounted across tab and Session switches, hiding the sidebar, and docking changes, preserving file folds, revealed large files, expanded context, layout, and scroll position while the diff is unchanged. Hidden changes views release their panel subscription and defer diff reads; returning reads again only when the latest head or local summary differs. A refresh that replaces the diff discards expanded context, and changed content may move the reading position. Temporary menus close when the view is hidden. Closing the tab or reloading the application discards this progress. Each file is a separate card, with a tinted header that stays at the top while its lines scroll. Files are named before their directories, which use smaller subdued type and shorten first; hovering one for 500ms shows its complete path, and both paths for a renamed file. Each file shows badges for a new, deleted, or renamed file, the last naming the old file name, or the old path when only the directory changed, and, in the Branch scope, an untracked one, and a menu that copies its path and opens the whole file in the sidebar for local changes or its page at the head in the browser for a change request. When the header is narrow, the path, the badges, and Changed since viewed shorten, so the line counts, Viewed, and the menu stay whole. Unchanged lines between hunks collapse into rows that expand from the file's new side: the working tree, the index for Staged, or the head commit through the code host; a file that changed after the diff was read stays collapsed until the view reads again. A row of at most 20 lines expands with one click. A longer row expands 20 lines at a time, down from the hunk above it or up from the hunk below it, the row before the first hunk only up and the row after the last hunk only down, and shows how many lines it still hides; the first click on the unknown lines after the last hunk reads the file and shows their first 20. A binary file and an untracked file over `maxDiffBytes` show a note instead of their lines, a file whose hunks draw more than 1,000 lines starts as one collapsed strip that names its changed lines and draws them when opened, and a file below files that change more than 5,000 lines starts collapsed. While the view reads changes it has not shown yet, it says Reading changes above file cards drawn as pulsing placeholders, one changed file in two columns when sides are split, and the files menu names no count; reduced motion keeps the placeholders still. The view reads again on Refresh and the page refresh shortcut, on each navigation, when the change request's head moves, and when the Branch scope's summary changes; a change request's view first waits for the status that names its head, unless no provider serves it or that poll failed. When the head moved past the latest status, the view keeps loading and reads again at the head of a status later than the one the read started with, at once when that status arrived during the read. While a read replaces changes already shown, the Refresh icon turns. A change request whose diff the code host or its provider refuses over a size limit, such as a GitHub diff whose output exceeds the provider's `maxOutputBytes`, says its changes are too large to show here and offers View in browser; another failed read offers Retry and, for a change request, View in browser. A change request's diff is downloaded once per head commit and base branch while it stays cached, so reopening, refreshing, and navigating at the same head read nothing from the host. Expanded unchanged lines and pending file reads survive a refresh of review marks for the same commit range, head, and patches. @@ -65,7 +65,7 @@ All files opens a searchable directory tree with the selected file scrolled to i Inspection runs `rev-parse --show-toplevel`, `rev-parse --path-format=absolute --git-common-dir`, `rev-parse --path-format=absolute --git-dir`, `symbolic-ref --quiet HEAD`, which names the checked-out branch when it is under `refs/heads/`, `rev-parse --short HEAD`, `rev-parse --abbrev-ref @{upstream}`, and `remote -v`; `worktreeBases` runs `for-each-ref --sort=-committerdate` over `refs/heads/` and `refs/remotes/` within `maxDiffBytes`, takes each remote's default branch from its `refs/remotes//HEAD`, leaves out other symbolic refs and the branches of unconfigured remotes, and keeps at most `maxBranches` local branches and `maxBranches` branches per remote whose names contain the query, with remotes in the code host order below; `requestWorktree` with a name checks it against Git's branch-name rules and runs `show-ref` in the checkout; `diffBases` finds the default fork point as `localDiff` does below, runs `for-each-ref --sort=-committerdate` over `refs/heads/` and `refs/remotes/` within `maxDiffBytes`, leaves out symbolic refs such as `origin/HEAD`, and keeps at most `maxBranches` branches of each kind whose names contain the query. Inspection then sizes the `branch` scope for the local changes row: it finds the fork point, runs `diff --numstat -z -M` against it with the same helper and submodule restrictions as `localDiff` below, and lists untracked files. Every command uses the Session's resolved sandbox mode: `read-only` and `workspace-write` require confinement, while `danger-full-access` runs without a sandbox backend. Commands disable optional index writes, hooks, the filesystem monitor, prompts, and lazy object fetches, remove inherited Git selectors and secret-bearing variables, and use their own `gitTimeoutMs` deadline and `maxOutputBytes` limit per stream. The top-level, Git, and common Git directories Git prints are resolved through `ctx.fs` into the canonical process paths that the working-directory service records; a checkout whose Git directory differs from the common one is a linked worktree. The worktree option is usable under the `danger-full-access` sandbox mode, never under `read-only`, and under `workspace-write` only when both directories lie inside the canonical workspace root of the Session's sandbox policy. -A worktree request is a `plugin:client-ui-forge/worktree` record, folded by the `forgeWorktree` projection: requests and withdrawals apply until the first `turn/start` or creation, and the first creation of an open request, read from the worktree service's `plugin:worktree/created` record or from the `created` record earlier panels wrote, applies until the first `step/start`. The projection also records the Session's directory from its header and each `working-directory/change`; its client view, which the Session summary carries, is the created worktree while that directory is the worktree or lies below it, else null. A request names its base by the full name of a local or remote-tracking branch, as earlier panels' short local names still resolve, and may name its branch. `requestWorktree` refuses with `forgePanel/session-started` after a turn started or the worktree was created, with `forgePanel/worktrees-unavailable` without a `worktrees` service, with `forgePanel/invalid-branch` for an empty base, with `forgePanel/invalid-name` for a branch name Git refuses, and with `forgePanel/branch-exists` for a branch name the checkout already uses; `cancelWorktree` refuses only with the first and needs no `worktrees` service; both forget a failed attempt. When a message enters the inbox of a Session whose request is open, an `agent/inbox/inserted` listener starts maintenance of the Session's Agent before the delivery wakes it, so the Agent latches the wake and starts the message's turn once that hold ends. The hold makes one attempt on the requested branch name, or on a new generated one, asking the worktree service to fetch a remote-tracking base branch first; it publishes the running stage in the panel state with `held` set and `waiting` as `creation`, and records `created` with the source repository root. After a failed attempt, whose branch, base, fetch, failed step, reason, and whether the branch or directory existed stay in the panel state as `failure`, or after `stopCreation`, the hold waits: `retryWorktree` makes another attempt, without the fetch when its `fetch` argument is false, refused with `forgePanel/not-waiting` while none waits or one runs; `requestWorktree` with another name changes the next attempt; and withdrawing the request lets the message go on in the current checkout. Each message that enters while the Agent is idle and the Session works in its created worktree starts a hold that checks whether the worktree is missing; while it is, the hold waits with `waiting` as `restoration`, and `restoreWorktree` or `continueInProject` runs inside it and then lets the message go on; a check that cannot answer lets the message go at once. The Agent's cancellation and the Remote's stop end a hold, and a message that enters while the Agent runs a turn or other maintenance gets none. The worktree service queues the working-directory notice, which the first step claims. An `agent/pre-step` listener creates the worktree at step 1 of a Session whose request is still open, which covers a message no hold took; it moves the notice into the proposed messages, and a failure ends the turn with the request kept. `restoreWorktree` and `continueInProject` run as maintenance of their own while no message waits; `restoreWorktree` publishes its running step as `restoration`, and clears `missing` in the same state that ends it. `track` rejects a URL no provider recognizes with `forgePanel/unrecognized-url`. `markReady` and `merge` act only on a visible binding of the Session that a provider serves, else they refuse with `forgePanel/not-bound`; `merge` passes the head commit the card showed, and a moved head refuses with `forgePanel/stale-head`, while any other refusal is `forgePanel/action-failed` with the host's reason. +A worktree request is a `plugin:client-ui-forge/worktree` record, folded by the `forgeWorktree` projection: requests and withdrawals apply until the first `turn/start` or creation, and the first creation of an open request, read from the worktree service's `plugin:worktree/created` record or from the `created` record earlier panels wrote, applies until the first `step/start`. The projection also records the Session's directory from its header and each `working-directory/change`; its client view, which the Session summary carries, is the created worktree while that directory is the worktree or lies below it, else null. A request names its base by the full name of a local or remote-tracking branch, as earlier panels' short local names still resolve, and may name its branch. `requestWorktree` refuses with `forgePanel/session-started` after a turn started or the worktree was created, with `forgePanel/worktrees-unavailable` without a `worktrees` service, with `forgePanel/invalid-branch` for an empty base, with `forgePanel/invalid-name` for a branch name Git refuses, and with `forgePanel/branch-exists` for a branch name the checkout already uses; `cancelWorktree` refuses only with the first and needs no `worktrees` service; both forget a failed attempt. When a message enters the next-turn queue of a Session whose request is open, an `agent/inbox/inserted` listener starts maintenance of the Session's Agent before the delivery wakes it, so the Agent latches the wake and starts the message's turn once that hold ends. A message queued for the next step, such as a notice another plugin injects, opens no turn and starts no hold. The hold makes one attempt on the requested branch name, or on a new generated one, asking the worktree service to fetch a remote-tracking base branch first; it publishes the running stage in the panel state with `held` set and `waiting` as `creation`, and records `created` with the source repository root. After a failed attempt, whose branch, base, fetch, failed step, reason, and whether the branch or directory existed stay in the panel state as `failure`, or after `stopCreation`, the hold waits: `retryWorktree` makes another attempt, without the fetch when its `fetch` argument is false, refused with `forgePanel/not-waiting` while none waits or one runs; `requestWorktree` with another name changes the next attempt; and withdrawing the request lets the message go on in the current checkout. Each next-turn message that enters while the Agent is idle and the Session works in its created worktree starts a hold that checks whether the worktree is missing; while it is, the hold waits with `waiting` as `restoration`, and `restoreWorktree` or `continueInProject` runs inside it and then lets the message go on; a check that cannot answer lets the message go at once. The Agent's cancellation and the Remote's stop end a hold, and a message that enters while the Agent runs a turn or other maintenance gets none. The worktree service queues the working-directory notice, which the first step claims. An `agent/pre-step` listener creates the worktree at step 1 of a Session whose request is still open, which covers a message no hold took; it moves the notice into the proposed messages, and a failure ends the turn with the request kept. `restoreWorktree` and `continueInProject` run as maintenance of their own while no message waits; `restoreWorktree` publishes its running step as `restoration`, and clears `missing` in the same state that ends it. `track` rejects a URL no provider recognizes with `forgePanel/unrecognized-url`. `markReady` and `merge` act only on a visible binding of the Session that a provider serves, else they refuse with `forgePanel/not-bound`; `merge` passes the head commit the card showed, and a moved head refuses with `forgePanel/stale-head`, while any other refusal is `forgePanel/action-failed` with the host's reason. Restoration records `restoring` before mutation and `restored` only after success. Projection version 3 retains incomplete restoration across reloads. Directory existence alone cannot release a waiting message: the checkout root and shared Git directory must match the recorded worktree. Plugin unload cancels and joins all creation, restoration, and waiting tasks before releasing panel readers and the projection. diff --git a/packages/experimental/client-ui-forge/README.zh.md b/packages/experimental/client-ui-forge/README.zh.md index 0ac9c13997..7ebad378f1 100644 --- a/packages/experimental/client-ui-forge/README.zh.md +++ b/packages/experimental/client-ui-forge/README.zh.md @@ -37,7 +37,7 @@ kind: "package-reference" - **检出行**——显示当前检出的分支(分离 HEAD 时为“不在分支上”与缩写提交),并说明检出的类型(Session 创建的 worktree 及其基准、其他 worktree 或项目目录);悬停 500ms 后出现的提示给出路径,宿主主目录缩写为 `~`;分支名放不下时,指针停在这一行上会滚动显示全文。这一行及其“更多”按钮打开检出根目录的目录菜单。worktree 已被删除时显示警示图标并提供“恢复”。无法读取 Git 时,这一行说明这一点,行尾的信息按钮在悬停 500ms、键盘聚焦或按下时给出失败原因;不在 Git 检出中时不显示这一行。 - **连接行**——Session 的面板流结束时(包括还没收到第一份状态就结束),环境分栏末尾的状态行说明状态已停止更新,Git 与变更请求信息可能已过时;「重试」重新打开流,这一行随即消失。 - **会话列表**——Session 在面板为它创建的 worktree 中工作时,会话行的时间之后显示分支图标;另有一个图标显示它最需要关注的变更请求的状态,依次为需要处理、打开、草稿、尚未轮询、已合并、已关闭。打开中的变更请求图标保持会话行的浅色,head 分支端点填充为检查进行中、已通过或失败对应的颜色;已合并与已关闭的保留各自的状态颜色。会话行的悬浮卡片写出 worktree 分支及其起点,再列出最多三个变更请求的编号、标题、状态与检查,并说明还有多少个。重启后,下次轮询之前显示重启前已知的状态。 -- **变更请求分栏**——Session 有已绑定的变更请求,或仓库所在托管平台需要登录时显示。分栏标题旁显示数量。卡片上方的状态行请用户登录托管平台:显示提供方给出的登录命令(例如 `gh auth login --hostname github.com`,悬停时滚动显示全文)和「复制」;提供方没有给出命令以及登录检查失败时,平台给出的原因收在信息按钮里,与检出行显示失败的方式相同。Session 没有绑定变更请求时,分栏只显示这一行。每张变更请求卡片显示状态图标、单行标题(悬停时滚动显示全文,点击在浏览器中打开)与编号;图标区分打开、草稿、已合并与已关闭,打开中的变更请求(草稿除外)检查失败、被要求修改或有冲突时显示为“需要处理”,与面板开关的黄点一致。卡片的“更多”菜单提供“在浏览器中打开”“复制变更请求链接”、由提供方服务的变更请求的“查看变更”、打开中草稿的“标记为可评审”,以及“从本会话移除”,移除后的 toast 提供“撤销”。已取消的检查单独计数;列出的检查没有失败项时,折叠卡片显示取消数量。折叠的卡片还显示打开的变更请求的检查,以及被要求修改、冲突、草稿中最需要注意的一项;已合并或已关闭的则显示结束时间。这些内容只占一行:含失败检查的一行放不下时,失败检查改用不带数量的短文案;仍放不下的一行末尾显示省略号,并随标题一起滚动显示。展开的卡片显示源分支与目标分支,下面每项一行,由图标与取值组成。打开的变更请求依次是:检查,其菜单按失败、运行中、已取消分组列出检查及其耗时与链接,按需列出通过与跳过的检查,用户可以重跑检查、且有失败检查指向一个其中没有检查仍在进行的重跑时提供“重跑失败项”;评审结论,带前三位评审者的头像与其余人数,其菜单列出每位评审者的类型与最近结论,注明早于最新提交的结论,用户可以请求评审时还能重新请求某位评审者,或通过先列出托管平台建议的搜索向其他人请求评审;合并状态,会注明 head 落后于基线,用户可以更新时提供“更新分支”,其菜单在 merge 与 rebase 之间选择,打开时固定卡片显示的 head,轮询发现 head 变化后禁用“确认更新”;按所选界面语言格式化的变更行数与未解决讨论数(提供方只统计了部分讨论时数字后带 `+`),点击该行打开变更视图;以及合并时托管平台会关闭的关联 issue,各自链接到其页面。讨论数和 issue 标题在悬停 500ms 后以提示显示。已合并或已关闭的显示结束时间与变更行数。“重跑失败项”、评审请求、“更新分支”、“标记为可评审”与“合并”的结果都以 toast 报告,托管平台未确认结果时提示到浏览器中查看变更请求;显示的 head 之后有新提交时不会重跑或更新。主机现在就会合并的变更请求在各行下方提供“合并”,其菜单列出仓库允许的合并方式并选中用户常用的一种,打开时固定卡片显示的 head。“确认合并”使用这个 head;轮询发现 head 变化后禁用确认,需重新检查并打开菜单。每次操作的结果都以 toast 报告;该 head 之后有新提交时不会合并。Session 只绑定了一个变更请求时,无论其状态如何,它的卡片默认展开;绑定多个时,所有卡片默认收起。用户展开或收起某张卡片后,在 Session 保持打开期间,更新和隐藏面板都不会改变这一选择;用户没有动过的卡片仍按默认规则。 +- **变更请求分栏**——Session 有已绑定的变更请求,或仓库所在托管平台需要登录时显示。分栏标题旁显示数量。卡片上方的状态行请用户登录托管平台:显示提供方给出的登录命令(例如 `gh auth login --hostname github.com`,悬停时滚动显示全文)和「复制」;提供方没有给出命令以及登录检查失败时,平台给出的原因收在信息按钮里,与检出行显示失败的方式相同。Session 没有绑定变更请求时,分栏只显示这一行。每个变更请求是一张紧凑卡片,即面板行列上的一块底色:一行内依次是状态图标、标题、编号和检查结果图标。点击这一行在右侧边栏打开该变更请求的变更;按住 Cmd 或 Ctrl 点击、用中键点击,以及没有提供方服务或尚未读取的变更请求,则打开托管平台上的页面。状态图标区分打开、草稿、已合并与已关闭,打开中的变更请求(草稿除外)检查失败、被要求修改或有冲突时显示为“需要处理”,与面板开关的黄点一致。卡片的“更多”菜单与面板其他行一样在悬停或聚焦时出现,提供由提供方服务的变更请求的“查看变更”、“在浏览器中打开”“复制变更请求链接”、打开中草稿的“标记为可评审”,以及“从本会话移除”,移除后的 toast 提供“撤销”。收起时,这一行把状态以文字读给辅助技术,卡片的悬停卡片显示完整标题、编号(带草稿状态与源分支、目标分支)和这段状态:打开的变更请求的检查,以及被要求修改、冲突、草稿中最需要注意的一项;已合并或已关闭的则是结束时间;读取失败或没有提供方服务的 URL 则显示相应说明。已取消的检查单独计数,列出的检查没有失败项时状态显示取消数量。检查结果图标共用同一个圆环:通过为勾,失败为叉,进行中为半填充,其余为短横。展开的卡片在这一行下面每项一行,由图标与取值组成。打开的变更请求依次是:检查,其菜单按失败、运行中、已取消分组列出检查及其耗时与链接,按需列出通过与跳过的检查,用户可以重跑检查、且有失败检查指向一个其中没有检查仍在进行的重跑时提供“重跑失败项”;评审结论,带前三位评审者的头像与其余人数,其菜单列出每位评审者的类型与最近结论,注明早于最新提交的结论,用户可以请求评审时还能重新请求某位评审者,或通过先列出托管平台建议的搜索向其他人请求评审;合并状态,会注明 head 落后于基线,用户可以更新时提供“更新分支”,其菜单在 merge 与 rebase 之间选择,打开时固定卡片显示的 head,轮询发现 head 变化后禁用“确认更新”;按所选界面语言格式化的变更行数与未解决讨论数(提供方只统计了部分讨论时数字后带 `+`),点击该行打开变更视图;以及合并时托管平台会关闭的关联 issue,各自链接到其页面。讨论数和 issue 标题在悬停 500ms 后以提示显示。已合并或已关闭的显示结束时间与变更行数。“重跑失败项”、评审请求、“更新分支”、“标记为可评审”与“合并”的结果都以 toast 报告,托管平台未确认结果时提示到浏览器中查看变更请求;显示的 head 之后有新提交时不会重跑或更新。主机现在就会合并的变更请求在各行下方提供“合并”,其菜单列出仓库允许的合并方式并选中用户常用的一种,打开时固定卡片显示的 head。“确认合并”使用这个 head;轮询发现 head 变化后禁用确认,需重新检查并打开菜单。每次操作的结果都以 toast 报告;该 head 之后有新提交时不会合并。列表显示三张卡片;更多时,卡片之后是面板的折叠控件,用来显示其余卡片或再次收起,Session 保持打开期间保留这一选择。Session 只绑定了一个变更请求时,无论其状态如何,它的卡片默认展开;绑定多个时,所有卡片默认收起。用户展开或收起某张卡片后,在 Session 保持打开期间,更新和隐藏面板都不会改变这一选择;用户没有动过的卡片仍按默认规则。 - **本地变更行**——`branch` 范围有文件变更时始终显示,不受已关联变更请求影响。这一行显示变更的文件数以及新增、删除行数,点击打开变更视图。它的“更多”菜单提供“查看变更”;识别出代码托管仓库、且没有以当前检出分支为源分支的打开中变更请求(含草稿)时,还提供“创建变更请求”:它以界面语言向 Session 发送一条用户消息,请 Agent 为这些变更创建变更请求,并以 toast 报告是否已发送。 - **变更视图**——变更请求卡片上的“变更”一行与“查看变更”菜单项、以及本地变更行会打开一个右侧边栏标签页,列出所有变更的文件;会话面板浮在对话上方时随之关闭。本地标签页名为“本地变更”,默认显示“分支”:工作树与未跟踪文件相对于分叉点的变更。它的标题栏写出当前检出的分支(分离 HEAD 时为缩写提交)与基准分支;点击基准分支打开可搜索的菜单:最前面是“默认”,即 Session 创建的 worktree 的基准提交,否则是 HEAD 与代码托管远端默认分支的合并基准;其后依次是远程跟踪分支与本地分支,各按最近提交排序,不含当前检出的分支,不在所创建的 worktree 中时也不含“默认”已经指向的远程跟踪分支。输入文字会立即筛选已列出的行,短暂停顿后列出名称包含该文字(不区分大小写)的分支;按 Enter 选择第一行。选择其他分支后,与 HEAD 和该分支的合并基准比较。标签页切换到其他范围时仍保留这个选择;关闭标签页或重新加载应用后回到“默认”。所选分支已不存在时,它的名称显示删除线;它与 HEAD 没有共同历史时,视图同样给出说明;两种情况都提供“使用默认基准分支”而不是“重试”。视图较窄时,先隐藏“包含未提交的修改”,再隐藏当前分支。“未提交”与 HEAD 比较,“未暂存”与暂存区比较,“已暂存”比较暂存区与 HEAD。变更请求的视图显示托管平台在其 head 处的 diff;当前检出分支就是该变更请求的源分支时,还会说明本地分支比该 head 多出几个提交。工具栏可以跳到某个文件、汇总变更行数、刷新,并在左右对比与单栏对比、自动换行与截断长行之间切换。工具栏的图标按钮和标题栏的“在浏览器中打开”悬停 500ms 后显示操作说明,键盘聚焦时立即显示。工具栏和标题栏各自保持一行:工具栏变窄时,先把变更行数、全部展开、左右对比与自动换行收进“更多视图选项”菜单,再收起“隐藏测试文件”开关,已审阅进度的文字缩短为圆环旁的计数,最后收起刷新;标题栏的按钮文字不换行,菜单和标题先缩短。访问过的变更标签页会在切换标签页与 Session、隐藏侧边栏及调整停靠位置时保持挂载,在 diff 未改变时保留文件折叠、大文件展开、上下文展开、布局与滚动位置。隐藏的变更视图释放面板订阅并推迟 diff 读取;返回时仅在最新 head 或本地摘要不同时重新读取。刷新替换 diff 后会丢弃展开的上下文,内容变化也可能移动阅读位置。视图隐藏时关闭临时菜单。关闭标签页或重新加载应用后不保留这些进度。每个文件是一张独立的卡片,带浅色底的标题在滚动时停在顶部。文件名在前,目录在后,用更小的浅色字显示,空间不够时目录先缩短;悬停 500ms 后显示完整路径,重命名的文件显示新旧两条路径。每个文件带有新文件、已删除、重命名的标记(重命名标记写出原文件名,只换了目录时写出原路径),“分支”范围下的未跟踪文件还标“未提交”;文件菜单可以复制路径,本地变更可在侧边栏打开整个文件,变更请求可在浏览器中查看该文件在 head 处的页面。标题变窄时,路径、标记和“有新改动”会缩短,行数、“已审阅”和文件菜单始终完整显示。hunk 之间未变更的行折叠成一行,点击后从文件的新版本展开:工作树、“已暂存”时为暂存区,或经托管平台读取的 head 提交;读取 diff 之后文件又有修改时不会展开,直到视图重新读取。不超过 20 行的折叠行点一次全部展开。更长的折叠行每次展开 20 行,可以从上方 hunk 向下展开,也可以从下方 hunk 向上展开;第一个 hunk 之前的折叠行只能向上展开,最后一个 hunk 之后的只能向下展开;折叠行上显示还隐藏的行数。最后一个 hunk 之后行数未知的折叠行,第一次点击时读取文件并显示前 20 行。二进制文件与超过 `maxDiffBytes` 的未跟踪文件只显示一条说明;hunk 超过 1,000 行的文件先显示为一条写出变更行数的折叠条,点击后才绘制;前面的文件累计变更超过 5,000 行后,其后的文件默认收起。视图读取尚未显示过的变更时,会在显示为脉动占位的文件卡片上方写出“正在读取变更…”,并排视图下其中一个已修改文件画成两栏,文件菜单不显示数量;开启“减少动态效果”时占位不动。刷新与页面刷新快捷键、每次导航、变更请求的 head 变化,以及“分支”范围的摘要变化时,视图都会重新读取;变更请求的视图会先等到给出 head 的状态再读取,除非没有提供方服务它或那次轮询失败。head 已越过最新状态时,视图保持加载,等到比读取开始时更新的状态后按其 head 重新读取;该状态在读取期间已到达时立即重读。重新读取已显示的变更时,刷新图标会旋转。托管平台或其提供方因超过大小上限拒绝给出 diff 的变更请求(例如 GitHub 上输出超过提供方 `maxOutputBytes` 的 diff)显示“变更太大,无法在这里显示”并提供“在浏览器中查看”;其他读取失败提供“重试”,变更请求还提供“在浏览器中查看”。变更请求的 diff 在缓存期间对每个 head 提交与目标分支只下载一次,因此在同一 head 下重新打开、刷新与导航都不会再从托管平台读取。刷新评审标记时,如果比较的提交范围、末端提交和补丁都相同,已经展开的未变更行和正在读取的文件内容会保留。 @@ -65,7 +65,7 @@ diff 按文件树的深度优先顺序排列:同层目录在前、文件在后 检查运行 `rev-parse --show-toplevel`、`rev-parse --path-format=absolute --git-common-dir`、`rev-parse --path-format=absolute --git-dir`、`symbolic-ref --quiet HEAD`(指向 `refs/heads/` 下的分支时即为当前分支)、`rev-parse --short HEAD`、`rev-parse --abbrev-ref @{upstream}` 与 `remote -v`;`worktreeBases` 在 `maxDiffBytes` 以内对 `refs/heads/` 与 `refs/remotes/` 运行 `for-each-ref --sort=-committerdate`,从 `refs/remotes//HEAD` 取每个远程的默认分支,略过其他符号引用与未配置远程的分支,并按下文的代码托管识别顺序排列远程,各保留最多 `maxBranches` 个名称包含查询文字的本地分支与每个远程的分支;带名称的 `requestWorktree` 按 Git 的分支名规则检查名称,并在检出中运行 `show-ref`;`diffBases` 像下文的 `localDiff` 一样找出默认分叉点,在 `maxDiffBytes` 以内对 `refs/heads/` 与 `refs/remotes/` 运行 `for-each-ref --sort=-committerdate`,排除 `origin/HEAD` 等符号引用,每类最多保留 `maxBranches` 个名称包含查询文字的分支。之后,检查会为本地变更行统计 `branch` 范围的规模:找出分叉点,对它运行 `diff --numstat -z -M`,采用与下文 `localDiff` 相同的辅助程序和子模块限制,并列出未跟踪文件。每个命令都使用 Session 解析出的沙箱模式:`read-only` 与 `workspace-write` 需要沙箱,`danger-full-access` 无需沙箱后端。命令禁用可选的索引写入、钩子、文件系统监视器、提示与对象的延迟获取,移除继承的 Git 选择器与携带密钥的变量,并各自受 `gitTimeoutMs` 时限与每个输出流的 `maxOutputBytes` 上限约束。Git 打印的顶层目录、Git 目录与公共 Git 目录经 `ctx.fs` 解析为工作目录服务记录的规范进程路径;Git 目录与公共 Git 目录不同的检出是链接 worktree。工作树选项在 `danger-full-access` 沙箱模式下可用,在 `read-only` 下不可用,在 `workspace-write` 下只有两个目录都位于 Session 沙箱策略的规范工作区根内时才可用。 -worktree 请求是一条 `plugin:client-ui-forge/worktree` 记录,由 `forgeWorktree` 投影折叠:请求与撤回在第一个 `turn/start` 或创建之前生效;在第一个 `step/start` 之前,未完成请求的第一条 `created` 记录生效。该投影还从 Session 头部与每个 `working-directory/change` 记录 Session 的目录;它的客户端视图随 Session 摘要下发,在该目录就是所创建的 worktree 或位于其下时为该 worktree,否则为 null。请求用本地分支或远程跟踪分支的完整引用名指定基准(早期面板记录的本地短名称仍可解析),并可指定分支名。一轮开始或 worktree 已创建之后,`requestWorktree` 以 `forgePanel/session-started` 拒绝;没有 `worktrees` 服务时以 `forgePanel/worktrees-unavailable` 拒绝;基准为空时以 `forgePanel/invalid-branch` 拒绝;Git 不接受分支名时以 `forgePanel/invalid-name` 拒绝;检出中已有同名分支时以 `forgePanel/branch-exists` 拒绝;`cancelWorktree` 只以第一种拒绝,也不需要 `worktrees` 服务;两者都会忘掉失败的尝试。消息进入有未完成请求的 Session 的收件箱时,一个 `agent/inbox/inserted` 监听器在这次投递唤醒 Agent 之前启动 Session 所属 Agent 的维护任务,因此 Agent 会暂存唤醒,等这次暂留结束后才开始这条消息的这一轮。暂留用请求的分支名或新的自动名称进行一次尝试,基准是远程跟踪分支时请 worktree 服务先获取它;它在面板状态中发布正在进行的阶段,设置 `held`,`waiting` 为 `creation`,并记录带源仓库根目录的 `created`。尝试失败(其分支、基准、是否获取、失败步骤、原因以及分支或目录是否已存在以 `failure` 留在面板状态中)或经 `stopCreation` 停止后,暂留继续等待:`retryWorktree` 再做一次尝试,`fetch` 参数为 false 时不获取,没有消息等待或已有尝试进行时以 `forgePanel/not-waiting` 拒绝;用另一个名称调用 `requestWorktree` 会改变下一次尝试;撤回请求则让消息在当前检出中继续。Agent 空闲且 Session 在所创建 worktree 中工作时,进入的每条消息都会启动一次暂留,检查该 worktree 是否缺失;缺失期间暂留以 `waiting` 为 `restoration` 等待,`restoreWorktree` 或 `continueInProject` 在暂留内运行,之后放行消息;检查无法给出结果时立即放行。Agent 的取消与 Remote 的停止都会结束暂留;Agent 正在运行一轮或其他维护任务时进入的消息不会被暂留。worktree 服务把工作目录通知排进队列,由第一步认领。一个 `agent/pre-step` 监听器在请求仍未完成的 Session 的第 1 步创建 worktree,覆盖没有被暂留的消息;它把通知移入本步提议的消息,失败时这一轮结束、请求保留。没有消息等待时,`restoreWorktree` 与 `continueInProject` 以各自的维护任务运行;`restoreWorktree` 以 `restoration` 发布正在进行的步骤,并在结束恢复的同一状态中清除 `missing`。套件把它的 `worktrees` 服务隔离,因此同时启用 Git Worktrees 时会有两个互不影响的服务。`track` 以 `forgePanel/unrecognized-url` 拒绝没有提供方识别的 URL。`markReady` 与 `merge` 只作用于该 Session 中由提供方服务的可见绑定,否则以 `forgePanel/not-bound` 拒绝;`merge` 带上卡片显示的 head 提交,head 已变化时以 `forgePanel/stale-head` 拒绝,其他拒绝都是带主机原因的 `forgePanel/action-failed`。 +worktree 请求是一条 `plugin:client-ui-forge/worktree` 记录,由 `forgeWorktree` 投影折叠:请求与撤回在第一个 `turn/start` 或创建之前生效;在第一个 `step/start` 之前,未完成请求的第一条 `created` 记录生效。该投影还从 Session 头部与每个 `working-directory/change` 记录 Session 的目录;它的客户端视图随 Session 摘要下发,在该目录就是所创建的 worktree 或位于其下时为该 worktree,否则为 null。请求用本地分支或远程跟踪分支的完整引用名指定基准(早期面板记录的本地短名称仍可解析),并可指定分支名。一轮开始或 worktree 已创建之后,`requestWorktree` 以 `forgePanel/session-started` 拒绝;没有 `worktrees` 服务时以 `forgePanel/worktrees-unavailable` 拒绝;基准为空时以 `forgePanel/invalid-branch` 拒绝;Git 不接受分支名时以 `forgePanel/invalid-name` 拒绝;检出中已有同名分支时以 `forgePanel/branch-exists` 拒绝;`cancelWorktree` 只以第一种拒绝,也不需要 `worktrees` 服务;两者都会忘掉失败的尝试。消息进入有未完成请求的 Session 的下一轮队列时,一个 `agent/inbox/inserted` 监听器在这次投递唤醒 Agent 之前启动 Session 所属 Agent 的维护任务,因此 Agent 会暂存唤醒,等这次暂留结束后才开始这条消息的这一轮。排给下一步的消息(例如其他插件注入的通知)不开启一轮,也不启动暂留。暂留用请求的分支名或新的自动名称进行一次尝试,基准是远程跟踪分支时请 worktree 服务先获取它;它在面板状态中发布正在进行的阶段,设置 `held`,`waiting` 为 `creation`,并记录带源仓库根目录的 `created`。尝试失败(其分支、基准、是否获取、失败步骤、原因以及分支或目录是否已存在以 `failure` 留在面板状态中)或经 `stopCreation` 停止后,暂留继续等待:`retryWorktree` 再做一次尝试,`fetch` 参数为 false 时不获取,没有消息等待或已有尝试进行时以 `forgePanel/not-waiting` 拒绝;用另一个名称调用 `requestWorktree` 会改变下一次尝试;撤回请求则让消息在当前检出中继续。Agent 空闲且 Session 在所创建 worktree 中工作时,进入下一轮队列的每条消息都会启动一次暂留,检查该 worktree 是否缺失;缺失期间暂留以 `waiting` 为 `restoration` 等待,`restoreWorktree` 或 `continueInProject` 在暂留内运行,之后放行消息;检查无法给出结果时立即放行。Agent 的取消与 Remote 的停止都会结束暂留;Agent 正在运行一轮或其他维护任务时进入的消息不会被暂留。worktree 服务把工作目录通知排进队列,由第一步认领。一个 `agent/pre-step` 监听器在请求仍未完成的 Session 的第 1 步创建 worktree,覆盖没有被暂留的消息;它把通知移入本步提议的消息,失败时这一轮结束、请求保留。没有消息等待时,`restoreWorktree` 与 `continueInProject` 以各自的维护任务运行;`restoreWorktree` 以 `restoration` 发布正在进行的步骤,并在结束恢复的同一状态中清除 `missing`。套件把它的 `worktrees` 服务隔离,因此同时启用 Git Worktrees 时会有两个互不影响的服务。`track` 以 `forgePanel/unrecognized-url` 拒绝没有提供方识别的 URL。`markReady` 与 `merge` 只作用于该 Session 中由提供方服务的可见绑定,否则以 `forgePanel/not-bound` 拒绝;`merge` 带上卡片显示的 head 提交,head 已变化时以 `forgePanel/stale-head` 拒绝,其他拒绝都是带主机原因的 `forgePanel/action-failed`。 恢复在修改前记录 `restoring`,仅在成功后记录 `restored`。投影版本 3 在重载后保留未完成的恢复。目录存在本身不能放行等待的消息:检出根目录与公共 Git 目录必须匹配记录的工作树。插件卸载会取消并等待所有创建、恢复与消息等待任务,然后释放面板读取器和投影。 diff --git a/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx b/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx index 11f3742b79..9ad8172250 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx @@ -1,22 +1,22 @@ /** - * One change request as a card: its one-line title links to the host and - * crawls into view while the pointer rests on the card's head, a one-line - * summary shows while collapsed, taking the short wording of failed checks - * while the full one does not fit and crawling with the title past that, and - * while expanded one row per fact (checks, review, merge state, the changed - * lines, which open its changes, and the linked issues) above the merge - * action. Opening, copying, viewing changes, marking a draft ready, and - * removing live in the card's actions menu. + * One change request as a compact card of the Session panel: one line with + * the state glyph, the title, the number, and the checks outcome, which opens + * the changes view, and, while expanded, one row per fact (checks, review, + * merge state, the changed lines, which open its changes too, and the linked + * issues) above the merge action. Opening on the host, copying, viewing + * changes, marking a draft ready, and removing live in the card's actions + * menu, which shows on hover or focus as on the panel's other rows. */ -import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type PointerEvent, type ReactNode, type RefObject } from 'react' +import { useId, useState, type MouseEvent, type ReactNode } from 'react' import clsx from 'clsx' import { - Button, IconCheckCircleOutlineRegular, IconChevronDownOutlineRegular, IconCloseOutlineRegular, IconCopyOutlineRegular, - IconEllipsisOutlineRegular, IconFilesDiffOutlineRegular, IconRightUpOutlineRegular, IconTriangleRightFillRegular, MarqueeText, Menu, - MenuItemButton, StateDot, Tooltip, useHoverMarquee, - type MenuEntry, type MenuItem, + Button, HoverCard, IconCheckCircleOutlineRegular, IconChevronDownOutlineRegular, IconCloseOutlineRegular, IconCopyOutlineRegular, + IconEllipsisOutlineRegular, IconFilesDiffOutlineRegular, IconRightUpOutlineRegular, IconTriangleRightFillRegular, Menu, + MenuItemButton, StateDot, Tooltip, + type MenuEntry, type MenuItem, type StateDotState, } from '@deepseek-ai/dsh-client-ui-primitives' +import type { PanelDetailsProps } from '@deepseek-ai/dsh-client-ui-session-panel/client' import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' import type { ChangeRequestSnapshot, CheckState, ChecksRollup, ForgeFailure, MergeMethod, MergeRequest, @@ -27,7 +27,7 @@ import { formatAgo } from './format.ts' import { ChangeRequestGlyph, CheckGlyph } from './glyphs.tsx' import type { ForgePanelKey, NS } from './locales.ts' import type { ForgeChangeRequestCardActionsProps } from './slots.ts' -import { ciSummary, flagOf, numberOf, TONE_LABEL, toneOf } from './status.ts' +import { ciSummary, flagOf, numberOf, TONE_LABEL, toneOf, type ChangeRequestTone } from './status.ts' import css from './Forge.module.css' type Translate = PropsLocale['t'] @@ -55,6 +55,10 @@ export interface ChangeRequestActions extends OverviewActions { readonly viewChanges?: ((entry: ForgePanelChangeRequest) => void) | undefined /** Draw the icon buttons plugins add to the card's head through `forge.change-request.card.actions`. */ readonly renderActions?: ((owner: ForgeChangeRequestCardActionsProps) => ReactNode) | undefined + /** + * Draw the content of the card's hover card, as the Session panel's rows do. A surface without it shows none. + */ + readonly renderDetails?: ((details: PanelDetailsProps) => ReactNode) | undefined } /** Props of one change request card. */ @@ -173,97 +177,50 @@ function finished(snapshot: ChangeRequestSnapshot, now: number, t: Translate): s } /** - * Collapsed status after the number: checks and the most urgent flag, the merge or close time, or a read in progress. - * With `short`, failed checks take the wording without their count. + * The checks outcome after the number: a spinner before the first read, the combined outcome of an open change + * request that has checks, and nothing for a finished one, whose glyph already says how it ended. */ -function Summary({ snapshot, now, short, t }: { - readonly snapshot: ChangeRequestSnapshot | null - readonly now: number - readonly short: boolean - readonly t: Translate -}): ReactNode { - if (snapshot === null) return - if (snapshot.state !== 'open') { - return {finished(snapshot, now, t)} - } +function Mark({ snapshot }: { readonly snapshot: ChangeRequestSnapshot | null }): ReactNode { + if (snapshot === null) return + if (snapshot.state !== 'open') return null const ci = ciSummary(snapshot) - const flag = flagOf(snapshot) - return ( - <> - - {ci.kind !== 'none' && } - {ci.kind === 'failed' - ? ci.count > 0 && !short ? t('change.ci.failed', { count: ci.count }) : t('change.ci.failedUnlisted') - : ci.kind === 'cancelled' ? t('change.ci.cancelled', { count: ci.count }) : t(`change.ci.${ci.kind}`)} - - {flag !== undefined && {t(`change.flag.${flag}`)}} - - ) + if (ci.kind === 'none') return null + return } /** - * What the collapsed status line shows when its failed checks can take the shorter wording without their count: the full - * wording and the flag, which decide the line's width. Null for any other status, and where the language's short wording - * is no shorter. + * The status in words: the checks and the most urgent flag of an open change request, or the merge or close time. + * The card's line shows it as glyphs, so assistive technology and the hover card read it here. * @param snapshot - change request status. + * @param now - current epoch milliseconds for the relative time. * @param t - copy. - * @returns the line's full text after the number, or null. + * @returns the status text. */ -function shortenable(snapshot: ChangeRequestSnapshot | null, t: Translate): string | null { - if (snapshot?.state !== 'open') return null +function statusText(snapshot: ChangeRequestSnapshot, now: number, t: Translate): string { + if (snapshot.state !== 'open') return finished(snapshot, now, t) const ci = ciSummary(snapshot) - if (ci.kind !== 'failed' || ci.count === 0) return null - const full = t('change.ci.failed', { count: ci.count }) - if (t('change.ci.failedUnlisted').length >= full.length) return null + const checks = ci.kind === 'failed' + ? ci.count > 0 ? t('change.ci.failed', { count: ci.count }) : t('change.ci.failedUnlisted') + : ci.kind === 'cancelled' ? t('change.ci.cancelled', { count: ci.count }) : t(`change.ci.${ci.kind}`) const flag = flagOf(snapshot) - return flag === undefined ? full : `${full} ${t(`change.flag.${flag}`)}` + return flag === undefined ? checks : `${checks} · ${t(`change.flag.${flag}`)}` } -/** - * Whether the collapsed status line shows the short wording of failed checks: only while the line with the full wording - * does not fit. A change of the line's width, of the fonts, or of `full` shows the full wording again for one layout pass, - * which measures it and switches before the frame is painted. - * @param line - the clipping status line. - * @param full - the line's full text after the number, from {@link shortenable}; null measures nothing. - * @returns whether the line takes the short wording. - */ -function useShortWording(line: RefObject, full: string | null): boolean { - const [measured, setMeasured] = useState<{ readonly full: string | null; readonly short: boolean }>({ full: null, short: false }) - const short = full !== null && measured.full === full && measured.short - useLayoutEffect(() => { - if (full === null || short) return - const element = line.current - /* v8 ignore next -- the status line is mounted whenever there is a full wording to measure */ - if (element === null) return - if (element.scrollWidth > element.clientWidth) setMeasured({ full, short: true }) - }) - useEffect(() => { - if (full === null) return - const element = line.current - /* v8 ignore next -- the status line is mounted whenever there is a full wording to measure */ - if (element === null) return - // A new object renders again even when the line already shows the full wording, so the layout effect measures. - const measure = (): void => { setMeasured({ full, short: false }) } - const observer = new ResizeObserver(measure) - observer.observe(element) - const fonts = document.fonts - fonts.addEventListener('loadingdone', measure) - return () => { - observer.disconnect() - fonts.removeEventListener('loadingdone', measure) - } - }, [line, full]) - return short +/** The state dot of the hover card: red for what needs the user, and a spinner while the checks run. */ +function dotOf(tone: ChangeRequestTone, snapshot: ChangeRequestSnapshot): StateDotState { + if (tone === 'blocked') return 'error' + if (snapshot.state !== 'open') return snapshot.state === 'merged' ? 'done' : 'idle' + return snapshot.checksRollup === 'pending' ? 'ongoing' : snapshot.checksRollup === 'success' ? 'done' : 'idle' } -/** Expanded identity after the number: draft state and the head and base branches. */ -function Target({ snapshot, t }: { readonly snapshot: ChangeRequestSnapshot; readonly t: Translate }): ReactNode { - return ( - <> - {snapshot.state === 'open' && snapshot.draft && {t('change.state.draft')}} - {`${snapshot.headBranch} → ${snapshot.baseBranch}`} - - ) +/** The hover card's line under the title: the number, draft state, and the head and base branches. */ +function identity(number: number | null, snapshot: ChangeRequestSnapshot | null, t: Translate): string[] { + const parts = [ + ...number === null ? [] : [t('change.number', { number })], + ...snapshot?.state === 'open' && snapshot.draft ? [t('change.state.draft')] : [], + ...snapshot === null ? [] : [`${snapshot.headBranch} → ${snapshot.baseBranch}`], + ] + return parts.length === 0 ? [] : [parts.join(' · ')] } /** The merge button and its menu: a title row, one row per method with the chosen one checked, and the confirmation. */ @@ -369,8 +326,8 @@ function Primary({ entry, snapshot, name, actions, t }: { } /** - * The card's actions menu: open on the host, copy the link, view the changes - * of a served change request, mark an open draft ready, and remove the binding. + * The card's actions menu: view the changes of a served change request, open + * on the host, copy the link, mark an open draft ready, and remove the binding. */ function CardMenu({ entry, snapshot, name, url, actions, t }: { readonly entry: ForgePanelChangeRequest @@ -392,12 +349,12 @@ function CardMenu({ entry, snapshot, name, url, actions, t }: { : undefined // Each item carries the action it runs, so a selection never reaches another item's action. const choices: { readonly item: MenuItem; readonly run: () => void }[] = [ - { item: { id: 'open', label: t('change.view'), icon: }, run: () => { actions.openLink(url) } }, - { item: { id: 'copy', label: t('change.copy'), icon: }, run: () => { actions.copyLink(url) } }, ...viewChanges !== undefined && snapshot !== null && entry.ref !== null ? [{ item: { id: 'changes', label: t('change.viewChanges'), icon: }, run: () => { viewChanges(entry) }, }] : [], + { item: { id: 'open', label: t('change.view'), icon: }, run: () => { actions.openLink(url) } }, + { item: { id: 'copy', label: t('change.copy'), icon: }, run: () => { actions.copyLink(url) } }, ...ready === undefined ? [] : [{ item: { id: 'ready', label: t('change.markReady'), icon: , disabled: busy }, run: ready, @@ -423,13 +380,12 @@ function CardMenu({ entry, snapshot, name, url, actions, t }: { anchor={( )} items={items} @@ -480,7 +436,10 @@ function Details({ entry, snapshot, name, now, actions, locale, t }: { } /** - * Render one change request. + * Render one change request. A press on the card's line opens the changes view of a change request a provider serves + * and has read; with the platform's modifier key or the middle button, and for any other change request, it opens + * the host's page. The line shows its status as glyphs and, while collapsed, reads it in words to assistive + * technology, which the expanded rows do otherwise; the hover card names the full title, the branches, and that status. * @param props - change request, expansion, current time, actions, and copy. * @returns the card. */ @@ -492,68 +451,60 @@ export function ChangeRequestCard({ entry, expanded, onToggle, now, actions, loc const notice = entry.ref === null ? 'change.unserved' : failure === undefined ? undefined : FAILURE[failure.code] const tone = toneOf(snapshot) const name = number === null ? snapshot?.title ?? url : t('change.number', { number }) - const titleRef = useRef(null) - const lineRef = useRef(null) - const titleMarquee = useHoverMarquee(titleRef) - const lineMarquee = useHoverMarquee(lineRef) - // One hover on the head carries every text it clips: the title, and the collapsed number and status line. - const marquee = useMemo(() => ({ - onPointerEnter: (event: PointerEvent): void => { - titleMarquee.onPointerEnter(event) - lineMarquee.onPointerEnter(event) - }, - onPointerLeave: (): void => { - titleMarquee.onPointerLeave() - lineMarquee.onPointerLeave() - }, - }), [titleMarquee, lineMarquee]) - const short = useShortWording(lineRef, expanded || notice !== undefined ? null : shortenable(snapshot, t)) - // A notice replaces the collapsed summary, so a failed read never shows its stale status beside it. - const meta = expanded - ? snapshot === null ? null : - : notice === undefined ? : null - const parts = ( - <> - {number !== null && {t('change.number', { number })}} - {number !== null && meta !== null && } - {meta} - - ) - return ( -
  • -
    - -
    - { - event.preventDefault() - actions.openLink(url) - }} - > - {snapshot?.title ?? url.replace(/^https?:\/\//i, '')} - - {(number !== null || meta !== null) && ( -
    - {expanded ? parts : {parts}} -
    - )} -
    + const title = snapshot?.title ?? url.replace(/^https?:\/\//i, '') + // A notice replaces the status, so a failed read never reads its stale status beside it. + const status: PanelDetailsProps['status'] = notice !== undefined + ? { state: 'warning', label: t(notice) } + : snapshot === null ? undefined : { state: dotOf(tone, snapshot), label: statusText(snapshot, now, t) } + const viewChanges = snapshot !== null && entry.ref !== null ? actions.viewChanges : undefined + const open = (event: MouseEvent): void => { + if (viewChanges === undefined || event.metaKey || event.ctrlKey) actions.openLink(url) + else viewChanges(entry) + } + const head = ( +
    + + + {number !== null && {t('change.number', { number })}} + {notice === undefined && } + {!expanded && notice === undefined && status !== undefined && {status.label}} {actions.renderActions?.({ url: entry.url, ref: entry.ref, headSha: snapshot?.headSha ?? null, state: snapshot?.state ?? null })} + + + + -
    + +
    + ) + const details = actions.renderDetails?.({ + title, + lines: identity(number, snapshot, t), + ...status === undefined ? {} : { status }, + }) + return ( +
  • + {details === undefined ? head : } {notice !== undefined && (
    {t(notice)} diff --git a/packages/experimental/client-ui-forge/src/client/ChangeRequestOverview.module.css b/packages/experimental/client-ui-forge/src/client/ChangeRequestOverview.module.css index 3f0cc3ba36..86f3c49ac4 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangeRequestOverview.module.css +++ b/packages/experimental/client-ui-forge/src/client/ChangeRequestOverview.module.css @@ -18,7 +18,7 @@ } .avatars > .avatar { - box-shadow: 0 0 0 1.5px var(--dsw-alias-bg-layer-1); + box-shadow: 0 0 0 1.5px var(--forge-card-surface, var(--dsw-alias-bg-layer-1)); } .moreCount { diff --git a/packages/experimental/client-ui-forge/src/client/ChangeRequestsSection.tsx b/packages/experimental/client-ui-forge/src/client/ChangeRequestsSection.tsx index e6785a22c7..77dafc3b66 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangeRequestsSection.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangeRequestsSection.tsx @@ -1,14 +1,14 @@ /** Session panel section listing the Session's change requests, and its title control. */ -import { useRef, type ReactNode } from 'react' +import { useCallback, useRef, type ReactNode } from 'react' import { - Button, IconWarningTriangleOutlineRegular, MarqueeText, useHoverMarquee, + Button, HoverCardGroup, IconWarningTriangleOutlineRegular, MarqueeText, useHoverMarquee, } from '@deepseek-ai/dsh-client-ui-primitives' import type { - HostObservable, InjectFace, PropsLocale, PropsRenderSlots, PropsRuntime, PropsStore, + HostObservable, InjectFace, PropsLocale, PropsRenderFactories, PropsRenderSlots, PropsRuntime, PropsStore, } from '@deepseek-ai/dsh-client-ui-slots' import type { ForgeReadiness, MergeRequest } from '@deepseek-ai/dsh-experimental-forge/types' -import type {} from '@deepseek-ai/dsh-client-ui-session-panel/client' +import type { PanelDetailsProps } from '@deepseek-ai/dsh-client-ui-session-panel/client' import type { ForgePanelChangeRequest, ForgePanelState } from '../types.ts' import { ChangeRequestCard, type ChangeRequestActions } from './ChangeRequestCard.tsx' import type { createChangeRequestsSectionStore } from './change-requests-store.ts' @@ -59,6 +59,7 @@ export interface ChangeRequestsSectionInjected { export type ChangeRequestsSectionProps = PropsRuntime<'conversation.session.panel.section'> & Pick, 'renderSlot'> + & PropsRenderFactories & InjectFace & PropsStore> & PropsLocale @@ -77,6 +78,9 @@ export type ChangeRequestsActionsProps = type Translate = ChangeRequestsSectionProps['t'] +/** Cards the list shows before its fold control holds the rest back. */ +const FOLD_LIMIT = 3 + /** Sign-in the repository's host still needs before its change requests show. */ interface SignInNeed { readonly host: string @@ -144,20 +148,27 @@ function SignInRow({ need, copyText, t }: { * Render the Session's change request cards. The section shows while the * Session binds a change request or the repository's host needs sign-in, which * a status row above the cards says; a lost stream shows in the Environment - * section instead. A card starts expanded when the Session binds - * exactly one change request; a card the user expands or collapses keeps that - * choice in the Session's store, across updates and while the panel is hidden. - * Viewing changes closes the panel's overlay. - * @param props - panel snapshot hooks, card actions, panel owner values, and copy. + * section instead. The list shows three cards and then the panel's fold + * control, which shows the rest; the choice is kept per Session. A card starts + * expanded when the Session binds exactly one change request; a card the user + * expands or collapses keeps that choice in the Session's store, across + * updates and while the panel is hidden. Viewing changes closes the panel's + * overlay. + * @param props - panel snapshot hooks, card actions, panel owner values, the store, and copy. * @returns the cards, or null with neither bound change requests nor a sign-in to complete. */ export function ChangeRequestsSection({ usePanel, useLocale, dismissOverlay, refresh, remove, markReady, merge, readChecks, - rerunChecks, requestReviews, reviewerCandidates, updateBranch, openLink, copyText, viewChanges, useStore, actions: store, renderSlot, t, + rerunChecks, requestReviews, reviewerCandidates, updateBranch, openLink, copyText, viewChanges, useStore, actions: store, renderSlot, + renderFactorySlot, t, }: ChangeRequestsSectionProps): ReactNode { const snapshot = usePanel(current => current) const locale = useLocale(value => value) const chosen = useStore(current => current.expanded) + const unfolded = useStore(current => current.unfolded) + const renderDetails = useCallback( + (details: PanelDetailsProps) => renderFactorySlot('conversation.session.panel.details', details), [renderFactorySlot], + ) const state = snapshot.state if (state === null) return null const signIn = signInNeedOf(state) @@ -170,30 +181,43 @@ export function ChangeRequestsSection({ dismissOverlay() }, renderActions: owner => renderSlot('forge.change-request.card.actions', owner), + renderDetails, } const defaults = defaultExpanded(state.changeRequests) const expanded = (url: string): boolean => chosen[url] ?? defaults.has(url) const toggle = (url: string): void => { store.toggled(url, !expanded(url)) } const now = Date.now() + const foldable = state.changeRequests.length > FOLD_LIMIT + const shown = foldable && !unfolded ? state.changeRequests.slice(0, FOLD_LIMIT) : state.changeRequests + const label = unfolded ? t('fold.less') : t('fold.more', { count: state.changeRequests.length - FOLD_LIMIT }) return (
    {signIn !== null && } - {state.changeRequests.length > 0 && ( -
      - {state.changeRequests.map(entry => ( - { toggle(entry.url) }} - now={now} - actions={actions} - locale={locale} - t={t} - /> - ))} -
    + {shown.length > 0 && ( + // Moving between cards swaps their hover cards without another dwell. + +
      + {shown.map(entry => ( + { toggle(entry.url) }} + now={now} + actions={actions} + locale={locale} + t={t} + /> + ))} +
    +
    )} + {foldable && renderFactorySlot('conversation.session.panel.fold', { + expanded: unfolded, + label, + name: t('fold.name', { label }), + onToggle: () => { store.unfoldedSet(!unfolded) }, + })}
    ) } diff --git a/packages/experimental/client-ui-forge/src/client/Forge.module.css b/packages/experimental/client-ui-forge/src/client/Forge.module.css index 3b5b1312a2..6e2d849597 100644 --- a/packages/experimental/client-ui-forge/src/client/Forge.module.css +++ b/packages/experimental/client-ui-forge/src/client/Forge.module.css @@ -1,134 +1,90 @@ /* Change request cards in the Session panel section, at the panel's 13px row size. */ .cards { - --forge-fill: var(--dsw-alias-card-fill); display: flex; flex-direction: column; - gap: 8px; + gap: 4px; min-width: 0; color: var(--dsw-alias-label-primary); font-size: var(--dsh-content-font-size-secondary, 13px); line-height: 20px; } -.iconButton { - display: inline-flex; - flex: none; - align-items: center; - justify-content: center; - width: 28px; - height: 28px; - padding: 0; - border: 0; - border-radius: var(--dsw-radius-sm); - background: transparent; - color: var(--dsw-alias-label-tertiary); - cursor: pointer; -} - -.iconButton:focus-visible { - background: var(--dsw-alias-interactive-bg-hover); - color: var(--dsw-alias-label-primary); -} - -@media (hover: hover) { - .iconButton:hover { - background: var(--dsw-alias-interactive-bg-hover); - color: var(--dsw-alias-label-primary); - } -} - -/* A More button shares its surface: the glyph darkens without a fill, as on Session panel rows. */ -.iconButton.moreButton:focus-visible { - background: transparent; -} - -@media (hover: hover) { - .iconButton.moreButton:hover { - background: transparent; - } -} - .list { display: flex; flex-direction: column; - gap: 8px; + gap: 4px; margin: 0; padding: 0; list-style: none; } +/* One change request: a filled block without a border, on the panel's row columns. The platform fill stands apart + from the panel's surface in both themes; the card fill is nearly that surface's own color in the dark theme. */ .change { min-width: 0; - border: 0.5px solid var(--dsw-alias-border-l2); - border-radius: var(--dsw-radius-md); - background: var(--dsw-alias-bg-layer-1); + border-radius: var(--dsw-radius-sm); + /* Named for what the block draws on itself, such as the ring that sets overlapping avatars apart. */ + --forge-card-surface: var(--dsw-alias-bg-module-platform); + background: var(--forge-card-surface); } -/* Glyph, title link with the number line below it, then the actions menu - and the expansion toggle. */ -.changeHead { - display: flex; - align-items: flex-start; - gap: 2px; - min-width: 0; - padding: 12px 8px 10px 14px; +/* The card's line is a panel row, 36px instead of 28px: the glyph in the icon column, the title, the number and the + checks outcome, the actions menu the panel reveals on hover, and the expansion toggle in the end column. */ +.change .changeHead { + min-height: 36px; } -.changeHead > .glyph { - margin: 3px 10px 0 0; +.change .changeHead > [data-row-part='body'] { + height: 36px; } -/* The buttons center on the title's first line. */ -.changeHead > .iconButton { - margin-top: -3px; +/* The number and the checks outcome after the title. */ +.status { + font-size: 12px; + font-variant-numeric: tabular-nums; } -.headText { - display: flex; - flex: 1; - flex-direction: column; - gap: 2px; - min-width: 0; - padding-top: 1px; +.number { + white-space: nowrap; } -.changeTitle { - display: block; - min-width: 0; - color: var(--dsw-alias-label-primary); - font-weight: 500; - line-height: 20px; - text-decoration: none; +/* The expansion toggle in the row's end column, 16px wide like the menu column: a 24px target around the chevron. */ +.change .changeHead > .end { + justify-content: center; + width: 16px; +} + +.expand { + display: inline-flex; + flex: none; + align-items: center; + justify-content: center; + width: 24px; + height: 24px; + margin: -4px; + padding: 0; + border: 0; + border-radius: var(--dsw-radius-xs); + background: transparent; + color: var(--dsw-alias-label-tertiary); + cursor: pointer; +} + +.expand:focus-visible { + outline-offset: -2px; } @media (hover: hover) { - .changeTitle:hover { + .expand:hover { color: var(--dsw-alias-label-primary); - text-decoration: underline; - text-underline-offset: 2px; } } -.changeTitle:focus-visible, .rowButton:focus-visible { outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); outline-offset: 1px; } -/* Number line below the title: the status while collapsed, the branches while expanded. */ -.meta { - display: flex; - align-items: center; - gap: 6px; - min-width: 0; - overflow: hidden; - padding: 1px 0; - color: var(--dsw-alias-label-tertiary); - font-size: 12px; - font-variant-numeric: tabular-nums; - line-height: 18px; -} - /* Lifecycle glyph; drawn in the current color unless the state tints it. */ .glyph { display: inline-flex; @@ -200,82 +156,27 @@ color: var(--dsw-alias-state-error-primary); } -.ci { - display: inline-flex; - align-items: center; - gap: 5px; - color: var(--dsw-alias-label-secondary); -} - -.ci[data-tone='error'], -.flag[data-flag='changesRequested'], -.flag[data-flag='conflicting'] { - color: var(--dsw-alias-state-error-primary); -} - -.flag { - color: var(--dsw-alias-label-tertiary); -} - -/* Only the branch names and the collapsed status line shorten; the number, checks, and flags keep whole words on one line. */ -.meta > :not(.ellipsis):not(.statusLine) { - flex: none; - white-space: nowrap; -} - -/* The collapsed number and status: one line as wide as the row, so a change of its wording never resizes it. It clips - with an ellipsis and crawls with the title; its parts sit inline so the ellipsis cuts between characters. */ -.statusLine { - flex: 1; -} - -.statusLine .dot { - margin: 0 6px; -} - -.statusLine .ci { - display: inline; -} - -.statusLine .checkGlyph { - margin-inline-end: 5px; - vertical-align: -2px; -} - -.statusLine .flag { - margin-inline-start: 6px; -} - -.finished { - color: var(--dsw-alias-label-secondary); -} - -.finished[data-tone='merged'] { - color: var(--dsw-alias-state-done-primary); -} - -/* Read failure or unsupported host below the head, with its one action. */ +/* Read failure or unsupported host below the card's line, from where the title starts, with its one action. */ .notice { display: flex; align-items: center; justify-content: space-between; gap: 8px; - padding: 0 10px 10px 33px; + padding: 0 8px 8px 30px; color: var(--dsw-alias-label-secondary); font-size: 12px; line-height: 18px; } -/* Expanded facts, one sentence per row: an icon under the glyph, the value, an optional trailing part, and a chevron - on a row that opens something. */ +/* Expanded facts inside the card's block, one sentence per row: an icon under the title's start, the value, an + optional trailing part, and a chevron in the card's end column on a row that opens something. */ .rows { /* Contains the visually hidden row labels, so they never extend a scroll area outside the panel. */ position: relative; display: grid; grid-template-columns: 24px minmax(0, 1fr) auto 12px; gap: 0 8px; - padding: 4px 6px 6px; - border-top: 0.5px solid var(--dsw-alias-border-l2); + padding: 0 8px 4px 22px; } .row { @@ -286,7 +187,7 @@ column-gap: 8px; box-sizing: border-box; width: 100%; - min-height: 32px; + min-height: 28px; margin: 0; padding: 0 8px; border: 0; @@ -415,7 +316,7 @@ display: flex; align-items: center; gap: 8px; - padding: 2px 14px 12px; + padding: 4px 8px 8px 26px; } .primaryAction { diff --git a/packages/experimental/client-ui-forge/src/client/change-requests-store.ts b/packages/experimental/client-ui-forge/src/client/change-requests-store.ts index 485a43363b..a091b531db 100644 --- a/packages/experimental/client-ui-forge/src/client/change-requests-store.ts +++ b/packages/experimental/client-ui-forge/src/client/change-requests-store.ts @@ -1,5 +1,5 @@ /** - * The expansion the user chose for the change request cards of one Session. The + * The expansion the user chose for the change request cards of one Session, and whether its list shows every card. The * registration declares it as an exclusive store, so each Session keeps its * choices while its scope is retained, across hiding and showing the panel. */ @@ -10,11 +10,14 @@ import { defineStore, type EngineStoreHandle } from '@deepseek-ai/dsh-client-sto export interface ChangeRequestsSectionState { /** Whether the user expanded (true) or collapsed (false) a card, by change request URL; unchosen cards are absent. */ expanded: Record + /** Whether the list shows the cards past its first three. */ + unfolded: boolean } /** The change requests section store's write set. */ type ChangeRequestsSectionActions = { toggled: (draft: ChangeRequestsSectionState, url: string, expanded: boolean) => void + unfoldedSet: (draft: ChangeRequestsSectionState, unfolded: boolean) => void } /** @@ -23,7 +26,7 @@ type ChangeRequestsSectionActions = { */ export function createChangeRequestsSectionStore(): EngineStoreHandle { return defineStore({ - init: (): ChangeRequestsSectionState => ({ expanded: {} }), + init: (): ChangeRequestsSectionState => ({ expanded: {}, unfolded: false }), actions: { /** * Record the user's choice for one card. @@ -34,6 +37,14 @@ export function createChangeRequestsSectionStore(): EngineStoreHandle { d.expanded[url] = expanded }, + /** + * Show every card of the list, or fold it to its first three again. + * @param d - draft state. + * @param unfolded - whether the list now shows every card. + */ + unfoldedSet: (d, unfolded: boolean) => { + d.unfolded = unfolded + }, }, }) } diff --git a/packages/experimental/client-ui-forge/src/client/glyphs.tsx b/packages/experimental/client-ui-forge/src/client/glyphs.tsx index a609e4abec..d86ef4f429 100644 --- a/packages/experimental/client-ui-forge/src/client/glyphs.tsx +++ b/packages/experimental/client-ui-forge/src/client/glyphs.tsx @@ -2,7 +2,7 @@ import type { ReactNode } from 'react' import clsx from 'clsx' -import { IconCheckCircleFillRegular, IconCloseCircleFillRegular } from '@deepseek-ai/dsh-client-ui-primitives' +import { IconCheckCircleFillRegular } from '@deepseek-ai/dsh-client-ui-primitives' import type { CheckState, ChecksRollup } from '@deepseek-ai/dsh-experimental-forge/types' import type { ChangeRequestTone } from './status.ts' import css from './Forge.module.css' @@ -125,25 +125,24 @@ const CHECK_TONE: Record = { } /** - * Draw the decorative outcome of one check beside its text: a filled circle - * for success or failure, a half-filled ring while it runs, and an empty ring - * for neutral, skipped, and cancelled checks. + * Draw the decorative outcome of one check beside its text, each inside the same ring: a check for success, a cross + * for failure, a half fill while it runs, and a dash for neutral, skipped, and cancelled checks. The ring has the + * radius and width of the success icon's, so mixed outcomes read as one set. * @param props.state - check outcome. * @param props.size - width and height in pixels, 16 by default. * @returns the glyph. */ export function CheckGlyph({ state, size = 16 }: { readonly state: CheckState; readonly size?: number | undefined }): ReactNode { - const running = state === 'pending' return ( diff --git a/packages/experimental/client-ui-forge/src/client/locales.ts b/packages/experimental/client-ui-forge/src/client/locales.ts index a2a27a90d9..4fa95dac40 100644 --- a/packages/experimental/client-ui-forge/src/client/locales.ts +++ b/packages/experimental/client-ui-forge/src/client/locales.ts @@ -97,6 +97,9 @@ export const zh = { 'list.worktree': '在自己的工作树中', 'list.stateChecks': '{state} · {checks}', 'list.more': '还有 {count} 个变更请求', + 'fold.more': '显示其余 {count} 个', + 'fold.less': '收起', + 'fold.name': '{label}(变更请求)', 'change.expand': '展开 {name}', 'change.collapse': '收起 {name}', 'change.ci.none': '没有检查', @@ -585,6 +588,9 @@ export const en: Record = { 'list.worktree': 'In its own worktree', 'list.stateChecks': '{state} · {checks}', 'list.more': '{count} more change requests', + 'fold.more': 'Show {count} more', + 'fold.less': 'Show less', + 'fold.name': '{label} (change requests)', 'change.expand': 'Expand {name}', 'change.collapse': 'Collapse {name}', 'change.ci.none': 'No checks', @@ -1043,6 +1049,9 @@ export const ja: Record = { 'list.worktree': '専用のワークツリー内', 'list.stateChecks': '{state} · {checks}', 'list.more': '他 {count} 件の変更リクエスト', + 'fold.more': '残り{count}件を表示', + 'fold.less': '折りたたむ', + 'fold.name': '{label}(変更リクエスト)', 'tab.title': '変更リクエスト', 'header.attention': 'このセッションの変更リクエストに対応が必要です', 'checkout.worktree': 'ワークツリー', @@ -1528,6 +1537,9 @@ export const es: Record = { 'list.worktree': 'En su propio árbol de trabajo', 'list.stateChecks': '{state} · {checks}', 'list.more': '{count} solicitudes de cambio más', + 'fold.more': 'Mostrar {count} más', + 'fold.less': 'Mostrar menos', + 'fold.name': '{label} (solicitudes de cambio)', 'tab.title': 'Solicitudes de cambio', 'header.attention': 'Las solicitudes de cambio de esta sesión requieren atención', 'checkout.worktree': 'Árbol de trabajo', @@ -2013,6 +2025,9 @@ export const fr: Record = { 'list.worktree': 'Dans son propre arbre de travail', 'list.stateChecks': '{state} · {checks}', 'list.more': '{count} demandes de changement supplémentaires', + 'fold.more': 'Afficher {count} de plus', + 'fold.less': 'Afficher moins', + 'fold.name': '{label} (demandes de modification)', 'tab.title': 'Demandes de modification', 'header.attention': 'Les demandes de modification de cette session nécessitent une intervention', 'checkout.worktree': 'Arbre de travail', @@ -2498,6 +2513,9 @@ export const de: Record = { 'list.worktree': 'Im eigenen Arbeitsbaum', 'list.stateChecks': '{state} · {checks}', 'list.more': '{count} weitere Änderungsanfragen', + 'fold.more': '{count} weitere anzeigen', + 'fold.less': 'Weniger anzeigen', + 'fold.name': '{label} (Änderungsanfragen)', 'tab.title': 'Änderungsanfragen', 'header.attention': 'Änderungsanfragen dieser Sitzung erfordern Aufmerksamkeit', 'checkout.worktree': 'Arbeitsbaum', @@ -2983,6 +3001,9 @@ export const ru: Record = { 'list.worktree': 'В собственном рабочем дереве', 'list.stateChecks': '{state} · {checks}', 'list.more': 'Ещё запросов на изменение: {count}', + 'fold.more': 'Показать ещё {count}', + 'fold.less': 'Свернуть', + 'fold.name': '{label} (запросы на изменение)', 'tab.title': 'Запросы на изменение', 'header.attention': 'Запросы на изменение этого сеанса требуют внимания', 'checkout.worktree': 'Рабочее дерево', @@ -3468,6 +3489,9 @@ export const pt: Record = { 'list.worktree': 'Na sua própria árvore de trabalho', 'list.stateChecks': '{state} · {checks}', 'list.more': 'Mais {count} solicitações de alteração', + 'fold.more': 'Mostrar mais {count}', + 'fold.less': 'Mostrar menos', + 'fold.name': '{label} (solicitações de alteração)', 'tab.title': 'Solicitações de alteração', 'header.attention': 'As solicitações de alteração desta sessão precisam de atenção', 'checkout.worktree': 'Árvore de trabalho', diff --git a/packages/experimental/client-ui-forge/src/index.ts b/packages/experimental/client-ui-forge/src/index.ts index cc2d4c9494..7a1a850cd8 100644 --- a/packages/experimental/client-ui-forge/src/index.ts +++ b/packages/experimental/client-ui-forge/src/index.ts @@ -14,7 +14,7 @@ import type { import type { SessionChangeRequest } from '@deepseek-ai/dsh-experimental-forge-session' import type { WorktreeCleanup } from '@deepseek-ai/dsh-experimental-worktree/types' import { appendPluginRecord } from '@deepseek-ai/dsh-session' -import type { Session, SessionEvent } from '@deepseek-ai/dsh-session' +import type { Session, SessionEvent, UserMessage } from '@deepseek-ai/dsh-session' import type { ProjectionHandle } from '@deepseek-ai/dsh-session-projection' import type {} from '@deepseek-ai/dsh-session-projection-cache' import type {} from '@deepseek-ai/dsh-session-query' @@ -178,7 +178,7 @@ export class ForgePanelController extends TypertRemoteService { this.creations = new WorktreeCreations(ctx, this.worktreeStates, this.config.worktreePrefix, (session) => { this.panels.get(session)?.updateWorktree() }) - const inbox = ctx.on('agent/inbox/inserted', ({ agent }) => { this.holdTurn(agent) }) + const inbox = ctx.on('agent/inbox/inserted', ({ agent, message }) => { this.holdTurn(agent, message) }) const events = ctx.on('session/event', (session: Session, event: SessionEvent) => { this.panels.get(session)?.observe(event) }) @@ -967,14 +967,17 @@ export class ForgePanelController extends TypertRemoteService { /* oxlint-enable typescript/require-await */ /** - * Hold the turn of a message entering a Session's inbox while the + * Hold the turn of a message entering a Session's next-turn queue while the * Session's requested worktree does not exist yet, or while the worktree * the Session works in is checked and, when gone, until it is restored or * left. The message is entering, so the delivery has not woken the Agent - * yet and its wake waits for the hold. + * yet and its wake waits for the hold. A message for the next step, such as + * a notice another plugin queues, opens no turn and gets no hold. * @param agent - Agent whose inbox receives the message. + * @param message - the entering message. */ - private holdTurn(agent: Agent): void { + private holdTurn(agent: Agent, message: UserMessage): void { + if (!agent.inbox.nextTurn.some(queued => queued.id === message.id)) return const session = agent.session const state = this.worktreeState(session) if (state.request !== null && state.created === null && !state.locked) { diff --git a/packages/experimental/client-ui-forge/tests/change-request-card.client.spec.tsx b/packages/experimental/client-ui-forge/tests/change-request-card.client.spec.tsx index fa1a11d9c0..22fb694408 100644 --- a/packages/experimental/client-ui-forge/tests/change-request-card.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/change-request-card.client.spec.tsx @@ -1,7 +1,10 @@ // @vitest-environment jsdom -/** One change request card: state glyph, title link, collapsed summary, read notices, and expanded details and actions. */ +/** + * One change request card: its line of state glyph, title, number, and checks outcome, the hover details, read notices, + * and expanded details and actions. + */ import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react' -import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' import type { ForgeFailure, MergeRequest } from '@deepseek-ai/dsh-experimental-forge/types' import { ChangeRequestCard, type ChangeRequestActions } from '../src/client/ChangeRequestCard.tsx' @@ -35,9 +38,10 @@ function card(value: ForgePanelChangeRequest, options: { expanded?: boolean; act ) const item = view.container.querySelector('[data-forge-change]') const head = item?.querySelector(`.${css.changeHead}`) - if (!(item instanceof HTMLElement) || !(head instanceof HTMLElement)) throw new Error('no change request card') - /** The number and status line below the title, or null when it names neither. */ - const meta = (): HTMLElement | null => head.querySelector(`.${css.meta}`) + const line = head?.querySelector('[data-row-part="body"]') + const status = head?.querySelector(`.${css.status}`) + const drawn = item instanceof HTMLElement && head instanceof HTMLElement && line instanceof HTMLElement && status instanceof HTMLElement + if (!drawn) throw new Error('no change request card') const menuButton = (): HTMLElement => within(head).getByRole('button', { name: /^Actions for / }) /** Labels of the actions menu, closing it again. */ const menuItems = (): string[] => { @@ -51,14 +55,13 @@ function card(value: ForgePanelChangeRequest, options: { expanded?: boolean; act fireEvent.click(menuButton()) fireEvent.click(screen.getByRole('menuitem', { name: label })) } - return { view, item, head, meta, menuButton, menuItems, choose, title: within(head).getByRole('link'), openLink, copyLink, retry, remove, onToggle } -} - -/** The number and status line of a card that has one. */ -function metaOf(b: ReturnType): HTMLElement { - const meta = b.meta() - if (meta === null) throw new Error('no number or status line') - return meta + /** The title the line shows. */ + const title = (): string | null => line.querySelector('[data-row-part="content"]')?.textContent ?? null + /** The status the line reads to assistive technology, or null when it reads none. */ + const spoken = (): string | null => status.querySelector(`.${css.visuallyHidden}`)?.textContent ?? null + return { + view, item, head, line, status, title, spoken, menuButton, menuItems, choose, openLink, copyLink, retry, remove, onToggle, + } } /** The value a details row shows after its name, which only assistive technology reads. */ @@ -111,63 +114,68 @@ describe('ChangeRequestCard head', () => { expect(glyph?.getAttribute('aria-label')).toBe(`Change request state: ${en['change.state.unknown']}`) }) - it('opens the snapshot URL from the title instead of following the link in the page', () => { - const b = card(entry(7, snapshot(7, { url: 'https://github.com/octo/demo/pull/7#web' }))) - expect(b.title.textContent).toBe('Change 7') - expect(b.title.getAttribute('href')).toBe('https://github.com/octo/demo/pull/7#web') - expect(fireEvent.click(b.title)).toBe(false) - expect(b.openLink).toHaveBeenCalledWith('https://github.com/octo/demo/pull/7#web') + it('lays its line out by the panel row marks: the body, the status, the actions menu, and the toggle in the end column', () => { + const b = card(entry(7, snapshot(7))) + expect(b.head.hasAttribute('data-session-panel-row')).toBe(true) + expect([...b.head.children].map(part => part.getAttribute('data-row-part'))).toEqual(['body', 'trailing', 'menu', 'trailing']) + expect([...b.line.children].map(part => part.getAttribute('data-row-part'))).toEqual(['icon', 'content']) + expect(b.line.tagName).toBe('BUTTON') + expect(b.line.querySelector('[data-row-part="icon"] [data-forge-glyph]')).not.toBeNull() + expect(b.title()).toBe('Change 7') + expect(b.menuButton().closest('[data-row-part]')?.getAttribute('data-row-part')).toBe('menu') + expect(within(b.head).getByRole('button', { name: 'Expand #7' }).closest(`.${css.end}`)).toBe(b.head.lastElementChild) + }) + + it('opens the changes of a served change request from its line, and its page with a modifier key or the middle button', () => { + const viewChanges = vi.fn<(entry: ForgePanelChangeRequest) => void>() + const value = entry(7, snapshot(7, { url: 'https://github.com/octo/demo/pull/7#web' })) + const b = card(value, { actions: { viewChanges } }) + expect(b.line.getAttribute('data-forge-opens')).toBe('changes') + + fireEvent.click(b.line) + expect(viewChanges.mock.calls).toEqual([[value]]) + expect(b.openLink).not.toHaveBeenCalled() + + fireEvent.click(b.line, { metaKey: true }) + fireEvent.click(b.line, { ctrlKey: true }) + fireEvent(b.line, new MouseEvent('auxclick', { bubbles: true, button: 1 })) + fireEvent(b.line, new MouseEvent('auxclick', { bubbles: true, button: 2 })) + expect(viewChanges).toHaveBeenCalledOnce() + expect(b.openLink.mock.calls).toEqual(Array.from({ length: 3 }, () => ['https://github.com/octo/demo/pull/7#web'])) expect(b.onToggle).not.toHaveBeenCalled() }) - it('crawls a title the card clips while the pointer rests on the card head, expanded or not', () => { - for (const expanded of [false, true]) { - const b = card(entry(7, snapshot(7)), { expanded }) - const text = b.title.firstElementChild - if (!(text instanceof HTMLElement)) throw new Error('no title text') - expect(text.textContent).toBe('Change 7') - Object.defineProperty(text, 'scrollWidth', { value: 240, configurable: true }) - Object.defineProperty(text, 'clientWidth', { value: 120, configurable: true }) - fireEvent.pointerEnter(b.head) - expect([text.hasAttribute('data-marquee'), text.style.getPropertyValue('--dsh-marquee-range')]).toEqual([true, '120px']) - fireEvent.pointerLeave(b.head) - expect([text.hasAttribute('data-marquee'), text.style.getPropertyValue('--dsh-marquee-range')]).toEqual([false, '']) - cleanup() - } + it.each([ + ['no provider serves', unserved('https://example.test/review/17'), true, 'https://example.test/review/17'], + ['is not read yet', entry(1, null), true, 'https://github.com/octo/demo/pull/1'], + ['shows on a surface without a changes view', entry(1, snapshot(1)), false, 'https://github.com/octo/demo/pull/1'], + ] as const)('opens the page of a change request that %s from its line', (_label, value, changes, url) => { + const viewChanges = vi.fn<(entry: ForgePanelChangeRequest) => void>() + const b = card(value, { actions: changes ? { viewChanges } : {} }) + expect(b.line.getAttribute('data-forge-opens')).toBe('link') + fireEvent.click(b.line) + expect(b.openLink.mock.calls).toEqual([[url]]) + expect(viewChanges).not.toHaveBeenCalled() }) - it('crawls the collapsed number and status line with the title while the pointer rests on the head', () => { - const b = card(entry(7, snapshot(7))) - const line = metaOf(b).firstElementChild - if (!(line instanceof HTMLElement)) throw new Error('no status line') - expect(line.className).toContain(css.statusLine) - Object.defineProperty(line, 'scrollWidth', { value: 200, configurable: true }) - Object.defineProperty(line, 'clientWidth', { value: 150, configurable: true }) - fireEvent.pointerEnter(b.head) - expect([line.hasAttribute('data-marquee'), line.style.getPropertyValue('--dsh-marquee-range')]).toEqual([true, '50px']) - fireEvent.pointerLeave(b.head) - expect([line.hasAttribute('data-marquee'), line.style.getPropertyValue('--dsh-marquee-range')]).toEqual([false, '']) - }) - - it('toggles from the chevron, while the number line stays plain text', () => { + it('toggles from the chevron, which the line does not contain', () => { const b = card(entry(7, snapshot(7))) expect(b.item.hasAttribute('data-expanded')).toBe(false) - expect(metaOf(b).closest('button')).toBeNull() const chevron = within(b.head).getByRole('button', { name: 'Expand #7' }) expect(chevron.getAttribute('aria-expanded')).toBe('false') + expect(b.line.contains(chevron)).toBe(false) fireEvent.click(chevron) expect(b.onToggle).toHaveBeenCalledOnce() + expect(b.openLink).not.toHaveBeenCalled() }) }) describe('collapsed ChangeRequestCard', () => { - it('summarizes an open change request by its number and checks beside its header actions, without its rows', () => { + it('shows the number and the checks outcome of an open change request after its title, without its rows', () => { const b = card(entry(7, snapshot(7))) - const meta = metaOf(b) - expect(within(meta).getByText('#7')).toBeTruthy() - expect(within(meta).getByText('·')).toBeTruthy() - expect(within(meta).getByText(en['change.ci.passed']).querySelector('[data-forge-check]')?.getAttribute('data-forge-check')).toBe('success') - expect(meta.querySelector('[data-flag]')).toBeNull() + expect(within(b.status).getByText('#7').className).toBe(css.number) + expect(b.status.querySelector('[data-forge-check]')?.getAttribute('data-forge-check')).toBe('success') + expect(b.spoken()).toBe(en['change.ci.passed']) expect(within(b.item).queryByText(en['change.row.changes'])).toBeNull() expect(within(b.item).queryByText('+12')).toBeNull() expect(b.menuButton().getAttribute('aria-label')).toBe('Actions for #7') @@ -180,102 +188,44 @@ describe('collapsed ChangeRequestCard', () => { }) it.each([ - ['no checks', { checksRollup: 'none' }, en['change.ci.none'], undefined, null], - ['running checks', { checksRollup: 'pending' }, en['change.ci.running'], 'pending', null], + ['no checks', { checksRollup: 'none' }, en['change.ci.none'], undefined], + ['running checks', { checksRollup: 'pending' }, en['change.ci.running'], 'pending'], ['listed failed checks', { checksRollup: 'failure', checks: [check('lint', { state: 'failure' }), check('test'), check('types', { state: 'failure' })], - }, '2 checks failed', 'failure', 'error'], - ['cancelled checks', { checksRollup: 'failure', checks: [check('build', { state: 'cancelled' })] }, '1 checks cancelled', 'cancelled', null], - ['failed checks the host did not list', { checksRollup: 'failure', checksTruncated: true }, en['change.ci.failedUnlisted'], 'failure', 'error'], - ] as const)('states %s', (_label, overrides, text, glyph, tone) => { - const ci = within(metaOf(card(entry(1, snapshot(1, overrides))))).getByText(text) - expect(ci.querySelector('[data-forge-check]')?.getAttribute('data-forge-check')).toBe(glyph) - expect(ci.getAttribute('data-tone')).toBe(tone) + }, '2 checks failed', 'failure'], + ['cancelled checks', { checksRollup: 'failure', checks: [check('build', { state: 'cancelled' })] }, '1 checks cancelled', 'cancelled'], + ['failed checks the host did not list', { checksRollup: 'failure', checksTruncated: true }, en['change.ci.failedUnlisted'], 'failure'], + ] as const)('marks %s with a glyph and reads them in words', (_label, overrides, text, glyph) => { + const b = card(entry(1, snapshot(1, overrides))) + expect(b.status.querySelector('[data-forge-check]')?.getAttribute('data-forge-check')).toBe(glyph) + expect(b.spoken()).toBe(text) }) it.each([ - ['requested changes', { reviewDecision: 'changes-requested', mergeability: 'conflicting' }, 'changesRequested', en['change.flag.changesRequested']], - ['merge conflicts', { mergeability: 'conflicting', draft: true }, 'conflicting', en['change.flag.conflicting']], - ['draft state', { draft: true }, 'draft', en['change.flag.draft']], - ] as const)('flags %s after the checks', (_label, overrides, flag, text) => { - const meta = metaOf(card(entry(1, snapshot(1, overrides)))) - expect(meta.querySelector('[data-flag]')?.getAttribute('data-flag')).toBe(flag) - expect(within(meta).getByText(text)).toBeTruthy() - }) - - /** - * Give status lines the given width and their content a width by wording, 200px with the full failed-checks wording and - * 150px with the short one, and capture the resize observer. Returns the setter of the width and the resize trigger. - */ - function fitting(initial: number) { - let available = initial - let resized: () => void = () => {} - vi.stubGlobal('ResizeObserver', class { - constructor(callback: () => void) { resized = callback } - observe = vi.fn() - disconnect = vi.fn() - }) - const isLine = (element: Element): boolean => element.matches(`.${css.statusLine}`) - const client = vi.spyOn(Element.prototype, 'clientWidth', 'get').mockImplementation(function (this: Element) { - return isLine(this) ? available : 0 - }) - const scroll = vi.spyOn(Element.prototype, 'scrollWidth', 'get').mockImplementation(function (this: Element) { - return isLine(this) ? (this.textContent ?? '').includes('2 checks failed') ? 200 : 150 : 0 - }) - onTestFinished(() => { - vi.unstubAllGlobals() - client.mockRestore() - scroll.mockRestore() - }) - return { - resize: (width: number): void => { available = width; act(() => { resized() }) }, - set: (width: number): void => { available = width }, - } - } - - const FAILING = { - checksRollup: 'failure', mergeability: 'conflicting', - checks: [check('lint', { state: 'failure' }), check('test'), check('types', { state: 'failure' })], - } as const - - it('takes the short wording of failed checks while the full line does not fit, and measures again on width and font changes', () => { - const fit = fitting(160) - const b = card(entry(1, snapshot(1, FAILING))) - const short = `#1·${en['change.ci.failedUnlisted']}${en['change.flag.conflicting']}` - expect(metaOf(b).textContent).toBe(short) - fit.resize(250) - expect(metaOf(b).textContent).toBe(`#1·2 checks failed${en['change.flag.conflicting']}`) - fit.set(160) - act(() => { document.fonts.dispatchEvent(new Event('loadingdone')) }) - expect(metaOf(b).textContent).toBe(short) - }) - - it('keeps the full wording of failed checks where the language has no shorter one', () => { - fitting(100) - const long = makeTranslate({ ...en, 'change.ci.failedUnlisted': 'Every check that ran has failed' }) - expect(metaOf(card(entry(1, snapshot(1, FAILING)), { t: long })).textContent).toBe(`#1·2 checks failed${en['change.flag.conflicting']}`) + ['requested changes', { reviewDecision: 'changes-requested', mergeability: 'conflicting' }, en['change.flag.changesRequested']], + ['merge conflicts', { mergeability: 'conflicting', draft: true }, en['change.flag.conflicting']], + ['draft state', { draft: true }, en['change.flag.draft']], + ] as const)('reads %s after the checks', (_label, overrides, text) => { + expect(card(entry(1, snapshot(1, overrides))).spoken()).toBe(`${en['change.ci.passed']} · ${text}`) }) it.each([ - ['merged three hours ago', { state: 'merged', closedAt: '2026-10-09T09:00:00Z' }, 'merged', 'Merged into main · 3 h ago'], - ['closed without a close time', { state: 'closed' }, 'closed', en['change.state.closed']], - ['closed at a time that does not parse', { state: 'closed', closedAt: 'last week' }, 'closed', en['change.state.closed']], - ] as const)('states a change request %s instead of its checks', (_label, overrides, tone, text) => { - const meta = metaOf(card(entry(1, snapshot(1, { ...overrides, checksRollup: 'failure', reviewDecision: 'changes-requested' })))) - expect(within(meta).getByText(text).getAttribute('data-tone')).toBe(tone) - expect(within(meta).queryByText(en['change.ci.failedUnlisted'])).toBeNull() - expect(meta.querySelector('[data-flag]')).toBeNull() + ['merged three hours ago', { state: 'merged', closedAt: '2026-10-09T09:00:00Z' }, 'Merged into main · 3 h ago'], + ['closed without a close time', { state: 'closed' }, en['change.state.closed']], + ['closed at a time that does not parse', { state: 'closed', closedAt: 'last week' }, en['change.state.closed']], + ] as const)('reads a change request %s instead of its checks, without a checks glyph', (_label, overrides, text) => { + const b = card(entry(1, snapshot(1, { ...overrides, checksRollup: 'failure', reviewDecision: 'changes-requested' }))) + expect(b.spoken()).toBe(text) + expect(b.status.querySelector('[data-forge-check]')).toBeNull() }) it('names the URL and the number of a change request with a spinner before its first poll', () => { const b = card(entry(1, null)) - expect(b.title.textContent).toBe('github.com/octo/demo/pull/1') - expect(b.title.getAttribute('href')).toBe('https://github.com/octo/demo/pull/1') - const meta = metaOf(b) - expect(within(meta).getByText('#1')).toBeTruthy() - expect(within(meta).getByText('·')).toBeTruthy() - expect(meta.querySelector('[data-state="ongoing"]')).not.toBeNull() + expect(b.title()).toBe('github.com/octo/demo/pull/1') + expect(within(b.status).getByText('#1')).toBeTruthy() + expect(b.status.querySelector('[data-state="ongoing"]')).not.toBeNull() + expect(b.spoken()).toBeNull() expect(b.item.querySelector(`.${css.notice}`)).toBeNull() }) @@ -283,10 +233,10 @@ describe('collapsed ChangeRequestCard', () => { ['not-found', en['change.failure.notFound']], ['unauthenticated', en['change.failure.unauthenticated']], ['unavailable', en['change.failure.unavailable']], - ] as const)('explains a %s read failure in place of the summary and retries it', (code, text) => { + ] as const)('explains a %s read failure below the line in place of the status and retries it', (code, text) => { const failure: ForgeFailure = { code, message: 'detail' } const b = card(entry(1, failure)) - expect(metaOf(b).textContent).toBe('#1') + expect(b.status.textContent).toBe('#1') const notice = b.item.querySelector(`.${css.notice}`) if (!(notice instanceof HTMLElement)) throw new Error('no failure notice') expect(within(notice).getByText(text)).toBeTruthy() @@ -296,17 +246,17 @@ describe('collapsed ChangeRequestCard', () => { expect(b.openLink).not.toHaveBeenCalled() }) - it('keeps the title of the last snapshot after a failed read but not its stale summary', () => { + it('keeps the title of the last snapshot after a failed read but not its stale status', () => { const b = card(entry(4, { code: 'unavailable', message: 'down' }, { kept: snapshot(4, { checksRollup: 'failure' }) })) - expect(b.title.textContent).toBe('Change 4') - expect(metaOf(b).textContent).toBe('#4') + expect(b.title()).toBe('Change 4') + expect(b.status.textContent).toBe('#4') expect(within(b.item).getByText(en['change.failure.unavailable'])).toBeTruthy() }) - it('opens a URL no provider serves instead of retrying it, without a number line when the URL names no number', () => { + it('opens a URL no provider serves instead of retrying it, without a number when the URL names none', () => { const b = card(unserved('http://example.test/review/latest')) - expect(b.title.textContent).toBe('example.test/review/latest') - expect(b.meta()).toBeNull() + expect(b.title()).toBe('example.test/review/latest') + expect(b.status.textContent).toBe('') const notice = b.item.querySelector(`.${css.notice}`) if (!(notice instanceof HTMLElement)) throw new Error('no unserved notice') expect(within(notice).getByText(en['change.unserved'])).toBeTruthy() @@ -319,17 +269,69 @@ describe('collapsed ChangeRequestCard', () => { }) it('reads the number of an unserved URL from its path', () => { - expect(metaOf(card(unserved('https://example.test/review/17'))).textContent).toBe('#17') + expect(card(unserved('https://example.test/review/17')).status.textContent).toBe('#17') + }) +}) + +describe('ChangeRequestCard hover card', () => { + /** Render a card on a surface that draws hover details, and return what the card asked it to draw. */ + function described(value: ForgePanelChangeRequest, expanded = false) { + const renderDetails = vi.fn>(() => ) + const b = card(value, { expanded, actions: { renderDetails } }) + return { ...b, details: renderDetails.mock.lastCall?.[0] } + } + + it('names the full title, the number with the branches, and the status in words', () => { + expect(described(entry(7, snapshot(7))).details).toEqual({ + title: 'Change 7', lines: ['#7 · feat → main'], status: { state: 'done', label: en['change.ci.passed'] }, + }) + }) + + it.each([ + ['a draft', snapshot(1, { draft: true, checksRollup: 'none' }), ['#1 · Draft · feat → main'], 'idle', `${en['change.ci.none']} · ${en['change.flag.draft']}`], + ['running checks', snapshot(1, { checksRollup: 'pending' }), ['#1 · feat → main'], 'ongoing', en['change.ci.running']], + ['what needs the author', snapshot(1, { mergeability: 'conflicting' }), ['#1 · feat → main'], 'error', `${en['change.ci.passed']} · ${en['change.flag.conflicting']}`], + ['a merge', snapshot(1, { state: 'merged' }), ['#1 · feat → main'], 'done', 'Merged into main'], + ['a close', snapshot(1, { state: 'closed' }), ['#1 · feat → main'], 'idle', en['change.state.closed']], + ] as const)('gives %s its state dot', (_label, value, lines, state, label) => { + expect(described(entry(1, value)).details).toEqual({ title: 'Change 1', lines, status: { state, label } }) + }) + + it('names only the URL and the number before the first poll', () => { + expect(described(entry(1, null)).details).toEqual({ title: 'github.com/octo/demo/pull/1', lines: ['#1'] }) + }) + + it('states a failed read and an unserved URL as its status', () => { + expect(described(entry(4, { code: 'unavailable', message: 'down' }, { kept: snapshot(4) })).details).toEqual({ + title: 'Change 4', lines: ['#4 · feat → main'], status: { state: 'warning', label: en['change.failure.unavailable'] }, + }) + cleanup() + expect(described(unserved('http://example.test/review/latest')).details).toEqual({ + title: 'example.test/review/latest', lines: [], status: { state: 'warning', label: en['change.unserved'] }, + }) + }) + + it('anchors the hover card to the line, expanded or not, and draws the line alone on a surface without details', () => { + for (const expanded of [false, true]) { + const b = described(entry(7, snapshot(7)), expanded) + expect(b.head.parentElement).not.toBe(b.item) + expect(b.item.contains(b.head)).toBe(true) + cleanup() + } + const plain = card(entry(7, snapshot(7))) + expect(plain.head.parentElement).toBe(plain.item) }) }) describe('expanded ChangeRequestCard', () => { - it('shows the target, details, and diff size of an open change request and runs its actions on the snapshot URL', () => { + it('shows the details and diff size of an open change request below its line and runs its actions on the snapshot URL', () => { const value = entry(7, snapshot(7, { url: 'https://github.com/octo/demo/pull/7#web', additions: 12345 })) const b = card(value, { expanded: true }) expect(b.item.getAttribute('data-forge-change')).toBe('https://github.com/octo/demo/pull/7') expect(b.item.hasAttribute('data-expanded')).toBe(true) - expect(metaOf(b).textContent).toBe('#7·feat → main') + // The rows below state the status, so the line no longer reads it. + expect(b.status.textContent).toBe('#7') + expect(b.spoken()).toBeNull() expect(within(b.head).getByRole('button', { name: 'Collapse #7' }).getAttribute('aria-expanded')).toBe('true') expect(rowValue(b.item, en['change.row.checks']).textContent).toBe(en['change.ci.none']) expect(within(b.item).getByText(en['change.row.checks']).closest('button')).toBeNull() @@ -351,12 +353,6 @@ describe('expanded ChangeRequestCard', () => { expect(b.remove).toHaveBeenCalledWith(value) }) - it('marks a draft before its branches', () => { - const meta = metaOf(card(entry(7, snapshot(7, { draft: true })), { expanded: true })) - expect(within(meta).getByText(en['change.state.draft'])).toBeTruthy() - expect(meta.textContent).toBe('#7·Draftfeat → main') - }) - it.each([ ['merge conflicts', { mergeability: 'conflicting' }, 'Conflicts with main', 'error'], ['an unknown mergeability', { mergeability: 'unknown' }, en['change.merge.unknown'], null], @@ -571,7 +567,7 @@ describe('expanded ChangeRequestCard', () => { it('shows only the link actions before the first poll', () => { const b = card(entry(1, null), { expanded: true }) - expect(metaOf(b).textContent).toBe('#1') + expect(b.status.textContent).toBe('#1') expect(within(b.item).queryByText(en['change.row.checks'])).toBeNull() expect(within(b.item).queryByText('+12')).toBeNull() expect(b.menuItems()).toEqual([en['change.view'], en['change.copy'], en['change.remove']]) @@ -579,10 +575,11 @@ describe('expanded ChangeRequestCard', () => { expect(b.copyLink).toHaveBeenCalledWith('https://github.com/octo/demo/pull/1') }) - it('shows the branches and opens the snapshot URL of an unnumbered change request', () => { + it('names an unnumbered change request by its title and opens its snapshot URL', () => { const b = card({ ...unserved('https://example.test/review/latest'), snapshot: snapshot(3, { url: 'https://example.test/review/latest#web' }) }, { expanded: true }) - expect(b.title.textContent).toBe('Change 3') - expect(metaOf(b).textContent).toBe('feat → main') + expect(b.title()).toBe('Change 3') + // No provider serves the URL, so the unserved notice stands in for the status. + expect(b.status.textContent).toBe('') expect(b.menuButton().getAttribute('aria-label')).toBe('Actions for Change 3') b.choose(en['change.remove']) expect(b.remove).toHaveBeenCalledOnce() diff --git a/packages/experimental/client-ui-forge/tests/controller.host.spec.ts b/packages/experimental/client-ui-forge/tests/controller.host.spec.ts index 08d741cb0f..3c8f6a56b7 100644 --- a/packages/experimental/client-ui-forge/tests/controller.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/controller.host.spec.ts @@ -60,6 +60,9 @@ function reader(opened: Bench): Follower { const ready = (state: ForgePanelState): boolean => state.checkout.state === 'ready' && state.readiness !== null +/** Text of a notice a plugin queues for the next step, as the approval service does after a policy change. */ +const POLICY_NOTICE = 'The user changed the approval policy from "ask the user for approval" to "never ask the user for approval".' + /** Worktree facts of a Session without a worktree service, request, or creation, whose checkout can host a worktree. */ const UNAVAILABLE = { editable: false, blocker: null, namePrefix: 'dsh-', request: null, created: null, creation: null, failure: null, missing: null, @@ -1255,6 +1258,31 @@ describe('forgePanel worktree creation while a message waits', () => { ]) }) + it('creates no worktree for a notice queued for the next step, and creates it when the first message arrives', async () => { + const { repo } = await project() + const opened = await open(repo, {}, { worktrees: true }) + const follower = reader(opened) + await follower.until(ready) + await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal) + const maintenance = vi.spyOn(opened.agent, 'runMaintenance') + const policy = prompt(POLICY_NOTICE) + + opened.agent.inject(policy) + const afterNotice = maintenance.mock.calls.length + const untouched = worktreeState(opened).created + sendPrompt(opened.agent, 'first') + await opened.agent.whenIdle() + + const created = worktreeState(opened)?.created ?? null + expect(afterNotice).toBe(0) + expect(untouched).toBeNull() + expect(maintenance).toHaveBeenCalledTimes(1) + expect(created?.repositoryRoot).toBe(repo) + expect(opened.agent.wakes).toBe(1) + expect(opened.agent.inbox.nextStep).toEqual([policy, notice(created?.path ?? '')]) + expect(queued(opened)).toEqual(['first']) + }) + it('keeps the message waiting with the failure the panel shows, and tries again with a new branch when asked', async () => { const { repo } = await project() const opened = await open(repo, {}, { worktrees: true }) @@ -1652,6 +1680,23 @@ describe('forgePanel removed worktrees', () => { expect(queued(opened)).toEqual(['before', 'first', 'inside', 'removed', 'outside']) }) + it('starts no check of a removed worktree for a notice queued for the next step', async () => { + const { repo } = await project() + const opened = await open(repo, {}, { worktrees: true }) + const created = await startInWorktree(opened) + await rm(created.path, { recursive: true, force: true }) + const maintenance = vi.spyOn(opened.agent, 'runMaintenance') + + opened.agent.inject(prompt(POLICY_NOTICE)) + const afterNotice = maintenance.mock.calls.length + sendPrompt(opened.agent, 'removed') + await vi.waitFor(async () => { await expect(opened.ctx.forgePanel.continueInProject(opened.session, signal)).resolves.toBeUndefined() }) + await opened.agent.whenIdle() + + expect(afterNotice).toBe(0) + expect(opened.ctx.workingDirectory.get(opened.session)).toBe(repo) + }) + it('leaves a worktree whose directory exists unchanged', async () => { const { repo } = await project() const opened = await open(repo, {}, { worktrees: true }) diff --git a/packages/experimental/client-ui-forge/tests/panel-entries.client.spec.tsx b/packages/experimental/client-ui-forge/tests/panel-entries.client.spec.tsx index bec2208327..e4f5886801 100644 --- a/packages/experimental/client-ui-forge/tests/panel-entries.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/panel-entries.client.spec.tsx @@ -11,6 +11,7 @@ import type { MergeRequest } from '@deepseek-ai/dsh-experimental-forge/types' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { bindSnapshotSelector, contextMenuHook, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' import type { ContextMenuTarget } from '@deepseek-ai/dsh-client-ui-context-menu/client' +import type { PanelFoldProps } from '@deepseek-ai/dsh-client-ui-session-panel/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { brandString } from '@deepseek-ai/dsh-brand' import { @@ -70,6 +71,12 @@ function section(state: ForgePanelState | null, options: { disconnected?: boolea dismissOverlay: vi.fn<() => void>(), // Plugins' card actions: a marker naming the change request it was drawn for. renderSlot: vi.fn((_name: string, owner: { url: string }) => ), + // The panel's Component Factories: the fold control as a button, and a row's hover details as a marker. + renderFactorySlot: vi.fn((name: string, input: object) => { + if (name !== 'conversation.session.panel.fold') return + const fold = input as PanelFoldProps + return + }), } const props = { sessionId: SESSION, @@ -82,7 +89,7 @@ function section(state: ForgePanelState | null, options: { disconnected?: boolea t, } as Pick as ChangeRequestsSectionProps const view = render() return { view, panel, store, ...handlers } @@ -154,6 +161,65 @@ describe('ChangeRequestsSection', () => { expect(expansion(section(ready({ changeRequests: [entry(1, snapshot(1))] })).view)).toEqual([true]) }) + /** The numbers of the rendered cards, in list order. */ + const numbers = (view: ReturnType): string[] => + [...view.container.querySelectorAll('[data-forge-change]')].map(card => card.getAttribute('data-forge-change')?.split('/').at(-1) ?? '') + const several = (count: number): ForgePanelState => + ready({ changeRequests: Array.from({ length: count }, (_unused, index) => entry(index + 1, snapshot(index + 1))) }) + + it('shows up to three cards without a fold control', () => { + const b = section(several(3)) + expect(numbers(b.view)).toEqual(['1', '2', '3']) + expect(b.view.container.querySelector('[data-fold]')).toBeNull() + }) + + it('shows three cards of four or more and then the fold control, which shows the rest and folds them again', () => { + const b = section(several(4)) + expect(numbers(b.view)).toEqual(['1', '2', '3']) + const fold = (): HTMLElement => b.view.container.querySelector('[data-fold]') as HTMLElement + expect([fold().textContent, fold().getAttribute('aria-label'), fold().getAttribute('aria-expanded')]) + .toEqual(['Show 1 more', 'Show 1 more (change requests)', 'false']) + // The control is the list's last row, after the cards. + expect(fold().compareDocumentPosition(b.view.container.querySelector('ul') as HTMLElement) & Node.DOCUMENT_POSITION_PRECEDING).toBeTruthy() + + fireEvent.click(fold()) + expect(numbers(b.view)).toEqual(['1', '2', '3', '4']) + expect([fold().textContent, fold().getAttribute('aria-label'), fold().getAttribute('aria-expanded')]) + .toEqual(['Show less', 'Show less (change requests)', 'true']) + act(() => { b.panel.set({ state: several(6), disconnected: false }) }) + expect(numbers(b.view)).toEqual(['1', '2', '3', '4', '5', '6']) + + fireEvent.click(fold()) + expect(numbers(b.view)).toEqual(['1', '2', '3']) + expect(fold().textContent).toBe('Show 3 more') + }) + + it('keeps the fold choice of the Session while the panel is hidden and shown again', () => { + const b = section(several(5)) + fireEvent.click(b.view.container.querySelector('[data-fold]') as HTMLElement) + b.view.unmount() + expect(numbers(section(several(5), { store: b.store }).view)).toEqual(['1', '2', '3', '4', '5']) + expect(numbers(section(several(5)).view)).toEqual(['1', '2', '3']) + }) + + it('draws each card\'s hover details through the panel\'s details Factory', () => { + const b = section(ready({ changeRequests: [entry(7, snapshot(7)), entry(8, null)] })) + expect(b.renderFactorySlot).toHaveBeenCalledWith('conversation.session.panel.details', { + title: 'Change 7', lines: ['#7 · feat → main'], status: { state: 'done', label: en['change.ci.passed'] }, + }) + expect(b.renderFactorySlot).toHaveBeenCalledWith('conversation.session.panel.details', { title: 'github.com/octo/demo/pull/8', lines: ['#8'] }) + }) + + it('opens the changes of a card from its line and closes the panel\'s overlay', () => { + const value = entry(7, snapshot(7)) + const b = section(ready({ changeRequests: [value, entry(8, snapshot(8))] })) + const line = b.view.container.querySelector('[data-forge-change="https://github.com/octo/demo/pull/7"] [data-row-part="body"]') as HTMLElement + fireEvent.click(line) + expect(b.viewChanges.mock.calls).toEqual([[value]]) + expect(b.dismissOverlay).toHaveBeenCalledOnce() + expect(b.openLink).not.toHaveBeenCalled() + }) + it('draws the actions plugins add to each card before its actions menu', () => { const b = section(ready({ changeRequests: [entry(7, snapshot(7)), entry(8, null)] })) expect(b.renderSlot).toHaveBeenCalledWith('forge.change-request.card.actions', { diff --git a/packages/experimental/cua-windows/README.i18n.yaml b/packages/experimental/cua-windows/README.i18n.yaml index 3840972d27..e3f75c7271 100644 --- a/packages/experimental/cua-windows/README.i18n.yaml +++ b/packages/experimental/cua-windows/README.i18n.yaml @@ -15,8 +15,8 @@ en: 8ee204b4021505b9 zh: 67040b79fcd9643b /deepseek-ai-dsh-cua-windows/setup-and-configuration: - en: 879fde2d14869543 - zh: 69d4c6c2c2823edc + en: 5f4acdea9b346066 + zh: 1793b993e7561647 /deepseek-ai-dsh-cua-windows/interface-semantics: en: 13ff5154e3ed57cf zh: b6a976028b104068 diff --git a/packages/experimental/cua-windows/README.md b/packages/experimental/cua-windows/README.md index 59e19b96b8..dcc3c9eaeb 100644 --- a/packages/experimental/cua-windows/README.md +++ b/packages/experimental/cua-windows/README.md @@ -24,7 +24,7 @@ Discover Windows applications, obtain consent, then inspect and operate their wi In a native Windows source checkout, activation uses the .NET 10 SDK on PATH to build the helper for the current architecture under `native/bin/win-`. Set `helperPath` to the absolute path of an existing executable to use it instead. For a manual build, run `pnpm run build:native:x64` or `pnpm run build:native:arm64` in this package. To use the standalone win-x64 ZIP, extract the entire archive and point `helperPath` at its exe. The framework-dependent `build:native` output in `native/bin/local` requires a matching Windows .NET runtime and an explicit `helperPath`. -`buildTimeoutMs` defaults to 300000, `connectTimeoutMs` to 30000, and `pollIntervalMs` to 25. Accessibility reads default to 2000 nodes and depth 25. Pass `maxElements` and `maxDepth` to override either limit for one read. The bundle loads this provider only on native Windows. When configured explicitly in WSL, `windowsPowerShellPath` defaults to `powershell.exe`. The WSL cache currently copies only the exe, so a multi-file publish cannot start from that cache. +`buildTimeoutMs` defaults to 300000, `connectTimeoutMs` to 600000, and `pollIntervalMs` to 25. Accessibility reads default to 2000 nodes and depth 25. Pass `maxElements` and `maxDepth` to override either limit for one read. The bundle loads this provider only on native Windows. When configured explicitly in WSL, `windowsPowerShellPath` defaults to `powershell.exe`. The WSL cache currently copies only the exe, so a multi-file publish cannot start from that cache. ## Interface semantics diff --git a/packages/experimental/cua-windows/README.zh.md b/packages/experimental/cua-windows/README.zh.md index 413061faf6..45f309ee88 100644 --- a/packages/experimental/cua-windows/README.zh.md +++ b/packages/experimental/cua-windows/README.zh.md @@ -24,7 +24,7 @@ kind: "package-reference" 在原生 Windows 的源码检出中,提供方启用时通过 PATH 中的 .NET 10 SDK 构建当前架构的 helper,输出到 `native/bin/win-`。`helperPath` 可指定现有 exe 的绝对路径。手动构建时,在本包中执行 `pnpm run build:native:x64` 或 `pnpm run build:native:arm64`。使用独立 win-x64 ZIP 时,需要完整解压,并将 `helperPath` 指向其中的 exe。使用 `build:native` 生成的 `native/bin/local` 产物时,需要匹配的 Windows .NET 运行时,并显式配置 `helperPath`。 -`buildTimeoutMs` 默认 300000,`connectTimeoutMs` 默认 30000,`pollIntervalMs` 默认 25。辅助功能树默认最多读取 2000 个节点、深度 25。一次读取可传入 `maxElements` 和 `maxDepth`。组合包仅在原生 Windows 上加载此提供方。显式在 WSL 中配置提供方时,`windowsPowerShellPath` 默认是 `powershell.exe`。目前 WSL 缓存只复制 exe,多文件发布目录不能直接从该缓存启动。 +`buildTimeoutMs` 默认 300000,`connectTimeoutMs` 默认 600000,`pollIntervalMs` 默认 25。辅助功能树默认最多读取 2000 个节点、深度 25。一次读取可传入 `maxElements` 和 `maxDepth`。组合包仅在原生 Windows 上加载此提供方。显式在 WSL 中配置提供方时,`windowsPowerShellPath` 默认是 `powershell.exe`。目前 WSL 缓存只复制 exe,多文件发布目录不能直接从该缓存启动。 ## 接口语义 diff --git a/packages/experimental/cua-windows/native/entry/ClipboardPaste.cs b/packages/experimental/cua-windows/native/entry/ClipboardPaste.cs index 3b25dc2062..6617c44232 100644 --- a/packages/experimental/cua-windows/native/entry/ClipboardPaste.cs +++ b/packages/experimental/cua-windows/native/entry/ClipboardPaste.cs @@ -1,5 +1,4 @@ -// Delayed rendering waits for clipboard data consumption before restoring the previous formats. -using System.Diagnostics; +// Paste publishes clipboard data immediately and leaves it available after dispatching Control+V. using System.Runtime.InteropServices; using System.Text; using DeepSeek.Cua.Protocol; @@ -8,96 +7,6 @@ namespace DeepSeek.Cua.Windows; internal sealed class ClipboardPaste { - private sealed class Transaction(ServiceControl control, int targetPid, uint format, byte[] payload, List<(uint Format, byte[] Data)> previous, uint originalSequence) - { - internal readonly TaskCompletionSource Consumed = new(TaskCreationOptions.RunContinuationsAsynchronously); - private uint sequence = originalSequence; - private bool replaced; - private bool restoring; - private bool changed; - private bool rendered; - - internal void Begin() - { - if (!Win32.OpenClipboard(control.Handle)) throw new NativeFailure("CLIPBOARD_BUSY", "Another application is using the clipboard"); - try - { - if (Win32.GetClipboardSequenceNumber() != sequence) throw new NativeFailure("CLIPBOARD_CHANGED", "The clipboard changed before paste; it was not replaced"); - if (!Win32.EmptyClipboard()) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "Windows refused clipboard replacement"); - replaced = true; - control.ClipboardMessage = Message; - Marshal.SetLastPInvokeError(0); - Win32.SetClipboardData(format, 0); - var error = Marshal.GetLastPInvokeError(); - sequence = Win32.GetClipboardSequenceNumber(); - if (error != 0) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "Windows refused the temporary clipboard format"); - } - finally { Win32.CloseClipboard(); } - // CloseClipboard can add synthesized formats and advance the sequence. - sequence = Win32.GetClipboardSequenceNumber(); - } - - private bool Message(int message, nint parameter) - { - if (message == 0x0307 && !restoring) - { - changed = true; - Consumed.TrySetException(new NativeFailure("CLIPBOARD_CHANGED", "Another writer replaced the clipboard; observe before deciding on further input")); - return true; - } - if (message is not (0x0305 or 0x0306)) return false; - if (message == 0x0305 && (uint)parameter != format) return false; - if (message == 0x0305) - { - Win32.GetWindowThreadProcessId(Win32.GetOpenClipboardWindow(), out var readerPid); - // Clipboard monitors can request data before the target handles Control+V. - // Leave the format delayed until the selected application requests it. - if (readerPid != targetPid) return true; - } - var opened = false; - try - { - if (Win32.GetClipboardOwner() != control.Handle) return true; - if (message == 0x0306) - { - if (!Win32.OpenClipboard(control.Handle)) return true; - opened = true; - } - if (Win32.GetClipboardSequenceNumber() != sequence) changed = true; - Publish(format, payload); - rendered = true; - sequence = Win32.GetClipboardSequenceNumber(); - if (changed) Consumed.TrySetException(new NativeFailure("CLIPBOARD_CHANGED", "Another writer changed the clipboard during paste")); - else if (message == 0x0305) Consumed.TrySetResult(null); - } - catch (Exception error) { Consumed.TrySetException(error); } - finally { if (opened) Win32.CloseClipboard(); } - return true; - } - - internal bool Restore() - { - if (!replaced) return true; - if (Win32.GetClipboardOwner() != control.Handle) { control.ClipboardMessage = null; return true; } - if (!Win32.OpenClipboard(control.Handle)) return false; - try - { - if (Win32.GetClipboardSequenceNumber() != sequence) changed = true; - if (changed) - { - // A later writer keeps its data; fulfill any remaining promise before releasing its renderer. - if (!rendered) Publish(format, payload); - return true; - } - restoring = true; - if (!Win32.EmptyClipboard()) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "Windows refused clipboard restoration"); - foreach (var original in previous) Publish(original.Format, original.Data); - return true; - } - finally { control.ClipboardMessage = null; Win32.CloseClipboard(); } - } - } - private static void Publish(uint format, byte[] bytes) { var memory = Win32.GlobalAlloc(0x0002, (nuint)bytes.Length); @@ -114,71 +23,29 @@ internal sealed class ClipboardPaste finally { if (memory != 0) Win32.GlobalFree(memory); } } - private static Transaction Prepare(ServiceControl control, int targetPid, string text, string format, int maximumBytes) + private static void SetClipboard(ServiceControl control, string text, string format, int maximumBytes) { + var payload = format == "html" ? HtmlClipboard.Encode(text) : Encoding.Unicode.GetBytes(text + "\0"); + if (payload.Length > maximumBytes) throw new NativeFailure("CLIPBOARD_LIMIT", "The paste content exceeds maxClipboardBytes"); + var nativeFormat = format == "html" ? Win32.RegisterClipboardFormat("HTML Format") : 13u; + if (nativeFormat == 0) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "Windows could not register the requested clipboard format"); if (!Win32.OpenClipboard(control.Handle)) throw new NativeFailure("CLIPBOARD_BUSY", "Another application is using the clipboard"); try { - var previous = new List<(uint, byte[])>(); - long total = 0; - uint current = 0; - while (true) - { - Marshal.SetLastPInvokeError(0); - current = Win32.EnumClipboardFormats(current); - if (current == 0) - { - if (Marshal.GetLastPInvokeError() != 0) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "The existing clipboard formats could not be enumerated"); - break; - } - if (current is 3 or 0x0083) - throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "The clipboard contains a metafile with nested handles; paste left it unchanged"); - var memory = Win32.GetClipboardData(current); - var size = memory == 0 ? 0 : Win32.GlobalSize(memory); - if (size == 0 || size > int.MaxValue) - throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "The current clipboard includes a format that cannot be preserved as bytes; paste left it unchanged"); - total += (long)size; - if (total > maximumBytes) throw new NativeFailure("CLIPBOARD_LIMIT", "The existing clipboard exceeds maxClipboardBytes; it was not replaced"); - var pointer = Win32.GlobalLock(memory); - if (pointer == 0) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "The current clipboard data could not be read; it was not replaced"); - var bytes = new byte[(int)size]; - try { Marshal.Copy(pointer, bytes, 0, bytes.Length); } - finally { Win32.GlobalUnlock(memory); } - previous.Add((current, bytes)); - } - var payload = format == "html" ? HtmlClipboard.Encode(text) : Encoding.Unicode.GetBytes(text + "\0"); - var nativeFormat = format == "html" ? Win32.RegisterClipboardFormat("HTML Format") : 13u; - if (nativeFormat == 0) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "Windows could not register the requested clipboard format"); - return new(control, targetPid, nativeFormat, payload, previous, Win32.GetClipboardSequenceNumber()); + if (!Win32.EmptyClipboard()) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "Windows refused clipboard replacement"); + Publish(nativeFormat, payload); } finally { Win32.CloseClipboard(); } } - internal async Task Paste(AppState app, WindowState window, string text, string format, int maximumBytes, int readTimeoutMs, RequestContext context) + internal async Task Paste(AppState app, WindowState window, string text, string format, int maximumBytes, RequestContext context) { Windows.RequireForeground(app, window, context); - // Clipboard readers are matched against this window's real process, not a removal-only app identity. - var targetPid = window.ProcessId; - var transaction = await context.Sta.Invoke(control => Prepare(control, targetPid, text, format, maximumBytes), context.Cancellation); - try + await context.Sta.Invoke(control => { - await context.Sta.Invoke(() => transaction.Begin(), context.Cancellation); - Input.Press(app, window, "v", ["ctrl"], context); - try { await transaction.Consumed.Task.WaitAsync(TimeSpan.FromMilliseconds(readTimeoutMs), context.Cancellation); } - catch (TimeoutException) - { - throw new NativeFailure("PASTE_NOT_CONSUMED", "The target did not request clipboard data before pasteReadTimeoutMs; observe before deciding on further input"); - } - } - finally - { - var clock = Stopwatch.StartNew(); - while (!await context.Sta.Invoke(_ => transaction.Restore(), CancellationToken.None)) - { - if (clock.ElapsedMilliseconds >= context.Config.GraceMs) - NativeServer.Fatal("CLIPBOARD_CLEANUP", "Clipboard cleanup did not finish before the native grace deadline"); - await Task.Delay(context.Config.PollIntervalMs); - } - } + SetClipboard(control, text, format, maximumBytes); + return true; + }, context.Cancellation); + Input.Press(app, window, "v", ["ctrl"], context); } } diff --git a/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs b/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs index 6af36d042f..91d63e8b62 100644 --- a/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs +++ b/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs @@ -48,16 +48,18 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IA return (window, parameters.GetProperty("x").GetDouble(), parameters.GetProperty("y").GetDouble()); } - internal async Task Execute(NativeRequest request, ClientState state, NativeConfig config, CancellationToken cancellation) + internal async Task Execute(NativeRequest request, ClientState state, NativeConfig config, CancellationToken cancellation, + Action reportFailure) { + var context = new RequestContext(config, cancellation, mta, sta, reportFailure); if (request.Method == "screenshot") { - var context = new RequestContext(config, cancellation, mta, sta); AppState app; WindowState window; await queue.WaitAsync(cancellation); try { + context.Check(); DesktopSession.RequireInteractive(); app = state.App(String(request.Params, "appHandle")); window = Selected(app, request.Params, context); @@ -68,7 +70,6 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IA await queue.WaitAsync(cancellation); try { - var context = new RequestContext(config, cancellation, mta, sta); context.Check(); var parameters = request.Params; if (request.Method == "permissionStatus") return DesktopSession.Status(WindowCapture.IsSupported); @@ -148,7 +149,7 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IA { var target = Selected(app, parameters, context); await clipboard.Paste(app, target, String(parameters, "text"), OptionalString(parameters, "format") ?? "text", - parameters.GetProperty("maxClipboardBytes").GetInt32(), parameters.GetProperty("pasteReadTimeoutMs").GetInt32(), context); + parameters.GetProperty("maxClipboardBytes").GetInt32(), context); return ActionResult(foreground); } case "mouseMove": diff --git a/packages/experimental/cua-windows/native/entry/Dispatchers.cs b/packages/experimental/cua-windows/native/entry/Dispatchers.cs index 11ba63b5c1..4fec3bd8a0 100644 --- a/packages/experimental/cua-windows/native/entry/Dispatchers.cs +++ b/packages/experimental/cua-windows/native/entry/Dispatchers.cs @@ -78,16 +78,10 @@ internal sealed class MtaDispatcher : IAsyncDisposable internal sealed class ServiceControl : Forms.Control { - internal Func? ClipboardMessage; protected override Forms.CreateParams CreateParams { get { var value = base.CreateParams; value.Parent = -3; return value; } } - protected override void WndProc(ref Forms.Message message) - { - if (ClipboardMessage?.Invoke(message.Msg, message.WParam) == true) return; - base.WndProc(ref message); - } } internal sealed class StaDispatcher : IAsyncDisposable @@ -162,7 +156,8 @@ internal sealed class StaDispatcher : IAsyncDisposable } } -internal sealed class RequestContext(NativeConfig config, CancellationToken cancellation, MtaDispatcher mta, StaDispatcher sta) +internal sealed class RequestContext(NativeConfig config, CancellationToken cancellation, MtaDispatcher mta, StaDispatcher sta, + Action reportFailure) { internal NativeConfig Config { get; } = config; internal CancellationToken Cancellation { get; } = cancellation; @@ -174,12 +169,18 @@ internal sealed class RequestContext(NativeConfig config, CancellationToken canc { Check(); var completed = 0; + NativeFailure TimedOut() => new("AX_TIMEOUT", "A Windows accessibility call did not return within its configured deadline; its outcome is unknown"); using var timer = new Timer(_ => { - if (Interlocked.Exchange(ref completed, 1) == 0) - NativeServer.Fatal("AX_TIMEOUT", "A Windows accessibility call did not return within its configured deadline"); + if (Interlocked.CompareExchange(ref completed, 2, 0) == 0) reportFailure(TimedOut()); }, null, Config.AxTimeoutMs, Timeout.Infinite); - try { var result = call(); Cancellation.ThrowIfCancellationRequested(); return result; } - finally { Interlocked.Exchange(ref completed, 1); } + try + { + var result = call(); + if (Interlocked.CompareExchange(ref completed, 1, 0) == 2) throw TimedOut(); + Check(); + return result; + } + finally { Interlocked.CompareExchange(ref completed, 1, 0); } } } diff --git a/packages/experimental/cua-windows/native/entry/NativeExceptionLog.cs b/packages/experimental/cua-windows/native/entry/NativeExceptionLog.cs new file mode 100644 index 0000000000..c7c2326d91 --- /dev/null +++ b/packages/experimental/cua-windows/native/entry/NativeExceptionLog.cs @@ -0,0 +1,58 @@ +// Shared-server exception diagnostics remain readable beside the helper executable. +using System.Runtime.ExceptionServices; +using System.Text; + +namespace DeepSeek.Cua.Windows; + +internal sealed class NativeExceptionLog : IDisposable +{ + private readonly string path = Path.Combine(AppContext.BaseDirectory, "dsh-cua-windows.log"); + private readonly object gate = new(); + private bool writing; + private bool disposed; + + internal NativeExceptionLog() + { + AppDomain.CurrentDomain.FirstChanceException += FirstChance; + AppDomain.CurrentDomain.UnhandledException += Unhandled; + Write("Startup", $"Shared server PID {Environment.ProcessId}"); + } + + private void FirstChance(object? sender, FirstChanceExceptionEventArgs args) + => Write("FirstChanceException", args.Exception); + + private void Unhandled(object? sender, UnhandledExceptionEventArgs args) + => Write($"UnhandledException (terminating={args.IsTerminating})", args.ExceptionObject); + + private void Write(string kind, object value) + { + lock (gate) + { + // First-chance notifications also fire for failures while formatting or writing this log. + if (disposed || writing) return; + writing = true; + try + { + var entry = $"[{DateTimeOffset.UtcNow:O}] {kind} PID={Environment.ProcessId} Thread={Environment.CurrentManagedThreadId}{Environment.NewLine}{value.ToString()}{Environment.NewLine}"; + File.AppendAllText(path, entry, Encoding.UTF8); + } + catch (Exception error) + { + try { Console.Error.WriteLine($"NATIVE_LOG: Could not append to {path}: {error}"); } + catch (Exception diagnosticError) { _ = diagnosticError; /* Diagnostic failures must not escape an exception event handler. */ } + } + finally { writing = false; } + } + } + + public void Dispose() + { + lock (gate) + { + if (disposed) return; + disposed = true; + AppDomain.CurrentDomain.FirstChanceException -= FirstChance; + AppDomain.CurrentDomain.UnhandledException -= Unhandled; + } + } +} diff --git a/packages/experimental/cua-windows/native/entry/NativeServer.cs b/packages/experimental/cua-windows/native/entry/NativeServer.cs index 2821df97ea..9f973a8840 100644 --- a/packages/experimental/cua-windows/native/entry/NativeServer.cs +++ b/packages/experimental/cua-windows/native/entry/NativeServer.cs @@ -1,6 +1,5 @@ // The per-user service serves isolated Agent connections and Host leases on a private named pipe. using System.Collections.Concurrent; -using System.Diagnostics.CodeAnalysis; using System.IO.Pipes; using System.Security.Cryptography; using System.Text.Json; @@ -11,14 +10,6 @@ namespace DeepSeek.Cua.Windows; internal static class NativeServer { - [DoesNotReturn] - internal static void Fatal(string code, string message) - { - Console.Error.WriteLine($"{code}: {message}; native handles are no longer usable"); - Environment.Exit(70); - throw new InvalidOperationException("Process exit returned"); - } - internal static async Task Run(string instance, string expectedRuntime, int connectTimeoutMs, int graceMs) { if (!Guid.TryParseExact(instance, "N", out _)) throw new NativeFailure("INVALID_ARGUMENT", "A Host instance identifier is required"); @@ -35,14 +26,28 @@ internal static class NativeServer await mta.Invoke(() => true, lifetime.Token); await using var executor = new DesktopExecutor(mta, sta); var clients = new ConcurrentDictionary(); - NamedPipeServerStream? listener = NewPipe(pipeName); + NamedPipeServerStream? listener = null; var membership = new object(); var connections = 0; try { while (!lifetime.IsCancellationRequested) { - await listener.WaitForConnectionAsync(lifetime.Token); + try + { + listener ??= NewPipe(pipeName); + await listener.WaitForConnectionAsync(lifetime.Token); + } + catch (OperationCanceledException) when (lifetime.IsCancellationRequested) { break; } + catch (Exception error) + { + Report("NATIVE_LISTENER", error); + try { listener?.Dispose(); } + catch (Exception cleanupError) { Report("NATIVE_CONNECTION", cleanupError); } + listener = null; + await Task.Delay(graceMs, lifetime.Token); + continue; + } var connected = listener; lock (membership) { @@ -50,14 +55,14 @@ internal static class NativeServer connections++; lifetime.CancelAfter(Timeout.Infinite); } - listener = NewPipe(pipeName); + listener = null; var task = Serve(connected, executor, instance, runtime, connectTimeoutMs, lifetime.Token); clients.TryAdd(task, 0); _ = task.ContinueWith(completed => { clients.TryRemove(completed, out _); - if (completed.IsFaulted) { _ = completed.Exception; Console.Error.WriteLine("NATIVE_CONNECTION: Connection cleanup failed"); } - lock (membership) { if (--connections == 0) lifetime.Cancel(); } + if (completed.IsFaulted) Report("NATIVE_CONNECTION", completed.Exception!); + lock (membership) { if (--connections == 0) lifetime.CancelAfter(connectTimeoutMs); } }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } @@ -71,6 +76,15 @@ internal static class NativeServer } } + private static void Report(string code, Exception error) + { + try { Console.Error.WriteLine($"{code}: {error.GetType().Name}"); } + catch (Exception reportError) when (reportError is IOException or ObjectDisposedException) + { + _ = reportError; // A disconnected diagnostic stream must not stop the shared service. + } + } + private static NamedPipeServerStream NewPipe(string name) => new(name, PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly); @@ -122,7 +136,12 @@ internal static class NativeServer continue; } var request = NativeRequest.Parse(value); - if (active is { IsCompleted: false }) throw new NativeFailure("NATIVE_BUSY", "Native requests must be sequential"); + if (active is { IsCompleted: false }) + { + await Write(pipe, writer, Failure(request.Id, "NATIVE_BUSY", "The previous native operation has not stopped; do not send further input until it finishes"), + config.MaxResponseBytes, config.GraceMs, lifetime.Token); + continue; + } if (active is not null) await active; cancellation?.Dispose(); cancellation = CancellationTokenSource.CreateLinkedTokenSource(lifetime.Token); @@ -133,18 +152,19 @@ internal static class NativeServer } catch (Exception error) { - if (error is not (IOException or OperationCanceledException)) Console.Error.WriteLine($"NATIVE_CONNECTION: {error.GetType().Name}"); + if (error is not (IOException or OperationCanceledException)) Report("NATIVE_CONNECTION", error); } finally { lifetime.Cancel(); cancellation?.Cancel(); - if (active is not null) + try { - try { await active; } - catch (Exception error) { Console.Error.WriteLine($"NATIVE_CONNECTION: {error.GetType().Name}"); } + if (active is not null) await active; } - cancellation?.Dispose(); + catch (NativeFailure error) when (error.Code == "NATIVE_CLEANUP") { throw; } + catch (Exception error) { Report("NATIVE_CONNECTION", error); } + finally { cancellation?.Dispose(); } state.Clear(); if (closeRequested) await Write(pipe, writer, new { type = "closed" }, 8192, cleanupTimeoutMs, CancellationToken.None); @@ -155,33 +175,67 @@ internal static class NativeServer private static async Task Dispatch(NativeRequest request, ClientState state, DesktopExecutor executor, NativeConfig config, Stream pipe, SemaphoreSlim writer, CancellationToken cancellation, CancellationToken connection) { - var operation = executor.Execute(request, state, config, cancellation); - using var monitorStop = CancellationTokenSource.CreateLinkedTokenSource(cancellation); - var monitor = WatchOperation(operation, monitorStop.Token, config.GraceMs); - object response; - try { response = new { id = request.Id, result = await operation }; } - catch (OperationCanceledException) { response = Failure(request.Id, "NATIVE_CANCELLED", "Native operation cancelled; observe before deciding on further input"); } - catch (NativeFailure error) { response = Failure(request.Id, error.Code, error.Message); } - catch (NotImplementedException error) { response = Failure(request.Id, "NOT_IMPLEMENTED", error.Message); } - catch (ElementNotAvailableException) { response = Failure(request.Id, "STALE_SNAPSHOT", "An accessibility element disappeared; read fresh state"); } - catch (ElementNotEnabledException) { response = Failure(request.Id, "ELEMENT_DISABLED", "The selected control is disabled"); } - catch (UnauthorizedAccessException) { response = Failure(request.Id, "PERMISSION_DENIED", "Windows refused access to the selected application"); } - catch (Exception error) { response = Failure(request.Id, "NATIVE_OPERATION", $"Windows operation failed (0x{error.HResult:X8}); observe before retrying"); } - finally { monitorStop.Cancel(); await monitor; } - var bytes = JsonSerializer.SerializeToUtf8Bytes(response, WireJson.Options); - if (bytes.Length + 1 > config.MaxResponseBytes) response = Failure(request.Id, "NATIVE_RESPONSE_LIMIT", "Native response exceeded its configured byte limit"); - await Write(pipe, writer, response, config.MaxResponseBytes, config.GraceMs, connection); + var operationStop = CancellationTokenSource.CreateLinkedTokenSource(cancellation); + var failure = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + // A synchronous native call must not block the pipe reader or its timeout response. + var operation = Task.Run(() => executor.Execute(request, state, config, operationStop.Token, + error => { failure.TrySetResult(error); })); + try + { + object response; + try { response = new { id = request.Id, result = await WatchOperation(operation, failure.Task, operationStop.Token, config.GraceMs) }; } + catch (OperationCanceledException) { response = Failure(request.Id, "NATIVE_CANCELLED", "Native operation cancelled; observe before deciding on further input"); } + catch (NativeFailure error) + { + if (error.Code is "AX_TIMEOUT" or "NATIVE_CLEANUP") operationStop.Cancel(); + response = Failure(request.Id, error.Code, error.Message); + } + catch (NotImplementedException error) { response = Failure(request.Id, "NOT_IMPLEMENTED", error.Message); } + catch (ElementNotAvailableException) { response = Failure(request.Id, "STALE_SNAPSHOT", "An accessibility element disappeared; read fresh state"); } + catch (ElementNotEnabledException) { response = Failure(request.Id, "ELEMENT_DISABLED", "The selected control is disabled"); } + catch (UnauthorizedAccessException) { response = Failure(request.Id, "PERMISSION_DENIED", "Windows refused access to the selected application"); } + catch (Exception error) { response = Failure(request.Id, "NATIVE_OPERATION", $"Windows operation failed (0x{error.HResult:X8}); observe before retrying"); } + var bytes = JsonSerializer.SerializeToUtf8Bytes(response, WireJson.Options); + if (bytes.Length + 1 > config.MaxResponseBytes) response = Failure(request.Id, "NATIVE_RESPONSE_LIMIT", "Native response exceeded its configured byte limit"); + await Write(pipe, writer, response, config.MaxResponseBytes, config.GraceMs, connection); + } + finally + { + try { await operation.WaitAsync(TimeSpan.FromMilliseconds(config.GraceMs)); } + catch (TimeoutException) when (!operation.IsCompleted) + { + throw new NativeFailure("NATIVE_CLEANUP", "The native operation did not stop before the cleanup deadline; its outcome is unknown"); + } + catch (Exception error) { _ = error; /* The operation failure has already been reported to the caller. */ } + finally + { + // A late native call still owns its cancellation token; observe its eventual failure. + _ = operation.ContinueWith(completed => + { + _ = completed.Exception; + operationStop.Dispose(); + }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); + } + } } private static object Failure(string id, string code, string message) => new { id, error = new { code, message } }; - private static async Task WatchOperation(Task operation, CancellationToken cancellation, int graceMs) + private static async Task WatchOperation(Task operation, Task failure, + CancellationToken cancellation, int graceMs) { - await Task.WhenAny(operation, Task.Delay(Timeout.Infinite, cancellation)); - if (operation.IsCompleted) return; - try { await operation.WaitAsync(TimeSpan.FromMilliseconds(graceMs)); } - catch (TimeoutException) { Fatal("NATIVE_CLEANUP", "A cancelled desktop operation did not stop before the grace deadline"); } - catch (Exception error) when (operation.IsCompleted) { _ = error; /* Dispatch owns the operation result. */ } + var completed = Task.WhenAny(operation, failure); + try { await completed.WaitAsync(cancellation); } + catch (OperationCanceledException) when (cancellation.IsCancellationRequested) + { + try { await completed.WaitAsync(TimeSpan.FromMilliseconds(graceMs)); } + catch (TimeoutException) + { + throw new NativeFailure("NATIVE_CLEANUP", "A cancelled desktop operation did not stop before the grace deadline; its outcome is unknown"); + } + } + if (failure.IsCompleted) throw await failure; + return await operation; } private static async Task Write(Stream pipe, SemaphoreSlim writer, object value, int maximum, int timeoutMs, CancellationToken cancellation) diff --git a/packages/experimental/cua-windows/native/entry/Program.cs b/packages/experimental/cua-windows/native/entry/Program.cs index 9c1577cfab..7809774609 100644 --- a/packages/experimental/cua-windows/native/entry/Program.cs +++ b/packages/experimental/cua-windows/native/entry/Program.cs @@ -3,6 +3,8 @@ using System.CommandLine; using DeepSeek.Cua.Protocol; using DeepSeek.Cua.Windows; +using var exceptionLog = args.Contains("--shared-server", StringComparer.Ordinal) ? new NativeExceptionLog() : null; + try { if (!OperatingSystem.IsWindowsVersionAtLeast(10, 0, 19041)) diff --git a/packages/experimental/cua-windows/src/guidance.ts b/packages/experimental/cua-windows/src/guidance.ts index 3561ecdf50..166581fae9 100644 --- a/packages/experimental/cua-windows/src/guidance.ts +++ b/packages/experimental/cua-windows/src/guidance.ts @@ -10,6 +10,7 @@ const methodDetails = new Map([ ['getAccessibilityTree', 'Set the node count or depth for one read. Windows accepts maxElements from 1 to 10000 and maxDepth from 1 to 100. Omitted limits use the provider settings; maxDepth=1 includes only the window root. If the tree is truncated, select a narrower window or increase the relevant limit. includeMenus expands menu contents. Element IDs are UI Automation RuntimeIds formatted as slash-separated integer strings, such as "12/345/6". Pass the complete string unchanged as elementId. Each element lists all its supported patterns, not action names. Disabled is an observed state, not a prohibition on attempting an operation.'], ['listActions', 'Actions use case-sensitive Pattern.Action names, such as "Invoke.Invoke", "Toggle.Toggle", and "ExpandCollapse.Expand". Each pattern has a known set of native UI Automation operations. One pattern can expose multiple actions. Use a known operation of an advertised pattern directly; call listActions when you need to confirm the exposed operations. Query methods are not exposed through performAction.'], ['invoke', 'The provider chooses default action for well-known patterns. A failed operation is not retried through another pattern or simulated input.'], + ['paste', 'Write text or HTML to the system clipboard and send Ctrl+V to the target window. The new clipboard contents remain in place. Return dispatch evidence, not confirmation that the target applied the content; observe the target before continuing. A failure is reported without substituting typeText.'], ['performAction', 'Use the exact Pattern.Action name. Omit argument or pass null for a parameter-free operation. Pass a single parameter as its direct JSON value; pass multiple parameters as an object using their native names. Enum values use their exact names as strings. Examples: await win.performAction(id, "Value.SetValue", "hello"); await win.performAction(id, "Window.SetWindowVisualState", "Normal"); await win.performAction(id, "Transform.Resize", { width: 800, height: 600 }).'], ]) @@ -19,6 +20,6 @@ export const GUIDANCE = `${PLATFORM_GUIDANCE} ${COMMON_GUIDANCE.replace(/^- ([\w.]+)\(.*$/gm, (entry, method: string) => { const detail = methodDetails.get(method) if (!detail) return entry - if (method === 'getAccessibilityTree') return `${entry.replace(/ — .*$/, '')} — ${detail}` + if (method === 'getAccessibilityTree' || method === 'paste') return `${entry.replace(/ — .*$/, '')} — ${detail}` return `${entry} ${detail}` })}` diff --git a/packages/experimental/cua-windows/src/index.ts b/packages/experimental/cua-windows/src/index.ts index 3be20956f5..875a383fca 100644 --- a/packages/experimental/cua-windows/src/index.ts +++ b/packages/experimental/cua-windows/src/index.ts @@ -39,7 +39,13 @@ export interface Config extends CuaConfig { /** Validate platform configuration before locating and launching the helper. */ export const Config = Schema.object({ ...CuaConfigFields, - connectTimeoutMs: CuaConfigFields.connectTimeoutMs.default(30_000), + timeoutMs: CuaConfigFields.timeoutMs.default(60_000), + connectTimeoutMs: CuaConfigFields.connectTimeoutMs.default(600_000), + screenshotTimeoutMs: CuaConfigFields.screenshotTimeoutMs.default(60_000), + axTimeoutMs: CuaConfigFields.axTimeoutMs.default(60_000), + // Currently unused on Windows: paste does not wait for clipboard consumption. + pasteReadTimeoutMs: CuaConfigFields.pasteReadTimeoutMs.default(60_000), + graceMs: CuaConfigFields.graceMs.default(60_000), windowsPowerShellPath: Schema.string().min(1).default('powershell.exe'), pollIntervalMs: Schema.number().step(1).min(1).max(2 ** 31 - 1).default(25), textEventIntervalMs: CuaConfigFields.textEventIntervalMs.default(0), @@ -60,7 +66,7 @@ export async function apply(ctx: Context, config: Config): Promise { const controller = new AbortController() const prepare = async () => { const wsl = host === 'wsl' ? await prepareWsl({ subprocess: ctx.subprocess, signal: controller.signal, - timeoutMs: config.connectTimeoutMs, graceMs: config.graceMs, powershellPath: config.windowsPowerShellPath }) : undefined + timeoutMs: config.timeoutMs, graceMs: config.graceMs, powershellPath: config.windowsPowerShellPath }) : undefined let helperPath = config.helperPath if (helperPath === undefined) { const architecture = wsl?.architecture ?? nativeHostArchitecture(process.platform, process.arch) @@ -79,9 +85,7 @@ export async function apply(ctx: Context, config: Config): Promise { }, 'cua-windows.native-preparation') const helperPath = await prepared controller.signal.throwIfAborted() - // Temporary native-runtime configuration. - const launchWaitMs = 1000 - const runtime = new WindowsNativeRuntime(ctx, config.pollIntervalMs, launchWaitMs, host === 'wsl' ? 'stdio' : 'pipe') + const runtime = new WindowsNativeRuntime(ctx, config.pollIntervalMs, config.timeoutMs, host === 'wsl' ? 'stdio' : 'pipe') ctx.effect(() => () => runtime.dispose(), 'cua-windows.native-runtime') installCua(ctx, config, { helperPath, createChannel: (_owner, native) => runtime.connect(native), getGuidance: () => GUIDANCE, capabilities: CAPABILITIES, diff --git a/packages/experimental/cua-windows/src/native-runtime.ts b/packages/experimental/cua-windows/src/native-runtime.ts index b5be44ac70..ca991d5fcd 100644 --- a/packages/experimental/cua-windows/src/native-runtime.ts +++ b/packages/experimental/cua-windows/src/native-runtime.ts @@ -1,8 +1,9 @@ /** Host-owned connector and independently disposable Agent connections to a shared Windows helper. */ import { createHash, randomUUID } from 'node:crypto' -import { createReadStream } from 'node:fs' +import { closeSync, createReadStream, fstatSync, openSync, readSync } from 'node:fs' import { addAbortListener } from 'node:events' import { realpath } from 'node:fs/promises' +import { dirname, join } from 'node:path' import { PassThrough, Writable, type Readable, type Duplex } from 'node:stream' import assert from 'node:assert/strict' import type { SubprocessHandle, SubprocessRuntime } from '@deepseek-ai/dsh-subprocess' @@ -20,6 +21,43 @@ type Owner = { subprocess: Pick } function failure(error: unknown): Error { return error instanceof Error ? error : new Error(String(error)) } +const windowsLogAttached = Symbol('windows-native-log-attached') + +/* v8 ignore start -- Temporary VM diagnostics; current transport fixtures do not exercise real log tails. */ +function readWindowsLogTail(logPath: string): string { + const file = openSync(logPath, 'r') + try { + const size = fstatSync(file).size + const start = Math.max(0, size - 64 * 1024) + const buffer = Buffer.alloc(size - start) + let length = 0 + while (length < buffer.length) { + const count = readSync(file, buffer, length, buffer.length - length, start + length) + if (count === 0) break + length += count + } + let offset = 0 + // A tail may start inside a UTF-8 character. + if (start > 0) while (offset < length && (buffer.readUInt8(offset) & 0xc0) === 0x80) offset++ + const contents = buffer.subarray(offset, length).toString('utf8') + return start > 0 ? `[Earlier log content omitted; showing the tail.]\n${contents}` : contents + } finally { closeSync(file) } +} +/* v8 ignore stop */ + +function withWindowsLog(error: unknown, logPath: string): NativeError { + const original = failure(error) + const cause = original instanceof NativeError ? original : new NativeError('NATIVE_IO', original.message, { cause: original }) + if (Object.hasOwn(cause, windowsLogAttached)) return cause + let diagnostics: string + // The shared client can reject immediately when a stream error or write callback fires. + try { diagnostics = readWindowsLogTail(logPath) } + catch (logError) { diagnostics = `Could not read the exception log: ${failure(logError).message}` } + cause.message += `\nWindows CUA exception log (${logPath}):\n${diagnostics}` + Object.defineProperty(cause, windowsLogAttached, { value: true }) + return cause +} + async function interruptible(operation: Promise, signal: AbortSignal): Promise { const cancelled = Promise.withResolvers() using _listener = addAbortListener(signal, () => { cancelled.reject(signal.reason) }) @@ -55,6 +93,7 @@ function firstFrame(stream: Readable, signal: AbortSignal): Promise<{ value: unk } class WindowsHelper { + logPath: string readonly ready: Promise> readonly done: Promise readonly sockets = new Set() @@ -66,6 +105,7 @@ class WindowsHelper { private error: Error | undefined constructor(private readonly owner: Owner, private readonly config: NativeClientConfig) { + this.logPath = join(dirname(config.helperPath), 'dsh-cua-windows.log') this.ready = this.readiness.promise void this.ready.catch(() => {}) this.done = this.run() @@ -90,6 +130,7 @@ class WindowsHelper { }, this.config.connectTimeoutMs) try { const helperPath = await realpath(this.config.helperPath) + this.logPath = join(dirname(helperPath), 'dsh-cua-windows.log') const digest = createHash('sha256') for await (const chunk of createReadStream(helperPath, { signal: this.startup.signal })) digest.update(chunk as Buffer) const runtimeKey = digest.digest('hex') @@ -134,7 +175,8 @@ class WindowsHelper { finally { clearTimeout(startupTimer) this.phase = 'closing' - const error = this.error ?? new NativeError('NATIVE_CLOSED', 'Windows helper closed; select applications again') + const error = this.error ? withWindowsLog(this.error, this.logPath) + : new NativeError('NATIVE_CLOSED', 'Windows helper closed; select applications again') for (const socket of this.sockets) socket.destroy(error) const handle = this.handle try { @@ -146,7 +188,8 @@ class WindowsHelper { if (!await handle.waitForExit()) throw new NativeError('NATIVE_CLEANUP', 'Windows helper process range did not exit') } finally { clearTimeout(timer) } } - } finally { + } catch (cleanupError) { throw withWindowsLog(cleanupError, this.logPath) } + finally { clearTimeout(this.stopTimer) this.phase = 'closed' this.readiness.reject(error) @@ -156,6 +199,7 @@ class WindowsHelper { } class WindowsChannel implements NativeChannel { + private logPath: string readonly stdout = new PassThrough() readonly stdin: Writable readonly done: Promise @@ -168,11 +212,16 @@ class WindowsChannel implements NativeChannel { constructor(helper: Promise, config: NativeClientConfig, pollIntervalMs: number, launchWaitMs: number, owner: Owner, transport: WindowsTransport) { + this.logPath = join(dirname(config.helperPath), 'dsh-cua-windows.log') this.stdin = new Writable({ write: (chunk: Buffer, _encoding, callback) => { void this.readiness.promise.then((socket) => { if (this.closing) { callback(new NativeError('NATIVE_CLOSED', 'Native connection is closing')); return } - socket.write(chunk, callback) + /* v8 ignore start -- Temporary VM diagnostics; current transport fixtures do not inject socket write failures. */ + try { + socket.write(chunk, (error) => { callback(error ? withWindowsLog(error, this.logPath) : error) }) + } catch (error) { callback(withWindowsLog(error, this.logPath)) } + /* v8 ignore stop */ }, callback) }, final: (callback) => { this.close(); callback() }, @@ -208,6 +257,7 @@ class WindowsChannel implements NativeChannel { try { helper = await interruptible(helperPromise, this.startup.signal) const ready = await interruptible(helper.ready, this.startup.signal) + this.logPath = helper.logPath this.startup.signal.throwIfAborted() connection = connectWindowsPipe(owner.subprocess, config, ready.endpoint, ready.runtimeKey, transport) const socket = connection.stream @@ -278,23 +328,25 @@ class WindowsChannel implements NativeChannel { try { await closed } finally { this.startup.signal.removeEventListener('abort', close) } } finally { this.startup.signal.removeEventListener('abort', abort) } } catch (error) { + if (helper) this.logPath = helper.logPath const cause = failure(error) - if (!this.closing || admitted) caught = cause - this.readiness.reject(cause) + if (!this.closing || admitted) caught = withWindowsLog(cause, this.logPath) + this.readiness.reject(caught ?? cause) } finally { + if (helper) this.logPath = helper.logPath clearTimeout(timer) clearTimeout(this.closeTimer) this.closing = true this.socket?.destroy() if (closed) { - try { await closed } catch (error) { if (admitted) caught ??= failure(error) } + try { await closed } catch (error) { if (admitted) caught ??= withWindowsLog(error, this.logPath) } } if (this.socket) helper?.sockets.delete(this.socket) let cleanupError: Error | undefined - try { await connection?.dispose() } catch (error) { cleanupError = failure(error); caught ??= cleanupError } + try { await connection?.dispose() } catch (error) { cleanupError = withWindowsLog(error, this.logPath); caught ??= cleanupError } if (admitted && !observation.acknowledged) { - cleanupError = new NativeError('NATIVE_CLEANUP', 'Windows pipe ended without native cleanup acknowledgement') + cleanupError = withWindowsLog(new NativeError('NATIVE_CLEANUP', 'Windows pipe ended without native cleanup acknowledgement'), this.logPath) } this.stdin.destroy() if (caught) this.stdout.destroy(caught) diff --git a/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts index dcee6fa104..4109de1af6 100644 --- a/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts @@ -40,7 +40,7 @@ it('uses an absolute fixture without compiling and disposes the Host runtime', a const ctx = owner(), config = Config({ helperPath: resolve('fixture.exe'), pollIntervalMs: 13 }) await apply(ctx, config) expect(native.prepare).not.toHaveBeenCalled() - expect(native.construct).toHaveBeenCalledWith(ctx, 13, 1000, 'pipe') + expect(native.construct).toHaveBeenCalledWith(ctx, 13, 60_000, 'pipe') const backend = native.install.mock.calls[0]![2] expect(backend.helperPath).toBe(config.helperPath) expect(native.architecture).not.toHaveBeenCalled() @@ -106,7 +106,7 @@ it('prepares the Windows architecture and stdio transport for WSL', async () => await apply(ctx, Config({})) expect(native.prepare.mock.calls[0]![0].architecture).toBe('arm64') expect(native.architecture).not.toHaveBeenCalled() - expect(native.construct).toHaveBeenCalledWith(ctx, 25, 1000, 'stdio') + expect(native.construct).toHaveBeenCalledWith(ctx, 25, 60_000, 'stdio') expect(native.install.mock.calls[0]![2].helperPath).toBe('/mnt/c/cache/helper.exe') }) diff --git a/packages/experimental/cua/src/index.ts b/packages/experimental/cua/src/index.ts index 036089bcc0..c854eff7ba 100644 --- a/packages/experimental/cua/src/index.ts +++ b/packages/experimental/cua/src/index.ts @@ -72,9 +72,9 @@ export interface CuaConfig { maxResponseBytes: number /** Maximum installed application matches returned for one discovery query. */ maxAppMatches: number - /** Maximum bytes preserved from the system clipboard during one paste. */ + /** Provider-specific clipboard byte limit for paste. */ maxClipboardBytes: number - /** Maximum wait for clipboard data consumption after the Paste command returns. */ + /** Provider-specific paste wait budget in milliseconds. */ pasteReadTimeoutMs: number /** Maximum UTF-8 bytes admitted for one helper request frame. */ maxRequestBytes: number diff --git a/packages/experimental/cua/src/types.ts b/packages/experimental/cua/src/types.ts index b38229c220..29a3e21d00 100644 --- a/packages/experimental/cua/src/types.ts +++ b/packages/experimental/cua/src/types.ts @@ -142,9 +142,8 @@ export interface CuaSurface { /** * Paste text or HTML at the target's current input focus. * Rejects when the provider does not support keyboard input at this scope. - * PASTE_NOT_CONSUMED means no clipboard read within the configured deadline after dispatch; inspect before retrying. * @param text - Clipboard contents in the selected format; defaults to plain text. - * @param options - Clipboard format. Original contents are restored unless another writer changes them. + * @param options - Clipboard format. * @returns Dispatch evidence; unsupported Paste commands fail without typing fallback. */ paste(text: string, options?: CuaPasteOptions): Promise diff --git a/packages/experimental/liveshare/package.json b/packages/experimental/liveshare/package.json index 6a54cb1dd0..ad4c49b727 100644 --- a/packages/experimental/liveshare/package.json +++ b/packages/experimental/liveshare/package.json @@ -93,6 +93,7 @@ "@deepseek-ai/dsh-api-workspace-files": "workspace:*", "@deepseek-ai/dsh-client-connection": "workspace:*", "@deepseek-ai/dsh-client-file-upload": "workspace:*", + "@deepseek-ai/dsh-client-hmr": "workspace:*", "@deepseek-ai/dsh-client-locale": "workspace:*", "@deepseek-ai/dsh-client-modules": "workspace:*", "@deepseek-ai/dsh-client-resources": "workspace:*", diff --git a/packages/experimental/liveshare/src/client/endpoint-classification.ts b/packages/experimental/liveshare/src/client/endpoint-classification.ts index c880912024..869f5090ef 100644 --- a/packages/experimental/liveshare/src/client/endpoint-classification.ts +++ b/packages/experimental/liveshare/src/client/endpoint-classification.ts @@ -9,6 +9,7 @@ import type {} from '@deepseek-ai/dsh-api-remotes/client' import type {} from '@deepseek-ai/dsh-api-remote-access/remote' import type { RemoteEndpoint } from '@deepseek-ai/dsh-api-remote-access/client' +import type {} from '@deepseek-ai/dsh-client-hmr/remote' import type {} from '@deepseek-ai/dsh-cua/remote' import type {} from '@deepseek-ai/dsh-experimental-api-speech-to-text/remote' import type {} from '@deepseek-ai/dsh-experimental-claude-code-mods/remote' diff --git a/packages/experimental/liveshare/src/endpoint-classification.ts b/packages/experimental/liveshare/src/endpoint-classification.ts index 7d5a6129cf..6a1f62f889 100644 --- a/packages/experimental/liveshare/src/endpoint-classification.ts +++ b/packages/experimental/liveshare/src/endpoint-classification.ts @@ -42,6 +42,7 @@ export const VIEWER_ENDPOINT_CLASSES = { 'llm/listProviders': 'reader-global-read', // the page lists providers 'session/canOpenWorkspacePath': 'reader-global-read', // the page asks whether a path can be opened 'session/modelCatalog': 'reader-global-read', // the page reads the model catalog + 'pluginEvents/follow': 'reader-global-read', // the page follows the plugin graph; the Host sends a non-owner schema defaults, never configured values 'productAnalytics/enabled': 'reader-global-read', // the page asks whether this host accepts analytics 'productAnalytics/report': 'reader-global-read', // the page reports its own product events 'productAnalytics/watchPolicy': 'reader-global-read', // the page follows the analytics policy diff --git a/packages/experimental/liveshare/src/host/viewer-access-policy.ts b/packages/experimental/liveshare/src/host/viewer-access-policy.ts index c9fbac8422..6d4cc510bf 100644 --- a/packages/experimental/liveshare/src/host/viewer-access-policy.ts +++ b/packages/experimental/liveshare/src/host/viewer-access-policy.ts @@ -107,6 +107,7 @@ const VIEWER_GLOBAL_ROLE: RemoteAccessRole<'global'> = { 'session/control', 'session/list', 'session/modelCatalog', + 'pluginEvents/follow', 'productAnalytics/enabled', 'productAnalytics/report', 'productAnalytics/watchPolicy', diff --git a/packages/experimental/liveshare/tests/viewer-access-policy.spec.ts b/packages/experimental/liveshare/tests/viewer-access-policy.spec.ts index 504fc19e27..0e7a07fd73 100644 --- a/packages/experimental/liveshare/tests/viewer-access-policy.spec.ts +++ b/packages/experimental/liveshare/tests/viewer-access-policy.spec.ts @@ -43,7 +43,7 @@ const CALL = { request: {} } */ const GLOBAL_ACTIONS = [ 'commands/list', 'llm/listConfigurableProviders', 'llm/listProviders', 'session/canOpenWorkspacePath', - 'session/control', 'session/list', 'session/modelCatalog', + 'session/control', 'session/list', 'session/modelCatalog', 'pluginEvents/follow', 'productAnalytics/enabled', 'productAnalytics/report', 'productAnalytics/watchPolicy', 'speech/cancelPreparation', 'speech/catalog', 'speech/follow', 'speech/prepare', 'speech/transcribe', 'workspace/follow', diff --git a/packages/experimental/liveshare/tests/viewer-fixture.client.ts b/packages/experimental/liveshare/tests/viewer-fixture.client.ts index 775dabbd95..d08c678980 100644 --- a/packages/experimental/liveshare/tests/viewer-fixture.client.ts +++ b/packages/experimental/liveshare/tests/viewer-fixture.client.ts @@ -440,7 +440,8 @@ const FIXTURE_GLOBAL_READS = [ 'commands/list', 'llm/listConfigurableProviders', 'llm/listProviders', 'productAnalytics/enabled', 'productAnalytics/report', 'productAnalytics/watchPolicy', 'speech/cancelPreparation', 'speech/catalog', 'speech/follow', 'speech/prepare', 'speech/transcribe', - 'session/canOpenWorkspacePath', 'session/control', 'session/list', 'session/modelCatalog', 'workspace/follow', + 'session/canOpenWorkspacePath', 'session/control', 'session/list', 'session/modelCatalog', 'pluginEvents/follow', + 'workspace/follow', ] as const type FixtureControlFrame = diff --git a/packages/experimental/timeline/tests/panel.client.spec.tsx b/packages/experimental/timeline/tests/panel.client.spec.tsx index 119f00b44c..4ec0d4c0f7 100644 --- a/packages/experimental/timeline/tests/panel.client.spec.tsx +++ b/packages/experimental/timeline/tests/panel.client.spec.tsx @@ -632,10 +632,13 @@ describe('the Task Tree and Timeline tabs', () => { const titles = [...container.querySelectorAll('.timeline-annotation-target')].map( node => node.textContent, ) + // The panel renders dates with the locale the fixture supplies; format the expected text with + // the same locale instead of the host ICU locale, which differs across CI runners. + const shown = (at: number) => new Date(at).toLocaleString('en') expect(titles).toEqual([ 'Task Tree: Review release', 'Review release · Verify behavior', - `Level 1 · 1m: ${new Date(report.start).toLocaleString()} – ${new Date(report.end).toLocaleString()}`, + `Level 1 · 1m: ${shown(report.start)} – ${shown(report.end)}`, ]) expect(screen.getByText(en.controlWaiting)).toBeTruthy() expect(screen.getByText('The saved result is verified.')).toBeTruthy() diff --git a/packages/experimental/timeline/tests/reports.spec.ts b/packages/experimental/timeline/tests/reports.spec.ts index f7dd8bbfcd..d8a68e52fa 100644 --- a/packages/experimental/timeline/tests/reports.spec.ts +++ b/packages/experimental/timeline/tests/reports.spec.ts @@ -659,7 +659,7 @@ describe('background summaries through a real agent loop', () => { it('hard-codes no activity without calling the model, including later empty intervals', async () => { const adapter = new Adapter() adapter.calls = 0 - const f = await running({}, adapter) + const f = await running({ language: 'en' }, adapter) await vi.advanceTimersByTimeAsync(60000) await f.waitRecords('plugin:timeline/report') expect(f.reports()[0]).toMatchObject({ diff --git a/packages/experimental/timeline/tests/settings.client.spec.tsx b/packages/experimental/timeline/tests/settings.client.spec.tsx index 425273a92c..715b7f19d1 100644 --- a/packages/experimental/timeline/tests/settings.client.spec.tsx +++ b/packages/experimental/timeline/tests/settings.client.spec.tsx @@ -154,7 +154,9 @@ describe('the Timeline Settings section', () => { expect(within(section).getByRole('heading', { level: 2 }).textContent).toBe('Task writing guidance') expect(section.previousElementSibling).toBe(screen.getByRole('region', { name: 'Timed reports' })) expect(taskPrompt.maxLength).toBe(32768) - const count = (length: number) => `${length.toLocaleString()} / ${taskPrompt.maxLength.toLocaleString()}` + // The counter renders with the locale the fixture supplies; do not follow the host ICU locale. + const count = (length: number) => + `${length.toLocaleString('en')} / ${taskPrompt.maxLength.toLocaleString('en')}` const prompt = 'Explain results and remaining evidence in task details.' expect(within(section).getByText(count(value.taskPrompt.length))).toBeTruthy() fireEvent.change(taskPrompt, { target: { value: prompt } }) diff --git a/packages/experimental/timeline/tests/tools.spec.ts b/packages/experimental/timeline/tests/tools.spec.ts index 0f7bf4d099..7b7f766ec9 100644 --- a/packages/experimental/timeline/tests/tools.spec.ts +++ b/packages/experimental/timeline/tests/tools.spec.ts @@ -504,7 +504,7 @@ describe('agent tools in the production loop', () => { } }) it('updates the fixed language rule in the next prompt assembly', async () => { - const f = await setup() + const f = await setup({ language: 'en' }) try { const prompt = () => f.ctx.systemPrompt.assemble({ scope: f.agent }) expect( diff --git a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts index be9916a03f..b5f37426fb 100644 --- a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts @@ -125,7 +125,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'contextMenu.content\', () => ctx.slots.register(\n { name: \'contextMenu.content\', key: \'\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-context-menu/src/client/index.ts:42', + source: 'packages/client/ui-context-menu/src/client/index.ts:43', }, { key: 'contextMenu.icon', @@ -171,7 +171,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'contextMenu.icon\', () => ctx.slots.register(\n { name: \'contextMenu.icon\', key: \'\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-context-menu/src/client/index.ts:40', + source: 'packages/client/ui-context-menu/src/client/index.ts:41', }, { key: 'conversation.approval.detail', @@ -3956,7 +3956,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'settings.action\', () => ctx.slots.register(\n { name: \'settings.action\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-settings/src/client/contract/slots.ts:54', + source: 'packages/client/ui-settings/src/client/contract/slots.ts:60', }, { key: 'settings.close', @@ -3990,7 +3990,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'settings.close\', () => ctx.slots.register(\n { name: \'settings.close\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-settings/src/client/contract/slots.ts:60', + source: 'packages/client/ui-settings/src/client/contract/slots.ts:66', }, { key: 'settings.general.item', @@ -4055,7 +4055,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'settings.general.item\', () => ctx.slots.register(\n { name: \'settings.general.item\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-settings/src/client/contract/slots.ts:109', + source: 'packages/client/ui-settings/src/client/contract/slots.ts:115', }, { key: 'settings.header', @@ -4089,7 +4089,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'settings.header\', () => ctx.slots.register(\n { name: \'settings.header\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-settings/src/client/contract/slots.ts:48', + source: 'packages/client/ui-settings/src/client/contract/slots.ts:54', }, { key: 'settings.launcher', @@ -4129,11 +4129,11 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ key: 'settings.launcher.notifications', kind: 'single', scope: 'root', - summary: 'Notifications anchored at the account menu; the contribution owns its markup and lifecycle.', - doc: 'Notifications anchored at the account menu; the contribution owns its markup and lifecycle.', + summary: 'Notifications in the row above the account launcher; the contribution owns its markup and lifecycle.', + doc: 'Notifications in the row above the account launcher; the contribution owns its markup and lifecycle.', registerOptions: [], ownerProps: [ - '/** Account-menu presentation facts supplied to its notification extension. */\nexport interface AccountNotificationsOwnerProps {\n /** Whether the account menu can display notifications outside onboarding. */\n active: boolean\n /** Open the account section in the existing settings shell. */\n openAccount: () => void\n}', + '/** Account presentation facts supplied to its notification extension. */\nexport interface AccountNotificationsOwnerProps {\n /** Whether a signed-in account can display notifications outside onboarding. */\n active: boolean\n /** Open the account section in the existing settings shell. */\n openAccount: () => void\n}', ], ownerPropsReferences: [], standardProps: [ @@ -4151,7 +4151,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ keyDomain: '', hookContext: '', slotInject: '', - declaredBy: 'an entry in \'settings.launcher\' (client-ui-settings-account), so it exists while that entry is mounted', + declaredBy: 'an entry in \'settings.notice\' (client-ui-settings-account), so it exists while that entry is mounted', occupants: [ 'client-ui-account-notifications AccountNotifications', ], @@ -4283,6 +4283,40 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'settings.models.sign-in\', () => ctx.slots.register(\n { name: \'settings.models.sign-in\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', source: 'packages/client/ui-settings-models/src/client/slot-contract.ts:35', }, + { + key: 'settings.notice', + kind: 'single', + scope: 'root', + summary: 'Optional content anchored above the launcher row at the launcher row\'s full width.', + doc: 'Optional content anchored above the launcher row at the launcher row\'s\nfull width. The row takes no height, so the content floats over the\nsidebar list; the shell hides it in the rail without unmounting it.', + registerOptions: [], + ownerProps: [ + '/** Settings navigation for the row above the launcher row. */\nexport interface SettingsNoticeOwnerProps {\n /** @param sectionId - section to open; absent uses the shell\'s default section. */\n openSettings: (sectionId?: string) => void\n}', + ], + ownerPropsReferences: [], + standardProps: [ + 'useRemoteAccess: (action: RemoteEndpoint) => boolean', + 'useResource: UseResource', + 'useContextMenu: UseContextMenu', + 'useWorkspaces: SnapshotSelectorHook', + 'usePanelInfo: UsePanelInfo', + 'useSessionStatus: UseSessionStatus', + 'useSessions: UseSessions', + 'useSessionRetainInfo: UseSessionRetainInfo', + 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', + 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', + ], + keyDomain: '', + hookContext: '', + slotInject: '', + declaredBy: 'an entry in \'sidebar.settings\' (client-ui-settings-general), so it exists while that entry is mounted', + occupants: [ + 'client-ui-settings-account AccountNotices', + ], + replaceRisk: 'shadows-shipped-ui', + example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'settings.notice\', () => ctx.slots.register(\n { name: \'settings.notice\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', + source: 'packages/client/ui-settings/src/client/contract/slots.ts:38', + }, { key: 'settings.onboarding', kind: 'list', @@ -4335,7 +4369,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'settings.onboarding\', () => ctx.slots.register(\n { name: \'settings.onboarding\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-settings/src/client/contract/slots.ts:94', + source: 'packages/client/ui-settings/src/client/contract/slots.ts:100', }, { key: 'settings.section', @@ -4392,7 +4426,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'settings.section\', () => ctx.slots.register(\n { name: \'settings.section\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-settings/src/client/contract/slots.ts:75', + source: 'packages/client/ui-settings/src/client/contract/slots.ts:81', }, { key: 'settings.section.icon', @@ -4443,7 +4477,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ occupants: [], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'settings.section.icon\', () => ctx.slots.register(\n { name: \'settings.section.icon\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-settings/src/client/contract/slots.ts:83', + source: 'packages/client/ui-settings/src/client/contract/slots.ts:89', }, { key: 'settings.trigger', @@ -4477,7 +4511,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'settings.trigger\', () => ctx.slots.register(\n { name: \'settings.trigger\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-settings/src/client/contract/slots.ts:42', + source: 'packages/client/ui-settings/src/client/contract/slots.ts:48', }, { key: 'shell.bottom', diff --git a/packages/extensions/tool-cordis/README.i18n.yaml b/packages/extensions/tool-cordis/README.i18n.yaml index 22ee9d77e5..f53652026b 100644 --- a/packages/extensions/tool-cordis/README.i18n.yaml +++ b/packages/extensions/tool-cordis/README.i18n.yaml @@ -15,11 +15,11 @@ en: d152484eb41ac6b4 zh: 3a2f21ff0dc3420d /deepseek-ai-dsh-tool-cordis/use-this-package: - en: 3dfbc3694e112e7f - zh: c8e32e111455f24a + en: 6a03f434a773ec43 + zh: d2d7c48df1a29e0b /deepseek-ai-dsh-tool-cordis/understand-the-implementation: - en: 8e9ef81505922995 - zh: 2909fe682cf66f7c + en: c4d39015cdf9a6b6 + zh: 9ca8a882bdea7529 /deepseek-ai-dsh-tool-cordis/further-exploration: en: 1863373f02bcc196 zh: 3efdbf5569411562 @@ -30,8 +30,8 @@ en: 72ffb7cae674c31a zh: 85674f298a78592a /deepseek-ai-dsh-tool-cordis/model-experience/runtime-inspection/what-the-model-sees: - en: f73493581a266830 - zh: d47bf0bf369f9b90 + en: 63d8b2a3ac2c6bc9 + zh: 2ada02dd993f3d4f /deepseek-ai-dsh-tool-cordis/model-experience/runtime-inspection/token-effect: en: b393ba67aaa0a600 zh: 89a899e2401e9a34 diff --git a/packages/extensions/tool-cordis/README.md b/packages/extensions/tool-cordis/README.md index f5b6b53d14..d672f52bb9 100644 --- a/packages/extensions/tool-cordis/README.md +++ b/packages/extensions/tool-cordis/README.md @@ -25,7 +25,7 @@ Inspect Host and Client runtime APIs before writing plugin code. Standard and Cr ## Use this package -Standard and Creator modes include this tool. Other compositions mount `@deepseek-ai/dsh-tool-cordis/host` once in the host composition beside the host runner that provides `cordisInspect`, and `@deepseek-ai/dsh-tool-cordis` in each agent preset that exposes the tool; a preset row alone registers no Host providers. Call `cordis_inspect` without `query` to discover providers, then pass a `query` object with `platform`, `provider`, `method`, and optional `input` to read a provider's exact methods and types. The Host `Config` provider lists live Loader entries in pages (`offset`, `limit` up to 100, optional exact plugin `name`; `total` and `nextOffset` bound the walk) with each entry's Loader id, the tree-local id patches address, and its Config status (`schema`, `absent`, `unsupported`, `tree` for group and include carriers, `inactive` for disabled, never imported, or disposed entries), and projects one entry's native Config into a self-contained JSON Schema document beside the entry's `packageDir`, the resolved directory holding the package README and built `lib/`, when the profile package lookup resolves it. A call without an Agent, or a `Config` query on a Host without a Loader, fails with `ToolContextUnavailableError`; a malformed `Config` paging field fails with `ToolArgsError`; and an unknown entry id fails with `InspectError` `INSPECT_TARGET_NOT_FOUND`. Use [Plugin Manager](../../boot/plugin-manager/README.md) to install bundles containing plugin code or MCP configuration. +Standard and Creator modes include this tool. Other compositions mount `@deepseek-ai/dsh-tool-cordis/host` once in the host composition beside the host runner that provides `cordisInspect`, and `@deepseek-ai/dsh-tool-cordis` in each agent preset that exposes the tool; a preset row alone registers no Host providers. Call `cordis_inspect` without `query` to discover providers, then pass a `query` object with `platform`, `provider`, `method`, and optional `input` to read a provider's exact methods and types. The Host `Config` provider lists live Loader entries in pages (`offset`, `limit` up to 100, optional exact plugin `name`; `total` and `nextOffset` bound the walk) with each entry's Loader id, the tree-local id patches address, and its Config status (`schema`, `absent`, `unsupported`, `tree` for group and include carriers, `inactive` for disabled, never imported, or disposed entries), and projects one entry's native Config into a self-contained JSON Schema document beside the entry's `packageDir`, the resolved directory holding the package README and built `lib/`, when the profile package lookup resolves it. The Host `Runtime` provider's `getVersion` returns `{ version }`, the exact running DSH version that plugin `engines.dsh` ranges and DSH peer dependencies are checked against. A call without an Agent, or a `Config` query on a Host without a Loader, fails with `ToolContextUnavailableError`; a malformed `Config` paging field fails with `ToolArgsError`; and an unknown entry id fails with `InspectError` `INSPECT_TARGET_NOT_FOUND`. Use [Plugin Manager](../../boot/plugin-manager/README.md) to install bundles containing plugin code or MCP configuration. ----- @@ -35,7 +35,7 @@ Standard and Creator modes include this tool. Other compositions mount `@deepsee
    Implementation internals — click to expand -Host providers combine generated Service/Event catalogs, the live Loader tree projected through the app-boot Config projector, and the requesting agent's tool registry. Client providers synchronize their manifests through the existing inspection registry and answer queries from a connected page. The host entry owns the Host provider registrations and the preset row owns the tool, each through Cordis effects; the registry rejects a duplicate provider id, which is why the providers register once per process rather than per preset. +Host providers combine generated Service/Event catalogs, the live Loader tree projected through the app-boot Config projector, the requesting agent's tool registry, and the app-boot runtime version. Client providers synchronize their manifests through the existing inspection registry and answer queries from a connected page. The host entry owns the Host provider registrations and the preset row owns the tool, each through Cordis effects; the registry rejects a duplicate provider id, which is why the providers register once per process rather than per preset.
    @@ -54,7 +54,7 @@ Host providers combine generated Service/Event catalogs, the live Loader tree pr #### What the model sees -The [tool catalog](../../../docs/tool-catalog.md#deepseek-aidsh-tool-cordis) describes one read-only inspection tool whose description explains directory discovery and queries without adding a system prompt section. In the `standard` and `cordis` presets, the first-turn skill catalog carries the description of the shipped `dsh-doc` skill, which covers questions about DSH and requests to build or change DSH plugins, MCP connections, and agent presets; its references cover Plugin Manager, MCP setup, Client packaging, and slot registration. Query results contain the requested API declarations, live tool schemas, the live entry directory with Config status, or one entry's projected Config JSON Schema. +The [tool catalog](../../../docs/tool-catalog.md#deepseek-aidsh-tool-cordis) describes one read-only inspection tool whose description explains directory discovery and queries without adding a system prompt section. In the `standard` and `cordis` presets, the first-turn skill catalog carries the description of the shipped `dsh-doc` skill, which covers questions about DSH and requests to build or change DSH plugins, MCP connections, and agent presets; its references cover Plugin Manager, MCP setup, Client packaging, and slot registration. Query results contain the requested API declarations, live tool schemas, the live entry directory with Config status, one entry's projected Config JSON Schema, or the running DSH version. #### Token effect diff --git a/packages/extensions/tool-cordis/README.zh.md b/packages/extensions/tool-cordis/README.zh.md index e3cfb00e87..e118bc222e 100644 --- a/packages/extensions/tool-cordis/README.zh.md +++ b/packages/extensions/tool-cordis/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用本包 -标准模式和创造模式包含这个工具。其他组合需要在宿主组合里、提供 `cordisInspect` 的 host runner 旁挂载一次 `@deepseek-ai/dsh-tool-cordis/host`,并在每个要暴露这个工具的 agent preset 里挂载 `@deepseek-ai/dsh-tool-cordis`;仅有 preset 行不会注册任何 Host provider。调用 `cordis_inspect` 时省略 `query` 以发现 provider,再传入包含 `platform`、`provider`、`method` 及可选 `input` 的 `query` 对象,读取 provider 的具体方法和类型。Host 的 `Config` provider 分页列出运行中的 Loader entry(`offset`、最多 100 的 `limit`、可选的精确插件 `name`;`total` 与 `nextOffset` 界定遍历),每个 entry 带 Loader id、patch 所寻址的树内 id 及其 Config 状态(`schema`、`absent`、`unsupported`、group 与 include 载体为 `tree`、禁用、未导入或已销毁的 entry 为 `inactive`),并把单个 entry 的原生 Config 投影为自包含的 JSON Schema 文档,同时在 profile 包查找能解析时给出该 entry 的 `packageDir`,即包 README 与构建产物 `lib/` 所在目录。没有 Agent 的调用,或在没有 Loader 的 Host 上的 `Config` 查询,以 `ToolContextUnavailableError` 失败;`Config` 分页字段格式错误时以 `ToolArgsError` 失败;未知 entry id 以 `InspectError` `INSPECT_TARGET_NOT_FOUND` 失败。通过 [Plugin Manager](../../boot/plugin-manager/README.zh.md) 安装包含插件代码或 MCP 配置的组合包。 +标准模式和创造模式包含这个工具。其他组合需要在宿主组合里、提供 `cordisInspect` 的 host runner 旁挂载一次 `@deepseek-ai/dsh-tool-cordis/host`,并在每个要暴露这个工具的 agent preset 里挂载 `@deepseek-ai/dsh-tool-cordis`;仅有 preset 行不会注册任何 Host provider。调用 `cordis_inspect` 时省略 `query` 以发现 provider,再传入包含 `platform`、`provider`、`method` 及可选 `input` 的 `query` 对象,读取 provider 的具体方法和类型。Host 的 `Config` provider 分页列出运行中的 Loader entry(`offset`、最多 100 的 `limit`、可选的精确插件 `name`;`total` 与 `nextOffset` 界定遍历),每个 entry 带 Loader id、patch 所寻址的树内 id 及其 Config 状态(`schema`、`absent`、`unsupported`、group 与 include 载体为 `tree`、禁用、未导入或已销毁的 entry 为 `inactive`),并把单个 entry 的原生 Config 投影为自包含的 JSON Schema 文档,同时在 profile 包查找能解析时给出该 entry 的 `packageDir`,即包 README 与构建产物 `lib/` 所在目录。Host 的 `Runtime` provider 的 `getVersion` 返回 `{ version }`,即插件 `engines.dsh` 范围和 DSH peer 依赖所比对的当前运行 DSH 的精确版本。没有 Agent 的调用,或在没有 Loader 的 Host 上的 `Config` 查询,以 `ToolContextUnavailableError` 失败;`Config` 分页字段格式错误时以 `ToolArgsError` 失败;未知 entry id 以 `InspectError` `INSPECT_TARGET_NOT_FOUND` 失败。通过 [Plugin Manager](../../boot/plugin-manager/README.zh.md) 安装包含插件代码或 MCP 配置的组合包。 ----- @@ -35,7 +35,7 @@ kind: "package-reference"
    实现细节 — 点击展开 -Host provider 结合生成的 Service/Event 目录、经 app-boot Config 投影器投影的运行中 Loader 树,以及请求 agent 的工具注册表。Client provider 通过现有检查注册表同步清单,并从已连接页面回答查询。宿主入口持有 Host provider 的注册,preset 行持有这个工具,都通过 Cordis effect;注册表拒绝重复的 provider id,所以 provider 按进程注册一次而不是按 preset 注册。 +Host provider 结合生成的 Service/Event 目录、经 app-boot Config 投影器投影的运行中 Loader 树、请求 agent 的工具注册表,以及 app-boot 运行时版本。Client provider 通过现有检查注册表同步清单,并从已连接页面回答查询。宿主入口持有 Host provider 的注册,preset 行持有这个工具,都通过 Cordis effect;注册表拒绝重复的 provider id,所以 provider 按进程注册一次而不是按 preset 注册。
    @@ -54,7 +54,7 @@ Host provider 结合生成的 Service/Event 目录、经 app-boot Config 投影 #### 模型所见 -[工具目录](../../../docs/tool-catalog.zh.md#deepseek-aidsh-tool-cordis) 描述一个只读检查工具,其描述说明目录发现和查询方式,不添加 system prompt 段落。在 `standard` 和 `cordis` preset 中,首轮 skill catalog 携带随附的 `dsh-doc` 技能的描述,该技能覆盖关于 DSH 的问题,以及构建或修改 DSH 插件、MCP 连接和 agent preset 的请求;其参考资料覆盖 Plugin Manager、MCP 设置、Client 打包和 slot 注册。查询结果包含所请求的 API 声明、当前工具 schema、带 Config 状态的运行中 entry 目录,或单个 entry 投影后的 Config JSON Schema。 +[工具目录](../../../docs/tool-catalog.zh.md#deepseek-aidsh-tool-cordis) 描述一个只读检查工具,其描述说明目录发现和查询方式,不添加 system prompt 段落。在 `standard` 和 `cordis` preset 中,首轮 skill catalog 携带随附的 `dsh-doc` 技能的描述,该技能覆盖关于 DSH 的问题,以及构建或修改 DSH 插件、MCP 连接和 agent preset 的请求;其参考资料覆盖 Plugin Manager、MCP 设置、Client 打包和 slot 注册。查询结果包含所请求的 API 声明、当前工具 schema、带 Config 状态的运行中 entry 目录、单个 entry 投影后的 Config JSON Schema,或当前运行的 DSH 版本。 #### Token 影响 diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index c4c0bce14d..2802f44d76 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -599,9 +599,15 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ methods: [ { signature: 'graph(): WebBootGraph', - description: 'Current composed entry graph (stable object between changes).', + description: 'Current composed entry graph (stable object between changes), carrying the configured synced values.', parameters: [], - returns: 'the graph served as `window.__DSH_BOOT__`.', + returns: 'the graph served as the owner\'s `window.__DSH_BOOT__`.', + }, + { + signature: 'graphFor(principal: Principal | undefined): WebBootGraph', + description: '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.', + parameters: [{ name: 'principal', description: '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.', }, { signature: 'clientPath(id: string): string | undefined', @@ -635,7 +641,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, { signature: 'onGraphChanged(listener: () => void): () => void', - description: 'Fires after any flush that recomposed the graph (row added/removed, or a rebuilt rev change). Pull model: listeners re-read graph.', + description: '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 graph.', parameters: [{ name: 'listener', description: 'notified with no payload.' }], returns: 'the unsubscriber.', }, @@ -718,6 +724,19 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, ], }, + { + key: 'config', + summary: 'Read-only access to other packages\' synced Config; a plugin receives its own through `apply`.', + description: 'Read-only access to other packages\' synced Config; a plugin receives its own through `apply`.', + methods: [ + { + signature: 'resolveConfigByPackage(packageName: string): SyncedConfig | undefined', + description: '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.', + parameters: [{ name: 'packageName', description: 'package name of the graph row.' }], + returns: 'the object, or undefined while no activation of the package is running.', + }, + ], + }, { key: 'configEditor', summary: 'Persist complete raw configs and apply them through the normal Loader path.', @@ -3262,7 +3281,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, { signature: 'abstract open(id: SessionId, access: SessionAccess, options?: SessionPersistenceOpenOptions): Promise', - description: 'Open an existing stored session.\n\n`read` never takes ownership and works while another handle (or process) holds write ownership. `write` atomically claims single-writer ownership; an existing active owner rejects.', + description: 'Open an existing stored session.\n\nReturned `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.', parameters: [{ name: 'id', description: 'the stored session to open.' }, { name: 'access', description: '`read` or `write`.' }, { name: 'options', description: 'optional cancellation.' }], returns: 'the open handle.', throws: ['{SessionPersistenceNotFoundError} when the session does not exist.', '{SessionAlreadyOwnedError} for `write` when ownership is taken.'], @@ -8741,7 +8760,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'PtcRunResult', - declaration: 'export interface PtcRunResult {\n sandbox?: PtcRunSandbox;\n value?: PtcJsonValue;\n output: PtcOutput[];\n error?: PtcRunFailure;\n}', + declaration: 'export interface PtcRunResult {\n sandbox?: PtcRunSandbox;\n value?: PtcJsonValue;\n output: PtcOutput[];\n outputTruncated?: boolean;\n error?: PtcRunFailure;\n}', }, { name: 'PtcRunSandbox', @@ -10339,6 +10358,18 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'SurfaceSnapshot', declaration: 'export interface SurfaceSnapshot {\n readonly generation: number;\n readonly tree: readonly SerializedNode[] | null;\n}', }, + { + name: 'SyncedConfig', + declaration: 'export type SyncedConfig = {\n readonly [K in keyof C as NonNullable extends Volatile ? K : never]-?: NonNullable extends Volatile ? SyncedConfigRef : never;\n};', + }, + { + name: 'SyncedConfigRef', + declaration: 'export interface SyncedConfigRef extends Volatile, ObservableSnapshot> {\n}', + }, + { + name: 'SyncedConfigValues', + declaration: 'export type SyncedConfigValues = {\n readonly [field: string]: JsonValue;\n};', + }, { name: 'SystemMessage', declaration: 'export interface SystemMessage extends MessageBase {\n readonly role: \'system\';\n readonly source: MessageSourceMap[\'system-prompt\'];\n}', @@ -10961,7 +10992,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'WebBootEntry', - declaration: 'export interface WebBootEntry {\n id: string;\n url: string;\n rev: string;\n inject?: string[];\n immediately?: boolean;\n external?: string[];\n}', + declaration: 'export interface WebBootEntry {\n id: string;\n url: string;\n rev: string;\n inject?: string[];\n immediately?: boolean;\n external?: string[];\n config?: SyncedConfigValues;\n}', }, { name: 'WebBootGraph', diff --git a/packages/extensions/tool-cordis/src/providers.ts b/packages/extensions/tool-cordis/src/providers.ts index aaf419341b..54fd70f748 100644 --- a/packages/extensions/tool-cordis/src/providers.ts +++ b/packages/extensions/tool-cordis/src/providers.ts @@ -1,6 +1,7 @@ /** First-party Host inspect providers registered by the Cordis tool package. */ import type { Context } from '@deepseek-ai/cordis' +import { getDshRuntimeVersion } from '@deepseek-ai/dsh-app-boot' import { InspectError, type HostCordisInspectProviderRegistration } from '@deepseek-ai/dsh-cordis-host-runner' import type { JsonValue } from '@deepseek-ai/dsh-util-values' import { EVENT_API, queryEventApi, queryServiceApi } from './api-catalog.ts' @@ -29,6 +30,9 @@ const CONFIG_INPUT: JsonValue = { const CONFIG_OUTPUT = { description: 'One directory page of live entries with patch ids, Config status, total, and nextOffset, or one entry\'s projected JSON Schema with shared definitions, omission acceptance, and projection limitations.', } as const +const RUNTIME_OUTPUT = { + description: 'Object whose version field is the exact running DSH version.', +} as const const HOST_EVENTS = EVENT_API.filter(event => !event.name.startsWith('cordis/')) /** @@ -62,6 +66,14 @@ export function hostInspectProviders(ctx: Context): HostCordisInspectProviderReg CONFIG_INPUT, CONFIG_OUTPUT, ), + registration( + 'Runtime', + 'Running DSH version, the version that plugin engines.dsh ranges and DSH peer dependencies are checked against.', + 'getVersion', + () => ({ version: getDshRuntimeVersion() }), + undefined, + RUNTIME_OUTPUT, + ), { manifest: { id: 'Tool', diff --git a/packages/extensions/tool-cordis/tests/host.spec.ts b/packages/extensions/tool-cordis/tests/host.spec.ts index 08eb796246..c43d422812 100644 --- a/packages/extensions/tool-cordis/tests/host.spec.ts +++ b/packages/extensions/tool-cordis/tests/host.spec.ts @@ -1,3 +1,4 @@ +import { createRequire } from 'node:module' import * as NativeToolExecutor from '@deepseek-ai/dsh-tool-executor-native' import { Context } from '@deepseek-ai/cordis' import { CordisInspectRegistryService } from '@deepseek-ai/dsh-cordis-host-runner' @@ -31,12 +32,21 @@ describe('the cordis-inspect-providers host entry', () => { const fiber = ctx.plugin(CordisInspectProviders) await fiber - expect(ctx.cordisInspect.list().map(provider => provider.id)).toEqual(['Service', 'Event', 'Config', 'Tool']) + expect(ctx.cordisInspect.list().map(provider => provider.id)).toEqual(['Service', 'Event', 'Config', 'Runtime', 'Tool']) await fiber.dispose() expect(ctx.cordisInspect.list()).toEqual([]) }) + it('answers the Runtime version query with the running DSH version', async () => { + const ctx = await host() + await ctx.plugin(CordisInspectProviders) + const agent = { ctx } as never + const signal = new AbortController().signal + expect(await ctx.cordisInspect.query('host', 'Runtime', 'getVersion', undefined, agent, signal)).toEqual({ version: (createRequire(import.meta.url)('@deepseek-ai/dsh-app-boot/package.json') as { version: string }).version }) + await ctx.fiber.dispose() + }) + it('reports a missing Agent and an undeclared provider method with error codes', async () => { const ctx = await host() await ctx.plugin(CordisInspectProviders) @@ -46,7 +56,7 @@ describe('the cordis-inspect-providers host entry', () => { await expect(query?.execute({ query: { platform: 'host', provider: 'Tool', method: 'listTools' } }, { signal } as never)).rejects.toMatchObject({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE', message: 'Cordis inspection requires an Agent-backed session', }) - for (const provider of hostInspectProviders(ctx).filter(candidate => ['Service', 'Tool'].includes(candidate.manifest.id))) { + for (const provider of hostInspectProviders(ctx).filter(candidate => ['Service', 'Runtime', 'Tool'].includes(candidate.manifest.id))) { await expect(Promise.resolve().then(() => provider.query('undeclared', undefined, { agent: undefined as never, signal }))) .rejects.toMatchObject({ name: 'InspectError', code: 'INSPECT_METHOD_NOT_FOUND' }) } diff --git a/packages/preset/agent-preset/skills/dsh-doc/SKILL.md b/packages/preset/agent-preset/skills/dsh-doc/SKILL.md index 058ca2a2e4..4254e6e11f 100644 --- a/packages/preset/agent-preset/skills/dsh-doc/SKILL.md +++ b/packages/preset/agent-preset/skills/dsh-doc/SKILL.md @@ -24,6 +24,7 @@ The files below live in this skill's base directory, which the `skill` tool repo | Find the installed version's documentation and package sources | `references/locate-docs.md` | | Build, install, enable, or debug a plugin or bundle | `references/plugin-development.md` | | Bundle manifest, locale resources, detail document, icons, installation, Host exports and Config | `references/host-plugin.md` | +| Read the running DSH version; declare `engines.dsh` | `references/dsh-version.md` | | Bundle descriptions, optional single-image details, locale paths and preview verification | `references/plugin-details.md` | | Save plugin configuration or credentials | `references/configuration.md` | | Web UI: Client manifest, module loader, slot registration | `references/ui-plugin.md` | diff --git a/packages/preset/agent-preset/skills/dsh-doc/references/dsh-version.md b/packages/preset/agent-preset/skills/dsh-doc/references/dsh-version.md new file mode 100644 index 0000000000..30f7ea2c91 --- /dev/null +++ b/packages/preset/agent-preset/skills/dsh-doc/references/dsh-version.md @@ -0,0 +1,11 @@ +# DSH version and `engines.dsh` + +Read the running DSH version before writing a version requirement. With `cordis_inspect`, pass `query: { platform: 'host', provider: 'Runtime', method: 'getVersion' }` and use the returned `version`; installation and activation check plugins against exactly this version. Otherwise use the version that `references/locate-docs.md` identifies. A `package.json` under the profile's `node_modules`, a lockfile, or an unrelated checkout may be an older copy and does not identify the running version. + +Declare the versions the plugin supports as a SemVer range in `engines.dsh`. Use the running version as the lower bound, copied exactly with any prerelease suffix: for a running `0.2.2-alpha.2`, `^0.2.2` rejects it, while `^0.2.2-alpha.2` accepts it. + +```json +{ "engines": { "dsh": "^0.2.2-alpha.2" } } +``` + +Prerelease versions take part in matching, so `^0.2.2-alpha.2` accepts `0.2.2-rc.1`, `0.2.2`, and `0.2.9`, but not `0.3.0`. When `engines.dsh` is present it alone decides; DSH peer dependencies are then ignored. Without it, every `@deepseek-ai/dsh` or `@deepseek-ai/dsh-*` range in `peerDependencies` must match. An empty, invalid, or `workspace:` range in `engines.dsh` rejects every version; a non-string value makes the manifest malformed. A plugin without either declaration loads on any version. A refusal returns the `incompatible-version` code with `runtimeVersion` and the unmet `requirements`; correct the range rather than requesting a version exemption for a plugin you are writing. diff --git a/packages/preset/agent-preset/skills/dsh-doc/references/host-plugin.md b/packages/preset/agent-preset/skills/dsh-doc/references/host-plugin.md index 86ba088864..b607af7c8f 100644 --- a/packages/preset/agent-preset/skills/dsh-doc/references/host-plugin.md +++ b/packages/preset/agent-preset/skills/dsh-doc/references/host-plugin.md @@ -26,6 +26,8 @@ A Host-only bundle needs no dependencies, install scripts, or build tool: config: {} ``` +To declare the DSH versions the bundle supports in `engines.dsh`, read `references/dsh-version.md` first. + ## Display metadata, detail document, and icon Plugin Manager and Settings read `meta.title` and `meta.description` from exported locale JSON and an icon from exported resources without activating plugins. The bundle's page in Plugin Manager shows the detail document that `meta.detail` names, otherwise the package README. Complete this checklist before installation: diff --git a/packages/preset/agent-preset/skills/dsh-doc/references/locate-docs.md b/packages/preset/agent-preset/skills/dsh-doc/references/locate-docs.md index 5a1374baaf..e05e120c13 100644 --- a/packages/preset/agent-preset/skills/dsh-doc/references/locate-docs.md +++ b/packages/preset/agent-preset/skills/dsh-doc/references/locate-docs.md @@ -6,7 +6,7 @@ Answer for the running installation, not an unrelated checkout in the current wo These runtime facts are not necessarily in model context. Print only the needed variables: in bash, `printf '%s\n' "$DSH_PROFILE" "$DSH_INSTALL_DIR" "$DSH_NODE_EXECUTABLE"`; in PowerShell, `$env:DSH_PROFILE; $env:DSH_INSTALL_DIR; $env:DSH_NODE_EXECUTABLE`. Keep the loaded skill's reported Base directory. `DSH_PROFILE=desktop` identifies the Desktop profile, including development launches; `web` can run from npm or source. Profile and distribution are not one-to-one: verify ASAR or checkout markers below. `DSH_PROFILE_DIR` holds the user's profile and added plugins, not the DSH installation root. Standard and Creator are agent modes, not installation layouts. -Verify that `DSH_INSTALL_DIR/package.json` names `@deepseek-ai/dsh`; its `version` identifies the running CLI package. Resolve symlinks before comparing directories. Missing variables alone do not establish that there is no profile or no source. Use the loaded skill's location or an inspected package directory to verify a candidate; if none is verifiable, report what remains unlocated. Do not change the profile to obtain tools. +When `cordis_inspect` is available, its Host `Runtime` provider's `getVersion` returns the running DSH version. Verify that `DSH_INSTALL_DIR/package.json` names `@deepseek-ai/dsh`; its `version` identifies the running CLI package. Copies of `@deepseek-ai/dsh` under the profile's `node_modules` may be stale and do not identify the running version. Resolve symlinks before comparing directories. Missing variables alone do not establish that there is no profile or no source. Use the loaded skill's location or an inspected package directory to verify a candidate; if none is verifiable, report what remains unlocated. Do not change the profile to obtain tools. ## Source checkout diff --git a/packages/preset/agent-preset/skills/dsh-doc/references/packages.md b/packages/preset/agent-preset/skills/dsh-doc/references/packages.md index dcfb0cdc64..f4932c7cae 100644 --- a/packages/preset/agent-preset/skills/dsh-doc/references/packages.md +++ b/packages/preset/agent-preset/skills/dsh-doc/references/packages.md @@ -65,9 +65,10 @@ Every package below exports a Cordis plugin that a bundle patch can name in a Lo | Package | Config | Description | |---|---|---| +| `@deepseek-ai/dsh-client-config` | no | Types of browser-synced plugin configuration | | `@deepseek-ai/dsh-client-connection` | yes | Authenticated RPC transport and generation lifecycle | | `@deepseek-ai/dsh-client-file-upload` | no | Agent-scoped browser file upload, streaming intake, and staged receipt service | -| `@deepseek-ai/dsh-client-hmr` | yes | Web client graph synchronization and rebuilt-bundle reload transport | +| `@deepseek-ai/dsh-client-hmr` | yes | Web client graph and rebuilt-bundle delivery over an authenticated Remote stream | | `@deepseek-ai/dsh-client-locale` | no | Locale plugin: Host-backed preference, extensible language catalog, browser fallback, and typed built-in dictionaries | | `@deepseek-ai/dsh-client-modules` | no | Client module system, dual-face: node half composes the __DSH_BOOT__ entry graph (incremental dsh.client scan, bundle route, index tap, webPlugins service); browser half is the lazy-CJS module table the vendored cordis Loader consumes as its internal seam | | `@deepseek-ai/dsh-client-product-analytics` | yes | Desktop product event collection and authenticated Host reporting | @@ -402,6 +403,7 @@ Every package below exports a Cordis plugin that a bundle patch can name in a Lo | `@deepseek-ai/dsh-session-checkpoint-policy` | no | Semantic session durability checkpoints before model requests and tool side effects | | `@deepseek-ai/dsh-session-log-deepseek` | yes | Incremental lossless session-log request extension for the official DeepSeek LLM API | | `@deepseek-ai/dsh-session-persistence-jsonl` | yes | JSONL durable session persistence backend for the DeepSeek Harness | +| `@deepseek-ai/dsh-session-persistence-sqlite` | yes | SQLite Session event storage backend for the DeepSeek Harness | | `@deepseek-ai/dsh-session-projection` | no | Session-projection seam: the merge-extensible projection type table, the provider contract, and the ctx.sessionProjections registry serving whole current values of log-derived per-session state | | `@deepseek-ai/dsh-session-projection-cache` | yes | Persisted projection cache (ctx.sessionProjectionCache): durable per-session checkpoint records on the session_projcache storage domain (per-record layout), throttled write-behind, and the cached listing read | | `@deepseek-ai/dsh-session-stats` | no | Whole-log conversation counts and wall times projection (sessionStats) for the DeepSeek Harness | diff --git a/packages/ptc-runtime/ptc-runtime-node/README.i18n.yaml b/packages/ptc-runtime/ptc-runtime-node/README.i18n.yaml index e8e8197105..19263a52b3 100644 --- a/packages/ptc-runtime/ptc-runtime-node/README.i18n.yaml +++ b/packages/ptc-runtime/ptc-runtime-node/README.i18n.yaml @@ -21,17 +21,17 @@ en: 2be5e2e5d17c7c7f zh: 4de138d85dea1614 /deepseek-ai-dsh-ptc-runtime-node/use-this-package/execution-and-results: - en: 602cc6327784725a - zh: 9ba81b1da70c0a15 + en: e4c2a44c600693e9 + zh: d4690975a3f95b14 /deepseek-ai-dsh-ptc-runtime-node/use-this-package/in-memory-modes: - en: a8550e22c243b40d - zh: 59847954dd88f24d + en: d5814e14a6b8cf9f + zh: 40968df6610e9d7f /deepseek-ai-dsh-ptc-runtime-node/use-this-package/deadlines-and-cancellation: en: d383ec7aeab8afec zh: 7c9c49e205fbbcd8 /deepseek-ai-dsh-ptc-runtime-node/use-this-package/failures: - en: 74411c07b1484746 - zh: 65b826012219bbec + en: e1bd21b71247a198 + zh: f479995b244c6715 /deepseek-ai-dsh-ptc-runtime-node/understand-the-implementation: en: e8a08aa2481e7b3e zh: eb1eed80b2bcc9b3 @@ -39,8 +39,8 @@ en: 5c93014a885ed89e zh: 21daedcd9de8cd7f /deepseek-ai-dsh-ptc-runtime-node/understand-the-implementation/source-and-built-bootstraps: - en: 12a242c6d56ef7dd - zh: a5a1a0811c266fcc + en: 20782961844b4192 + zh: 2e7e592b38bf8449 /deepseek-ai-dsh-ptc-runtime-node/understand-the-implementation/runner-import-handling: en: ccde763016c0e039 zh: fd881e88391a9d90 diff --git a/packages/ptc-runtime/ptc-runtime-node/README.md b/packages/ptc-runtime/ptc-runtime-node/README.md index bb6d7da29b..fb7fe112a5 100644 --- a/packages/ptc-runtime/ptc-runtime-node/README.md +++ b/packages/ptc-runtime/ptc-runtime-node/README.md @@ -82,6 +82,8 @@ All execution modes provide the complete native Node console, whose stdout and s Model instructions also restrict raw template literals (`String.raw`) to short text whose backslashes must stay exactly as written, such as regular expressions. Other text, including file contents and commands, is requested as ordinary strings, and file contents as an array of quoted line strings joined with newlines. +Captured output stops at `maxOutputBytes`: the runtime keeps an ordered text and image prefix, drops subsequent output, and sets `outputTruncated: true`. Execution and awaited tool calls continue, including during initialization; existing deadlines, cancellation, memory and control-message limits still apply. Completion values and failure diagnostics take priority within the combined budget, so finalization may shorten the retained prefix. Required completion values remain lossless and fail with `output-limit` if they cannot fit; oversized diagnostics are truncated without changing the failure kind. Truncation alone neither fails execution nor clears retained variables. + `run_code` sets `discardCompletion: true`: function return values and final expression values are omitted without JSON serialization, while inspected output remains visible. Direct runtime consumers receive the usual lossless-JSON completion unless they set this option. Direct filesystem, network and subprocess operations remain Node operations, subject to the selected OS sandbox. Nested host bindings cross the control channel; PTC tool calls retain the registry's visibility, ordering, logging and approval rules. Running a program does not change the Session's standing policy or automatically replay it after a denial. @@ -114,11 +116,11 @@ In REPL mode, each live Agent keeps its own process and top-level variables, fun In `persistent-in-memory` mode, call `registerEnvironmentInitializer(program)` before the first run is admitted to install REPL source that executes once per new environment. The runtime installs current bindings first and evaluates initialization separately from the user program, sharing the first call's deadline, cancellation and output limits. It discards the completion value and includes printed output in the result. New owners, owner-less execution, release and process loss create environments that run initialization again; ordinary calls reuse initialized state. Assigning to an initialized global does not trigger initialization. Initialization lines do not shift user-program locations. Other modes reject registration. -Initialization errors, cancellation, timeout or captured-output overflow prevent the user program from starting and terminate the environment before returning. Earlier external effects remain. Once the Host accepts initialization, user-program failures follow the ordinary retained-state rules below. The [runtime service](../ptc-runtime/README.md#choose-a-backend) defines registration and asynchronous unregistration. +Initialization errors, cancellation or timeout prevent the user program from starting and terminate the environment before returning. Earlier external effects remain. Once the Host accepts initialization, user-program failures follow the ordinary retained-state rules below. The [runtime service](../ptc-runtime/README.md#choose-a-backend) defines registration and asynchronous unregistration. With `replScoped` omitted or `true`, `persistent-in-memory` reports program format `scoped-repl` and compiles each call as a separate strict VM Script in one retained context. Each call starts with copies of the top-level bindings left by earlier calls and may declare any of those names again with any keyword; functions and still-running code from earlier calls keep their own bindings, and assignments that earlier code makes after a call starts are not copied into it. Assigning to an earlier name without declaring it, including one declared with `const`, changes only the copy seen by that call and later calls. The last top-level expression statement is the completion and a Promise completion is not awaited; top-level `return` is rejected. `eval`, `new Function` and WebAssembly compilation in the program context are rejected. Programs load modules only with dynamic `import()`, whose relative specifiers resolve from the working directory of the environment's first call; `require`, `module` and built-in module globals are not provided. A `var` declared inside a block is a top-level name of its call and carries to later calls like any other `var`. A `var` redeclaration of an earlier name starts from the earlier value, so one that does not run, after a throw or in a branch that is not taken, keeps that value. Uncaught callback exceptions and unhandled rejections fail the evaluation that created the callback while it is active and are otherwise discarded, without ending the process; a callback that throws a frozen or non-extensible object still ends the process, as in Node REPL. The [scoped REPL decision](../../../.agents/notes/implemented/architecture/2026-11-09-retained-ptc-scoped-repl.md) records the complete behavior and its comparison with Node REPL. -Memory is best-effort and never saved to disk. Restart, Agent disposal, provider unload, protocol failure, output overflow, or process exit clears it. Missing variables raise normal reference errors; reacquire handles and recreate declarations. Exceptions in the active evaluation settle once and preserve earlier mutations. In REPL mode, exceptions from callbacks belonging to a completed evaluation are not reported in a later result. In Script mode, uncaught callback exceptions can terminate the retained process; await asynchronous work before completing an evaluation. The Session still records programs, tool dispatches and visible results; restoring a Session or forking an Agent starts with empty memory. Each evaluation resets the process working directory to its resolved cwd; program calls to `process.chdir()` do not persist across evaluations. Direct Node access follows the process launch policy. A retained owner cannot change mode, workspace root, or Session identity until its environment is released. Additional writable directories are fixed when the process starts: later grants and revocations apply only after release and recreation. +Memory is best-effort and never saved to disk. Restart, Agent disposal, provider unload, protocol failure or process exit clears it. Missing variables raise normal reference errors; reacquire handles and recreate declarations. Exceptions in the active evaluation settle once and preserve earlier mutations. In REPL mode, exceptions from callbacks belonging to a completed evaluation are not reported in a later result. In Script mode, uncaught callback exceptions can terminate the retained process; await asynchronous work before completing an evaluation. The Session still records programs, tool dispatches and visible results; restoring a Session or forking an Agent starts with empty memory. Each evaluation resets the process working directory to its resolved cwd; program calls to `process.chdir()` do not persist across evaluations. Direct Node access follows the process launch policy. A retained owner cannot change mode, workspace root, or Session identity until its environment is released. Additional writable directories are fixed when the process starts: later grants and revocations apply only after release and recreation. Service consumers pass an object as `stateOwner` to reuse its environment and await `release(owner)` when finished. Requests without an owner run in temporary processes. Their failures leave other owners' retained variables intact and do not report clearing them. Permission setters record the new mode synchronously. The runtime immediately invalidates affected processes and begins cancellation when the Session mode changes, including idle environments. The next program waits for their cleanup before starting; cleanup failure blocks that program and remains retryable. Permission-setting success does not mean old processes have finished stopping. A one-time approved escalation uses a separate environment and awaits its cleanup before returning; it cannot read the standing environment's variables or retain new declarations. Concurrent runs for one owner reject until execution and required cleanup complete; distinct owners may run concurrently. An idle environment has no expiration timer and keeps its process until release or failure. Raw stdout/stderr have no evaluation identity: bytes received during an evaluation share its output budget, even when written by an earlier child process; idle stdout is discarded and idle stderr retains only the bounded diagnostic tail. Await child-process completion before ending an evaluation. Process-exit diagnostics include the exit code and retained stderr tail; idle failures are written to the host logger. If process observation fails during cleanup, releasing the owner retries termination; new runs remain blocked until cleanup succeeds. Pipes that fail to drain after confirmed process exit produce a diagnostic but do not prevent releasing the environment. @@ -132,7 +134,7 @@ Omitting `timeoutMs` uses the configured elapsed default; numeric requests are v ### Failures -Program parse errors and thrown exceptions are `exception`; deadline expiry is `timeout`; cancellation is `abort`; unparsable or oversized control traffic and invalid program messages are `protocol`; unavailable confinement is `sandbox-unavailable`; early process exit, lost control transport or failed managed cleanup is `worker-exit`. Control I/O failures retain the transport diagnostic alongside the observed process exit status. The substrate-independent failure name remains `worker-exit` for process providers. When completion capture is enabled, lossy values are `invalid-output`, and an oversized outer result is `output-limit`, retaining a fitting ordered text and image prefix alongside the diagnostic. Invalid or unsupported options and calls after disposal reject as caller misuse. +Program parse errors and thrown exceptions are `exception`; deadline expiry is `timeout`; cancellation is `abort`; unparsable or oversized control traffic and invalid program messages are `protocol`; unavailable confinement is `sandbox-unavailable`; early process exit, lost control transport or failed managed cleanup is `worker-exit`. Control I/O failures retain the transport diagnostic alongside the observed process exit status. An output-suppression send that rejects while the evaluation and control channel remain active fails the run as `protocol`. Output drained during termination remains bounded locally without sending further suppression notifications. The substrate-independent failure name remains `worker-exit` for process providers. When completion capture is enabled, lossy values are `invalid-output`, and a completion that cannot fit even without captured output is `output-limit`. Neither failure clears retained variables. Diagnostic truncation preserves the failure kind. Invalid or unsupported options and calls after disposal reject as caller misuse. ----- @@ -162,7 +164,7 @@ Per-call completion leaves unfinished binding waits pending and stops binding ca Source execution loads an erasable-only bootstrap closure without relying on sibling built exports; its evaluator modules and installed Acorn and birpc dependencies must be available in the execution world. Built script execution uses `process.js` for every mode; `persistent-process.js` delegates to the same loop with a REPL default for hosts that omit program syntax. Embedded carriers launch their private worker through `launch.executable` and carry the program format and retention flag in each evaluation. A remote script deployment supplies the matching `launch.bootstrapPath`. `resolveLaunch()` selects the local default during construction; an explicit remote invocation never depends on whether the client itself is packaged. A host path is never assumed to name the same remote file. -Custom `launch.bootstrapPath` deployments must use bootstrap protocol 4. `HostMethods.invoke` replies contain `{ value: flatWire, inspection?: string }`; the optional text is associated with the decoded object or array for direct inspection. Deploy the matching bootstrap with the host; the [upgrade guide](../../../docs/upgrade-guide/v0.2.2-rc.3/ptc-tool-result-inspection/guide.md) covers migration from protocol 3. +Custom `launch.bootstrapPath` deployments must use bootstrap protocol 5. `HostMethods.invoke` replies contain `{ value: flatWire, inspection?: string }`; the optional text is associated with the decoded object or array for direct inspection. Deploy the matching bootstrap with the host; the [inspection guide](../../../docs/upgrade-guide/v0.2.2-rc.3/ptc-tool-result-inspection/guide.md) covers binding replies and the [output-truncation guide](../../../docs/upgrade-guide/v0.2.2-rc.3/ptc-output-limit/guide.md) covers output suppression. Bootstraps announcing protocol 3 or 4 are rejected before program dispatch. Source containing `await` is checked for top-level await before native compilation, which can otherwise treat `await` as an identifier. Acorn parses an async wrapper, and acorn-walk traverses it using Node's REPL visitors, declaration hoisting and character-position edits. Computed class-method keys are traversed while method bodies remain separate evaluations. The transform boxes the final expression; the evaluator unwraps and awaits its value. Source that needs no lowering uses native compilation; submissions without `await` retain native syntax diagnostics. Syntax errors preserve the parser message and available source location and caret, without compiler or transformer stack frames. Dynamic `import()` expressions remain native and use the compiling Script's `importModuleDynamically` option. Both private process bundles include Acorn, acorn-walk and birpc; source execution imports the installed packages. diff --git a/packages/ptc-runtime/ptc-runtime-node/README.zh.md b/packages/ptc-runtime/ptc-runtime-node/README.zh.md index b622c32d58..7d6b785bf5 100644 --- a/packages/ptc-runtime/ptc-runtime-node/README.zh.md +++ b/packages/ptc-runtime/ptc-runtime-node/README.zh.md @@ -82,6 +82,8 @@ profile 编辑器可从 `@deepseek-ai/dsh-ptc-runtime-node/configuration` 导入 模型指引还要求:raw 模板字面量(`String.raw`)只用于反斜杠必须原样保留的短文本,例如正则表达式。其他文本,包括文件内容和命令,用普通字符串书写;文件内容写成逐行引号字符串组成的数组,再用换行符拼接。 +捕获输出达到 `maxOutputBytes` 后,运行时保留有序的图文前缀,丢弃后续输出,并设置 `outputTruncated: true`。程序和等待中的工具调用继续执行,初始化期间也一样;原有截止时间、取消、内存和控制消息限制继续生效。完成值和失败诊断在组合预算内优先,因此最终结算可能缩短已保留的输出前缀。要求返回的完成值保持无损,无法容纳时以 `output-limit` 失败;过大的诊断会截断,但不改变失败类型。截断本身不会使执行失败或清空保留变量。 + `run_code` 设置 `discardCompletion: true`:函数返回值和末尾表达式的值不经过 JSON 序列化,也不出现在结果中,显式 inspect 的输出仍然可见。直接调用运行时的消费方在未设置此选项时,仍可取得原有的无损 JSON 完成值。 直接文件系统、网络与子进程操作仍是 Node 操作,受所选 OS 沙箱约束。嵌套 Host 绑定通过控制通道调用;PTC 工具调用保留注册表的可见性、排序、日志和审批规则。运行程序不会改变 Session 的常设策略,也不会在拒绝后自动重放程序。 @@ -114,11 +116,11 @@ profile 编辑器可从 `@deepseek-ai/dsh-ptc-runtime-node/configuration` 导入 在 `persistent-in-memory` 模式下,于运行时首次接纳运行前调用 `registerEnvironmentInitializer(program)`,注册在每个新环境中只执行一次的 REPL 源码。运行时先安装本次绑定,再独立于用户程序求值初始化;二者共享首次调用的截止时间、取消和输出上限。初始化的完成值会被丢弃,打印输出加入结果。新所有者、无所有者执行,以及释放或进程丢失后的运行会创建新环境并再次执行初始化;普通调用复用已初始化的状态。给已初始化的全局变量赋值不会触发初始化。初始化行不会偏移用户程序的位置。其他模式会拒绝注册。 -初始化期间的错误、取消、超时或捕获输出超限会阻止用户程序启动,并在返回前终止该环境。此前的外部效果仍然保留。Host 确认初始化完成后,用户程序失败遵循下方的普通状态保留规则。[运行时服务](../ptc-runtime/README.zh.md#choose-a-backend)定义注册和异步注销行为。 +初始化期间的错误、取消或超时会阻止用户程序启动,并在返回前终止该环境。此前的外部效果仍然保留。Host 确认初始化完成后,用户程序失败遵循下方的普通状态保留规则。[运行时服务](../ptc-runtime/README.zh.md#choose-a-backend)定义注册和异步注销行为。 省略 `replScoped` 或设为 `true` 时,`persistent-in-memory` 报告程序格式 `scoped-repl`,每次调用编译成同一个保留 context 里独立的 strict VM Script。每次调用开始时拿到之前调用留下的顶层绑定的拷贝,可以用任意关键字再次声明这些名字;之前调用里的函数和仍在运行的代码保留各自的绑定,调用开始后之前的代码再赋的值不会拷进来。不声明、直接给之前的名字赋值,包括用 `const` 声明的名字,只改这次及之后调用看到的拷贝。最后一条顶层表达式语句是完成值,Promise 完成值不会被等待;顶层 `return` 会被拒绝。程序环境里的 `eval`、`new Function` 和 WebAssembly 编译会被拒绝。程序只能用动态 `import()` 加载模块,相对路径按这个环境第一次调用时的工作目录解析;不提供 `require`、`module` 和内置模块全局变量。块里声明的 `var` 算作这次调用的顶层名字,和其他 `var` 一样带到之后的调用。用 `var` 重新声明之前的名字时,这次的 `var` 从旧值开始,所以没执行到的声明(抛错之后或在没走到的分支里)保留旧值。未捕获的回调异常和未处理的 rejection,在创建回调的那次执行仍在运行时让它失败,否则被丢弃,不会结束进程;回调里抛出冻结或不可扩展的对象时,进程仍会结束,与 Node REPL 相同。[scoped REPL 决策](../../../.agents/notes/implemented/architecture/2026-11-09-retained-ptc-scoped-repl.zh.md)记录完整行为及其与 Node REPL 的对比。 -内存按尽力保留处理,不保存到磁盘。重启、Agent 销毁、提供方卸载、协议失败、输出超限或进程退出都会清除内存。缺失变量产生普通引用错误,模型需要重新获取句柄和创建声明。当前执行中的异常只结算一次,并保留此前发生的修改。在 REPL 模式下,已完成执行的回调抛出的异常不会在后续结果中报告。在 Script 模式下,未捕获的回调异常可能终止保留进程;结束执行前应等待异步工作完成。Session 仍记录程序、工具分派和可见结果;恢复 Session 或派生 Agent 时从空内存开始。每次执行都会将进程工作目录重置为本次解析的 cwd;程序中的 `process.chdir()` 不跨执行保留。直接 Node 访问遵循进程启动时的文件策略。保留状态的所有者必须先释放环境,才能更改权限模式、工作区根目录或 Session 身份。额外可写目录在进程启动时固定:之后的授权和撤销仅在释放并重新创建环境后生效。 +内存按尽力保留处理,不保存到磁盘。重启、Agent 销毁、提供方卸载、协议失败或进程退出都会清除内存。缺失变量产生普通引用错误,模型需要重新获取句柄和创建声明。当前执行中的异常只结算一次,并保留此前发生的修改。在 REPL 模式下,已完成执行的回调抛出的异常不会在后续结果中报告。在 Script 模式下,未捕获的回调异常可能终止保留进程;结束执行前应等待异步工作完成。Session 仍记录程序、工具分派和可见结果;恢复 Session 或派生 Agent 时从空内存开始。每次执行都会将进程工作目录重置为本次解析的 cwd;程序中的 `process.chdir()` 不跨执行保留。直接 Node 访问遵循进程启动时的文件策略。保留状态的所有者必须先释放环境,才能更改权限模式、工作区根目录或 Session 身份。额外可写目录在进程启动时固定:之后的授权和撤销仅在释放并重新创建环境后生效。 服务消费者通过 `stateOwner` 对象复用环境,并在结束时等待 `release(owner)`。没有所有者的请求在临时进程中执行。此类执行失败不影响其他所有者保留的变量,也不报告清空了这些变量。权限设置同步记录新模式。Session 模式变化时,运行时立即禁止复用受影响的进程并开始取消,包括空闲环境。下一次程序执行前等待这些进程清理;清理失败会阻止本次程序启动,并允许重试。权限设置成功时,旧进程可能仍在停止过程中。单次获准的提权使用独立环境,返回前等待清理;该次执行无法访问原环境的变量,也不会保留新声明。执行及必要清理完成之前,同一所有者的并发调用会被拒绝;不同所有者可以并发。空闲环境没有过期计时器,进程保留到释放或失败为止。原始 stdout/stderr 不携带执行标识:执行期间收到的字节计入本次输出预算,包括较早启动的子进程此时写出的内容;空闲期间丢弃 stdout,只保留限额内的 stderr 诊断尾部。结束本次执行前,应等待子进程完成。进程退出诊断包含退出码和保留的 stderr 尾部;空闲期间的失败写入宿主日志。清理期间无法观测进程范围时,释放所有者会重试终止;清理成功前拒绝新执行。确认进程退出后仍未排空的管道会产生诊断,但不阻止释放环境。 @@ -132,7 +134,7 @@ PTC 消费方按 [dsh-tool-executor-ptc](../../core/tool-executor-ptc/README.zh. ### 失败 -程序解析错误与抛出异常为 `exception`;截止到期为 `timeout`;取消为 `abort`;无法解析或超量的控制通信以及无效的程序消息为 `protocol`;约束不可用为 `sandbox-unavailable`;进程提前退出、控制通道丢失或受管清理失败为 `worker-exit`。控制通道 I/O 失败时,在观测到的进程退出状态之外保留通道诊断原因。进程提供方保留与执行基底无关的失败名 `worker-exit`。捕获完成值时,有损值为 `invalid-output`,外层结果超限为 `output-limit`,并在诊断之外保留预算内有序的图文前缀。无效或不支持的选项,以及资源释放后的调用,以调用方误用拒绝。 +程序解析错误与抛出异常为 `exception`;截止到期为 `timeout`;取消为 `abort`;无法解析或超量的控制通信以及无效的程序消息为 `protocol`;约束不可用为 `sandbox-unavailable`;进程提前退出、控制通道丢失或受管清理失败为 `worker-exit`。控制通道 I/O 失败时,在观测到的进程退出状态之外保留通道诊断原因。若求值和控制通道仍然有效,发送输出抑制通知被拒绝会使本次运行以 `protocol` 失败。终止期间排空的输出仍在本地受预算限制,不再发送输出抑制通知。进程提供方保留与执行基底无关的失败名 `worker-exit`。捕获完成值时,有损值为 `invalid-output`,即使不保留捕获输出也无法容纳的完成值为 `output-limit`。这两种失败都不会清空保留变量。诊断截断保留原来的失败类型。无效或不支持的选项,以及资源释放后的调用,以调用方误用拒绝。 ----- @@ -162,7 +164,7 @@ Host 通过有序控制管道上的 birpc 调用子进程的 `run()`。同一时 源代码执行加载仅含可擦除语法的 bootstrap 依赖,不依赖同级包的构建后导出;执行世界中必须提供求值器模块和已安装的 Acorn 与 birpc 依赖。构建后脚本对所有模式使用 `process.js`;`persistent-process.js` 委托同一个循环,并为未指定程序语法的宿主提供 REPL 默认值。内嵌载体通过 `launch.executable` 启动私有 worker,并在每次执行中携带程序格式和保留标志。远端脚本部署提供对应的 `launch.bootstrapPath`。`resolveLaunch()` 在构造时选择本地默认值;显式的远端调用不依赖客户端自身是否打包。不会假设 Host 路径对应同一个远程文件。 -自定义 `launch.bootstrapPath` 部署必须使用 bootstrap 协议 4。`HostMethods.invoke` 的回复包含 `{ value: flatWire, inspection?: string }`;可选文本与解码后的对象或数组关联,供直接展示使用。请与宿主一起部署匹配的 bootstrap;[升级指南](../../../docs/upgrade-guide/v0.2.2-rc.3/ptc-tool-result-inspection/guide.zh.md)说明了从协议 3 迁移的步骤。 +自定义 `launch.bootstrapPath` 部署必须使用 bootstrap 协议 5。`HostMethods.invoke` 的回复包含 `{ value: flatWire, inspection?: string }`;可选文本与解码后的对象或数组关联,供直接展示使用。请与宿主一起部署匹配的 bootstrap;[展示指南](../../../docs/upgrade-guide/v0.2.2-rc.3/ptc-tool-result-inspection/guide.zh.md)说明绑定回复,[输出截断指南](../../../docs/upgrade-guide/v0.2.2-rc.3/ptc-output-limit/guide.zh.md)说明输出抑制。声明协议 3 或 4 的 bootstrap 会在程序分发前被拒绝。 包含 `await` 的源码会在原生编译前检查顶层 await,否则原生编译可能将 `await` 当作标识符。Acorn 解析包住源码的异步函数,acorn-walk 沿用 Node REPL 的 visitor、声明提升和按字符位置修改源码的方式进行遍历。类方法的计算属性名参与遍历,方法体仍独立求值。转换包装末尾表达式,求值器解包并等待其值。无需转换的源码使用原生编译;不含 `await` 的提交保留原生语法诊断。语法错误保留解析器消息、可用的源码位置与光标,不包含编译器或转换器的调用帧。动态 `import()` 表达式保持原生形式,使用编译该 Script 时的 `importModuleDynamically` 选项。两个私有进程 bundle 都包含 Acorn、acorn-walk 和 birpc;源码执行导入已安装的包。 diff --git a/packages/ptc-runtime/ptc-runtime-node/src/bootstrap.ts b/packages/ptc-runtime/ptc-runtime-node/src/bootstrap.ts index 0bcefbf4f9..160a81b7b4 100644 --- a/packages/ptc-runtime/ptc-runtime-node/src/bootstrap.ts +++ b/packages/ptc-runtime/ptc-runtime-node/src/bootstrap.ts @@ -85,8 +85,7 @@ export interface PatchableStream { * a sink as each item lands (the real sink sends text to the host eagerly, * so captured output survives a mid-run termination). It includes the log * array syntax and string escaping in its accounting. Once exhausted it emits - * the fitting prefix and reports the limit once; the host turns that condition - * into an explicit `output-limit` run failure. + * the fitting prefix and reports truncation once; execution continues. */ export class LogBuffer { private bytes = 2 // JSON serialization of the empty logs array: [] @@ -133,13 +132,11 @@ export class LogBuffer { this.sink(text) } + /** Discard further output after the host exhausts the combined text and image budget. */ + discard(): void { this.truncated = true } + /** Whether captured text has exceeded the shared output budget. */ get overflowed(): boolean { return this.truncated } - - /** Remaining exact JSON-byte budget for the completion value or failure message. */ - remainingOutputBytes(): number { - return this.maxBytes - this.bytes - } } /** @@ -152,7 +149,7 @@ export class LogBuffer { * @throws If object formatting fails; preceding arguments remain visible. */ export function makeInspect( - logs: Pick, images: Pick, 'get'>, emitImage: (id: string) => void, + logs: Pick, images: Pick, 'get'>, emitImage: (id: string) => void, inspections?: Pick, 'get'>, ): { inspect: (...args: unknown[]) => void @@ -167,6 +164,7 @@ export function makeInspect( pending.length = 0 } for (const arg of args) { + if (logs.overflowed) break const inspection = arg !== null && typeof arg === 'object' ? inspections?.get(arg) : undefined if (inspection !== undefined && matchesInspection(arg as object, inspection.snapshot, images)) { flush() @@ -242,19 +240,19 @@ export function captureStreamWrites(logs: Pick, stream: Patch /** * Prepare the program's completion value for the run result. Only lossless - * JSON crosses, and a value that does not fit the remaining combined outer - * budget reports `output-limit`; the host revalidates hostile traffic and + * JSON crosses, and a value that does not fit even without captured output + * reports `output-limit`; the host revalidates hostile traffic and * remains authoritative for native pipe writes the program shim cannot observe. * * @param value - the program's completion value. - * @param remainingOutputBytes - exact bytes left after captured logs. + * @param availableBytes - bytes available to the completion or diagnostic. * @param maxOutputBytes - the configured cap named in an overflow diagnostic. * @returns the result fragment: `{}` for `undefined`, else a flat wire `{ value }`. */ export function prepareCompletion( value: unknown, - remainingOutputBytes: number, - maxOutputBytes: number = remainingOutputBytes, + availableBytes: number, + maxOutputBytes: number = availableBytes, ): ProgramResult { if (value === undefined) return {} let snapshot: ReturnType @@ -267,48 +265,35 @@ export function prepareCompletion( return prepareFailure( 'invalid-output', 'program completion must be lossless JSON', - remainingOutputBytes, - maxOutputBytes, + availableBytes, ) } - if (jsonValueBytesUpTo(snapshot, remainingOutputBytes) === undefined) { - return outputLimit(maxOutputBytes) + if (jsonValueBytesUpTo(snapshot, availableBytes) === undefined) { + return { error: { kind: 'output-limit', message: `completion value exceeded ${maxOutputBytes} bytes` } } } return { value: encodePtcJsonWire(snapshot) } } -/** - * Build the fixed overflow fragment without carrying rejected variable bytes. - * @param maxOutputBytes Configured limit reported to the caller. - * @returns The output-limit failure shared by evaluation phases. - */ -export function outputLimit(maxOutputBytes: number): ProgramResult { - return { error: { kind: 'output-limit', message: `outer output exceeded ${maxOutputBytes} bytes` } } -} - -/** Admit one bounded failure message or replace it with the fixed overflow diagnostic. */ +/** Truncate diagnostic text while preserving its failure kind. */ function prepareFailure( kind: 'exception' | 'invalid-output', message: string, - remainingOutputBytes: number, - maxOutputBytes: number, + availableBytes: number, ): ProgramResult { - if (jsonStringBytesUpTo(message, remainingOutputBytes) === undefined) return outputLimit(maxOutputBytes) - return { error: { kind, message } } + const retained = truncateJsonStringBytes(message, availableBytes) + return { error: { kind, message: retained }, ...retained !== message ? { outputTruncated: true } : {} } } /** * Prepare a thrown program value, including cross-realm errors, without sending * an unbounded stack or string across the process channel. * @param error - the value thrown by the program. - * @param remainingOutputBytes - exact bytes left after captured logs. - * @param maxOutputBytes - the configured cap named in an overflow diagnostic. - * @returns a bounded exception or fixed output-limit fragment. + * @param availableBytes - bytes available to the completion or diagnostic. + * @returns a bounded exception preserving its kind and indicating truncated diagnostics. */ export function prepareException( error: unknown, - remainingOutputBytes: number, - maxOutputBytes: number = remainingOutputBytes, + availableBytes: number, ): ProgramResult { let message: string try { @@ -317,7 +302,7 @@ export function prepareException( } catch { message = 'program threw an unrenderable value' } - return prepareFailure('exception', message, remainingOutputBytes, maxOutputBytes) + return prepareFailure('exception', message, availableBytes) } /** Constructor type for one program-visible binding rejection class. */ diff --git a/packages/ptc-runtime/ptc-runtime-node/src/config.ts b/packages/ptc-runtime/ptc-runtime-node/src/config.ts index 291a789aa9..6fde898608 100644 --- a/packages/ptc-runtime/ptc-runtime-node/src/config.ts +++ b/packages/ptc-runtime/ptc-runtime-node/src/config.ts @@ -21,7 +21,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 diff --git a/packages/ptc-runtime/ptc-runtime-node/src/execution.ts b/packages/ptc-runtime/ptc-runtime-node/src/execution.ts index 2362247ed2..588ad10523 100644 --- a/packages/ptc-runtime/ptc-runtime-node/src/execution.ts +++ b/packages/ptc-runtime/ptc-runtime-node/src/execution.ts @@ -134,13 +134,13 @@ function stripTypeScript(source: string): string { const STRIP_PREFIX = 'async function __dsh_program__() {\n' const STRIP_SUFFIX = '\n}' -const RETAINED_STATE_INSTRUCTIONS = '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. Do not redeclare existing let, const, or class names; reuse mutable bindings or choose new names. 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.' +const RETAINED_STATE_INSTRUCTIONS = '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. Do not redeclare existing let, const, or class names; reuse mutable bindings or choose new names. 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.' /** Scoped REPL guidance; its output sentence is shared with the other modes. */ function scopedReplMode(outputInstructions: string): ExecutionMode { return { format: 'scoped-repl', retainsState: true, - executionInstructions: '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. ' + outputInstructions + ' 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.', + executionInstructions: '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. ' + outputInstructions + ' 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.', stripTypes: stripTypeScript, } } diff --git a/packages/ptc-runtime/ptc-runtime-node/src/output-ledger.ts b/packages/ptc-runtime/ptc-runtime-node/src/output-ledger.ts index 6d30416ba5..a31bc0323b 100644 --- a/packages/ptc-runtime/ptc-runtime-node/src/output-ledger.ts +++ b/packages/ptc-runtime/ptc-runtime-node/src/output-ledger.ts @@ -12,15 +12,24 @@ function entryBytes(entry: PtcOutput, available: number): number | undefined { export class OutputLedger { private bytes = 2 // JSON serialization of the empty output array: [] private entries = 0 + truncated = false - constructor(private readonly maxBytes: number, private readonly overflowMessage?: string) {} + constructor(private readonly maxBytes: number) {} /** Admit one ordered text or image entry against the combined output budget. */ admit(entry: PtcOutput, sink: PtcOutput[]): boolean { + if (this.truncated) return false const separatorBytes = this.entries > 0 ? 1 : 0 const remaining = this.maxBytes - this.bytes - separatorBytes const bytes = entryBytes(entry, remaining) - if (bytes === undefined) return false + if (bytes === undefined) { + this.truncated = true + if (entry.type === 'text') { + const prefix = truncateJsonStringBytes(entry.text, remaining) + if (prefix.length > 0) sink.push({ type: 'text', text: prefix }) + } + return false + } this.bytes += bytes + separatorBytes this.entries += 1 sink.push(entry) @@ -29,46 +38,26 @@ export class OutputLedger { /** Finalize a successful absent-or-JSON completion against the combined cap. */ success(output: PtcOutput[], value?: PtcJsonValue): PtcRunResult { - if (value !== undefined && jsonValueBytesUpTo(value, this.maxBytes - this.bytes) === undefined) return this.limit(output) - return { output, ...value !== undefined ? { value } : {} } + const valueBytes = value === undefined ? 0 : jsonValueBytesUpTo(value, this.maxBytes - 2) + if (valueBytes === undefined) return this.failure(output, { kind: 'output-limit', message: `completion value exceeded ${this.maxBytes} bytes` }) + return { ...this.retain(output, valueBytes), ...value !== undefined ? { value } : {} } } - /** Finalize a failure diagnostic, with output-limit taking precedence when combined bytes exceed the cap. */ + /** Prioritize the terminal diagnostic without changing its failure kind. */ failure(output: PtcOutput[], error: PtcRunFailure): PtcRunResult { - if (jsonStringBytesUpTo(error.message, this.maxBytes - this.bytes) === undefined) return this.limit(output) - return { output, error } + const message = truncateJsonStringBytes(error.message, this.maxBytes - 2) + if (message !== error.message) this.truncated = true + return { ...this.retain(output, Buffer.byteLength(JSON.stringify(message))), error: { ...error, message } } } - /** Build the explicit output-limit failure while retaining a fitting ordered output prefix. */ - limit(output: PtcOutput[]): PtcRunResult { - const fullMessage = this.overflowMessage ?? `outer output exceeded ${this.maxBytes} bytes` - // The fixed diagnostic is ASCII, so every character is one byte plus the quotes. - const messageBytes = fullMessage.length + 2 + /** Keep an ordered prefix after reserving bytes for the completion or diagnostic. */ + private retain(output: PtcOutput[], terminalBytes: number): Pick { const retained: PtcOutput[] = [] - let retainedBytes = 2 - const logBudget = this.maxBytes - messageBytes + const ledger = new OutputLedger(this.maxBytes - terminalBytes) for (const entry of output) { - const separatorBytes = retained.length > 0 ? 1 : 0 - const availableBytes = logBudget - retainedBytes - separatorBytes - const bytes = entryBytes(entry, availableBytes) - if (bytes !== undefined) { - retained.push(entry) - retainedBytes += bytes + separatorBytes - continue - } - if (entry.type === 'image') break - const prefix = truncateJsonStringBytes(entry.text, availableBytes) - if (prefix.length > 0) { - const prefixBytes = jsonStringBytesUpTo(prefix, availableBytes) - /* v8 ignore next -- truncateJsonStringBytes guarantees its returned prefix fits the same budget. */ - if (prefixBytes === undefined) throw new Error('output ledger produced an oversized log prefix') - retained.push({ type: 'text', text: prefix }) - retainedBytes += prefixBytes + separatorBytes - } - break + if (!ledger.admit(entry, retained)) break } - const availableMessageBytes = this.maxBytes - retainedBytes - const message = truncateJsonStringBytes(fullMessage, availableMessageBytes) - return { output: retained, error: { kind: 'output-limit', message } } + this.truncated ||= ledger.truncated + return { output: retained, ...this.truncated ? { outputTruncated: true } : {} } } } diff --git a/packages/ptc-runtime/ptc-runtime-node/src/process.ts b/packages/ptc-runtime/ptc-runtime-node/src/process.ts index 1437812075..5b70c199e3 100644 --- a/packages/ptc-runtime/ptc-runtime-node/src/process.ts +++ b/packages/ptc-runtime/ptc-runtime-node/src/process.ts @@ -4,7 +4,7 @@ import { inspect } from 'node:util' import type { Duplex } from 'node:stream' import type { PtcProgramFormat, PtcJsonValue } from '@deepseek-ai/dsh-ptc-runtime' import { createProcessRpc } from './rpc.ts' -import { captureStreamWrites, LogBuffer, makeInspect, makeBindingErrorClass, makeNamespaces, outputLimit, prepareCompletion, prepareException } from './bootstrap.ts' +import { captureStreamWrites, LogBuffer, makeInspect, makeBindingErrorClass, makeNamespaces, prepareCompletion, prepareException } from './bootstrap.ts' import type { BindingErrorConstructor, BindingInspection, ImageInspectOptions, PatchableStream } from './bootstrap.ts' import type { PtcImageWire } from './json-wire.ts' import { clearProgramEnvironment, filterRuntimeWarnings } from './environment.ts' @@ -106,12 +106,15 @@ export async function runNodeMain( } const imageSink = (id: string): void => { const evaluation = context.getStore() - if (evaluation && acceptsCalls(evaluation)) void connection.image(id) + if (evaluation && acceptsCalls(evaluation) && !evaluation.logs.overflowed) void connection.image(id) + } + const logSink = { + get overflowed(): boolean { return context.getStore()?.logs.overflowed ?? true }, + push(text: string): void { + const evaluation = context.getStore() + if (evaluation && acceptsCalls(evaluation)) evaluation.logs.push(text) + }, } - const logSink = { push(text: string): void { - const evaluation = context.getStore() - if (evaluation && acceptsCalls(evaluation)) evaluation.logs.push(text) - } } const { inspect: programInspect, collectImage } = makeInspect(logSink, images, imageSink, inspections) captureStreamWrites(logSink, processState.stdout) captureStreamWrites(logSink, processState.stderr) @@ -145,7 +148,7 @@ export async function runNodeMain( if (evaluator === undefined) { evaluator = createProgramEvaluator(format, (error) => { const active = context.getStore() - if (active?.active && error) active.finish(prepareException(error, active.logs.remainingOutputBytes(), active.maxOutputBytes)) + if (active?.active && error) active.finish(prepareException(error, active.maxOutputBytes - 2)) }, importHandler === undefined ? undefined : (request) => { const active = context.getStore() if (!active?.active) throw new ImportEvaluationEndedError(active?.reusable ?? true) @@ -197,25 +200,22 @@ export async function runNodeMain( }) }) if (!canContinue()) return - if (logs.overflowed) { - evaluation.finish(outputLimit(data.maxOutputBytes)) - return - } await connection.initialized() } if (!canContinue()) return programEvaluator.evaluate(data.code, (result) => { if (!canContinue()) return evaluation.finish(result.ok - ? data.discardCompletion ? {} : prepareCompletion(result.value, logs.remainingOutputBytes(), data.maxOutputBytes) - : prepareException(result.error, logs.remainingOutputBytes(), data.maxOutputBytes)) + ? data.discardCompletion ? {} : prepareCompletion(result.value, data.maxOutputBytes - 2, data.maxOutputBytes) + : prepareException(result.error, data.maxOutputBytes - 2)) }) } catch (error: unknown) { - if (canContinue()) evaluation.finish(prepareException(error, logs.remainingOutputBytes(), data.maxOutputBytes)) + if (canContinue()) evaluation.finish(prepareException(error, data.maxOutputBytes - 2)) } }) return await completion.promise }, + discardOutput() { current?.logs.discard() }, revoke() { const evaluation = current if (!evaluation?.active) return diff --git a/packages/ptc-runtime/ptc-runtime-node/src/protocol.ts b/packages/ptc-runtime/ptc-runtime-node/src/protocol.ts index 7e8cb05d6c..a2d281e6f4 100644 --- a/packages/ptc-runtime/ptc-runtime-node/src/protocol.ts +++ b/packages/ptc-runtime/ptc-runtime-node/src/protocol.ts @@ -3,7 +3,7 @@ import type { PtcProgramFormat, PtcJsonValue, PtcRunFailure } from '@deepseek-ai import { decodePtcJsonWire, type PtcJsonWire } from './json-wire.ts' /** Wire revision required before the host dispatches program code. */ -export const PROGRAM_PROTOCOL_VERSION = 4 +export const PROGRAM_PROTOCOL_VERSION = 5 /** One binding's JSON value and optional host-authored inspection text. */ export interface BindingResult { @@ -31,13 +31,14 @@ export interface ProgramBootData { names: string[] errorClass?: { name: string; memberNameProperty: string } }[] - /** Combined serialized log and completion budget. */ + /** Combined serialized output and completion or diagnostic budget; terminal data takes priority. */ maxOutputBytes: number } /** Program completion; logs are delivered separately before this result. */ export interface ProgramResult { value?: PtcJsonWire + outputTruncated?: boolean error?: { kind: 'exception' | 'invalid-output' | 'output-limit'; message: string } } @@ -72,7 +73,7 @@ export interface HostMethods { * @param id - Image identity issued by this process’s host. */ image(id: string): void - /** Report exhausted program-side output accounting. */ + /** Report discarded program output without ending the evaluation. */ outputLimit(): void } @@ -87,6 +88,8 @@ export interface ProgramMethods { run(cwd: string, data: ProgramBootData): Promise /** Notify the program thread to revoke bindings and output; run() still owns completion. */ revoke(): void + /** Discard subsequent captured output while allowing execution and binding calls to continue. */ + discardOutput(): void } const record = (value: unknown): value is Record => typeof value === 'object' && value !== null && !Array.isArray(value) @@ -96,17 +99,18 @@ const record = (value: unknown): value is Record => typeof valu * @param result - Untrusted result returned by the program process. * @returns Decoded completion or failure; malformed envelopes throw a protocol error. */ -export function readProgramResult(result: unknown): { value?: PtcJsonValue; error?: PtcRunFailure } { - if (!record(result)) throw new Error('invalid program result') +export function readProgramResult(result: unknown): { value?: PtcJsonValue; error?: PtcRunFailure; outputTruncated?: boolean } { + if (!record(result) || (result.outputTruncated !== undefined && typeof result.outputTruncated !== 'boolean')) throw new Error('invalid program result') + const truncation = result.outputTruncated ? { outputTruncated: true } : {} if (result.error !== undefined) { const error = result.error if (!record(error) || typeof error.message !== 'string' || (error.kind !== 'exception' && error.kind !== 'invalid-output' && error.kind !== 'output-limit')) { throw new Error('invalid terminal error') } - return { error: { kind: error.kind, message: error.message } } + return { ...truncation, error: { kind: error.kind, message: error.message } } } - if (result.value === undefined) return {} + if (result.value === undefined) return truncation const value = decodePtcJsonWire(result.value) - return value === undefined ? { error: { kind: 'invalid-output', message: 'program completion must be lossless JSON' } } : { value } + return value === undefined ? { ...truncation, error: { kind: 'invalid-output', message: 'program completion must be lossless JSON' } } : { ...truncation, value } } diff --git a/packages/ptc-runtime/ptc-runtime-node/src/worker.ts b/packages/ptc-runtime/ptc-runtime-node/src/worker.ts index e93c368540..f00fcd45af 100644 --- a/packages/ptc-runtime/ptc-runtime-node/src/worker.ts +++ b/packages/ptc-runtime/ptc-runtime-node/src/worker.ts @@ -32,8 +32,8 @@ interface Evaluation { invoke: typeof invokeBinding pending: number pendingBytes: number - admit(text: string): void - image(attachment: PtcImage['attachment']): void + admit(entry: PtcOutput): void + truncateOutput(): void finish(error?: PtcRunFailure, value?: PtcJsonValue, discard?: boolean): void } @@ -104,30 +104,23 @@ export class ProgramWorker { } finally { this.running = false } } - private output(): OutputLedger { - return new OutputLedger(this.config.maxOutputBytes, this.retainsState - ? `retained variables were cleared; outer output exceeded ${this.config.maxOutputBytes} bytes` : undefined) - } - private message(message: string): string { return this.retainsState ? `${message}; retained variables were cleared` : message } private async evaluate(spec: PtcRunSpec, bindings: Map): Promise { + const ledger = new OutputLedger(this.config.maxOutputBytes) if (this.exitOutcome !== undefined) { - const output = this.output() const failure: PtcRunFailure = spec.signal?.aborted ? { kind: 'abort', message: this.message('execution canceled') } : { kind: 'worker-exit', message: this.message(this.exitMessage(this.exitOutcome)) } try { await this.terminate() } catch (error: unknown) { - return output.failure([], { kind: 'worker-exit', message: `managed process cleanup failed: ${messageOf(error)}` }) + return ledger.failure([], { kind: 'worker-exit', message: `managed process cleanup failed: ${messageOf(error)}` }) } - return output.failure([], failure) + return ledger.failure([], failure) } this.stderr = '' - const ledger = this.output() const output: PtcOutput[] = [] - let overflowed = false const result = Promise.withResolvers() const timer = spec.timeoutMs === null ? undefined : setTimeout(() => { const phase = evaluation.completion !== undefined ? 'during execution' : 'before code started' @@ -151,21 +144,19 @@ export class ProgramWorker { }, spec, bindings, pending: 0, pendingBytes: 0, invoke: AsyncLocalStorage.bind((binding, args) => invokeBinding(binding, args, image => this.registerImage(image))), - admit: (text) => { - if (overflowed) return - if (!ledger.admit({ type: 'text', text }, output)) { - overflowed = true - output.push({ type: 'text', text }) - evaluation.finish({ kind: 'output-limit', message: 'output limit exceeded' }, undefined, true) - } + truncateOutput: () => { + ledger.truncated = true + const channel = this.channel + if (evaluation.settled || this.closed || !channel || channel.$closed) return + void channel.discardOutput().catch((error: unknown) => { + // Ended evaluations need no notification; channel closure already owns failure reporting. + if (this.active !== evaluation || evaluation.settled || this.closed || channel.$closed) return + this.fail('protocol', `failed to send output-discard notification: ${messageOf(error)}`) + }) }, - image: (attachment) => { - if (overflowed || evaluation.settled) return - if (!ledger.admit({ type: 'image', attachment }, output)) { - overflowed = true - evaluation.finish({ kind: 'output-limit', message: 'output limit exceeded' }, undefined, true) - return - } + admit: (entry) => { + if (ledger.truncated) return + if (!ledger.admit(entry, output)) evaluation.truncateOutput() }, finish: (error, value, discard = false) => { if (evaluation.settled) return @@ -174,21 +165,16 @@ export class ProgramWorker { spec.signal?.removeEventListener('abort', onAbort) const initializationIncomplete = this.pendingInitialization !== undefined if (initializationIncomplete && error?.kind === 'exception') error = { ...error, message: this.message(error.message) } - const complete = (): PtcRunResult => overflowed || error?.kind === 'output-limit' ? ledger.limit(output) - : error ? ledger.failure(output, error) : ledger.success(output, value) - const outcome = complete() const cleanup = async (): Promise => { const interrupted = error?.kind === 'timeout' || error?.kind === 'abort' - let preserved = this.retainsState && !initializationIncomplete && !discard && outcome.error?.kind !== 'output-limit' + let preserved = this.retainsState && !initializationIncomplete && !discard if (preserved && interrupted) preserved = await this.interruptEvaluation(evaluation) let drained = true if (!preserved) drained = await this.terminate() if (interrupted && this.retainsState && error) { error = { ...error, message: `${error.message}; retained variables were ${preserved ? 'preserved' : 'cleared'}` } } - const completed = complete() - // The final interruption diagnostic also consumes output budget. - if (completed.error?.kind === 'output-limit' && preserved) drained = await this.terminate() + const completed = error ? ledger.failure(output, error) : ledger.success(output, value) return drained ? completed : ledger.failure(output, { kind: 'worker-exit', message: 'managed process exited but its output did not drain cleanly' }) } void cleanup().then((completed) => { @@ -281,12 +267,13 @@ export class ProgramWorker { private dispatch(evaluation: Evaluation): void { const completion = this.channel?.run(evaluation.spec.cwd, evaluation.data).then(readProgramResult) evaluation.completion = completion - void completion?.then(({ error, value }) => { + void completion?.then(({ error, value, outputTruncated }) => { if (evaluation.settled) return if (this.pendingInitialization !== undefined && error === undefined) { this.fail('protocol', 'environment initialization completed without Host acceptance') return } + if (outputTruncated) evaluation.truncateOutput() // Raw stdio can be queued beside the RPC result on separate pipes. setImmediate(() => { evaluation.finish(error, value) }) }).catch((error: unknown) => { @@ -333,7 +320,7 @@ export class ProgramWorker { stream.setEncoding('utf8') stream.on('data', (text: string) => { if (stream === handle.stderr) this.stderr = (this.stderr + text).slice(-this.config.maxOutputBytes) - this.active?.admit(text) + this.active?.admit({ type: 'text', text }) }) stream.on('error', (error: Error) => { this.fail('worker-exit', error.message) }) } @@ -362,16 +349,16 @@ export class ProgramWorker { }, log: (text: unknown) => { if (!this.ready || !this.active || typeof text !== 'string') { this.fail('protocol', 'invalid program log'); return } - if (!this.active.settled) this.active.admit(text) + if (!this.active.settled) this.active.admit({ type: 'text', text }) }, image: (id: unknown) => { const image = typeof id === 'string' ? this.images.get(id) : undefined if (!this.ready || !this.active || image === undefined) { this.fail('protocol', 'invalid program image'); return } - this.active.image(image) + if (!this.active.settled) this.active.admit({ type: 'image', attachment: image }) }, outputLimit: () => { if (!this.ready || !this.active) { this.fail('protocol', 'idle PTC output limit'); return } - this.active.finish({ kind: 'output-limit', message: 'output limit exceeded' }, undefined, true) + this.active.truncateOutput() }, invoke: async (global, name, wire) => { const evaluation = this.active @@ -404,7 +391,7 @@ export class ProgramWorker { if (evaluation.settled) throw new Error('PTC evaluation ended before the binding completed') return value }, - }, ['revoke'], (error, kind) => { + }, ['revoke', 'discardOutput'], (error, kind) => { if (kind === 'protocol') this.fail('protocol', error.message) else { if (kind === 'io') this.controlFailure = error.message diff --git a/packages/ptc-runtime/ptc-runtime-node/tests/bootstrap.spec.ts b/packages/ptc-runtime/ptc-runtime-node/tests/bootstrap.spec.ts index 5702002b7a..fb4e2c9a14 100644 --- a/packages/ptc-runtime/ptc-runtime-node/tests/bootstrap.spec.ts +++ b/packages/ptc-runtime/ptc-runtime-node/tests/bootstrap.spec.ts @@ -35,7 +35,6 @@ describe('LogBuffer', () => { expect(seen).toEqual(['12345', '123']) expect(limits).toBe(1) expect(buffer.overflowed).toBe(true) - expect(buffer.remainingOutputBytes()).toBe(0) const exactlyFull: string[] = [] const fullBuffer = new LogBuffer(6, text => exactlyFull.push(text)) @@ -76,7 +75,7 @@ describe('makeInspect', () => { ['undefined property', { value: undefined }, '{ value: undefined }'], ])('displays a %s argument and continues execution', (_name, value, expected) => { const text: string[] = [] - const { inspect } = makeInspect({ push: line => text.push(line) }, new WeakMap(), () => {}) + const { inspect } = makeInspect({ overflowed: false, push: line => text.push(line) }, new WeakMap(), () => {}) inspect('before', value, 'after') expect(text).toHaveLength(1) expect(text[0]).toContain(expected) @@ -87,7 +86,7 @@ describe('makeInspect', () => { const revoked = Proxy.revocable({}, {}) revoked.revoke() const text: string[] = [] - const { inspect } = makeInspect({ push: line => text.push(line) }, new WeakMap(), () => {}) + const { inspect } = makeInspect({ overflowed: false, push: line => text.push(line) }, new WeakMap(), () => {}) inspect(revoked.proxy, { get value() { throw new Error('getter') } }) expect(text).toEqual([' { value: [Getter] }\n']) }) @@ -116,7 +115,7 @@ describe('makeInspect', () => { const images = new WeakMap() const text: string[] = [] const selected: string[] = [] - const { inspect, collectImage } = makeInspect({ push: line => text.push(line) }, images, id => selected.push(id)) + const { inspect, collectImage } = makeInspect({ overflowed: false, push: line => text.push(line) }, images, id => selected.push(id)) const one = inspectedImage(collectImage, '/one.png') const two = inspectedImage(collectImage, '/two.png', 4, 8) images.set(one, 'one').set(two, 'two') @@ -135,7 +134,7 @@ describe('makeInspect', () => { const images = new WeakMap() const text: string[] = [] const selected: string[] = [] - const { inspect, collectImage } = makeInspect({ push: line => text.push(line) }, images, id => selected.push(id)) + const { inspect, collectImage } = makeInspect({ overflowed: false, push: line => text.push(line) }, images, id => selected.push(id)) const image = inspectedImage(collectImage, '/image.png') images.set(image, 'image') const read = vi.fn(() => image) @@ -149,7 +148,7 @@ describe('makeInspect', () => { const images = new WeakMap() const text: string[] = [] const selected: string[] = [] - const { inspect, collectImage } = makeInspect({ push: line => text.push(line) }, images, id => selected.push(id)) + const { inspect, collectImage } = makeInspect({ overflowed: false, push: line => text.push(line) }, images, id => selected.push(id)) const image = inspectedImage(collectImage, '/image.png') images.set(image, 'image') inspect({ @@ -163,7 +162,7 @@ describe('makeInspect', () => { it('selects registered images returned by a custom formatter', () => { const images = new WeakMap() const selected: string[] = [] - const { inspect, collectImage } = makeInspect({ push() {} }, images, id => selected.push(id)) + const { inspect, collectImage } = makeInspect({ overflowed: false, push() {} }, images, id => selected.push(id)) const image = inspectedImage(collectImage, '/image.png') images.set(image, 'image') inspect({ [nodeInspect.custom]() { return { image } } }) @@ -174,7 +173,7 @@ describe('makeInspect', () => { it('keeps collectors separate across reentrant inspection calls', () => { const images = new WeakMap() const selected: string[] = [] - const { inspect, collectImage } = makeInspect({ push() {} }, images, id => selected.push(id)) + const { inspect, collectImage } = makeInspect({ overflowed: false, push() {} }, images, id => selected.push(id)) const one = inspectedImage(collectImage, '/one.png') const two = inspectedImage(collectImage, '/two.png') images.set(one, 'one').set(two, 'two') @@ -192,7 +191,7 @@ describe('makeInspect', () => { const images = new WeakMap() const text: string[] = [] const selected: string[] = [] - const { inspect, collectImage } = makeInspect({ push: line => text.push(line) }, images, id => selected.push(id)) + const { inspect, collectImage } = makeInspect({ overflowed: false, push: line => text.push(line) }, images, id => selected.push(id)) const image = inspectedImage(collectImage, '/image.png') images.set(image, 'image') expect(() => { @@ -210,7 +209,7 @@ describe('makeInspect', () => { it('selects images from Map entries, Set values and enumerable symbol properties', () => { const images = new WeakMap() const selected: string[] = [] - const { inspect, collectImage } = makeInspect({ push() {} }, images, id => selected.push(id)) + const { inspect, collectImage } = makeInspect({ overflowed: false, push() {} }, images, id => selected.push(id)) const one = inspectedImage(collectImage, '/one.png') const two = inspectedImage(collectImage, '/two.png', 4, 8) images.set(one, 'one').set(two, 'two') @@ -227,7 +226,7 @@ describe('makeInspect', () => { it('reads Map and Set entries without consulting overridden methods', () => { const images = new WeakMap() const selected: string[] = [] - const { inspect, collectImage } = makeInspect({ push() {} }, images, id => selected.push(id)) + const { inspect, collectImage } = makeInspect({ overflowed: false, push() {} }, images, id => selected.push(id)) const image = inspectedImage(collectImage, '/image.png') images.set(image, 'image') const map = new Map([['image', image]]) @@ -241,7 +240,7 @@ describe('makeInspect', () => { it('finds images in cyclic containers alongside binary views', () => { const images = new WeakMap() const selected: string[] = [] - const { inspect, collectImage } = makeInspect({ push() {} }, images, id => selected.push(id)) + const { inspect, collectImage } = makeInspect({ overflowed: false, push() {} }, images, id => selected.push(id)) const image = inspectedImage(collectImage, '/image.png') images.set(image, 'image') const value: Record = { binary: new Uint8Array([1, 2, 3]), image } @@ -252,7 +251,7 @@ describe('makeInspect', () => { it('displays undefined arguments and cycles', () => { const text: string[] = [] - const { inspect } = makeInspect({ push: line => text.push(line) }, new WeakMap(), () => {}) + const { inspect } = makeInspect({ overflowed: false, push: line => text.push(line) }, new WeakMap(), () => {}) inspect(undefined) expect(text).toEqual(['undefined\n']) inspect(null) @@ -275,7 +274,7 @@ describe('binding inspection metadata', () => { [empty, { snapshot: {}, text: '' }], ]) const seen: string[] = [] - const { inspect } = makeInspect({ push: text => seen.push(text) }, new WeakMap(), () => {}, inspections) + const { inspect } = makeInspect({ overflowed: false, push: text => seen.push(text) }, new WeakMap(), () => {}, inspections) inspect('before', object, array, empty, 'after') expect(seen).toEqual(['before\n', 'object rendering\n', 'array rendering\n', 'after\n']) expect(Reflect.ownKeys(object)).toEqual(['value']) @@ -286,7 +285,9 @@ describe('binding inspection metadata', () => { const inspections = new WeakMap() const text: string[] = [] const selected: string[] = [] - const { inspect, collectImage } = makeInspect({ push: value => text.push(value) }, images, id => selected.push(id), inspections) + const { inspect, collectImage } = makeInspect( + { overflowed: false, push: value => text.push(value) }, images, id => selected.push(id), inspections, + ) const original = inspectedImage(collectImage, '/same.png') const replacement = inspectedImage(collectImage, '/same.png') images.set(original, 'original') @@ -314,7 +315,7 @@ describe('binding inspection metadata', () => { const snapshot = snapshotPtcJsonValue(value)! const inspections = new WeakMap([[value, { snapshot, text: 'original rendering' }]]) const seen: string[] = [] - const { inspect } = makeInspect({ push: text => seen.push(text) }, new WeakMap(), () => {}, inspections) + const { inspect } = makeInspect({ overflowed: false, push: text => seen.push(text) }, new WeakMap(), () => {}, inspections) change(value) inspect(value) expect(seen.join('')).not.toContain('original rendering') @@ -390,6 +391,19 @@ describe('captureStreamWrites', () => { }) }) +it('skips formatting after output is discarded, including later arguments in one inspect call', () => { + const rendered = vi.fn(() => 'must not format') + const value = { [nodeInspect.custom]: rendered } + const logs = new LogBuffer(4, () => {}) + const images = new WeakMap() + const image = {} + images.set(image, 'image') + const { inspect } = makeInspect(logs, images, () => {}) + inspect('overflow', image, value) + inspect(value) + expect(rendered).not.toHaveBeenCalled() +}) + describe('prepareCompletion', () => { it('omits undefined and passes lossless JSON values exactly', () => { expect(prepareCompletion(undefined, 100)).toEqual({}) @@ -410,14 +424,14 @@ describe('prepareCompletion', () => { it('reports an oversized value instead of substituting rendered text', () => { expect(prepareCompletion('x'.repeat(50), 10)).toEqual({ - error: { kind: 'output-limit', message: 'outer output exceeded 10 bytes' }, + error: { kind: 'output-limit', message: 'completion value exceeded 10 bytes' }, }) }) it('measures the exact JSON serialization at and over the boundary', () => { expect(prepareCompletion('€', 5)).toEqual({ value: encodePtcJsonWire('€') }) expect(prepareCompletion('€', 4)).toEqual({ - error: { kind: 'output-limit', message: 'outer output exceeded 4 bytes' }, + error: { kind: 'output-limit', message: 'completion value exceeded 4 bytes' }, }) }) @@ -428,9 +442,9 @@ describe('prepareCompletion', () => { }) }) - it('uses the remaining combined budget for invalid-output diagnostics', () => { + it('truncates invalid-output diagnostics without changing the failure kind', () => { expect(prepareCompletion(() => 1, 4, 64)).toEqual({ - error: { kind: 'output-limit', message: 'outer output exceeded 64 bytes' }, + error: { kind: 'invalid-output', message: 'pr' }, outputTruncated: true, }) }) }) @@ -445,10 +459,10 @@ describe('prepareException', () => { expect(prepareException(error, 1_000)).toEqual({ error: { kind: 'exception', message } }) }) - it('passes a fitting diagnostic and rejects one byte over without carrying its text', () => { - expect(prepareException('boom', 6, 64)).toEqual({ error: { kind: 'exception', message: 'boom' } }) - expect(prepareException('boom', 5, 64)).toEqual({ - error: { kind: 'output-limit', message: 'outer output exceeded 64 bytes' }, + it('passes a fitting diagnostic and truncates one byte over without changing its kind', () => { + expect(prepareException('boom', 6)).toEqual({ error: { kind: 'exception', message: 'boom' } }) + expect(prepareException('boom', 5)).toEqual({ + error: { kind: 'exception', message: 'boo' }, outputTruncated: true, }) }) diff --git a/packages/ptc-runtime/ptc-runtime-node/tests/host-failures.spec.ts b/packages/ptc-runtime/ptc-runtime-node/tests/host-failures.spec.ts index dfab317387..a002407434 100644 --- a/packages/ptc-runtime/ptc-runtime-node/tests/host-failures.spec.ts +++ b/packages/ptc-runtime/ptc-runtime-node/tests/host-failures.spec.ts @@ -265,7 +265,7 @@ describe('Node runtime host failures', () => { expect((await h.start()).error?.kind).toBe('protocol') }) - it.each([[], [0], [PROGRAM_PROTOCOL_VERSION - 1], [PROGRAM_PROTOCOL_VERSION + 1], ['1']])('refuses bootstrap readiness with incompatible version arguments %j before dispatch', async (...args) => { + it.each([[], [0], [3], [4], [PROGRAM_PROTOCOL_VERSION + 1], ['1']])('refuses bootstrap readiness with incompatible version arguments %j before dispatch', async (...args) => { const h = await setup() const result = await h.start(request, { t: 'q', m: 'ready', a: args }) expect(result.error).toEqual({ kind: 'protocol', message: 'bootstrap protocol mismatch; upgrade launch.bootstrapPath with the host' }) @@ -379,7 +379,7 @@ describe('Node runtime host failures', () => { expect(result.error).toEqual({ kind: 'protocol', message: 'control output exceeds 256 queued bytes' }) }) - it('keeps an output overflow delivered beside the program result', async () => { + it('keeps the actual failure and sandbox denial when output overflows beside the result', async () => { const h = await setup({ maxOutputBytes: 64 }, 'read-only') vi.spyOn(h.ctx.sandbox, 'confine').mockImplementation(async argv => confinement([...argv])) h.receive((message) => { @@ -390,8 +390,9 @@ describe('Node runtime host failures', () => { h.control.push(Buffer.from(`${JSON.stringify(result)}\n${JSON.stringify(log)}\n`)) }) const result = await h.start() - expect(result.error?.kind).toBe('output-limit') - expect(result.sandbox?.denied).toBe(false) + expect(result.error?.kind).toBe('exception') + expect(result.outputTruncated).toBe(true) + expect(result.sandbox?.denied).toBe(true) }) it('retains admitted logs when the program reports its own output limit', async () => { @@ -447,13 +448,97 @@ describe('Node runtime host failures', () => { h.stdout.end() h.direct.resolve({ exitCode: 0, signal: null }) }) - h.onBoot(() => { h.stdout.write('x'.repeat(1024)) }) + h.onBoot(() => { h.stdout.write('x'.repeat(1024)); h.complete({}) }) const result = await h.start() - expect(result.error?.kind).toBe('output-limit') + expect(result.error).toBeUndefined() + expect(result.outputTruncated).toBe(true) expect(result.output.filter(block => block.type === 'text').map(block => block.text).join('')).toMatch(/^x+$/) expect(Buffer.byteLength(JSON.stringify(result.output.filter(block => block.type === 'text').map(block => block.text)))).toBeLessThanOrEqual(256) }) + describe.each(['stdout', 'stderr'] as const)('overflow while draining %s', (stream) => { + it.each([undefined, { kind: 'exception', message: 'program failed' }] as const)('preserves the completed outcome %j after control closure', async (failure) => { + const h = await setup({ maxOutputBytes: 256 }) + vi.mocked(h.terminate).mockImplementation(() => { + expect(h.control.destroyed).toBe(true) + h[stream].write('x'.repeat(1024)) + h.stdout.end() + h.stderr.end() + h.direct.resolve({ exitCode: 0, signal: null }) + }) + h.onBoot(() => { h.complete(failure === undefined ? {} : { error: failure }) }) + const result = await h.start() + await setImmediate() + expect(result.error).toEqual(failure) + expect(result.outputTruncated).toBe(true) + const text = result.output.filter(block => block.type === 'text').map(block => block.text) + expect(text.join('')).toMatch(/^x+$/) + expect(Buffer.byteLength(JSON.stringify(text))).toBeLessThanOrEqual(256) + expect(h.messages).not.toContainEqual(expect.objectContaining({ m: 'discardOutput' })) + expect(h.terminate).toHaveBeenCalledOnce() + }) + }) + + it('reports a failed output-suppression send while execution is active', async () => { + const h = await setup({ maxOutputBytes: 256 }) + h.onBoot(() => { + vi.spyOn(h.control, 'write').mockImplementation(() => { throw new Error('notification transport failed') }) + h.stdout.write('x'.repeat(1024)) + }) + const result = await h.start() + expect(result.error).toEqual({ kind: 'protocol', message: 'failed to send output-discard notification: notification transport failed' }) + expect(result.outputTruncated).toBe(true) + expect(h.terminate).toHaveBeenCalledOnce() + }) + + it('continues binding calls after notifying the program to suppress output', async () => { + const h = await setup({ maxOutputBytes: 256 }) + const binding = vi.fn(async () => null) + h.receive((message) => { + if (typeof message !== 'object' || message === null) return + if ('m' in message && message.m === 'run') h.stdout.write('x'.repeat(1024)) + if ('m' in message && message.m === 'discardOutput') h.emit(call(1)) + if ('t' in message && message.t === 's') h.complete({}) + }) + const result = await h.start(withBinding(binding)) + expect(binding).toHaveBeenCalledOnce() + expect(result.error).toBeUndefined() + expect(result.outputTruncated).toBe(true) + }) + + it('keeps the transport diagnostic when an output-suppression send closes the channel', async () => { + const h = await setup({ maxOutputBytes: 256 }) + h.onBoot(() => { + vi.spyOn(h.control, 'write').mockImplementation(() => { + const failure = new Error('notification transport failed') + h.control.emit('error', failure) + throw failure + }) + h.stdout.write('x'.repeat(1024)) + }) + const result = await h.start() + expect(result.error).toEqual({ kind: 'worker-exit', message: 'Node process exited (0, signal null); control channel failed: notification transport failed' }) + expect(result.outputTruncated).toBe(true) + expect(h.stdout.destroyed).toBe(true) + expect(h.stderr.destroyed).toBe(true) + }) + + it('preserves cancellation when an output-suppression send rejects during shutdown', async () => { + const h = await setup({ maxOutputBytes: 256 }) + const controller = new AbortController() + h.onBoot(() => { + vi.spyOn(h.control, 'write').mockImplementation(() => { + controller.abort(new Error('caller canceled')) + throw new Error('notification transport failed') + }) + h.stdout.write('x'.repeat(1024)) + }) + const result = await h.start({ ...request, signal: controller.signal }) + expect(result.error).toEqual({ kind: 'abort', message: 'caller canceled' }) + expect(result.outputTruncated).toBe(true) + expect(h.terminate).toHaveBeenCalledOnce() + }) + it.each(['stdout', 'stderr'] as const)('reports a broken raw %s pipe', async (name) => { const h = await setup() h.onBoot(() => { h[name].emit('error', new Error(`${name} closed`)) }) diff --git a/packages/ptc-runtime/ptc-runtime-node/tests/initialization.spec.ts b/packages/ptc-runtime/ptc-runtime-node/tests/initialization.spec.ts index 9955fa29bb..b048d1c045 100644 --- a/packages/ptc-runtime/ptc-runtime-node/tests/initialization.spec.ts +++ b/packages/ptc-runtime/ptc-runtime-node/tests/initialization.spec.ts @@ -154,20 +154,22 @@ describe('Node environment initialization', () => { } }) - it('shares output accounting and initializes again after output overflow', async () => { + it('shares output accounting while preserving initialized state after truncation', async () => { const { run } = await setup({ maxOutputBytes: 256 }, 'globalThis.resource = 42; inspect("x".repeat(120))') const result = await run('inspect("y".repeat(120)); "z".repeat(50)') - expect(result.error?.kind).toBe('output-limit') + expect(result.error).toBeUndefined() + expect(result.outputTruncated).toBe(true) expect(result.output[0]?.type === 'text' ? result.output[0].text : undefined).toBe('x'.repeat(120) + '\n') - expect(result.error?.message).toContain('retained variables were cleared') - expect((await run('resource')).value).toBe(42) + expect(result.value).toBe('z'.repeat(50)) + expect(await run('resource')).toMatchObject({ value: 42, output: [] }) }) - it('does not start the program after initialization exhausts captured output', async () => { + it('starts the program after initialization exhausts captured output', async () => { const { run, cwd } = await setup({ maxOutputBytes: 256 }, 'var fs = await import("node:fs"); inspect("x".repeat(1000))') - const result = await run('fs.writeFileSync("program-started", "unexpected")') - expect(result.error?.kind).toBe('output-limit') - await expect(access(join(cwd, 'program-started'))).rejects.toMatchObject({ code: 'ENOENT' }) + const result = await run('fs.writeFileSync("program-started", "completed")') + expect(result.error).toBeUndefined() + expect(result.outputTruncated).toBe(true) + await expect(access(join(cwd, 'program-started'))).resolves.toBeUndefined() }) it.each([ diff --git a/packages/ptc-runtime/ptc-runtime-node/tests/inspectable-output.spec.ts b/packages/ptc-runtime/ptc-runtime-node/tests/inspectable-output.spec.ts index b3e4004f2b..1a50c24b88 100644 --- a/packages/ptc-runtime/ptc-runtime-node/tests/inspectable-output.spec.ts +++ b/packages/ptc-runtime/ptc-runtime-node/tests/inspectable-output.spec.ts @@ -168,7 +168,8 @@ it('charges inspection text only when emitted and bounds its complete output', a const shown = await runtime.run(runtime.resolve({ program: 'inspect(await tools.read({}));', bindings: binding, discardCompletion: true, })) - expect(shown.error?.kind).toBe('output-limit') + expect(shown.error).toBeUndefined() + expect(shown.outputTruncated).toBe(true) }) it('rejects a non-JSON wrapped binding value instead of replacing it with rendered text', async () => { diff --git a/packages/ptc-runtime/ptc-runtime-node/tests/output-ledger.spec.ts b/packages/ptc-runtime/ptc-runtime-node/tests/output-ledger.spec.ts index 1bbe37be1d..84e23c3784 100644 --- a/packages/ptc-runtime/ptc-runtime-node/tests/output-ledger.spec.ts +++ b/packages/ptc-runtime/ptc-runtime-node/tests/output-ledger.spec.ts @@ -1,71 +1,65 @@ import type { AttachmentId } from '@deepseek-ai/dsh-attachment' import { expect, it } from 'vitest' -import type { PtcOutput } from '@deepseek-ai/dsh-ptc-runtime' +import type { PtcOutput, PtcRunResult } from '@deepseek-ai/dsh-ptc-runtime' import { OutputLedger } from '../src/output-ledger.ts' import { brandString } from '@deepseek-ai/dsh-brand' -it('accounts for exact JSON escaping, separators and optional completion values', () => { +function bytes(result: PtcRunResult): number { + return Buffer.byteLength(JSON.stringify(result.output.map(block => block.type === 'text' ? block.text : block))) + + (result.error ? Buffer.byteLength(JSON.stringify(result.error.message)) + : result.value === undefined ? 0 : Buffer.byteLength(JSON.stringify(result.value))) +} + +it('retains a prefix and gives the completion priority within the combined cap', () => { const ledger = new OutputLedger(20) const output: PtcOutput[] = [] expect(ledger.admit({ type: 'text', text: 'first' }, output)).toBe(true) expect(ledger.admit({ type: 'text', text: 'second' }, output)).toBe(true) expect(ledger.admit({ type: 'text', text: 'third' }, output)).toBe(false) - expect(ledger.success(output)).toEqual({ output: [{ type: 'text', text: 'first' }, { type: 'text', text: 'second' }] }) - expect(ledger.success(output, 1)).toEqual({ output: [{ type: 'text', text: 'first' }, { type: 'text', text: 'second' }], value: 1 }) - expect(ledger.success(output, 'too long').error?.kind).toBe('output-limit') + expect(ledger.success(output)).toEqual({ output, outputTruncated: true }) + expect(ledger.success(output, 1)).toEqual({ output, value: 1, outputTruncated: true }) + expect(ledger.success(output, 'too long')).toEqual({ output: [output[0]], value: 'too long', outputTruncated: true }) + expect(ledger.success(output, 'x'.repeat(20)).error?.kind).toBe('output-limit') }) -it('retains a bounded prefix when logs or a failure diagnostic exceed the limit', () => { - for (const maxBytes of [4, 8, 40, 80]) { - const ledger = new OutputLedger(maxBytes) - const result = ledger.limit(['a', 'b', '你好🙂'.repeat(50)].map(text => ({ type: 'text', text }))) - expect(result.error?.kind).toBe('output-limit') - const bytes = Buffer.byteLength(JSON.stringify(result.output.filter(block => block.type === 'text').map(block => block.text))) + Buffer.byteLength(JSON.stringify(result.error?.message)) - expect(bytes).toBeLessThanOrEqual(maxBytes) +it.each([4, 8, 40, 80])('bounds multibyte output and diagnostics without losing failure kinds at %s bytes', (maxBytes) => { + const ledger = new OutputLedger(maxBytes) + const output: PtcOutput[] = [] + ledger.admit({ type: 'text', text: '你好🙂'.repeat(50) }, output) + const success = ledger.success(output) + expect(success.error).toBeUndefined() + expect(success.outputTruncated).toBe(true) + expect(bytes(success)).toBeLessThanOrEqual(maxBytes) + for (const kind of ['exception', 'timeout', 'abort', 'protocol', 'worker-exit'] as const) { + const failure = ledger.failure(output, { kind, message: '失败🙂'.repeat(50) }) + expect(failure.error?.kind).toBe(kind) + expect(failure.outputTruncated).toBe(true) + expect(bytes(failure)).toBeLessThanOrEqual(maxBytes) } - const ledger = new OutputLedger(80) - expect(ledger.failure([], { kind: 'exception', message: 'short' })).toEqual({ output: [], error: { kind: 'exception', message: 'short' } }) - expect(ledger.failure([], { kind: 'exception', message: 'x'.repeat(100) }).error?.kind).toBe('output-limit') }) +it('leaves fitting output and diagnostics unchanged', () => { + const ledger = new OutputLedger(80) + expect(ledger.success([])).toEqual({ output: [] }) + expect(ledger.failure([], { kind: 'exception', message: 'short' })).toEqual({ output: [], error: { kind: 'exception', message: 'short' } }) + const output: PtcOutput[] = [] + expect(ledger.admit({ type: 'text', text: 'x'.repeat(76) }, output)).toBe(true) + expect(bytes(ledger.success(output))).toBe(80) +}) -it('charges ordered image descriptors and text against one budget', () => { - const attachment = { attachmentId: brandString('sha256:image'), mediaType: 'image/png' as const, bytes: 64, width: 8, height: 4 } - const entry: PtcOutput = { type: 'image', attachment } - const bytes = Buffer.byteLength(JSON.stringify([entry])) - const ledger = new OutputLedger(bytes) +it('keeps whole images in emission order and drops everything after an oversized entry', () => { + const entry: PtcOutput = { type: 'image', attachment: { + attachmentId: brandString('sha256:image'), mediaType: 'image/png', bytes: 64, width: 8, height: 4, + } } + const size = Buffer.byteLength(JSON.stringify([entry])) + const ledger = new OutputLedger(size) const output: PtcOutput[] = [] expect(ledger.admit(entry, output)).toBe(true) expect(ledger.admit(entry, output)).toBe(false) expect(ledger.admit({ type: 'text', text: 'text' }, output)).toBe(false) - expect(ledger.success(output)).toEqual({ output: [entry] }) + expect(ledger.success(output)).toEqual({ output: [entry], outputTruncated: true }) + expect(ledger.success(output, 1)).toEqual({ output: [], value: 1, outputTruncated: true }) const multiple = new OutputLedger(Buffer.byteLength(JSON.stringify([entry, entry]))) expect(multiple.admit(entry, [])).toBe(true) expect(multiple.admit(entry, [])).toBe(true) }) - -it('retains a fitting ordered image prefix with the overflow diagnostic', () => { - const image: PtcOutput = { type: 'image', attachment: { - attachmentId: brandString('sha256:image'), mediaType: 'image/png', bytes: 64, width: 8, height: 4, - } } - const before: PtcOutput = { type: 'text', text: 'before' } - const after: PtcOutput = { type: 'text', text: 'after' } - const maxBytes = Buffer.byteLength(JSON.stringify(['before', image])) + Buffer.byteLength(JSON.stringify('limit')) - const ledger = new OutputLedger(maxBytes, 'limit') - const output: PtcOutput[] = [] - expect(ledger.admit(before, output)).toBe(true) - expect(ledger.admit(image, output)).toBe(true) - for (const result of [ - ledger.limit([...output, after]), - ledger.success(output, 'x'.repeat(maxBytes)), - ledger.failure(output, { kind: 'exception', message: 'x'.repeat(maxBytes) }), - ]) { - expect(result).toEqual({ output: [before, image], error: { kind: 'output-limit', message: 'limit' } }) - const bytes = Buffer.byteLength(JSON.stringify(result.output.map(block => block.type === 'text' ? block.text : block))) - + Buffer.byteLength(JSON.stringify(result.error!.message)) - expect(bytes).toBe(maxBytes) - } - expect(new OutputLedger(maxBytes - 1, 'limit').limit([before, image, after])).toEqual({ - output: [before], error: { kind: 'output-limit', message: 'limit' }, - }) -}) diff --git a/packages/ptc-runtime/ptc-runtime-node/tests/output.spec.ts b/packages/ptc-runtime/ptc-runtime-node/tests/output.spec.ts index 1ab9a310d9..4a8cd760bd 100644 --- a/packages/ptc-runtime/ptc-runtime-node/tests/output.spec.ts +++ b/packages/ptc-runtime/ptc-runtime-node/tests/output.spec.ts @@ -9,6 +9,7 @@ import { brandString } from '@deepseek-ai/dsh-brand' const modes = [ { executionMode: 'per-call', scriptPersistence: false }, { executionMode: 'persistent-in-memory', scriptPersistence: false, replScoped: false }, + { executionMode: 'persistent-in-memory', scriptPersistence: false, replScoped: true }, { executionMode: 'vm-script', scriptPersistence: false }, { executionMode: 'vm-script', scriptPersistence: true }, ] as const @@ -224,6 +225,40 @@ describe.each(modes)('program output in $executionMode with retention $scriptPer await runtime.release(stateOwner) }) + it('finishes actions after overflow and preserves retained variables for the next run', async () => { + const { runtime } = await mountRuntime(new Context(), { ...mode, maxOutputBytes: 64 }) + const stateOwner = {} + const calls: unknown[] = [] + const result = await runtime.run(runtime.resolve({ + program: 'var retained = 1; await tools.action("before"); inspect("x".repeat(512)); await tools.action("after"); retained = 42; inspect("omitted");', + bindings: [{ global: 'tools', functions: { action: async (value) => { calls.push(value); return null } } }], + stateOwner, discardCompletion: true, + })) + expect(result.error).toBeUndefined() + expect(result.outputTruncated).toBe(true) + expect(calls).toEqual(['before', 'after']) + expect(result.output).toEqual([{ type: 'text', text: 'x'.repeat(60) }]) + if (runtime.retainsState) { + const next = await runtime.run(runtime.resolve({ program: 'inspect(retained)', bindings: [], stateOwner, discardCompletion: true })) + expect(next.error).toBeUndefined() + expect(next.outputTruncated).toBeUndefined() + expect(next.output).toEqual([{ type: 'text', text: '42\n' }]) + } + }) + + it('reports an exception after output fills the budget', async () => { + const { runtime } = await mountRuntime(new Context(), { ...mode, maxOutputBytes: 64 }) + const result = await runtime.run(runtime.resolve({ + program: 'inspect("x".repeat(512)); await tools.barrier({}); throw "failure after overflow"', + bindings: [{ global: 'tools', functions: { barrier: async () => null } }], discardCompletion: true, + })) + const message = mode.executionMode === 'persistent-in-memory' && !mode.replScoped + ? "Uncaught 'failure after overflow'" : 'failure after overflow' + expect(result.error).toEqual({ kind: 'exception', message }) + expect(result.outputTruncated).toBe(true) + expect(result.output[0]).toEqual({ type: 'text', text: 'x'.repeat(60 - Buffer.byteLength(JSON.stringify(message))) }) + }) + it('retains an ordered text and image prefix when output overflows', async () => { const { runtime } = await mountRuntime(new Context(), { ...mode, maxOutputBytes: 256 }) const image = new PtcImage('/images/selected.png', { attachmentId: brandString('sha256:selected'), mediaType: 'image/png', bytes: 64, width: 8, height: 4 }) @@ -232,7 +267,8 @@ describe.each(modes)('program output in $executionMode with retention $scriptPer bindings: [{ global: 'tools', functions: { image: () => Promise.resolve(image) } }], discardCompletion: true, })) - expect(result.error?.kind).toBe('output-limit') + expect(result.error).toBeUndefined() + expect(result.outputTruncated).toBe(true) expect(result.output[0]).toEqual({ type: 'text', text: 'before\n' }) expect(result.output[1]).toEqual({ type: 'image', attachment: image.attachment }) expect(result.output[2]).toEqual({ type: 'text', text: expect.stringMatching(/^x+$/) as string }) @@ -245,7 +281,8 @@ describe.each(modes)('program output in $executionMode with retention $scriptPer const quiet = await runtime.run(runtime.resolve({ program: 'await tools.image({})', bindings, discardCompletion: true })) expect(quiet.error).toBeUndefined() const selected = await runtime.run(runtime.resolve({ program: 'inspect(await tools.image({}))', bindings, discardCompletion: true })) - expect(selected.error?.kind).toBe('output-limit') + expect(selected.error).toBeUndefined() + expect(selected.outputTruncated).toBe(true) expect(selected.output).toEqual([]) }) @@ -254,7 +291,8 @@ describe.each(modes)('program output in $executionMode with retention $scriptPer const result = await runtime.run(runtime.resolve({ program: 'inspect({ value: "x".repeat(512) })', bindings: [], discardCompletion: true, })) - expect(result.error?.kind).toBe('output-limit') + expect(result.error).toBeUndefined() + expect(result.outputTruncated).toBe(true) const prefix = result.output[0] if (prefix?.type !== 'text') throw new Error('Expected an inspected text prefix') expect(prefix.text).toMatch(/^\{\s+value: 'x+/) diff --git a/packages/ptc-runtime/ptc-runtime-node/tests/persistent-host.spec.ts b/packages/ptc-runtime/ptc-runtime-node/tests/persistent-host.spec.ts index 606de8b92e..e51b3118f4 100644 --- a/packages/ptc-runtime/ptc-runtime-node/tests/persistent-host.spec.ts +++ b/packages/ptc-runtime/ptc-runtime-node/tests/persistent-host.spec.ts @@ -223,7 +223,7 @@ describe('persistent PTC host protocol', () => { expect(h.waitForExit).toHaveBeenCalledTimes(1) }) - it.each([{ error: { kind: 'other', message: '' } }, { error: { kind: 'exception', message: 1 } }])('rejects malformed results %j', async (raw) => { + it.each([{ outputTruncated: 'yes' }, { error: { kind: 'other', message: '' } }, { error: { kind: 'exception', message: 1 } }])('rejects malformed results %j', async (raw) => { const h = await setup() h.onBoot(() => { h.complete(raw) }) expect((await h.start()).error?.kind).toBe('protocol') @@ -248,8 +248,17 @@ describe('persistent PTC host protocol', () => { h.onBoot(() => { h.complete({ value: 'bad' }) }) expect((await h.start()).error?.kind).toBe('invalid-output') const limited = await setup({ maxOutputBytes: 30 }) - limited.onBoot(() => { limited.emit({ t: 'q', m: 'log', a: ['x'.repeat(100)] }) }) - expect((await limited.start()).error?.kind).toBe('output-limit') + limited.onBoot(() => { limited.emit({ t: 'q', m: 'log', a: ['x'.repeat(100)] }); limited.complete({ value: encodePtcJsonWire(42) }) }) + expect(await limited.start()).toMatchObject({ value: 42, outputTruncated: true }) + }) + + it.each([undefined, encodePtcJsonWire(42), 'invalid wire'])('preserves a reported truncation flag with completion %j', async (value) => { + const h = await setup() + h.onBoot(() => { h.complete({ value, outputTruncated: true }) }) + const result = await h.start() + expect(result.outputTruncated).toBe(true) + expect(result.error?.kind).toBe(value === 'invalid wire' ? 'invalid-output' : undefined) + expect(result.value).toBe(Array.isArray(value) ? 42 : undefined) }) it('returns current binding successes, exceptions and unavailable bindings', async () => { @@ -314,24 +323,25 @@ describe('persistent PTC host protocol', () => { expect(h.terminate).not.toHaveBeenCalled() }) - it('clears retained resources when final diagnostic accounting detects an overflow', async () => { + it('preserves retained resources and the failure kind when a diagnostic is truncated', async () => { const h = await setup({ maxOutputBytes: 100 }) h.onBoot(() => { h.complete({ error: { kind: 'exception', message: 'x'.repeat(1000) } }) }) const result = await h.start() - expect(result.error?.kind).toBe('output-limit') - expect(result.error?.message).toContain('retained variables were cleared') - expect(h.terminate).toHaveBeenCalledTimes(1) + expect(result.error?.kind).toBe('exception') + expect(result.outputTruncated).toBe(true) + expect(result.error?.message).toBe('x'.repeat(96)) + expect(h.terminate).not.toHaveBeenCalled() }) - it('keeps the first outcome when tagged output overflows beside a terminal frame', async () => { + it('keeps the completion when tagged output overflows beside a terminal frame', async () => { const h = await setup({ maxOutputBytes: 100 }) h.onBoot(() => { h.complete({ value: encodePtcJsonWire(42) }) queueMicrotask(() => { h.emit({ t: 'q', m: 'log', a: ['x'.repeat(1000)] }) }) }) - expect((await h.start()).error?.kind).toBe('output-limit') + expect(await h.start()).toMatchObject({ value: 42, outputTruncated: true }) await setImmediate() - expect(h.terminate).toHaveBeenCalledTimes(1) + expect(h.terminate).not.toHaveBeenCalled() }) it('reports the exit result when the control pipe ends beside process completion', async () => { @@ -420,26 +430,20 @@ describe('persistent PTC host protocol', () => { it('reports failed managed cleanup and waits for both exit and pipe drain', async () => { const h = await setup() h.waitForExit.mockRejectedValue(new Error('cleanup failed')) - h.onBoot(() => { h.emit({ t: 'q', m: 'outputLimit', a: [] }) }) + h.onBoot(() => { h.emit({ t: 'q', m: 'log', a: [42] }) }) expect((await h.start()).error?.message).toContain('cleanup failed') }) - it.each([ - { maxOutputBytes: 38, kind: 'worker-exit' }, - { maxOutputBytes: 4, kind: 'output-limit' }, - ])('bounds cleanup failure after parse diagnostics overflow a $maxOutputBytes-byte budget', async ({ maxOutputBytes, kind }) => { + it.each([38, 4])('preserves the exception kind when parse diagnostics exceed %s bytes', async (maxOutputBytes) => { const h = await setup({ maxOutputBytes }) h.onBoot(() => { h.complete({}) }) - expect(await h.start()).toMatchObject({ output: [] }) - h.waitForExit.mockRejectedValue(new Error('x')) + await h.start() const result = await h.runtime.run(h.runtime.resolve({ ...request, program: 'return 1' })) - expect(result.error?.kind).toBe(kind) - if (kind === 'worker-exit') expect(result.error?.message).toContain('cleanup failed: x') - const bytes = Buffer.byteLength(JSON.stringify(result.output.filter(block => block.type === 'text').map(block => block.text))) + Buffer.byteLength(JSON.stringify(result.error?.message)) - expect(bytes).toBeLessThanOrEqual(maxOutputBytes) - expect(h.terminate).toHaveBeenCalledTimes(1) - expect(h.waitForExit).toHaveBeenCalledTimes(1) - await expect(h.runtime.release(request.stateOwner!)).rejects.toThrow('x') + expect(result.error?.kind).toBe('exception') + expect(result.outputTruncated).toBe(true) + expect(Buffer.byteLength(JSON.stringify(result.error?.message)) + 2).toBeLessThanOrEqual(maxOutputBytes) + expect(h.terminate).not.toHaveBeenCalled() + expect(h.waitForExit).not.toHaveBeenCalled() }) it('rejects invalid resolved inputs and deployment bounds', async () => { @@ -609,23 +613,6 @@ it('retries process observation before releasing an owner after cleanup fails', } finally { reported.mockRestore() } }) -it('reserves the owner while parse-output overflow releases its environment', async () => { - const h = await setup({ maxOutputBytes: 32 }) - const cleanup = Promise.withResolvers() - const stopped = Promise.withResolvers() - h.onBoot(() => { h.complete({}) }) - await h.start() - h.waitForExit.mockImplementation(async () => { cleanup.resolve(true); return stopped.promise }) - const pending = h.runtime.run(h.runtime.resolve({ ...request, program: 'return 1' })) - try { - await cleanup.promise - await expect(h.runtime.run(h.runtime.resolve(request))).rejects.toThrow('does not accept concurrent') - expect(h.spawn).toHaveBeenCalledOnce() - stopped.resolve(true) - expect((await pending).error?.kind).toBe('output-limit') - } finally { stopped.resolve(true); await pending } -}) - it.each([true, false])('classifies confined process spawn failure with runner evidence %s', async (runnerFailure) => { const h = await setup() const runner = '/missing-ptc-sandbox-runner' diff --git a/packages/ptc-runtime/ptc-runtime-node/tests/persistent-process.spec.ts b/packages/ptc-runtime/ptc-runtime-node/tests/persistent-process.spec.ts index 5255d8bea2..f7c970cce2 100644 --- a/packages/ptc-runtime/ptc-runtime-node/tests/persistent-process.spec.ts +++ b/packages/ptc-runtime/ptc-runtime-node/tests/persistent-process.spec.ts @@ -81,15 +81,15 @@ it('does not adopt a REPL completion Promise without explicit await', async () = expect(decodePtcJsonWire((await h.run('await Promise.resolve(42)')).value)).toBe(42) }) -it('prevents the program after initialization exceptions and output overflow', async () => { +it('prevents the program after initialization exceptions but continues after output truncation', async () => { const h = await setup() await h.run('var entered = 0;') expect((await h.run('entered++', [], 4096, 'const =')).error?.kind).toBe('exception') const failed = await h.run('entered++', [], 1024, 'throw "initialization failed"') expect(failed.error?.kind).toBe('exception') expect(failed.error?.message).toContain('initialization failed') - expect((await h.run('entered++', [], 64, 'inspect("x".repeat(100))')).error?.kind).toBe('output-limit') - expect(decodePtcJsonWire((await h.run('entered')).value)).toBe(0) + expect((await h.run('entered++', [], 64, 'inspect("x".repeat(100))')).error).toBeUndefined() + expect(decodePtcJsonWire((await h.run('entered')).value)).toBe(1) }) it('does not resume the program after initialization reports an asynchronous failure', async () => { diff --git a/packages/ptc-runtime/ptc-runtime-node/tests/persistent.spec.ts b/packages/ptc-runtime/ptc-runtime-node/tests/persistent.spec.ts index e7143ec963..f55a5f6426 100644 --- a/packages/ptc-runtime/ptc-runtime-node/tests/persistent.spec.ts +++ b/packages/ptc-runtime/ptc-runtime-node/tests/persistent.spec.ts @@ -354,25 +354,25 @@ describe.each([ expect((await run('42', { timeoutMs: null })).value).toBe(42) }) - it.each(['throw new Error("long diagnostic ".repeat(1000))', '"large completion".repeat(1000)'])('clears retained state after a final output overflow: %s', async (program) => { + it.each([['throw new Error("long diagnostic ".repeat(1000))', 'exception'], ['"large completion".repeat(1000)', 'output-limit']])('retains state after oversized terminal output: %s', async (program, kind) => { const { run } = await setup({ maxOutputBytes: 100 }) await run('let retained = true;') const result = await run(program) - expect(result.error?.kind).toBe('output-limit') - expect(result.error?.message).toContain('retained variables were cleared') + expect(result.error?.kind).toBe(kind) const outputBytes = Buffer.byteLength(JSON.stringify(result.output.filter(block => block.type === 'text').map(block => block.text))) + Buffer.byteLength(JSON.stringify(result.error?.message)) expect(outputBytes).toBeLessThanOrEqual(100) - expect((await run('typeof retained')).value).toBe('undefined') + expect((await run('typeof retained')).value).toBe('boolean') }) - it('bounds type-stripping diagnostics and clears the owner after a parse-output overflow', async () => { + it('bounds type-stripping diagnostics without clearing retained variables', async () => { const { run } = await setup({ maxOutputBytes: 32 }) await run('let retained = true;') const result = await run('const =') - expect(result.error?.kind).toBe('output-limit') + expect(result.error?.kind).toBe('exception') + expect(result.outputTruncated).toBe(true) const outputBytes = Buffer.byteLength(JSON.stringify(result.output.filter(block => block.type === 'text').map(block => block.text))) + Buffer.byteLength(JSON.stringify(result.error?.message)) expect(outputBytes).toBeLessThanOrEqual(32) - expect((await run('typeof retained')).value).toBe('undefined') + expect((await run('typeof retained')).value).toBe('boolean') }) it('accepts an embedded carrier for a packaged host', async () => { @@ -389,10 +389,10 @@ describe.each([ } }) - it('bounds output and clears state after an overflow', async () => { + it('bounds output and retains state after truncation', async () => { const { run } = await setup({ maxOutputBytes: 100 }) - expect((await run('let retained = true; inspect("x".repeat(1000))')).error?.kind).toBe('output-limit') - expect((await run('typeof retained')).value).toBe('undefined') + expect(await run('let retained = true; inspect("x".repeat(1000))')).toMatchObject({ outputTruncated: true }) + expect((await run('typeof retained')).value).toBe('boolean') }) }) diff --git a/packages/ptc-runtime/ptc-runtime-node/tests/process-main.spec.ts b/packages/ptc-runtime/ptc-runtime-node/tests/process-main.spec.ts index ec808f2022..4a247f63a4 100644 --- a/packages/ptc-runtime/ptc-runtime-node/tests/process-main.spec.ts +++ b/packages/ptc-runtime/ptc-runtime-node/tests/process-main.spec.ts @@ -45,6 +45,17 @@ async function setup(limit = 4096, namespaces: ProgramBootData['namespaces'] = [ return { child, host, state, nativeEnvironment, methods, peer, main, logs, run } } +it('discards output on host request without cancelling binding calls or the next evaluation', async () => { + const h = await setup() + await h.peer.discardOutput() + h.methods.invoke = async () => { await h.peer.discardOutput(); return { value: encodePtcJsonWire(42) } } + const result = await h.run('inspect("before"); const value = await tools.echo({}); inspect("dropped"); return value') + expect(decodePtcJsonWire(result.value)).toBe(42) + expect(h.logs).toEqual(['before\n']) + await h.run('inspect("next")') + expect(h.logs).toEqual(['before\n', 'next\n']) +}) + it('clears the environment and returns a binding result after captured output', async () => { const h = await setup() h.methods.invoke = async (_global, _name, wire) => { @@ -127,8 +138,8 @@ it.each([4, 64])('reports exhausted output accounting during the run with a %s-b const h = await setup() const limited = vi.fn() h.methods.outputLimit = limited - expect(await h.run('inspect("x".repeat(100)); return null', maxOutputBytes)) - .toEqual({ error: { kind: 'output-limit', message: `outer output exceeded ${maxOutputBytes} bytes` } }) + expect(await h.run('inspect("x".repeat(100)); return 0', maxOutputBytes)) + .toEqual({ value: encodePtcJsonWire(0) }) if (maxOutputBytes === 4) expect(h.logs).toEqual([]) await vi.waitFor(() => { expect(limited).toHaveBeenCalledOnce() }) }) @@ -148,7 +159,10 @@ it.each([ it.each(['throw "x".repeat(1_000_000)', 'throw new Error("x".repeat(1_000_000))'])('bounds large diagnostics for %s', async (code) => { const h = await setup() - expect(await h.run(code, 64)).toEqual({ error: { kind: 'output-limit', message: 'outer output exceeded 64 bytes' } }) + const result = await h.run(code, 64) + expect(result.error?.kind).toBe('exception') + expect(result.outputTruncated).toBe(true) + expect(Buffer.byteLength(JSON.stringify(result.error?.message))).toBeLessThanOrEqual(62) }) it.each([ diff --git a/packages/ptc-runtime/ptc-runtime-node/tests/runtime.spec.ts b/packages/ptc-runtime/ptc-runtime-node/tests/runtime.spec.ts index b133db93aa..778a70045f 100644 --- a/packages/ptc-runtime/ptc-runtime-node/tests/runtime.spec.ts +++ b/packages/ptc-runtime/ptc-runtime-node/tests/runtime.spec.ts @@ -154,8 +154,10 @@ describe('Node program process', () => { it('enforces the combined output cap', async () => { const { run } = await setup({ maxOutputBytes: 80 }) const result = await run({ program: 'inspect("x".repeat(500)); return 42;', bindings: [] }) - expect(result.error?.kind).toBe('output-limit') - const bytes = Buffer.byteLength(JSON.stringify(result.output.filter(block => block.type === 'text').map(block => block.text))) + Buffer.byteLength(JSON.stringify(result.error?.message)) + expect(result.error).toBeUndefined() + expect(result.value).toBe(42) + expect(result.outputTruncated).toBe(true) + const bytes = Buffer.byteLength(JSON.stringify(result.output.filter(block => block.type === 'text').map(block => block.text))) + Buffer.byteLength(JSON.stringify(result.value)) expect(bytes).toBeLessThanOrEqual(80) }) @@ -338,8 +340,9 @@ it('preserves empty inspected entries and bounds native output overflow', async const lines = await run({ program: 'inspect("a"); inspect(""); inspect("b")', bindings: [] }) expect(lines.output.filter(block => block.type === 'text').map(block => block.text)).toEqual(['a\n', '\n', 'b\n']) const overflow = await run({ program: 'const fs=await import("node:fs"); fs.writeSync(1,"HEAD-"+"x".repeat(100000));', bindings: [] }) - expect(overflow.error?.kind).toBe('output-limit') + expect(overflow.error).toBeUndefined() + expect(overflow.outputTruncated).toBe(true) expect(overflow.output.filter(block => block.type === 'text').map(block => block.text).join('')).toContain('HEAD-') - const bytes = Buffer.byteLength(JSON.stringify(overflow.output.filter(block => block.type === 'text').map(block => block.text))) + Buffer.byteLength(JSON.stringify(overflow.error?.message)) + const bytes = Buffer.byteLength(JSON.stringify(overflow.output.filter(block => block.type === 'text').map(block => block.text))) expect(bytes).toBeLessThanOrEqual(100) }) diff --git a/packages/ptc-runtime/ptc-runtime-node/tests/scoped-repl-mode.spec.ts b/packages/ptc-runtime/ptc-runtime-node/tests/scoped-repl-mode.spec.ts index 26a2159eb9..d9be6dc722 100644 --- a/packages/ptc-runtime/ptc-runtime-node/tests/scoped-repl-mode.spec.ts +++ b/packages/ptc-runtime/ptc-runtime-node/tests/scoped-repl-mode.spec.ts @@ -42,7 +42,7 @@ it('advertises retained scoped REPL syntax with its complete model guidance', as + "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. ' + + '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. ' diff --git a/packages/ptc-runtime/ptc-runtime-node/tests/timeout.spec.ts b/packages/ptc-runtime/ptc-runtime-node/tests/timeout.spec.ts index 2c77039596..cabaa4bf31 100644 --- a/packages/ptc-runtime/ptc-runtime-node/tests/timeout.spec.ts +++ b/packages/ptc-runtime/ptc-runtime-node/tests/timeout.spec.ts @@ -112,6 +112,29 @@ async function retainedChild(config: Config = {}) { } describe.each(['timeout', 'abort'] as const)('retained %s', (action) => { + it('continues after output overflow until the original stop condition occurs', async () => { + const h = await retainedChild({ maxOutputBytes: 128 }) + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) + const pending = h.start() + try { + await h.booted.promise + h.emit({ t: 'q', m: 'log', a: ['x'.repeat(1024)] }) + await vi.advanceTimersByTimeAsync(0) + expect(h.messages).toContainEqual({ t: 'q', m: 'discardOutput', a: [] }) + expect(h.messages).not.toContainEqual({ t: 'q', m: 'revoke', a: [] }) + expect(h.terminate).not.toHaveBeenCalled() + if (action === 'timeout') await vi.advanceTimersByTimeAsync(100) + else { h.controller.abort(); await vi.advanceTimersByTimeAsync(0) } + expect(h.messages).toContainEqual({ t: 'q', m: 'revoke', a: [] }) + h.complete({}) + const result = await pending + expect(result.error?.kind).toBe(action) + expect(result.error?.message).toContain('retained variables were preserved') + expect(result.outputTruncated).toBe(true) + expect(h.terminate).not.toHaveBeenCalled() + } finally { h.controller.abort(); h.complete({}); await pending; vi.useRealTimers() } + }) + it.each(['missing completion', 'rejection', 'malformed completion'] as const)('terminates after %s and recreates the environment', async (failure) => { const h = await retainedChild() vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) @@ -237,7 +260,7 @@ it('terminates when cancellation follows control-channel closure', async () => { } finally { await h.runtime.release(h.request.stateOwner) } }) -it('terminates when the final stop diagnostic exceeds the output budget', async () => { +it('preserves the timeout kind and retained state when its diagnostic is truncated', async () => { const h = await retainedChild({ maxOutputBytes: 70 }) vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) try { @@ -245,8 +268,10 @@ it('terminates when the final stop diagnostic exceeds the output budget', async await h.booted.promise await vi.advanceTimersByTimeAsync(100) h.complete({}) - expect((await pending).error?.kind).toBe('output-limit') - expect(h.terminate).toHaveBeenCalledOnce() + const result = await pending + expect(result.error?.kind).toBe('timeout') + expect(result.outputTruncated).toBe(true) + expect(h.terminate).not.toHaveBeenCalled() } finally { await h.runtime.release(h.request.stateOwner); vi.useRealTimers() } }) diff --git a/packages/ptc-runtime/ptc-runtime/README.i18n.yaml b/packages/ptc-runtime/ptc-runtime/README.i18n.yaml index 737cc6e6ad..6823c0b9de 100644 --- a/packages/ptc-runtime/ptc-runtime/README.i18n.yaml +++ b/packages/ptc-runtime/ptc-runtime/README.i18n.yaml @@ -27,8 +27,8 @@ en: b770e26d4e3906d3 zh: 97e6a4ecb7dc15f2 /deepseek-ai-dsh-ptc-runtime/use-this-package/what-can-go-wrong: - en: 35129568fa436d64 - zh: 0f4138ad427ef486 + en: 88ab4ad5b18ad4b7 + zh: 9768b8444a5b9005 /deepseek-ai-dsh-ptc-runtime/understand-the-implementation: en: 686d570f5e669fa4 zh: 2075cf27c30f251a diff --git a/packages/ptc-runtime/ptc-runtime/README.md b/packages/ptc-runtime/ptc-runtime/README.md index f9adeb31a4..df3c638879 100644 --- a/packages/ptc-runtime/ptc-runtime/README.md +++ b/packages/ptc-runtime/ptc-runtime/README.md @@ -61,7 +61,7 @@ Binding-global and error-class names must match `[A-Za-z_$][A-Za-z0-9_$]*` and e ### What can go wrong -Failures arrive as `result.error` with an orthogonal `kind`: `exception`, `timeout`, `abort`, `worker-exit`, `invalid-output`, `output-limit`, `protocol` or `sandbox-unavailable`. Providers return applicable `result.sandbox` facts separately from success or failure. Invalid or unsupported execution options fail during `resolve`; `run` rejects caller misuse, such as unresolved inputs, invalid binding names or a call after disposal. Contract misuse rejects with `PtcRuntimeError`: `PTC_RUNTIME_INVALID_ARGUMENT` for an invalid request or spec, `PTC_RUNTIME_UNAVAILABLE` after disposal or while a retained environment's cleanup is incomplete, and `PTC_RUNTIME_CONFLICT` for a concurrent run for one owner or a retained environment launched under another sandbox policy. +Providers mark truncated captured output or diagnostics with `result.outputTruncated`; this flag does not imply execution failure. Required completion values are never truncated into successful results. Failures arrive as `result.error` with an orthogonal `kind`: `exception`, `timeout`, `abort`, `worker-exit`, `invalid-output`, `output-limit`, `protocol` or `sandbox-unavailable`. Providers return applicable `result.sandbox` facts separately from success or failure. Invalid or unsupported execution options fail during `resolve`; `run` rejects caller misuse, such as unresolved inputs, invalid binding names or a call after disposal. Contract misuse rejects with `PtcRuntimeError`: `PTC_RUNTIME_INVALID_ARGUMENT` for an invalid request or spec, `PTC_RUNTIME_UNAVAILABLE` after disposal or while a retained environment's cleanup is incomplete, and `PTC_RUNTIME_CONFLICT` for a concurrent run for one owner or a retained environment launched under another sandbox policy. ----- diff --git a/packages/ptc-runtime/ptc-runtime/README.zh.md b/packages/ptc-runtime/ptc-runtime/README.zh.md index 2358fe3c6c..596897514e 100644 --- a/packages/ptc-runtime/ptc-runtime/README.zh.md +++ b/packages/ptc-runtime/ptc-runtime/README.zh.md @@ -61,7 +61,7 @@ binding-global 与 error-class 名称必须匹配 `[A-Za-z_$][A-Za-z0-9_$]*`, ### 可能出什么问题 -失败以 `result.error` 返回,带正交的 `kind`:`exception`、`timeout`、`abort`、`worker-exit`、`invalid-output`、`output-limit`、`protocol` 或 `sandbox-unavailable`。提供方在成功或失败之外,单独返回适用的 `result.sandbox` 事实。无效或不支持的执行选项在 `resolve` 期间失败;`run` 拒绝调用方误用,例如未解析输入、无效绑定名或资源释放后的调用。契约误用以 `PtcRuntimeError` 拒绝:无效的请求或 spec 为 `PTC_RUNTIME_INVALID_ARGUMENT`,资源释放后或保留环境清理未完成时为 `PTC_RUNTIME_UNAVAILABLE`,同一所有者的并发运行或保留环境以其他沙箱策略启动时为 `PTC_RUNTIME_CONFLICT`。 +提供方通过 `result.outputTruncated` 标记捕获输出或诊断被截断;该标记不表示执行失败。要求返回的完成值不会被截断为成功结果。失败以 `result.error` 返回,带正交的 `kind`:`exception`、`timeout`、`abort`、`worker-exit`、`invalid-output`、`output-limit`、`protocol` 或 `sandbox-unavailable`。提供方在成功或失败之外,单独返回适用的 `result.sandbox` 事实。无效或不支持的执行选项在 `resolve` 期间失败;`run` 拒绝调用方误用,例如未解析输入、无效绑定名或资源释放后的调用。契约误用以 `PtcRuntimeError` 拒绝:无效的请求或 spec 为 `PTC_RUNTIME_INVALID_ARGUMENT`,资源释放后或保留环境清理未完成时为 `PTC_RUNTIME_UNAVAILABLE`,同一所有者的并发运行或保留环境以其他沙箱策略启动时为 `PTC_RUNTIME_CONFLICT`。 ----- diff --git a/packages/ptc-runtime/ptc-runtime/src/types.ts b/packages/ptc-runtime/ptc-runtime/src/types.ts index afe402c4f2..042d5de6f4 100644 --- a/packages/ptc-runtime/ptc-runtime/src/types.ts +++ b/packages/ptc-runtime/ptc-runtime/src/types.ts @@ -139,7 +139,7 @@ export interface PtcRunSandbox { * - `'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. */ @@ -172,6 +172,8 @@ export 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 } diff --git a/packages/session-query/session-query/src/cold-read.ts b/packages/session-query/session-query/src/cold-read.ts index f86a11a4e4..7ca77356e5 100644 --- a/packages/session-query/session-query/src/cold-read.ts +++ b/packages/session-query/session-query/src/cold-read.ts @@ -18,9 +18,10 @@ export interface ColdSessionLog { } /** - * Read one complete stored session log without taking ownership or mutating - * storage: open a read handle, read the validated contiguous log, close the - * handle, and append `interruptedTurnClosers` so a log whose writer crashed + * Read one complete stored session log without retaining write ownership. + * The backend may import legacy history before returning the read handle. + * Read the validated contiguous log, close the handle, and append + * `interruptedTurnClosers` so a log whose writer crashed * mid-turn folds as a balanced transcript. Backend failures propagate * unmapped — each caller owns its error taxonomy. * @param persistence - the mounted persistence service. diff --git a/packages/session/session-persistence-jsonl/README.i18n.yaml b/packages/session/session-persistence-jsonl/README.i18n.yaml index 03e90dcc66..e17b315418 100644 --- a/packages/session/session-persistence-jsonl/README.i18n.yaml +++ b/packages/session/session-persistence-jsonl/README.i18n.yaml @@ -18,8 +18,8 @@ en: d6112142a705ec43 zh: f0914d9e37216f97 /deepseek-ai-dsh-session-persistence-jsonl/use-this-package/when-to-choose-it: - en: 37c10302bbbde268 - zh: 3d5c027bac868efd + en: 8fca7647035f8795 + zh: 0bfb12da95611091 /deepseek-ai-dsh-session-persistence-jsonl/use-this-package/minimal-configuration: en: b6c2f0f11f2fa9cf zh: 9fac03fcbe5bbad4 diff --git a/packages/session/session-persistence-jsonl/README.md b/packages/session/session-persistence-jsonl/README.md index df20957cc0..48620b7a73 100644 --- a/packages/session/session-persistence-jsonl/README.md +++ b/packages/session/session-persistence-jsonl/README.md @@ -29,7 +29,7 @@ Mount this backend when a composition needs durable sessions backed by per-sessi ### When to choose it -Choose this backend when consumers benefit from one artifact per session — navigation, external tooling, or a raw line-readable log. It is the sole first-party Session-persistence provider. The backend keeps sessions under a deployment-controlled root: project-local, shared, temporary, or centralized. +Choose this backend when consumers benefit from one artifact per session — navigation, external tooling, or a raw line-readable log. Shipped profiles use this provider by default. The [SQLite provider](../session-persistence-sqlite/README.md) is a separate plugin that imports existing JSONL history on first open. The backend keeps sessions under a deployment-controlled root: project-local, shared, temporary, or centralized. ### Minimal configuration diff --git a/packages/session/session-persistence-jsonl/README.zh.md b/packages/session/session-persistence-jsonl/README.zh.md index 8c82392627..90cc8afc89 100644 --- a/packages/session/session-persistence-jsonl/README.zh.md +++ b/packages/session/session-persistence-jsonl/README.zh.md @@ -29,7 +29,7 @@ kind: "package-reference" ### 何时选择 -当消费方受益于每会话一份产物——导航、外部工具或可逐行读取的原始日志——时选择此后端。它是唯一的第一方会话持久化提供方。后端把会话保存在部署控制的根下:项目本地、共享、临时或集中式。 +当消费方受益于每会话一份产物——导航、外部工具或可逐行读取的原始日志——时选择此后端。内置 profile 默认使用此提供者。[SQLite 提供者](../session-persistence-sqlite/README.zh.md) 是独立插件,在首次打开时导入现有 JSONL 历史。后端把会话保存在部署控制的根下:项目本地、共享、临时或集中式。 ### 最小配置 diff --git a/packages/session/session-persistence-jsonl/src/index.ts b/packages/session/session-persistence-jsonl/src/index.ts index 79b549bcd2..c77401556e 100644 --- a/packages/session/session-persistence-jsonl/src/index.ts +++ b/packages/session/session-persistence-jsonl/src/index.ts @@ -58,6 +58,18 @@ import { type PreparedJsonlMigration, } from './generation.ts' +/** Logical JSONL history retained until its destination commits under write ownership. */ +interface LegacySessionSnapshot { + readonly header: SessionHeader + readonly inheritedEventCount: SessionLogOffsetType + readonly events: readonly SessionEvent[] +} + +/** Prepared legacy history whose related sources are checked before destination publication. */ +interface PreparedLegacySession { + commit(publish: (snapshot: LegacySessionSnapshot) => Promise): Promise +} + export type { JsonlCompression } from './format.ts' /** @@ -305,15 +317,12 @@ function waitWithAbort(operation: Promise, signal?: AbortSignal): Promise< } /** - * The JSONL backend registered as `ctx.sessionPersistence` by the plugin. + * JSONL Session persistence with historical-format migration. * Sessions materialize lazily: a created session is * visible to this process immediately, reaches disk on its first append or * flush, and never existed if the process crashes before that. */ -class JsonlSessionPersistence extends SessionPersistence { - /** Backend label for diagnostics and effects; shadows `Service.name` without changing the service key. */ - override readonly name = 'session-persistence-jsonl' - +export class JsonlSessionPersistence extends SessionPersistence { private root: string private compression: JsonlCompression /** @@ -348,7 +357,13 @@ class JsonlSessionPersistence extends SessionPersistence { /** One joinable decode/migration operation per selected historical Session file revision. */ private readonly migrationPreparations = new Map() - constructor(ctx: Context, public config: Config, private readonly tracker: JsonlBackendTracker) { + /** + * @param ctx - context used for scoped diagnostics and filesystem reads. + * @param config - JSONL root, physical encoding, and listing concurrency. + * @param tracker - handle bookkeeping; omitted creates bookkeeping for legacy reads. + */ + constructor(ctx: Context, public config: Config, + private readonly tracker = new JsonlBackendTracker('session-persistence-jsonl')) { super(ctx) /* v8 ignore next 5 -- generated catalog and Session source share one build-time version owner. */ if (sessionFormatCatalog.currentVersion !== SESSION_FORMAT_VERSION) { @@ -381,6 +396,35 @@ class JsonlSessionPersistence extends SessionPersistence { return { kind: 'jsonl', path: logPath(this.root, meta.cwd, meta.id, this.compression) } } + /** + * Prepare logical history while the caller retains Session write ownership. + * @param id - stored Session identity. + * @param signal - optional cancellation for decoding and destination publication. + * @returns a commit operation that validates related sources before publishing the history. + */ + async prepare(id: SessionId, signal?: AbortSignal): Promise { + await this.ensureRootEncoding() + signal?.throwIfAborted() + const stored = await this.requireStoredLog(id, signal) + const snapshot = { header: stored.meta, inheritedEventCount: stored.inheritedEventCount, events: stored.events } + return { commit: async (publish) => { + signal?.throwIfAborted() + if (stored.status === 'prepared') await stored.validateRelatedSources() + signal?.throwIfAborted() + await publish(snapshot) + } } + } + + /** + * Check whether a JSONL artifact occupies the Session identity. + * @param id - stored Session identity. + * @returns whether the artifact exists. + */ + async hasStoredJsonl(id: SessionId): Promise { + await this.ensureRootEncoding() + return await this.findLog(id) !== undefined + } + // --- SessionPersistence service API --- /** @@ -712,7 +756,7 @@ class JsonlSessionPersistence extends SessionPersistence { const sources = await children() const related = await prepareCatalogFacts(id, sources, this.compression, signal) for (const failure of related.failures) { - this.ctx.logger.warn(`${this.name}: session "${id}" catalog retained a child with unknown descriptor (raw log: ${failure.path}): ${String(failure.error)}`) + this.ctx.logger.warn(`${name}: session "${id}" catalog retained a child with unknown descriptor (raw log: ${failure.path}): ${String(failure.error)}`) } const membership = sources.map(source => source.path).sort() validateRelatedSources = async () => { @@ -967,7 +1011,7 @@ class JsonlSessionPersistence extends SessionPersistence { async truncateTornTail(header: SessionHeader, truncateTo: number): Promise { this.coldLogMemo.delete(header.id) await this.repair(header, truncateTo) - this.ctx.logger.warn(`${this.name}: session "${header.id}" recovered from a torn tail; incomplete tail bytes were discarded`) + this.ctx.logger.warn(`${name}: session "${header.id}" recovered from a torn tail; incomplete tail bytes were discarded`) } /** diff --git a/packages/session/session-persistence-sqlite/README.i18n.yaml b/packages/session/session-persistence-sqlite/README.i18n.yaml new file mode 100644 index 0000000000..0f59027442 --- /dev/null +++ b/packages/session/session-persistence-sqlite/README.i18n.yaml @@ -0,0 +1,55 @@ +# Bilingual-pair consistency record for README.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 packages/session/session-persistence-sqlite/README.md +/: + en: 45c507cd1be83a49 + zh: 0892f22bc67f3c2b +/deepseek-ai-dsh-session-persistence-sqlite: + en: 22cf683fb8ec6976 + zh: c4c0244b1b7340bd +/deepseek-ai-dsh-session-persistence-sqlite/summary: + en: fe7d7d6b65eb14b8 + zh: e979ace0de85182b +/deepseek-ai-dsh-session-persistence-sqlite/table-of-contents: + en: d152484eb41ac6b4 + zh: 3a2f21ff0dc3420d +/deepseek-ai-dsh-session-persistence-sqlite/use-this-package: + en: e9211101131a5db2 + zh: 0d34955cfaadbbeb +/deepseek-ai-dsh-session-persistence-sqlite/use-this-package/minimal-configuration: + en: 4b80aca7e9524b84 + zh: 44bb710bf7c5a442 +/deepseek-ai-dsh-session-persistence-sqlite/use-this-package/opening-existing-history: + en: 3a0476996102dcce + zh: c0692ddc53045ff2 +/deepseek-ai-dsh-session-persistence-sqlite/use-this-package/durability-and-shutdown: + en: e420c74a70699060 + zh: 83d37ea617216ac9 +/deepseek-ai-dsh-session-persistence-sqlite/understand-the-implementation: + en: d2f152e5f3020a77 + zh: c40f206b7a73dc35 +/deepseek-ai-dsh-session-persistence-sqlite/further-exploration: + en: 6c9f517924d25414 + zh: 0a8400a08ec55dbf +/deepseek-ai-dsh-session-persistence-sqlite/model-experience: + en: 215e7ba838619b7b + zh: a311da3843709f90 +/deepseek-ai-dsh-session-persistence-sqlite/model-experience/restored-history: + en: af9a6e2fdfb3eb09 + zh: 5cee3d5d560a6df8 +/deepseek-ai-dsh-session-persistence-sqlite/model-experience/restored-history/what-the-model-sees: + en: 37ef7b6c32cafb45 + zh: a0b53fe40abc64de +/deepseek-ai-dsh-session-persistence-sqlite/model-experience/restored-history/token-effect: + en: 9f80b2e96a1c9c01 + zh: 23c96e7f02d087be +/deepseek-ai-dsh-session-persistence-sqlite/model-experience/restored-history/kv-cache-effect: + en: 3a849c807fae4040 + zh: cb3a122553040b79 +/deepseek-ai-dsh-session-persistence-sqlite/known-limitations-and-deferred-work: + en: a50bf9d3b012d7c4 + zh: 880fd4c27465ba5c +/deepseek-ai-dsh-session-persistence-sqlite/known-limitations-and-deferred-work/dev-note: + en: e67f633dc6fe7773 + zh: e88aeb617ffb74ea diff --git a/packages/session/session-persistence-sqlite/README.md b/packages/session/session-persistence-sqlite/README.md new file mode 100644 index 0000000000..f5d5863abd --- /dev/null +++ b/packages/session/session-persistence-sqlite/README.md @@ -0,0 +1,127 @@ +--- +description: "Save and reopen Session histories in SQLite, import existing JSONL histories, and coordinate concurrent readers and writers." +kind: "package-reference" +--- + +# @deepseek-ai/dsh-session-persistence-sqlite + +English | [中文](README.zh.md) + +## Summary + +Save Session histories in SQLite and reopen them through the existing persistence API. Existing JSONL histories import on first open while their source files remain intact. Readers can share a database with an active writer; each Session permits one writer. Choose this provider explicitly: shipped profiles continue to use JSONL. + +## Table of Contents + +- [Use this package](#use-this-package) +- [Understand the implementation](#understand-the-implementation) +- [Further Exploration](#further-exploration) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Use this package + +Mount this provider for the storage root whose Sessions should use SQLite. + +### Minimal configuration + +Replace the JSONL provider's package name in your composition, preserving its root and legacy encoding settings: + +```yaml +- name: '@deepseek-ai/dsh-session-persistence-sqlite' + config: + root: './.sessions' +``` + +The database lives at `/.segments/sessions.sqlite`. Application callers continue to use `ctx.sessionPersistence` and its Session handles. + +| Field | Default | Meaning | +|---|---|---| +| `root` | Required | Storage root containing the database and any existing JSONL histories. | +| `compression` | `zstd` | Existing JSONL encoding; SQLite events use ordinary JSON. | +| `listConcurrency` | `3` | Concurrent filesystem reads for legacy metadata and routing records. | + +The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-session-persistence-sqlite) documents all accepted fields. + +### Opening existing history + +A first read or write open decodes the selected JSONL generation through its version migration chain, then imports the current logical history into SQLite. Import preserves metadata, event order, source coordinates and the inheritance marker. It creates an independent root Segment and retains the JSONL source bytes. The imported Session and its later events reopen through SQLite. + +An active JSONL writer retains ownership until it closes. A SQLite read open waits for that ownership; a competing write open rejects. Cancellation or provider disposal stops the wait. After import, readers can open while the SQLite writer remains active. `stat()` and `list()` observe metadata without importing history. + +### Durability and shutdown + +Direct append, live Session events and durability checkpoints use the same handle. `flush()` drains pending events; writer close and provider disposal finish admitted writes before releasing ownership. An automatic write failure retains its pending batch and pauses automatic writes; the next explicit checkpoint retries and reports any remaining failure. + +----- + + +## Understand the implementation + +
    +Implementation internals — click to expand + +The plugin supplies the existing persistence service and uses a JSONL provider in an isolated service context to read legacy histories. Import acquires the Session's artifact lease, commits its metadata and events in a database transaction, then records SQLite routing. A write open retains the lease through the handoff. + +SQLite keeps thread metadata, predecessor-linked Segment metadata and indexed JSON event rows. WAL is enabled before schema publication so a concurrent reader cannot prevent the first mode switch. The backend owns write queues, live-event buffering, transaction completion and handle cleanup; callers do not address Segments. + +| Source | Responsibility | +|---|---| +| [persistence.ts](src/persistence.ts) | Service routing and durable JSONL takeover. | +| [migration.ts](src/migration.ts) | Import sequencing, ownership handoff and cancellation. | +| [sqlite.ts](src/sqlite.ts) | Database, Segment access, handles and durability. | + +
    + +----- + + +## Further Exploration + +- [Session persistence](../session-persistence/README.md) — the shared service and handle semantics. +- [JSONL persistence](../session-persistence-jsonl/README.md) — physical generations and version migration. +- [Persistence subsystem](../../../docs/subsystems/persistence.md) — recovery and consumer-facing APIs. + +----- + + +## Model Experience + +### Restored history + +#### What the model sees + +This provider adds no prompt or tool schema. Restored `user/message` and `assistant/message` events supply the same conversation history; the Session consumer owns interrupted-turn repair. + +#### Token effect + +Storage adds no tokens. Restored history has its usual conversation cost. + +#### KV Cache effect + +Storage preserves event order and does not rewrite model request prefixes. + +## Known Limitations and Deferred Work + + + +These constraints apply when selecting this provider. + +- The first legacy read open writes the SQLite database and requires write access to the storage root. +- Retained JSONL files contain the imported prefix and exclude later SQLite events; they cannot restore the latest history on their own. +- All processes writing imported Sessions must use the SQLite provider. +- SQLite accepts the current Session format; a future event-format upgrade needs its own SQLite history migration. + + +### Dev Note + +
    +Working context for maintainers — click to expand + +None. + +
    diff --git a/packages/session/session-persistence-sqlite/README.zh.md b/packages/session/session-persistence-sqlite/README.zh.md new file mode 100644 index 0000000000..821d47ed64 --- /dev/null +++ b/packages/session/session-persistence-sqlite/README.zh.md @@ -0,0 +1,127 @@ +--- +description: "在 SQLite 中保存和重新打开 Session 历史,导入现有 JSONL 历史,并协调并发读写。" +kind: "package-reference" +--- + +# @deepseek-ai/dsh-session-persistence-sqlite + +[English](README.md) | 中文 + +## 概述 + +在 SQLite 中保存 Session 历史,并通过原有持久化 API 重新打开。现有 JSONL 历史在首次打开时导入,源文件保持不变。读者可以与活跃写者共享数据库;每个 Session 只允许一个写者。需要显式选择此提供者:内置 profile 继续使用 JSONL。 + +## 目录 + +- [使用本包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [进一步探索](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与待办](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用本包 + +为需要使用 SQLite 的 Session 存储根目录挂载此提供者。 + +### 最小配置 + +在组合配置中替换 JSONL 提供者的包名,保留其根目录和旧历史编码设置: + +```yaml +- name: '@deepseek-ai/dsh-session-persistence-sqlite' + config: + root: './.sessions' +``` + +数据库位于 `/.segments/sessions.sqlite`。应用调用方继续使用 `ctx.sessionPersistence` 及其 Session 句柄。 + +| 字段 | 默认值 | 含义 | +|---|---|---| +| `root` | 必填 | 包含数据库和现有 JSONL 历史的存储根目录。 | +| `compression` | `zstd` | 现有 JSONL 的编码;SQLite 事件使用普通 JSON。 | +| `listConcurrency` | `3` | 旧历史元数据及路由记录的并发文件系统读取数。 | + +生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-session-persistence-sqlite)记录了所有可用字段。 + +### 打开现有历史 + +首次 read 或 write open 通过版本迁移链解码选定的 JSONL 代次,然后将当前逻辑历史导入 SQLite。导入保留元数据、事件顺序、来源坐标和继承标记。它创建独立根 Segment,并保留 JSONL 源文件字节。导入后的 Session 及其后续事件通过 SQLite 重新打开。 + +活跃的 JSONL 写者保持所有权,直到关闭。SQLite read open 等待该所有权释放;竞争的 write open 会被拒绝。取消或提供者卸载会停止等待。导入后,读者可以在 SQLite 写者仍活跃时打开。`stat()` 和 `list()` 只观察元数据,不导入历史。 + +### 持久化与关闭 + +直接 append、实时 Session 事件和持久化检查点使用同一个句柄。`flush()` 排空待写事件;写句柄关闭及提供者卸载会完成已接收的写入,再释放所有权。自动写入失败会保留待写批次并暂停自动写入;下一个显式检查点重试,并报告仍然存在的失败。 + +----- + + +## 理解实现 + +
    +实现内部细节——点击展开 + +插件提供原有持久化服务,并在隔离的服务上下文中使用 JSONL 提供者读取旧历史。导入取得 Session 的文件租约,在数据库事务中提交元数据和事件,然后记录 SQLite 路由。write open 在交接过程中保持租约。 + +SQLite 保存 thread 元数据、前驱关联的 Segment 元数据及带索引的 JSON 事件行。发布 schema 前先启用 WAL,防止并发读者阻碍首次模式切换。后端负责写入队列、实时事件缓冲、事务完成和句柄清理;调用方不直接访问 Segment。 + +| 源码 | 职责 | +|---|---| +| [persistence.ts](src/persistence.ts) | 服务路由和 JSONL 的持久接管。 | +| [migration.ts](src/migration.ts) | 导入排序、所有权交接和取消。 | +| [sqlite.ts](src/sqlite.ts) | 数据库、Segment 访问、句柄和持久化。 | + +
    + +----- + + +## 进一步探索 + +- [Session 持久化](../session-persistence/README.zh.md) — 公共服务和句柄语义。 +- [JSONL 持久化](../session-persistence-jsonl/README.zh.md) — 物理代次和版本迁移。 +- [持久化子系统](../../../docs/subsystems/persistence.zh.md) — 恢复及面向调用方的 API。 + +----- + + +## 模型体验 + +### 恢复的历史 + +#### 模型实际看到什么 + +此提供者不增加提示词或工具 schema。恢复的 `user/message` 和 `assistant/message` 事件提供相同的对话历史;Session 调用方负责 interrupted-turn 修复。 + +#### Token 影响 + +存储不增加 token。恢复历史仍有正常的对话成本。 + +#### KV Cache 影响 + +存储保留事件顺序,不改写模型请求前缀。 + +## 已知限制与待办 + + + +选择此提供者时适用以下约束。 + +- 首次读取旧历史会写入 SQLite 数据库,因此需要存储根目录的写权限。 +- 保留的 JSONL 文件只包含导入前缀,不包含后续 SQLite 事件;单靠它们无法恢复最新历史。 +- 所有写入已导入 Session 的进程都必须使用 SQLite 提供者。 +- SQLite 接受当前 Session 格式;未来事件格式升级需要独立的 SQLite 历史迁移。 + + +### 开发备注 + +
    +维护者工作上下文——点击展开 + +无。 + +
    diff --git a/packages/session/session-persistence-sqlite/locale/de.json b/packages/session/session-persistence-sqlite/locale/de.json new file mode 100644 index 0000000000..026810b046 --- /dev/null +++ b/packages/session/session-persistence-sqlite/locale/de.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "session-persistence-sqlite" + } +} diff --git a/packages/session/session-persistence-sqlite/locale/en.json b/packages/session/session-persistence-sqlite/locale/en.json new file mode 100644 index 0000000000..026810b046 --- /dev/null +++ b/packages/session/session-persistence-sqlite/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "session-persistence-sqlite" + } +} diff --git a/packages/session/session-persistence-sqlite/locale/es.json b/packages/session/session-persistence-sqlite/locale/es.json new file mode 100644 index 0000000000..026810b046 --- /dev/null +++ b/packages/session/session-persistence-sqlite/locale/es.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "session-persistence-sqlite" + } +} diff --git a/packages/session/session-persistence-sqlite/locale/fr.json b/packages/session/session-persistence-sqlite/locale/fr.json new file mode 100644 index 0000000000..026810b046 --- /dev/null +++ b/packages/session/session-persistence-sqlite/locale/fr.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "session-persistence-sqlite" + } +} diff --git a/packages/session/session-persistence-sqlite/locale/ja.json b/packages/session/session-persistence-sqlite/locale/ja.json new file mode 100644 index 0000000000..026810b046 --- /dev/null +++ b/packages/session/session-persistence-sqlite/locale/ja.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "session-persistence-sqlite" + } +} diff --git a/packages/session/session-persistence-sqlite/locale/pt.json b/packages/session/session-persistence-sqlite/locale/pt.json new file mode 100644 index 0000000000..026810b046 --- /dev/null +++ b/packages/session/session-persistence-sqlite/locale/pt.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "session-persistence-sqlite" + } +} diff --git a/packages/session/session-persistence-sqlite/locale/ru.json b/packages/session/session-persistence-sqlite/locale/ru.json new file mode 100644 index 0000000000..026810b046 --- /dev/null +++ b/packages/session/session-persistence-sqlite/locale/ru.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "session-persistence-sqlite" + } +} diff --git a/packages/session/session-persistence-sqlite/locale/zh.json b/packages/session/session-persistence-sqlite/locale/zh.json new file mode 100644 index 0000000000..026810b046 --- /dev/null +++ b/packages/session/session-persistence-sqlite/locale/zh.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "session-persistence-sqlite" + } +} diff --git a/packages/session/session-persistence-sqlite/package.json b/packages/session/session-persistence-sqlite/package.json new file mode 100644 index 0000000000..a08b08d198 --- /dev/null +++ b/packages/session/session-persistence-sqlite/package.json @@ -0,0 +1,55 @@ +{ + "name": "@deepseek-ai/dsh-session-persistence-sqlite", + "description": "SQLite Session event storage backend for the DeepSeek Harness", + "version": "0.2.2-rc.3", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/session/session-persistence-sqlite" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" + }, + "files": [ + "locale/*.json", + "lib/index.js", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "lib/**/*.js.map", + "src" + ], + "license": "MIT", + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-session": "workspace:*", + "@deepseek-ai/dsh-session-persistence": "workspace:*" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-session": "workspace:*", + "@deepseek-ai/dsh-session-persistence": "workspace:*" + }, + "dependencies": { + "@deepseek-ai/dsh-session-persistence-jsonl": "workspace:*", + "@deepseek-ai/dsh-brand": "workspace:*", + "@deepseek-ai/dsh-llm": "workspace:*", + "@deepseek-ai/dsh-session-format": "workspace:*", + "@deepseek-ai/dsh-session-format-v3-to-v4": "workspace:*", + "zod": "4.6.6", + "@deepseek-ai/node-addon-system": "workspace:~", + "p-limit": "7.3.3", + "koffi": "3.1.1" + } +} diff --git a/packages/session/session-persistence-sqlite/src/buffer.ts b/packages/session/session-persistence-sqlite/src/buffer.ts new file mode 100644 index 0000000000..c168309844 --- /dev/null +++ b/packages/session/session-persistence-sqlite/src/buffer.ts @@ -0,0 +1,86 @@ +/** Ordered live-event batching shared by the persistence backends. @module */ +import type { SessionEvent } from '@deepseek-ai/dsh-session' + +/** Backend-owned serialization and commit operations for a live batch. */ +interface LiveWriteOptions { + delayMs: number + maxEvents: number + enqueue(operation: () => Promise): Promise + persist(batch: readonly SessionEvent[]): Promise + retry(error: unknown): boolean + canSchedule(): boolean +} + +/** Retains admitted copies until commit, pausing automatic retries after failure. */ +export class LiveWriteBuffer { + private events: SessionEvent[] = [] + private timer: ReturnType | undefined + private draining: Promise | undefined + private paused = false + private report: ((error: unknown) => void) | undefined + + constructor(private readonly options: LiveWriteOptions) {} + + /** Number of admitted events awaiting commit. */ + get length(): number { return this.events.length } + + /** Whether a durability drain is in progress. */ + get active(): boolean { return this.draining !== undefined } + + /** + * Admit exclusively owned event copies and schedule their durability deadline. + * @param events - backend-validated or snapshotted live events. + * @param report - observes automatic write failures. + */ + append(events: readonly SessionEvent[], report: (error: unknown) => void): void { + this.events.push(...events) + this.report = report + if (this.paused || !this.options.canSchedule()) return + if (this.events.length >= this.options.maxEvents) { + void this.drain().catch(report) + } else if (this.timer === undefined) { + this.timer = setTimeout(() => { + this.timer = undefined + void this.drain().catch(report) + }, this.options.delayMs) + } + } + + /** + * Commit all admitted events in order; concurrent callers join one drain. + * @returns durability completion, rejecting with the backend's write failure. + */ + drain(): Promise { + if (this.draining !== undefined) return this.draining + this.cancelTimer() + this.paused = false + return this.draining = this.commit().finally(() => { + this.draining = undefined + if (this.events.length > 0 && !this.paused && this.options.canSchedule() && this.report !== undefined) { + void this.drain().catch(this.report) + } + }) + } + + private cancelTimer(): void { + if (this.timer !== undefined) { clearTimeout(this.timer); this.timer = undefined } + } + + private async commit(): Promise { + while (this.events.length > 0) { + try { await this.options.enqueue(async () => { + this.cancelTimer() + const batch = this.events.splice(0, this.options.maxEvents) + try { await this.options.persist(batch) } + catch (error: unknown) { + if (this.options.retry(error)) this.events = batch.concat(this.events) + this.paused = true + throw error + } + }) } catch (error: unknown) { + this.paused = true + throw error + } + } + } +} diff --git a/packages/session/session-persistence-sqlite/src/codec.ts b/packages/session/session-persistence-sqlite/src/codec.ts new file mode 100644 index 0000000000..d1435c7e65 --- /dev/null +++ b/packages/session/session-persistence-sqlite/src/codec.ts @@ -0,0 +1,72 @@ +/** SQLite stores logical Session headers and events without JSONL row encoding. @module */ +import { isAbsolute } from 'node:path' +import { z } from 'zod' +import { SESSION_FORMAT_VERSION, SessionId, KNOWN_SESSION_EVENT_TYPES, SessionLogOffset } from '@deepseek-ai/dsh-session' +import type { SessionEvent, SessionHeader } from '@deepseek-ai/dsh-session' +import type { SessionFormatEvent } from '@deepseek-ai/dsh-session-format' +import { assertV4RowAdmission } from '@deepseek-ai/dsh-session-format-v3-to-v4' + +/** SQLite's logical format version; a new Session version requires an explicit storage migration. */ +export const SQLITE_SESSION_FORMAT_VERSION = 4 satisfies typeof SESSION_FORMAT_VERSION + +const header = z.object({ + version: z.literal(SQLITE_SESSION_FORMAT_VERSION), + id: z.string().transform(SessionId), + createdAt: z.number().int().nonnegative(), + isSeeded: z.boolean(), + cwd: z.string().refine(isAbsolute).optional(), + parentSession: z.string().transform(SessionId).optional(), + origin: z.literal('subagent').optional(), + delegationDepth: z.number().int().nonnegative().default(0), + agentPreset: z.string().optional(), +}).strict() +const event = z.object({ + type: z.string(), + seq: z.number().int().nonnegative(), + time: z.number().int(), + data: z.unknown().refine(value => value !== undefined), + ignorable: z.literal(true).optional(), + sourceEventSeqs: z.array(z.number().int().nonnegative()).optional(), + surfaceOp: z.union([z.literal('append'), z.object({ + op: z.literal('replace'), startSeq: z.number().int().nonnegative(), endSeq: z.number().int().nonnegative(), + }).strict()]).optional(), +}).strict() + +/** + * Read current logical Session metadata from a stored JSON object. + * @param value - untrusted SQLite header parsed from JSON. + * @returns validated metadata with an explicit delegation depth. + */ +export function decodeHeader(value: unknown): SessionHeader { + const { cwd, parentSession, origin, agentPreset, ...metadata } = header.parse(value) + return { ...metadata, + ...cwd === undefined ? {} : { cwd }, + ...parentSession === undefined ? {} : { parentSession }, + ...origin === undefined ? {} : { origin }, + ...agentPreset === undefined ? {} : { agentPreset }, + } +} + +/** + * Preserve the existing seeded/cut checks before reserving or importing a Session. + * @param metadata - detached creation or import header. + * @param inheritedEventCount - exact inherited prefix, required for seeded Sessions. + * @returns normalized logical metadata for SQLite JSON storage. + */ +export function materializeHeader(metadata: SessionHeader, inheritedEventCount?: SessionLogOffset): SessionHeader { + if (metadata.isSeeded && inheritedEventCount === undefined) throw new Error('seeded session header requires an inherited event count') + const cut = SessionLogOffset(inheritedEventCount ?? 0) + if (!metadata.isSeeded && cut !== 0) throw new Error('unseeded session header inherited event count must be 0') + return decodeHeader(metadata) +} + +/** + * Read a logical event envelope; native payload validation remains in Session adoption. + * Source coordinates stay as arrays and are never decoded from JSONL ranges. + * @param value - untrusted SQLite event parsed from JSON. + * @returns logical event for vocabulary validation and Session adoption. + */ +export function decodeEvent(value: unknown): SessionFormatEvent & SessionEvent { + assertV4RowAdmission(value, KNOWN_SESSION_EVENT_TYPES) + return event.parse(value) as SessionFormatEvent & SessionEvent +} diff --git a/packages/session/session-persistence-sqlite/src/index.ts b/packages/session/session-persistence-sqlite/src/index.ts new file mode 100644 index 0000000000..2a7b6d1110 --- /dev/null +++ b/packages/session/session-persistence-sqlite/src/index.ts @@ -0,0 +1,37 @@ +/** SQLite Session persistence and event storage. @module */ +import { Context, type Fiber } from '@deepseek-ai/cordis' +import { Config as JsonlConfig, JsonlSessionPersistence } from '@deepseek-ai/dsh-session-persistence-jsonl' +import type { Config as JsonlConfigOptions } from '@deepseek-ai/dsh-session-persistence-jsonl' +import { SqliteSessionPersistence } from './persistence.ts' + +/** Loader label for the SQLite Session persistence provider. */ +export const name = 'session-persistence-sqlite' + +/** Storage root and JSONL settings used when importing legacy Sessions. */ +export type Config = JsonlConfigOptions + +/** Validate the storage root and legacy JSONL reader settings. */ +export const Config = JsonlConfig + +/** + * Provide SQLite persistence and retain storage resources through consumer unload. + * @param ctx - plugin context owning the provider and its resources. + * @param config - storage root and legacy JSONL reader settings. + * @returns resolves after the persistence service is registered. + */ +export async function apply(ctx: Context, config: Config): Promise { + let service!: Fiber + ctx.effect(function* () { + const resources = ctx.plugin({ name: 'session-segment-resources', apply() {} }) + yield resources.dispose + service = ctx.plugin({ + name: 'session-persistence-sqlite-service', + apply(serviceCtx: Context) { + const legacy = new JsonlSessionPersistence(serviceCtx.isolate('sessionPersistence'), config) + new SqliteSessionPersistence(serviceCtx, resources.ctx, config, legacy) + }, + }) + yield service.dispose + }, 'session-persistence-sqlite resources') + await service.await() +} diff --git a/packages/session/session-persistence-sqlite/src/lease.ts b/packages/session/session-persistence-sqlite/src/lease.ts new file mode 100644 index 0000000000..6286d19015 --- /dev/null +++ b/packages/session/session-persistence-sqlite/src/lease.ts @@ -0,0 +1,138 @@ +/** + * Cross-process write-ownership lock for one session's artifact directory, + * held for the whole life of a write handle. The arbiter is the kernel: + * POSIX takes a non-blocking `flock(2)` via native system support on `session.lock` + * beside the log, and Windows holds a named kernel semaphore derived from + * that path — never a file lock or handle, so readers, searches, and + * directory removal proceed freely while the lock is held. Contention maps + * to `SessionAlreadyOwnedError`; the kernel releases the lock when the + * holder's descriptor or last object handle closes, including on any process + * death, so a crashed holder never blocks a successor. A live but wedged + * holder keeps the lock until its process exits: there is deliberately no + * expiry that could expropriate a stalled writer whose resumed appends would + * tear the log. + * A POSIX lock names an inode, not a path, so after locking the holder + * verifies the locked inode is still the file at the lock path and retries + * otherwise: an unlinked-and-recreated lock file carries a fresh inode, and + * a lock on the orphaned one proves nothing. Removing a live session's lock + * file therefore forfeits exclusion on POSIX (nothing in the harness does + * so); Windows has no lock file at all. Readers never touch the lock. + * The lock is acquired at write-open of an existing artifact and, for a + * created session, only right before its first materializing write — an + * unmaterialized session has no filesystem footprint. Release never removes + * the POSIX lock file: every acquired lock belongs to a materialized or + * materializing session, and the surviving file keeps the stable inode later + * lockers verify against. The browser worker stubs the native flock entry to + * immediate success: it is single-process, so the in-process write claim + * already excludes every writer. + * @module @deepseek-ai/dsh-session-persistence-sqlite/lease + */ +// JSONL retains a separate copy so the two backends need no shared helper exports. +/* jscpd:ignore-start */ + +import { mkdir, open, stat } from 'node:fs/promises' +import type { FileHandle } from 'node:fs/promises' +import { join } from 'node:path' +import { tryLockExclusive } from '@deepseek-ai/node-addon-system/flock' +import { SessionAlreadyOwnedError } from '@deepseek-ai/dsh-session-persistence' +import type { SessionId } from '@deepseek-ai/dsh-session' +import { acquireLockHandleWin32, releaseLockHandleWin32 } from './win32.ts' + +/** Base name of the kernel lock file inside a session's directory. */ +export const LEASE_FILENAME = 'session.lock' + +/** The held kernel lock: a POSIX descriptor or a Win32 semaphore handle. */ +type HeldLock = + | { readonly kind: 'posix'; readonly handle: FileHandle } + | { readonly kind: 'win32'; readonly handle: number } + +/** Whether a flock failure means another descriptor holds the lock. */ +function isLockContention(error: unknown): boolean { + const code = (error as NodeJS.ErrnoException | null)?.code + // flock(2) reports EAGAIN; some libcs spell it EWOULDBLOCK. + return code === 'EAGAIN' || code === 'EWOULDBLOCK' +} + +/** + * One held write lock. Constructed only by {@link SessionWriteLease.acquire}; + * `release` closes the descriptor or handle, which is what releases the lock. + */ +export class SessionWriteLease { + private released = false + + private constructor(private readonly held: HeldLock) {} + + /** + * Acquire the session directory's kernel write lock. + * @param dir - the session's artifact directory (created if absent). + * @param id - the session the lock guards, for error identities. + * @returns the held lock. + * @throws {SessionAlreadyOwnedError} while another holder keeps the lock. + */ + static async acquire(dir: string, id: SessionId): Promise { + const path = join(dir, LEASE_FILENAME) + // Owner-only like materializePosix's directories: the lock may create the + // session directory first, and both creators must agree on the mode. + await mkdir(dir, { recursive: true, mode: 0o700 }) + /* v8 ignore start -- native Windows coverage exercises this platform branch; Linux covers the POSIX peer */ + if (process.platform === 'win32') { + let handle: number + try { + handle = await acquireLockHandleWin32(path) + } catch (error: unknown) { + // Sharing violation: another handle already holds the write exclusion. + if ((error as NodeJS.ErrnoException | null)?.code === 'EBUSY') throw new SessionAlreadyOwnedError(id) + throw error + } + return new SessionWriteLease({ kind: 'win32', handle }) + } + /* v8 ignore stop */ + // Bounded retry: locking an inode a releasing creator just unlinked (or a + // recreated path) re-opens the fresh file; steady state needs one pass. + for (let attempt = 0; attempt < 3; attempt += 1) { + const handle = await open(path, 'w') + try { + try { + await tryLockExclusive(handle.fd) + } catch (error: unknown) { + if (isLockContention(error)) throw new SessionAlreadyOwnedError(id) + throw error + } + const held = await handle.stat({ bigint: true }) + const current = await stat(path, { bigint: true }).catch((error: unknown) => { + if ((error as NodeJS.ErrnoException | null)?.code === 'ENOENT') return undefined + throw error + }) + if (current !== undefined && current.ino === held.ino && current.dev === held.dev) { + return new SessionWriteLease({ kind: 'posix', handle }) + } + } catch (error: unknown) { + await handle.close() + throw error + } + // The locked inode is no longer the file at the lock path: start over + // against whatever now stands there. + await handle.close() + } + throw new SessionAlreadyOwnedError(id) + } + + /** + * Release the kernel lock by closing its descriptor or handle. The POSIX + * lock file is never removed: every acquired lock belongs to a + * materialized or materializing session, and keeping the file preserves + * the stable inode later lockers verify against. Idempotent. + */ + async release(): Promise { + if (this.released) return + this.released = true + /* v8 ignore start -- native Windows coverage exercises this platform branch; Linux covers the POSIX peer */ + if (this.held.kind === 'win32') { + await releaseLockHandleWin32(this.held.handle) + return + } + /* v8 ignore stop */ + await this.held.handle.close() + } +} +/* jscpd:ignore-end */ diff --git a/packages/session/session-persistence-sqlite/src/migration.ts b/packages/session/session-persistence-sqlite/src/migration.ts new file mode 100644 index 0000000000..bcdf281994 --- /dev/null +++ b/packages/session/session-persistence-sqlite/src/migration.ts @@ -0,0 +1,95 @@ +/** Exclusive legacy Session import with same-provider open sequencing. @module */ +import type { SessionId } from '@deepseek-ai/dsh-session' +import type { JsonlSessionPersistence } from '@deepseek-ai/dsh-session-persistence-jsonl' +import { HarnessError } from '@deepseek-ai/dsh-llm' +import { setTimeout } from 'node:timers/promises' +import { SessionAlreadyOwnedError } from '@deepseek-ai/dsh-session-persistence' +import type { SessionAccess, SessionHandle, SessionPersistenceOpenOptions } from '@deepseek-ai/dsh-session-persistence' +import type { SqliteStore } from './sqlite.ts' + +/** Historical reads used by the persistence service; no JSONL writes or live handles. */ +export type JsonlBackend = Pick + +/** Owns pending legacy opens until import, ownership handoff, and cleanup finish. */ +export class LegacySessionMigration { + private readonly pending = new Map>() + private closing = false + private readonly stopped = new AbortController() + constructor(private readonly jsonl: JsonlBackend, private readonly sqlite: SqliteStore, + private readonly selected: (id: SessionId) => Promise, private readonly publish: (id: SessionId) => Promise) {} + + /** + * Serialize legacy opens within this provider. Readers wait for another provider's import; writers reject contention. + * @param id - legacy Session identity. + * @param access - requested access after import. + * @param options - optional cancellation checked when the queued open starts. + * @returns SQLite handle; a write handle retains the import lease without a release/reacquire gap. + */ + open(id: SessionId, access: SessionAccess, options?: SessionPersistenceOpenOptions): Promise { + if (this.closing) return Promise.reject(new HarnessError('Session migration is closing', 'SESSION_STORAGE_CLOSED')) + const previous = this.pending.get(id) ?? Promise.resolve() + const next = previous.catch((_error: unknown) => { /* A failed caller does not cancel the next open. */ }) + .then(() => this.migrate(id, access, options?.signal)) + this.pending.set(id, next) + const settled = (): void => { if (this.pending.get(id) === next) this.pending.delete(id) } + void next.then(settled, settled) + return next + } + + private async migrate(id: SessionId, access: SessionAccess, signal?: AbortSignal): Promise { + signal?.throwIfAborted() + // The caller observed no SQLite row before queueing; the lease loop below rechecks before each attempt. + // Header inspection does not decode history; the full snapshot is read only under ownership. + const metadata = await this.jsonl.stat(id, signal === undefined ? undefined : { signal }) + if (metadata === undefined) { + // A Session committed to SQLite while this open was queued has no legacy metadata. + if (await this.selected(id)) return this.sqlite.open(id, access, signal) + // The reader owns precise absent/malformed-header diagnostics. + await this.jsonl.prepare(id, signal) + throw new HarnessError('Legacy Session has no readable metadata', 'SESSION_STORAGE_CORRUPT') + } + let lease: Awaited> | undefined + const waitingSignal = signal === undefined ? this.stopped.signal : AbortSignal.any([signal, this.stopped.signal]) + for (;;) { + waitingSignal.throwIfAborted() + if (await this.selected(id)) return this.sqlite.open(id, access, signal) + try { + lease = await this.sqlite.acquireSessionLease(metadata.header) + break + } catch (error: unknown) { + if (access !== 'read' || !(error instanceof SessionAlreadyOwnedError)) throw error + // Kernel leases have no completion notification; observe the committed row between acquisition attempts. + await setTimeout(50, undefined, { signal: waitingSignal }) + } + } + let handle: SessionHandle | undefined + try { + signal?.throwIfAborted() + if (!await this.selected(id)) { + const prepared = await this.jsonl.prepare(id, signal) + await prepared.commit(snapshot => this.sqlite.importLegacy(snapshot.header, snapshot.inheritedEventCount, snapshot.events, signal)) + } else await this.publish(id) + signal?.throwIfAborted() + handle = await this.sqlite.open(id, access, signal, access === 'write' ? lease : undefined) + if (access === 'write') lease = undefined + else { + const imported = lease + lease = undefined + await imported.release() + } + return handle + } catch (error: unknown) { + const cleanup = await Promise.allSettled([handle?.close(), lease?.release()]) + const failures = cleanup.filter(result => result.status === 'rejected').map((result): unknown => result.reason) + if (failures.length > 0) throw new AggregateError([error, ...failures], 'Session migration and cleanup failed') + throw error + } + } + + /** Stop admission and settle accepted imports before SQLite closes. @returns settled cleanup. */ + async close(): Promise { + this.closing = true + this.stopped.abort(new HarnessError('Session migration is closing', 'SESSION_STORAGE_CLOSED')) + await Promise.allSettled([...this.pending.values()]) + } +} diff --git a/packages/session/session-persistence-sqlite/src/paths.ts b/packages/session/session-persistence-sqlite/src/paths.ts new file mode 100644 index 0000000000..01cdefc1f5 --- /dev/null +++ b/packages/session/session-persistence-sqlite/src/paths.ts @@ -0,0 +1,89 @@ +/** Session artifact directories shared by persistence backends. @module */ +// JSONL retains a separate copy so the two backends need no shared helper exports. +/* jscpd:ignore-start */ +import { join } from 'node:path' +import type { SessionId } from '@deepseek-ai/dsh-session' + +/** + * Encode an arbitrary string as a single safe path segment, injectively over ALL JS (UTF-16) + * strings — including lone surrogates. A {@link SessionId} is an unvalidated branded string, + * so this neutralizes `../`, absolute paths, NUL, and separators before any filesystem use. + * Safe code units remain literal; every other unit, including `~`, becomes + * `~XXXX`. Operating on code units preserves lone surrogates, while special- + * casing `.` and `..` prevents traversal by an otherwise safe whole segment. + * + * @param raw - the string to encode; must be non-empty (throws on `''`). + * @returns the escaped single path segment, decodable back to `raw`. + */ +export function encodeSegment(raw: string): string { + if (raw.length === 0) throw new Error('cannot encode an empty path segment') + if (raw === '.') return '~002E' + if (raw === '..') return '~002E~002E' + let out = '' + for (let i = 0; i < raw.length; i++) { + const code = raw.charCodeAt(i) + const ch = String.fromCharCode(code) + if (ch !== '~' && /^[A-Za-z0-9._-]$/.test(ch)) { + out += ch + } else { + out += '~' + code.toString(16).toUpperCase().padStart(4, '0') + } + } + return out +} + +/** + * Build the readable directory key for a project path. + * Filesystem separators and drive separators become `-`; unsafe code units use + * the same `~XXXX` escape as session ids. The key is bounded for filesystem + * component limits. Separator replacement and truncation are intentionally + * lossy, following the common human-navigable project-directory convention. + * @param cwd - the session's project directory. + * @returns a single filesystem-safe project directory name. + */ +export function projectKey(cwd: string): string { + if (cwd.length === 0) throw new Error('cannot encode an empty project path') + let readable = '' + let separatorRun = false + for (let i = 0; i < cwd.length; i++) { + const code = cwd.charCodeAt(i) + const ch = String.fromCharCode(code) + if (ch === '/' || ch === '\\' || ch === ':') { + if (!separatorRun) readable += '-' + separatorRun = true + } else if (ch !== '~' && /^[A-Za-z0-9._-]$/.test(ch)) { + readable += ch + separatorRun = false + } else { + readable += '~' + code.toString(16).toUpperCase().padStart(4, '0') + separatorRun = false + } + } + const slug = readable.replace(/^-+/, '') || 'root' + return `--${slug.slice(0, 251)}--` +} + +/** + * The configured root's human-navigable project directory. A configured root + * may be local or shared; this grouping does not prescribe its deployment. + * @param root - the backend's session root directory. + * @param cwd - the session's project directory; `undefined` selects `_no-cwd`. + * @returns the project directory path under `root`. + */ +export function projectDir(root: string, cwd: string | undefined): string { + if (cwd === undefined) return join(root, '_no-cwd') + return join(root, projectKey(cwd)) +} + +/** + * The directory owned by one session and available for future session-local + * artifacts. + * @param root - the backend's session root directory. + * @param cwd - the session's project directory. + * @param id - the session id, encoded to one safe path segment. + * @returns the session directory beneath its project directory. + */ +export function sessionDir(root: string, cwd: string | undefined, id: SessionId): string { + return join(projectDir(root, cwd), encodeSegment(id)) +} +/* jscpd:ignore-end */ diff --git a/packages/session/session-persistence-sqlite/src/persistence.ts b/packages/session/session-persistence-sqlite/src/persistence.ts new file mode 100644 index 0000000000..cadbc55152 --- /dev/null +++ b/packages/session/session-persistence-sqlite/src/persistence.ts @@ -0,0 +1,204 @@ +/** SQLite Session persistence and durable takeover of legacy JSONL identities. @module */ +import { createHash, randomUUID } from 'node:crypto' +import { link, mkdir, open, readFile, readdir, rm } from 'node:fs/promises' +import { basename, join, resolve } from 'node:path' +import type { Context } from '@deepseek-ai/cordis' +import type { Config } from '@deepseek-ai/dsh-session-persistence-jsonl' +import pLimit, { type LimitFunction } from 'p-limit' +import { z } from 'zod' +import { HarnessError } from '@deepseek-ai/dsh-llm' +import { SessionPersistence, SessionAlreadyExistsError, SessionPersistenceNotFoundError, materializeCreateHeader } from '@deepseek-ai/dsh-session-persistence' +import type { SessionAccess, SessionPersistenceCreateOptions, SessionPersistenceOpenOptions, + SessionPersistenceStatOptions, SessionPersistenceListOptions, SessionPersistenceSnapshot } from '@deepseek-ai/dsh-session-persistence' +import { SessionId } from '@deepseek-ai/dsh-session' +import type { SessionHeader } from '@deepseek-ai/dsh-session' +import { publishNewFileWin32, ensureDurableDirectoryWin32 } from './win32.ts' +import { SqliteStore, isAbsent } from './sqlite.ts' +import { SessionWriteLease } from './lease.ts' +import { sessionDir } from './paths.ts' +import { LegacySessionMigration } from './migration.ts' +import type { JsonlBackend } from './migration.ts' + +const marker = z.object({ id: z.string().transform(SessionId), database: z.string() }).strict() + +/** Routes the existing logical Session API; Segment identifiers never cross this service. */ +export class SqliteSessionPersistence extends SessionPersistence { + private readonly directory: string + private readonly sqlite: SqliteStore + private readonly migration: LegacySessionMigration + private readonly rootPath: string + private readonly jsonl: JsonlBackend + private readonly listLimit: LimitFunction + private readonly publishedRoutes = new Set() + constructor(ctx: Context, owner: Context, config: Config, + jsonl: JsonlBackend) { + super(ctx) + this.rootPath = resolve(config.root) + this.listLimit = pLimit(config.listConcurrency ?? 3) + this.directory = join(this.rootPath, '.segments') + this.sqlite = new SqliteStore({ + path: join(this.directory, 'sessions.sqlite'), + legacyRoot: this.rootPath, + publish: id => this.publish(id), + acquireCreationLease: header => this.acquireCreationLease(header), + report: (id, error) => { owner.logger.error(`Segment persistence failed for ${id}; durability checkpoint will reject: ${String(error)}`) }, + }) + this.jsonl = jsonl + this.migration = new LegacySessionMigration(jsonl, this.sqlite, + async id => await this.selected(id) !== undefined, id => this.publish(id)) + this.sqlite.install(owner, () => this.migration.close()) + } + + /** + * Initialize SQLite before a Session is created or opened. + * @returns resolves once SQLite is ready. + */ + async start(): Promise { + await this.sqlite.start() + } + + /** + * Claim the existing artifact lock before a new Session first commits. + * @param header - pending Session metadata. + * @returns the held artifact lock. + */ + protected async acquireCreationLease(header: SessionHeader): Promise { + const lease = await SessionWriteLease.acquire(sessionDir(this.rootPath, header.cwd, header.id), header.id) + try { + if (await this.jsonl.hasStoredJsonl(header.id)) { + throw new SessionAlreadyExistsError(header.id) + } + return lease + } catch (error: unknown) { + try { await lease.release() } + catch (releaseError: unknown) { throw new AggregateError([error, releaseError], 'Session creation and lock release failed') } + throw error + } + } + + private markerPath(id: SessionId): string { + return join(this.directory, `${createHash('sha256').update(id).digest('hex')}.json`) + } + + /** Decode one routing record and require it to name `id` in the configured database. */ + private readMarker(text: string, path: string, id: SessionId): void { + let stored: z.infer + try { stored = marker.parse(JSON.parse(text)) } + catch (error: unknown) { + throw new HarnessError(`Stored Segment routing record is invalid: ${path}`, 'SESSION_STORAGE_CORRUPT', { cause: error }) + } + if (stored.id !== id || stored.database !== this.sqlite.path) { + throw new HarnessError('Recorded Segment storage differs from the configured database; restore the original configuration', 'SESSION_STORAGE_IDENTITY') + } + } + + private async selected(id: SessionId, signal?: AbortSignal): Promise { + let text: string + try { text = await readFile(this.markerPath(id), 'utf8') } + catch (error: unknown) { + if (!isAbsent(error)) throw error + await this.sqlite.assertRoutingDatabase() + return this.sqlite.stat(id, signal) + } + this.readMarker(text, this.markerPath(id), id) + await this.sqlite.assertRoutingDatabase() + const snapshot = await this.sqlite.stat(id, signal) + if (snapshot === undefined) { + if (!await this.sqlite.hasDatabase()) { + throw new HarnessError('Recorded Segment database is missing; restore it before opening the Session', 'SESSION_STORAGE_MISSING') + } + throw new SessionPersistenceNotFoundError(id) + } + return snapshot + } + + /** + * Atomically publish durable backend selection once per Session in this provider after the database commit. + * @param id - committed Session identity. + */ + protected async publish(id: SessionId): Promise { + if (this.publishedRoutes.has(id)) return + if (process.platform === 'win32') await ensureDurableDirectoryWin32(this.directory) + else await mkdir(this.directory, { recursive: true, mode: 0o700 }) + const path = this.markerPath(id) + try { + this.readMarker(await readFile(path, 'utf8'), path, id) + await this.syncDirectory() + this.publishedRoutes.add(id) + return + } catch (error: unknown) { if (!isAbsent(error)) throw error } + const temporary = join(this.directory, `.route-${randomUUID()}.tmp`) + const file = await open(temporary, 'wx', 0o600) + try { + try { await file.writeFile(JSON.stringify({ id, database: this.sqlite.path }) + '\n'); await file.sync() } + finally { await file.close() } + try { + if (process.platform === 'win32') await publishNewFileWin32(temporary, path) + else await link(temporary, path) + } catch (error: unknown) { + if (error !== null && typeof error === 'object' && 'code' in error && error.code === 'EEXIST') { + this.readMarker(await readFile(path, 'utf8'), path, id) + } else throw error + } + await this.syncDirectory() + } finally { await rm(temporary, { force: true }) } + this.publishedRoutes.add(id) + } + + private async syncDirectory(): Promise { + if (process.platform === 'win32') return + const directory = await open(this.directory, 'r') + try { await directory.sync() } finally { await directory.close() } + } + + async create(header: SessionHeader, options?: SessionPersistenceCreateOptions) { + options?.signal?.throwIfAborted() + const snapshot = materializeCreateHeader(header) + await this.start() + await this.sqlite.assertRoutingDatabase() + // SQLite rejects an existing row itself; only the retained JSONL identity needs this check. + if (await this.jsonl.hasStoredJsonl(snapshot.id)) throw new SessionAlreadyExistsError(snapshot.id) + return this.sqlite.create(snapshot, options) + } + + async open(id: SessionId, access: SessionAccess, options?: SessionPersistenceOpenOptions) { + options?.signal?.throwIfAborted() + await this.start() + return await this.selected(id) ? this.sqlite.open(id, access, options?.signal) : this.migration.open(id, access, options) + } + + async stat(id: SessionId, options?: SessionPersistenceStatOptions) { + options?.signal?.throwIfAborted() + const snapshot = await this.selected(id, options?.signal) + options?.signal?.throwIfAborted() + return snapshot === undefined ? this.jsonl.stat(id, options) : snapshot + } + + async list(options?: SessionPersistenceListOptions) { + options?.signal?.throwIfAborted() + await this.sqlite.assertRoutingDatabase() + // Routing records publish after their commit, so reading them first guarantees each one's row is in the later scan. + let names: string[] = [] + try { names = await this.listLimit(async () => { + options?.signal?.throwIfAborted() + return readdir(this.directory) + }) } catch (error: unknown) { if (!isAbsent(error)) throw error } + const [{ entries: segmented, omitted }, entries] = await Promise.all([ + this.sqlite.scan(options?.signal), + this.jsonl.list(options), + ]) + // A row omitted for its header is still stored; only a routing record without a row is lost state. + const known = new Set([...segmented.map(entry => entry.header.id), ...omitted]) + // Routing records are named by their Session hash, so membership needs no record reads. + const routed = new Set([...known].map(id => basename(this.markerPath(id)))) + for (const name of names) { + if (name.endsWith('.json') && !routed.has(name)) { + throw new HarnessError('Recorded Segment Session is missing; restore its database before listing Sessions', 'SESSION_STORAGE_MISSING') + } + } + options?.signal?.throwIfAborted() + return [...entries.filter(entry => !known.has(entry.header.id)), ...segmented] + } + + async flush(): Promise { await this.sqlite.flush() } +} diff --git a/packages/session/session-persistence-sqlite/src/sqlite.ts b/packages/session/session-persistence-sqlite/src/sqlite.ts new file mode 100644 index 0000000000..3bfd9aab50 --- /dev/null +++ b/packages/session/session-persistence-sqlite/src/sqlite.ts @@ -0,0 +1,1012 @@ +/** SQLite event lists keyed by trace_uuid, projected through SessionPersistence handles. @module */ +import { LiveWriteBuffer } from './buffer.ts' +import { createHash, randomUUID } from 'node:crypto' +import { brandString } from '@deepseek-ai/dsh-brand' +import type { Branded } from '@deepseek-ai/dsh-brand' +import type { DatabaseSync, StatementSync } from 'node:sqlite' +import { mkdir, open, stat, readdir, realpath } from 'node:fs/promises' +import { dirname, join, resolve } from 'node:path' +import { setImmediate } from 'node:timers/promises' +import type { Context } from '@deepseek-ai/cordis' +import { z } from 'zod' +import { HarnessError } from '@deepseek-ai/dsh-llm' +import { SESSION_FORMAT_VERSION, KNOWN_SESSION_EVENT_TYPES, SessionLogOffset, SessionId as sessionIdentity } from '@deepseek-ai/dsh-session' +import type { SessionEvent, SessionHeader, SessionId } from '@deepseek-ai/dsh-session' +import { assertContiguous, materializeAppendBatch, validateStoredEvents, SessionAlreadyExistsError, + SessionAlreadyOwnedError, SessionFormatUnsupportedError, SessionHandleClosedError, SessionPersistenceCorruptionError, + SessionPersistenceNotFoundError, SessionPersistenceRevision, SessionReadOnlyError, + sessionFormatVersionRefusal } from '@deepseek-ai/dsh-session-persistence' +import type { SessionAccess, SessionHandle, SessionHandleAppendOptions, SessionHandleFlushOptions, + SessionHandleReadOptions, SessionPersistenceCreateOptions, SessionPersistenceSnapshot } from '@deepseek-ai/dsh-session-persistence' +import { decodeHeader, decodeEvent, materializeHeader } from './codec.ts' +import { SessionWriteLease } from './lease.ts' +import { ensureDurableDirectoryWin32 } from './win32.ts' +import { SessionFormatUnsupportedMigrationError } from '@deepseek-ai/dsh-session-format' +import type { SessionFormatEvent } from '@deepseek-ai/dsh-session-format' +import { restoreReleasedV4Artifact } from '@deepseek-ai/dsh-session-format-v3-to-v4' +import { sessionDir } from './paths.ts' + +/** Private Segment storage database schema version; incompatible versions are refused, never reset. */ +export const SCHEMA_VERSION = 1 +const APPLICATION_ID = 0x44535043 +// SQLite primary result codes; extended result codes retain the low byte. +const SQLITE_CORRUPT = 11, SQLITE_NOTADB = 26 +/** + * Internal scheduling constant, not deployment configuration: decoded events + * between two event-loop yields while reading a stored history slice. + */ +const READ_DECODE_YIELD_EVENTS = 2048 +/** SQLite busy handler wait for a locked database before an operation fails; a protocol constant shared by every opener. */ +const BUSY_TIMEOUT_MS = 5000 +/** Maximum intentional wait before a routed live session batch starts writing; matches the JSONL backend. */ +const LIVE_WRITE_BATCH_MAX_DELAY_MS = 200 +/** Admitted live events that start a write before the delay elapses, bounding one transaction's size. */ +const LIVE_WRITE_BATCH_MAX_EVENTS = 256 +type SegmentId = Branded<'SessionSegmentId'> +const segmentId = (value: string): SegmentId => brandString(value) +const metadata = z.object({ header: z.string(), event_count: z.number().int().nonnegative(), base_seq: z.number().int().nonnegative(), + tail_segment_uuid: z.string().transform(segmentId), inherited_count: z.number().int().nonnegative() }) +const traceIdentity = z.object({ trace_uuid: z.string().transform(sessionIdentity) }) +const TRACE_METADATA_SQL = `SELECT t.trace_uuid, header, tail_segment_uuid, inherited_count, base_seq, + base_seq + COALESCE((SELECT seq + 1 FROM events WHERE segment_uuid = s.segment_uuid ORDER BY seq DESC LIMIT 1), 0) AS event_count + FROM traces t LEFT JOIN segments s ON s.segment_uuid = t.tail_segment_uuid` +const segmentFields = { segment_uuid: z.string().transform(segmentId), event_count: z.number().int().nonnegative() } +const segmentRow = z.union([ + z.object({ ...segmentFields, parent_segment_uuid: z.null(), parent_end_seq: z.null(), base_seq: z.literal(0) }), + z.object({ ...segmentFields, parent_segment_uuid: z.string().transform(segmentId), + parent_end_seq: z.number().int().nonnegative(), base_seq: z.number().int().nonnegative() }), +]) +type Metadata = z.infer +type Segment = z.infer + +/** + * Whether a filesystem rejection reports a missing path. + * @param error - rejected value from a `node:fs` operation. + * @returns true for `ENOENT`. + */ +export function isAbsent(error: unknown): boolean { + return error !== null && typeof error === 'object' && 'code' in error && error.code === 'ENOENT' +} + +/** Normalize one rejected value for error causes and close-failure aggregation. */ +function asError(error: unknown): Error { + /* v8 ignore next -- rejected values are normally Error; normalize a hostile rejection. */ + return error instanceof Error ? error : new Error(String(error)) +} + +/** + * Build the provider-wide refusal after a transaction whose commit state cannot be known. + * @param cause - the failed COMMIT or ROLLBACK, with the original operation failure when present. + * @returns the error every later SQLite operation of this store rejects with. + */ +function unknownOutcome(cause: unknown): HarnessError { + return new HarnessError('SQLite transaction outcome is unknown; Segment storage is unusable until the session persistence plugin restarts', 'SESSION_STORAGE_UNKNOWN', { cause }) +} + +/** Resolved settings and provider callbacks for one SQLite Segment store. */ +export interface SqliteStoreOptions { + /** Absolute database path. */ + readonly path: string + /** Resolved JSONL root holding the per-Session write-lock directories and `.segments` routing records. */ + readonly legacyRoot: string + /** Publish a Session's routing record after its first commit. */ + readonly publish: (id: SessionId) => Promise + /** Claim a new Session across the provider's physical backends. */ + readonly acquireCreationLease: (header: SessionHeader) => Promise<{ release(): Promise }> + /** Report a background live-write failure; the Session's next durability barrier retries and rejects. */ + readonly report: (id: SessionId, error: unknown) => void +} + +/** Trace persistence over private predecessor-linked Segments in one SQLite database. */ +export class SqliteStore { + /** Absolute database path, recorded in routing records. */ + readonly path: string + private readonly legacyRoot: string + private readonly published: (id: SessionId) => Promise + private readonly acquireCreationLease: SqliteStoreOptions['acquireCreationLease'] + private readonly report: (id: SessionId, error: unknown) => void + private readonly pendingCreates = new Map() + private readonly creating = new Set() + private readonly directorySyncs = new Set() + private readonly statements = new Map() + private ready: Promise | undefined + private closing: Promise | undefined + private failure: Error | undefined + private readonly chains = new Map }>() + private readonly handles = new Set() + private readonly writers = new Map() + constructor(options: SqliteStoreOptions) { + this.path = options.path + this.legacyRoot = options.legacyRoot + this.published = options.publish + this.acquireCreationLease = options.acquireCreationLease + this.report = options.report + } + + private corruption(context: string, error: unknown): SessionPersistenceCorruptionError { + return new SessionPersistenceCorruptionError(context, { cause: asError(error) }) + } + + private parseHeader(id: SessionId, text: string): SessionHeader { + let value: unknown + try { value = JSON.parse(text) } + catch (error: unknown) { throw this.corruption(`session "${id}": stored SQLite header is not valid JSON`, error) } + const version = typeof value === 'object' && value !== null && !Array.isArray(value) + ? (value as { version?: unknown }).version + : undefined + if (typeof version !== 'number' || !Number.isSafeInteger(version)) { + throw new SessionPersistenceCorruptionError(`session "${id}": stored SQLite header has no valid version`, { + cause: new TypeError('missing or invalid session version'), + }) + } + if (version !== SESSION_FORMAT_VERSION) { + throw new SessionFormatUnsupportedError(sessionFormatVersionRefusal(id, version)) + } + try { return decodeHeader(value) } + catch (error: unknown) { throw this.corruption(`session "${id}": stored SQLite header is invalid`, error) } + } + + private database(): Promise { + if (this.failure !== undefined) return Promise.reject(this.failure) + return this.ready ??= this.initialize().catch((error: unknown) => { + this.ready = undefined + throw error + }) + } + + /** + * Refuse to use or create a database while routing records claim one that is missing. + * @returns resolves when the database file exists or no routing record requires it. + */ + async assertRoutingDatabase(): Promise { + if (this.ready !== undefined || await this.databaseFileExists()) return + let records: string[] + try { records = await readdir(join(this.legacyRoot, '.segments')) } + catch (error: unknown) { + if (isAbsent(error)) return + throw error + } + if (!records.some(record => record.endsWith('.json'))) return + // Another initializer may have created the database while routing records were read. + if (await this.databaseFileExists()) return + throw new HarnessError('The Segment database is missing but routing records remain; restore the database before using Sessions', 'SESSION_STORAGE_MISSING') + } + + private async initialize(): Promise { + await this.assertRoutingDatabase() + await this.ensureDirectory(dirname(this.path)) + // Retain the routing directory before the first Session commit. + await this.ensureDirectory(join(this.legacyRoot, '.segments')) + try { const file = await open(this.path, 'wx', 0o600); await file.close() } + catch (error: unknown) { + if (error === null || typeof error !== 'object' || !('code' in error) || error.code !== 'EEXIST') throw error + } + const { DatabaseSync } = await import('node:sqlite') + let db: DatabaseSync | undefined + try { + const opened = new DatabaseSync(this.path, { timeout: BUSY_TIMEOUT_MS }) + db = opened + // Readers can acquire a snapshot as soon as schema creation commits. + opened.exec('PRAGMA foreign_keys = ON; PRAGMA journal_mode = WAL; PRAGMA synchronous = FULL;') + this.transaction(opened, () => { + const current = this.schemaState(opened) + if (current.version === 0 && current.application === 0) { + const tables = opened.prepare("SELECT name FROM sqlite_schema WHERE type = 'table'").all() + if (tables.length !== 0) throw new HarnessError('Refusing an unrelated SQLite database', 'SESSION_STORAGE_FORMAT') + this.createSchema(opened) + } else if (current.version !== SCHEMA_VERSION || current.application !== APPLICATION_ID) { + throw new HarnessError('Unsupported SQLite persistence schema; database left intact', 'SESSION_STORAGE_FORMAT') + } + }) + return opened + } catch (error: unknown) { + db?.close() + if (error instanceof HarnessError + || error instanceof SessionPersistenceCorruptionError + || error instanceof SessionFormatUnsupportedError) throw error + if (error !== null && typeof error === 'object' && 'errcode' in error + && typeof error.errcode === 'number' && [SQLITE_CORRUPT, SQLITE_NOTADB].includes(error.errcode & 0xff)) { + throw this.corruption(`SQLite persistence database "${this.path}" is unreadable`, error) + } + throw error + } + } + + /** Persist newly created directory entries, retaining unfinished synchronization for initialization retries. */ + private async ensureDirectory(target: string): Promise { + /* v8 ignore start -- Windows uses write-through directory publication instead of directory fsync. */ + if (process.platform === 'win32') return ensureDurableDirectoryWin32(target) + /* v8 ignore stop */ + /* v8 ignore start -- Windows cannot fsync directory handles; its write-through publication returns above. */ + const firstCreated = await mkdir(target, { recursive: true, mode: 0o700 }) + if (firstCreated !== undefined) { + for (let current = resolve(target); ; current = dirname(current)) { + this.directorySyncs.add(dirname(current)) + if (current === resolve(firstCreated)) break + } + } + for (const directory of this.directorySyncs) { + const parent = await open(directory, 'r') + try { await parent.sync() } finally { await parent.close() } + this.directorySyncs.delete(directory) + } + /* v8 ignore stop */ + } + + private schemaState(db: DatabaseSync): { version: number; application: number } { + return { + version: z.object({ user_version: z.number() }).parse(db.prepare('PRAGMA user_version').get()).user_version, + application: z.object({ application_id: z.number() }).parse(db.prepare('PRAGMA application_id').get()).application_id, + } + } + + private createSchema(db: DatabaseSync): void { + db.exec(`CREATE TABLE segments ( + segment_uuid TEXT PRIMARY KEY, parent_segment_uuid TEXT REFERENCES segments(segment_uuid), parent_end_seq INTEGER, + base_seq INTEGER NOT NULL CHECK(base_seq >= 0), + CHECK((parent_segment_uuid IS NULL AND parent_end_seq IS NULL AND base_seq = 0) + OR (parent_segment_uuid IS NOT NULL AND parent_end_seq IS NOT NULL AND parent_end_seq >= 0 AND parent_segment_uuid != segment_uuid)) + ) STRICT; + CREATE TABLE traces ( + trace_uuid TEXT PRIMARY KEY, header TEXT NOT NULL, + tail_segment_uuid TEXT NOT NULL REFERENCES segments(segment_uuid), + inherited_count INTEGER NOT NULL CHECK(inherited_count >= 0) + ) STRICT; + CREATE UNIQUE INDEX exclusive_trace_head ON traces(tail_segment_uuid); + CREATE TABLE events ( + segment_uuid TEXT NOT NULL REFERENCES segments(segment_uuid), seq INTEGER NOT NULL CHECK(seq >= 0), + payload TEXT NOT NULL, PRIMARY KEY(segment_uuid, seq) + ) STRICT, WITHOUT ROWID; + CREATE TRIGGER events_no_update BEFORE UPDATE ON events BEGIN SELECT RAISE(ABORT, 'events are append-only'); END; + CREATE TRIGGER events_no_delete BEFORE DELETE ON events BEGIN SELECT RAISE(ABORT, 'events are append-only'); END; + CREATE TRIGGER segments_no_reparent BEFORE UPDATE OF parent_segment_uuid, parent_end_seq, base_seq ON segments + BEGIN SELECT RAISE(ABORT, 'segment ancestry is immutable'); END; + PRAGMA application_id = ${APPLICATION_ID}; PRAGMA user_version = ${SCHEMA_VERSION};`) + this.createAncestrySchema(db) + } + + /** Maintain immutable ancestor ranges in the same transaction as each new Segment. */ + private createAncestrySchema(db: DatabaseSync): void { + db.exec(`CREATE TABLE segment_ancestors ( + segment_uuid TEXT NOT NULL REFERENCES segments(segment_uuid), + ancestor_uuid TEXT NOT NULL REFERENCES segments(segment_uuid), + end_seq INTEGER NOT NULL CHECK(end_seq >= 0), + PRIMARY KEY(segment_uuid, ancestor_uuid), CHECK(segment_uuid != ancestor_uuid) + ) STRICT, WITHOUT ROWID; + CREATE TRIGGER segments_index_ancestors AFTER INSERT ON segments WHEN NEW.parent_segment_uuid IS NOT NULL BEGIN + INSERT INTO segment_ancestors VALUES (NEW.segment_uuid, NEW.parent_segment_uuid, NEW.parent_end_seq); + INSERT INTO segment_ancestors SELECT NEW.segment_uuid, ancestor_uuid, end_seq + FROM segment_ancestors WHERE segment_uuid = NEW.parent_segment_uuid; + END; + CREATE TRIGGER ancestors_no_update BEFORE UPDATE ON segment_ancestors + BEGIN SELECT RAISE(ABORT, 'segment ancestry is immutable'); END; + CREATE TRIGGER ancestors_no_delete BEFORE DELETE ON segment_ancestors + BEGIN SELECT RAISE(ABORT, 'segment ancestry is immutable'); END;`) + } + + private transaction(db: DatabaseSync, operation: () => T, mode: 'IMMEDIATE' | 'DEFERRED' = 'IMMEDIATE'): T { + this.assertHealthy() + db.exec(`BEGIN ${mode}`) + let result: T + try { result = operation() } + catch (error: unknown) { + try { if (db.isTransaction) db.exec('ROLLBACK') } + catch (rollbackError: unknown) { + this.failure = unknownOutcome(new AggregateError([error, rollbackError], 'SQLite operation and rollback failed')) + throw this.failure + } + throw error + } + try { db.exec('COMMIT'); return result } + catch (commitError: unknown) { + this.failure = unknownOutcome(commitError) + try { if (db.isTransaction) db.exec('ROLLBACK') } + catch (rollbackError: unknown) { + this.failure = unknownOutcome(new AggregateError([commitError, rollbackError], 'SQLite COMMIT and ROLLBACK failed')) + } + throw this.failure + } + } + + private assertHealthy(): void { + if (this.failure !== undefined) throw this.failure + } + + private check(): void { + if (this.closing !== undefined) throw new HarnessError('SQLite persistence is closing', 'SESSION_STORAGE_CLOSED') + this.assertHealthy() + } + + private statement(db: DatabaseSync, sql: string): StatementSync { + let statement = this.statements.get(sql) + if (statement === undefined) { + statement = db.prepare(sql) + this.statements.set(sql, statement) + } + return statement + } + + private row(db: DatabaseSync, id: SessionId) { + this.assertHealthy() + const raw = this.statement(db, `${TRACE_METADATA_SQL} WHERE t.trace_uuid = ?`).get(id) + if (raw === undefined) return undefined + return this.parseMetadata(raw, id) + } + + private parseMetadata(raw: unknown, id: SessionId): Metadata { + try { return metadata.parse(raw) } + catch (error: unknown) { throw this.corruption(`session "${id}": stored SQLite trace metadata is invalid`, error) } + } + + private segment(db: DatabaseSync, id: SegmentId): Segment { + const row = this.statement(db, 'SELECT s.*, COALESCE((SELECT seq + 1 FROM events WHERE segment_uuid = s.segment_uuid ORDER BY seq DESC LIMIT 1), 0) AS event_count FROM segments s WHERE segment_uuid = ?').get(id) + if (row === undefined) throw new HarnessError('Trace references a missing segment', 'SESSION_STORAGE_CORRUPT') + try { return segmentRow.parse(row) } + catch (error: unknown) { throw this.corruption(`stored SQLite segment "${id}" metadata is invalid`, error) } + } + + /** Fetch indexed ancestor metadata together, retaining the authoritative chain checks during reads. */ + private parents(db: DatabaseSync, id: SegmentId, offset: number, nodes: Map): void { + const rows = this.statement(db, `SELECT s.*, COALESCE((SELECT seq + 1 FROM events WHERE segment_uuid = s.segment_uuid + ORDER BY seq DESC LIMIT 1), 0) AS event_count FROM segment_ancestors a + JOIN segments s ON s.segment_uuid = a.ancestor_uuid + WHERE a.segment_uuid = ? AND (s.base_seq > ? OR s.base_seq + a.end_seq > ?)`).all(id, offset, offset) + for (const row of rows) { + let parsed: Segment + try { parsed = segmentRow.parse(row) } + catch (error: unknown) { throw this.corruption('Stored SQLite predecessor metadata is invalid', error) } + nodes.set(parsed.segment_uuid, parsed) + } + } + + private newSegment(db: DatabaseSync, id: SegmentId, parent: Segment | undefined, end: number): void { + const base = parent === undefined ? 0 : parent.base_seq + end + this.statement(db, 'INSERT INTO segments VALUES (?, ?, ?, ?)').run(id, parent?.segment_uuid ?? null, parent === undefined ? null : end, base) + } + + /** + * Locate the Segment a fork of `source` at `end` attaches to, through the ancestor index rather than the parent chain. + * Fork creation is the consumer; `end` never exceeds the source event count. + * @param db - open database inside the caller's transaction. + * @param source - forked Trace metadata. + * @param end - exclusive logical prefix length shared with the source. + * @returns the attachment Segment and the prefix length within it; no Segment for an empty prefix. + */ + cut(db: DatabaseSync, source: Metadata, end: number): { parent?: Segment; end: number } { + if (end === 0) return { end: 0 } + const tail = this.segment(db, source.tail_segment_uuid) + if (end >= tail.base_seq) return { parent: tail, end: end - tail.base_seq } + // Among ancestors starting at or before the cut, the deepest one holds it; an empty-prefix tie is logically equivalent. + const raw = this.statement(db, `SELECT s.*, a.end_seq AS visible_end, COALESCE((SELECT seq + 1 FROM events + WHERE segment_uuid = s.segment_uuid ORDER BY seq DESC LIMIT 1), 0) AS event_count FROM segment_ancestors a + JOIN segments s ON s.segment_uuid = a.ancestor_uuid + WHERE a.segment_uuid = ? AND s.base_seq <= ? ORDER BY s.base_seq DESC, a.end_seq DESC LIMIT 1`).get(tail.segment_uuid, end) + if (raw === undefined) throw new HarnessError('Invalid Trace segment chain', 'SESSION_STORAGE_CORRUPT') + let parent: Segment, visible: number + try { + parent = segmentRow.parse(raw) + visible = z.object({ visible_end: z.number().int().nonnegative() }).parse(raw).visible_end + } catch (error: unknown) { throw this.corruption('Stored SQLite predecessor metadata is invalid', error) } + const within = end - parent.base_seq + if (within > visible || within > parent.event_count) throw new HarnessError('Invalid segment offset', 'SESSION_STORAGE_CORRUPT') + return { parent, end: within } + } + + /** + * Reserve a pending Trace; its rows commit with the first append or flush. + * @param header - loop-owned metadata. + * @param options - optional cancellation and inherited count. + * @returns exclusive in-process write handle. + */ + async create(header: SessionHeader, options?: SessionPersistenceCreateOptions): Promise { + this.check() + options?.signal?.throwIfAborted() + // Preserve the existing seeded/cut refusal before reserving a Session. + const meta = materializeHeader(header, options?.inheritedEventCount) + const inheritedCount = options?.inheritedEventCount ?? 0 + if (this.creating.has(meta.id) || this.pendingCreates.has(meta.id) || this.writers.has(meta.id)) { + throw new SessionAlreadyExistsError(meta.id) + } + this.creating.add(meta.id) + try { + if (await this.stat(meta.id) !== undefined) throw new SessionAlreadyExistsError(meta.id) + await this.assertRoutingDatabase() + this.check() + options?.signal?.throwIfAborted() + this.pendingCreates.set(meta.id, { header: meta, inheritedCount, head: segmentId(randomUUID()) }) + return await this.admit(meta, 'write', inheritedCount, true) + } catch (error: unknown) { + this.pendingCreates.delete(meta.id) + throw error + } finally { + this.creating.delete(meta.id) + } + } + + /** + * Acquire a handle; a write open reads the stored log once to validate it before the restore read. + * @param id - trace_uuid identifying the event list. + * @param access - read or in-process exclusive write access. + * @param signal - optional cancellation. + * @param ownership - optional import lease, transferred only to a successful write open. + * @returns handle over the original stored identity. + */ + async open(id: SessionId, access: SessionAccess, signal?: AbortSignal, + ownership?: { release(): Promise }): Promise { + this.check(); signal?.throwIfAborted() + const pending = this.pendingCreates.get(id) + if (pending !== undefined) return this.admit(pending.header, access, pending.inheritedCount) + if (!await this.exists()) throw new SessionPersistenceNotFoundError(id) + const db = await this.database() + this.check(); signal?.throwIfAborted() + const row = this.row(db, id) + if (row === undefined) throw new SessionPersistenceNotFoundError(id) + const header = this.parseHeader(id, row.header) + if (header.id !== id) throw new HarnessError('SQLite Trace identity mismatch', 'SESSION_STORAGE_CORRUPT') + const handle = await this.admit(header, access, row.inherited_count, false, ownership) + try { + signal?.throwIfAborted() + if (access === 'write') handle.prime(await this.read(handle.header, 0, Number.MAX_SAFE_INTEGER)) + signal?.throwIfAborted() + } catch (error: unknown) { + try { await handle.close() } + catch (closeError: unknown) { throw new AggregateError([error, closeError], 'SQLite open and handle cleanup failed') } + throw error + } + return handle + } + + /** + * Claim existing Session ownership for a legacy import and its subsequent write open. + * @param header - legacy metadata identifying the artifact lock. + * @returns database and artifact leases, retained until release or successful write-open transfer. + */ + acquireSessionLease(header: SessionHeader): Promise<{ release(): Promise }> { + this.check() + return this.acquireWriteLease(header, false) + } + + /** + * Import a validated legacy log as one independent root Segment under caller-held Session ownership. + * A transaction failure leaves no partial Session; publication failure leaves the committed row authoritative. + * @param header - current logical metadata decoded by the legacy reader. + * @param inheritedCount - exact logical inheritance count from the legacy header. + * @param events - complete, contiguous legacy prefix without consumer-generated repairs. + * @param signal - cancellation checked before the synchronous transaction. + */ + async importLegacy(header: SessionHeader, inheritedCount: SessionLogOffset, + events: readonly SessionEvent[], signal?: AbortSignal): Promise { + this.check(); signal?.throwIfAborted() + const storedHeader = materializeHeader(header, inheritedCount) + const batch = materializeAppendBatch(events) + assertContiguous(header.id, batch, 0) + const payloads = batch.map(event => JSON.stringify(event)) + const db = await this.database() + this.check(); signal?.throwIfAborted() + this.transaction(db, () => { + if (this.row(db, header.id) !== undefined) throw new SessionAlreadyExistsError(header.id) + const head = segmentId(randomUUID()) + this.newSegment(db, head, undefined, 0) + this.statement(db, 'INSERT INTO traces VALUES (?, ?, ?, ?)').run(header.id, JSON.stringify(storedHeader), head, inheritedCount) + const insert = this.statement(db, 'INSERT INTO events (segment_uuid, seq, payload) VALUES (?, ?, ?)') + for (const [seq, payload] of payloads.entries()) insert.run(head, seq, payload) + }) + await this.route(header.id) + } + + /** Publish routing after a commit; the committed rows stay authoritative when publication fails. */ + private async route(id: SessionId): Promise { + try { await this.published(id) } + catch (error: unknown) { + throw new HarnessError('Session history committed, but routing publication failed; close and reopen the Session', + 'SESSION_STORAGE_PUBLICATION', { cause: error }) + } + } + + /** Hold both database-wide Session ownership and the root's artifact/creation guards. */ + private async acquireWriteLease(header: SessionHeader, created: boolean): Promise<{ release(): Promise }> { + await this.database() + const database = await realpath(this.path) + const directory = join(`${database}.session-locks`, createHash('sha256').update(header.id).digest('hex')) + const shared = await SessionWriteLease.acquire(directory, header.id) + let artifact: { release(): Promise } + try { + artifact = created + ? await this.acquireCreationLease(header) + : await SessionWriteLease.acquire(sessionDir(this.legacyRoot, header.cwd, header.id), header.id) + } catch (error: unknown) { + try { + await shared.release() + } catch (releaseError: unknown) { + throw new AggregateError([error, releaseError], 'SQLite write ownership acquisition and rollback failed') + } + throw error + } + return { + release: async () => { + const results = await Promise.allSettled([artifact.release(), shared.release()]) + const failures = results + .filter(result => result.status === 'rejected') + .map((result): unknown => result.reason) + if (failures.length > 1) throw new AggregateError(failures, 'SQLite write ownership release failed') + if (failures.length === 1) throw failures[0] + }, + } + } + + /** + * Admit a handle. A write open takes the cross-process lease now; a created Session takes it + * immediately before its first commit, so an unused create leaves no filesystem footprint. + */ + private async admit(header: SessionHeader, access: SessionAccess, inheritedCount = 0, created = false, + ownership?: { release(): Promise }): Promise { + if (access === 'write' && this.writers.has(header.id)) throw new SessionAlreadyOwnedError(header.id) + let lease = access === 'write' && !created + ? ownership ?? await this.acquireWriteLease(header, false) + : undefined + try { + this.check() + const handle = new SqliteSessionHandle(header, access, this, async () => { + this.handles.delete(handle) + if (![...this.handles].some(active => active.id === header.id)) this.chains.delete(header.id) + if (access === 'write') { + this.writers.delete(header.id) + this.pendingCreates.delete(header.id) + } + await lease?.release() + }, async () => { + lease ??= await this.acquireWriteLease(header, true) + }, () => { + this.assertHealthy() + }, + SessionLogOffset(inheritedCount)) + this.handles.add(handle) + if (access === 'write') this.writers.set(header.id, handle) + return handle + } catch (error: unknown) { + await lease?.release() + throw error + } + } + + /** + * Read only the requested indexed list slice, validating the decoded event vocabulary. + * @param header - selected Trace metadata. + * @param offset - first sequence. + * @param length - maximum number of events. + * @returns independently owned event slice. + */ + async read(header: SessionHeader, offset: number, length: number): Promise { + this.assertHealthy() + if (this.pendingCreates.has(header.id)) return [] + const db = await this.database() + const stored = this.transaction(db, () => { + const meta = this.row(db, header.id) + if (meta === undefined) throw new SessionPersistenceNotFoundError(header.id) + let cached = this.chains.get(header.id) + if (cached === undefined || cached.head !== meta.tail_segment_uuid) { + cached = { head: meta.tail_segment_uuid, nodes: new Map() } + this.chains.set(header.id, cached) + } + const visited = new Set(), ranges: { segment: Segment; end: number }[] = [] + let current = this.segment(db, meta.tail_segment_uuid), end = meta.event_count - current.base_seq + cached.nodes.set(current.segment_uuid, current) + for (;;) { + if (visited.has(current.segment_uuid) || end < 0 || end > current.event_count) { + throw new HarnessError('Invalid Trace segment chain', 'SESSION_STORAGE_CORRUPT') + } + visited.add(current.segment_uuid) + ranges.push({ segment: current, end }) + if (current.parent_segment_uuid === null || current.base_seq <= offset) break + const child = current + if (!cached.nodes.has(child.parent_segment_uuid)) this.parents(db, child.segment_uuid, offset, cached.nodes) + current = cached.nodes.get(child.parent_segment_uuid) ?? this.segment(db, child.parent_segment_uuid) + cached.nodes.set(current.segment_uuid, current) + end = child.parent_end_seq + if (current.base_seq + end !== child.base_seq) throw new HarnessError('Invalid segment offset', 'SESSION_STORAGE_CORRUPT') + } + const payloads: string[] = [], stop = offset + Math.min(length, Math.max(0, meta.event_count - offset)) + const select = this.statement(db, 'SELECT payload FROM events WHERE segment_uuid = ? AND seq >= ? AND seq < ? ORDER BY seq') + for (const { segment, end } of ranges.reverse()) { + const start = Math.max(0, offset - segment.base_seq), finish = Math.min(end, stop - segment.base_seq) + if (finish <= start) continue + const rows = select.all(segment.segment_uuid, start, finish) + if (rows.length !== finish - start) throw new HarnessError('SQLite segment is incomplete', 'SESSION_STORAGE_CORRUPT') + for (const row of rows) { + const payload = row['payload'] + if (typeof payload !== 'string') { + throw this.corruption(`session "${header.id}": stored SQLite event payload is not text`, + new TypeError('expected a SQLite TEXT payload')) + } + payloads.push(payload) + } + } + return { payloads, inheritedCount: meta.inherited_count, complete: offset === 0 && stop === meta.event_count } + }, 'DEFERRED') + const decoded: (SessionFormatEvent & SessionEvent)[] = [] + for (const [index, payload] of stored.payloads.entries()) { + // One synchronous transaction fetched the rows; decoding yields so a long history does not stall the event loop. + if (index > 0 && index % READ_DECODE_YIELD_EVENTS === 0) await setImmediate() + try { + decoded.push(decodeEvent(JSON.parse(payload))) + } catch (error: unknown) { + if (error instanceof SessionFormatUnsupportedMigrationError) throw new SessionFormatUnsupportedError(error.message) + throw this.corruption(`session "${header.id}": stored event at index ${offset + index} is invalid`, error) + } + } + if (stored.complete) { + try { + restoreReleasedV4Artifact({ header: { ...header, delegationDepth: header.delegationDepth ?? 0 }, + inheritedEventCount: stored.inheritedCount, events: decoded }, KNOWN_SESSION_EVENT_TYPES) + } catch (error: unknown) { + if (error instanceof SessionFormatUnsupportedMigrationError) throw new SessionFormatUnsupportedError(error.message) + throw this.corruption(`session "${header.id}": stored V4 relationships are invalid`, error) + } + } + const events = validateStoredEvents(header, decoded, { kind: 'sqlite', path: this.path }) + assertContiguous(header.id, events, offset) + return events + } + + /** + * Insert a new suffix atomically; recover the append position through the event index without updating metadata counters. + * @param header - selected Trace metadata. + * @param batch - independently materialized new events. + */ + async append(header: SessionHeader, batch: readonly SessionEvent[]): Promise { + const db = await this.database() + const payloads = batch.map(event => JSON.stringify(event)) + this.transaction(db, () => { + const row = this.ensureRow(db, header) + assertContiguous(header.id, batch, row.event_count) + const start = row.event_count - row.base_seq + const insert = this.statement(db, 'INSERT INTO events (segment_uuid, seq, payload) VALUES (?, ?, ?)') + for (const [index, payload] of payloads.entries()) insert.run(row.tail_segment_uuid, start + index, payload) + }) + this.pendingCreates.delete(header.id) + await this.route(header.id) + } + + private ensureRow(db: DatabaseSync, header: SessionHeader): Metadata { + let row = this.row(db, header.id) + if (row !== undefined) { + if (this.pendingCreates.has(header.id)) throw new SessionAlreadyExistsError(header.id) + return row + } + const pending = this.pendingCreates.get(header.id) + if (pending === undefined) throw new SessionPersistenceNotFoundError(header.id) + const head = pending.head + this.newSegment(db, head, undefined, 0) + const storedHeader = materializeHeader(header, SessionLogOffset(pending.inheritedCount)) + this.statement(db, 'INSERT INTO traces VALUES (?, ?, ?, ?)').run( + header.id, JSON.stringify(storedHeader), head, pending.inheritedCount, + ) + row = this.row(db, header.id) + if (row === undefined) throw new HarnessError('Committed Session metadata is unavailable', 'SESSION_STORAGE_CORRUPT') + return row + } + + /** + * Materialize a pending empty Session at its explicit durability barrier. + * @param header - pending Session metadata. + */ + async materialize(header: SessionHeader): Promise { + this.assertHealthy() + const pending = this.pendingCreates.get(header.id) + if (pending === undefined) return + const db = await this.database() + this.transaction(db, () => { this.ensureRow(db, header) }) + this.pendingCreates.delete(header.id) + await this.route(header.id) + } + + /** + * Observe metadata without querying any event payloads. + * @param id - selected trace_uuid. + * @param signal - optional cancellation. + * @returns header, exact count and revision, or absence. + */ + async stat(id: SessionId, signal?: AbortSignal): Promise { + this.check(); signal?.throwIfAborted() + const pending = this.pendingCreates.get(id) + // Each create mints its own head, so a closed unmaterialized create and a + // later create of the same id never share a revision. + if (pending !== undefined) return { header: pending.header, revision: SessionPersistenceRevision(`pending:${pending.head}`) } + if (!await this.exists()) return undefined + const row = this.row(await this.database(), id) + if (row === undefined) return undefined + return this.snapshot(id, row, this.parseHeader(id, row.header)) + } + + private snapshot(id: SessionId, row: Metadata, header: SessionHeader): SessionPersistenceSnapshot { + if (header.id !== id) throw new HarnessError('SQLite Trace identity mismatch', 'SESSION_STORAGE_CORRUPT') + // SQLite rows always hold the current Session format. + return { header, formatStatus: 'current', eventCount: row.event_count, + revision: SessionPersistenceRevision(`${row.tail_segment_uuid}:${row.event_count}`) } + } + + private async databaseFileExists(): Promise { + try { await stat(this.path); return true } + catch (error: unknown) { + if (isAbsent(error)) return false + throw error + } + } + + private async exists(): Promise { + return this.ready !== undefined || this.databaseFileExists() + } + + /** + * Whether the configured database file exists without opening or creating it. + * @returns true when the database file exists. + */ + async hasDatabase(): Promise { return await this.exists() } + + /** + * Open or create the configured database and validate its schema. + * @returns resolves once the database is ready for session operations. + */ + async start(): Promise { this.check(); await this.database() } + + /** + * List Sessions, omitting rows whose stored header is corrupt or of an unsupported version. + * Matching an unreadable JSONL generation header, an omitted row still rejects direct + * `open` and `stat`. Invalid row metadata and an identity mismatch reject the listing. + * @param signal - optional cancellation. + * @returns listed snapshots and the ids of stored rows omitted for their header. + */ + async scan(signal?: AbortSignal): Promise<{ entries: SessionPersistenceSnapshot[]; omitted: Set }> { + this.check(); signal?.throwIfAborted() + const pending = [...this.pendingCreates.keys()] + const entries: SessionPersistenceSnapshot[] = [], omitted = new Set(), seen = new Set() + if (await this.exists()) { + const db = await this.database() + // One joined query observes all durable metadata in the same read snapshot. + this.transaction(db, () => { + for (const trace of this.statement(db, `${TRACE_METADATA_SQL} ORDER BY t.trace_uuid`).all()) { + signal?.throwIfAborted() + const id = traceIdentity.parse(trace).trace_uuid + seen.add(id) + const row = this.parseMetadata(trace, id) + let header: SessionHeader + try { header = this.parseHeader(id, row.header) } + catch (error: unknown) { + /* v8 ignore next -- parseHeader classifies every header failure; any other error must not be skipped. */ + if (!(error instanceof SessionPersistenceCorruptionError || error instanceof SessionFormatUnsupportedError)) throw error + omitted.add(id) + continue + } + entries.push(this.snapshot(id, row, header)) + } + }, 'DEFERRED') + } + for (const id of pending) { + if (seen.has(id)) continue + const entry = await this.stat(id, signal) + if (entry !== undefined) entries.push(entry) + } + return { entries, omitted } + } + + /** + * Register live-event and durability listeners for the provider lifetime. + * @param ctx - owning parent scope, disposed after injected consumers. + * @param beforeClose - optional admitted-import settlement before handle teardown. + */ + install(ctx: Context, beforeClose?: () => Promise): void { + ctx.effect(() => async () => { await beforeClose?.(); await this.close() }) + ctx.on('session/event', (session, event) => { + const handle = this.writers.get(session.id) + if (handle !== undefined) void handle.receive(event).catch((error: unknown) => { + ctx.logger.error(`SQLite persistence failed for ${session.id}: ${String(error)}`) + }) + }) + ctx.on('session/flush', session => this.writers.get(session.id)?.flush()) + ctx.on('session/disposed', (session) => { + const handle = this.writers.get(session.id) + if (handle !== undefined) void handle.close().catch((error: unknown) => { + ctx.logger.error(`SQLite handle close failed for ${session.id}: ${String(error)}`) + }) + }) + } + + /** + * Report a background failure while retaining the rejected durability state. + * @param id - affected Session. + * @param error - retained failure. + */ + reportFailure(id: SessionId, error: unknown): void { this.report(id, error) } + + /** Join all admitted writer operations; commits already use FULL synchronous durability. */ + async flush(): Promise { + this.check() + const results = await Promise.allSettled([...this.writers.values()].map(async (handle) => { + try { await handle.flush() } catch (error: unknown) { + if (error instanceof SessionHandleClosedError) await handle.close(); else throw error + } + })) + const failures = results.filter(result => result.status === 'rejected').map((result): unknown => result.reason) + if (failures.length > 0) throw new AggregateError(failures, 'SQLite flush failed') + } + + /** Drain admitted handles before closing the database connection. */ + close(): Promise { + return this.closing ??= (async () => { + const results = await Promise.allSettled([...this.handles].map(handle => handle.close())) + const failures = results.filter(result => result.status === 'rejected').map((result): unknown => result.reason) + if (this.ready !== undefined) { + // Initialization closes its connection before rejecting; disposal only joins that attempt. + const db = await this.ready.catch((_error: unknown) => undefined) + try { db?.close() } catch (error: unknown) { failures.push(error) } + } + this.statements.clear() + if (failures.length > 0) throw new AggregateError(failures, 'SQLite disposal failed') + })() + } +} + +/** One SessionHandle over a logical SQLite event stream. */ +export class SqliteSessionHandle implements SessionHandle { + private closed = false + private pending: Promise = Promise.resolve() + private closing: Promise | undefined + private failure: Error | undefined + private primed: SessionEvent[] | undefined + private readonly buffer: LiveWriteBuffer + constructor(readonly header: SessionHeader, readonly access: SessionAccess, + private readonly store: SqliteStore, + private readonly release: () => Promise, private readonly acquireLease: () => Promise, + private readonly checkStorage: () => void, + readonly inheritedEventCount = SessionLogOffset(0)) { + this.buffer = new LiveWriteBuffer({ + delayMs: LIVE_WRITE_BATCH_MAX_DELAY_MS, + maxEvents: LIVE_WRITE_BATCH_MAX_EVENTS, + enqueue: operation => this.enqueue(operation), + persist: batch => this.store.append(this.header, batch), + retry: (error) => { + if (error instanceof HarnessError && error.code === 'SESSION_STORAGE_PUBLICATION') { + this.failure = error + return false + } + return true + }, + canSchedule: () => this.failure === undefined && this.closing === undefined, + }) + } + get id() { return this.header.id } + + private check(): void { + if (this.closing !== undefined) throw new SessionHandleClosedError(this.id, 'access') + this.checkStorage() + if (this.failure !== undefined) throw this.failure + } + + async read(offset = 0, length = Number.MAX_SAFE_INTEGER, options?: SessionHandleReadOptions) { + this.check(); options?.signal?.throwIfAborted() + if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(length) || length < 0) throw new RangeError('read offset and length must be non-negative safe integers') + await this.pending + this.check(); options?.signal?.throwIfAborted() + const primed = this.primed + this.primed = undefined + const events = primed === undefined + ? await this.store.read(this.header, offset, length) : primed.slice(offset, offset + length) + // The synchronous SQLite read cannot be interrupted; a cancelled read still returns no events. + options?.signal?.throwIfAborted() + return { eventState: 'detached' as const, events } + } + + /** + * Retain the validated write-open prefix for the immediate restore read. + * @param events - exclusively owned validated prefix. + */ + prime(events: SessionEvent[]): void { this.primed = events } + + /** + * Admit one live event into the bounded batching window, including while close drains the routed producer. + * @param event - newly emitted event, copied before asynchronous persistence. + * @returns admission completion; durability requires flush. Rejects once the close drain has finished. + */ + receive(event: SessionEvent): Promise { + // Provider failures retain their identity across Session event admission. + try { this.checkStorage() } catch (error: unknown) { return Promise.reject(asError(error)) } + try { + if (this.closed) throw new SessionHandleClosedError(this.id, 'receive') + this.primed = undefined + const batch = materializeAppendBatch([event]) + this.buffer.append(batch, (error) => { this.store.reportFailure(this.id, error) }) + return Promise.resolve() + } catch (error: unknown) { + this.failure = new HarnessError('Session event admission failed', 'SESSION_STORAGE_FAILED', { cause: error }) + return Promise.reject(this.failure) + } + } + + /** Drain admitted live records without forcing an unused empty Session to materialize. */ + drainLive(): Promise { + if (this.buffer.length === 0 && !this.buffer.active) return this.pending + return this.buffer.drain() + } + + async append(events: readonly SessionEvent[], options?: SessionHandleAppendOptions): Promise { + this.check() + if (this.access !== 'write') throw new SessionReadOnlyError(this.id, 'append') + if (events.length === 0) return + options?.signal?.throwIfAborted() + const batch = materializeAppendBatch(events) + // Live and explicit batches own separate durable writes. Drain admitted live + // events first so an aborted or failed explicit append cannot take them. + await this.drainLive() + /* v8 ignore next -- concurrent admission can follow a completed drain before append resumes. */ + while (this.buffer.length > 0) await this.drainLive() + options?.signal?.throwIfAborted() + this.primed = undefined + return this.enqueue(async () => { + options?.signal?.throwIfAborted() + try { + await this.store.append(this.header, batch) + } catch (error: unknown) { + if (error instanceof HarnessError && error.code === 'SESSION_STORAGE_PUBLICATION') this.failure = error + throw error + } + }, options?.signal) + } + + async flush(options?: SessionHandleFlushOptions): Promise { + this.check() + if (this.access !== 'write') throw new SessionReadOnlyError(this.id, 'flush') + options?.signal?.throwIfAborted() + do { await this.drainLive() } while (this.buffer.length > 0) + return this.enqueue(async () => { + options?.signal?.throwIfAborted() + try { await this.store.materialize(this.header) } + catch (error: unknown) { + if (error instanceof HarnessError && error.code === 'SESSION_STORAGE_PUBLICATION') this.failure = error + throw error + } + }, options?.signal) + } + + private enqueue(operation: () => Promise, signal?: AbortSignal): Promise { + const next = this.pending.then(async () => { + this.checkStorage() + if (this.failure !== undefined) throw this.failure + signal?.throwIfAborted() + await this.acquireLease() + await operation() + }) + this.pending = next.then(() => undefined, () => undefined) + return next + } + + close(): Promise { + if (this.closing !== undefined) return this.closing + const drained = this.drainLive() + return this.closing = (async () => { + const failures: Error[] = [] + try { + let draining = drained + for (;;) { + await draining + await this.pending + if (this.buffer.length === 0) break + draining = this.drainLive() + } + if (this.failure !== undefined) failures.push(this.failure) + } catch (error: unknown) { + failures.push(asError(error)) + } + await this.pending + this.closed = true + try { await this.release() } + catch (error: unknown) { failures.push(asError(error)) } + if (failures.length > 1) throw new AggregateError(failures, `session "${this.id}": close failed to drain and release`) + if (failures[0] !== undefined) throw failures[0] + })() + } + [Symbol.asyncDispose]() { return this.close() } +} diff --git a/packages/session/session-persistence-sqlite/src/win32.ts b/packages/session/session-persistence-sqlite/src/win32.ts new file mode 100644 index 0000000000..a35af3609a --- /dev/null +++ b/packages/session/session-persistence-sqlite/src/win32.ts @@ -0,0 +1,211 @@ +/** + * Windows durable namespace helpers for Session persistence backends. + * + * POSIX publishes a newly-created log by creating a directory entry and then + * fsyncing the parent directory. Windows does not expose that parent-directory + * fsync contract through Node, so the Windows path uses the native durable + * namespace primitive instead: create a staging object in the target directory + * and publish it with `MoveFileExW(..., MOVEFILE_WRITE_THROUGH)` without + * replacement or cross-volume copy fallback. + * + * @module dsh-session-persistence-sqlite/win32 + */ +// JSONL retains a separate copy so the two backends need no shared helper exports. +/* jscpd:ignore-start */ + +import { createHash } from 'node:crypto' +import { mkdtemp, rm, stat } from 'node:fs/promises' +import { join, parse, resolve, toNamespacedPath } from 'node:path' + +type MoveFileExW = (existing: string, replacement: string, flags: number) => number +type CreateSemaphoreW = (security: null, initial: number, maximum: number, name: string) => number +type WaitForSingleObject = (handle: number, milliseconds: number) => number +type ReleaseSemaphore = (handle: number, count: number, previous: null) => number +type CloseHandle = (handle: number) => number +type GetLastError = () => number + +interface Win32Bindings { + moveFileExW: MoveFileExW + createSemaphoreW: CreateSemaphoreW + waitForSingleObject: WaitForSingleObject + releaseSemaphore: ReleaseSemaphore + closeHandle: CloseHandle + getLastError: GetLastError +} + +interface Win32ErrnoException extends NodeJS.ErrnoException { + win32Code: number + dest: string +} + +const MOVEFILE_WRITE_THROUGH = 0x00000008 +const WAIT_OBJECT_0 = 0 +const WAIT_TIMEOUT = 0x00000102 +const ERROR_FILE_NOT_FOUND = 2 +const ERROR_PATH_NOT_FOUND = 3 +const ERROR_ACCESS_DENIED = 5 +const ERROR_NOT_SAME_DEVICE = 17 +const ERROR_SHARING_VIOLATION = 32 +const ERROR_FILE_EXISTS = 80 +const ERROR_INVALID_NAME = 123 +const ERROR_ALREADY_EXISTS = 183 + +let bindings: Win32Bindings | undefined + +/** Load the small Win32 API lazily so non-Windows processes never load Koffi. */ +async function win32(): Promise { + if (bindings !== undefined) return bindings + const koffi = (await import('koffi')).default + const kernel32 = koffi.load('kernel32.dll') + bindings = { + moveFileExW: kernel32.func('__stdcall', 'MoveFileExW', 'int', ['str16', 'str16', 'uint']) as MoveFileExW, + createSemaphoreW: kernel32.func('__stdcall', 'CreateSemaphoreW', 'intptr', ['void*', 'int', 'int', 'str16']) as CreateSemaphoreW, + waitForSingleObject: kernel32.func('__stdcall', 'WaitForSingleObject', 'uint', ['intptr', 'uint']) as WaitForSingleObject, + releaseSemaphore: kernel32.func('__stdcall', 'ReleaseSemaphore', 'int', ['intptr', 'int', 'void*']) as ReleaseSemaphore, + closeHandle: kernel32.func('__stdcall', 'CloseHandle', 'int', ['intptr']) as CloseHandle, + getLastError: kernel32.func('__stdcall', 'GetLastError', 'uint', []) as GetLastError, + } + return bindings +} + +function errnoCode(win32Code: number): string { + switch (win32Code) { + case ERROR_FILE_NOT_FOUND: + case ERROR_PATH_NOT_FOUND: + return 'ENOENT' + case ERROR_ACCESS_DENIED: + return 'EACCES' + case ERROR_NOT_SAME_DEVICE: + return 'EXDEV' + case ERROR_SHARING_VIOLATION: + return 'EBUSY' + case ERROR_FILE_EXISTS: + case ERROR_ALREADY_EXISTS: + return 'EEXIST' + case ERROR_INVALID_NAME: + return 'EINVAL' + default: + return 'EIO' + } +} + +function win32Error(syscall: string, win32Code: number, path: string, dest: string): Win32ErrnoException { + const code = errnoCode(win32Code) + const error = new Error(`${syscall} ${code} (Win32 ${win32Code}): ${path} -> ${dest}`) as Win32ErrnoException + error.code = code + error.errno = win32Code + error.syscall = syscall + error.path = path + error.dest = dest + error.win32Code = win32Code + return error +} + +function isENOENT(error: unknown): boolean { + return (error as NodeJS.ErrnoException | null)?.code === 'ENOENT' +} + +function isEEXIST(error: unknown): boolean { + return (error as NodeJS.ErrnoException | null)?.code === 'EEXIST' +} + +async function assertDirectory(path: string): Promise { + try { + // A bare drive root is already short, and Node rejects its extended-length + // spelling as EISDIR. Descendants retain the namespace for long-path probes. + const probe = path === parse(path).root ? path : toNamespacedPath(path) + const info = await stat(probe) + if (info.isDirectory()) return true + const error = new Error(`path exists but is not a directory: ${path}`) as NodeJS.ErrnoException + error.code = 'ENOTDIR' + error.path = path + throw error + } catch (error) { + if (isENOENT(error)) return false + throw error + } +} + +/** + * Publish `existing` at `replacement` with Windows write-through rename + * semantics. The destination must not already exist; the move must stay within + * the volume (no copy fallback flag is set). + * @param existing - the synced staging path to move. + * @param replacement - the final path, which must not already exist. + */ +export async function publishNewFileWin32(existing: string, replacement: string): Promise { + const api = await win32() + const ok = api.moveFileExW(toNamespacedPath(existing), toNamespacedPath(replacement), MOVEFILE_WRITE_THROUGH) + if (ok === 0) throw win32Error('MoveFileExW', api.getLastError(), existing, replacement) +} + +/** + * Acquire the session write lock as a named kernel semaphore (count 1) whose + * name is derived from the canonical lock path. A kernel object never touches + * the filesystem, so readers, searches, and directory removal proceed freely + * while the lock is held; a second acquirer's zero-timeout wait times out + * (`EBUSY`); and when the last handle closes — including on any process + * death — the object is destroyed, so a successor's create starts fresh. + * @param path - the lock file path the name is derived from (case-folded: + * Windows paths are case-insensitive). + * @returns the open semaphore handle, released via {@link releaseLockHandleWin32}. + */ +export async function acquireLockHandleWin32(path: string): Promise { + const api = await win32() + const name = `Local\\dsh-session-lock-${createHash('sha256').update(resolve(path).toLowerCase()).digest('hex')}` + const handle = api.createSemaphoreW(null, 1, 1, name) + if (handle === 0) throw win32Error('CreateSemaphoreW', api.getLastError(), path, name) + const wait = api.waitForSingleObject(handle, 0) + if (wait === WAIT_OBJECT_0) return handle + api.closeHandle(handle) + if (wait === WAIT_TIMEOUT) throw win32Error('WaitForSingleObject', ERROR_SHARING_VIOLATION, path, name) + throw win32Error('WaitForSingleObject', api.getLastError(), path, name) +} + +/** + * Release a lock from {@link acquireLockHandleWin32}: restore the semaphore + * count and close the handle (the object dies with its last handle). + * @param handle - the open semaphore handle. + */ +export async function releaseLockHandleWin32(handle: number): Promise { + const api = await win32() + const released = api.releaseSemaphore(handle, 1, null) + const closed = api.closeHandle(handle) + if (released === 0 || closed === 0) throw win32Error('ReleaseSemaphore', api.getLastError(), `handle:${handle}`, `handle:${handle}`) +} + +/** + * Create `target` and its missing ancestors with durable Windows namespace + * publication. Each missing directory is first created as a random staging + * sibling, then moved to its final name with `MOVEFILE_WRITE_THROUGH`; races + * with another creator are accepted only after verifying the winner is a + * directory. + * @param target - the absolute directory path to create durably when absent. + */ +export async function ensureDurableDirectoryWin32(target: string): Promise { + const absolute = resolve(target) + const root = parse(absolute).root + await assertDirectory(root) + + const segments = absolute.slice(root.length).split(/[\\/]+/).filter(part => part.length > 0) + let current = root + for (const segment of segments) { + const next = join(current, segment) + if (!await assertDirectory(next)) await createLeafDirectoryWin32(current, next) + current = next + } +} + +async function createLeafDirectoryWin32(parent: string, target: string): Promise { + // Keep the staging component independent of the target basename so a legal + // 255-byte target component does not make mkdtemp's sibling name too long. + const staging = await mkdtemp(toNamespacedPath(join(parent, '.dsh-mkdir-'))) + try { + await publishNewFileWin32(staging, target) + } catch (error) { + await rm(staging, { recursive: true, force: true }) + if (isEEXIST(error) && await assertDirectory(target)) return + throw error + } +} +/* jscpd:ignore-end */ diff --git a/packages/session/session-persistence-sqlite/tests/buffer.spec.ts b/packages/session/session-persistence-sqlite/tests/buffer.spec.ts new file mode 100644 index 0000000000..4add452c38 --- /dev/null +++ b/packages/session/session-persistence-sqlite/tests/buffer.spec.ts @@ -0,0 +1,109 @@ +/** Shared live batching retains ordered work across backend and queue failures. @module */ +import { afterEach, expect, it, vi } from 'vitest' +import { SessionSeq } from '@deepseek-ai/dsh-session' +import type { SessionEvent } from '@deepseek-ai/dsh-session' +import { LiveWriteBuffer } from '../src/buffer.ts' + +const event = (seq: number): SessionEvent<'turn/start'> => ({ type: 'turn/start', seq: SessionSeq(seq), time: 0, data: { turn: seq + 1 } }) +afterEach(() => { vi.useRealTimers() }) + +it('keeps the first event deadline when later events arrive before the batch limit', async () => { + vi.useFakeTimers() + const persist = vi.fn(async (_events: readonly SessionEvent[]) => {}) + const buffer = new LiveWriteBuffer({ delayMs: 10, maxEvents: 8, + enqueue: async operation => operation(), persist, retry: () => true, canSchedule: () => true, + }) + buffer.append([event(0)], vi.fn()) + await vi.advanceTimersByTimeAsync(5) + buffer.append([event(1)], vi.fn()) + await vi.advanceTimersByTimeAsync(5) + expect(persist).toHaveBeenCalledExactlyOnceWith([event(0), event(1)]) + expect(buffer.length).toBe(0) +}) + +it('retains an uncommitted batch after a write fails and retries it at the explicit checkpoint', async () => { + vi.useFakeTimers() + const failure = new Error('disk full') + const persist = vi.fn(async (_events: readonly SessionEvent[]) => {}).mockRejectedValueOnce(failure) + const report = vi.fn() + const buffer = new LiveWriteBuffer({ delayMs: 10, maxEvents: 2, + enqueue: async operation => operation(), persist, retry: () => true, canSchedule: () => true, + }) + buffer.append([event(0)], report) + await vi.advanceTimersByTimeAsync(10) + expect(report).toHaveBeenCalledWith(failure) + expect(buffer.length).toBe(1) + await buffer.drain() + expect(persist).toHaveBeenCalledTimes(2) + expect(buffer.length).toBe(0) +}) + +it('does not replay a batch whose database commit succeeded before routing publication failed', async () => { + vi.useFakeTimers() + const failure = new Error('routing publication failed') + const persist = vi.fn(async (_events: readonly SessionEvent[]) => { throw failure }) + const report = vi.fn() + const buffer = new LiveWriteBuffer({ delayMs: 10, maxEvents: 2, + enqueue: async operation => operation(), persist, retry: () => false, canSchedule: () => true, + }) + buffer.append([event(0)], report) + await vi.advanceTimersByTimeAsync(10) + expect(report).toHaveBeenCalledWith(failure) + expect(buffer.length).toBe(0) + await buffer.drain() + expect(persist).toHaveBeenCalledOnce() +}) + +it('holds events when automatic scheduling stops and drains them explicitly', async () => { + vi.useFakeTimers() + const persist = vi.fn(async (_events: readonly SessionEvent[]) => {}) + const buffer = new LiveWriteBuffer({ delayMs: 10, maxEvents: 2, + enqueue: async operation => operation(), persist, retry: () => true, canSchedule: () => false, + }) + buffer.append([event(0)], vi.fn()) + await vi.advanceTimersByTimeAsync(100) + expect(persist).not.toHaveBeenCalled() + await buffer.drain() + expect(persist).toHaveBeenCalledExactlyOnceWith([event(0)]) +}) + +it('pauses automatic writes when serialization rejects before taking a batch, then retries without losing events', async () => { + vi.useFakeTimers() + const failure = new Error('queue unavailable') + const enqueue = vi.fn(async (operation: () => Promise) => operation()).mockRejectedValueOnce(failure) + const persist = vi.fn(async (_events: readonly SessionEvent[]) => {}) + const report = vi.fn() + const buffer = new LiveWriteBuffer({ delayMs: 10, maxEvents: 2, enqueue, persist, retry: () => true, canSchedule: () => true }) + buffer.append([event(0)], report) + await vi.advanceTimersByTimeAsync(10) + expect(report).toHaveBeenCalledWith(failure) + buffer.append([event(1), event(2)], report) + await vi.advanceTimersByTimeAsync(100) + expect(enqueue).toHaveBeenCalledOnce() + expect(buffer.length).toBe(3) + await buffer.drain() + expect(persist.mock.calls.map(([batch]) => batch.map(item => item.seq))).toEqual([[0, 1], [2]]) + expect(buffer.length).toBe(0) +}) + +it('joins concurrent drains and keeps events admitted during a commit in the next bounded batch', async () => { + vi.useFakeTimers() + const release = Promise.withResolvers(), entered = Promise.withResolvers() + const batches: number[][] = [] + const buffer = new LiveWriteBuffer({ delayMs: 10, maxEvents: 2, + enqueue: async operation => operation(), + persist: async (batch) => { batches.push(batch.map(item => item.seq)); entered.resolve(undefined); await release.promise }, + retry: () => true, canSchedule: () => true, + }) + buffer.append([event(0)], vi.fn()) + const drain = buffer.drain() + await entered.promise + expect(buffer.active).toBe(true) + expect(buffer.drain()).toBe(drain) + buffer.append([event(1), event(2), event(3)], vi.fn()) + release.resolve(undefined) + await drain + expect(batches).toEqual([[0], [1, 2], [3]]) + expect(buffer.active).toBe(false) + await vi.runAllTimersAsync() +}) diff --git a/packages/session/session-persistence-sqlite/tests/codec.spec.ts b/packages/session/session-persistence-sqlite/tests/codec.spec.ts new file mode 100644 index 0000000000..777288af78 --- /dev/null +++ b/packages/session/session-persistence-sqlite/tests/codec.spec.ts @@ -0,0 +1,57 @@ +/** SQLite JSON decoding preserves logical Session records. @module */ +import type { SessionHeader } from '@deepseek-ai/dsh-session' +import { describe, expect, it } from 'vitest' +import { SESSION_FORMAT_VERSION, SessionId, SessionLogOffset } from '@deepseek-ai/dsh-session' +import { decodeHeader, decodeEvent, materializeHeader } from '../src/codec.ts' + +const header: SessionHeader = { version: SESSION_FORMAT_VERSION, id: SessionId('codec'), createdAt: 0, isSeeded: false } + +describe('SQLite header decoding', () => { + it('reads logical metadata and preserves optional parent metadata', () => { + expect(decodeHeader(header)).toEqual({ ...header, delegationDepth: 0 }) + const parent = { ...header, cwd: '/work', parentSession: SessionId('parent'), origin: 'subagent' as const, delegationDepth: 1, agentPreset: 'worker' } + expect(decodeHeader(parent)).toEqual(parent) + }) + + it.each([null, { ...header, version: 100 }, { ...header, version: 3 }, { ...header, delegationDepth: -1 }])( + 'refuses malformed or unsupported logical metadata %j', (value) => { + expect(() => decodeHeader(value)).toThrow() + }, + ) +}) + +describe('SQLite event decoding', () => { + const event = { type: 'feedback/record', seq: 0, time: 0, data: { text: 'fixture' } } + + it('preserves decoded fields and accepts ignorable extension events', () => { + expect(decodeEvent(event)).toEqual(event) + expect(decodeEvent({ ...event, type: 'fixture/extension', ignorable: true })).toEqual({ + ...event, type: 'fixture/extension', ignorable: true, + }) + }) + + it.each([-1, 0.5, Number.MAX_SAFE_INTEGER + 1, '0', null])( + 'refuses invalid sequence %s before Session adoption', (seq) => { + expect(() => decodeEvent({ ...event, seq })).toThrow() + }, + ) + + it.each(['type', 'seq', 'time', 'data'])('refuses a missing %s field', (key) => { + const row = Object.fromEntries(Object.entries(event).filter(([field]) => field !== key)) + expect(() => decodeEvent(row)).toThrow() + }) + + it.each([ + { type: 1 }, { time: 0.5 }, { time: Number.MAX_SAFE_INTEGER + 1 }, + { ignorable: false }, { extra: true }, { data: undefined }, + ])('refuses malformed envelope fields %j', (fields) => { + expect(() => decodeEvent({ ...event, ...fields })).toThrow() + }) +}) + +it('requires the inherited count to agree with seeded metadata', () => { + expect(() => materializeHeader({ ...header, isSeeded: true })).toThrow('seeded session header requires') + expect(() => materializeHeader(header, SessionLogOffset(1))).toThrow('unseeded session header inherited') + expect(materializeHeader(header)).toEqual({ ...header, delegationDepth: 0 }) + expect(materializeHeader({ ...header, isSeeded: true }, SessionLogOffset(0))).toMatchObject({ isSeeded: true }) +}) diff --git a/packages/session/session-persistence-sqlite/tests/creation-identity.spec.ts b/packages/session/session-persistence-sqlite/tests/creation-identity.spec.ts new file mode 100644 index 0000000000..f6b555e055 --- /dev/null +++ b/packages/session/session-persistence-sqlite/tests/creation-identity.spec.ts @@ -0,0 +1,138 @@ +/** Session creation identity and consumer teardown across persistence instances. @module */ +import { Context } from '@deepseek-ai/cordis' +import { writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { expect, it, onTestFinished, vi } from 'vitest' +import { SESSION_FORMAT_VERSION, SessionId, SessionSeq } from '@deepseek-ai/dsh-session' +import type { SessionHeader, SessionEvent } from '@deepseek-ai/dsh-session' +import { SessionAlreadyExistsError, SessionAlreadyOwnedError } from '@deepseek-ai/dsh-session-persistence' +import { SessionWriteLease } from '../src/lease.ts' +import { generationLogPath, toHeaderLine } from '../../session-persistence-jsonl/src/format.ts' +import { persistenceFixture } from './fixtures/persistence.ts' + +const header: SessionHeader = { version: SESSION_FORMAT_VERSION, id: SessionId('competing'), createdAt: 0, isSeeded: false } +const event = (turn: number): SessionEvent<'turn/start'> => ({ type: 'turn/start', seq: SessionSeq(0), time: 0, data: { turn } }) + +async function fixture() { + const storage = await persistenceFixture() + const mount = async () => { + const backend = await storage.mount('sqlite') + return backend.context + } + return { root: storage.root, mount } +} + +it('preserves the identity refusal and release failure without retaining either lock', async () => { + const { mount, root } = await fixture() + const a = await mount(), b = await mount() + const first = await a.sessionPersistence.create(header) + const second = await b.sessionPersistence.create({ ...header, cwd: join(root, 'other-project') }) + await first.flush(); await first.close() + await writeFile(generationLogPath(root, header.cwd, header.id, header.version, 'none'), JSON.stringify(toHeaderLine(header)) + '\n') + const failure = new Error('creation lease release failed') + const spy = vi.spyOn(SessionWriteLease.prototype, 'release').mockImplementationOnce(async function (this: SessionWriteLease) { + spy.mockRestore() + await this.release() + throw failure + }) + try { + await expect(second.flush()).rejects.toMatchObject({ errors: [expect.any(SessionAlreadyExistsError), failure] }) + } finally { spy.mockRestore() } + await expect(second.flush()).rejects.toBeInstanceOf(SessionAlreadyExistsError) + await second.close() +}) + +it('excludes another provider while the first creation holds the Session write lock', async () => { + const { mount, root } = await fixture() + const a = await mount(), b = await mount() + const first = await a.sessionPersistence.create(header) + const second = await b.sessionPersistence.create({ ...header, cwd: join(root, 'other-project') }) + const acquired = Promise.withResolvers(), release = Promise.withResolvers() + const acquire = SessionWriteLease.acquire.bind(SessionWriteLease) + const spy = vi.spyOn(SessionWriteLease, 'acquire').mockImplementationOnce(async (...args) => { + const lease = await acquire(...args) + acquired.resolve(undefined) + await release.promise + return lease + }) + onTestFinished(() => { release.resolve(undefined); spy.mockRestore() }) + const writing = first.append([event(1)]) + try { + await acquired.promise + await expect(second.append([event(2)])).rejects.toBeInstanceOf(SessionAlreadyOwnedError) + } finally { release.resolve(undefined); spy.mockRestore(); await writing; await first.close() } + await expect(second.append([event(2)])).rejects.toBeInstanceOf(SessionAlreadyExistsError) + await second.close() +}) + +it.each([false, true])('refuses a losing create with different cwd=%s', async (differentCwd) => { + const { mount, root } = await fixture() + const a = await mount(), b = await mount() + const first = await a.sessionPersistence.create(header) + const second = await b.sessionPersistence.create({ ...header, ...differentCwd ? { cwd: join(root, 'project') } : {} }) + await first.append([event(1)]); await first.close() + const result = await second.append([event(2)]).then(() => 'committed', (error: unknown) => error) + await second.close() + const restarted = await mount() + const listed = await restarted.sessionPersistence.list() + const reader = await restarted.sessionPersistence.open(header.id, 'read') + let stored: readonly SessionEvent[] + try { stored = (await reader.read()).events } finally { await reader.close() } + expect(result).toBeInstanceOf(SessionAlreadyExistsError) + expect(listed.map(entry => entry.header.id)).toEqual([header.id]) + expect(stored).toEqual([event(1)]) +}) + +it.each(['provider', 'root', 'consumer-first'] as const)('preserves the final event during %s teardown', async (owner) => { + const storage = await persistenceFixture() + const { context: ctx, provider } = await storage.mount('sqlite') + const entered = Promise.withResolvers(), release = Promise.withResolvers() + onTestFinished(() => { release.resolve(undefined) }) + const consumer = await ctx.plugin({ name: 'final-writer', inject: ['sessionPersistence', 'sessions'], + async apply(consumerCtx: Context) { + const sessions = consumerCtx.sessions + const live = sessions.prepare(SessionId('final')) + // Own the Session and final dependency use in one ordered effect, as the Agent factory does. + consumerCtx.effect(function* () { + yield sessions.enter(live) + sessions.announce(live) + yield async () => { + entered.resolve(undefined) + await release.promise + live.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) + await sessions.flush(live) + } + }) + await consumerCtx.sessionPersistence.create(live.header) + live.append('turn/start', { turn: 1 }) + await consumerCtx.sessions.flush(live) + }, + }) + const consumerStop = owner === 'consumer-first' ? consumer.dispose() : undefined + if (consumerStop !== undefined) await entered.promise + let finished = false + const stop = (owner === 'root' ? ctx.fiber.dispose() : provider.dispose()).then(() => { finished = true }) + await entered.promise + // Immediate inspection after a microtask only checks the known consumer barrier. + await Promise.resolve(undefined) + expect(finished).toBe(false) + expect(ctx.events.dispatch('emit', ['session/event'])).toHaveLength(1) + release.resolve(undefined) + await stop + await consumerStop + const { context: fresh } = await storage.mount('sqlite') + const reader = await fresh.sessionPersistence.open(SessionId('final'), 'read') + try { expect((await reader.read()).events.map(item => item.type)).toEqual(['turn/start', 'turn/end']) } + finally { await reader.close() } +}) + +it('rejects creation of an existing legacy JSONL identity before reserving a SQLite writer', async () => { + const fixture = await persistenceFixture() + const jsonl = await fixture.mount('jsonl') + const writer = await jsonl.persistence.create(header) + await writer.flush(); await writer.close() + const sqlite = await fixture.mount('sqlite') + await expect(sqlite.persistence.create(header)).rejects.toBeInstanceOf(SessionAlreadyExistsError) + const reader = await sqlite.persistence.open(header.id, 'read') + await reader.close() +}) diff --git a/packages/session/session-persistence-sqlite/tests/directory-durability.spec.ts b/packages/session/session-persistence-sqlite/tests/directory-durability.spec.ts new file mode 100644 index 0000000000..60d2f55453 --- /dev/null +++ b/packages/session/session-persistence-sqlite/tests/directory-durability.spec.ts @@ -0,0 +1,93 @@ +/** SQLite directory entries settle before database creation, including initialization retries. @module */ +import { mkdtemp, rm, stat } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { afterEach, expect, it, onTestFinished, vi } from 'vitest' +import { sqliteLogs } from './fixtures/store.ts' + +const observed = vi.hoisted(() => ({ database: '', failAt: '', creationError: undefined as Error | undefined, + events: [] as { path: string; operation: string }[] })) +vi.mock('node:fs/promises', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, open: async (...args: Parameters) => { + const path = String(args[0]) + if (path === observed.database && args[1] === 'wx' && observed.creationError !== undefined) throw observed.creationError + const handle = await actual.open(...args) + if (path === observed.database) observed.events.push({ path, operation: 'database-open' }) + if (args[1] === 'r') { + const sync = handle.sync.bind(handle), close = handle.close.bind(handle) + handle.sync = async () => { + observed.events.push({ path, operation: 'sync' }) + if (path === observed.failAt) throw new Error('fixture directory sync failed') + await sync() + } + handle.close = async () => { + observed.events.push({ path, operation: 'close' }) + await close() + } + } + return handle + } } +}) + +afterEach(() => { observed.database = ''; observed.failAt = ''; observed.creationError = undefined; observed.events = [] }) + +async function fixture(custom: boolean) { + const base = await mkdtemp(join(tmpdir(), 'sqlite-directory-')) + const root = join(base, 'profiles', 'sessions') + const path = custom ? join(base, 'databases', 'nested', 'sessions.sqlite') : join(root, '.segments', 'sessions.sqlite') + const logs = sqliteLogs(path, root) + observed.database = path + onTestFinished(async () => { try { await logs.close() } finally { await rm(base, { recursive: true, force: true }) } }) + return { base, root, path, logs } +} + +// Windows publishes new directories with MOVEFILE_WRITE_THROUGH rather than opening them for fsync. +it.skipIf(process.platform === 'win32').each([false, true])( + 'syncs new directory ancestors before creating SQLite (custom path: %s)', async (custom) => { + const { base, root, logs } = await fixture(custom) + await logs.start() + const databaseOpen = observed.events.findIndex(event => event.operation === 'database-open') + expect(databaseOpen).toBeGreaterThan(0) + const synced = observed.events.slice(0, databaseOpen).filter(event => event.operation === 'sync').map(event => event.path) + expect(synced).toEqual(expect.arrayContaining(custom + ? [base, join(base, 'databases'), join(base, 'profiles'), root] + : [base, join(base, 'profiles'), root])) + expect(synced).not.toContain(dirname(base)) + }, +) + +it.skipIf(process.platform === 'win32')('closes a failed directory sync and repeats ancestor sync on initialization retry', async () => { + const { base, path, logs } = await fixture(true) + observed.failAt = base + await expect(logs.start()).rejects.toThrow('fixture directory sync failed') + await expect(stat(path)).rejects.toMatchObject({ code: 'ENOENT' }) + expect(observed.events.at(-1)).toEqual({ path: base, operation: 'close' }) + observed.failAt = '' + observed.events = [] + await logs.start() + expect(observed.events).toContainEqual({ path: base, operation: 'sync' }) +}) + +it('preserves a database creation failure after directory preparation and permits retry', async () => { + const { path, logs } = await fixture(true) + const failure = Object.assign(new Error('fixture database creation denied'), { code: 'EACCES' }) + observed.creationError = failure + await expect(logs.start()).rejects.toBe(failure) + await expect(stat(path)).rejects.toMatchObject({ code: 'ENOENT' }) + observed.creationError = undefined + await expect(logs.start()).resolves.toBeUndefined() +}) + +// Existing directory entries need no new publication; POSIX is the only directory-fsync path. +it.skipIf(process.platform === 'win32')('opens existing storage without synchronizing shared ancestor directories', async () => { + const { root, path, logs } = await fixture(true) + await logs.start() + await logs.close() + observed.events = [] + const reopened = sqliteLogs(path, root) + try { + await reopened.start() + expect(observed.events.filter(event => event.operation === 'sync')).toEqual([]) + } finally { await reopened.close() } +}) diff --git a/packages/session/session-persistence-sqlite/tests/fixtures/legacy-opener.mjs b/packages/session/session-persistence-sqlite/tests/fixtures/legacy-opener.mjs new file mode 100644 index 0000000000..389bc2b60a --- /dev/null +++ b/packages/session/session-persistence-sqlite/tests/fixtures/legacy-opener.mjs @@ -0,0 +1,53 @@ +/** Built-package import holder with stdin barriers for ownership handoff. @module */ +import { Context } from '@deepseek-ai/cordis' +import { createInterface } from 'node:readline' +import * as persistence from '@deepseek-ai/dsh-session-persistence-sqlite' + +const [root, id, access, pause] = process.argv.slice(2) +const ctx = new Context() +const lines = createInterface({ input: process.stdin }) +const commands = lines[Symbol.asyncIterator]() +try { + if (pause === 'start') { + process.stdout.write('ready\n') + await commands.next() + } + await ctx.plugin(persistence, { root, compression: 'none' }) + if (pause === 'pause') { + const reader = Reflect.get(ctx.sessionPersistence, 'jsonl') + const prepare = reader.prepare.bind(reader) + reader.prepare = async (...args) => { + process.stdout.write('reading\n') + await commands.next() + return prepare(...args) + } + } + if (pause === 'wait') { + const sqlite = Reflect.get(ctx.sessionPersistence, 'sqlite') + const acquire = sqlite.acquireSessionLease.bind(sqlite) + let reported = false + sqlite.acquireSessionLease = async (...args) => { + try { return await acquire(...args) } + catch (error) { + if (!reported && error.name === 'SessionAlreadyOwnedError') { + reported = true + process.stdout.write('contended\n') + } + throw error + } + } + } + try { + await using handle = await ctx.sessionPersistence.open(id, access) + process.stdout.write('opened\n') + await commands.next() + } catch (error) { + process.stdout.write(`${error.name}\n`) + // The suite asserts on the name; the message and cause go to the inherited stderr for diagnosis. + process.stderr.write(`legacy opener ${access} ${id}: ${String(error)}${error.cause === undefined ? '' : ` (cause: ${String(error.cause)})`}\n`) + } +} finally { + await ctx.fiber.dispose() + lines.close() + process.stdin.destroy() +} diff --git a/packages/session/session-persistence-sqlite/tests/fixtures/persistence.ts b/packages/session/session-persistence-sqlite/tests/fixtures/persistence.ts new file mode 100644 index 0000000000..9a69d9a1c7 --- /dev/null +++ b/packages/session/session-persistence-sqlite/tests/fixtures/persistence.ts @@ -0,0 +1,38 @@ +/** Isolated persistence providers sharing one test-owned storage directory. @module */ +import { Context } from '@deepseek-ai/cordis' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { onTestFinished } from 'vitest' +import * as SqlitePersistence from '../../src/index.ts' +import * as JsonlPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' +import type { JsonlCompression } from '@deepseek-ai/dsh-session-persistence-jsonl' +import SessionStore from '@deepseek-ai/dsh-session' + +/** + * Allocate private storage and close every mounted provider before removing it. + * @returns storage root and factories for independently owned providers. + */ +export async function persistenceFixture() { + const root = await mkdtemp(join(tmpdir(), 'dsh-sqlite-persistence-')) + const contexts: Context[] = [] + onTestFinished(async () => { + let failures: unknown[] + try { + const results = await Promise.allSettled(contexts.map(context => context.fiber.dispose())) + failures = results.filter(result => result.status === 'rejected').map((result): unknown => result.reason) + } finally { + await rm(root, { recursive: true, force: true }) + } + if (failures.length > 0) throw new AggregateError(failures, 'Persistence fixture disposal failed') + }) + async function mount(storage: 'sqlite' | 'jsonl', compression: JsonlCompression = 'none') { + const context = new Context() + contexts.push(context) + await context.plugin(SessionStore) + const plugin = storage === 'sqlite' ? SqlitePersistence : JsonlPersistence + const provider = await context.plugin(plugin, { root, compression }) + return { context, persistence: context.sessionPersistence, provider } + } + return { root, mount } +} diff --git a/packages/session/session-persistence-sqlite/tests/fixtures/store.ts b/packages/session/session-persistence-sqlite/tests/fixtures/store.ts new file mode 100644 index 0000000000..9554e5c2c7 --- /dev/null +++ b/packages/session/session-persistence-sqlite/tests/fixtures/store.ts @@ -0,0 +1,129 @@ +/** SQLite store fixtures and observations of durable event rows. @module */ +import { createHash, randomUUID } from 'node:crypto' +import { readdir } from 'node:fs/promises' +import { basename, join } from 'node:path' +import { DatabaseSync } from 'node:sqlite' +import type { StatementSync } from 'node:sqlite' +import { z } from 'zod' +import { brandString } from '@deepseek-ai/dsh-brand' +import { onTestFinished, vi } from 'vitest' +import { SESSION_FORMAT_VERSION, SessionSeq } from '@deepseek-ai/dsh-session' +import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session' +import { SqliteStore } from '../../src/sqlite.ts' +import type { SqliteStoreOptions } from '../../src/sqlite.ts' +import { SessionWriteLease } from '../../src/lease.ts' +import { sessionDir } from '../../src/paths.ts' + +/** + * Construct a store with the plugin defaults and no-op provider callbacks. + * @param path - database path. + * @param root - legacy root holding lock directories and routing records. + * @param overrides - option replacements for the test. + * @returns an unopened store. + */ +export function sqliteLogs(path: string, root: string, overrides: Partial = {}): SqliteStore { + return new SqliteStore({ path, legacyRoot: root, + acquireCreationLease: header => SessionWriteLease.acquire(sessionDir(root, header.cwd, header.id), header.id), + publish: async () => {}, report: () => {}, ...overrides }) +} + +/** + * Populate a persisted shared prefix for Segment read and cut-selection tests. + * @param logs - store containing the durable source. + * @param source - source Session. + * @param target - child fixture identity. + * @param prefix - prefix selecting the shared length. + */ +export async function sharedHistory(logs: SqliteStore, source: SessionId, target: SessionId, + prefix: readonly SessionEvent[]): Promise { + const snapshot = await logs.stat(source) + if (snapshot === undefined) throw new Error('Missing source fixture') + // Cached statements must use the connection owned by this store. + const db = await logs['database']() + { + const stored = z.object({ header: z.string(), inherited_count: z.number(), base_seq: z.number(), + tail_segment_uuid: z.string().transform(value => brandString[1]['tail_segment_uuid']>(value)) }) + .parse(db.prepare('SELECT header, inherited_count, tail_segment_uuid, base_seq FROM traces JOIN segments ON segment_uuid = tail_segment_uuid WHERE trace_uuid = ?').get(source)) + const cut = logs.cut(db, { ...stored, event_count: z.number().parse(snapshot.eventCount) }, prefix.length) + const segment = randomUUID() + const marker: SessionEvent<'session/end-seed'> = { type: 'session/end-seed', seq: SessionSeq(prefix.length), time: 0, data: { inherited: true } } + db.exec('BEGIN IMMEDIATE') + try { + const id = brandString[1]['tail_segment_uuid']>(segment) + logs['newSegment'](db, id, cut.parent, cut.end) + db.prepare('INSERT INTO traces VALUES (?, ?, ?, ?)').run(target, + JSON.stringify({ version: SESSION_FORMAT_VERSION, id: target, createdAt: 0, isSeeded: true, + delegationDepth: 0 }), segment, prefix.length) + db.prepare('INSERT INTO events VALUES (?, 0, ?)').run(segment, JSON.stringify(marker)) + db.exec('COMMIT') + } catch (error) { db.exec('ROLLBACK'); throw error } + } +} + +/** + * Report the backend that durably holds one Session from its routing record. + * @param root - legacy root. + * @param id - Session identity. + * @returns `sqlite` when a routing record exists, otherwise `jsonl`. + */ +export async function routeOf(root: string, id: SessionId): Promise<'sqlite' | 'jsonl'> { + const marker = join(root, '.segments', `${createHash('sha256').update(id).digest('hex')}.json`) + return (await readdir(join(root, '.segments'))).includes(basename(marker)) ? 'sqlite' : 'jsonl' +} + +/** + * Count event payload rows and Segment metadata queries issued by the store. + * @returns live counters, restored when the test finishes. + */ +export function countSqliteReads(): { payloadRows: () => number; segmentQueries: () => number } { + let payloadRows = 0, segmentQueries = 0 + // oxlint-disable-next-line typescript/unbound-method -- Called with the intercepted database as receiver below. + const prepare = DatabaseSync.prototype.prepare + const spy = vi.spyOn(DatabaseSync.prototype, 'prepare').mockImplementation(function (this: DatabaseSync, sql: string) { + const statement = prepare.call(this, sql) + if (sql.startsWith('SELECT s.*')) { + const get = statement.get.bind(statement), all = statement.all.bind(statement) + Object.defineProperty(statement, 'get', { value: (...args: Parameters) => { + segmentQueries++ + return get(...args) + } }) + Object.defineProperty(statement, 'all', { value: (...args: Parameters) => { + segmentQueries++ + return all(...args) + } }) + } + if (sql === 'SELECT payload FROM events WHERE segment_uuid = ? AND seq >= ? AND seq < ? ORDER BY seq') { + const all = statement.all.bind(statement) + Object.defineProperty(statement, 'all', { value: (...args: Parameters) => { + const rows = all(...args) + payloadRows += rows.length + return rows + } }) + } + return statement + }) + onTestFinished(() => { spy.mockRestore() }) + return { payloadRows: () => payloadRows, segmentQueries: () => segmentQueries } +} + +/** + * Read one imported root Segment directly from durable SQLite rows. + * @param root - persistence root using the default database. + * @param id - imported Session identity. + * @returns logical current header and event records in sequence order. + */ +export function importedRows(root: string, id: SessionId): unknown[] { + const db = new DatabaseSync(join(root, '.segments', 'sessions.sqlite')) + try { + const row = db.prepare('SELECT header, tail_segment_uuid FROM traces WHERE trace_uuid = ?').get(id) + if (typeof row?.header !== 'string' || typeof row.tail_segment_uuid !== 'string') throw new Error('Missing imported Session') + const rootSegment = db.prepare('SELECT parent_segment_uuid FROM segments WHERE segment_uuid = ?').get(row.tail_segment_uuid) + if (rootSegment?.parent_segment_uuid !== null) throw new Error('Expected an imported root Segment') + return [JSON.parse(row.header), ...db.prepare('SELECT payload FROM events WHERE segment_uuid = ? ORDER BY seq') + .all(row.tail_segment_uuid).map((event) => { + if (typeof event.payload !== 'string') throw new Error('Invalid event payload') + const value: unknown = JSON.parse(event.payload) + return value + })] + } finally { db.close() } +} diff --git a/packages/session/session-persistence-sqlite/tests/initialization.spec.ts b/packages/session/session-persistence-sqlite/tests/initialization.spec.ts new file mode 100644 index 0000000000..e569a223b9 --- /dev/null +++ b/packages/session/session-persistence-sqlite/tests/initialization.spec.ts @@ -0,0 +1,47 @@ +/** Concurrent schema initialization and WAL publication. @module */ +import { expect, it, vi } from 'vitest' +import { DatabaseSync } from 'node:sqlite' +import { join } from 'node:path' +import { meta, oneTurnLog } from '../../session-persistence/tests/contract.ts' +import { persistenceFixture } from './fixtures/persistence.ts' + +it('initializes the schema once when two providers create Sessions simultaneously', async () => { + const fixture = await persistenceFixture() + const first = await fixture.mount('sqlite') + const second = await fixture.mount('sqlite') + const writers = await Promise.all([ + first.persistence.create(meta('first-provider')), + second.persistence.create(meta('second-provider')), + ]) + await Promise.all(writers.map(writer => writer.append(oneTurnLog()))) + await Promise.all(writers.map(writer => writer.close())) + expect((await first.persistence.list()).map(entry => entry.header.id).sort()).toEqual(['first-provider', 'second-provider']) +}) + +it('enables WAL before publishing the schema to a concurrent reader', async () => { + const fixture = await persistenceFixture() + const backend = await fixture.mount('sqlite') + let snapshot: DatabaseSync | undefined + // oxlint-disable-next-line typescript/unbound-method -- Forwarded with its database receiver. + const execute = DatabaseSync.prototype.exec + const spy = vi.spyOn(DatabaseSync.prototype, 'exec').mockImplementation(function (this: DatabaseSync, sql) { + execute.call(this, sql) + if (sql === 'COMMIT' && snapshot === undefined) { + snapshot = new DatabaseSync(join(fixture.root, '.segments', 'sessions.sqlite'), { readOnly: true }) + execute.call(snapshot, 'BEGIN') + expect(snapshot.prepare('SELECT COUNT(*) AS count FROM traces').get()?.count).toBe(0) + } + }) + try { + const header = meta('wal-reader') + const writer = await backend.persistence.create(header) + await writer.append(oneTurnLog()) + await writer.close() + expect(snapshot).toBeDefined() + expect(snapshot?.prepare('SELECT COUNT(*) AS count FROM traces').get()?.count).toBe(0) + expect((await backend.persistence.stat(header.id))?.eventCount).toBe(oneTurnLog().length) + } finally { + spy.mockRestore() + snapshot?.close() + } +}) diff --git a/packages/session/session-persistence-sqlite/tests/lease.spec.ts b/packages/session/session-persistence-sqlite/tests/lease.spec.ts new file mode 100644 index 0000000000..7360fb8fcc --- /dev/null +++ b/packages/session/session-persistence-sqlite/tests/lease.spec.ts @@ -0,0 +1,95 @@ +/** Kernel lease contention, filesystem failures, and inode verification. @module */ +import { mkdtemp, readFile, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' +import { SessionId } from '@deepseek-ai/dsh-session' +import { SessionAlreadyOwnedError } from '@deepseek-ai/dsh-session-persistence' +import { SessionWriteLease, LEASE_FILENAME } from '../src/lease.ts' + +const faults = vi.hoisted(() => ({ flock: '', stat: false, swap: 0, remove: false })) +vi.mock('@deepseek-ai/node-addon-system/flock', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, tryLockExclusive: async (fd: number) => { + if (faults.flock !== '') { + const code = faults.flock + faults.flock = '' + throw Object.assign(new Error(`flock failed: ${code}`), { code }) + } + await actual.tryLockExclusive(fd) + } } +}) +vi.mock('node:fs/promises', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, stat: async (...args: Parameters) => { + if (String(args[0]).endsWith('session.lock')) { + if (faults.stat) { + faults.stat = false + throw Object.assign(new Error('lock path denied'), { code: 'EACCES' }) + } + if (faults.remove) { + faults.remove = false + await actual.unlink(args[0]) + } else if (faults.swap > 0) { + faults.swap-- + await actual.unlink(args[0]) + await actual.writeFile(args[0], '') + } + } + return actual.stat(...args) + } } +}) +afterEach(() => { faults.flock = ''; faults.stat = false; faults.swap = 0; faults.remove = false }) + +async function fixtureRoot() { + const root = await mkdtemp(join(tmpdir(), 'dsh-sqlite-lease-')) + const leases: SessionWriteLease[] = [] + onTestFinished(async () => { + try { await Promise.all(leases.map(lease => lease.release())) } + finally { await rm(root, { recursive: true, force: true }) } + }) + async function acquire() { + const lease = await SessionWriteLease.acquire(root, SessionId('lease')) + leases.push(lease) + return lease + } + return { root, acquire } +} + +describe.skipIf(process.platform === 'win32')('POSIX SQLite leases', () => { + it('excludes a second descriptor until the holder releases its lock', async () => { + const fixture = await fixtureRoot() + const first = await fixture.acquire() + await expect(fixture.acquire()).rejects.toBeInstanceOf(SessionAlreadyOwnedError) + await first.release() + const next = await fixture.acquire() + await next.release() + await next.release() + expect(await readFile(join(fixture.root, LEASE_FILENAME), 'utf8')).toBe('') + }) + + it.each(['EACCES', 'EWOULDBLOCK'])('releases the descriptor after flock reports %s', async (code) => { + const fixture = await fixtureRoot() + faults.flock = code + const failed = expect(fixture.acquire()).rejects + if (code === 'EWOULDBLOCK') await failed.toBeInstanceOf(SessionAlreadyOwnedError) + else await failed.toMatchObject({ code }) + await fixture.acquire() + }) + + it('releases the descriptor when inode verification cannot read the lock path', async () => { + const fixture = await fixtureRoot() + faults.stat = true + await expect(fixture.acquire()).rejects.toMatchObject({ code: 'EACCES' }) + await fixture.acquire() + }) + + it.each(['removed', 'replaced', 'unstable'] as const)('verifies the current inode when its path is %s', async (mode) => { + const fixture = await fixtureRoot() + if (mode === 'removed') faults.remove = true + else faults.swap = mode === 'replaced' ? 1 : 3 + if (mode === 'unstable') await expect(fixture.acquire()).rejects.toBeInstanceOf(SessionAlreadyOwnedError) + else await (await fixture.acquire()).release() + await fixture.acquire() + }) +}) diff --git a/packages/session/session-persistence-sqlite/tests/legacy-import.spec.ts b/packages/session/session-persistence-sqlite/tests/legacy-import.spec.ts new file mode 100644 index 0000000000..c1e2979b92 --- /dev/null +++ b/packages/session/session-persistence-sqlite/tests/legacy-import.spec.ts @@ -0,0 +1,195 @@ +import { describe, expect, it, vi, onTestFinished } from 'vitest' +import { appendFile, mkdir, readFile, readdir, writeFile } from 'node:fs/promises' +import { dirname, join } from 'node:path' +import { DatabaseSync } from 'node:sqlite' +import { SessionLogOffset, SessionSeq } from '@deepseek-ai/dsh-session' +import type { SessionEvent, SessionHeader } from '@deepseek-ai/dsh-session' +import type { JsonlCompression } from '@deepseek-ai/dsh-session-persistence-jsonl' +import { SessionAlreadyOwnedError } from '@deepseek-ai/dsh-session-persistence' +import { JsonlSessionPersistence } from '@deepseek-ai/dsh-session-persistence-jsonl' +import { generationLogPath } from '../../session-persistence-jsonl/src/format.ts' +import { SessionWriteLease } from '../src/lease.ts' +import { meta, oneTurnLog } from '../../session-persistence/tests/contract.ts' +import { persistenceFixture } from './fixtures/persistence.ts' + +type Fixture = Awaited> + +async function writeLegacy(fixture: Fixture, compression: JsonlCompression, header = meta('legacy', '/workspace'), events = oneTurnLog(), inheritedEventCount?: SessionLogOffset) { + const backend = await fixture.mount('jsonl', compression) + const writer = await backend.persistence.create(header, inheritedEventCount === undefined ? undefined : { inheritedEventCount }) + await writer.append(events) + await writer.close() + await backend.context.fiber.dispose() + const path = generationLogPath(fixture.root, header.cwd, header.id, header.version, compression) + return { header, events, path, bytes: await readFile(path) } +} + +describe('JSONL import through the SQLite provider', () => { + it('runs the released version migration before importing historical JSONL', async () => { + const fixture = await persistenceFixture() + const header = meta('released-v3', '/workspace') + const bytes = Buffer.from([ + JSON.stringify({ type: 'session', ...header, version: 3, delegationDepth: 0 }), + ...oneTurnLog().map(event => JSON.stringify(event)), + '', + ].join('\n')) + const path = generationLogPath(fixture.root, header.cwd, header.id, 3, 'none') + await mkdir(dirname(path), { recursive: true }) + await writeFile(path, bytes) + const jsonl = await fixture.mount('jsonl') + const source = await jsonl.persistence.open(header.id, 'read') + const expected = await source.read() + const currentHeader = source.header + await source.close() + await jsonl.context.fiber.dispose() + const sqlite = await fixture.mount('sqlite') + const imported = await sqlite.persistence.open(header.id, 'read') + expect(imported.header).toEqual(currentHeader) + expect((await imported.read()).events).toEqual(expected.events) + await imported.close() + expect(await readFile(path)).toEqual(bytes) + expect(await readdir(dirname(path))).toContain('session.v3.jsonl') + expect(await readdir(dirname(path))).not.toContain('session.v4.jsonl') + }) + + it('imports the complete prefix of a torn JSONL tail without adding semantic repair events', async () => { + const fixture = await persistenceFixture() + const legacy = await writeLegacy(fixture, 'none', meta('torn-tail'), oneTurnLog().slice(0, 3)) + await appendFile(legacy.path, '{"type":"assistant/message"') + const bytes = await readFile(legacy.path) + const sqlite = await fixture.mount('sqlite') + const reader = await sqlite.persistence.open(legacy.header.id, 'read') + expect((await reader.read()).events).toEqual(legacy.events) + await reader.close() + expect(await readFile(legacy.path)).toEqual(bytes) + }) + + it.each(['none', 'zstd'] as const)('imports %s history into one root segment and preserves logical inheritance and source bytes', async (compression) => { + const fixture = await persistenceFixture() + const header: SessionHeader = { ...meta('seeded-legacy', '/workspace'), isSeeded: true, parentSession: meta('parent').id, delegationDepth: 0 } + const original = oneTurnLog() + const events: SessionEvent[] = [ + ...original.slice(0, 2), + { type: 'session/end-seed', seq: SessionSeq(2), time: 2, data: { inherited: true } }, + ...original.slice(2).map(event => ({ ...event, seq: SessionSeq(event.seq + 1) })), + ] + const legacy = await writeLegacy(fixture, compression, header, events, SessionLogOffset(2)) + const { persistence } = await fixture.mount('sqlite', compression) + expect((await persistence.stat(header.id))?.header).toEqual(header) + expect((await persistence.list()).map(entry => entry.header.id)).toEqual([header.id]) + expect(await readdir(fixture.root)).not.toContain('.segments') + const reader = await persistence.open(header.id, 'read') + expect(reader.header).toEqual(header) + expect(reader.inheritedEventCount).toBe(2) + expect((await reader.read()).events).toEqual(events) + await reader.close() + expect(await readFile(legacy.path)).toEqual(legacy.bytes) + expect((await persistence.list()).map(entry => entry.header.id)).toEqual([header.id]) + const db = new DatabaseSync(join(fixture.root, '.segments', 'sessions.sqlite'), { readOnly: true }) + try { + expect(db.prepare('SELECT COUNT(*) AS count FROM traces').get()?.count).toBe(1) + expect(db.prepare('SELECT parent_segment_uuid, parent_end_seq, base_seq FROM segments').all()).toEqual([ + { parent_segment_uuid: null, parent_end_seq: null, base_seq: 0 }, + ]) + expect(db.prepare('SELECT COUNT(*) AS count FROM events').get()?.count).toBe(events.length) + } finally { db.close() } + }) + + it('continues writing in SQLite after reopening and leaves the imported JSONL unchanged', async () => { + const fixture = await persistenceFixture() + const legacy = await writeLegacy(fixture, 'none') + const first = await fixture.mount('sqlite') + const writer = await first.persistence.open(legacy.header.id, 'write') + const continuation: SessionEvent[] = [ + { type: 'turn/start', seq: SessionSeq(6), time: 10, data: { turn: 2 } }, + { type: 'turn/end', seq: SessionSeq(7), time: 11, data: { turn: 2, reason: { kind: 'completed' } } }, + ] + await writer.append(continuation) + await writer.close() + await first.context.fiber.dispose() + const reopened = await fixture.mount('sqlite') + const reader = await reopened.persistence.open(legacy.header.id, 'read') + expect((await reader.read()).events).toEqual([...legacy.events, ...continuation]) + await reader.close() + expect(await readFile(legacy.path)).toEqual(legacy.bytes) + }) + + it('imports once when two readers open the same legacy Session simultaneously', async () => { + const fixture = await persistenceFixture() + const legacy = await writeLegacy(fixture, 'none') + const { persistence } = await fixture.mount('sqlite') + const prepare = vi.spyOn(JsonlSessionPersistence.prototype, 'prepare') + onTestFinished(() => { prepare.mockRestore() }) + const readers = await Promise.all([ + persistence.open(legacy.header.id, 'read'), + persistence.open(legacy.header.id, 'read'), + ]) + expect(prepare).toHaveBeenCalledTimes(1) + for (const reader of readers) { + expect((await reader.read()).events).toEqual(legacy.events) + await reader.close() + } + }) + + it('allows another provider to read an imported Session while its writer retains ownership', async () => { + const fixture = await persistenceFixture() + const legacy = await writeLegacy(fixture, 'none') + const first = await fixture.mount('sqlite') + const second = await fixture.mount('sqlite') + const writer = await first.persistence.open(legacy.header.id, 'write') + const reader = await second.persistence.open(legacy.header.id, 'read') + expect((await reader.read()).events).toEqual(legacy.events) + await expect(second.persistence.open(legacy.header.id, 'write')).rejects.toBeInstanceOf(SessionAlreadyOwnedError) + await reader.close() + await writer.close() + const next = await second.persistence.open(legacy.header.id, 'write') + await next.close() + }) + + it('waits for the active JSONL writer before importing its final committed prefix', async () => { + const fixture = await persistenceFixture() + const jsonl = await fixture.mount('jsonl') + const header = meta('active-legacy', '/workspace') + const writer = await jsonl.persistence.create(header) + await writer.append(oneTurnLog().slice(0, 3)) + const sqlite = await fixture.mount('sqlite') + const attempted = Promise.withResolvers() + const acquire = SessionWriteLease.acquire.bind(SessionWriteLease) + const spy = vi.spyOn(SessionWriteLease, 'acquire').mockImplementation(async (...args) => { + try { return await acquire(...args) } finally { attempted.resolve(undefined) } + }) + onTestFinished(() => { spy.mockRestore() }) + const pending = sqlite.persistence.open(header.id, 'read') + await attempted.promise + await writer.append(oneTurnLog().slice(3)) + await writer.close() + const reader = await pending + expect((await reader.read()).events).toEqual(oneTurnLog()) + await reader.close() + }) + + it('cancels a read waiting for JSONL ownership and permits a later import', async () => { + const fixture = await persistenceFixture() + const jsonl = await fixture.mount('jsonl') + const header = meta('cancel-import') + const writer = await jsonl.persistence.create(header) + await writer.append(oneTurnLog()) + const sqlite = await fixture.mount('sqlite') + const attempted = Promise.withResolvers() + const acquire = SessionWriteLease.acquire.bind(SessionWriteLease) + const spy = vi.spyOn(SessionWriteLease, 'acquire').mockImplementation(async (...args) => { + try { return await acquire(...args) } finally { attempted.resolve(undefined) } + }) + onTestFinished(() => { spy.mockRestore() }) + const controller = new AbortController() + const reason = new Error('cancelled import') + const rejected = expect(sqlite.persistence.open(header.id, 'read', { signal: controller.signal })).rejects.toMatchObject({ name: 'AbortError', cause: reason }) + await attempted.promise + controller.abort(reason) + await rejected + await writer.close() + const reader = await sqlite.persistence.open(header.id, 'read') + expect((await reader.read()).events).toEqual(oneTurnLog()) + await reader.close() + }) +}) diff --git a/packages/session/session-persistence-sqlite/tests/legacy-open.two-process.e2e.ts b/packages/session/session-persistence-sqlite/tests/legacy-open.two-process.e2e.ts new file mode 100644 index 0000000000..3845d7ef32 --- /dev/null +++ b/packages/session/session-persistence-sqlite/tests/legacy-open.two-process.e2e.ts @@ -0,0 +1,136 @@ +/** Built-package ownership during concurrent legacy import and SQLite handoff. @module */ +import { spawn } from 'node:child_process' +import type { ChildProcess } from 'node:child_process' +import { createInterface } from 'node:readline' +import type { Interface } from 'node:readline' +import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { describe, expect, it, onTestFinished } from 'vitest' +import { Context } from '@deepseek-ai/cordis' +import { SessionId } from '@deepseek-ai/dsh-session' +import * as persistence from '../src/index.ts' +import { eventLines, generationLogPath, toHeaderLine } from '../../session-persistence-jsonl/src/format.ts' +import { meta, oneTurnLog } from '../../session-persistence/tests/contract.ts' + +const opener = fileURLToPath(new URL('./fixtures/legacy-opener.mjs', import.meta.url)) + +async function fixture() { + const root = await mkdtemp(join(tmpdir(), 'dsh-sqlite-import-process-')) + const contexts: Context[] = [] + const children: { child: ChildProcess; closed: Promise<{ code: number | null; signal: NodeJS.Signals | null }>; lines: Interface }[] = [] + onTestFinished(async () => { + try { + for (const { child } of children) { + if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL') + } + await Promise.all(children.map(async (probe) => { + await probe.closed + probe.lines.close() + })) + for (const context of contexts) await context.fiber.dispose() + } finally { await rm(root, { recursive: true, force: true }) } + }) + const id = SessionId('legacy-process') + const path = await store(id) + const bytes = await readFile(path) + async function store(target: SessionId) { + const header = meta(target) + const path = generationLogPath(root, header.cwd, target, header.version, 'none') + await mkdir(dirname(path), { recursive: true }) + await writeFile(path, JSON.stringify(toHeaderLine(header)) + '\n' + eventLines(oneTurnLog()) + '\n') + return path + } + function launch(access = 'read', pause = '', target = id) { + const child = spawn(process.execPath, [opener, root, target, access, pause], { stdio: ['pipe', 'pipe', 'inherit'] }) + const closed = new Promise<{ code: number | null; signal: NodeJS.Signals | null }>((resolve, reject) => { + child.once('error', reject) + child.once('close', (code, signal) => { resolve({ code, signal }) }) + }) + const lines = createInterface({ input: child.stdout }) + const iterator = lines[Symbol.asyncIterator]() + const probe = { + child, closed, lines, + async status() { + const line = await iterator.next() + if (line.done) throw new Error('Legacy opener closed before reporting status') + return line.value + }, + async close() { + child.stdin.end('close\n') + expect(await closed).toEqual({ code: 0, signal: null }) + }, + } + children.push(probe) + return probe + } + async function mount() { + const context = new Context() + contexts.push(context) + await context.plugin(persistence, { root, compression: 'none' }) + return context.sessionPersistence + } + return { root, id, path, bytes, store, launch, mount } +} + +describe('legacy import across processes', { retry: 0 }, () => { + it('initializes one database while two processes first open different Sessions', async () => { + const b = await fixture() + const otherId = SessionId('other-legacy-process') + await b.store(otherId) + const first = b.launch('read', 'start'), second = b.launch('read', 'start', otherId) + expect(await Promise.all([first.status(), second.status()])).toEqual(['ready', 'ready']) + first.child.stdin.write('continue\n') + second.child.stdin.write('continue\n') + expect(await Promise.all([first.status(), second.status()])).toEqual(['opened', 'opened']) + await Promise.all([first.close(), second.close()]) + const persistence = await b.mount() + expect((await persistence.list()).map(entry => entry.header.id).sort()).toEqual([b.id, otherId].sort()) + for (const id of [b.id, otherId]) { + await using read = await persistence.open(id, 'read') + expect((await read.read()).events).toEqual(oneTurnLog()) + } + }) + + it.each(['read', 'write'])('waits for another process to import and hands off %s access', async (access) => { + const b = await fixture(), first = b.launch(access, 'pause') + expect(await first.status()).toBe('reading') + const competing = b.launch('read', 'wait') + expect(await competing.status()).toBe('contended') + first.child.stdin.write('continue\n') + expect(await first.status()).toBe('opened') + expect(await competing.status()).toBe('opened') + await competing.close() + const currentReader = b.launch() + expect(await currentReader.status()).toBe('opened') + await currentReader.close() + if (access === 'write') { + const competingWriter = b.launch('write') + expect(await competingWriter.status()).toBe('SessionAlreadyOwnedError') + expect(await competingWriter.closed).toEqual({ code: 0, signal: null }) + } + await first.close() + expect(await readFile(b.path)).toEqual(b.bytes) + const persistence = await b.mount() + await using read = await persistence.open(b.id, 'read') + expect((await read.read()).events).toEqual(oneTurnLog()) + }) + + it('releases import ownership after process death and retries the complete import', async () => { + const b = await fixture(), first = b.launch('write', 'pause') + expect(await first.status()).toBe('reading') + first.child.kill('SIGKILL') + const result = await first.closed + // Windows reports forced termination as an exit code rather than a POSIX signal. + if (process.platform === 'win32') expect(result.code).not.toBe(0) + else expect(result.signal).toBe('SIGKILL') + const retry = b.launch('write') + expect(await retry.status()).toBe('opened') + await retry.close() + expect(await readFile(b.path)).toEqual(b.bytes) + const persistence = await b.mount() + await using read = await persistence.open(b.id, 'read') + expect((await read.read()).events).toEqual(oneTurnLog()) + }) +}) diff --git a/packages/session/session-persistence-sqlite/tests/list-concurrency.spec.ts b/packages/session/session-persistence-sqlite/tests/list-concurrency.spec.ts new file mode 100644 index 0000000000..5b63b3f20b --- /dev/null +++ b/packages/session/session-persistence-sqlite/tests/list-concurrency.spec.ts @@ -0,0 +1,49 @@ +/** Routing scans share JSONL's filesystem budget and settle before returning. @module */ +import { Context } from '@deepseek-ai/cordis' +import { SessionId, SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it, onTestFinished, vi } from 'vitest' +import * as persistence from '../src/index.ts' + +const interception = vi.hoisted(() => ({ + read: undefined as ((path: string, next: () => Promise) => Promise) | undefined, +})) +vi.mock('node:fs/promises', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, readFile: (...args: Parameters) => { + const next = () => actual.readFile(...args) + return interception.read === undefined || typeof args[0] !== 'string' + ? next() : interception.read(args[0], next) + } } +}) + +async function fixture() { + const root = await mkdtemp(join(tmpdir(), 'dsh-route-list-concurrency-')) + const ctx = new Context() + onTestFinished(async () => { + interception.read = undefined + try { await ctx.fiber.dispose() } finally { await rm(root, { recursive: true, force: true }) } + }) + await ctx.plugin(persistence, { root, compression: 'none', listConcurrency: 2 }) + for (let ordinal = 0; ordinal < 4; ordinal++) { + const handle = await ctx.sessionPersistence.create({ + version: SESSION_FORMAT_VERSION, id: SessionId(`route-${ordinal}`), createdAt: ordinal, isSeeded: false, + }) + await handle.flush(); await handle.close() + } + return { ctx, directory: join(root, '.segments') } +} + +it('lists concurrent Session snapshots without reading per-Session routing records', async () => { + const { ctx, directory } = await fixture() + let reads = 0 + interception.read = async (path, next) => { + if (path.startsWith(directory) && path.endsWith('.json')) reads++ + return next() + } + const results = await Promise.all([ctx.sessionPersistence.list(), ctx.sessionPersistence.list()]) + for (const entries of results) expect(entries).toHaveLength(4) + expect(reads).toBe(0) +}) diff --git a/packages/session/session-persistence-sqlite/tests/listing.spec.ts b/packages/session/session-persistence-sqlite/tests/listing.spec.ts new file mode 100644 index 0000000000..17045d34a6 --- /dev/null +++ b/packages/session/session-persistence-sqlite/tests/listing.spec.ts @@ -0,0 +1,113 @@ +/** Pending creation and durable Session listing share one identity and header policy. @module */ +import { DatabaseSync } from 'node:sqlite' +import { Context } from '@deepseek-ai/cordis' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it, onTestFinished, vi } from 'vitest' +import { SESSION_FORMAT_VERSION, SessionId, SessionSeq } from '@deepseek-ai/dsh-session' +import type { SessionHeader } from '@deepseek-ai/dsh-session' +import { SessionFormatUnsupportedError, SessionPersistenceCorruptionError } from '@deepseek-ai/dsh-session-persistence' +import * as persistence from '../src/index.ts' +import { SqliteStore } from '../src/sqlite.ts' + +it('public list emits an identity once when first materialization completes after pending capture', async () => { + const root = await mkdtemp(join(tmpdir(), 'dsh-session-list-once-')) + const ctx = new Context() + onTestFinished(async () => { try { await ctx.fiber.dispose() } finally { await rm(root, { recursive: true, force: true }) } }) + await ctx.plugin(persistence, { root, compression: 'none' }) + const id = SessionId('public-list-once') + const writer = await ctx.sessionPersistence.create({ version: SESSION_FORMAT_VERSION, id, createdAt: 0, isSeeded: false }) + let writing: Promise | undefined + const materialize = () => writing ??= writer.append([{ type: 'turn/start', seq: SessionSeq(0), time: 0, data: { turn: 1 } }]) + // oxlint-disable-next-line typescript/unbound-method -- Called with the intercepted store as receiver below. + const scan = SqliteStore.prototype.scan + const spy = vi.spyOn(SqliteStore.prototype, 'scan').mockImplementationOnce(async function (this: SqliteStore, ...args) { + Object.defineProperty(this, 'exists', { configurable: true, value: async () => { await materialize(); return true } }) + try { return await scan.call(this, ...args) } + finally { Reflect.deleteProperty(this, 'exists') } + }) + const restore = () => { spy.mockRestore() } + onTestFinished(() => { restore() }) + const listed = await ctx.sessionPersistence.list() + await writing + restore() + await writer.close() + expect(listed.map(entry => entry.header.id)).toEqual([id]) +}) + +it.each(['corrupt', 'unsupported'] as const)('omits %s headers whose first commit landed after the pending listing snapshot', async (kind) => { + const root = await mkdtemp(join(tmpdir(), 'dsh-session-list-omitted-')) + const ctx = new Context() + onTestFinished(async () => { try { await ctx.fiber.dispose() } finally { await rm(root, { recursive: true, force: true }) } }) + await ctx.plugin(persistence, { root, compression: 'none' }) + const id = SessionId('omitted') + const header: SessionHeader = { version: SESSION_FORMAT_VERSION, id, createdAt: 0, isSeeded: false } + const writer = await ctx.sessionPersistence.create(header) + let writing: Promise | undefined + const materialize = () => writing ??= (async () => { + await writer.append([{ type: 'turn/start', seq: SessionSeq(0), time: 0, data: { turn: 1 } }]) + const db = new DatabaseSync(join(root, '.segments', 'sessions.sqlite')) + try { + db.prepare('UPDATE traces SET header = ? WHERE trace_uuid = ?') + .run(kind === 'corrupt' ? 'invalid' : JSON.stringify({ ...header, version: SESSION_FORMAT_VERSION + 1 }), id) + } finally { db.close() } + })() + // oxlint-disable-next-line typescript/unbound-method -- Called with the intercepted store as receiver below. + const scan = SqliteStore.prototype.scan + const spy = vi.spyOn(SqliteStore.prototype, 'scan').mockImplementationOnce(async function (this: SqliteStore, ...args) { + Object.defineProperty(this, 'exists', { configurable: true, value: async () => { + await materialize() + return true + } }) + try { return await scan.call(this, ...args) } + finally { Reflect.deleteProperty(this, 'exists') } + }) + onTestFinished(() => { spy.mockRestore() }) + await expect(ctx.sessionPersistence.list()).resolves.toEqual([]) + spy.mockRestore() + await writer.close() + await expect(ctx.sessionPersistence.list()).resolves.toEqual([]) + await expect(ctx.sessionPersistence.stat(id)).rejects.toBeInstanceOf(kind === 'corrupt' + ? SessionPersistenceCorruptionError : SessionFormatUnsupportedError) +}) + +it('lists 201 durable SQLite sessions with one metadata query and no event payload reads', async () => { + const root = await mkdtemp(join(tmpdir(), 'dsh-session-list-query-')) + const ctx = new Context() + onTestFinished(async () => { try { await ctx.fiber.dispose() } finally { await rm(root, { recursive: true, force: true }) } }) + await ctx.plugin(persistence, { root, compression: 'none' }) + const ids = Array.from({ length: 201 }, (_, index) => SessionId(`session-${String(index).padStart(3, '0')}`)) + const writer = await ctx.sessionPersistence.create({ version: SESSION_FORMAT_VERSION, id: SessionId('session-000'), createdAt: 0, isSeeded: false }) + try { await writer.append([{ type: 'turn/start', seq: SessionSeq(0), time: 0, data: { turn: 1 } }]) } + finally { await writer.close() } + // Populate unrelated durable rows in one fixture transaction; listing must not decode their payloads. + const db = new DatabaseSync(join(root, '.segments', 'sessions.sqlite')) + try { + db.exec('BEGIN IMMEDIATE') + const segment = db.prepare('INSERT INTO segments VALUES (?, NULL, NULL, 0)') + const trace = db.prepare('INSERT INTO traces VALUES (?, ?, ?, 0)') + const event = db.prepare('INSERT INTO events VALUES (?, 0, ?)') + for (const id of ids.slice(1)) { + const head = `fixture-${id}` + segment.run(head) + trace.run(id, JSON.stringify({ version: SESSION_FORMAT_VERSION, id, createdAt: 0, isSeeded: false }), head) + event.run(head, 'invalid payload must remain unread') + } + db.exec('COMMIT') + } finally { db.close() } + const queries: string[] = [] + // oxlint-disable-next-line typescript/unbound-method -- Invoked with the intercepted database below. + const prepare = DatabaseSync.prototype.prepare + const spy = vi.spyOn(DatabaseSync.prototype, 'prepare').mockImplementation(function (this: DatabaseSync, sql) { + queries.push(sql) + return prepare.call(this, sql) + }) + onTestFinished(() => { spy.mockRestore() }) + const entries = await ctx.sessionPersistence.list() + spy.mockRestore() + expect(entries.map(entry => entry.header.id)).toEqual(ids) + expect(entries.every(entry => entry.eventCount === 1)).toBe(true) + expect(queries).toHaveLength(1) + expect(queries[0]).not.toMatch(/payload/i) +}) diff --git a/packages/session/session-persistence-sqlite/tests/migration.spec.ts b/packages/session/session-persistence-sqlite/tests/migration.spec.ts new file mode 100644 index 0000000000..45601d522b --- /dev/null +++ b/packages/session/session-persistence-sqlite/tests/migration.spec.ts @@ -0,0 +1,130 @@ +/** Import sequencing and cleanup preserve ownership after failure. @module */ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it, onTestFinished, vi } from 'vitest' +import type { SessionHeader } from '@deepseek-ai/dsh-session' +import { SessionId, SessionLogOffset, SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session' +import { Context } from '@deepseek-ai/cordis' +import { SqliteSessionPersistence } from '../src/persistence.ts' +import { SessionAlreadyOwnedError, SessionPersistenceRevision } from '@deepseek-ai/dsh-session-persistence' +import { SqliteStore } from '../src/sqlite.ts' +import { LegacySessionMigration } from '../src/migration.ts' +import type { JsonlBackend } from '../src/migration.ts' + +const id = SessionId('migration') +const header: SessionHeader = { version: SESSION_FORMAT_VERSION, id, createdAt: 0, isSeeded: false } +async function fixture() { + const root = await mkdtemp(join(tmpdir(), 'sqlite-import-sequence-')) + const sqlite = new SqliteStore({ path: join(root, 'sessions.sqlite'), legacyRoot: root, + acquireCreationLease: async () => ({ release: async () => {} }), publish: async () => {}, report: () => {} }) + const jsonl: JsonlBackend = { + hasStoredJsonl: async () => true, list: async () => [], + stat: async () => ({ header, revision: SessionPersistenceRevision('legacy'), eventCount: 0 }), + prepare: async () => ({ header, inheritedEventCount: SessionLogOffset(0), events: [], + commit: async publish => publish({ header, inheritedEventCount: SessionLogOffset(0), events: [] }) }), + } + const selected = vi.fn(async () => false) + const migration = new LegacySessionMigration(jsonl, sqlite, selected, async () => {}) + onTestFinished(async () => { await migration.close(); await sqlite.close(); await rm(root, { recursive: true, force: true }) }) + return { sqlite, jsonl, selected, migration } +} + +it('rejects admission after close', async () => { + const { migration } = await fixture() + await migration.close() + await expect(migration.open(id, 'read')).rejects.toMatchObject({ code: 'SESSION_STORAGE_CLOSED' }) +}) + +it('lets a queued open succeed after the preceding caller fails', async () => { + const { migration, jsonl } = await fixture() + vi.spyOn(jsonl, 'stat').mockRejectedValueOnce(new Error('metadata failed')) + const first = migration.open(id, 'read') + const next = migration.open(id, 'read') + await expect(first).rejects.toThrow('metadata failed') + const reader = await next + await reader.close() +}) + +it('rejects legacy preparation without readable metadata', async () => { + const { migration, jsonl } = await fixture() + vi.spyOn(jsonl, 'stat').mockResolvedValue(undefined) + await expect(migration.open(id, 'read')).rejects.toMatchObject({ code: 'SESSION_STORAGE_CORRUPT' }) +}) + +it.each(['read', 'write'] as const)('reports non-contention lease failure for %s', async (access) => { + const { sqlite, migration } = await fixture() + vi.spyOn(sqlite, 'acquireSessionLease').mockRejectedValue(new Error('lease denied')) + await expect(migration.open(id, access)).rejects.toThrow('lease denied') +}) + +it('reuses a commit that wins while metadata is read', async () => { + const { sqlite, migration, selected } = await fixture() + await sqlite.importLegacy(header, SessionLogOffset(0), []) + selected.mockResolvedValueOnce(false).mockResolvedValue(true) + const handle = await migration.open(id, 'read') + await handle.close() +}) + +it('publishes a commit that wins while the artifact lease is acquired', async () => { + const { sqlite, migration, selected } = await fixture() + await sqlite.importLegacy(header, SessionLogOffset(0), []) + selected.mockResolvedValueOnce(false).mockResolvedValue(true) + const handle = await migration.open(id, 'write') + await handle.close() +}) + +it('preserves import and lease cleanup failures together', async () => { + const { sqlite, jsonl, migration } = await fixture() + vi.spyOn(sqlite, 'acquireSessionLease').mockResolvedValue({ release: async () => { throw new Error('release failed') } }) + vi.spyOn(jsonl, 'prepare').mockRejectedValue(new Error('decode failed')) + await expect(migration.open(id, 'read')).rejects.toMatchObject({ errors: [expect.any(Error), expect.any(Error)] }) +}) + +it('closes the opened reader when artifact release fails', async () => { + const { sqlite, migration } = await fixture() + vi.spyOn(sqlite, 'acquireSessionLease').mockResolvedValue({ release: async () => { throw new Error('release failed') } }) + await expect(migration.open(id, 'read')).rejects.toThrow('release failed') +}) + +it('waits for a competing import and stops the wait on disposal', async () => { + const { sqlite, migration } = await fixture() + const entered = Promise.withResolvers() + vi.spyOn(sqlite, 'acquireSessionLease').mockImplementation(async () => { + entered.resolve(undefined) + throw new SessionAlreadyOwnedError(id) + }) + const opening = migration.open(id, 'read') + await entered.promise + const closing = migration.close() + await expect(opening).rejects.toThrow() + await closing +}) + +it('republishes routing when a competing importer commits under lease acquisition', async () => { + const { jsonl } = await fixture() + const root = await mkdtemp(join(tmpdir(), 'sqlite-routing-import-')) + const ctx = new Context() + onTestFinished(async () => { await ctx.fiber.dispose(); await rm(root, { recursive: true, force: true }) }) + const provider = new SqliteSessionPersistence(ctx, ctx, { root }, jsonl) + // oxlint-disable-next-line typescript/unbound-method -- Called with the native store receiver below. + const acquire = SqliteStore.prototype.acquireSessionLease + const fault = vi.spyOn(SqliteStore.prototype, 'acquireSessionLease').mockImplementationOnce(async function (this: SqliteStore, metadata) { + await this.importLegacy(metadata, SessionLogOffset(0), []) + return acquire.call(this, metadata) + }) + try { + const handle = await provider.open(id, 'read') + await handle.close() + expect(await provider.stat(id)).toMatchObject({ header }) + } finally { fault.mockRestore() } +}) + +it('opens a concurrent SQLite commit when queued legacy metadata no longer exists', async () => { + const { sqlite, jsonl, selected, migration } = await fixture() + await sqlite.importLegacy(header, SessionLogOffset(0), []) + vi.spyOn(jsonl, 'stat').mockResolvedValue(undefined) + selected.mockResolvedValue(true) + const reader = await migration.open(id, 'read') + await reader.close() +}) diff --git a/packages/session/session-persistence-sqlite/tests/open-lifecycle.spec.ts b/packages/session/session-persistence-sqlite/tests/open-lifecycle.spec.ts new file mode 100644 index 0000000000..9c0c03970d --- /dev/null +++ b/packages/session/session-persistence-sqlite/tests/open-lifecycle.spec.ts @@ -0,0 +1,79 @@ +/** Cancellation and disposal while SQLite opens an existing Session. @module */ +import { expect, it, vi } from 'vitest' +import { SessionWriteLease } from '../src/lease.ts' +import { SqliteStore } from '../src/sqlite.ts' +import { sessionDir } from '../src/paths.ts' +import { persistenceFixture } from './fixtures/persistence.ts' +import { meta, oneTurnLog } from '../../session-persistence/tests/contract.ts' + +it('releases both write leases when cancellation arrives after acquisition', async () => { + const fixture = await persistenceFixture() + const { persistence } = await fixture.mount('sqlite') + const header = meta('cancel-write-open') + const writer = await persistence.create(header) + await writer.append(oneTurnLog()) + await writer.close() + const controller = new AbortController(), reason = new Error('cancel write open') + const acquire = SessionWriteLease.acquire.bind(SessionWriteLease) + const spy = vi.spyOn(SessionWriteLease, 'acquire').mockImplementation(async (dir, id) => { + const lease = await acquire(dir, id) + if (dir === sessionDir(fixture.root, header.cwd, header.id)) controller.abort(reason) + return lease + }) + try { + await expect(persistence.open(header.id, 'write', { signal: controller.signal })).rejects.toBe(reason) + } finally { spy.mockRestore() } + const next = await fixture.mount('sqlite') + await using reopened = await next.persistence.open(header.id, 'write') + expect((await reopened.read()).events).toEqual(oneTurnLog()) +}) + +it('returns no history when cancellation arrives during the write-open restore read', async () => { + const fixture = await persistenceFixture() + const { persistence } = await fixture.mount('sqlite') + const header = meta('cancel-restore-read') + const writer = await persistence.create(header) + await writer.append(oneTurnLog()) + await writer.close() + const controller = new AbortController(), reason = new Error('cancel restore read') + // oxlint-disable-next-line typescript/unbound-method -- Forwarded with its store receiver. + const read = SqliteStore.prototype.read + const spy = vi.spyOn(SqliteStore.prototype, 'read').mockImplementationOnce(async function (this: SqliteStore, ...args) { + const events = await read.call(this, ...args) + controller.abort(reason) + return events + }) + try { + await expect(persistence.open(header.id, 'write', { signal: controller.signal })).rejects.toBe(reason) + } finally { spy.mockRestore() } + await using reopened = await persistence.open(header.id, 'write') + expect((await reopened.read()).events).toEqual(oneTurnLog()) +}) + +it('releases acquired leases when the provider closes before admitting the write handle', async () => { + const fixture = await persistenceFixture() + const { persistence, context } = await fixture.mount('sqlite') + const header = meta('dispose-write-open') + const writer = await persistence.create(header) + await writer.append(oneTurnLog()) + await writer.close() + const entered = Promise.withResolvers(), release = Promise.withResolvers() + const acquire = SessionWriteLease.acquire.bind(SessionWriteLease) + const spy = vi.spyOn(SessionWriteLease, 'acquire').mockImplementation(async (dir, id) => { + const lease = await acquire(dir, id) + if (dir === sessionDir(fixture.root, header.cwd, header.id)) { + entered.resolve(undefined) + await release.promise + } + return lease + }) + const rejected = expect(persistence.open(header.id, 'write')).rejects.toMatchObject({ code: 'SESSION_STORAGE_CLOSED' }) + try { + await entered.promise + await context.fiber.dispose() + } finally { release.resolve(undefined); spy.mockRestore() } + await rejected + const next = await fixture.mount('sqlite') + await using reopened = await next.persistence.open(header.id, 'write') + expect((await reopened.read()).events).toEqual(oneTurnLog()) +}) diff --git a/packages/session/session-persistence-sqlite/tests/paths.spec.ts b/packages/session/session-persistence-sqlite/tests/paths.spec.ts new file mode 100644 index 0000000000..da4233a525 --- /dev/null +++ b/packages/session/session-persistence-sqlite/tests/paths.spec.ts @@ -0,0 +1,17 @@ +/** SQLite artifact paths preserve arbitrary Session identifiers. @module */ +import { expect, it } from 'vitest' +import { SessionId } from '@deepseek-ai/dsh-session' +import { encodeSegment, projectKey, sessionDir } from '../src/paths.ts' + +it('escapes unsafe identifiers and rejects empty path components', () => { + expect(() => encodeSegment('')).toThrow('empty path segment') + expect(encodeSegment('.')).toBe('~002E') + expect(encodeSegment('..')).toBe('~002E~002E') + expect(encodeSegment('a/~')).toBe('a~002F~007E') + expect(encodeSegment('\ud800')).toBe('~D800') + expect(() => projectKey('')).toThrow('empty project path') + expect(projectKey('/')).toBe('--root--') + expect(projectKey('/开发/~agent')).toBe('--~5F00~53D1-~007Eagent--') + expect(projectKey('C:\\work\\agent')).toBe('--C-work-agent--') + expect(sessionDir('/root', undefined, SessionId('id'))).toBe('/root/_no-cwd/id'.replaceAll('/', process.platform === 'win32' ? '\\' : '/')) +}) diff --git a/packages/session/session-persistence-sqlite/tests/persistence.spec.ts b/packages/session/session-persistence-sqlite/tests/persistence.spec.ts new file mode 100644 index 0000000000..0d129e939d --- /dev/null +++ b/packages/session/session-persistence-sqlite/tests/persistence.spec.ts @@ -0,0 +1,84 @@ +/** Shared persistence semantics and SQLite plugin activation. @module */ +import { describe, expect, it } from 'vitest' +import { DatabaseSync } from 'node:sqlite' +import { readdir } from 'node:fs/promises' +import { join } from 'node:path' +import { meta, oneTurnLog, runPersistenceContract } from '../../session-persistence/tests/contract.ts' +import { persistenceFixture } from './fixtures/persistence.ts' + +runPersistenceContract('sqlite', async () => { + const fixture = await persistenceFixture() + const backend = await fixture.mount('sqlite') + return { + persistence: backend.persistence, + dispose: () => backend.context.fiber.dispose(), + reopen: async () => { + const reopened = await fixture.mount('sqlite') + return { persistence: reopened.persistence, dispose: () => reopened.context.fiber.dispose() } + }, + } +}) + +describe('SQLite persistence plugin', () => { + it('registers the service before creating the database and initializes on first create', async () => { + const fixture = await persistenceFixture() + const { persistence } = await fixture.mount('sqlite') + expect(persistence).toBeDefined() + expect(await persistence.list()).toEqual([]) + expect(await readdir(fixture.root)).toEqual([]) + const writer = await persistence.create(meta('first-create')) + await writer.flush() + await writer.close() + expect(await readdir(join(fixture.root, '.segments'))).toContain('sessions.sqlite') + }) + + it('stores one complete logical event stream in an independent root segment', async () => { + const fixture = await persistenceFixture() + const { persistence, context } = await fixture.mount('sqlite') + const header = meta('root-segment', '/workspace') + const events = oneTurnLog() + const writer = await persistence.create(header) + await writer.append(events) + await writer.close() + await context.fiber.dispose() + const db = new DatabaseSync(join(fixture.root, '.segments', 'sessions.sqlite')) + try { + const thread = db.prepare('SELECT header, tail_segment_uuid FROM traces WHERE trace_uuid = ?').get(header.id) + expect(JSON.parse(String(thread?.header))).toEqual({ ...header, delegationDepth: 0 }) + const segment = db.prepare('SELECT parent_segment_uuid, parent_end_seq, base_seq FROM segments WHERE segment_uuid = ?').get(thread?.tail_segment_uuid as string) + expect(segment).toEqual({ parent_segment_uuid: null, parent_end_seq: null, base_seq: 0 }) + const stored = db.prepare('SELECT payload FROM events WHERE segment_uuid = ? ORDER BY seq').all(thread?.tail_segment_uuid as string) + expect(stored.map((row) => { + const event: unknown = JSON.parse(String(row.payload)) + return event + })).toEqual(events) + } finally { + db.close() + } + }) + + it('keeps the default JSONL provider independent of SQLite storage', async () => { + const fixture = await persistenceFixture() + const { persistence } = await fixture.mount('jsonl') + const writer = await persistence.create(meta('default-jsonl', '/workspace')) + await writer.append(oneTurnLog()) + await writer.close() + expect(await readdir(fixture.root)).not.toContain('.segments') + }) + + it('drains live Session events before provider disposal', async () => { + const fixture = await persistenceFixture() + const { persistence, context } = await fixture.mount('sqlite') + const session = context.sessions.create(meta('shutdown-drain').id) + await persistence.create(session.header) + const events = [ + session.append('turn/start', { turn: 1 }), + session.append('turn/end', { turn: 1, reason: { kind: 'completed' } }), + ] + await context.fiber.dispose() + const reopened = await fixture.mount('sqlite') + const reader = await reopened.persistence.open(session.id, 'read') + expect((await reader.read()).events).toEqual(events) + await reader.close() + }) +}) diff --git a/packages/session/session-persistence-sqlite/tests/publication.spec.ts b/packages/session/session-persistence-sqlite/tests/publication.spec.ts new file mode 100644 index 0000000000..a5d1bdcb5f --- /dev/null +++ b/packages/session/session-persistence-sqlite/tests/publication.spec.ts @@ -0,0 +1,111 @@ +/** Recovery of a committed SQLite Session whose routing record failed to publish. @module */ +import { readdir } from 'node:fs/promises' +import { basename, join } from 'node:path' +import { SESSION_FORMAT_VERSION, SessionId, SessionSeq } from '@deepseek-ai/dsh-session' +import type { SessionEvent, SessionHeader } from '@deepseek-ai/dsh-session' +import { expect, it, vi } from 'vitest' +import { SqliteStore, SqliteSessionHandle } from '../src/sqlite.ts' +import { routeOf } from './fixtures/store.ts' +import { persistenceFixture } from './fixtures/persistence.ts' +import { meta, oneTurnLog } from '../../session-persistence/tests/contract.ts' + +const faults = vi.hoisted(() => ({ routes: false })) +vi.mock('node:fs/promises', async (importOriginal) => { + const actual = await importOriginal() + const refused = () => Promise.reject(Object.assign(new Error('routing directory refused'), { code: 'EACCES' })) + // Fail publication's routing-directory creation (POSIX) and its temporary record file (every platform). + return { ...actual, + mkdir: (...args: Parameters) => + faults.routes && basename(String(args[0])) === '.segments' ? refused() : actual.mkdir(...args), + open: (...args: Parameters) => + faults.routes && basename(String(args[0])).startsWith('.route-') ? refused() : actual.open(...args), + } +}) + +const header: SessionHeader = { version: SESSION_FORMAT_VERSION, id: SessionId('unpublished'), createdAt: 0, isSeeded: false } +const event = (seq: number): SessionEvent<'turn/start'> => ({ type: 'turn/start', seq: SessionSeq(seq), time: 0, data: { turn: seq + 1 } }) + +it('serves a committed Session without its routing record to a fresh provider', async () => { + const fixture = await persistenceFixture(), root = fixture.root + const { context: first } = await fixture.mount('sqlite') + const writer = await first.sessionPersistence.create(header) + faults.routes = true + try { + const failure = await writer.append([event(0)]).then(() => undefined, (error: unknown) => error) + expect(failure).toMatchObject({ code: 'SESSION_STORAGE_PUBLICATION', cause: { message: 'routing directory refused' } }) + await expect(writer.close()).rejects.toBe(failure) + } finally { faults.routes = false } + await first.fiber.dispose() + expect(await routeOf(root, header.id)).toBe('jsonl') + expect((await readdir(join(root, '.segments'))).filter(name => name.endsWith('.json'))).toEqual([]) + + // The committed row selects SQLite without a routing record. + const { context: fresh } = await fixture.mount('sqlite') + expect(await fresh.sessionPersistence.stat(header.id)).toMatchObject({ header, eventCount: 1 }) + expect((await fresh.sessionPersistence.list()).map(entry => [entry.header.id, entry.eventCount])).toEqual([[header.id, 1]]) + const reopened = await fresh.sessionPersistence.open(header.id, 'write') + try { + expect((await reopened.read()).events).toEqual([event(0)]) + // The next commit publishes the missing routing record. + await reopened.append([event(1)]) + } finally { await reopened.close() } + expect(await routeOf(root, header.id)).toBe('sqlite') + expect((await fresh.sessionPersistence.stat(header.id))?.eventCount).toBe(2) + expect((await readdir(root, { recursive: true })).some(name => name.endsWith('.jsonl'))).toBe(false) +}) + +it('reports a live routing failure and retains its rejected durability checkpoint', async () => { + const fixture = await persistenceFixture() + const { context: ctx } = await fixture.mount('sqlite') + const reported = Promise.withResolvers() + // oxlint-disable-next-line typescript/unbound-method -- Forwarded with its store receiver. + const reportFailure = SqliteStore.prototype.reportFailure + const report = vi.spyOn(SqliteStore.prototype, 'reportFailure').mockImplementation(function (this: SqliteStore, id, error) { + reportFailure.call(this, id, error) + reported.resolve(undefined) + }) + const writer = await ctx.sessionPersistence.create(header) + if (!(writer instanceof SqliteSessionHandle)) throw new Error('Expected SQLite writer') + faults.routes = true + try { + await writer.receive(event(0)) + await reported.promise + await expect(writer.flush()).rejects.toMatchObject({ code: 'SESSION_STORAGE_PUBLICATION' }) + await expect(writer.close()).rejects.toMatchObject({ code: 'SESSION_STORAGE_PUBLICATION' }) + expect(report).toHaveBeenCalledOnce() + } finally { faults.routes = false; report.mockRestore() } +}) + +it('reopens an empty committed Session after routing publication fails', async () => { + const fixture = await persistenceFixture() + const { persistence } = await fixture.mount('sqlite') + const writer = await persistence.create(meta('empty-publication')) + faults.routes = true + try { + await expect(writer.flush()).rejects.toMatchObject({ code: 'SESSION_STORAGE_PUBLICATION' }) + await expect(writer.close()).rejects.toMatchObject({ code: 'SESSION_STORAGE_PUBLICATION' }) + } finally { faults.routes = false } + const fresh = await fixture.mount('sqlite') + expect(await fresh.persistence.stat(writer.id)).toMatchObject({ eventCount: 0 }) + await using reader = await fresh.persistence.open(writer.id, 'read') + expect((await reader.read()).events).toEqual([]) +}) + +it('uses the committed import when routing publication fails after the import transaction', async () => { + const fixture = await persistenceFixture() + const legacy = await fixture.mount('jsonl') + const header = meta('import-publication') + const writer = await legacy.persistence.create(header) + await writer.append(oneTurnLog()) + await writer.close() + const { persistence } = await fixture.mount('sqlite') + const initialization = await persistence.create(meta('initialize')) + await initialization.close() + faults.routes = true + try { + await expect(persistence.open(header.id, 'read')).rejects.toMatchObject({ code: 'SESSION_STORAGE_PUBLICATION' }) + } finally { faults.routes = false } + await using reader = await persistence.open(header.id, 'read') + expect((await reader.read()).events).toEqual(oneTurnLog()) + expect((await persistence.list()).filter(entry => entry.header.id === header.id)).toHaveLength(1) +}) diff --git a/packages/session/session-persistence-sqlite/tests/recovery-regressions.spec.ts b/packages/session/session-persistence-sqlite/tests/recovery-regressions.spec.ts new file mode 100644 index 0000000000..a6776e9a78 --- /dev/null +++ b/packages/session/session-persistence-sqlite/tests/recovery-regressions.spec.ts @@ -0,0 +1,124 @@ +/** Initialization retries, automatic rollbacks, and durable parent writes. @module */ +import { DatabaseSync } from 'node:sqlite' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it, onTestFinished, vi } from 'vitest' +import { SessionId, SessionSeq, SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session' +import type { SessionEvent, SessionHeader } from '@deepseek-ai/dsh-session' +import { createUserMessage } from '@deepseek-ai/dsh-llm' +import { SessionPersistenceCorruptionError } from '@deepseek-ai/dsh-session-persistence' +import { sqliteLogs } from './fixtures/store.ts' + +async function fixture() { + const root = await mkdtemp(join(tmpdir(), 'dsh-sqlite-recovery-')) + const path = join(root, 'sessions.sqlite') + const logs = sqliteLogs(path, root) + onTestFinished(async () => { try { await logs.close() } finally { await rm(root, { recursive: true, force: true }) } }) + const header = (name: string): SessionHeader => ({ version: SESSION_FORMAT_VERSION, id: SessionId(name), createdAt: 0, isSeeded: false }) + const event = (seq: number): SessionEvent<'turn/start'> => ({ type: 'turn/start', seq: SessionSeq(seq), time: 0, data: { turn: seq + 1 } }) + return { root, path, logs, header, event } +} + +it('retries initialization after a database lock without reporting corruption or repeating the error on close', async () => { + const { path, logs, header } = await fixture() + const blocker = new DatabaseSync(path) + try { + blocker.exec('BEGIN IMMEDIATE') + const failure = await logs.start().then(() => undefined, (error: unknown) => error) + expect(failure).toMatchObject({ errcode: 5 }) + expect(failure).not.toBeInstanceOf(SessionPersistenceCorruptionError) + blocker.exec('ROLLBACK') + await logs.start() + const writer = await logs.create(header('retry')) + await writer.flush(); await writer.close() + expect(await logs.stat(writer.id)).toMatchObject({ eventCount: 0 }) + await expect(logs.close()).resolves.toBeUndefined() + } finally { blocker.close() } +}) + +it('retains retryable state after SQLite automatically rolls back an append', async () => { + const { path, logs, header, event } = await fixture() + const writer = await logs.create(header('source')) + await writer.flush() + const db = new DatabaseSync(path) + try { + db.exec("CREATE TRIGGER auto_rollback BEFORE INSERT ON events BEGIN SELECT RAISE(ROLLBACK, 'automatic rollback'); END") + await expect(writer.append([event(0)])).rejects.toThrow('automatic rollback') + expect((await logs.stat(writer.id))?.eventCount).toBe(0) + db.exec('DROP TRIGGER auto_rollback') + await writer.append([event(0)]) + expect((await writer.read()).events).toEqual([event(0)]) + await writer.close() + } finally { db.close() } +}) + +it('retries the same append after SQLITE_FULL automatically ends its transaction', async () => { + const { logs, header } = await fixture() + const writer = await logs.create(header('disk-full')) + await writer.flush() + const entry: SessionEvent<'user/message'> = { + type: 'user/message', surfaceOp: 'append', seq: SessionSeq(0), time: 0, + data: createUserMessage({ content: [{ type: 'text', text: 'large payload '.repeat(10_000) }], source: { kind: 'user' } }), + } + // oxlint-disable-next-line typescript/unbound-method -- Forwarded with its database receiver. + const exec = DatabaseSync.prototype.exec + let connection: DatabaseSync | undefined + const fault = vi.spyOn(DatabaseSync.prototype, 'exec').mockImplementation(function (this: DatabaseSync, sql) { + if (sql === 'BEGIN IMMEDIATE' && connection === undefined) { + // oxlint-disable-next-line typescript/no-this-alias -- Retain the native connection to remove its page limit after failure. + connection = this + const pages = this.prepare('PRAGMA page_count').get()?.page_count + if (typeof pages !== 'number') throw new Error('Expected a page count') + exec.call(this, `PRAGMA max_page_count = ${pages}`) + } + exec.call(this, sql) + }) + try { + await expect(writer.append([entry])).rejects.toMatchObject({ errcode: 13 }) + expect(connection?.isTransaction).toBe(false) + } finally { + fault.mockRestore() + connection?.exec('PRAGMA max_page_count = 2147483646') + } + expect((await logs.stat(writer.id))?.eventCount).toBe(0) + await writer.append([entry]) + expect((await writer.read()).events).toEqual([entry]) + await writer.close() +}) + +it('joins an initialization that rejects while disposal is already waiting', async () => { + const { logs } = await fixture() + // oxlint-disable-next-line typescript/unbound-method -- Forwarded with its database receiver. + const exec = DatabaseSync.prototype.exec + const denied = new Error('initialization interrupted') + const fault = vi.spyOn(DatabaseSync.prototype, 'exec').mockImplementation(function (this: DatabaseSync, sql) { + if (sql === 'BEGIN IMMEDIATE') throw denied + exec.call(this, sql) + }) + try { + const opening = logs.start() + const closing = logs.close() + await expect(opening).rejects.toBe(denied) + await expect(closing).resolves.toBeUndefined() + } finally { fault.mockRestore() } +}) + +it('retains unknown outcome when COMMIT ended the transaction before reporting failure', async () => { + const { path, logs, header, event } = await fixture() + const writer = await logs.create(header('commit-ended')) + await writer.flush() + // oxlint-disable-next-line typescript/unbound-method -- Forwarded with its database receiver. + const exec = DatabaseSync.prototype.exec + const fault = vi.spyOn(DatabaseSync.prototype, 'exec').mockImplementation(function (this: DatabaseSync, sql) { + exec.call(this, sql) + if (sql === 'COMMIT') throw new Error('commit outcome unavailable') + }) + try { + await expect(writer.append([event(0)])).rejects.toMatchObject({ code: 'SESSION_STORAGE_UNKNOWN' }) + } finally { fault.mockRestore() } + await expect(logs.stat(writer.id)).rejects.toMatchObject({ code: 'SESSION_STORAGE_UNKNOWN' }) + const db = new DatabaseSync(path) + try { expect(db.prepare('SELECT count(*) AS count FROM events').get()?.count).toBe(1) } finally { db.close() } + await writer.close() +}) diff --git a/packages/session/session-persistence-sqlite/tests/relationships.spec.ts b/packages/session/session-persistence-sqlite/tests/relationships.spec.ts new file mode 100644 index 0000000000..49b96cdff0 --- /dev/null +++ b/packages/session/session-persistence-sqlite/tests/relationships.spec.ts @@ -0,0 +1,59 @@ +/** SQLite validates whole-artifact relationships and event-local V4 fields on slices. @module */ +import { DatabaseSync } from 'node:sqlite' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it, onTestFinished } from 'vitest' +import { SessionId, SessionSeq, SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session' +import { SessionFormatUnsupportedError, SessionPersistenceCorruptionError } from '@deepseek-ai/dsh-session-persistence' +import { sqliteLogs } from './fixtures/store.ts' + +async function fixture() { + const root = await mkdtemp(join(tmpdir(), 'dsh-sqlite-v4-')) + const path = join(root, 'sessions.sqlite'), logs = sqliteLogs(path, root), id = SessionId('v4') + onTestFinished(async () => { try { await logs.close() } finally { await rm(root, { recursive: true, force: true }) } }) + const writer = await logs.create({ version: SESSION_FORMAT_VERSION, id, createdAt: 0, isSeeded: false }) + await writer.append([0, 1].map(seq => ({ type: 'turn/start' as const, seq: SessionSeq(seq), time: 0, data: { turn: seq + 1 } }))) + await writer.close() + const db = new DatabaseSync(path) + onTestFinished(() => { db.close() }) + db.exec('DROP TRIGGER events_no_update') + const replace = (seq: number, type: string, data: object) => { + db.prepare('UPDATE events SET payload = ? WHERE segment_uuid = (SELECT tail_segment_uuid FROM traces WHERE trace_uuid = ?) AND seq = ?') + .run(JSON.stringify({ type, seq, time: 0, data }), id, seq) + } + replace(1, 'turn/end', { turn: 1, reason: { kind: 'completed' } }) + return { logs, db, id, replace } +} + +it('rejects an inherited marker in an unseeded artifact on complete read and writable restore', async () => { + const { logs, id, replace } = await fixture() + replace(1, 'session/end-seed', { inherited: true }) + const reader = await logs.open(id, 'read') + expect((await reader.read(0, 1)).events).toHaveLength(1) + await expect(reader.read()).rejects.toBeInstanceOf(SessionPersistenceCorruptionError) + await reader.close() + await expect(logs.open(id, 'write')).rejects.toBeInstanceOf(SessionPersistenceCorruptionError) +}) + +it('rejects a seeded header whose stored cut differs from its inherited marker', async () => { + const { logs, db, id, replace } = await fixture() + replace(1, 'session/end-seed', { inherited: true }) + const row = db.prepare('SELECT header FROM traces WHERE trace_uuid = ?').get(id) + if (typeof row?.header !== 'string') throw new Error('Missing stored header') + const header: unknown = JSON.parse(row.header) + if (typeof header !== 'object' || header === null || Array.isArray(header)) throw new Error('Invalid stored header') + db.prepare('UPDATE traces SET header = ?, inherited_count = 0 WHERE trace_uuid = ?') + .run(JSON.stringify({ ...header, isSeeded: true }), id) + const reader = await logs.open(id, 'read') + await expect(reader.read()).rejects.toBeInstanceOf(SessionPersistenceCorruptionError) + await reader.close() +}) + +it('classifies an unknown required event in a complete artifact as unsupported', async () => { + const { logs, id, replace } = await fixture() + replace(1, 'future/required', {}) + const reader = await logs.open(id, 'read') + await expect(reader.read()).rejects.toBeInstanceOf(SessionFormatUnsupportedError) + await reader.close() +}) diff --git a/packages/session/session-persistence-sqlite/tests/routing.spec.ts b/packages/session/session-persistence-sqlite/tests/routing.spec.ts new file mode 100644 index 0000000000..603b71336d --- /dev/null +++ b/packages/session/session-persistence-sqlite/tests/routing.spec.ts @@ -0,0 +1,245 @@ +/** Routing publication errors and platform-specific durable publication. @module */ +import { Context } from '@deepseek-ai/cordis' +import type { SessionHeader } from '@deepseek-ai/dsh-session' +import { SessionId, SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session' +import { SqliteSessionPersistence } from '../src/persistence.ts' +import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, it, onTestFinished, vi } from 'vitest' + +const faults = vi.hoisted(() => ({ op: '', error: undefined as Error | undefined, race: false, skip: 0, + directory: '', directorySyncs: 0, directoryCloses: 0 })) +vi.mock('node:fs/promises', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, + readFile: (...args: Parameters) => { + if (faults.op === 'readFile') return Promise.reject(faults.error ?? new Error('Injected filesystem failure')) + return actual.readFile(...args) + }, + readdir: (...args: Parameters) => { + if (faults.op === 'readdir') return Promise.reject(faults.error ?? new Error('Injected filesystem failure')) + return actual.readdir(...args) + }, + stat: (...args: Parameters) => { + if (faults.op === 'stat' && faults.skip-- <= 0) return Promise.reject(faults.error ?? new Error('Injected filesystem failure')) + return actual.stat(...args) + }, + open: async (...args: Parameters) => { + if (faults.op === 'open') throw faults.error ?? new Error('Injected filesystem failure') + if (String(args[0]) === faults.directory) { + // Windows cannot open a directory through fs.open; this stand-in isolates the POSIX publication protocol. + const handle = await actual.open(`${faults.directory}.sync`, 'w') + const sync = handle.sync.bind(handle), close = handle.close.bind(handle) + handle.sync = async () => { faults.directorySyncs++; await sync() } + handle.close = async () => { faults.directoryCloses++; await close() } + return handle + } + return actual.open(...args) + }, + link: async (source: string, target: string) => { + if (faults.op === 'link') { + if (faults.race) await actual.link(source, target) + throw faults.error + } + await actual.link(source, target) + }, + } +}) +vi.mock('../src/win32.ts', async (importOriginal) => { + const windows = await importOriginal() + const actual = await import('node:fs/promises') + return { ...windows, ensureDurableDirectoryWin32: (path: string) => actual.mkdir(path, { recursive: true }), + publishNewFileWin32: (source: string, target: string) => actual.link(source, target) } +}) + +class Adapter extends SqliteSessionPersistence { + constructor(ctx: Context, root: string) { + super(ctx, ctx, { root }, { + async prepare() { throw new Error('legacy preparation') }, + async stat() { return undefined }, + async list() { return [] }, + async hasStoredJsonl() { return false }, + }) + } + publishRoute(id: SessionId) { return this.publish(id) } +} +afterEach(() => { + faults.op = ''; faults.error = undefined; faults.race = false; faults.skip = 0 + faults.directory = ''; faults.directorySyncs = 0; faults.directoryCloses = 0 + vi.restoreAllMocks() +}) +async function fixture() { + const root = await mkdtemp(join(tmpdir(), 'dsh-segment-routing-')) + const ctx = new Context() + onTestFinished(async () => { try { await ctx.fiber.dispose() } finally { await rm(root, { recursive: true, force: true }) } }) + const storage = new Adapter(ctx, root) + return { root, ctx, storage } +} +const header: SessionHeader = { version: SESSION_FORMAT_VERSION, id: SessionId('selected'), createdAt: 0, isSeeded: false } + +it('uses the resolved defaults for SQLite creation', async () => { + const { storage } = await fixture() + const writer = await storage.create(header) + await writer.flush(); await writer.close() + await storage.flush() +}) + +it('validates routing read failures rather than treating them as absence', async () => { + const { storage } = await fixture() + faults.op = 'readFile'; faults.error = Object.assign(new Error('routing denied'), { code: 'EACCES' }) + await expect(storage.stat(header.id)).rejects.toThrow('routing denied') + faults.op = '' +}) + +it('rejects an unreadable routing directory and preserves explicit absence', async () => { + const { storage } = await fixture() + faults.op = 'readdir'; faults.error = Object.assign(new Error('directory denied'), { code: 'EACCES' }) + await expect(storage.list()).rejects.toThrow('directory denied') + faults.op = '' + expect(await storage.list()).toEqual([]) + +}) + +it('propagates routing directory read failures during create', async () => { + const { storage } = await fixture() + faults.op = 'readdir' + faults.error = Object.assign(new Error('routing directory denied'), { code: 'EACCES' }) + await expect(storage.create(header)).rejects.toThrow('routing directory denied') +}) + +it.each(['linux', 'win32'])('publishes routing using the %s durable namespace', async (platform) => { + const { root, storage } = await fixture() + const descriptor = Object.getOwnPropertyDescriptor(process, 'platform') + if (descriptor === undefined) throw new Error('Missing platform descriptor') + try { + Object.defineProperty(process, 'platform', { ...descriptor, value: platform }) + faults.directory = join(root, '.segments') + await storage.publishRoute(header.id) + await storage.publishRoute(header.id) + expect(faults.directorySyncs).toBe(platform === 'linux' ? 1 : 0) + expect(faults.directoryCloses).toBe(faults.directorySyncs) + } finally { Object.defineProperty(process, 'platform', descriptor) } +}) + +it.each(['identity', 'parse', 'race', 'link-failure'] as const)('retains routing publication failure for %s', async (fault) => { + const { root, storage: initial } = await fixture() + const writer = await initial.create(header); await writer.flush(); await writer.close() + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + const storage = new Adapter(ctx, root) + const { readdir, readFile } = await import('node:fs/promises') + const directory = join(root, '.segments') + const name = (await readdir(directory)).find(name => name.endsWith('.json')) + if (name === undefined) throw new Error('Missing route') + const path = join(directory, name), original = await readFile(path) + if (fault === 'identity' || fault === 'parse') { + await writeFile(path, fault === 'parse' ? 'invalid' : JSON.stringify({ id: 'wrong', database: '/wrong' })) + await expect(storage.publishRoute(header.id)).rejects.toThrow() + await writeFile(path, original) + } else { + await rm(path) + faults.op = 'link'; faults.error = Object.assign(new Error('link failure'), { code: fault === 'race' ? 'EEXIST' : 'EACCES' }) + faults.race = fault === 'race' + if (fault === 'race') await storage.publishRoute(header.id) + else await expect(storage.publishRoute(header.id)).rejects.toThrow('link failure') + faults.op = '' + } + await storage.publishRoute(header.id) +}) + + +it.each(['open', 'stat', 'readdir', 'exists'] as const)('refuses database initialization after a %s failure', async (op) => { + const { root } = await fixture() + const path = join(root, 'events.sqlite') + const { sqliteLogs } = await import('./fixtures/store.ts') + const logs = sqliteLogs(path, root) + if (op !== 'readdir') await writeFile(path, '') + faults.op = op === 'exists' ? 'stat' : op; faults.skip = op === 'stat' ? 1 : 0 + faults.error = Object.assign(new Error('database admission denied'), { code: 'EACCES' }) + try { await expect(logs.create(header)).rejects.toThrow('database admission denied') } + finally { + faults.op = '' + await expect(logs.close()).resolves.toBeUndefined() + } +}) + +it('refuses orphan routing records before admitting new Sessions', async () => { + const { storage, root } = await fixture() + await storage.publishRoute(header.id) + const { SqliteStore } = await import('../src/sqlite.ts') + const database = vi.spyOn(SqliteStore.prototype, 'hasDatabase').mockResolvedValue(false) + await expect(storage.stat(header.id)).rejects.toMatchObject({ code: 'SESSION_STORAGE_MISSING' }) + await rm(join(root, '.segments'), { recursive: true }) + expect(await storage.stat(header.id)).toBeUndefined() + faults.op = 'readdir'; faults.error = new Error('routing scan denied') + await expect(storage.stat(header.id)).rejects.toThrow('routing scan denied') + database.mockRestore() +}) + +it('reports a database removed between routing validation and row inspection', async () => { + const { storage } = await fixture() + const writer = await storage.create(header); await writer.flush(); await writer.close() + const { SqliteStore } = await import('../src/sqlite.ts') + vi.spyOn(SqliteStore.prototype, 'stat').mockResolvedValue(undefined) + vi.spyOn(SqliteStore.prototype, 'hasDatabase').mockResolvedValue(false) + await expect(storage.stat(header.id)).rejects.toMatchObject({ code: 'SESSION_STORAGE_MISSING' }) +}) + +it('refuses a competing publication with a different identity', async () => { + const { storage } = await fixture() + const actual = await vi.importActual('node:fs/promises') + const link = vi.spyOn(await import('node:fs/promises'), 'link').mockImplementation(async (_source, target) => { + await actual.writeFile(target, JSON.stringify({ id: 'wrong', database: '/wrong' })) + throw Object.assign(new Error('race'), { code: 'EEXIST' }) + }) + await expect(storage.publishRoute(header.id)).rejects.toMatchObject({ code: 'SESSION_STORAGE_IDENTITY' }) + link.mockRestore() +}) + +it('honors cancellation while entering the bounded routing scan', async () => { + const { storage } = await fixture() + const { SqliteStore } = await import('../src/sqlite.ts') + const aborted = new AbortController() + vi.spyOn(SqliteStore.prototype, 'assertRoutingDatabase').mockImplementation(async () => { aborted.abort() }) + await expect(storage.list({ signal: aborted.signal })).rejects.toThrow() +}) + +it('preserves filesystem failures while checking a database recreated during initialization', async () => { + const { root } = await fixture() + const actual = await vi.importActual('node:fs/promises') + await actual.mkdir(join(root, '.segments'), { recursive: true }) + await actual.writeFile(join(root, '.segments', 'orphan.json'), '{}') + const { sqliteLogs } = await import('./fixtures/store.ts') + const logs = sqliteLogs(join(root, 'missing.sqlite'), root) + const stat = vi.spyOn(await import('node:fs/promises'), 'stat') + .mockRejectedValueOnce(Object.assign(new Error('absent'), { code: 'ENOENT' })) + .mockRejectedValueOnce(new Error('stat denied')) + await expect(logs.start()).rejects.toThrow('stat denied') + stat.mockRestore() + await logs.close() +}) + +it('allows an empty routing directory without a database', async () => { + const { storage, root } = await fixture() + const actual = await vi.importActual('node:fs/promises') + await actual.mkdir(join(root, '.segments'), { recursive: true }) + expect(await storage.stat(header.id)).toBeUndefined() +}) + +it('accepts a database initialized while its routing directory is being inspected', async () => { + const { root } = await fixture() + const { sqliteLogs } = await import('./fixtures/store.ts') + const path = join(root, 'events.sqlite') + const observer = sqliteLogs(path, root), initializer = sqliteLogs(path, root) + const fs = await import('node:fs/promises') + const actual = await vi.importActual('node:fs/promises') + const readdir = vi.spyOn(fs, 'readdir').mockImplementationOnce(async (...args) => { + await initializer.start() + await actual.mkdir(join(root, '.segments'), { recursive: true }) + await actual.writeFile(join(root, '.segments', 'published.json'), '{}') + return actual.readdir(...args) + }) + try { await observer.assertRoutingDatabase() } + finally { readdir.mockRestore(); await observer.close(); await initializer.close() } +}) diff --git a/packages/session/session-persistence-sqlite/tests/storage-failures.spec.ts b/packages/session/session-persistence-sqlite/tests/storage-failures.spec.ts new file mode 100644 index 0000000000..ad91d1baf1 --- /dev/null +++ b/packages/session/session-persistence-sqlite/tests/storage-failures.spec.ts @@ -0,0 +1,559 @@ +/** SQLite durable-data refusals, failed transactions, and ownership cleanup. @module */ +import { mkdir, mkdtemp, rm, readdir, readFile, stat, writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { tmpdir } from 'node:os' +import { DatabaseSync } from 'node:sqlite' +import { Context } from '@deepseek-ai/cordis' +import { SessionId, SessionLogOffset, SessionSeq, SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session' +import type { SessionEvent, SessionHeader } from '@deepseek-ai/dsh-session' +import { SessionAlreadyExistsError, SessionFormatUnsupportedError, SessionHandleClosedError, + SessionPersistenceCorruptionError, SessionPersistenceNotFoundError } from '@deepseek-ai/dsh-session-persistence' +import { expect, it, onTestFinished, vi } from 'vitest' +import { z } from 'zod' +import { SessionWriteLease } from '../src/lease.ts' +import { SqliteSessionPersistence } from '../src/persistence.ts' +import { sharedHistory, sqliteLogs } from './fixtures/store.ts' +import { persistenceFixture } from './fixtures/persistence.ts' + +/** A coded refusal or an error class from a durable read. */ +type Refusal = { readonly code: string; readonly message?: string } | (new (...args: never[]) => Error) +async function expectRefusal(operation: Promise, refusal: Refusal): Promise { + if (typeof refusal === 'function') await expect(operation).rejects.toBeInstanceOf(refusal) + else await expect(operation).rejects.toMatchObject(refusal) +} +const header = (id = 'source'): SessionHeader => ({ version: SESSION_FORMAT_VERSION, id: SessionId(id), createdAt: 0, isSeeded: false }) +const event = (seq: number): SessionEvent => seq % 2 === 0 + ? { type: 'turn/start', seq: SessionSeq(seq), time: 0, data: { turn: seq / 2 + 1 } } + : { type: 'turn/end', seq: SessionSeq(seq), time: 0, data: { turn: (seq + 1) / 2, reason: { kind: 'completed' } } } +async function fixture() { + const fixture = await persistenceFixture() + const { context: ctx, persistence: storage } = await fixture.mount('sqlite') + if (!(storage instanceof SqliteSessionPersistence)) throw new Error('Missing SQLite provider') + return { root: fixture.root, ctx, storage } +} +async function raw(publish: () => Promise = async () => {}, failedClose = false) { + const root = await mkdtemp(join(tmpdir(), 'dsh-sqlite-failures-')), path = join(root, 'events.sqlite') + const report = vi.fn() + const logs = sqliteLogs(path, root, { publish, report }) + onTestFinished(async () => { + try { + if (failedClose) await expect(logs.close()).rejects.toMatchObject({ message: 'SQLite disposal failed', errors: [expect.any(Error)] }) + else await logs.close() + } finally { await rm(root, { recursive: true, force: true }) } + }) + return { logs, path, root, report } +} + +it.each([ + { fault: 'identity', open: { code: 'SESSION_STORAGE_IDENTITY' }, list: { code: 'SESSION_STORAGE_IDENTITY' } }, + { fault: 'missing-row', open: SessionPersistenceNotFoundError, list: { code: 'SESSION_STORAGE_MISSING' } }, + { fault: 'invalid-json', open: { code: 'SESSION_STORAGE_CORRUPT' }, list: { code: 'SESSION_STORAGE_CORRUPT' } }, +] as const)('refuses $fault without creating a JSONL fallback', async ({ fault, open, list }) => { + const { storage, root } = await fixture() + const writer = await storage.create(header()); await writer.flush(); await writer.close() + const directory = join(root, '.segments') + const route = (await readdir(directory)).find(name => name.endsWith('.json')) + if (route === undefined) throw new Error('Missing route') + const path = join(directory, route) + if (fault === 'identity') { + const value = z.object({ id: z.string(), database: z.string() }).parse(JSON.parse(await readFile(path, 'utf8'))) + await writeFile(path, JSON.stringify({ ...value, database: '/wrong.sqlite' })) + } else if (fault === 'invalid-json') await writeFile(path, 'invalid') + else { + const db = new DatabaseSync(join(directory, 'sessions.sqlite')) + try { db.prepare('DELETE FROM traces WHERE trace_uuid = ?').run('source') } finally { db.close() } + } + await expectRefusal(storage.open(header().id, 'write'), open) + if (fault === 'missing-row') await expectRefusal(storage.list(), list) + else expect(await storage.list()).toHaveLength(1) + expect((await readdir(root, { recursive: true })).some(name => name.endsWith('.jsonl'))).toBe(false) +}) + +it.each([ + { label: 'corrupt', stored: '{invalid', error: SessionPersistenceCorruptionError }, + { label: 'future-version', stored: JSON.stringify({ ...header(), version: SESSION_FORMAT_VERSION + 1 }), error: SessionFormatUnsupportedError }, +])('omits a $label SQLite header from list while direct access still rejects', async ({ stored, error }) => { + const { storage, root } = await fixture() + const writer = await storage.create(header()); await writer.append([event(0)]); await writer.close() + const healthy = await storage.create(header('healthy')); await healthy.append([event(0)]); await healthy.close() + const db = new DatabaseSync(join(root, '.segments/sessions.sqlite')) + try { + db.prepare('UPDATE traces SET header = ? WHERE trace_uuid = ?').run(stored, header().id) + } finally { db.close() } + await expect(storage.open(header().id, 'read')).rejects.toBeInstanceOf(error) + await expect(storage.stat(header().id)).rejects.toBeInstanceOf(error) + expect((await storage.list()).map(entry => entry.header.id)).toEqual([SessionId('healthy')]) +}) + +it('rejects the listing when a stored SQLite header names another Session', async () => { + const { storage, root } = await fixture() + const writer = await storage.create(header()); await writer.append([event(0)]); await writer.close() + const db = new DatabaseSync(join(root, '.segments/sessions.sqlite')) + try { + db.prepare('UPDATE traces SET header = ? WHERE trace_uuid = ?').run(JSON.stringify(header('other')), header().id) + } finally { db.close() } + await expect(storage.list()).rejects.toThrow('identity mismatch') +}) + +it.each(['{}', '[]', 'null', '4', JSON.stringify({ version: 4.5 }), JSON.stringify({ version: SESSION_FORMAT_VERSION, id: 'source' })])( + 'classifies an invalid stored SQLite header %#', + async (storedHeader) => { + const { storage, root } = await fixture() + const writer = await storage.create(header()); await writer.append([event(0)]); await writer.close() + const db = new DatabaseSync(join(root, '.segments/sessions.sqlite')) + try { + db.prepare('UPDATE traces SET header = ? WHERE trace_uuid = ?').run(storedHeader, header().id) + } finally { db.close() } + await expect(storage.open(header().id, 'read')).rejects.toBeInstanceOf(SessionPersistenceCorruptionError) + }, +) + +it('classifies a non-database SQLite file', async () => { + const root = await mkdtemp(join(tmpdir(), 'dsh-segment-corrupt-db-')) + onTestFinished(() => rm(root, { recursive: true, force: true })) + const path = join(root, 'sessions.sqlite') + await writeFile(path, 'not a database') + const logs = sqliteLogs(path, root) + onTestFinished(async () => { await logs.close().catch(() => undefined) }) + await expect(logs.stat(header().id)).rejects.toBeInstanceOf(SessionPersistenceCorruptionError) +}) + +it('fails on invalid selected event data while unrelated Session bodies remain readable', async () => { + const { storage, root } = await fixture() + const writer = await storage.create(header()); await writer.append([event(0)]); await writer.close() + const db = new DatabaseSync(join(root, '.segments/sessions.sqlite')) + try { + db.exec('DROP TRIGGER events_no_update') + db.prepare('UPDATE events SET payload = ?').run('invalid') + } finally { db.close() } + await expect(storage.open(header().id, 'write')).rejects.toBeInstanceOf(SessionPersistenceCorruptionError) + const replacement = await storage.create(header('healthy')); await replacement.flush(); await replacement.close() + expect(await storage.stat(SessionId('healthy'))).toMatchObject({ eventCount: 0 }) +}) + +it('preserves complete Session metadata without exposing Segment identifiers', async () => { + const { logs } = await raw() + const meta: SessionHeader = { ...header(), cwd: tmpdir(), parentSession: SessionId('parent'), origin: 'subagent', delegationDepth: 2, agentPreset: 'test' } + const writer = await logs.create(meta); await writer.flush(); await writer.close() + const reader = await logs.open(meta.id, 'read') + expect(reader.header).toEqual(meta) + await reader[Symbol.asyncDispose]() +}) + +it.each([ + { fault: 'missing-segment', error: SessionPersistenceCorruptionError }, + { fault: 'missing-parent', error: { code: 'SESSION_STORAGE_CORRUPT', message: 'Trace references a missing segment' } }, + { fault: 'cycle', error: { code: 'SESSION_STORAGE_CORRUPT', message: 'Invalid Trace segment chain' } }, + { fault: 'missing-prefix', error: SessionPersistenceCorruptionError }, + { fault: 'offset', error: { code: 'SESSION_STORAGE_CORRUPT', message: 'Invalid segment offset' } }, + { fault: 'event-hole', error: { code: 'SESSION_STORAGE_CORRUPT', message: 'SQLite segment is incomplete' } }, + { fault: 'identity', error: { code: 'SESSION_STORAGE_CORRUPT', message: 'SQLite Trace identity mismatch' } }, +] as const)( + 'refuses corrupted $fault instead of returning partial history', async ({ fault, error }) => { + const { logs, path } = await raw() + const source = await logs.create(header()); await source.append([event(0), event(1)]); await source.close() + await sharedHistory(logs, header().id, SessionId('child'), [event(0)]) + const reader = await logs.open(SessionId('child'), 'read') + const db = new DatabaseSync(path) + try { + db.exec('PRAGMA foreign_keys = OFF; PRAGMA ignore_check_constraints = ON; DROP TRIGGER segments_no_reparent; DROP TRIGGER events_no_delete;') + const head = "(SELECT tail_segment_uuid FROM traces WHERE trace_uuid = 'child')" + if (fault === 'missing-segment') db.exec(`DELETE FROM segments WHERE segment_uuid = ${head}`) + if (fault === 'missing-parent') db.exec(`UPDATE segments SET parent_segment_uuid = 'absent' WHERE segment_uuid = ${head}`) + if (fault === 'cycle') db.exec(`UPDATE segments SET parent_segment_uuid = segment_uuid, parent_end_seq = 0 WHERE segment_uuid = ${head}`) + if (fault === 'missing-prefix') db.exec(`UPDATE segments SET parent_segment_uuid = NULL, parent_end_seq = NULL WHERE segment_uuid = ${head}`) + if (fault === 'offset') db.exec(`UPDATE segments SET parent_end_seq = 0 WHERE segment_uuid = ${head}`) + if (fault === 'event-hole') db.exec(`INSERT INTO events SELECT segment_uuid, 1, payload FROM events WHERE segment_uuid = ${head}; DELETE FROM events WHERE segment_uuid = ${head} AND seq = 0`) + if (fault === 'identity') db.prepare("UPDATE traces SET header = ? WHERE trace_uuid = 'child'").run(JSON.stringify(header('other'))) + await expectRefusal(fault === 'identity' ? logs.open(SessionId('child'), 'read') : reader.read(), error) + } finally { db.close(); await reader.close() } + }) + +it('refuses live events on a closed handle and keeps close idempotent', async () => { + const { logs } = await raw() + const writer = await logs.create(header()); await writer.close() + const failure = await writer.receive(event(0)).then(() => undefined, (error: unknown) => error) + expect(failure).toMatchObject({ code: 'SESSION_STORAGE_FAILED' }) + expect(failure instanceof Error ? failure.cause : undefined).toBeInstanceOf(SessionHandleClosedError) + await writer.close() +}) + +it('isolates an unknown transaction outcome and releases the writer when the database closes', async () => { + const { logs } = await raw() + const writer = await logs.create(header()); await writer.flush() + // oxlint-disable-next-line typescript/unbound-method -- Called with the intercepted database as receiver below. + const exec = DatabaseSync.prototype.exec + const spy = vi.spyOn(DatabaseSync.prototype, 'exec').mockImplementation(function (this: DatabaseSync, sql) { + if (sql === 'COMMIT' || sql === 'ROLLBACK') throw new Error('transaction outcome unavailable') + exec.call(this, sql) + }) + try { + const failure = await writer.append([event(0)]).then(() => undefined, (error: unknown) => error) + expect(failure).toMatchObject({ code: 'SESSION_STORAGE_UNKNOWN', cause: { errors: [{ message: 'transaction outcome unavailable' }, { message: 'transaction outcome unavailable' }] } }) + // Every later operation of the store rejects with the same retained refusal. + await expect(logs.stat(header().id)).rejects.toBe(failure) + await expect(writer.append([event(0)])).rejects.toBe(failure) + } finally { spy.mockRestore(); await writer.close() } +}) + +it('marks unknown when COMMIT fails even if ROLLBACK succeeds', async () => { + const { logs } = await raw() + const writer = await logs.create(header()); await writer.flush() + // oxlint-disable-next-line typescript/unbound-method -- Called with the intercepted database as receiver below. + const exec = DatabaseSync.prototype.exec + const spy = vi.spyOn(DatabaseSync.prototype, 'exec').mockImplementation(function (this: DatabaseSync, sql) { + if (sql === 'COMMIT') throw new Error('commit outcome unavailable') + exec.call(this, sql) + }) + try { + const failure = await writer.append([event(0)]).then(() => undefined, (error: unknown) => error) + expect(failure).toMatchObject({ code: 'SESSION_STORAGE_UNKNOWN', cause: { message: 'commit outcome unavailable' } }) + await expect(logs.stat(header().id)).rejects.toBe(failure) + } finally { spy.mockRestore(); await writer.close() } +}) + +it('aggregates drain and release failures on close', async () => { + const { logs, path } = await raw() + const writer = await logs.create(header()); await writer.flush() + const db = new DatabaseSync(path) + try { + db.exec("CREATE TRIGGER fail_close BEFORE INSERT ON events BEGIN SELECT RAISE(ABORT, 'drain failed'); END") + await writer.receive(event(0)) + // oxlint-disable-next-line typescript/unbound-method -- Called with the lease instance as receiver. + const original = SessionWriteLease.prototype.release + SessionWriteLease.prototype.release = async function (this: SessionWriteLease) { + await original.call(this) + throw new Error('release failed') + } + try { + const failure = await writer.close().then(() => undefined, (error: unknown) => error) + expect(failure).toBeInstanceOf(AggregateError) + const messages = (failure as AggregateError).errors.map(String) + expect(messages.some(message => message.includes('drain failed'))).toBe(true) + expect(messages.some(message => message.includes('release failed'))).toBe(true) + } finally { SessionWriteLease.prototype.release = original } + } finally { db.close() } +}) + +it('marks unknown when an operation failure and its rollback both fail', async () => { + const { logs, path } = await raw() + const writer = await logs.create(header()); await writer.flush() + const db = new DatabaseSync(path) + try { + db.exec("CREATE TRIGGER fail_operation BEFORE INSERT ON events BEGIN SELECT RAISE(ABORT, 'operation failed'); END") + // oxlint-disable-next-line typescript/unbound-method -- Called with the intercepted database as receiver below. + const exec = DatabaseSync.prototype.exec + const spy = vi.spyOn(DatabaseSync.prototype, 'exec').mockImplementation(function (this: DatabaseSync, sql) { + if (sql === 'ROLLBACK') throw new Error('rollback unavailable') + exec.call(this, sql) + }) + try { + await expect(writer.append([event(0)])).rejects.toMatchObject({ code: 'SESSION_STORAGE_UNKNOWN', + cause: { errors: [{ message: 'operation failed' }, { message: 'rollback unavailable' }] } }) + } finally { spy.mockRestore() } + } finally { db.close() } +}) + +it('aggregates failed writer barriers and disposal failures without losing their cause', async () => { + const { logs, path } = await raw(async () => {}, true) + const writer = await logs.create(header()); await writer.flush() + const db = new DatabaseSync(path) + try { + db.exec("CREATE TRIGGER fail_append BEFORE INSERT ON events BEGIN SELECT RAISE(ABORT, 'persistent failure'); END") + await writer.receive(event(0)) + await expect(logs.flush()).rejects.toMatchObject({ message: 'SQLite flush failed', errors: [expect.any(Error)] }) + await expect(logs.close()).rejects.toMatchObject({ message: 'SQLite disposal failed', errors: [expect.any(Error)] }) + } finally { db.close() } +}) + +it('joins an already closing writer during a provider flush', async () => { + const { logs } = await raw() + const writer = await logs.create(header()); await writer.append([event(0)]) + const append = logs.append.bind(logs), gate = Promise.withResolvers() + const spy = vi.spyOn(logs, 'append').mockImplementationOnce(async (...args) => { await gate.promise; await append(...args) }) + onTestFinished(() => { gate.resolve(undefined); spy.mockRestore() }) + await writer.receive(event(1)) + const closing = writer.close() + let flushed = false + const flush = logs.flush().then(() => { flushed = true }) + await new Promise(resolve => setImmediate(resolve)) + // The provider barrier joins the closing writer's held drain instead of resolving around it. + expect(flushed).toBe(false) + gate.resolve(undefined) + await flush + expect((await logs.stat(header().id))?.eventCount).toBe(2) + await closing +}) + +it('materializes pending metadata through listing and releases abandoned creates', async () => { + const { logs } = await raw() + const writer = await logs.create(header()) + expect((await logs.scan()).entries).toHaveLength(1) + const pendingReader = await logs.open(header().id, 'read') + expect((await pendingReader.read()).events).toEqual([]) + await pendingReader.close(); await writer.close() + expect((await logs.scan()).entries).toEqual([]) +}) + +it('refuses a missing parent Session row before appending and preserves the committed payloads', async () => { + const { logs, path } = await raw() + const writer = await logs.create(header()); await writer.append([event(0)]) + const db = new DatabaseSync(path) + try { + db.prepare('DELETE FROM traces WHERE trace_uuid = ?').run(header().id) + await expect(writer.read()).rejects.toBeInstanceOf(SessionPersistenceNotFoundError) + await expect(writer.append([event(1)])).rejects.toBeInstanceOf(SessionPersistenceNotFoundError) + } finally { db.close(); await writer.close() } +}) + +it('reports listener failures and joins successful consumer teardown through the owning scope', async () => { + const { logs } = await raw() + const { SessionStore } = await import('@deepseek-ai/dsh-session') + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + await ctx.plugin(SessionStore) + logs.install(ctx) + const session = ctx.sessions.create(header().id) + const writer = await logs.create(session.header) + const error = vi.spyOn(ctx.logger, 'error').mockImplementation(() => {}) + const receive = vi.spyOn(writer, 'receive').mockRejectedValueOnce(new Error('event admission refused')) + const close = vi.spyOn(writer, 'close').mockRejectedValueOnce(new Error('close refused')) + onTestFinished(() => { error.mockRestore(); receive.mockRestore(); close.mockRestore() }) + ctx.emit('session/event', session, event(0)) + ctx.emit('session/disposed', session) + await vi.waitFor(() => { expect(error).toHaveBeenCalledTimes(2) }) + expect(error.mock.calls.map(([message]) => String(message)).sort()).toEqual([ + 'SQLite handle close failed for source: Error: close refused', + 'SQLite persistence failed for source: Error: event admission refused', + ]) + close.mockRestore(); receive.mockRestore() + await writer.close() + await ctx.fiber.dispose() +}) + +it('refuses opening a missing database without creating it', async () => { + const { logs, path } = await raw() + await expect(logs.open(header().id, 'read')).rejects.toBeInstanceOf(SessionPersistenceNotFoundError) + await expect(stat(path)).rejects.toMatchObject({ code: 'ENOENT' }) +}) + +it('refuses a stale append position after the durable tail grows', async () => { + const { logs, path } = await raw() + const writer = await logs.create(header()); await writer.append([event(0)]) + const db = new DatabaseSync(path) + try { + db.prepare('INSERT INTO events SELECT segment_uuid, 1, ? FROM segments').run(JSON.stringify(event(1))) + await expect(writer.append([event(1)])).rejects.toThrow('append seq mismatch for "source": expected 2 at index 0, got 1') + } finally { db.close(); await writer.close() } +}) + +it('rolls back materialization when a database trigger removes its new metadata', async () => { + const { logs, path } = await raw() + const committed = await logs.create(header()); await committed.flush(); await committed.close() + const writer = await logs.create(header('pending')) + const db = new DatabaseSync(path) + try { + db.exec('CREATE TRIGGER remove_new_trace AFTER INSERT ON traces BEGIN DELETE FROM traces WHERE trace_uuid = NEW.trace_uuid; END') + await expect(writer.flush()).rejects.toMatchObject({ code: 'SESSION_STORAGE_CORRUPT', message: 'Committed Session metadata is unavailable' }) + db.exec('DROP TRIGGER remove_new_trace') + await writer.flush() + } finally { db.close(); await writer.close() } +}) + +it('rejects a corrupt stored header identity during stat', async () => { + const { logs, path } = await raw() + const writer = await logs.create(header()); await writer.flush(); await writer.close() + const db = new DatabaseSync(path) + try { db.prepare('UPDATE traces SET header = ?').run(JSON.stringify(header('different'))) } finally { db.close() } + await expect(logs.stat(header().id)).rejects.toThrow('identity mismatch') +}) + +it('includes pending creates beside materialized metadata and tolerates a pending entry disappearing', async () => { + const { logs } = await raw() + const writer = await logs.create(header()); await writer.flush(); await writer.close() + const pending = await logs.create(header('pending')) + expect((await logs.scan()).entries).toHaveLength(2) + const stat = logs.stat.bind(logs) + const spy = vi.spyOn(logs, 'stat').mockImplementation(async id => id === SessionId('pending') ? undefined : stat(id)) + expect((await logs.scan()).entries).toHaveLength(1) + spy.mockRestore(); await pending.close() +}) + +it('rejects queued work after a preceding commit failed to publish its routing record', async () => { + const { logs } = await raw(async () => { throw new Error('publish unavailable') }) + const writer = await logs.create(header()) + const first = writer.append([event(0)]), queued = writer.append([event(1)]) + const failure = await first.then(() => undefined, (error: unknown) => error) + expect(failure).toMatchObject({ code: 'SESSION_STORAGE_PUBLICATION', cause: { message: 'publish unavailable' } }) + await expect(queued).rejects.toBe(failure) + await expect(writer.close()).rejects.toBe(failure) +}) + +it('refuses importing a legacy identity already committed in SQLite', async () => { + const { logs } = await raw() + await logs.importLegacy(header(), SessionLogOffset(0), []) + await expect(logs.importLegacy(header(), SessionLogOffset(0), [])).rejects.toBeInstanceOf(SessionAlreadyExistsError) +}) + +it('keeps an absent materialization a no-op', async () => { + const { logs } = await raw() + await logs.materialize(header()) +}) + +it('aggregates write-open validation and ownership cleanup failures', async () => { + const { logs } = await raw() + const writer = await logs.create(header()); await writer.flush(); await writer.close() + const { SessionWriteLease } = await import('../src/lease.ts') + // oxlint-disable-next-line typescript/unbound-method -- Forwarded with the lease receiver below. + const release = SessionWriteLease.prototype.release + const fault = vi.spyOn(SessionWriteLease.prototype, 'release').mockImplementation(async function (this: SessionWriteLease) { + await release.call(this) + throw new Error('release failed') + }) + const read = vi.spyOn(logs, 'read').mockRejectedValue(new Error('history failed')) + try { await expect(logs.open(header().id, 'write')).rejects.toMatchObject({ errors: [expect.any(Error), expect.any(Error)] }) } + finally { fault.mockRestore(); read.mockRestore() } +}) + +it('aggregates creation refusal and shared ownership rollback failure', async () => { + const { logs } = await raw() + const { SessionWriteLease } = await import('../src/lease.ts') + const acquire = SessionWriteLease.acquire.bind(SessionWriteLease) + let calls = 0 + const fault = vi.spyOn(SessionWriteLease, 'acquire').mockImplementation(async (dir, id) => { + if (++calls === 2) throw new Error('artifact refused') + const lease = await acquire(dir, id) + const release = lease.release.bind(lease) + lease.release = async () => { await release(); throw new Error('rollback failed') } + return lease + }) + const writer = await logs.create(header()) + try { await expect(writer.flush()).rejects.toMatchObject({ errors: [expect.any(Error), expect.any(Error)] }) } + finally { fault.mockRestore(); await writer.close() } +}) + +it.each([1, 2])('reports %i owned lease release failures', async (failures) => { + const { logs } = await raw() + const { SessionWriteLease } = await import('../src/lease.ts') + const acquire = SessionWriteLease.acquire.bind(SessionWriteLease) + let acquired = 0 + const fault = vi.spyOn(SessionWriteLease, 'acquire').mockImplementation(async (dir, id) => { + const lease = await acquire(dir, id) + const release = lease.release.bind(lease) + if (++acquired <= failures) lease.release = async () => { await release(); throw new Error('release failed') } + return lease + }) + const writer = await logs.create(header()) + try { + await writer.flush() + await expect(writer.close()).rejects.toThrow(failures === 1 ? 'release failed' : 'SQLite write ownership release failed') + } finally { fault.mockRestore() } +}) + +it('refuses initializing a missing database when Session routing records remain', async () => { + const { logs, root, path } = await raw() + await mkdir(join(root, '.segments')) + await writeFile(join(root, '.segments/source.json'), JSON.stringify({ id: 'source', database: path })) + await expect(logs.start()).rejects.toMatchObject({ code: 'SESSION_STORAGE_MISSING' }) + await expect(stat(path)).rejects.toMatchObject({ code: 'ENOENT' }) +}) + +it('leaves an unrelated unversioned SQLite database intact', async () => { + const { logs, path } = await raw() + const db = new DatabaseSync(path) + try { + db.exec('CREATE TABLE unrelated (value TEXT)') + await expect(logs.start()).rejects.toMatchObject({ code: 'SESSION_STORAGE_FORMAT' }) + expect(db.prepare("SELECT name FROM sqlite_schema WHERE type = 'table'").all()).toEqual([{ name: 'unrelated' }]) + expect(db.prepare('PRAGMA user_version').get()).toMatchObject({ user_version: 0 }) + } finally { db.close() } +}) + +it('reports an absent Session in an existing database', async () => { + const { logs } = await raw() + const writer = await logs.create(header()); await writer.flush(); await writer.close() + await expect(logs.open(SessionId('absent'), 'read')).rejects.toBeInstanceOf(SessionPersistenceNotFoundError) +}) + +it('refuses a non-text payload in a damaged durable event table', async () => { + const { logs, path } = await raw() + const writer = await logs.create(header()); await writer.append([event(0)]); await writer.close() + const db = new DatabaseSync(path) + try { + const head = db.prepare('SELECT tail_segment_uuid FROM traces').get()?.['tail_segment_uuid'] + if (typeof head !== 'string') throw new Error('Missing Session segment') + db.exec('DROP TABLE events; CREATE TABLE events (segment_uuid TEXT, seq INTEGER, payload ANY) STRICT') + db.prepare('INSERT INTO events VALUES (?, 0, ?)').run(head, null) + } finally { db.close() } + const reader = await logs.open(header().id, 'read') + try { await expect(reader.read()).rejects.toBeInstanceOf(SessionPersistenceCorruptionError) } + finally { await reader.close() } +}) + +it('classifies retired V4 events as unsupported when reading durable rows', async () => { + const { logs, path } = await raw() + const writer = await logs.create(header()); await writer.append([event(0)]); await writer.close() + const db = new DatabaseSync(path) + try { + db.exec('DROP TRIGGER events_no_update') + db.prepare('UPDATE events SET payload = ?').run(JSON.stringify({ type: 'tool/code-dispatch', seq: 0, time: 0, data: {} })) + } finally { db.close() } + const reader = await logs.open(header().id, 'read') + try { await expect(reader.read()).rejects.toBeInstanceOf(SessionFormatUnsupportedError) } + finally { await reader.close() } +}) + +it('refuses invalid indexed predecessor metadata before returning inherited events', async () => { + const { logs, path } = await raw() + const writer = await logs.create(header()); await writer.append([event(0), event(1)]); await writer.close() + await sharedHistory(logs, header().id, SessionId('child'), [event(0), event(1)]) + const db = new DatabaseSync(path) + try { + db.exec('DROP TRIGGER segments_no_reparent; PRAGMA ignore_check_constraints = ON') + db.exec('UPDATE segments SET parent_end_seq = -1 WHERE parent_segment_uuid IS NULL') + } finally { db.close() } + await expect(sharedHistory(logs, SessionId('child'), SessionId('bad-cut'), [event(0)])).rejects.toThrow('predecessor metadata is invalid') + const reader = await logs.open(SessionId('child'), 'read') + try { await expect(reader.read(0, 1)).rejects.toThrow('predecessor metadata is invalid') } + finally { await reader.close() } +}) + +it('forks an earlier ancestor prefix and refuses invalid ancestry during cut selection', async () => { + const { logs, path } = await raw() + const source = await logs.create(header()); await source.append([event(0), event(1), event(2)]); await source.close() + await sharedHistory(logs, header().id, SessionId('child'), [event(0), event(1)]) + await sharedHistory(logs, SessionId('child'), SessionId('grandchild'), [event(0)]) + const grandchild = await logs.open(SessionId('grandchild'), 'read') + try { expect((await grandchild.read()).events.map(item => item.seq)).toEqual([0, 1]) } + finally { await grandchild.close() } + const db = new DatabaseSync(path) + try { + db.exec('DROP TRIGGER ancestors_no_update; DROP TRIGGER ancestors_no_delete') + db.exec("UPDATE segment_ancestors SET end_seq = 0 WHERE segment_uuid = (SELECT tail_segment_uuid FROM traces WHERE trace_uuid = 'child')") + await expect(sharedHistory(logs, SessionId('child'), SessionId('invalid'), [event(0)])).rejects.toThrow('offset') + db.exec("DELETE FROM segment_ancestors WHERE segment_uuid = (SELECT tail_segment_uuid FROM traces WHERE trace_uuid = 'child')") + await expect(sharedHistory(logs, SessionId('child'), SessionId('invalid'), [event(0)])).rejects.toThrow('chain') + } finally { db.close() } +}) + +it('ignores events from a Session without a persistence writer', async () => { + const { ctx, storage } = await fixture() + const session = ctx.sessions.create(header().id) + session.append('turn/start', { turn: 1 }) + await storage.flush() + expect(await storage.stat(session.id)).toBeUndefined() +}) + +it('reports a database close failure after draining and releasing the writer', async () => { + const { logs } = await raw(async () => {}, true) + const writer = await logs.create(header()); await writer.flush(); await writer.close() + const failure = Object.assign(new Error('database close failed'), { code: 'EIO' }) + // oxlint-disable-next-line typescript/unbound-method -- Forwarded with the intercepted database receiver. + const close = DatabaseSync.prototype.close + const fault = vi.spyOn(DatabaseSync.prototype, 'close').mockImplementationOnce(function (this: DatabaseSync) { + close.call(this) + throw failure + }) + try { await expect(logs.close()).rejects.toMatchObject({ message: 'SQLite disposal failed', errors: [failure] }) } + finally { fault.mockRestore() } +}) diff --git a/packages/session/session-persistence-sqlite/tests/structure.spec.ts b/packages/session/session-persistence-sqlite/tests/structure.spec.ts new file mode 100644 index 0000000000..3129768669 --- /dev/null +++ b/packages/session/session-persistence-sqlite/tests/structure.spec.ts @@ -0,0 +1,201 @@ +/** SQLite list ordering, indexed reads and atomic append failures for Segment persistence. @module */ +import { DatabaseSync } from 'node:sqlite' +import { mkdtemp, rm } from 'node:fs/promises' +import { join } from 'node:path' +import { tmpdir } from 'node:os' +import { expect, it, onTestFinished } from 'vitest' +import { z } from 'zod' +import { SESSION_FORMAT_VERSION, SessionId, SessionSeq } from '@deepseek-ai/dsh-session' +import type { SessionEvent, SessionHeader } from '@deepseek-ai/dsh-session' +import { createUserMessage } from '@deepseek-ai/dsh-llm' +import { SCHEMA_VERSION } from '../src/sqlite.ts' +import { countSqliteReads, sharedHistory, sqliteLogs } from './fixtures/store.ts' + +async function fixture() { + const root = await mkdtemp(join(tmpdir(), 'dsh-sqlite-persistence-')), path = join(root, 'sessions.sqlite') + const logs = sqliteLogs(path, root) + onTestFinished(async () => { try { await logs.close() } finally { await rm(root, { recursive: true, force: true }) } }) + const id = SessionId('selected') + const header: SessionHeader = { version: SESSION_FORMAT_VERSION, id, createdAt: 0, isSeeded: false } + const event = (seq: number, text = `event ${seq}`): SessionEvent<'user/message'> => ({ type: 'user/message', surfaceOp: 'append', seq: SessionSeq(seq), time: 0, + data: createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'user' } }) }) + return { root, logs, path, id, header, event } +} + +it('selects a cut inside an earlier ancestor rather than sharing the later child suffix', async () => { + const { logs, id, header, event } = await fixture() + await using parent = await logs.create(header) + const prefix = [event(0), event(1), event(2)] + await parent.append(prefix) + const childId = SessionId('later-child'), descendantId = SessionId('earlier-cut') + await sharedHistory(logs, id, childId, prefix) + await sharedHistory(logs, childId, descendantId, prefix.slice(0, 1)) + await using descendant = await logs.open(descendantId, 'read') + expect((await descendant.read()).events).toEqual([ + prefix[0], { type: 'session/end-seed', seq: SessionSeq(1), time: 0, data: { inherited: true } }, + ]) +}) + +it('forks bounded prefixes into private tails without copying historical event rows', async () => { + const { logs, path, id, header, event } = await fixture() + const reads = countSqliteReads() + const source = await logs.create(header) + const sourcePrefix = [event(0), event(1), event(2), event(3)] + await source.append(sourcePrefix) + const db = new DatabaseSync(path) + try { + const count = (table: 'traces' | 'segments' | 'events') => z.object({ n: z.number() }) + .parse(db.prepare(`SELECT count(*) AS n FROM ${table}`).get()).n + const before = [count('traces'), count('segments'), count('events')] + const branchId = SessionId('branch') + await sharedHistory(logs, id, branchId, sourcePrefix.slice(0, 2)) + expect([count('traces'), count('segments'), count('events')]).toEqual(before.map(value => value + 1)) + const branch = await logs.open(branchId, 'write') + expect(branch.inheritedEventCount).toBe(2) + expect((await branch.read()).events.map(item => item.seq)).toEqual([0, 1, 2]) + await branch.append([event(3, 'branch-only')]) + await source.append([event(4, 'source-only')]) + expect(JSON.stringify((await branch.read()).events)).not.toContain('source-only') + expect(JSON.stringify((await source.read()).events)).not.toContain('branch-only') + const beforeForks = [count('traces'), count('segments'), count('events')] + let current = branchId + let prefix: SessionEvent[] = (await branch.read()).events + const beforePayloads = reads.payloadRows() + for (let index = 0; index < 128; index++) { + const next = SessionId(`descendant-${index}`) + await sharedHistory(logs, current, next, prefix) + prefix = [...prefix, { type: 'session/end-seed', seq: SessionSeq(prefix.length), time: 0, data: { inherited: true } }] + current = next + } + expect([count('traces'), count('segments'), count('events')]).toEqual(beforeForks.map(value => value + 128)) + expect(reads.payloadRows() - beforePayloads).toBe(0) + const last = await logs.open(current, 'read') + const beforeTail = reads.segmentQueries() + expect((await last.read(131, 1)).events).toHaveLength(1) + expect(reads.segmentQueries() - beforeTail).toBe(1) + expect((await last.read()).events).toHaveLength(132) + const warm = reads.segmentQueries() + expect((await last.read(0, 1)).events).toHaveLength(1) + expect(reads.segmentQueries() - warm).toBe(1) + await last.close() + const reopened = await logs.open(current, 'read'), cold = reads.segmentQueries() + expect((await reopened.read(0, 1)).events).toHaveLength(1) + expect(reads.segmentQueries() - cold).toBe(2) + } finally { db.close() } +}) + +it('rolls back the whole appended batch and its cursor when an insert fails', async () => { + const { logs, path, id, header, event } = await fixture() + const handle = await logs.create(header) + await handle.append([event(0)]) + const db = new DatabaseSync(path) + try { + const before = db.prepare('SELECT * FROM traces WHERE trace_uuid = ?').get(id) + db.exec("CREATE TRIGGER reject_fixture BEFORE INSERT ON events WHEN NEW.seq = 2 BEGIN SELECT RAISE(ABORT, 'fixture insert failure'); END") + await expect(handle.append([event(1), event(2)])).rejects.toThrow('fixture insert failure') + expect(db.prepare('SELECT seq FROM events WHERE segment_uuid = (SELECT tail_segment_uuid FROM traces WHERE trace_uuid = ?) ORDER BY seq').all(id)).toMatchObject([{ seq: 0 }]) + expect(db.prepare('SELECT * FROM traces WHERE trace_uuid = ?').get(id)).toEqual(before) + await handle.flush() + await handle.close() + db.exec('DROP TRIGGER reject_fixture') + const restored = await logs.open(id, 'write') + await restored.append([event(1)]) + expect((await restored.read()).events).toHaveLength(2) + } finally { db.close() } +}) + +it('refuses an incompatible database version while retaining its schema and payloads', async () => { + const { root, logs, path, header, id, event } = await fixture() + const handle = await logs.create(header) + await handle.append([event(0)]) + await handle.close() + await logs.close() + const db = new DatabaseSync(path) + const before = db.prepare('SELECT payload FROM events').all() + db.exec(`PRAGMA user_version = ${SCHEMA_VERSION + 1}`) + db.close() + const refused = sqliteLogs(path, root) + await expect(refused.stat(id)).rejects.toMatchObject({ code: 'SESSION_STORAGE_FORMAT' }) + await expect(refused.close()).resolves.toBeUndefined() + const inspect = new DatabaseSync(path) + try { + expect(inspect.prepare('PRAGMA user_version').get()).toMatchObject({ user_version: SCHEMA_VERSION + 1 }) + expect(inspect.prepare('SELECT payload FROM events').all()).toEqual(before) + } finally { inspect.close() } +}) + +it('recovers append positions from the event index without updating Trace or Segment metadata', async () => { + const { root, logs, path, id, header, event } = await fixture() + const handle = await logs.create(header) + await handle.flush() + const db = new DatabaseSync(path) + try { + for (const table of ['traces', 'segments']) { + const columns = db.prepare(`PRAGMA table_info(${table})`).all().map(column => column.name) + expect(columns).not.toContain('next_seq') + expect(columns).not.toContain('revision') + db.exec(`CREATE TRIGGER reject_${table}_update BEFORE UPDATE ON ${table} BEGIN SELECT RAISE(ABORT, 'metadata update'); END`) + } + const empty = await logs.stat(id) + await handle.append([event(0), event(1)]) + const first = await logs.stat(id) + expect(first?.eventCount).toBe(2) + expect(first?.revision).not.toBe(empty?.revision) + await handle.close() + await logs.close() + const reopened = sqliteLogs(path, root) + try { + expect(await reopened.stat(id)).toEqual(first) + await using writer = await reopened.open(id, 'write') + await writer.append([event(2)]) + expect((await writer.read()).events.map(item => item.seq)).toEqual([0, 1, 2]) + expect((await reopened.stat(id))?.eventCount).toBe(3) + const plan = db.prepare('EXPLAIN QUERY PLAN SELECT seq FROM events WHERE segment_uuid = ? ORDER BY seq DESC LIMIT 1').all('unused') + expect(plan.map(row => row.detail).join(' ')).toContain('SEARCH events USING PRIMARY KEY') + } finally { await reopened.close() } + } finally { db.close() } +}) + +it('stores logical JSON events and reads their source coordinates from an indexed suffix', async () => { + const { root, logs, path, header, event } = await fixture() + const ranged = { ...event(4), sourceEventSeqs: [SessionSeq(0), SessionSeq(1), SessionSeq(2)] } + const batch = [event(0), event(1), event(2), event(3), ranged] + const writer = await logs.create(header) + await writer.append(batch) + await writer.close() + await logs.close() + const db = new DatabaseSync(path) + try { + const row = z.object({ payload: z.string() }).parse(db.prepare('SELECT payload FROM events WHERE seq = 4').get()) + const physical = z.object({ sourceEventSeqs: z.unknown() }).loose().parse(JSON.parse(row.payload)) + expect(physical).toEqual(ranged) + expect(physical.sourceEventSeqs).toEqual([0, 1, 2]) + const stored = z.object({ header: z.string() }).parse(db.prepare('SELECT header FROM traces').get()) + expect(JSON.parse(stored.header)).toEqual({ ...header, delegationDepth: 0 }) + } finally { db.close() } + const reopened = sqliteLogs(path, root) + try { + await using reader = await reopened.open(header.id, 'read') + expect((await reader.read(4, 1)).events).toEqual([ranged]) + expect((await reader.read()).events).toEqual(batch) + } finally { await reopened.close() } +}) + +it('reads an empty inherited prefix from its independent child Segment', async () => { + const { logs, id, header } = await fixture() + const writer = await logs.create(header) + await writer.flush() + await sharedHistory(logs, id, SessionId('empty-child'), []) + const child = await logs.open(SessionId('empty-child'), 'read') + try { expect((await child.read()).events).toMatchObject([{ type: 'session/end-seed', seq: 0 }]) } + finally { await child.close(); await writer.close() } +}) + +it('reads long histories across decoding yields and restores headers without an explicit delegation depth', async () => { + const { logs, header, event } = await fixture() + const events = Array.from({ length: 2050 }, (_, seq) => event(seq)) + const writer = await logs.create(header) + await writer.append(events) + expect(await logs.read(header, 0, events.length)).toEqual(events) + await writer.close() +}) diff --git a/packages/session/session-persistence-sqlite/tests/unknown-outcome.spec.ts b/packages/session/session-persistence-sqlite/tests/unknown-outcome.spec.ts new file mode 100644 index 0000000000..e6d9885363 --- /dev/null +++ b/packages/session/session-persistence-sqlite/tests/unknown-outcome.spec.ts @@ -0,0 +1,133 @@ +/** Provider-wide SQLite transaction failures across cached handles and durability barriers. @module */ +import { LiveWriteBuffer } from '../src/buffer.ts' +import { DatabaseSync } from 'node:sqlite' +import { Context } from '@deepseek-ai/cordis' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it, onTestFinished, vi } from 'vitest' +import { SESSION_FORMAT_VERSION, SessionId, SessionSeq, SessionStore } from '@deepseek-ai/dsh-session' +import type { SessionHeader } from '@deepseek-ai/dsh-session' +import * as persistence from '../src/index.ts' +import { SqliteSessionHandle } from '../src/sqlite.ts' +import { sqliteLogs } from './fixtures/store.ts' +import { SessionWriteLease } from '../src/lease.ts' +import { sessionDir } from '../src/paths.ts' + +it.each(['commit', 'rollback'] as const)('isolates every SQLite handle after an unknown %s result and still releases them', async (operation) => { + const root = await mkdtemp(join(tmpdir(), 'dsh-segment-unknown-')) + const ctx = new Context() + onTestFinished(async () => { try { await ctx.fiber.dispose() } finally { await rm(root, { recursive: true, force: true }) } }) + await ctx.plugin(SessionStore) + await ctx.plugin(persistence, { root, compression: 'none' }) + const session = ctx.sessions.create(SessionId('unknown')) + const source = await ctx.sessionPersistence.create(session.header) + await source.flush() + const cached = ctx.sessions.create(SessionId('cached')) + const first = await ctx.sessionPersistence.create(cached.header) + cached.append('turn/start', { turn: 1 }) + await ctx.sessions.flush(cached) + await first.close() + const primed = await ctx.sessionPersistence.open(cached.id, 'write') + if (!(primed instanceof SqliteSessionHandle)) throw new Error('Expected a SQLite handle') + const pendingId = SessionId('pending') + const pending = await ctx.sessionPersistence.create({ version: SESSION_FORMAT_VERSION, id: pendingId, createdAt: 0, isSeeded: false }) + const pendingReader = await ctx.sessionPersistence.open(pendingId, 'read') + if (operation === 'rollback') { + const db = new DatabaseSync(join(root, '.segments', 'sessions.sqlite')) + try { db.exec("CREATE TRIGGER refuse_append BEFORE INSERT ON events BEGIN SELECT RAISE(ABORT, 'append refused'); END") } + finally { db.close() } + } + // oxlint-disable-next-line typescript/unbound-method -- Called with the intercepted database as receiver below. + const exec = DatabaseSync.prototype.exec + const fault = vi.spyOn(DatabaseSync.prototype, 'exec').mockImplementation(function (this: DatabaseSync, sql) { + if (sql === operation.toUpperCase()) throw new Error(`${operation} result unavailable`) + exec.call(this, sql) + }) + const event = { type: 'turn/start' as const, seq: SessionSeq(0), time: 0, data: { turn: 1 } } + let failure: unknown + try { failure = await source.append([event]).then(() => undefined, (error: unknown) => error) } + finally { fault.mockRestore() } + expect(failure).toMatchObject({ code: 'SESSION_STORAGE_UNKNOWN' }) + await expect(source.append([])).rejects.toBe(failure) + await expect(primed.read()).rejects.toBe(failure) + await expect(pendingReader.read()).rejects.toBe(failure) + await expect(primed.receive({ type: 'turn/end', seq: SessionSeq(1), time: 0, data: { turn: 1, reason: { kind: 'completed' } } })).rejects.toBe(failure) + await expect(source.flush()).rejects.toBe(failure) + await expect(ctx.sessions.flush(session)).rejects.toBe(failure) + await expect(ctx.sessionPersistence.flush()).rejects.toBe(failure) + const error = vi.spyOn(ctx.logger, 'error').mockImplementation(() => {}) + try { + cached.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) + await vi.waitFor(() => { expect(error).toHaveBeenCalledOnce() }) + expect(String(error.mock.calls[0]?.[0])).toContain('SQLite transaction outcome is unknown') + const buffer: unknown = Reflect.get(primed, 'buffer') + if (!(buffer instanceof LiveWriteBuffer)) throw new Error('Missing live buffer') + expect(buffer.length).toBe(0) + } finally { error.mockRestore() } + await source.close(); await primed.close(); await pendingReader.close(); await pending.close() + await expect(ctx.sessionPersistence.flush()).rejects.toBe(failure) +}) + +it('rejects a created writer whose first lease completes after another Session makes the store unusable', async () => { + const root = await mkdtemp(join(tmpdir(), 'dsh-segment-lease-unknown-')) + const entered = Promise.withResolvers(), release = Promise.withResolvers() + const logs = sqliteLogs(join(root, 'sessions.sqlite'), root, { acquireCreationLease: async (header) => { + if (header.id === SessionId('waiting')) { entered.resolve(undefined); await release.promise } + return SessionWriteLease.acquire(sessionDir(root, header.cwd, header.id), header.id) + } }) + onTestFinished(async () => { + release.resolve(undefined) + try { await logs.close() } finally { await rm(root, { recursive: true, force: true }) } + }) + const header = (id: string): SessionHeader => ({ version: SESSION_FORMAT_VERSION, id: SessionId(id), createdAt: 0, isSeeded: false }) + const first = await logs.create(header('first')), waiting = await logs.create(header('waiting')) + await first.flush() + const event = { type: 'turn/start' as const, seq: SessionSeq(0), time: 0, data: { turn: 1 } } + const blocked = waiting.append([event]).then(() => undefined, (error: unknown) => error) + await entered.promise + // oxlint-disable-next-line typescript/unbound-method -- Called with the intercepted database as receiver below. + const exec = DatabaseSync.prototype.exec + const fault = vi.spyOn(DatabaseSync.prototype, 'exec').mockImplementation(function (this: DatabaseSync, sql) { + if (sql === 'COMMIT') throw new Error('commit result unavailable') + exec.call(this, sql) + }) + let failure: unknown + try { failure = await first.append([event]).then(() => undefined, (error: unknown) => error) } + finally { fault.mockRestore(); release.resolve(undefined) } + expect(failure).toMatchObject({ code: 'SESSION_STORAGE_UNKNOWN' }) + expect(await blocked).toBe(failure) + await first.close(); await waiting.close() + const lease = await SessionWriteLease.acquire(sessionDir(root, undefined, waiting.id), waiting.id) + await lease.release() +}) + +it('refuses a queued second Session before its transaction begins and rejects flush after all writers close', async () => { + const root = await mkdtemp(join(tmpdir(), 'dsh-segment-queued-unknown-')) + const path = join(root, 'sessions.sqlite'), logs = sqliteLogs(path, root) + onTestFinished(async () => { try { await logs.close() } finally { await rm(root, { recursive: true, force: true }) } }) + const header = (id: string): SessionHeader => ({ version: SESSION_FORMAT_VERSION, id: SessionId(id), createdAt: 0, isSeeded: false }) + const first = await logs.create(header('first')), second = await logs.create(header('second')) + await first.flush(); await second.flush() + // oxlint-disable-next-line typescript/unbound-method -- Called with the intercepted database as receiver below. + const exec = DatabaseSync.prototype.exec + let failed = false, laterTransactions = 0 + const fault = vi.spyOn(DatabaseSync.prototype, 'exec').mockImplementation(function (this: DatabaseSync, sql) { + if (failed && sql.startsWith('BEGIN ')) laterTransactions++ + if (sql === 'COMMIT' && !failed) { failed = true; throw new Error('commit result unavailable') } + exec.call(this, sql) + }) + const event = { type: 'turn/start' as const, seq: SessionSeq(0), time: 0, data: { turn: 1 } } + let one: unknown, two: unknown + try { + const writes = [first.append([event]), second.append([event])] + ;[one, two] = await Promise.all(writes.map(async writing => writing.then(() => undefined, (error: unknown) => error))) + } finally { fault.mockRestore() } + expect(one).toMatchObject({ code: 'SESSION_STORAGE_UNKNOWN' }) + expect(two).toBe(one) + expect(laterTransactions).toBe(0) + const db = new DatabaseSync(path) + try { expect(db.prepare('SELECT payload FROM events').all()).toEqual([]) } finally { db.close() } + await first.close(); await second.close() + await expect(logs.flush()).rejects.toBe(one) +}) diff --git a/packages/session/session-persistence-sqlite/tests/win32.spec.ts b/packages/session/session-persistence-sqlite/tests/win32.spec.ts new file mode 100644 index 0000000000..aa78cd6d49 --- /dev/null +++ b/packages/session/session-persistence-sqlite/tests/win32.spec.ts @@ -0,0 +1,288 @@ +/** + * Unit tests for the Windows durable namespace helper with a mocked kernel32 + * binding. The real JSONL suite exercises the helper on native Windows; these + * tests keep the Win32 error mapping and race handling covered on every host. + */ + +import { afterEach, describe, expect, it, vi } from 'vitest' +import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs' +import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +const MOVEFILE_WRITE_THROUGH = 0x00000008 +const ERROR_FILE_NOT_FOUND = 2 +const ERROR_PATH_NOT_FOUND = 3 +const ERROR_ACCESS_DENIED = 5 +const ERROR_NOT_SAME_DEVICE = 17 +const ERROR_FILE_EXISTS = 80 +const ERROR_INVALID_NAME = 123 +const ERROR_ALREADY_EXISTS = 183 + +type MoveFileExW = (existing: string, replacement: string, flags: number, setLastError: (code: number) => void) => number + +const roots: string[] = [] + +function stripNamespace(path: string): string { + if (path.startsWith('\\\\?\\UNC\\')) return `\\\\${path.slice('\\\\?\\UNC\\'.length)}` + if (path.startsWith('\\\\?\\')) return path.slice('\\\\?\\'.length) + return path +} + +async function tempRoot(): Promise { + const dir = await mkdtemp(join(tmpdir(), 'dsh-jsonl-win32-')) + roots.push(dir) + return dir +} + +async function importWithMove(moveFileExW: MoveFileExW): Promise { + vi.resetModules() + vi.doMock('koffi', () => { + let lastError = 0 + const setLastError = (code: number): void => { lastError = code } + const move: MoveFileExW = (existing, replacement, flags, setError) => { + const ok = moveFileExW(existing, replacement, flags, setError) + lastError = ok === 0 ? lastError : 0 + return ok + } + return { + default: { + load: () => ({ + func: (_convention: string, name: string, result: string) => { + if (name === 'MoveFileExW') return (existing: string, replacement: string, flags: number) => { + expect(result).toBe('int') + const ok = move(existing, replacement, flags, setLastError) + return ok + } + return () => lastError + }, + }), + }, + } + }) + return import('../src/win32.ts') +} + +async function importWithError(code: number): Promise { + vi.resetModules() + vi.doMock('koffi', () => ({ + default: { + load: () => ({ + func: (_convention: string, name: string) => { + if (name === 'MoveFileExW') return () => 0 + return () => code + }, + }), + }, + })) + return import('../src/win32.ts') +} + +async function importWithFilesystemMove(): Promise { + return importWithMove((existing, replacement, flags, setLastError) => { + expect(flags).toBe(MOVEFILE_WRITE_THROUGH) + const from = stripNamespace(existing) + const to = stripNamespace(replacement) + if (!existsSync(from)) { setLastError(ERROR_FILE_NOT_FOUND); return 0 } + if (existsSync(to)) { setLastError(ERROR_ALREADY_EXISTS); return 0 } + renameSync(from, to) + return 1 + }) +} + +afterEach(async () => { + vi.doUnmock('koffi') + vi.doUnmock('node:fs/promises') + vi.doUnmock('node:path') + vi.resetModules() + for (const root of roots.splice(0)) await rm(root, { recursive: true, force: true }) +}) + +describe('Windows durable namespace helpers', () => { + it('keeps drive-root probes native while namespacing descendants', async () => { + const probes: string[] = [] + vi.resetModules() + vi.doMock('node:fs/promises', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + stat: async (path: string) => { + probes.push(path) + return { isDirectory: () => true } + }, + } + }) + vi.doMock('node:path', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + join: (...paths: string[]) => actual.win32.join(...paths), + parse: (path: string) => actual.win32.parse(path), + resolve: (...paths: string[]) => actual.win32.resolve(...paths), + toNamespacedPath: (path: string) => actual.win32.toNamespacedPath(path), + } + }) + const { ensureDurableDirectoryWin32 } = await import('../src/win32.ts') + + await ensureDurableDirectoryWin32('C:\\existing') + + expect(probes).toEqual(['C:\\', '\\\\?\\C:\\existing']) + }) + + it('publishes a new file with write-through MoveFileExW semantics', async () => { + const { publishNewFileWin32 } = await importWithFilesystemMove() + const root = await tempRoot() + const tmp = join(root, 'log.tmp') + const final = join(root, 'log.jsonl') + await writeFile(tmp, 'content') + + await publishNewFileWin32(tmp, final) + expect(existsSync(tmp)).toBe(false) + expect(readFileSync(final, 'utf8')).toBe('content') + }) + + it('maps Win32 publish failures to Node-style errno codes', async () => { + const cases = [ + [ERROR_FILE_NOT_FOUND, 'ENOENT'], + [ERROR_PATH_NOT_FOUND, 'ENOENT'], + [ERROR_ACCESS_DENIED, 'EACCES'], + [ERROR_NOT_SAME_DEVICE, 'EXDEV'], + [ERROR_FILE_EXISTS, 'EEXIST'], + [ERROR_ALREADY_EXISTS, 'EEXIST'], + [ERROR_INVALID_NAME, 'EINVAL'], + [9999, 'EIO'], + ] as const + for (const [win32Code, code] of cases) { + const { publishNewFileWin32 } = await importWithError(win32Code) + await expect(publishNewFileWin32('from', 'to')).rejects.toMatchObject({ code, win32Code, path: 'from', dest: 'to' }) + } + }) + + it('creates missing directories through staging siblings and tolerates an already-created race', async () => { + const root = await tempRoot() + const raced = join(root, 'raced') + const { ensureDurableDirectoryWin32 } = await importWithMove((existing, replacement, flags, setLastError) => { + expect(flags).toBe(MOVEFILE_WRITE_THROUGH) + const from = stripNamespace(existing) + const to = stripNamespace(replacement) + if (to === raced) { + mkdirSync(to) + setLastError(ERROR_ALREADY_EXISTS) + return 0 + } + if (!existsSync(from)) { setLastError(ERROR_FILE_NOT_FOUND); return 0 } + if (existsSync(to)) { setLastError(ERROR_ALREADY_EXISTS); return 0 } + renameSync(from, to) + return 1 + }) + + await ensureDurableDirectoryWin32(join(root, 'a', 'b')) + expect(existsSync(join(root, 'a', 'b'))).toBe(true) + await ensureDurableDirectoryWin32(join(root, 'a', 'b')) + await ensureDurableDirectoryWin32(raced) + expect(existsSync(raced)).toBe(true) + }) + + it('keeps staging names valid for a maximum-length target component', async () => { + const { ensureDurableDirectoryWin32 } = await importWithFilesystemMove() + const root = await tempRoot() + const target = join(root, 'x'.repeat(255)) + + await ensureDurableDirectoryWin32(target) + expect(existsSync(target)).toBe(true) + }) + + it('surfaces directory publication failures other than an existing-target race', async () => { + const { ensureDurableDirectoryWin32 } = await importWithError(ERROR_ACCESS_DENIED) + const root = await tempRoot() + + await expect(ensureDurableDirectoryWin32(join(root, 'denied'))).rejects.toMatchObject({ code: 'EACCES' }) + }) + + it('rejects a non-directory component instead of treating it as missing', async () => { + const { ensureDurableDirectoryWin32 } = await importWithFilesystemMove() + const root = await tempRoot() + const blocked = join(root, 'blocked') + writeFileSync(blocked, 'x') + + await expect(ensureDurableDirectoryWin32(join(blocked, 'child'))).rejects.toMatchObject({ code: 'ENOTDIR' }) + }) +}) + +async function importWithLock(bindings: { + createSemaphoreW?: (name: string, initial: number, maximum: number) => number + waitResult?: number + releaseSemaphore?: (handle: number) => number + closeHandle?: (handle: number) => number + lastError?: number +}): Promise { + vi.resetModules() + vi.doMock('koffi', () => ({ + default: { + load: () => ({ + func: (_convention: string, name: string) => { + if (name === 'CreateSemaphoreW') { + return (_security: null, initial: number, maximum: number, semName: string) => + (bindings.createSemaphoreW ?? (() => 7))(semName, initial, maximum) + } + if (name === 'WaitForSingleObject') return () => bindings.waitResult ?? 0 + if (name === 'ReleaseSemaphore') return bindings.releaseSemaphore ?? (() => 1) + if (name === 'CloseHandle') return bindings.closeHandle ?? (() => 1) + if (name === 'MoveFileExW') return () => 1 + return () => bindings.lastError ?? 0 // GetLastError + }, + }), + }, + })) + return import('../src/win32.ts') +} + +describe('Windows write-lock semaphore', () => { + it('acquires a path-derived named semaphore with a zero-timeout wait', async () => { + const created: Array<{ name: string; initial: number; maximum: number }> = [] + const { acquireLockHandleWin32 } = await importWithLock({ + createSemaphoreW: (name, initial, maximum) => { + created.push({ name, initial, maximum }) + return 7 + }, + }) + await expect(acquireLockHandleWin32('C:\\s\\session.lock')).resolves.toBe(7) + expect(created).toHaveLength(1) + // Count-1 semaphore in the login-session namespace, named by path hash: + // no filesystem footprint, and case-insensitive like Windows paths. + expect(created[0]).toMatchObject({ initial: 1, maximum: 1 }) + expect(created[0]?.name).toMatch(/^Local\\dsh-session-lock-[0-9a-f]{64}$/) + const upper = await importWithLock({ createSemaphoreW: (name) => { created.push({ name, initial: 1, maximum: 1 }); return 7 } }) + await upper.acquireLockHandleWin32('C:\\S\\SESSION.LOCK') + expect(created[1]?.name).toBe(created[0]?.name) + }) + + it('maps a held semaphore (wait timeout) to EBUSY and closes the probe handle', async () => { + const closed: number[] = [] + const { acquireLockHandleWin32 } = await importWithLock({ + waitResult: 0x102, + closeHandle: (handle) => { closed.push(handle); return 1 }, + }) + await expect(acquireLockHandleWin32('C:\\s\\session.lock')).rejects.toMatchObject({ code: 'EBUSY' }) + expect(closed).toEqual([7]) + }) + + it('surfaces create and wait failures with Win32 codes', async () => { + const createFailed = await importWithLock({ createSemaphoreW: () => 0, lastError: 5 }) + await expect(createFailed.acquireLockHandleWin32('C:\\s\\session.lock')).rejects.toMatchObject({ code: 'EACCES', win32Code: 5 }) + const waitFailed = await importWithLock({ waitResult: 0xffffffff, lastError: 5 }) + await expect(waitFailed.acquireLockHandleWin32('C:\\s\\session.lock')).rejects.toMatchObject({ code: 'EACCES', win32Code: 5 }) + }) + + it('releases by restoring the count and closing, surfacing a failed release', async () => { + const order: string[] = [] + const working = await importWithLock({ + releaseSemaphore: (handle) => { order.push(`release:${handle}`); return 1 }, + closeHandle: (handle) => { order.push(`close:${handle}`); return 1 }, + }) + await working.releaseLockHandleWin32(7) + expect(order).toEqual(['release:7', 'close:7']) + const failing = await importWithLock({ releaseSemaphore: () => 0, lastError: 5 }) + await expect(failing.releaseLockHandleWin32(9)).rejects.toMatchObject({ code: 'EACCES', win32Code: 5 }) + }) +}) diff --git a/packages/session/session-persistence-sqlite/tests/write-deadline.spec.ts b/packages/session/session-persistence-sqlite/tests/write-deadline.spec.ts new file mode 100644 index 0000000000..a36398297c --- /dev/null +++ b/packages/session/session-persistence-sqlite/tests/write-deadline.spec.ts @@ -0,0 +1,134 @@ +/** Follow-up batching deadlines while a preceding write remains in flight. @module */ +import { mkdtemp, rm } from 'node:fs/promises' +import { join } from 'node:path' +import { tmpdir } from 'node:os' +import { expect, it, onTestFinished, vi } from 'vitest' +import { Context } from '@deepseek-ai/cordis' +import { SESSION_FORMAT_VERSION, SessionId, SessionSeq, SessionStore } from '@deepseek-ai/dsh-session' +import type { SessionEvent } from '@deepseek-ai/dsh-session' +import { sqliteLogs } from './fixtures/store.ts' +import * as persistence from '../src/index.ts' +import { SqliteStore, SqliteSessionHandle } from '../src/sqlite.ts' + +const event = (seq: number): SessionEvent => seq % 2 === 0 + ? { type: 'turn/start', seq: SessionSeq(seq), time: 0, data: { turn: seq / 2 + 1 } } + : { type: 'turn/end', seq: SessionSeq(seq), time: 0, data: { turn: (seq + 1) / 2, reason: { kind: 'completed' } } } + +it.each([false, true])('schedules a threshold batch during drain settlement, failure=%s', async (fail) => { + const root = await mkdtemp(join(tmpdir(), 'dsh-session-drain-settlement-')) + const reported = Promise.withResolvers() + const logs = sqliteLogs(join(root, 'sessions.sqlite'), root, { + report: (_id, error) => { reported.resolve(error) }, + }) + onTestFinished(async () => { try { await logs.close() } finally { await rm(root, { recursive: true, force: true }) } }) + const writer = await logs.create({ version: SESSION_FORMAT_VERSION, id: SessionId('settlement'), createdAt: 0, isSeeded: false }) + const entered = Promise.withResolvers(), release = Promise.withResolvers() + const stored = Promise.withResolvers(), failure = new Error('follow-up rejected') + const append = logs.append.bind(logs) + let refused = false + const spy = vi.spyOn(logs, 'append').mockImplementation(async (...args) => { + if (args[1][0]?.seq === 0) { entered.resolve(undefined); await release.promise } + if (args[1][0]?.seq === 256 && fail && !refused) { refused = true; throw failure } + await append(...args) + if (args[1][0]?.seq === 256) stored.resolve(undefined) + }) + onTestFinished(() => { release.resolve(undefined); spy.mockRestore() }) + for (let seq = 0; seq < 256; seq++) await writer.receive(event(seq)) + await entered.promise + // This queue barrier places admission after the drain's last batch, before its completion handler. + const pending: unknown = Reflect.get(writer, 'pending') + if (!(pending instanceof Promise)) throw new Error('Missing write queue barrier') + const admission = pending.then(() => Promise.all( + Array.from({ length: 256 }, (_, seq) => writer.receive(event(seq + 256))), + )) + release.resolve(undefined) + await writer.drainLive() + await admission + expect(spy).toHaveBeenCalledTimes(2) + if (fail) { + expect(await reported.promise).toBe(failure) + await writer.flush() + } + await stored.promise + await writer.close() + const reader = await logs.open(writer.id, 'read') + try { expect((await reader.read()).events.map(event => event.seq)).toEqual(Array.from({ length: 512 }, (_, seq) => seq)) } + finally { await reader.close() } +}) + +it('starts a follow-up write once its own batching deadline elapsed during the preceding commit', async () => { + const root = await mkdtemp(join(tmpdir(), 'dsh-sqlite-deadline-')) + const logs = sqliteLogs(join(root, 'sessions.sqlite'), root) + const writer = await logs.create({ version: SESSION_FORMAT_VERSION, id: SessionId('deadline'), createdAt: 0, isSeeded: false }) + await writer.flush() + const entered = Promise.withResolvers(), release = Promise.withResolvers() + const append = logs.append.bind(logs) + const writes = vi.spyOn(logs, 'append').mockImplementationOnce(async (...args) => { + entered.resolve(undefined) + await release.promise + await append(...args) + }) + vi.useFakeTimers() + try { + await writer.receive(event(0)); await writer.receive(event(1)) + await vi.advanceTimersByTimeAsync(200) + await entered.promise + await writer.receive(event(2)) + // The follow-up deadline expires while the first commit remains owned by the barrier. + await vi.advanceTimersByTimeAsync(400) + expect(writes).toHaveBeenCalledTimes(1) + release.resolve(undefined) + await writer.drainLive() + await vi.advanceTimersByTimeAsync(0) + expect(writes).toHaveBeenCalledTimes(2) + } finally { + release.resolve(undefined) + try { await writer.close() } + finally { + writes.mockRestore() + vi.useRealTimers() + try { await logs.close() } + finally { await rm(root, { recursive: true, force: true }) } + } + } +}) + +it('retains the published settlement event under an immediate-close interleaving', async () => { + const root = await mkdtemp(join(tmpdir(), 'dsh-session-close-settlement-')) + const ctx = new Context() + onTestFinished(async () => { try { await ctx.fiber.dispose() } finally { await rm(root, { recursive: true, force: true }) } }) + await ctx.plugin(SessionStore) + await ctx.plugin(persistence, { root, compression: 'none' }) + const session = ctx.sessions.create(SessionId('settlement-parity')) + const writer = await ctx.sessionPersistence.create(session.header) + if (!(writer instanceof SqliteSessionHandle)) throw new Error('Missing provider handle') + const entered = Promise.withResolvers(), release = Promise.withResolvers() + let restore: () => void + { + // oxlint-disable-next-line typescript/unbound-method -- Called with the intercepted store as receiver below. + const original = SqliteStore.prototype.append + const spy = vi.spyOn(SqliteStore.prototype, 'append').mockImplementationOnce(async function (this: SqliteStore, ...args) { + entered.resolve(undefined) + await release.promise + await original.call(this, ...args) + }) + restore = () => { spy.mockRestore() } + } + onTestFinished(() => { release.resolve(undefined); restore() }) + session.append('turn/start', { turn: 1 }) + const draining = writer.drainLive() + await entered.promise + const pending: unknown = Reflect.get(writer, 'pending') + if (!(pending instanceof Promise)) throw new Error('Missing current provider queue barrier') + const closing = pending.then(() => { + session.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) + return writer.close() + }) + release.resolve(undefined) + await draining + await closing + restore() + const reader = await ctx.sessionPersistence.open(session.id, 'read') + try { expect((await reader.read()).events.map(item => item.type)).toEqual(['turn/start', 'turn/end']) } + finally { await reader.close() } +}) diff --git a/packages/session/session-persistence-sqlite/tests/write-recovery.spec.ts b/packages/session/session-persistence-sqlite/tests/write-recovery.spec.ts new file mode 100644 index 0000000000..63ae9a43fd --- /dev/null +++ b/packages/session/session-persistence-sqlite/tests/write-recovery.spec.ts @@ -0,0 +1,79 @@ +/** First-write lease failures and cancellation through published Session events. @module */ +import { Context } from '@deepseek-ai/cordis' +import { mkdtemp, rm, stat } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it, onTestFinished, vi } from 'vitest' +import { SessionId, SessionStore } from '@deepseek-ai/dsh-session' +import * as plugin from '../src/index.ts' +import { SessionWriteLease } from '../src/lease.ts' +import { sessionDir } from '../../session-persistence-jsonl/src/format.ts' + +async function fixture() { + const root = await mkdtemp(join(tmpdir(), 'dsh-session-write-recovery-')) + const ctx = new Context() + onTestFinished(async () => { + try { await ctx.fiber.dispose() } + finally { await rm(root, { recursive: true, force: true }) } + }) + await ctx.plugin(SessionStore) + await ctx.plugin(plugin, { root, compression: 'none' }) + return { ctx, root } +} + +it('persists live events arriving while close drains an earlier batch', async () => { + const { ctx } = await fixture() + const session = ctx.sessions.create(SessionId('close-live-events')) + const writer = await ctx.sessionPersistence.create(session.header) + const entered = Promise.withResolvers(), release = Promise.withResolvers() + const acquire = SessionWriteLease.acquire.bind(SessionWriteLease) + const spy = vi.spyOn(SessionWriteLease, 'acquire').mockImplementationOnce(async (dir, id) => { + entered.resolve(undefined) + await release.promise + return acquire(dir, id) + }) + onTestFinished(() => { release.resolve(undefined); spy.mockRestore() }) + session.append('turn/start', { turn: 1 }) + const closing = writer.close() + try { + await entered.promise + session.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) + } finally { release.resolve(undefined) } + await closing + await using reader = await ctx.sessionPersistence.open(session.id, 'read') + expect((await reader.read()).events.map(event => event.seq)).toEqual([0, 1]) +}) + +it('retains a published event when its first lease fails', async () => { + const { ctx } = await fixture() + const reported = Promise.withResolvers() + const error = vi.spyOn(ctx.logger, 'error').mockImplementation(() => { reported.resolve(undefined) }) + const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => { reported.resolve(undefined) }) + const acquire = vi.spyOn(SessionWriteLease, 'acquire') + .mockRejectedValueOnce(Object.assign(new Error('lease temporarily unavailable'), { code: 'EACCES' })) + onTestFinished(() => { acquire.mockRestore(); error.mockRestore(); warn.mockRestore() }) + const session = ctx.sessions.create(SessionId('lease-retry')) + const writer = await ctx.sessionPersistence.create(session.header) + session.append('turn/start', { turn: 1 }) + await reported.promise + expect(acquire).toHaveBeenCalledOnce() + await expect(ctx.sessions.flush(session)).resolves.toBe(true) + await writer.close() + const reader = await ctx.sessionPersistence.open(session.id, 'read') + try { expect((await reader.read()).events.map(event => event.seq)).toEqual([0]) } + finally { await reader.close() } +}) + +it('does not acquire a first lease for a pre-cancelled flush', async () => { + const { ctx, root } = await fixture() + const session = ctx.sessions.create(SessionId('cancelled-flush')) + const writer = await ctx.sessionPersistence.create(session.header) + const controller = new AbortController(), reason = new Error('cancel before checkpoint') + controller.abort(reason) + const acquire = vi.spyOn(SessionWriteLease, 'acquire') + try { + await expect(writer.flush({ signal: controller.signal })).rejects.toBe(reason) + expect(acquire).not.toHaveBeenCalled() + await expect(stat(sessionDir(root, undefined, session.id))).rejects.toMatchObject({ code: 'ENOENT' }) + } finally { acquire.mockRestore(); await writer.close() } +}) diff --git a/packages/session/session-persistence-sqlite/tsconfig.json b/packages/session/session-persistence-sqlite/tsconfig.json new file mode 100644 index 0000000000..6993b9b684 --- /dev/null +++ b/packages/session/session-persistence-sqlite/tsconfig.json @@ -0,0 +1,42 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../session-persistence-jsonl" + }, + { + "path": "../../../vendor/cosmokit" + }, + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../llm/llm" + }, + { + "path": "../../core/session" + }, + { + "path": "../session-persistence" + }, + { + "path": "../session-format" + }, + { + "path": "../session-format-v3-to-v4" + }, + { + "path": "../../util/brand" + }, + { + "path": "../../../native/system/packages/entry" + } + ] +} diff --git a/packages/session/session-persistence/README.i18n.yaml b/packages/session/session-persistence/README.i18n.yaml index bd02807cf7..9295470b9e 100644 --- a/packages/session/session-persistence/README.i18n.yaml +++ b/packages/session/session-persistence/README.i18n.yaml @@ -18,8 +18,8 @@ en: bd48e96d14122170 zh: f8a06e7246b55a6f /deepseek-ai-dsh-session-persistence/use-this-package/choosing-a-backend: - en: 170892270261aae0 - zh: 7daf1edd4f764409 + en: 5d6697e1514600a8 + zh: b17602b37282166b /deepseek-ai-dsh-session-persistence/use-this-package/what-the-service-provides: en: c10b9c7d9bad305c zh: 0e9c391e9df37da6 diff --git a/packages/session/session-persistence/README.md b/packages/session/session-persistence/README.md index 9e9446b81b..1faad48ef4 100644 --- a/packages/session/session-persistence/README.md +++ b/packages/session/session-persistence/README.md @@ -29,7 +29,7 @@ Mount one persistence backend to make sessions durable. The backend registers it ### Choosing a backend -The seam ships the [JSONL](../session-persistence-jsonl/README.md) backend: one append-only `.jsonl.zstd` log per session. A third-party backend may implement the service directly; the [backend contract](#understand-the-implementation) below is what it must honor. +Shipped profiles use the [JSONL](../session-persistence-jsonl/README.md) backend: one append-only `.jsonl.zstd` log per session. The separate [SQLite provider](../session-persistence-sqlite/README.md) saves logical events in a database and imports existing JSONL histories on first open. Both providers expose the same service and handle methods. A third-party backend may implement the service directly; the [backend contract](#understand-the-implementation) below is what it must honor. ### What the service provides diff --git a/packages/session/session-persistence/README.zh.md b/packages/session/session-persistence/README.zh.md index cc1f2edb82..1f59283ae1 100644 --- a/packages/session/session-persistence/README.zh.md +++ b/packages/session/session-persistence/README.zh.md @@ -29,7 +29,7 @@ kind: "package-reference" ### 选择后端 -seam 随产品交付 [JSONL](../session-persistence-jsonl/README.zh.md) 后端。它为每个会话存储一份仅追加的 `.jsonl.zstd` 日志。第三方后端可以直接实现该服务;必须遵守的[后端约定](#understand-the-implementation)见下文。 +内置 profile 使用 [JSONL](../session-persistence-jsonl/README.zh.md) 后端,为每个会话存储一份仅追加的 `.jsonl.zstd` 日志。独立的 [SQLite 提供者](../session-persistence-sqlite/README.zh.md) 在数据库中保存逻辑事件,并在首次打开时导入现有 JSONL 历史。两个提供者暴露相同的服务和句柄方法。第三方后端可以直接实现该服务;必须遵守的[后端约定](#understand-the-implementation)见下文。 ### 服务提供什么 diff --git a/packages/session/session-persistence/src/index.ts b/packages/session/session-persistence/src/index.ts index 951c60b31f..a69131260b 100644 --- a/packages/session/session-persistence/src/index.ts +++ b/packages/session/session-persistence/src/index.ts @@ -161,8 +161,10 @@ export abstract class SessionPersistence extends Service { /** * 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`. diff --git a/packages/skill/skill-office/tests/converted-pdf.spec.ts b/packages/skill/skill-office/tests/converted-pdf.spec.ts new file mode 100644 index 0000000000..c1611b1c54 --- /dev/null +++ b/packages/skill/skill-office/tests/converted-pdf.spec.ts @@ -0,0 +1,32 @@ +/** The temporary file and byte count a PDF conversion reports, which the real Office export lane asserts. */ +import { brandString } from '@deepseek-ai/dsh-brand' +import { createToolResultMessage, type ToolCallId } from '@deepseek-ai/dsh-llm' +import { Session, type SessionId, type SessionEvent } from '@deepseek-ai/dsh-session' +import { expect, it } from 'vitest' +import { convertedPdfFiles } from './fixtures/real-office.ts' + +const temporary = '/h/.dsh/office-kit/outputs/session-0123456789abcdef01234567/2f0f8c3e-7d1b-4c1e-9b0a-0d5e6f7a8b9c/input.pdf' + +/** Record native tool results carrying one text block each. */ +function results(texts: readonly string[], isError = false): readonly SessionEvent[] { + const session = Session.create(brandString('converted-pdf')) + for (const text of texts) { + session.append('tool/result', { turn: 1, step: 1, + message: createToolResultMessage({ callId: brandString('convert'), content: [{ type: 'text', text }], isError }), + }, { surfaceOp: 'append' }) + } + return session.snapshotEvents() +} + +it('collects the temporary file and byte count a PDF conversion reports', () => { + expect(convertedPdfFiles(results([`Converted input.docx to pdf (2048 bytes): ${temporary}\nCopy this temporary file to its destination with the shell now.`]))) + .toEqual([{ bytes: 2048, file: temporary }]) + expect(convertedPdfFiles(results([`Converted input.docx to pdf (4096 bytes, 3 pages): ${temporary}`]))) + .toEqual([{ bytes: 4096, file: temporary }]) +}) + +it('ignores failed results, other formats, and render summaries', () => { + expect(convertedPdfFiles(results([`Converted input.docx to pdf (2048 bytes): ${temporary}`], true))).toEqual([]) + expect(convertedPdfFiles(results(['Converted input.docx to docx (1024 bytes): /h/outputs/input.docx']))).toEqual([]) + expect(convertedPdfFiles(results(['Rendered 2 images of input.docx (3 in the document) at 144 DPI.']))).toEqual([]) +}) diff --git a/packages/skill/skill-office/tests/fixtures/real-office.ts b/packages/skill/skill-office/tests/fixtures/real-office.ts index a75c6b6613..b11dd32a33 100644 --- a/packages/skill/skill-office/tests/fixtures/real-office.ts +++ b/packages/skill/skill-office/tests/fixtures/real-office.ts @@ -67,6 +67,33 @@ export function officeImages(events: readonly SessionEvent[]): ImageBlock[] { }) } +/** One PDF conversion the Office tool reported inside a recorded task. */ +export interface ConvertedPdfFile { + /** Absolute path of the temporary file the conversion reported. */ + readonly file: string + /** Byte count the conversion reported for {@link ConvertedPdfFile.file}. */ + readonly bytes: number +} + +/** One `Converted to pdf ( bytes[, pages]): ` result line. */ +const CONVERTED_PDF = /^Converted .+ to pdf \((\d+) bytes(?:, \d+ pages?)?\): (.+)$/mu + +/** + * Collect the PDF conversions reported by successful native Office tool results. + * @param events - Recorded task events. + * @returns Reported temporary files in log order; failed results and other formats are excluded. + */ +export function convertedPdfFiles(events: readonly SessionEvent[]): ConvertedPdfFile[] { + return events.flatMap((event): ConvertedPdfFile[] => { + if (event.type !== 'tool/result' || event.data.message.isError) return [] + return event.data.message.content.flatMap((block): ConvertedPdfFile[] => { + if (block.type !== 'text') return [] + const match = CONVERTED_PDF.exec(block.text) + return match === null ? [] : [{ bytes: Number(match[1]), file: match[2]! }] + }) + }) +} + /** * Reject recorded Office render calls and the "Render the saved deliverable" instruction. * @param events - Recorded task events, including nested skill and shell results. diff --git a/packages/skill/skill-office/tests/render-tools.e2e.ts b/packages/skill/skill-office/tests/render-tools.e2e.ts index 08ada06519..83512f7612 100644 --- a/packages/skill/skill-office/tests/render-tools.e2e.ts +++ b/packages/skill/skill-office/tests/render-tools.e2e.ts @@ -6,7 +6,8 @@ import { execa } from 'execa' import { expect, it } from 'vitest' import { runLoaderSmoke } from '@deepseek-ai/dsh-loader-smoke' import { parseSessionLog } from '@deepseek-ai/dsh-llm-replay' -import { expectNoRenderContext, officeCalls, officeImages, officeModelPatches, officeToolPatches } from './fixtures/real-office.ts' +import { convertedPdfFiles, expectNoRenderContext, officeCalls, officeImages, + officeModelPatches, officeToolPatches } from './fixtures/real-office.ts' const repo = fileURLToPath(new URL('../../../../', import.meta.url)) const runtime = process.env.DSH_PRIMARY_RUNTIME @@ -104,16 +105,18 @@ it.skipIf(!process.env.DEEPSEEK_API_KEY || !runtime)('exports PDF with office_co : event.type === 'tool/ptc-dispatch' ? [{ name: event.data.name, arguments: JSON.stringify(event.data.arguments) }] : []) const skills = calls.filter(call => call.name === 'skill').map(call => (JSON.parse(call.arguments) as { name: string }).name) const office = officeCalls(events) - const diagnostic = JSON.stringify({ calls: calls.map(call => call.name), skills, - office: office.map(call => ({ name: call.name, input: call.args.input, format: call.args.format })) }) - expect(skills.some(name => ['office-docx', 'office-pptx', 'office-xlsx'].includes(name)), diagnostic).toBe(false) const commands = calls.filter(call => call.name === 'bash' || call.name === 'pwsh') .map(call => (JSON.parse(call.arguments) as { command: string }).command).join('\n') + const converted = convertedPdfFiles(events) + const diagnostic = JSON.stringify({ calls: calls.map(call => call.name), skills, commands, + office: office.map(call => ({ name: call.name, input: call.args.input, format: call.args.format })), converted }) expect(office.some(call => call.name === 'office_convert' && call.args.format === 'pdf'), diagnostic).toBe(true) - expect(office.some(call => call.name === 'office_render'), diagnostic).toBe(false) - expectNoRenderContext(events) - expect(commands, diagnostic).not.toMatch(/pypdf|PyPDF2|\bfitz\b|pdfminer|pdfplumber|pdfinfo|pdftotext/iu) - expect((await readFile(join(cwd, 'result.pdf'))).subarray(0, 5).toString()).toBe('%PDF-') + // The conversion reports the temporary output's byte count and that file is released when the conversation + // ends, so a matching size is what ties result.pdf to office_convert. Extra steps such as pdfinfo, a format + // skill, or a render of the result are model choices and do not change the deliverable. + const delivered = await readFile(join(cwd, 'result.pdf')) + expect(converted.some(conversion => conversion.bytes === delivered.length), diagnostic).toBe(true) + expect(delivered.subarray(0, 5).toString(), diagnostic).toBe('%PDF-') expect(await readFile(join(cwd, 'input.docx'))).toEqual(original) }, }) diff --git a/packages/spill/spill-policy/tests/spill-policy.spec.ts b/packages/spill/spill-policy/tests/spill-policy.spec.ts index 9460c39ccf..09ab6f20cf 100644 --- a/packages/spill/spill-policy/tests/spill-policy.spec.ts +++ b/packages/spill/spill-policy/tests/spill-policy.spec.ts @@ -225,7 +225,7 @@ describe('oversized plain-text replacement', () => { }) describe('outer PTC mode failure capture', () => { - it('spills the bounded output-limit diagnostic through the ordinary outer-result policy', async () => { + it('spills a failure after output truncation through the ordinary outer-result policy', async () => { const ctx = new Context() await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) @@ -238,11 +238,11 @@ describe('outer PTC mode failure capture', () => { const result = await executeModelToolFixture(ctx, { signal: testToolSignal, - callId: brandString('code-output-limit'), + callId: brandString('code-truncated-failure'), name: 'run_code', arguments: { - code: 'inspect("HEAD-" + "x".repeat(300)); inspect("TAIL-" + "y".repeat(300)); return "unreachable";', - description: 'Print oversized head and tail lines', + code: 'inspect("HEAD-" + "x".repeat(300)); inspect("TAIL-" + "y".repeat(300)); throw "after output";', + description: 'Print oversized output before throwing', }, agent: agent as never, }) @@ -251,7 +251,8 @@ describe('outer PTC mode failure capture', () => { const saved = (ctx.spillStore as StubStore).saves expect(saved).toHaveLength(1) expect(saved[0]?.source).toMatchObject({ toolName: 'run_code' }) - expect(saved[0]?.content).toContain('code run failed (output-limit)') + expect(saved[0]?.content).toContain('code run failed (exception): after output') + expect(saved[0]?.content).toContain('Output was truncated.') expect(saved[0]?.content).toContain('HEAD-') expect(textOf(result.content)).toContain('Full formatted result stored at: /spill/run_code.txt') expect(events).toEqual([]) diff --git a/packages/subagent/subagent-fork-in-process/README.i18n.yaml b/packages/subagent/subagent-fork-in-process/README.i18n.yaml index f33da46d9b..d2da288c49 100644 --- a/packages/subagent/subagent-fork-in-process/README.i18n.yaml +++ b/packages/subagent/subagent-fork-in-process/README.i18n.yaml @@ -54,14 +54,14 @@ en: 91a5bd22001586e9 zh: 456e5bf20881a70d /deepseek-ai-dsh-subagent-fork-in-process/model-experience/child-agent-history-and-envelope/what-the-model-sees: - en: d4d51c5937bab67c - zh: e7c07b5a38d68d8e + en: aa73e4e958b4d1af + zh: f514cf0ec0ef3ef4 /deepseek-ai-dsh-subagent-fork-in-process/model-experience/child-agent-history-and-envelope/token-effect: en: 19b588baaa87126b zh: 7010e93bbe7d71ba /deepseek-ai-dsh-subagent-fork-in-process/model-experience/child-agent-history-and-envelope/kv-cache-effect: - en: 1e8f8bbab3052b39 - zh: 1efff4da78d60ef9 + en: d01f590e986f815e + zh: a1c433d759b4e908 /deepseek-ai-dsh-subagent-fork-in-process/model-experience/parent-tool-result-indirectly: en: 75d061c2151624a7 zh: 71e58e020b60ff90 diff --git a/packages/subagent/subagent-fork-in-process/README.md b/packages/subagent/subagent-fork-in-process/README.md index 556653b007..cafe091c3e 100644 --- a/packages/subagent/subagent-fork-in-process/README.md +++ b/packages/subagent/subagent-fork-in-process/README.md @@ -109,7 +109,7 @@ Read these pages when the package-level contract is not enough; they move from t #### What the model sees -The child receives the parent's balanced completed-turn prefix, then the new task content verbatim. It joins the parent's preset revision, which supplies persona and tools. Parent agent-local restrictions are not copied. An optional structured-output request adds a child-only tool; the parent's current in-flight turn is excluded. +The child receives the parent's balanced completed-turn prefix, then the new task as a message from the parent agent: `Agent sent a message: ` followed by the task content verbatim. It joins the parent's preset revision, which supplies persona and tools. Parent agent-local restrictions are not copied. An optional structured-output request adds a child-only tool; the parent's current in-flight turn is excluded. #### Token effect @@ -117,7 +117,7 @@ Forking duplicates retained completed history into the child's request, which th #### KV Cache effect -The child may reuse the inherited byte-identical prefix under the same provider and model. Structured output, generated-SDK, route changes, or historical descriptor overrides on cold resume can invalidate reuse before inherited history; later child history is append-only. Continuable messaging adds no child-only system-prompt section or tool schema; the parent id and return guidance follow inherited history in the initial user task ([cache-preserving fork Agent Note](../../../.agents/notes/implemented/architecture/2026-08-10-fork-children-stay-one-shot.md)). +The child may reuse the inherited byte-identical prefix under the same provider and model. Structured output, generated-SDK, route changes, or historical descriptor overrides on cold resume can invalidate reuse before inherited history; later child history is append-only. Continuable messaging adds no child-only system-prompt section or tool schema; the parent id and return guidance follow inherited history in the initial delegated task ([cache-preserving fork Agent Note](../../../.agents/notes/implemented/architecture/2026-08-10-fork-children-stay-one-shot.md)). ### Parent tool result, indirectly diff --git a/packages/subagent/subagent-fork-in-process/README.zh.md b/packages/subagent/subagent-fork-in-process/README.zh.md index 7d232a1efb..ee0e16b6c5 100644 --- a/packages/subagent/subagent-fork-in-process/README.zh.md +++ b/packages/subagent/subagent-fork-in-process/README.zh.md @@ -109,7 +109,7 @@ kind: "package-reference" #### 模型看到什么 -子 agent 先接收由父级已配平的已完成轮次构成的前缀,再逐字接收新的任务内容。它加入父级的 preset 代际,由 preset 提供 persona 和工具。父级 agent 局部限制不会被复制。可选的结构化输出请求会添加仅属于子 agent 的工具;父级当前进行中的轮次会被排除。 +子 agent 先接收由父级已配平的已完成轮次构成的前缀,再接收一条来自父 agent 的新任务消息:`Agent sent a message: ` 后接逐字任务内容。它加入父级的 preset 代际,由 preset 提供 persona 和工具。父级 agent 局部限制不会被复制。可选的结构化输出请求会添加仅属于子 agent 的工具;父级当前进行中的轮次会被排除。 #### Token 影响 @@ -117,7 +117,7 @@ fork 会把保留的已完成历史复制到子 agent 的请求中,子 agent #### KV Cache 影响 -在提供方与模型相同的前提下,子 agent 可以复用继承的逐字节相同前缀。结构化输出、生成 SDK、路由变化,或冷恢复时的历史 descriptor 覆盖,可能在继承历史之前使复用失效;后续子 agent 历史仅追加。可继续消息不会增加子级专属的系统提示词区段或工具 schema;父级 ID 与返回指导在初始用户任务中位于继承历史之后(见[保持 fork 缓存的 Agent Note](../../../.agents/notes/implemented/architecture/2026-08-10-fork-children-stay-one-shot.zh.md))。 +在提供方与模型相同的前提下,子 agent 可以复用继承的逐字节相同前缀。结构化输出、生成 SDK、路由变化,或冷恢复时的历史 descriptor 覆盖,可能在继承历史之前使复用失效;后续子 agent 历史仅追加。可继续消息不会增加子级专属的系统提示词区段或工具 schema;父级 ID 与返回指导在初始委派任务中位于继承历史之后(见[保持 fork 缓存的 Agent Note](../../../.agents/notes/implemented/architecture/2026-08-10-fork-children-stay-one-shot.zh.md))。 ### 父级工具结果(间接) diff --git a/packages/subagent/subagent-spawn-in-process/README.i18n.yaml b/packages/subagent/subagent-spawn-in-process/README.i18n.yaml index cd2ac2ed30..837e3d968e 100644 --- a/packages/subagent/subagent-spawn-in-process/README.i18n.yaml +++ b/packages/subagent/subagent-spawn-in-process/README.i18n.yaml @@ -51,8 +51,8 @@ en: 05e6180f1498fdf9 zh: 2b05d2b97bfa67da /deepseek-ai-dsh-subagent-spawn-in-process/model-experience/child-agent-request/what-the-model-sees: - en: c9dfab9a4d363fed - zh: 6cb3b0914ccb73e2 + en: 84a5e689a55f5bec + zh: 89d6bcbe1a7fb6e7 /deepseek-ai-dsh-subagent-spawn-in-process/model-experience/child-agent-request/token-effect: en: eb373a4b35a4b548 zh: 9537d0e466e8bcd9 diff --git a/packages/subagent/subagent-spawn-in-process/README.md b/packages/subagent/subagent-spawn-in-process/README.md index c81fb63901..d785dd16f4 100644 --- a/packages/subagent/subagent-spawn-in-process/README.md +++ b/packages/subagent/subagent-spawn-in-process/README.md @@ -106,7 +106,7 @@ Read these pages when the package-level contract is not enough; they move from t #### What the model sees -The fresh child receives the task content verbatim as its only user message in a new empty conversation, with the parent provider, model, reasoning effort, output-token limit, and working directory by default. The inherited or selected preset supplies tools and prompt sections. No parent conversation message is included. +The fresh child receives the task as its only user message in a new empty conversation, attributed to the parent agent: `Agent sent a message: ` followed by the task content verbatim. It uses the parent provider, model, reasoning effort, output-token limit, and working directory by default. The inherited or selected preset supplies tools and prompt sections. No parent conversation message is included. #### Token effect diff --git a/packages/subagent/subagent-spawn-in-process/README.zh.md b/packages/subagent/subagent-spawn-in-process/README.zh.md index b60b16cab2..1a6982422d 100644 --- a/packages/subagent/subagent-spawn-in-process/README.zh.md +++ b/packages/subagent/subagent-spawn-in-process/README.zh.md @@ -106,7 +106,7 @@ kind: "package-reference" #### 模型看到什么 -全新子 agent 逐字接收任务内容,作为新空对话中的唯一用户消息,默认使用父级提供方、模型、推理强度、输出 token 上限与工作目录。继承或选定的 preset 提供工具和提示词片段。不包含任何父级对话消息。 +全新子 agent 在新空对话中接收唯一一条用户消息,即来自父 agent 的任务:`Agent sent a message: ` 后接逐字任务内容。默认使用父级提供方、模型、推理强度、输出 token 上限与工作目录。继承或选定的 preset 提供工具和提示词片段。不包含任何父级对话消息。 #### Token 影响 diff --git a/packages/subagent/subagent/README.i18n.yaml b/packages/subagent/subagent/README.i18n.yaml index c537b6a6fa..fba27cafa5 100644 --- a/packages/subagent/subagent/README.i18n.yaml +++ b/packages/subagent/subagent/README.i18n.yaml @@ -68,6 +68,18 @@ /deepseek-ai-dsh-subagent/model-experience: en: 215e7ba838619b7b zh: a311da3843709f90 +/deepseek-ai-dsh-subagent/model-experience/message-authorship: + en: 4350a9a08e35641b + zh: 75cd6deac5f7430a +/deepseek-ai-dsh-subagent/model-experience/message-authorship/what-the-model-sees: + en: 572bb322919ae1cb + zh: 5c49bbd85cf0fd31 +/deepseek-ai-dsh-subagent/model-experience/message-authorship/token-effect: + en: 8611aab0a4bcb5b4 + zh: c2286d8a73b818ac +/deepseek-ai-dsh-subagent/model-experience/message-authorship/kv-cache-effect: + en: 55d5610dcc9049e3 + zh: 382e85de9c81cb11 /deepseek-ai-dsh-subagent/model-experience/settlement-notice: en: f7cec22ba9d3fb4f zh: 67b1d40f9b136f71 diff --git a/packages/subagent/subagent/README.md b/packages/subagent/subagent/README.md index cc4613943d..334a89ff18 100644 --- a/packages/subagent/subagent/README.md +++ b/packages/subagent/subagent/README.md @@ -170,6 +170,20 @@ Read these pages when the package-level contract is not enough. They move from t ## Model Experience +### Message authorship + +#### What the model sees + +Local continuable agents receive initial delegated tasks and later agent-to-agent messages with the `agent-message` source and the actual sender's Session id. Both start with `Agent sent a message: ` followed by the supplied content blocks. Direct human messages keep their original content and `user` source. The child delegation-scope statement below tells the child that user messages without the agent prefix come from the human user and that it answers them in its reply. Root input and retained history are unchanged. + +#### Token effect + +One short author prefix per initial delegated task or agent-to-agent message. Human input adds no attribution tokens; the authorship rule is part of the child's fixed delegation statement. + +#### KV Cache effect + +The initial task follows any inherited history; later messages append without changing retained history. + ### Settlement notice #### What the model sees @@ -213,7 +227,7 @@ Every in-process child's runtime-context snapshot carries the `subagent:delegati ##### The delegation-scope statement ```markdown -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 job needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it. +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 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. ``` #### Token effect diff --git a/packages/subagent/subagent/README.zh.md b/packages/subagent/subagent/README.zh.md index c020137fb6..06b3317b13 100644 --- a/packages/subagent/subagent/README.zh.md +++ b/packages/subagent/subagent/README.zh.md @@ -170,6 +170,20 @@ kind: "package-reference" ## 模型体验 +### 消息作者 + +#### 模型看到什么 + +本地可续聊 agent 收到的初始委派任务与后续 agent 间消息都使用 `agent-message` source,并记录实际发送方的 Session ID。两者均以 `Agent sent a message: ` 开头,后接原始内容块。真人直接发给子会话的消息保留原始内容和 `user` source。下方的子级委派范围声明告诉子 agent:不带 agent 前缀的 user 消息来自真人用户,并应在回复中直接回答。主 agent 的输入与已有历史不变。 + +#### Token 影响 + +每条初始委派任务或 agent 间消息增加一个简短作者前缀。真人输入不增加来源 token;作者规则属于子 agent 固定的委派声明。 + +#### KV Cache 影响 + +初始任务位于继承历史之后;后续消息只追加,不改写已有历史。 + ### 结算通知 #### 模型看到什么 @@ -213,7 +227,7 @@ Your final answer is delivered automatically if your parent is still online. Inc ##### 委派范围声明 ```markdown -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 job needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it. +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 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. ``` #### Token 影响 diff --git a/packages/subagent/subagent/src/child-agent.ts b/packages/subagent/subagent/src/child-agent.ts index ffc2af10e1..41bb80b974 100644 --- a/packages/subagent/subagent/src/child-agent.ts +++ b/packages/subagent/subagent/src/child-agent.ts @@ -164,7 +164,7 @@ export interface ChildComposition { } /** - * Model-facing delegation-scope statement for every in-process child. A + * Model-facing delegation-scope and message-authorship statement for every in-process child. A * runtime-context contribution rather than a system-prompt section, so the * deployment's system prompt stays uniform across parents and children. */ @@ -172,7 +172,9 @@ export const SUBAGENT_DELEGATION_CONTEXT = '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.' + + 'limitation in your reply so the delegating agent can handle it. Messages from other agents begin with ' + + '"Agent 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.' /** * Compose a child before publication and restore historical descriptor overrides. diff --git a/packages/subagent/subagent/src/manager.ts b/packages/subagent/subagent/src/manager.ts index 43e1dc44ff..e14ca86033 100644 --- a/packages/subagent/subagent/src/manager.ts +++ b/packages/subagent/subagent/src/manager.ts @@ -403,12 +403,13 @@ export class SubagentManager { established = activation const child = requireLocalActivation(activation).handle.agent const childHeader = child.session.header + const task = createAgentMessage(parent, agentAddress(this.pathOf(parent, ancestry.root), parent.id), spec.prompt) return await this.submitMaterialized( activation, spec.delivery !== 'caller' - ? withResultDeliveryGuidance(spec.prompt) - : spec.prompt, - { source: { kind: 'user' }, signal, delivery: 'queue', authorize: () => { this.assertAdmitting(parent) } }, + ? withResultDeliveryGuidance([...task.content]) + : [...task.content], + { source: task.source, signal, delivery: 'queue', authorize: () => { this.assertAdmitting(parent) } }, ancestry.root, () => { this.assertAdmitting(parent) diff --git a/packages/subagent/subagent/src/types.ts b/packages/subagent/subagent/src/types.ts index 1786ed8e2e..9099b608c7 100644 --- a/packages/subagent/subagent/src/types.ts +++ b/packages/subagent/subagent/src/types.ts @@ -152,7 +152,7 @@ export 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; diff --git a/packages/subagent/subagent/tests/activation-policy.spec.ts b/packages/subagent/subagent/tests/activation-policy.spec.ts index 175dff67f1..c75795c9eb 100644 --- a/packages/subagent/subagent/tests/activation-policy.spec.ts +++ b/packages/subagent/subagent/tests/activation-policy.spec.ts @@ -186,6 +186,7 @@ describe('in-process policy inheritance', () => { expect(contextText).toContain('Approval prompts are disabled') // The statement rides runtime context; the system node (surface node 0) stays uniform. expect(contextText).toContain('You are a delegated subagent') + expect(contextText).toContain('Other user messages come from the human user') const systemHead = child.session.deriveMessages()[0] if (systemHead?.role !== 'system') throw new Error('child surface node 0 is not a system message') expect(child.session.surface.nodes[0]).toBe(systemNode.seq) diff --git a/packages/subagent/subagent/tests/continuation.spec.ts b/packages/subagent/subagent/tests/continuation.spec.ts index 66f4f78f3d..cd5c745594 100644 --- a/packages/subagent/subagent/tests/continuation.spec.ts +++ b/packages/subagent/subagent/tests/continuation.spec.ts @@ -147,7 +147,8 @@ function hasAssistantText(events: readonly SessionEvent[], text: string): boolea /** Caller-supplied user message texts in log order (runtime-context snapshots excluded). */ function userTexts(events: readonly SessionEvent[]): string[] { return events.flatMap(event => event.type === 'user/message' && event.data.source.kind !== 'runtime-context' - ? event.data.content.flatMap(block => block.type === 'text' + ? event.data.content.flatMap((block, index) => block.type === 'text' + && !(event.data.source.kind === 'agent-message' && index === 0) && !block.text.startsWith('Your final answer is delivered automatically ') ? [block.text] : []) @@ -1256,6 +1257,53 @@ describe('target-only Queue residency routing', () => { }) describe('continuable human steering delivery', () => { + it.each(['queue', 'steer'] as const)('distinguishes delegated tasks from cold %s input without RPC metadata', async (delivery) => { + const { ctx, parent, adapter } = await setup([ + textResponse('root answer'), textResponse('child answer'), textResponse('human answer'), textResponse('agent answer'), + ]) + try { + parent.followup(createUserMessage({ content: message('root question'), source: { kind: 'user' } })) + await parent.whenIdle() + parkParent(ctx, parent) + const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) + await expect(started.result).resolves.toMatchObject({ stopReason: 'completed' }) + let ended = Promise.withResolvers() + ctx.on('subagent/end', (info) => { if (info.id === started.childId) ended.resolve(undefined) }) + const id = await subagentManager(ctx).deliverPrompt(started.childId, message('human question'), { + delivery, source: { kind: 'user' }, signal: testSignal, + }) + await ended.promise + ended = Promise.withResolvers() + await ctx.subagents.sendMessage(parent, started.childId, message('agent question'), { signal: testSignal }) + await ended.promise + + expect(adapter.requests).toHaveLength(4) + expect(adapter.requests[0]!.messages.find(item => item.source?.kind === 'user')?.content) + .toEqual(message('root question')) + const task = adapter.requests[1]!.messages.find(item => item.source?.kind === 'agent-message')! + expect(task.source).toEqual({ + kind: 'agent-message', form: 'relay', senderSessionId: parent.id, + }) + expect(task.content).toHaveLength(3) + expect(task.content.slice(0, 2)).toEqual([ + { type: 'text', text: 'Agent lead sent a message: ' }, + { type: 'text', text: 'child task' }, + ]) + const guidance = task.content[2]! + expect(guidance.type === 'text' && guidance.text).toMatch(/^Your final answer is delivered automatically /) + const received = adapter.requests[2]!.messages.find(item => item.id === id) + expect(received).toMatchObject({ + role: 'user', source: { kind: 'user' }, content: message('human question'), + }) + expect(adapter.requests[3]!.messages.findLast(item => item.source?.kind === 'agent-message')?.content) + .toEqual([{ type: 'text', text: 'Agent lead sent a message: ' }, ...message('agent question')]) + const stored = await loadStoredSession(ctx.sessionPersistence, started.childId) + expect(stored.events.find(event => event.type === 'user/message' && event.data.id === id)?.data).toEqual(received) + } finally { + await ctx.fiber.dispose() + } + }) + it('places resident steering in nextStep with its durable identity and source', async () => { const release = Promise.withResolvers() const adapter = new GatedAdapter([ diff --git a/packages/subagent/subagent/tests/sibling-messages.spec.ts b/packages/subagent/subagent/tests/sibling-messages.spec.ts index abd8e78a5b..65cb1feee0 100644 --- a/packages/subagent/subagent/tests/sibling-messages.spec.ts +++ b/packages/subagent/subagent/tests/sibling-messages.spec.ts @@ -144,7 +144,8 @@ describe('subagent sibling messages', () => { .toEqual([3, 3]) await ctx.subagents.sendMessage(sender, b, [{ type: 'text', text: 'hello' }], { signal }) - const delivered = (await storedUserMessages(ctx, b)).find(event => event.data.source.kind === 'agent-message')! + const delivered = (await storedUserMessages(ctx, b)).find(event => event.data.source.kind === 'agent-message' + && event.data.source.senderSessionId === a)! expect(textOf(delivered)).toBe('Agent agent-1 sent a message: hello') expect(delivered.data.source).toEqual({ kind: 'agent-message', form: 'relay', senderSessionId: a }) ctx.subagents.interrupt(a, { kind: 'ancestor', agent: parent }) @@ -238,7 +239,8 @@ describe('tree-wide messages', () => { await ctx.subagents.sendMessage(sender, leafId, [{ type: 'text', text: 'cold cousin' }], { signal }) const messages = await storedUserMessages(ctx, leafId) - const delivered = messages.find(event => event.data.source.kind === 'agent-message')! + const delivered = messages.find(event => event.data.source.kind === 'agent-message' + && event.data.source.senderSessionId === a)! expect(textOf(delivered)).toBe('Agent agent-2 sent a message: cold cousin') expect(delivered.data.source).toEqual({ kind: 'agent-message', form: 'relay', senderSessionId: a }) await settled(ctx, branchId) diff --git a/packages/subagent/tool-subagent-control/tests/tool-subagent-control.spec.ts b/packages/subagent/tool-subagent-control/tests/tool-subagent-control.spec.ts index 868aec9da5..872ff88365 100644 --- a/packages/subagent/tool-subagent-control/tests/tool-subagent-control.spec.ts +++ b/packages/subagent/tool-subagent-control/tests/tool-subagent-control.spec.ts @@ -169,9 +169,9 @@ describe('dsh-tool-subagent-control', () => { const prompt = loaded.events[promptIndex] if (prompt?.type !== 'user/message') throw new Error('expected the initial fork task') const texts = prompt.data.content.flatMap(block => block.type === 'text' ? [block.text] : []) - expect(texts[0]).toBe('fork task') - expect(texts[1]).toContain('Your final answer is delivered automatically') - expect(texts[1]).not.toContain('send_message') + expect(texts.slice(0, 2)).toEqual(['Agent lead sent a message: ', 'fork task']) + expect(texts[2]).toContain('Your final answer is delivered automatically') + expect(texts[2]).not.toContain('send_message') expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('You are a subagent delegated by agent') expect(loaded.events.some(event => event.type === 'user/message' && event.data.source.kind === 'runtime-context' && JSON.stringify(event.data.content).includes('You are a subagent delegated by agent'))).toBe(true) @@ -446,6 +446,7 @@ describe('dsh-tool-subagent-control', () => { : []) : []) expect(prompts).toEqual([ + 'Agent lead sent a message: ', 'long work', 'Agent lead sent a message: ', 'also consider Y', @@ -600,6 +601,7 @@ describe('dsh-tool-subagent-control interrupt_agent', () => { : []) : []) expect(prompts).toEqual([ + 'Agent lead sent a message: ', 'long work', 'Agent lead sent a message: ', 'parked follow-up', diff --git a/packages/test-support/client-runtime/package.json b/packages/test-support/client-runtime/package.json index f20d9bfb91..9c129667e8 100644 --- a/packages/test-support/client-runtime/package.json +++ b/packages/test-support/client-runtime/package.json @@ -90,7 +90,8 @@ "@deepseek-ai/dsh-web-app": "workspace:*", "react": "^18.2.0", "react-dom": "^18.2.0", - "@deepseek-ai/dsh-client-ui-context-menu": "workspace:*" + "@deepseek-ai/dsh-client-ui-context-menu": "workspace:*", + "@deepseek-ai/dsh-client-config": "workspace:*" }, "files": [ "lib/index.js", diff --git a/packages/test-support/client-runtime/src/assembly/remote-default-responses.ts b/packages/test-support/client-runtime/src/assembly/remote-default-responses.ts index 52002d2829..cfb6a626a1 100644 --- a/packages/test-support/client-runtime/src/assembly/remote-default-responses.ts +++ b/packages/test-support/client-runtime/src/assembly/remote-default-responses.ts @@ -63,5 +63,7 @@ export const remoteDefaultResponses: RemoteTable = { 'terminal/watch': openStream([[]]), // ui-connector-account `apply`: the registered connector accounts, none in a default composition, then open. 'connectorAccounts/watch': openStream([{ accounts: [] }]), + // client-hmr browser `apply`: open without a baseline, so the page keeps the boot graph the harness composed. + 'pluginEvents/follow': openStream(), }, } diff --git a/packages/test-support/client-runtime/src/assembly/remote-proxies.ts b/packages/test-support/client-runtime/src/assembly/remote-proxies.ts index d1a3b09142..3b88825ea5 100644 --- a/packages/test-support/client-runtime/src/assembly/remote-proxies.ts +++ b/packages/test-support/client-runtime/src/assembly/remote-proxies.ts @@ -23,22 +23,29 @@ export const REMOTES_PACKAGE = '@deepseek-ai/dsh-api-remotes' const PREFIX = 'remote.' +/** Namespaces a roster package mounts through its own generated Remote client; a proxy would collide with that mount. */ +const SELF_MOUNTED_NAMESPACES: Readonly> = { + pluginEvents: '@deepseek-ai/dsh-client-hmr', +} + /** * Namespaces to provide: every `remote.` a roster module injects, plus the - * namespace of every endpoint the mock has a rule for. - * @param modules - loaded roster modules. + * namespace of every endpoint the mock has a rule for, except a namespace that + * a roster package mounts itself. + * @param modules - loaded roster modules keyed by package name. * @param mock - the spec's mock. * @returns sorted namespace names. */ -export function remoteNamespacesOf(modules: Iterable, mock: RemoteMock): readonly string[] { +export function remoteNamespacesOf(modules: ReadonlyMap, mock: RemoteMock): readonly string[] { const names = new Set() - for (const module of modules) { + for (const module of modules.values()) { for (const service of injectNames(module.inject)) if (service.startsWith(PREFIX)) names.add(service.slice(PREFIX.length)) } for (const endpoint of mock.endpoints()) { const slash = endpoint.indexOf('/') if (slash > 0 && !endpoint.startsWith('$')) names.add(endpoint.slice(0, slash)) } + for (const [namespace, owner] of Object.entries(SELF_MOUNTED_NAMESPACES)) if (modules.has(owner)) names.delete(namespace) return [...names].sort() } diff --git a/packages/test-support/client-runtime/src/assembly/test-client.ts b/packages/test-support/client-runtime/src/assembly/test-client.ts index 0593eac143..698f8d9474 100644 --- a/packages/test-support/client-runtime/src/assembly/test-client.ts +++ b/packages/test-support/client-runtime/src/assembly/test-client.ts @@ -86,7 +86,7 @@ const DEFAULT_CONNECT_TIMEOUT_MS = 5_000 /** * Browser globals jsdom lacks that roster plugins touch at apply or mount: - * client-hmr opens an `EventSource`; layout components observe size, media queries, and font loading. + * layout components observe size, media queries, and font loading. * Inert stand-ins, installed only where the global is absent. */ const JSDOM_SHIMS: Readonly> = { @@ -95,10 +95,6 @@ const JSDOM_SHIMS: Readonly> = { addListener() {}, removeListener() {}, }), - EventSource: class { - addEventListener(): void {} - close(): void {} - }, ResizeObserver: class { observe(): void {} disconnect(): void {} @@ -259,7 +255,7 @@ export class TestClient { mountPoint = resolveMountPoint(options.mount) release = sharedJsdomShims.acquire() const system = createInProcessModules(graphFromRoster(roster.rows), modules) - ctx.plugin(remoteProxiesPlugin(remoteNamespacesOf(modules.values(), mock), mock) as Plugin) + ctx.plugin(remoteProxiesPlugin(remoteNamespacesOf(modules, mock), mock) as Plugin) // The dropped remote-access row's Hooks: every action is allowed on every resource unless the spec fixes the answers. if (generated.includes(REMOTE_ACCESS_PACKAGE)) { ctx.plugin(options.access === undefined ? allowAllAccessPlugin : staticAccessPlugin(options.access)) diff --git a/packages/test-support/client-runtime/src/index.ts b/packages/test-support/client-runtime/src/index.ts index 5eee1c7a74..2ed5c0f75a 100644 --- a/packages/test-support/client-runtime/src/index.ts +++ b/packages/test-support/client-runtime/src/index.ts @@ -62,6 +62,7 @@ export type { FixtureSnapshot, SessionBehaviorOverrides, SessionFixture, SessionFixtureSnapshot, Stabilizer, } from './fixtures.ts' export { contextMenuHook } from './context-menu.ts' +export { syncedConfig } from './synced-config.ts' export { makeTranslate } from './translate.ts' export { allowAllAccess, allowAllAccessPlugin, StaticRemoteAccess, staticAccessPlugin } from './access.ts' export type { AccessStandardProps, StaticAccessPlugin } from './access.ts' @@ -310,15 +311,16 @@ export class SlotTestRuntime { * so a missing provider fails loud instead of suspending the fiber forever * (deliberate load-order suspension tests use `ctx.plugin` directly). * @param plugin - plugin value (function, class, or `{ inject, apply }` object). + * @param config - the plugin's `apply` config, such as a {@link syncedConfig} object for a Client face with synced fields. * @returns handle owning the fiber's explicit disposal. */ - async mount(plugin: Plugin): Promise { + async mount(plugin: Plugin, config?: unknown): Promise { const required = Object.keys(Inject.resolve((plugin as { inject?: Inject }).inject)) const missing = required.filter(name => this.ctx.get(name) === undefined) if (missing.length > 0) { throw new Error(`mount would suspend: missing service(s) ${missing.join(', ')} — provide() them first`) } - const fiber = this.ctx.plugin(plugin) + const fiber = this.ctx.plugin(plugin, config) await this.stabilizer(async () => { await fiber.await() }) diff --git a/packages/test-support/client-runtime/src/synced-config.ts b/packages/test-support/client-runtime/src/synced-config.ts new file mode 100644 index 0000000000..24cd67c675 --- /dev/null +++ b/packages/test-support/client-runtime/src/synced-config.ts @@ -0,0 +1,12 @@ +/** Synced Config objects for specs that mount a Client plugin face directly instead of through the page entry controller. */ +import type { SyncedConfig, SyncedConfigValues } from '@deepseek-ai/dsh-client-config/types' +import { SyncedConfigEntry } from '@deepseek-ai/dsh-client-modules/src/client/synced-config.ts' + +/** + * Build the object a plugin activation receives as its `apply` config, holding fixed values. + * @param values - JSON values of the plugin's top-level volatile fields. + * @returns the activation's read-only Config object. + */ +export function syncedConfig(values: SyncedConfigValues): SyncedConfig { + return new SyncedConfigEntry(values).activate() as SyncedConfig +} diff --git a/packages/test-support/client-runtime/tests/assembly-dependencies.client.spec.ts b/packages/test-support/client-runtime/tests/assembly-dependencies.client.spec.ts index 4bd4835b59..81a653fa8c 100644 --- a/packages/test-support/client-runtime/tests/assembly-dependencies.client.spec.ts +++ b/packages/test-support/client-runtime/tests/assembly-dependencies.client.spec.ts @@ -13,13 +13,14 @@ const hmrTest = createClientTest({ roster: hmrRoster }, { awaitConnected: false const sessionTest = createClientTest({ roster: sessionRoster }) describe('bundle dependency closures', () => { - hmrTest('activates HMR with its declared module provider and no Connection', async ({ start }) => { + hmrTest('activates HMR with its declared module and Remote carrier providers', async ({ start }) => { expect(hmrRoster.rows.map(row => row.name)).toContain(MODULES) const client = await start() const entry = [...client.ctx.loader.entries()].find(row => row.options.name === HMR) expect(entry?.fiber?.state).toBe(FiberState.ACTIVE) expect(client.ctx.get('modules')).toBeDefined() - expect(client.ctx.get('connection')).toBeUndefined() + expect(client.ctx.get('config')).toBeDefined() + expect(client.ctx.get('remote')).toBeDefined() }, 60_000) sessionTest('activates Session Controller with its declared file-upload provider', async ({ mock, start }) => { diff --git a/packages/test-support/client-runtime/tests/assembly-remote-proxies.client.spec.ts b/packages/test-support/client-runtime/tests/assembly-remote-proxies.client.spec.ts index 3f6593c120..a4f235b751 100644 --- a/packages/test-support/client-runtime/tests/assembly-remote-proxies.client.spec.ts +++ b/packages/test-support/client-runtime/tests/assembly-remote-proxies.client.spec.ts @@ -18,12 +18,16 @@ async function drain(source: AsyncIterable): Promise { describe('remoteNamespacesOf', () => { it('collects remote. injects in both inject forms plus the namespaces of registered endpoints, skipping Gateway-internal ones', () => { - const modules: ClientPluginModule[] = [ - { apply() {}, inject: ['slots', 'remote.settings', 'remote'] }, - { apply() {}, inject: { 'remote.session': { required: true }, connection: { required: false } } }, - { apply() {} }, - ] + const modules = new Map([ + ['a', { apply() {}, inject: ['slots', 'remote.settings', 'remote'] }], + ['b', { apply() {}, inject: { 'remote.session': { required: true }, connection: { required: false } } }], + ['c', { apply() {} }], + ]) const mock = RemoteMock.create().unary('goals/create', ok({ id: 'g' })).stream('workspace/follow', openStream()) + .stream('pluginEvents/follow', openStream()) + expect(remoteNamespacesOf(modules, mock)).toEqual(['goals', 'pluginEvents', 'session', 'settings', 'workspace']) + // A namespace its own roster package mounts gets no proxy. + modules.set('@deepseek-ai/dsh-client-hmr', { apply() {} }) expect(remoteNamespacesOf(modules, mock)).toEqual(['goals', 'session', 'settings', 'workspace']) }) }) diff --git a/packages/test-support/client-runtime/tests/assembly-test-client.client.spec.ts b/packages/test-support/client-runtime/tests/assembly-test-client.client.spec.ts index 2dd5de587e..69236c6a78 100644 --- a/packages/test-support/client-runtime/tests/assembly-test-client.client.spec.ts +++ b/packages/test-support/client-runtime/tests/assembly-test-client.client.spec.ts @@ -19,7 +19,7 @@ const PARALLEL_PROBE = '@deepseek-ai/dsh-client-test-parallel-probe' /** Declared by ui-sidebar, whose SlotMap merge is outside this package's compilation face. */ const SIDEBAR_SETTINGS = 'sidebar.settings' as never const BRAND = '@deepseek-ai/dsh-client-ui-brand-official' -const globals = globalThis as { EventSource?: unknown; ResizeObserver?: unknown; matchMedia?: typeof window.matchMedia } +const globals = globalThis as { ResizeObserver?: unknown; matchMedia?: typeof window.matchMedia } /** The whole roster's first boot pays the cold module transform of every plugin package. */ const COLD_BOOT_TIMEOUT_MS = 60_000 @@ -44,7 +44,6 @@ describe('TestClient (jsdom)', () => { expect(document.body.contains(container)).toBe(true) expect(container.childElementCount).toBeGreaterThan(0) expect('__DSH_TRANSPORT__' in globalThis).toBe(false) - expect(globals.EventSource).toBeDefined() expect(globals.ResizeObserver).toBeDefined() const query = globals.matchMedia!('(pointer: coarse)') expect(query.media).toBe('(pointer: coarse)') @@ -57,7 +56,6 @@ describe('TestClient (jsdom)', () => { await client.dispose() expect(document.body.contains(container)).toBe(false) expect('__DSH_TRANSPORT__' in globalThis).toBe(false) - expect(globals.EventSource).toBeUndefined() expect(globals.ResizeObserver).toBeUndefined() expect(globals.matchMedia).toBeUndefined() expect(document.fonts).toBeUndefined() @@ -75,10 +73,10 @@ describe('TestClient (jsdom)', () => { }) const client = await started({ roster: API_ROSTER }) expect(globals.ResizeObserver).toBe(existing) - expect(globals.EventSource).toBeDefined() + expect(globals.matchMedia).toBeDefined() await client.dispose() expect(globals.ResizeObserver).toBe(existing) - expect(globals.EventSource).toBeUndefined() + expect(globals.matchMedia).toBeUndefined() expect(document.fonts).toBe(fonts) }) @@ -118,11 +116,11 @@ describe('TestClient (jsdom)', () => { expect(mockB.log.calls('session/rename')).toHaveLength(1) await a.dispose() expect('__DSH_TRANSPORT__' in globalThis).toBe(false) - expect(globals.EventSource).toBeDefined() + expect(globals.matchMedia).toBeDefined() expect(document.fonts).toBeInstanceOf(EventTarget) await b.dispose() expect('__DSH_TRANSPORT__' in globalThis).toBe(false) - expect(globals.EventSource).toBeUndefined() + expect(globals.matchMedia).toBeUndefined() expect(document.fonts).toBeUndefined() }) @@ -278,6 +276,6 @@ describe('TestClient (jsdom)', () => { const mock = RemoteMock.create().stream('$events', openStream([])) await expect(TestClient.start({ roster }, mock, { connectTimeoutMs: 300 })) .rejects.toThrow(/connection state is \S+ after 300ms; unmatched: \[unary workspace\/follow\]; streams: \[.*\$events \(open\).*\]/) - expect(globals.EventSource).toBeUndefined() + expect(globals.matchMedia).toBeUndefined() }) }) diff --git a/packages/test-support/client-runtime/tsconfig.json b/packages/test-support/client-runtime/tsconfig.json index 6301534ed9..9777e82c3b 100644 --- a/packages/test-support/client-runtime/tsconfig.json +++ b/packages/test-support/client-runtime/tsconfig.json @@ -12,6 +12,9 @@ "src" ], "references": [ + { + "path": "../../client/config" + }, { "path": "../../../vendor/cordis" }, @@ -91,7 +94,7 @@ "path": "../remote-mock" }, { - "path": "../../client/hmr" + "path": "../../client/hmr/tsconfig.client.json" }, { "path": "../../client/ui-context-menu" diff --git a/packages/workflow/workflow-ptc/tests/host.spec.ts b/packages/workflow/workflow-ptc/tests/host.spec.ts index 190696879d..3c50372480 100644 --- a/packages/workflow/workflow-ptc/tests/host.spec.ts +++ b/packages/workflow/workflow-ptc/tests/host.spec.ts @@ -241,6 +241,15 @@ describe('workflow runtime outcomes', () => { } finally { await handle.dispose() } }) + it('accepts a complete workflow value when incidental runtime output was truncated', async () => { + const value = { value: 42, stopReason: 'completed', agentsStarted: 0 } + const { start } = await setup(() => Promise.resolve({ output: [], value, outputTruncated: true })) + const handle = start() + try { + expect(await handle.result).toEqual(value) + } finally { await handle.dispose() } + }) + it('carries a guest-reported fatal code onto the run result', async () => { const value = { value: null, stopReason: 'error', agentsStarted: 1, error: 'total agent cap (1)', errorCode: 'AGENT_CAP' } const { start } = await setup(() => Promise.resolve({ output: [], value })) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 7efb71efc4..a359a9065f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -465,6 +465,9 @@ importers: '@deepseek-ai/dsh-sdk-minimal': specifier: workspace:* version: link:../../packages/bundle/sdk-minimal + '@deepseek-ai/dsh-session-persistence-sqlite': + specifier: workspace:* + version: link:../../packages/session/session-persistence-sqlite '@deepseek-ai/dsh-session-projection': specifier: workspace:* version: link:../../packages/session/session-projection @@ -3595,6 +3598,18 @@ importers: specifier: 0.2.3 version: 0.2.3 + packages/client/config: + devDependencies: + '@deepseek-ai/cordis': + specifier: workspace:~ + version: link:../../../vendor/cordis + '@deepseek-ai/dsh-client-store': + specifier: workspace:* + version: link:../store + '@deepseek-ai/dsh-util-values': + specifier: workspace:* + version: link:../../util/values + packages/client/connection: dependencies: '@deepseek-ai/dsh-brand': @@ -3674,9 +3689,18 @@ importers: packages/client/hmr: dependencies: + '@deepseek-ai/dsh-deque': + specifier: workspace:* + version: link:../../util/deque + '@deepseek-ai/dsh-typert-protocol': + specifier: workspace:* + version: link:../../typert/protocol '@deepseek-ai/schemastery': specifier: link:../../../vendor/schemastery version: link:../../../vendor/schemastery + zod: + specifier: 4.6.6 + version: 4.6.6 devDependencies: '@deepseek-ai/cordis': specifier: workspace:~ @@ -3684,15 +3708,15 @@ importers: '@deepseek-ai/cordis-plugin-loader': specifier: workspace:~ version: link:../../../vendor/loader + '@deepseek-ai/dsh-api-gateway': + specifier: workspace:* + version: link:../../api/gateway + '@deepseek-ai/dsh-api-remote-access': + specifier: workspace:* + version: link:../../api/remote-access '@deepseek-ai/dsh-client-modules': specifier: workspace:* version: link:../modules - '@deepseek-ai/dsh-host-webserver': - specifier: workspace:* - version: link:../../host/webserver - eventsource-parser: - specifier: ^3.1.0 - version: 3.1.0 packages/client/locale: dependencies: @@ -3745,6 +3769,9 @@ importers: '@deepseek-ai/cordis-plugin-loader': specifier: workspace:~ version: link:../../../vendor/loader + '@deepseek-ai/dsh-client-config': + specifier: workspace:* + version: link:../config '@deepseek-ai/dsh-client-script-realm': specifier: workspace:* version: link:../script-realm @@ -3757,6 +3784,15 @@ importers: '@deepseek-ai/dsh-package-manifest': specifier: workspace:* version: link:../../util/package-manifest + '@deepseek-ai/dsh-typert-protocol': + specifier: workspace:* + version: link:../../typert/protocol + '@deepseek-ai/dsh-util-values': + specifier: workspace:* + version: link:../../util/values + '@deepseek-ai/schemastery': + specifier: link:../../../vendor/schemastery + version: link:../../../vendor/schemastery packages/client/product-analytics: dependencies: @@ -4478,6 +4514,10 @@ importers: version: 18.3.1(react@18.3.1) packages/client/ui-context-menu: + dependencies: + '@deepseek-ai/schemastery': + specifier: link:../../../vendor/schemastery + version: link:../../../vendor/schemastery devDependencies: '@deepseek-ai/cordis': specifier: workspace:~ @@ -4485,6 +4525,9 @@ importers: '@deepseek-ai/dsh-brand': specifier: workspace:* version: link:../../util/brand + '@deepseek-ai/dsh-client-config': + specifier: workspace:* + version: link:../config '@deepseek-ai/dsh-client-locale': specifier: workspace:* version: link:../locale @@ -4515,9 +4558,6 @@ importers: '@deepseek-ai/dsh-session': specifier: workspace:* version: link:../../core/session - '@deepseek-ai/schemastery': - specifier: link:../../../vendor/schemastery - version: link:../../../vendor/schemastery react: specifier: ^18.2.0 version: 18.3.1 @@ -4552,6 +4592,9 @@ importers: '@deepseek-ai/dsh-brand': specifier: workspace:* version: link:../../util/brand + '@deepseek-ai/dsh-client-config': + specifier: workspace:* + version: link:../config '@deepseek-ai/dsh-client-file-upload': specifier: workspace:* version: link:../file-upload @@ -11546,6 +11589,9 @@ importers: '@deepseek-ai/dsh-client-file-upload': specifier: workspace:* version: link:../../client/file-upload + '@deepseek-ai/dsh-client-hmr': + specifier: workspace:* + version: link:../../client/hmr '@deepseek-ai/dsh-client-locale': specifier: workspace:* version: link:../../client/locale @@ -16379,6 +16425,46 @@ importers: specifier: workspace:* version: link:../session-persistence + packages/session/session-persistence-sqlite: + dependencies: + '@deepseek-ai/dsh-brand': + specifier: workspace:* + version: link:../../util/brand + '@deepseek-ai/dsh-llm': + specifier: workspace:* + version: link:../../llm/llm + '@deepseek-ai/dsh-session-format': + specifier: workspace:* + version: link:../session-format + '@deepseek-ai/dsh-session-format-v3-to-v4': + specifier: workspace:* + version: link:../session-format-v3-to-v4 + '@deepseek-ai/dsh-session-persistence-jsonl': + specifier: workspace:* + version: link:../session-persistence-jsonl + '@deepseek-ai/node-addon-system': + specifier: workspace:~ + version: link:../../../native/system/packages/entry + koffi: + specifier: 3.1.1 + version: 3.1.1 + p-limit: + specifier: 7.3.3 + version: 7.3.3 + zod: + specifier: 4.6.6 + version: 4.6.6 + devDependencies: + '@deepseek-ai/cordis': + specifier: workspace:~ + version: link:../../../vendor/cordis + '@deepseek-ai/dsh-session': + specifier: workspace:* + version: link:../../core/session + '@deepseek-ai/dsh-session-persistence': + specifier: workspace:* + version: link:../session-persistence + packages/session/session-projection: dependencies: zod: @@ -18867,6 +18953,9 @@ importers: '@deepseek-ai/dsh-brand': specifier: workspace:* version: link:../../util/brand + '@deepseek-ai/dsh-client-config': + specifier: workspace:* + version: link:../../client/config '@deepseek-ai/dsh-client-connection': specifier: workspace:* version: link:../../client/connection diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index 6c9ea0f975..a68258f574 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -81,6 +81,7 @@ export const SERVICE_PAGE: Record = { shell: 'shell.md', shellEnv: 'shell.md', clientModules: 'client-modules.md', + config: 'client-modules.md', ptcRuntime: 'ptc-runtime.md', browserUse: 'browser-use.md', computerUse: 'computer-use.md', @@ -1076,6 +1077,7 @@ export const TYPE_LINK_EXEMPTIONS: Readonly> = { ConnectorAccountRegistration: 'Plugins page account registration is owned by packages/client/ui-connector-account/README.md', ConnectorAccountsView: 'registered account stream item is owned by packages/client/ui-connector-account/README.md', ConnectorOperationId: 'account operation id is owned by packages/client/ui-connector-account/README.md', + SyncedConfig: 'packages/client/config/README.md', ActionCardDecision: 'packages/experimental/action-cards/README.md', ActionCardKind: 'packages/experimental/action-cards/README.md', ActionCardResult: 'packages/experimental/action-cards/README.md', diff --git a/scripts/gen-doc-graphs.ts b/scripts/gen-doc-graphs.ts index 2d1630154e..4a7b078fa6 100644 --- a/scripts/gen-doc-graphs.ts +++ b/scripts/gen-doc-graphs.ts @@ -969,6 +969,15 @@ const SERVICE_ROLES: ServiceRole[] = [ consumers: ['harness-dev-context'], note: '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.', }, + { + key: 'config', + pkg: 'client-config', + title: 'Browser synced configuration lookup', + mode: 'service', + implementations: ['client-modules'], + consumers: [], + note: 'Types-only declaration; the client-modules plugin face provides the read-only lookup of each package\'s current synced Config.', + }, { key: 'clientModules', pkg: 'client-modules', diff --git a/scripts/no-unknown-casts.baseline.json b/scripts/no-unknown-casts.baseline.json index 5b255eabbd..f1ce3ad4af 100644 --- a/scripts/no-unknown-casts.baseline.json +++ b/scripts/no-unknown-casts.baseline.json @@ -370,12 +370,6 @@ "12a2d457945d43a02ab415318a8f6744ef620abd1fe272e12a164fa4ff476289": 1, "37d0e226122b7a3a4253e22583da5c77cc3690554dc959c74bf570589f3224fd": 1 }, - "packages/client/hmr/tests/node-half.client.spec.ts": { - "46197efe57255c9d92d64476470c89d0602c7333bf98ad75509bf43c1b357a3b": 1 - }, - "packages/client/hmr/tests/transport.client.spec.ts": { - "3f1a5cec801bec1f78158f48fca9f53657f85a8bb1f6ff4690fce56ab5ff8e98": 1 - }, "packages/client/locale/tests/apply.client.spec.ts": { "04984a2ce1486250236e638e0197da0a1a840855ed3975c59130a85358c7e5fe": 1 }, @@ -388,7 +382,6 @@ "packages/client/modules/tests/node-half.client.spec.ts": { "621628e4e895b24171e82d1b3fa3ecb12970e8eb0dfccab8bacc8c5784188a28": 2, "6c4ace8d135ab45685d0152eefb0f8156bbf95f66cefedd9a1a8da081d3cb180": 1, - "8eb8ea3592cbd4e828a33b2cbe2876089d3923738996fb2259ded563811a1a85": 1, "c4f0b7f87a16d26a1e4e7ef7a07991e789f0bbcfdbe2240a97fcd879668b5b3f": 1, "f549d88ac2b1db67fb33f18a024c116051ff83d3f8ad0433ba4ceedc679e9044": 2 }, diff --git a/scripts/plugin-entry-existing-exports.ts b/scripts/plugin-entry-existing-exports.ts index 4006abda41..28de7738ec 100644 --- a/scripts/plugin-entry-existing-exports.ts +++ b/scripts/plugin-entry-existing-exports.ts @@ -36,7 +36,6 @@ export const EXISTING_PLUGIN_ENTRY_EXPORTS = { 'API_PATH', 'CONNECT_PATH', 'Peer', 'RpcId', 'clientRequestSchema', 'rpcErrorSchema', 'rpcIdSchema', 'rpcMessageSchema', 'rpcResultSchema', 'serverResponseSchema', 'transportError', ], - '@deepseek-ai/dsh-client-hmr': ['EVENTS_ENDPOINT'], '@deepseek-ai/dsh-client-locale': ['LOCALE_IDS', 'LOCALE_PREFERENCE_FIELD', 'LOCALE_SETTINGS_NAMESPACE'], '@deepseek-ai/dsh-client-modules': ['bootInjections', 'orderByModuleGraph', 'stripClientSuffix'], '@deepseek-ai/dsh-client-ui-chat': [ diff --git a/scripts/product-package-policy.ts b/scripts/product-package-policy.ts index ffdaf762f4..5a72d4502f 100644 --- a/scripts/product-package-policy.ts +++ b/scripts/product-package-policy.ts @@ -32,6 +32,7 @@ export const PRODUCT_PACKAGE_POLICY: Readonly\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` 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" + "text": "\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` 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 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" } ], "source": { @@ -3200,7 +3218,7 @@ }, { "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." + "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 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." } ] }, @@ -3262,38 +3280,18 @@ } } }, - { - "method": "session.event", - "payload": { - "sessionId": "{{child-1}}", - "event": { - "type": "session/title", - "seq": 24, - "time": 0, - "data": { - "title": "Reply with exactly DIRECT_CHILD_OK and", - "messageSeqs": [ - 20 - ], - "source": { - "kind": "fallback" - } - } - } - } - }, { "method": "session.event", "payload": { "sessionId": "{{child-1}}", "event": { "type": "session-log-deepseek/delivery-accepted", - "seq": 25, + "seq": 24, "time": 0, "data": { "sessionId": "{{child-1}}", "sessionFormatVersion": 4, - "throughSeq": 24 + "throughSeq": 23 } } } @@ -3304,7 +3302,7 @@ "sessionId": "{{child-1}}", "event": { "type": "assistant/message", - "seq": 26, + "seq": 25, "time": 0, "data": { "turn": 2, @@ -3418,7 +3416,7 @@ "sessionId": "{{child-1}}", "event": { "type": "step/end", - "seq": 27, + "seq": 26, "time": 0, "data": { "turn": 2, @@ -3433,7 +3431,7 @@ "sessionId": "{{child-1}}", "event": { "type": "turn/end", - "seq": 28, + "seq": 27, "time": 0, "data": { "turn": 2, @@ -3788,13 +3786,19 @@ "inserted": [ { "content": [ + { + "type": "text", + "text": "Agent lead sent a message: " + }, { "type": "text", "text": "Reply with exactly WORKFLOW_CHILD_OK and nothing else." } ], "source": { - "kind": "user" + "kind": "agent-message", + "form": "relay", + "senderSessionId": "{{parent}}" }, "role": "user", "id": "{{messageId}}" @@ -3988,13 +3992,19 @@ "inserted": [ { "content": [ + { + "type": "text", + "text": "Agent lead sent a message: " + }, { "type": "text", "text": "Reply with exactly WORKFLOW_CHILD_OK and nothing else." } ], "source": { - "kind": "user" + "kind": "agent-message", + "form": "relay", + "senderSessionId": "{{parent}}" }, "role": "user", "id": "{{messageId}}" @@ -4165,13 +4175,19 @@ "time": 0, "data": { "content": [ + { + "type": "text", + "text": "Agent lead sent a message: " + }, { "type": "text", "text": "Reply with exactly WORKFLOW_CHILD_OK and nothing else." } ], "source": { - "kind": "user" + "kind": "agent-message", + "form": "relay", + "senderSessionId": "{{parent}}" }, "role": "user", "id": "{{messageId}}" @@ -4192,7 +4208,7 @@ "content": [ { "type": "text", - "text": "\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` 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" + "text": "\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` 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 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" } ], "source": { @@ -4217,7 +4233,7 @@ }, { "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." + "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 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." } ] }, @@ -4279,38 +4295,18 @@ } } }, - { - "method": "session.event", - "payload": { - "sessionId": "{{child-2}}", - "event": { - "type": "session/title", - "seq": 24, - "time": 0, - "data": { - "title": "Reply with exactly WORKFLOW_CHILD_OK and", - "messageSeqs": [ - 20 - ], - "source": { - "kind": "fallback" - } - } - } - } - }, { "method": "session.event", "payload": { "sessionId": "{{child-2}}", "event": { "type": "session-log-deepseek/delivery-accepted", - "seq": 25, + "seq": 24, "time": 0, "data": { "sessionId": "{{child-2}}", "sessionFormatVersion": 4, - "throughSeq": 24 + "throughSeq": 23 } } } @@ -4321,7 +4317,7 @@ "sessionId": "{{child-2}}", "event": { "type": "assistant/message", - "seq": 26, + "seq": 25, "time": 0, "data": { "turn": 2, @@ -4435,7 +4431,7 @@ "sessionId": "{{child-2}}", "event": { "type": "step/end", - "seq": 27, + "seq": 26, "time": 0, "data": { "turn": 2, @@ -4450,7 +4446,7 @@ "sessionId": "{{child-2}}", "event": { "type": "turn/end", - "seq": 28, + "seq": 27, "time": 0, "data": { "turn": 2, diff --git a/scripts/snapshots/python-sdk-single-exe/advanced/session.1.v4.jsonl b/scripts/snapshots/python-sdk-single-exe/advanced/session.1.v4.jsonl index 0559fac263..fd000a7158 100644 --- a/scripts/snapshots/python-sdk-single-exe/advanced/session.1.v4.jsonl +++ b/scripts/snapshots/python-sdk-single-exe/advanced/session.1.v4.jsonl @@ -4,14 +4,14 @@ {"type":"approval/policy","data":{"policy":"never","source":"delegation"}} {"type":"permission/preset","data":{"preset":"danger-full-access"}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed."}],"source":{"kind":"plugin:serial-created-fixture"}}]}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly DIRECT_CHILD_OK and nothing else."},{"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":"{{messageId}}"}]}} +{"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 DIRECT_CHILD_OK and nothing else."},{"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":"{{parent}}"},"role":"user","id":"{{messageId}}"}]}} {"type":"turn/start","data":{"turn":1}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Cancellation checkpoint probe."}],"source":{"kind":"plugin:serial-created-fixture"}}]}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[],"outcome":"canceled"}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed."}],"source":{"kind":"plugin:serial-created-fixture"}}]}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly DIRECT_CHILD_OK and nothing else."},{"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":"{{messageId}}"}]}} +{"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 DIRECT_CHILD_OK and nothing else."},{"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":"{{parent}}"},"role":"user","id":"{{messageId}}"}]}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"aborted","reason":{"kind":"user"}}}} {"type":"turn/start","data":{"turn":2}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} @@ -19,12 +19,11 @@ {"type":"step/start","data":{"turn":2,"step":1}} {"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{messageId}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed."}],"source":{"kind":"plugin:serial-created-fixture"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly DIRECT_CHILD_OK and nothing else."},{"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":"{{messageId}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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":"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":"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":"{{messageId}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Reply with exactly DIRECT_CHILD_OK and nothing else."},{"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":"{{parent}}"},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` 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 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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":"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":"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 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":"{{messageId}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","reasoningEffort":"high","maxTokens":256000},"adapterDefaults":{"maxTokens":true},"tools":["cordis_inspect","job_kill","job_list","job_output","snapshot_double","subagent","workflow","working_directory"]},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"smoke-model","contextWindow":1000000}} -{"type":"session/title","data":{"title":"Reply with exactly DIRECT_CHILD_OK and","messageSeqs":[20],"source":{"kind":"fallback"}}} -{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{child-1}}","sessionFormatVersion":4,"throughSeq":24}} +{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{child-1}}","sessionFormatVersion":4,"throughSeq":23}} {"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"DIRECT_CHILD_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model","replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"smoke-model"},"blocks":[{"type":"text"}]}},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["DIRECT_CHILD_OK"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DIRECT_CHILD_OK"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"},"replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"smoke-model"},"blocks":[{"type":"text"}]}}}]},"surfaceOp":"append"} {"type":"step/end","data":{"turn":2,"step":1}} {"type":"turn/end","data":{"turn":2,"reason":{"kind":"completed"}}} diff --git a/scripts/snapshots/python-sdk-single-exe/advanced/session.2.v4.jsonl b/scripts/snapshots/python-sdk-single-exe/advanced/session.2.v4.jsonl index 31a554cecc..0e447b865f 100644 --- a/scripts/snapshots/python-sdk-single-exe/advanced/session.2.v4.jsonl +++ b/scripts/snapshots/python-sdk-single-exe/advanced/session.2.v4.jsonl @@ -4,14 +4,14 @@ {"type":"approval/policy","data":{"policy":"never","source":"delegation"}} {"type":"permission/preset","data":{"preset":"danger-full-access"}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed."}],"source":{"kind":"plugin:serial-created-fixture"}}]}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly WORKFLOW_CHILD_OK and nothing else."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"}]}} +{"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 WORKFLOW_CHILD_OK and nothing else."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{parent}}"},"role":"user","id":"{{messageId}}"}]}} {"type":"turn/start","data":{"turn":1}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Cancellation checkpoint probe."}],"source":{"kind":"plugin:serial-created-fixture"}}]}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[],"outcome":"canceled"}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed."}],"source":{"kind":"plugin:serial-created-fixture"}}]}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly WORKFLOW_CHILD_OK and nothing else."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"}]}} +{"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 WORKFLOW_CHILD_OK and nothing else."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{parent}}"},"role":"user","id":"{{messageId}}"}]}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"aborted","reason":{"kind":"user"}}}} {"type":"turn/start","data":{"turn":2}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} @@ -19,12 +19,11 @@ {"type":"step/start","data":{"turn":2,"step":1}} {"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{messageId}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed."}],"source":{"kind":"plugin:serial-created-fixture"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly WORKFLOW_CHILD_OK and nothing else."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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":"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":"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":"{{messageId}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Reply with exactly WORKFLOW_CHILD_OK and nothing else."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{parent}}"},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` 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 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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":"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":"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 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":"{{messageId}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","reasoningEffort":"high","maxTokens":256000},"adapterDefaults":{"maxTokens":true},"tools":["cordis_inspect","job_kill","job_list","job_output","snapshot_double","subagent","workflow","working_directory"]},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"smoke-model","contextWindow":1000000}} -{"type":"session/title","data":{"title":"Reply with exactly WORKFLOW_CHILD_OK and","messageSeqs":[20],"source":{"kind":"fallback"}}} -{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{child-2}}","sessionFormatVersion":4,"throughSeq":24}} +{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{child-2}}","sessionFormatVersion":4,"throughSeq":23}} {"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"WORKFLOW_CHILD_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model","replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"smoke-model"},"blocks":[{"type":"text"}]}},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["WORKFLOW_CHILD_OK"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"WORKFLOW_CHILD_OK"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"},"replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"smoke-model"},"blocks":[{"type":"text"}]}}}]},"surfaceOp":"append"} {"type":"step/end","data":{"turn":2,"step":1}} {"type":"turn/end","data":{"turn":2,"reason":{"kind":"completed"}}} diff --git a/scripts/verify-package-readme-model-experience.ts b/scripts/verify-package-readme-model-experience.ts index da98505ce9..6816992ff0 100644 --- a/scripts/verify-package-readme-model-experience.ts +++ b/scripts/verify-package-readme-model-experience.ts @@ -50,6 +50,7 @@ const NO_MODEL_EXPERIENCE_SECTION: Readonly> = { * blocks. A package moves on or off this list with its context behavior. */ const SENTENCE_MODEL_EXPERIENCE: Readonly> = { + 'packages/client/config': { kind: 'none', reason: 'Browser configuration types register nothing and add no model input.' }, 'packages/client/script-realm': { kind: 'none', reason: 'Optional browser execution-provider registration contributes no model input.' }, 'packages/client/script-realm-iframe': { kind: 'none', reason: 'Same-origin browser script environments contribute no model input.' }, 'packages/client/ui-context-menu': { kind: 'none', reason: 'Client menu presentation and contributed callbacks add no model input.' }, diff --git a/scripts/verify-product-use.ts b/scripts/verify-product-use.ts index d4a1f0a73b..f6472656b9 100644 --- a/scripts/verify-product-use.ts +++ b/scripts/verify-product-use.ts @@ -261,7 +261,7 @@ function validCategory(path: string, category: ProductPackagePolicy['category']) case 'sdk': return path === 'packages/sdk/client' case 'build': return path === 'packages/typert/generator' case 'web-distribution': return path === 'packages/client/web' || path === 'packages/client/ui-dockkit' - case 'declarations': return path === 'packages/util/package-manifest' + case 'declarations': return path === 'packages/util/package-manifest' || path === 'packages/client/config' default: return assertNever(category) } } diff --git a/snapshots/sdk/command-attachments/tool-schemas.expected.json b/snapshots/sdk/command-attachments/tool-schemas.expected.json index 85bc6d2cf7..f43c7ed7dd 100644 --- a/snapshots/sdk/command-attachments/tool-schemas.expected.json +++ b/snapshots/sdk/command-attachments/tool-schemas.expected.json @@ -328,7 +328,7 @@ }, { "name": "plugin_manager", - "description": "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.", + "description": "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.", "parameters": { "type": "object", "properties": { diff --git a/snapshots/sdk/cua-run-code/tool-schemas.expected.json b/snapshots/sdk/cua-run-code/tool-schemas.expected.json index ab2f74e916..2895bc9372 100644 --- a/snapshots/sdk/cua-run-code/tool-schemas.expected.json +++ b/snapshots/sdk/cua-run-code/tool-schemas.expected.json @@ -158,7 +158,7 @@ }, { "name": "cua_run_code", - "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.", "parameters": { "type": "object", "properties": { @@ -349,7 +349,7 @@ }, { "name": "plugin_manager", - "description": "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.", + "description": "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.", "parameters": { "type": "object", "properties": { diff --git a/snapshots/sdk/desktop-context/tool-schemas.expected.json b/snapshots/sdk/desktop-context/tool-schemas.expected.json index 1209423422..b63e7eb817 100644 --- a/snapshots/sdk/desktop-context/tool-schemas.expected.json +++ b/snapshots/sdk/desktop-context/tool-schemas.expected.json @@ -312,7 +312,7 @@ }, { "name": "plugin_manager", - "description": "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.", + "description": "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.", "parameters": { "type": "object", "properties": { diff --git a/snapshots/sdk/desktop-ptc-context/system-prompt.expected.md b/snapshots/sdk/desktop-ptc-context/system-prompt.expected.md index c73f06b4db..cb1c9d2ec9 100644 --- a/snapshots/sdk/desktop-ptc-context/system-prompt.expected.md +++ b/snapshots/sdk/desktop-ptc-context/system-prompt.expected.md @@ -166,7 +166,7 @@ interface ToolArgsMap { } & Record; /** List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry names, descriptions, and status. A descendant's name is its path from the root, such as reviewer/checker. You can message any other agent in the subagent tree. running means it is working; inactive means no turn is executing; it does not indicate task completion, success, or failure. corrupt, unsupported, or unavailable means this row's own descendants could not be read; the row itself is still a member you can message. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation. */ list_agents: Record; - /** 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. */ plugin_manager: { /** Management operation. */ action: "list_plugins" | "list_bundles" | "set_plugin" | "set_bundle" | "install_bundle" | "remove_bundle" | "list_version_exemptions" | "set_version_exemption"; diff --git a/snapshots/sdk/plan-review/tool-schemas.expected.json b/snapshots/sdk/plan-review/tool-schemas.expected.json index 07f6cdbbe1..6a56497a36 100644 --- a/snapshots/sdk/plan-review/tool-schemas.expected.json +++ b/snapshots/sdk/plan-review/tool-schemas.expected.json @@ -312,7 +312,7 @@ }, { "name": "plugin_manager", - "description": "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.", + "description": "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.", "parameters": { "type": "object", "properties": { @@ -1253,7 +1253,7 @@ }, { "name": "plugin_manager", - "description": "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.", + "description": "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.", "parameters": { "type": "object", "properties": { @@ -2193,7 +2193,7 @@ }, { "name": "plugin_manager", - "description": "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.", + "description": "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.", "parameters": { "type": "object", "properties": { @@ -3133,7 +3133,7 @@ }, { "name": "plugin_manager", - "description": "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.", + "description": "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.", "parameters": { "type": "object", "properties": { @@ -4073,7 +4073,7 @@ }, { "name": "plugin_manager", - "description": "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.", + "description": "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.", "parameters": { "type": "object", "properties": { diff --git a/snapshots/sdk/subagent-activation-limit/session.1.v4.jsonl b/snapshots/sdk/subagent-activation-limit/session.1.v4.jsonl index 7268d60b9b..0afeab5fdc 100644 --- a/snapshots/sdk/subagent-activation-limit/session.1.v4.jsonl +++ b/snapshots/sdk/subagent-activation-limit/session.1.v4.jsonl @@ -3,17 +3,16 @@ {"type":"sandbox/mode","data":{"mode":"danger-full-access","source":"delegation"}} {"type":"approval/policy","data":{"policy":"never","source":"delegation"}} {"type":"permission/preset","data":{"preset":"danger-full-access"}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly CHILD_OK."},{"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":"{{message:12}}"}]}} +{"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_OK."},{"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":"{{session:1}}"},"role":"user","id":"{{message:12}}"}]}} {"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":"{{message:13}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly CHILD_OK."},{"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":"{{message:12}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", 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":"{{message:14}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Reply with exactly CHILD_OK."},{"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":"{{session:1}}"},"role":"user","id":"{{message:12}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", 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 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", 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 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":"{{message:14}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:15}}"},"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_OK. Your","messageSeqs":[9],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"CHILD_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:16}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1793796120944,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1793796120944,"index":0,"dt":[],"texts":["CHILD_OK"]},{"type":"chunk","time":1793796120944,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"CHILD_OK"}}},{"type":"chunk","time":1793796120944,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1793796120944,"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"}}} diff --git a/snapshots/sdk/subagent-continuable-inheritance/session.1.v4.jsonl b/snapshots/sdk/subagent-continuable-inheritance/session.1.v4.jsonl index 29891b60f4..6a486ae1ea 100644 --- a/snapshots/sdk/subagent-continuable-inheritance/session.1.v4.jsonl +++ b/snapshots/sdk/subagent-continuable-inheritance/session.1.v4.jsonl @@ -2,17 +2,16 @@ {"type":"subagent/descriptor","data":{"version":3,"mode":"continuable","provider":"spawn","label":"Reply with CHILD_OK","agentProvider":"deepseek-official","agentModel":"deepseek-v4-flash"}} {"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":"Reply with exactly the word CHILD_OK and nothing else."},{"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":"{{message:9}}"}]}} +{"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 the word CHILD_OK and nothing else."},{"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":"{{session:1}}"},"role":"user","id":"{{message:9}}"}]}} {"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":"{{message:10}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly the word CHILD_OK and nothing else."},{"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":"{{message:9}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\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: \"\", 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"}],"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: \"\", 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":"{{message:11}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Reply with exactly the word CHILD_OK and nothing else."},{"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":"{{session:1}}"},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\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: \"\", 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 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"}],"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: \"\", 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 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":"{{message:11}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:12}}"},"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 the word","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"CHILD_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:13}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1793796122485,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1793796122485,"index":0,"dt":[],"texts":["CHILD_OK"]},{"type":"chunk","time":1793796122485,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"CHILD_OK"}}},{"type":"chunk","time":1793796122485,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1793796122485,"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"}}} diff --git a/snapshots/sdk/subagent-continuable/session.1.v4.jsonl b/snapshots/sdk/subagent-continuable/session.1.v4.jsonl index 49eb1a6479..f259bf1b3b 100644 --- a/snapshots/sdk/subagent-continuable/session.1.v4.jsonl +++ b/snapshots/sdk/subagent-continuable/session.1.v4.jsonl @@ -3,7 +3,7 @@ {"type":"sandbox/mode","data":{"mode":"danger-full-access","source":"delegation"}} {"type":"approval/policy","data":{"policy":"never","source":"delegation"}} {"type":"permission/preset","data":{"preset":"danger-full-access"}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly the word CHILD_OK and nothing else."},{"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":"{{message:16}}"}]}} +{"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 the word CHILD_OK and nothing else."},{"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":"{{session:1}}"},"role":"user","id":"{{message:16}}"}]}} {"type":"turn/start","data":{"turn":1}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Now reply with exactly SECOND_OK."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{session:1}}"},"role":"user","id":"{{message:17}}"}]}} @@ -11,12 +11,11 @@ {"type":"agent/inbox/spliced","data":{"target":"next-step","start":2,"inserted":[{"content":[{"type":"text","text":"Human priority: keep the requested exact reply."}],"source":{"kind":"user","rpcId":"{{rpc:1}}"},"role":"user","id":"{{message:19}}"}]}} {"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":"{{message:20}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly the word CHILD_OK and nothing else."},{"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":"{{message:16}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", 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":"{{message:21}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Reply with exactly the word CHILD_OK and nothing else."},{"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":"{{session:1}}"},"role":"user","id":"{{message:16}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", 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 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", 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 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":"{{message:21}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:22}}"},"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 the word","messageSeqs":[12],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"CHILD_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:23}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1793796121671,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1793796121671,"index":0,"dt":[],"texts":["CHILD_OK"]},{"type":"chunk","time":1793796121671,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"CHILD_OK"}}},{"type":"chunk","time":1793796121671,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1793796121671,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":3,"inserted":[]}} @@ -24,6 +23,7 @@ {"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Now reply with exactly SECOND_OK."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{session:1}}"},"role":"user","id":"{{message:17}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Now reply with exactly THIRD_OK."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{session:1}}"},"role":"user","id":"{{message:18}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Human priority: keep the requested exact reply."}],"source":{"kind":"user","rpcId":"{{rpc:1}}"},"role":"user","id":"{{message:19}}"},"surfaceOp":"append"} +{"type":"session/title","data":{"title":"Human priority: keep the requested","messageSeqs":[23],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"reasoning","text":"I will return the requested exact reply."},{"type":"text","text":"SECOND_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:24}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1793796121684,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1793796121684,"index":0,"dt":[],"texts":["I will return the requested exact reply."]},{"type":"chunk","time":1793796121684,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"I will return the requested exact reply."}}},{"type":"chunk","time":1793796121684,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1793796121684,"index":1,"dt":[],"texts":["SECOND_OK"]},{"type":"chunk","time":1793796121684,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"SECOND_OK"}}},{"type":"chunk","time":1793796121684,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1793796121684,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":2}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/snapshots/sdk/subagent-fork-in-process/session.1.v4.jsonl b/snapshots/sdk/subagent-fork-in-process/session.1.v4.jsonl index a4f658304c..52088deb9c 100644 --- a/snapshots/sdk/subagent-fork-in-process/session.1.v4.jsonl +++ b/snapshots/sdk/subagent-fork-in-process/session.1.v4.jsonl @@ -21,12 +21,12 @@ {"type":"sandbox/mode","data":{"mode":"danger-full-access","source":"delegation"}} {"type":"approval/policy","data":{"policy":"never","source":"delegation"}} {"type":"permission/preset","data":{"preset":"danger-full-access"}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"What is the project codeword mentioned earlier in this conversation? Reply with exactly that one word and nothing else."},{"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":"{{message:11}}"}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"What is the project codeword mentioned earlier in this conversation? Reply with exactly that one word and nothing else."},{"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":"{{session:1}}"},"role":"user","id":"{{message:11}}"}]}} {"type":"turn/start","data":{"turn":2}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":2,"step":1}} -{"type":"user/message","data":{"content":[{"type":"text","text":"What is the project codeword mentioned earlier in this conversation? Reply with exactly that one word and nothing else."},{"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":"{{message:11}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session. It replaces earlier versions of this context, including any retained in conversation summaries.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", 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":"{{message:12}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"What is the project codeword mentioned earlier in this conversation? Reply with exactly that one word and nothing else."},{"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":"{{session:1}}"},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session. It replaces earlier versions of this context, including any retained in conversation summaries.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", 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 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", 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 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":"{{message:12}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"resume"}} {"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user asked me to remember the project codeword \"MARMALADE\" and now they're asking what it is. I should just reply with that word."},{"type":"text","text":"MARMALADE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:13}}"},"usage":{"inputTokens":97,"outputTokens":39,"cacheReadTokens":2816,"reasoningTokens":34},"stream":[{"type":"chunk","time":1793796126253,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1793796126253,"index":0,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["The"," user"," asked"," me"," to"," remember"," the"," project"," cod","ew","ord"," \"","M","ARM","AL","ADE","\""," and"," now"," they","'re"," asking"," what"," it"," is","."," I"," should"," just"," reply"," with"," that"," word","."]},{"type":"chunk","time":1793796126253,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1793796126253,"index":1,"dt":[0,0,0],"texts":["M","ARM","AL","ADE"]},{"type":"chunk","time":1793796126253,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user asked me to remember the project codeword \"MARMALADE\" and now they're asking what it is. I should just reply with that word."}}},{"type":"chunk","time":1793796126253,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"MARMALADE"}}},{"type":"chunk","time":1793796126253,"chunk":{"type":"usage","usage":{"inputTokens":97,"outputTokens":39,"cacheReadTokens":2816,"reasoningTokens":34}}},{"type":"chunk","time":1793796126253,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} {"type":"step/end","data":{"turn":2,"step":1}} diff --git a/snapshots/sdk/subagent-list-agents/session.1.v4.jsonl b/snapshots/sdk/subagent-list-agents/session.1.v4.jsonl index 3f07ed2107..e86e8de9ff 100644 --- a/snapshots/sdk/subagent-list-agents/session.1.v4.jsonl +++ b/snapshots/sdk/subagent-list-agents/session.1.v4.jsonl @@ -3,17 +3,16 @@ {"type":"sandbox/mode","data":{"mode":"danger-full-access","source":"delegation"}} {"type":"approval/policy","data":{"policy":"never","source":"delegation"}} {"type":"permission/preset","data":{"preset":"danger-full-access"}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly the word CHILD_OK and nothing else."},{"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":"{{message:14}}"}]}} +{"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 the word CHILD_OK and nothing else."},{"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":"{{session:1}}"},"role":"user","id":"{{message:14}}"}]}} {"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":"{{message:15}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly the word CHILD_OK and nothing else."},{"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":"{{message:14}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", 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":"{{message:16}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Reply with exactly the word CHILD_OK and nothing else."},{"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":"{{session:1}}"},"role":"user","id":"{{message:14}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", 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 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", 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 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":"{{message:16}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:17}}"},"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 the word","messageSeqs":[9],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"CHILD_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:18}}"},"usage":{"inputTokens":10,"outputTokens":3},"stream":[{"type":"chunk","time":1793796126903,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1793796126903,"index":0,"dt":[],"texts":["CHILD_OK"]},{"type":"chunk","time":1793796126903,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"CHILD_OK"}}},{"type":"chunk","time":1793796126903,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":3}}},{"type":"chunk","time":1793796126903,"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"}}} diff --git a/snapshots/sdk/subagent-mixed/session.1.v4.jsonl b/snapshots/sdk/subagent-mixed/session.1.v4.jsonl index 70de7c510f..49c402e67f 100644 --- a/snapshots/sdk/subagent-mixed/session.1.v4.jsonl +++ b/snapshots/sdk/subagent-mixed/session.1.v4.jsonl @@ -3,17 +3,16 @@ {"type":"sandbox/mode","data":{"mode":"danger-full-access","source":"delegation"}} {"type":"approval/policy","data":{"policy":"never","source":"delegation"}} {"type":"permission/preset","data":{"preset":"danger-full-access"}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly the word ALPHA and nothing else."},{"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":"{{message:14}}"}]}} +{"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 the word ALPHA and nothing else."},{"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":"{{session:1}}"},"role":"user","id":"{{message:14}}"}]}} {"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":"{{message:15}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly the word ALPHA and nothing else."},{"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":"{{message:14}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", 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":"{{message:16}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Reply with exactly the word ALPHA and nothing else."},{"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":"{{session:1}}"},"role":"user","id":"{{message:14}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", 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 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", 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 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":"{{message:16}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:17}}"},"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 the word","messageSeqs":[9],"source":{"kind":"fallback"}}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user asked me to reply with exactly the word \"ALPHA\" and nothing else."},{"type":"text","text":"ALPHA"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:18}}"},"usage":{"inputTokens":48,"outputTokens":23,"cacheReadTokens":2816,"reasoningTokens":19},"stream":[{"type":"chunk","time":1793796127633,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1793796127633,"index":0,"dt":[0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["The"," user"," asked"," me"," to"," reply"," with"," exactly"," the"," word"," \"","AL","P","HA","\""," and"," nothing"," else","."]},{"type":"chunk","time":1793796127634,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1793796127634,"index":1,"dt":[0,0],"texts":["AL","P","HA"]},{"type":"chunk","time":1793796127634,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user asked me to reply with exactly the word \"ALPHA\" and nothing else."}}},{"type":"chunk","time":1793796127634,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"ALPHA"}}},{"type":"chunk","time":1793796127634,"chunk":{"type":"usage","usage":{"inputTokens":48,"outputTokens":23,"cacheReadTokens":2816,"reasoningTokens":19}}},{"type":"chunk","time":1793796127634,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user asked me to reply with exactly the word \"ALPHA\" and nothing else."},{"type":"text","text":"ALPHA"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:18}}"},"usage":{"inputTokens":48,"outputTokens":23,"cacheReadTokens":2816,"reasoningTokens":19},"stream":[{"type":"chunk","time":1794555248339,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1794555248339,"index":0,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["The"," user"," asked"," me"," to"," reply"," with"," exactly"," the"," word"," \"","AL","P","HA","\""," and"," nothing"," else","."]},{"type":"chunk","time":1794555248339,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1794555248339,"index":1,"dt":[0,0],"texts":["AL","P","HA"]},{"type":"chunk","time":1794555248339,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user asked me to reply with exactly the word \"ALPHA\" and nothing else."}}},{"type":"chunk","time":1794555248339,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"ALPHA"}}},{"type":"chunk","time":1794555248339,"chunk":{"type":"usage","usage":{"inputTokens":48,"outputTokens":23,"cacheReadTokens":2816,"reasoningTokens":19}}},{"type":"chunk","time":1794555248339,"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"}}} diff --git a/snapshots/sdk/subagent-mixed/session.2.v4.jsonl b/snapshots/sdk/subagent-mixed/session.2.v4.jsonl index a88ecf5174..9858640ac2 100644 --- a/snapshots/sdk/subagent-mixed/session.2.v4.jsonl +++ b/snapshots/sdk/subagent-mixed/session.2.v4.jsonl @@ -21,12 +21,12 @@ {"type":"sandbox/mode","data":{"mode":"danger-full-access","source":"delegation"}} {"type":"approval/policy","data":{"policy":"never","source":"delegation"}} {"type":"permission/preset","data":{"preset":"danger-full-access"}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"What is the project codeword mentioned earlier in this conversation? Reply with exactly that one word and nothing else."},{"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":"{{message:19}}"}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"What is the project codeword mentioned earlier in this conversation? Reply with exactly that one word and nothing else."},{"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":"{{session:1}}"},"role":"user","id":"{{message:19}}"}]}} {"type":"turn/start","data":{"turn":2}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":2,"step":1}} -{"type":"user/message","data":{"content":[{"type":"text","text":"What is the project codeword mentioned earlier in this conversation? Reply with exactly that one word and nothing else."},{"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":"{{message:19}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session. It replaces earlier versions of this context, including any retained in conversation summaries.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", 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":"{{message:20}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"What is the project codeword mentioned earlier in this conversation? Reply with exactly that one word and nothing else."},{"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":"{{session:1}}"},"role":"user","id":"{{message:19}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session. It replaces earlier versions of this context, including any retained in conversation summaries.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", 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 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", 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 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":"{{message:20}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"resume"}} {"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user is asking me to recall the project codeword that was mentioned earlier in the conversation. I was told to remember it: SAFFRON."},{"type":"text","text":"SAFFRON"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:21}}"},"usage":{"inputTokens":95,"outputTokens":35,"cacheReadTokens":2816,"reasoningTokens":31},"stream":[{"type":"chunk","time":1793796127698,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1793796127698,"index":0,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["The"," user"," is"," asking"," me"," to"," recall"," the"," project"," cod","ew","ord"," that"," was"," mentioned"," earlier"," in"," the"," conversation","."," I"," was"," told"," to"," remember"," it",":"," SA","FF","RON","."]},{"type":"chunk","time":1793796127698,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1793796127698,"index":1,"dt":[0,0],"texts":["SA","FF","RON"]},{"type":"chunk","time":1793796127698,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user is asking me to recall the project codeword that was mentioned earlier in the conversation. I was told to remember it: SAFFRON."}}},{"type":"chunk","time":1793796127698,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"SAFFRON"}}},{"type":"chunk","time":1793796127698,"chunk":{"type":"usage","usage":{"inputTokens":95,"outputTokens":35,"cacheReadTokens":2816,"reasoningTokens":31}}},{"type":"chunk","time":1793796127698,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} {"type":"step/end","data":{"turn":2,"step":1}} diff --git a/snapshots/sdk/subagent-send-message/session.1.v4.jsonl b/snapshots/sdk/subagent-send-message/session.1.v4.jsonl index 5c9f47fad3..5ad02567d1 100644 --- a/snapshots/sdk/subagent-send-message/session.1.v4.jsonl +++ b/snapshots/sdk/subagent-send-message/session.1.v4.jsonl @@ -3,20 +3,19 @@ {"type":"sandbox/mode","data":{"mode":"danger-full-access","source":"delegation"}} {"type":"approval/policy","data":{"policy":"never","source":"delegation"}} {"type":"permission/preset","data":{"preset":"danger-full-access"}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Send exactly CHILD_MESSAGE_OK to your parent with send_message, then stop."},{"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":"{{message:13}}"}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Send exactly CHILD_MESSAGE_OK to your parent with send_message, then stop."},{"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":"{{session:1}}"},"role":"user","id":"{{message:13}}"}]}} {"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":"{{message:14}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Send exactly CHILD_MESSAGE_OK to your parent with send_message, then stop."},{"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":"{{message:13}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", 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":"{{message:15}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Send exactly CHILD_MESSAGE_OK to your parent with send_message, then stop."},{"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":"{{session:1}}"},"role":"user","id":"{{message:13}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", 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 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", 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 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":"{{message:15}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:16}}"},"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":"Send exactly CHILD_MESSAGE_OK to your","messageSeqs":[9],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_send_message_1","name":"send_message","arguments":"{\"agent\": \"lead\", \"message\": \"CHILD_MESSAGE_OK\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:17}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1793796128438,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1793796128438,"index":0,"dt":[],"id":"call_send_message_1","name":"send_message","args":["{\"agent\": \"lead\", \"message\": \"CHILD_MESSAGE_OK\"}"]},{"type":"chunk","time":1793796128438,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_send_message_1","name":"send_message","arguments":"{\"agent\": \"lead\", \"message\": \"CHILD_MESSAGE_OK\"}"}}},{"type":"chunk","time":1793796128438,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1793796128438,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_send_message_1","name":"send_message","arguments":"{\"agent\": \"lead\", \"message\": \"CHILD_MESSAGE_OK\"}"}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_send_message_1"},"toolCallId":"call_send_message_1","content":[{"type":"text","text":"message delivered to agent lead"}],"isError":false,"id":"{{message:18}}"}},"sourceEventSeqs":[16],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_send_message_1"},"toolCallId":"call_send_message_1","content":[{"type":"text","text":"message delivered to agent lead"}],"isError":false,"id":"{{message:18}}"}},"sourceEventSeqs":[15],"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":"Message sent."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:19}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1793796128455,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1793796128455,"index":0,"dt":[],"texts":["Message sent."]},{"type":"chunk","time":1793796128455,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Message sent."}}},{"type":"chunk","time":1793796128455,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1793796128455,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} diff --git a/snapshots/sdk/subagent-spawn-in-process/notifications.expected.jsonl b/snapshots/sdk/subagent-spawn-in-process/notifications.expected.jsonl index d9b754e40a..ef57c9dd43 100644 --- a/snapshots/sdk/subagent-spawn-in-process/notifications.expected.jsonl +++ b/snapshots/sdk/subagent-spawn-in-process/notifications.expected.jsonl @@ -16,22 +16,21 @@ {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"subagent/descriptor","seq":0,"time":0,"data":{"version":3,"mode":"continuable","provider":"spawn","label":"echo probe","agentProvider":"deepseek-official","agentModel":"deepseek-v4-flash"}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"sandbox/mode","seq":1,"time":0,"data":{"mode":"workspace-write","source":"delegation"}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"approval/policy","seq":2,"time":0,"data":{"policy":"never","source":"delegation"}}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"agent/inbox/spliced","seq":3,"time":0,"data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly: child answer 42."},{"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}}"}]}}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"agent/inbox/spliced","seq":3,"time":0,"data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Reply with exactly: child answer 42."},{"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}}"}]}}}} {"method":"session.status","params":{"sessionId":"{{sessionId}}","status":"running"}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"turn/start","seq":4,"time":0,"data":{"turn":1}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"agent/inbox/spliced","seq":5,"time":0,"data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"subagent/catalog","seq":16,"time":0,"data":{"version":3,"childId":"{{sessionId}}","childCreatedAt":0,"mode":"continuable","label":"echo probe","name":"agent-1"}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"step/start","seq":6,"time":0,"data":{"turn":1,"step":1}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"system/message","seq":7,"time":0,"data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"user/message","seq":8,"time":0,"data":{"content":[{"type":"text","text":"Reply with exactly: child answer 42."},{"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"}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"user/message","seq":9,"time":0,"data":{"content":[{"type":"text","text":"\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: \"\", 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"}],"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: \"\", 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"}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"user/message","seq":8,"time":0,"data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Reply with exactly: child answer 42."},{"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"}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"user/message","seq":9,"time":0,"data":{"content":[{"type":"text","text":"\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: \"\", 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 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"}],"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: \"\", 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 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"}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"user/message","seq":10,"time":0,"data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"request/header","seq":11,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"request/context","seq":12,"time":0,"data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"session/title","seq":13,"time":0,"data":{"title":"Reply with exactly: child answer","messageSeqs":[8],"source":{"kind":"fallback"}}}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/message","seq":14,"time":0,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"child answer 42."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["child answer 42."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"child answer 42."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"step/end","seq":15,"time":0,"data":{"turn":1,"step":1}}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"turn/end","seq":16,"time":0,"data":{"turn":1,"reason":{"kind":"completed"}}}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/message","seq":13,"time":0,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"child answer 42."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["child answer 42."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"child answer 42."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"step/end","seq":14,"time":0,"data":{"turn":1,"step":1}}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"turn/end","seq":15,"time":0,"data":{"turn":1,"reason":{"kind":"completed"}}}}} {"method":"session.status","params":{"sessionId":"{{sessionId}}","status":"idle"}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"agent/inbox/spliced","seq":17,"time":0,"data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"Background subagent agent-1 finished and will do no further work unless you send it more."},{"type":"text","text":"Its closing message:"},{"type":"text","text":"child answer 42."}],"source":{"kind":"subagent-settled","form":"notice","summary":"Background subagent agent-1 finished and will do no further work unless you send it more.","stopReason":"completed","senderSessionId":"{{sessionId}}"},"role":"user","id":"{{sessionId}}"}]}}}} {"method":"subagent.finished","params":{"provider":"spawn","agentId":"{{sessionId}}","parentSessionId":"{{sessionId}}","childSessionId":"{{sessionId}}","status":"ok","stopReason":"completed","lastAssistantMessage":[{"type":"text","text":"child answer 42."}]}} diff --git a/snapshots/sdk/subagent-spawn-in-process/session.1.v4.jsonl b/snapshots/sdk/subagent-spawn-in-process/session.1.v4.jsonl index 3a765d41c2..f7aedb9dbf 100644 --- a/snapshots/sdk/subagent-spawn-in-process/session.1.v4.jsonl +++ b/snapshots/sdk/subagent-spawn-in-process/session.1.v4.jsonl @@ -2,17 +2,16 @@ {"type":"subagent/descriptor","data":{"version":3,"mode":"continuable","provider":"spawn","label":"echo probe","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 answer 42."},{"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":"{{message:9}}"}]}} +{"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 answer 42."},{"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":"{{session:1}}"},"role":"user","id":"{{message:9}}"}]}} {"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":"{{message:10}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly: child answer 42."},{"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":"{{message:9}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\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: \"\", 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"}],"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: \"\", 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":"{{message:11}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Reply with exactly: child answer 42."},{"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":"{{session:1}}"},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\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: \"\", 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 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"}],"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: \"\", 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 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":"{{message:11}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:12}}"},"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 answer","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"child answer 42."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:13}}"},"stream":[{"type":"chunk","time":1793796129132,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1793796129132,"index":0,"dt":[],"texts":["child answer 42."]},{"type":"chunk","time":1793796129132,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"child answer 42."}}},{"type":"chunk","time":1793796129132,"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"}}} diff --git a/snapshots/sdk/team-default-enabled/session.1.v4.jsonl b/snapshots/sdk/team-default-enabled/session.1.v4.jsonl index 47b6e3c003..ac72e1faa3 100644 --- a/snapshots/sdk/team-default-enabled/session.1.v4.jsonl +++ b/snapshots/sdk/team-default-enabled/session.1.v4.jsonl @@ -2,25 +2,24 @@ {"type":"subagent/descriptor","data":{"version":3,"mode":"continuable","provider":"spawn","label":"Read the shared Team board","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":"List the shared tasks, verify Configured Team is present, then reply TEAM_CHILD_OK."},{"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":"{{message:14}}"}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"List the shared tasks, verify Configured Team is present, then reply TEAM_CHILD_OK."},{"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":"{{session:1}}"},"role":"user","id":"{{message:14}}"}]}} {"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":"{{message:15}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"List the shared tasks, verify Configured Team is present, then reply TEAM_CHILD_OK."},{"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":"{{message:14}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\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: \"\", message: \"...\" }).\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"}],"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: \"\", message: \"...\" }).\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":"{{message:16}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"List the shared tasks, verify Configured Team is present, then reply TEAM_CHILD_OK."},{"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":"{{session:1}}"},"role":"user","id":"{{message:14}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\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: \"\", message: \"...\" }).\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 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"}],"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: \"\", message: \"...\" }).\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 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":"{{message:16}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:17}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: 2026-10-16T00:00:00+00:00[UTC]\nBrowser time zone for this request: unavailable. Ask the user to clarify otherwise-unqualified dates and times.\nElapsed since the preceding model-visible message: unavailable."}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: 2026-10-16T00:00:00+00:00[UTC]\nBrowser time zone for this request: unavailable. Ask the user to clarify otherwise-unqualified dates and times.\nElapsed since the preceding model-visible message: unavailable."}]},"role":"user","id":"{{message:18}}"},"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":"List the shared tasks, verify","messageSeqs":[8],"source":{"kind":"fallback"}}} -{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{session:2}}","sessionFormatVersion":4,"throughSeq":14}} +{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{session:2}}","sessionFormatVersion":4,"throughSeq":13}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"team-list-2","name":"team_task_list","arguments":"{}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:19}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792108800000,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1792108800000,"index":0,"dt":[],"id":"team-list-2","name":"team_task_list","args":["{}"]},{"type":"chunk","time":1792108800000,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"team-list-2","name":"team_task_list","arguments":"{}"}}},{"type":"chunk","time":1792108800000,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792108800000,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"team-list-2","name":"team_task_list","arguments":"{}"}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"team-list-2"},"toolCallId":"team-list-2","content":[{"type":"text","text":"{\"tasks\":[{\"id\":\"task-1\",\"revision\":1,\"subject\":\"Configured Team\",\"description\":\"Enabled by Cordis patch\",\"status\":\"pending\",\"blockedBy\":[],\"writeScopes\":[],\"ready\":true,\"writeScopeWarnings\":[]}]}"}],"isError":false,"id":"{{message:20}}"}},"sourceEventSeqs":[17],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"team-list-2"},"toolCallId":"team-list-2","content":[{"type":"text","text":"{\"tasks\":[{\"id\":\"task-1\",\"revision\":1,\"subject\":\"Configured Team\",\"description\":\"Enabled by Cordis patch\",\"status\":\"pending\",\"blockedBy\":[],\"writeScopes\":[],\"ready\":true,\"writeScopeWarnings\":[]}]}"}],"isError":false,"id":"{{message:20}}"}},"sourceEventSeqs":[16],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} -{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{session:2}}","sessionFormatVersion":4,"throughSeq":20}} +{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{session:2}}","sessionFormatVersion":4,"throughSeq":19}} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"text","text":"TEAM_CHILD_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:21}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792108800000,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1792108800000,"index":0,"dt":[],"texts":["TEAM_CHILD_OK"]},{"type":"chunk","time":1792108800000,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"TEAM_CHILD_OK"}}},{"type":"chunk","time":1792108800000,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792108800000,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":2}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/snapshots/sdk/team-default-enabled/tool-schemas.1.expected.json b/snapshots/sdk/team-default-enabled/tool-schemas.1.expected.json index 52d309609b..6e786f2a9b 100644 --- a/snapshots/sdk/team-default-enabled/tool-schemas.1.expected.json +++ b/snapshots/sdk/team-default-enabled/tool-schemas.1.expected.json @@ -284,7 +284,7 @@ }, { "name": "plugin_manager", - "description": "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.", + "description": "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.", "parameters": { "type": "object", "properties": { diff --git a/snapshots/sdk/team-default-enabled/tool-schemas.expected.json b/snapshots/sdk/team-default-enabled/tool-schemas.expected.json index 52d309609b..6e786f2a9b 100644 --- a/snapshots/sdk/team-default-enabled/tool-schemas.expected.json +++ b/snapshots/sdk/team-default-enabled/tool-schemas.expected.json @@ -284,7 +284,7 @@ }, { "name": "plugin_manager", - "description": "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.", + "description": "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.", "parameters": { "type": "object", "properties": { diff --git a/snapshots/session/advanced-toolchain-runtime/session.1.v4.jsonl b/snapshots/session/advanced-toolchain-runtime/session.1.v4.jsonl index a2fdb349d2..73731749aa 100644 --- a/snapshots/session/advanced-toolchain-runtime/session.1.v4.jsonl +++ b/snapshots/session/advanced-toolchain-runtime/session.1.v4.jsonl @@ -3,16 +3,15 @@ {"type":"sandbox/mode","data":{"mode":"danger-full-access","source":"delegation"}} {"type":"approval/policy","data":{"policy":"never","source":"delegation"}} {"type":"permission/preset","data":{"preset":"danger-full-access"}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly DIRECT_CHILD_OK and nothing else."},{"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":"{{message:14}}"}]}} +{"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 DIRECT_CHILD_OK and nothing else."},{"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":"{{session:1}}"},"role":"user","id":"{{message:14}}"}]}} {"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":"{{message:15}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly DIRECT_CHILD_OK and nothing else."},{"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":"{{message:14}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", 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":"{{message:16}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Reply with exactly DIRECT_CHILD_OK and nothing else."},{"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":"{{session:1}}"},"role":"user","id":"{{message:14}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", 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 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", 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 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":"{{message:16}}"},"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 DIRECT_CHILD_OK and","messageSeqs":[9],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"DIRECT_CHILD_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:17}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1789821278406,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1789821278406,"index":0,"dt":[],"texts":["DIRECT_CHILD_OK"]},{"type":"chunk","time":1789821278406,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DIRECT_CHILD_OK"}}},{"type":"chunk","time":1789821278406,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1789821278406,"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"}}} diff --git a/snapshots/session/advanced-toolchain-runtime/session.2.v4.jsonl b/snapshots/session/advanced-toolchain-runtime/session.2.v4.jsonl index b324dd8ca4..aa5e83ad38 100644 --- a/snapshots/session/advanced-toolchain-runtime/session.2.v4.jsonl +++ b/snapshots/session/advanced-toolchain-runtime/session.2.v4.jsonl @@ -3,16 +3,15 @@ {"type":"sandbox/mode","data":{"mode":"danger-full-access","source":"delegation"}} {"type":"approval/policy","data":{"policy":"never","source":"delegation"}} {"type":"permission/preset","data":{"preset":"danger-full-access"}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly WORKFLOW_CHILD_OK and nothing else."}],"source":{"kind":"user"},"role":"user","id":"{{message:18}}"}]}} +{"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 WORKFLOW_CHILD_OK and nothing else."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{session:1}}"},"role":"user","id":"{{message:18}}"}]}} {"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":"{{message:19}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly WORKFLOW_CHILD_OK and nothing else."}],"source":{"kind":"user"},"role":"user","id":"{{message:18}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", 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":"{{message:20}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Reply with exactly WORKFLOW_CHILD_OK and nothing else."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{session:1}}"},"role":"user","id":"{{message:18}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", 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 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", 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 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":"{{message:20}}"},"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 WORKFLOW_CHILD_OK and","messageSeqs":[9],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"WORKFLOW_CHILD_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:21}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1789821278609,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1789821278609,"index":0,"dt":[],"texts":["WORKFLOW_CHILD_OK"]},{"type":"chunk","time":1789821278609,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"WORKFLOW_CHILD_OK"}}},{"type":"chunk","time":1789821278609,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1789821278609,"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"}}} diff --git a/snapshots/session/advanced-toolchain-runtime/session.v4.jsonl b/snapshots/session/advanced-toolchain-runtime/session.v4.jsonl index 45601e352c..a611238f9b 100644 --- a/snapshots/session/advanced-toolchain-runtime/session.v4.jsonl +++ b/snapshots/session/advanced-toolchain-runtime/session.v4.jsonl @@ -14,7 +14,7 @@ {"type":"session/title","data":{"title":"Run this advanced flow exactly","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-inspect-before","name":"cordis_inspect","arguments":"{}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1790493376576,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1790493376576,"index":0,"dt":[],"id":"advanced-inspect-before","name":"cordis_inspect","args":["{}"]},{"type":"chunk","time":1790493376577,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-inspect-before","name":"cordis_inspect","arguments":"{}"}}},{"type":"chunk","time":1790493376577,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1790493376577,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"advanced-inspect-before","name":"cordis_inspect","arguments":"{}"}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"advanced-inspect-before"},"toolCallId":"advanced-inspect-before","content":[{"type":"text","text":"{\n \"providers\": [\n {\n \"platform\": \"host\",\n \"id\": \"Service\",\n \"description\": \"Progressive Host Service discovery: compact capability/signature directory, then one exact coding contract.\",\n \"methods\": [\n {\n \"name\": \"listService\",\n \"description\": \"Progressive Host Service discovery: compact capability/signature directory, then one exact coding contract.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"service\": {\n \"type\": \"string\",\n \"description\": \"Exact Service key. Omit it for the compact Service and method-signature directory.\"\n }\n },\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"Compact Service directory, or one exact Service contract with only its referenced type declarations.\"\n }\n }\n ]\n },\n {\n \"platform\": \"host\",\n \"id\": \"Event\",\n \"description\": \"Progressive Host Event discovery: compact listener directory, then one exact event contract.\",\n \"methods\": [\n {\n \"name\": \"listEvents\",\n \"description\": \"Progressive Host Event discovery: compact listener directory, then one exact event contract.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"event\": {\n \"type\": \"string\",\n \"description\": \"Exact Event name. Omit it for the compact Event and listener-signature directory.\"\n }\n },\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"Compact Event directory, or one exact Event contract with only its referenced type declarations.\"\n }\n }\n ]\n },\n {\n \"platform\": \"host\",\n \"id\": \"Config\",\n \"description\": \"Progressive live plugin Config discovery: paged entry directory with schema status, then one entry's exact JSON Schema.\",\n \"methods\": [\n {\n \"name\": \"listConfigs\",\n \"description\": \"Progressive live plugin Config discovery: paged entry directory with schema status, then one entry's exact JSON Schema.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"entry\": {\n \"type\": \"string\",\n \"description\": \"Exact Loader entry id from the directory; returns that entry's projected Config schema.\"\n },\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Exact plugin package name; limits the directory to its entries.\"\n },\n \"offset\": {\n \"type\": \"number\",\n \"description\": \"Zero-based directory offset; defaults to 0.\"\n },\n \"limit\": {\n \"type\": \"number\",\n \"description\": \"Directory page size, from 1 to 100; defaults to 25.\"\n }\n },\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"One directory page of live entries with patch ids, Config status, total, and nextOffset, or one entry's projected JSON Schema with shared definitions, omission acceptance, and projection limitations.\"\n }\n }\n ]\n },\n {\n \"platform\": \"host\",\n \"id\": \"Tool\",\n \"description\": \"Tools visible to the requesting Agent, including scoped and dynamic registrations.\",\n \"methods\": [\n {\n \"name\": \"listTools\",\n \"description\": \"Return every Tool schema currently callable by this Agent.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {},\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"JSON data owned by this inspect provider.\"\n }\n }\n ]\n }\n ]\n}"}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"advanced-inspect-before"},"toolCallId":"advanced-inspect-before","content":[{"type":"text","text":"{\n \"providers\": [\n {\n \"platform\": \"host\",\n \"id\": \"Service\",\n \"description\": \"Progressive Host Service discovery: compact capability/signature directory, then one exact coding contract.\",\n \"methods\": [\n {\n \"name\": \"listService\",\n \"description\": \"Progressive Host Service discovery: compact capability/signature directory, then one exact coding contract.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"service\": {\n \"type\": \"string\",\n \"description\": \"Exact Service key. Omit it for the compact Service and method-signature directory.\"\n }\n },\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"Compact Service directory, or one exact Service contract with only its referenced type declarations.\"\n }\n }\n ]\n },\n {\n \"platform\": \"host\",\n \"id\": \"Event\",\n \"description\": \"Progressive Host Event discovery: compact listener directory, then one exact event contract.\",\n \"methods\": [\n {\n \"name\": \"listEvents\",\n \"description\": \"Progressive Host Event discovery: compact listener directory, then one exact event contract.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"event\": {\n \"type\": \"string\",\n \"description\": \"Exact Event name. Omit it for the compact Event and listener-signature directory.\"\n }\n },\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"Compact Event directory, or one exact Event contract with only its referenced type declarations.\"\n }\n }\n ]\n },\n {\n \"platform\": \"host\",\n \"id\": \"Config\",\n \"description\": \"Progressive live plugin Config discovery: paged entry directory with schema status, then one entry's exact JSON Schema.\",\n \"methods\": [\n {\n \"name\": \"listConfigs\",\n \"description\": \"Progressive live plugin Config discovery: paged entry directory with schema status, then one entry's exact JSON Schema.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"entry\": {\n \"type\": \"string\",\n \"description\": \"Exact Loader entry id from the directory; returns that entry's projected Config schema.\"\n },\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Exact plugin package name; limits the directory to its entries.\"\n },\n \"offset\": {\n \"type\": \"number\",\n \"description\": \"Zero-based directory offset; defaults to 0.\"\n },\n \"limit\": {\n \"type\": \"number\",\n \"description\": \"Directory page size, from 1 to 100; defaults to 25.\"\n }\n },\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"One directory page of live entries with patch ids, Config status, total, and nextOffset, or one entry's projected JSON Schema with shared definitions, omission acceptance, and projection limitations.\"\n }\n }\n ]\n },\n {\n \"platform\": \"host\",\n \"id\": \"Runtime\",\n \"description\": \"Running DSH version, the version that plugin engines.dsh ranges and DSH peer dependencies are checked against.\",\n \"methods\": [\n {\n \"name\": \"getVersion\",\n \"description\": \"Running DSH version, the version that plugin engines.dsh ranges and DSH peer dependencies are checked against.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {},\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"Object whose version field is the exact running DSH version.\"\n }\n }\n ]\n },\n {\n \"platform\": \"host\",\n \"id\": \"Tool\",\n \"description\": \"Tools visible to the requesting Agent, including scoped and dynamic registrations.\",\n \"methods\": [\n {\n \"name\": \"listTools\",\n \"description\": \"Return every Tool schema currently callable by this Agent.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {},\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"JSON data owned by this inspect provider.\"\n }\n }\n ]\n }\n ]\n}"}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"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":"tool-call","id":"advanced-direct-child","name":"subagent","arguments":"{\"description\":\"Check direct child\",\"prompt\":\"Reply with exactly DIRECT_CHILD_OK and nothing else.\",\"run_in_background\":false}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1790493376601,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1790493376601,"index":0,"dt":[],"id":"advanced-direct-child","name":"subagent","args":["{\"description\":\"Check direct child\",\"prompt\":\"Reply with exactly DIRECT_CHILD_OK and nothing else.\",\"run_in_background\":false}"]},{"type":"chunk","time":1790493376601,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-direct-child","name":"subagent","arguments":"{\"description\":\"Check direct child\",\"prompt\":\"Reply with exactly DIRECT_CHILD_OK and nothing else.\",\"run_in_background\":false}"}}},{"type":"chunk","time":1790493376602,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1790493376602,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} @@ -38,7 +38,7 @@ {"type":"step/start","data":{"turn":1,"step":4}} {"type":"assistant/message","data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-inspect-after","name":"cordis_inspect","arguments":"{}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:11}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1790493376863,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1790493376864,"index":0,"dt":[],"id":"advanced-inspect-after","name":"cordis_inspect","args":["{}"]},{"type":"chunk","time":1790493376864,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-inspect-after","name":"cordis_inspect","arguments":"{}"}}},{"type":"chunk","time":1790493376864,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1790493376864,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":4,"callId":"advanced-inspect-after","name":"cordis_inspect","arguments":"{}"}} -{"type":"tool/result","data":{"turn":1,"step":4,"message":{"role":"tool","source":{"kind":"tool","callId":"advanced-inspect-after"},"toolCallId":"advanced-inspect-after","content":[{"type":"text","text":"{\n \"providers\": [\n {\n \"platform\": \"host\",\n \"id\": \"Service\",\n \"description\": \"Progressive Host Service discovery: compact capability/signature directory, then one exact coding contract.\",\n \"methods\": [\n {\n \"name\": \"listService\",\n \"description\": \"Progressive Host Service discovery: compact capability/signature directory, then one exact coding contract.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"service\": {\n \"type\": \"string\",\n \"description\": \"Exact Service key. Omit it for the compact Service and method-signature directory.\"\n }\n },\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"Compact Service directory, or one exact Service contract with only its referenced type declarations.\"\n }\n }\n ]\n },\n {\n \"platform\": \"host\",\n \"id\": \"Event\",\n \"description\": \"Progressive Host Event discovery: compact listener directory, then one exact event contract.\",\n \"methods\": [\n {\n \"name\": \"listEvents\",\n \"description\": \"Progressive Host Event discovery: compact listener directory, then one exact event contract.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"event\": {\n \"type\": \"string\",\n \"description\": \"Exact Event name. Omit it for the compact Event and listener-signature directory.\"\n }\n },\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"Compact Event directory, or one exact Event contract with only its referenced type declarations.\"\n }\n }\n ]\n },\n {\n \"platform\": \"host\",\n \"id\": \"Config\",\n \"description\": \"Progressive live plugin Config discovery: paged entry directory with schema status, then one entry's exact JSON Schema.\",\n \"methods\": [\n {\n \"name\": \"listConfigs\",\n \"description\": \"Progressive live plugin Config discovery: paged entry directory with schema status, then one entry's exact JSON Schema.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"entry\": {\n \"type\": \"string\",\n \"description\": \"Exact Loader entry id from the directory; returns that entry's projected Config schema.\"\n },\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Exact plugin package name; limits the directory to its entries.\"\n },\n \"offset\": {\n \"type\": \"number\",\n \"description\": \"Zero-based directory offset; defaults to 0.\"\n },\n \"limit\": {\n \"type\": \"number\",\n \"description\": \"Directory page size, from 1 to 100; defaults to 25.\"\n }\n },\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"One directory page of live entries with patch ids, Config status, total, and nextOffset, or one entry's projected JSON Schema with shared definitions, omission acceptance, and projection limitations.\"\n }\n }\n ]\n },\n {\n \"platform\": \"host\",\n \"id\": \"Tool\",\n \"description\": \"Tools visible to the requesting Agent, including scoped and dynamic registrations.\",\n \"methods\": [\n {\n \"name\": \"listTools\",\n \"description\": \"Return every Tool schema currently callable by this Agent.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {},\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"JSON data owned by this inspect provider.\"\n }\n }\n ]\n }\n ]\n}"}],"isError":false,"id":"{{message:12}}"}},"sourceEventSeqs":[38],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":4,"message":{"role":"tool","source":{"kind":"tool","callId":"advanced-inspect-after"},"toolCallId":"advanced-inspect-after","content":[{"type":"text","text":"{\n \"providers\": [\n {\n \"platform\": \"host\",\n \"id\": \"Service\",\n \"description\": \"Progressive Host Service discovery: compact capability/signature directory, then one exact coding contract.\",\n \"methods\": [\n {\n \"name\": \"listService\",\n \"description\": \"Progressive Host Service discovery: compact capability/signature directory, then one exact coding contract.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"service\": {\n \"type\": \"string\",\n \"description\": \"Exact Service key. Omit it for the compact Service and method-signature directory.\"\n }\n },\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"Compact Service directory, or one exact Service contract with only its referenced type declarations.\"\n }\n }\n ]\n },\n {\n \"platform\": \"host\",\n \"id\": \"Event\",\n \"description\": \"Progressive Host Event discovery: compact listener directory, then one exact event contract.\",\n \"methods\": [\n {\n \"name\": \"listEvents\",\n \"description\": \"Progressive Host Event discovery: compact listener directory, then one exact event contract.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"event\": {\n \"type\": \"string\",\n \"description\": \"Exact Event name. Omit it for the compact Event and listener-signature directory.\"\n }\n },\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"Compact Event directory, or one exact Event contract with only its referenced type declarations.\"\n }\n }\n ]\n },\n {\n \"platform\": \"host\",\n \"id\": \"Config\",\n \"description\": \"Progressive live plugin Config discovery: paged entry directory with schema status, then one entry's exact JSON Schema.\",\n \"methods\": [\n {\n \"name\": \"listConfigs\",\n \"description\": \"Progressive live plugin Config discovery: paged entry directory with schema status, then one entry's exact JSON Schema.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"entry\": {\n \"type\": \"string\",\n \"description\": \"Exact Loader entry id from the directory; returns that entry's projected Config schema.\"\n },\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Exact plugin package name; limits the directory to its entries.\"\n },\n \"offset\": {\n \"type\": \"number\",\n \"description\": \"Zero-based directory offset; defaults to 0.\"\n },\n \"limit\": {\n \"type\": \"number\",\n \"description\": \"Directory page size, from 1 to 100; defaults to 25.\"\n }\n },\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"One directory page of live entries with patch ids, Config status, total, and nextOffset, or one entry's projected JSON Schema with shared definitions, omission acceptance, and projection limitations.\"\n }\n }\n ]\n },\n {\n \"platform\": \"host\",\n \"id\": \"Runtime\",\n \"description\": \"Running DSH version, the version that plugin engines.dsh ranges and DSH peer dependencies are checked against.\",\n \"methods\": [\n {\n \"name\": \"getVersion\",\n \"description\": \"Running DSH version, the version that plugin engines.dsh ranges and DSH peer dependencies are checked against.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {},\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"Object whose version field is the exact running DSH version.\"\n }\n }\n ]\n },\n {\n \"platform\": \"host\",\n \"id\": \"Tool\",\n \"description\": \"Tools visible to the requesting Agent, including scoped and dynamic registrations.\",\n \"methods\": [\n {\n \"name\": \"listTools\",\n \"description\": \"Return every Tool schema currently callable by this Agent.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {},\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"JSON data owned by this inspect provider.\"\n }\n }\n ]\n }\n ]\n}"}],"isError":false,"id":"{{message:12}}"}},"sourceEventSeqs":[38],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":4}} {"type":"step/start","data":{"turn":1,"step":5}} {"type":"assistant/message","data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"text","text":"ADVANCED_ACP_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:13}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1790493376883,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1790493376883,"index":0,"dt":[],"texts":["ADVANCED_ACP_OK"]},{"type":"chunk","time":1790493376883,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"ADVANCED_ACP_OK"}}},{"type":"chunk","time":1790493376883,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1790493376884,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} diff --git a/snapshots/session/advanced-toolchain/session.1.v4.jsonl b/snapshots/session/advanced-toolchain/session.1.v4.jsonl index 5448dc8976..2eabe81885 100644 --- a/snapshots/session/advanced-toolchain/session.1.v4.jsonl +++ b/snapshots/session/advanced-toolchain/session.1.v4.jsonl @@ -3,16 +3,15 @@ {"type":"sandbox/mode","data":{"mode":"danger-full-access","source":"delegation"}} {"type":"approval/policy","data":{"policy":"never","source":"delegation"}} {"type":"permission/preset","data":{"preset":"danger-full-access"}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly DIRECT_CHILD_OK and nothing else."},{"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":"{{message:20}}"}]}} +{"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 DIRECT_CHILD_OK and nothing else."},{"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":"{{session:1}}"},"role":"user","id":"{{message:20}}"}]}} {"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":"{{message:21}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly DIRECT_CHILD_OK and nothing else."},{"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":"{{message:20}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", 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":"{{message:22}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Reply with exactly DIRECT_CHILD_OK and nothing else."},{"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":"{{session:1}}"},"role":"user","id":"{{message:20}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", 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 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", 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 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":"{{message:22}}"},"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 DIRECT_CHILD_OK and","messageSeqs":[9],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"DIRECT_CHILD_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:23}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1789821276956,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1789821276956,"index":0,"dt":[],"texts":["DIRECT_CHILD_OK"]},{"type":"chunk","time":1789821276956,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DIRECT_CHILD_OK"}}},{"type":"chunk","time":1789821276956,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1789821276956,"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"}}} diff --git a/snapshots/session/advanced-toolchain/session.2.v4.jsonl b/snapshots/session/advanced-toolchain/session.2.v4.jsonl index 4aeef9e8c1..4d7cb7a752 100644 --- a/snapshots/session/advanced-toolchain/session.2.v4.jsonl +++ b/snapshots/session/advanced-toolchain/session.2.v4.jsonl @@ -3,16 +3,15 @@ {"type":"sandbox/mode","data":{"mode":"danger-full-access","source":"delegation"}} {"type":"approval/policy","data":{"policy":"never","source":"delegation"}} {"type":"permission/preset","data":{"preset":"danger-full-access"}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly WORKFLOW_CHILD_OK and nothing else."}],"source":{"kind":"user"},"role":"user","id":"{{message:24}}"}]}} +{"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 WORKFLOW_CHILD_OK and nothing else."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{session:1}}"},"role":"user","id":"{{message:24}}"}]}} {"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":"{{message:25}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly WORKFLOW_CHILD_OK and nothing else."}],"source":{"kind":"user"},"role":"user","id":"{{message:24}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", 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":"{{message:26}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Reply with exactly WORKFLOW_CHILD_OK and nothing else."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{session:1}}"},"role":"user","id":"{{message:24}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", 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 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", 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 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":"{{message:26}}"},"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 WORKFLOW_CHILD_OK and","messageSeqs":[9],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"WORKFLOW_CHILD_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:27}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1789821277094,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1789821277094,"index":0,"dt":[],"texts":["WORKFLOW_CHILD_OK"]},{"type":"chunk","time":1789821277094,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"WORKFLOW_CHILD_OK"}}},{"type":"chunk","time":1789821277094,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1789821277094,"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"}}} diff --git a/snapshots/session/advanced-toolchain/session.v4.jsonl b/snapshots/session/advanced-toolchain/session.v4.jsonl index f50bf829e6..a7dc3dfb8a 100644 --- a/snapshots/session/advanced-toolchain/session.v4.jsonl +++ b/snapshots/session/advanced-toolchain/session.v4.jsonl @@ -14,7 +14,7 @@ {"type":"session/title","data":{"title":"Run this advanced flow exactly","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-inspect-before","name":"cordis_inspect","arguments":"{}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791315715021,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1791315715022,"index":0,"dt":[],"id":"advanced-inspect-before","name":"cordis_inspect","args":["{}"]},{"type":"chunk","time":1791315715022,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-inspect-before","name":"cordis_inspect","arguments":"{}"}}},{"type":"chunk","time":1791315715022,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791315715022,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"advanced-inspect-before","name":"cordis_inspect","arguments":"{}"}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"advanced-inspect-before"},"toolCallId":"advanced-inspect-before","content":[{"type":"text","text":"{\n \"providers\": [\n {\n \"platform\": \"host\",\n \"id\": \"Service\",\n \"description\": \"Progressive Host Service discovery: compact capability/signature directory, then one exact coding contract.\",\n \"methods\": [\n {\n \"name\": \"listService\",\n \"description\": \"Progressive Host Service discovery: compact capability/signature directory, then one exact coding contract.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"service\": {\n \"type\": \"string\",\n \"description\": \"Exact Service key. Omit it for the compact Service and method-signature directory.\"\n }\n },\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"Compact Service directory, or one exact Service contract with only its referenced type declarations.\"\n }\n }\n ]\n },\n {\n \"platform\": \"host\",\n \"id\": \"Event\",\n \"description\": \"Progressive Host Event discovery: compact listener directory, then one exact event contract.\",\n \"methods\": [\n {\n \"name\": \"listEvents\",\n \"description\": \"Progressive Host Event discovery: compact listener directory, then one exact event contract.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"event\": {\n \"type\": \"string\",\n \"description\": \"Exact Event name. Omit it for the compact Event and listener-signature directory.\"\n }\n },\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"Compact Event directory, or one exact Event contract with only its referenced type declarations.\"\n }\n }\n ]\n },\n {\n \"platform\": \"host\",\n \"id\": \"Config\",\n \"description\": \"Progressive live plugin Config discovery: paged entry directory with schema status, then one entry's exact JSON Schema.\",\n \"methods\": [\n {\n \"name\": \"listConfigs\",\n \"description\": \"Progressive live plugin Config discovery: paged entry directory with schema status, then one entry's exact JSON Schema.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"entry\": {\n \"type\": \"string\",\n \"description\": \"Exact Loader entry id from the directory; returns that entry's projected Config schema.\"\n },\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Exact plugin package name; limits the directory to its entries.\"\n },\n \"offset\": {\n \"type\": \"number\",\n \"description\": \"Zero-based directory offset; defaults to 0.\"\n },\n \"limit\": {\n \"type\": \"number\",\n \"description\": \"Directory page size, from 1 to 100; defaults to 25.\"\n }\n },\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"One directory page of live entries with patch ids, Config status, total, and nextOffset, or one entry's projected JSON Schema with shared definitions, omission acceptance, and projection limitations.\"\n }\n }\n ]\n },\n {\n \"platform\": \"host\",\n \"id\": \"Tool\",\n \"description\": \"Tools visible to the requesting Agent, including scoped and dynamic registrations.\",\n \"methods\": [\n {\n \"name\": \"listTools\",\n \"description\": \"Return every Tool schema currently callable by this Agent.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {},\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"JSON data owned by this inspect provider.\"\n }\n }\n ]\n }\n ]\n}"}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"advanced-inspect-before"},"toolCallId":"advanced-inspect-before","content":[{"type":"text","text":"{\n \"providers\": [\n {\n \"platform\": \"host\",\n \"id\": \"Service\",\n \"description\": \"Progressive Host Service discovery: compact capability/signature directory, then one exact coding contract.\",\n \"methods\": [\n {\n \"name\": \"listService\",\n \"description\": \"Progressive Host Service discovery: compact capability/signature directory, then one exact coding contract.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"service\": {\n \"type\": \"string\",\n \"description\": \"Exact Service key. Omit it for the compact Service and method-signature directory.\"\n }\n },\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"Compact Service directory, or one exact Service contract with only its referenced type declarations.\"\n }\n }\n ]\n },\n {\n \"platform\": \"host\",\n \"id\": \"Event\",\n \"description\": \"Progressive Host Event discovery: compact listener directory, then one exact event contract.\",\n \"methods\": [\n {\n \"name\": \"listEvents\",\n \"description\": \"Progressive Host Event discovery: compact listener directory, then one exact event contract.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"event\": {\n \"type\": \"string\",\n \"description\": \"Exact Event name. Omit it for the compact Event and listener-signature directory.\"\n }\n },\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"Compact Event directory, or one exact Event contract with only its referenced type declarations.\"\n }\n }\n ]\n },\n {\n \"platform\": \"host\",\n \"id\": \"Config\",\n \"description\": \"Progressive live plugin Config discovery: paged entry directory with schema status, then one entry's exact JSON Schema.\",\n \"methods\": [\n {\n \"name\": \"listConfigs\",\n \"description\": \"Progressive live plugin Config discovery: paged entry directory with schema status, then one entry's exact JSON Schema.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"entry\": {\n \"type\": \"string\",\n \"description\": \"Exact Loader entry id from the directory; returns that entry's projected Config schema.\"\n },\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Exact plugin package name; limits the directory to its entries.\"\n },\n \"offset\": {\n \"type\": \"number\",\n \"description\": \"Zero-based directory offset; defaults to 0.\"\n },\n \"limit\": {\n \"type\": \"number\",\n \"description\": \"Directory page size, from 1 to 100; defaults to 25.\"\n }\n },\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"One directory page of live entries with patch ids, Config status, total, and nextOffset, or one entry's projected JSON Schema with shared definitions, omission acceptance, and projection limitations.\"\n }\n }\n ]\n },\n {\n \"platform\": \"host\",\n \"id\": \"Runtime\",\n \"description\": \"Running DSH version, the version that plugin engines.dsh ranges and DSH peer dependencies are checked against.\",\n \"methods\": [\n {\n \"name\": \"getVersion\",\n \"description\": \"Running DSH version, the version that plugin engines.dsh ranges and DSH peer dependencies are checked against.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {},\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"Object whose version field is the exact running DSH version.\"\n }\n }\n ]\n },\n {\n \"platform\": \"host\",\n \"id\": \"Tool\",\n \"description\": \"Tools visible to the requesting Agent, including scoped and dynamic registrations.\",\n \"methods\": [\n {\n \"name\": \"listTools\",\n \"description\": \"Return every Tool schema currently callable by this Agent.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {},\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"JSON data owned by this inspect provider.\"\n }\n }\n ]\n }\n ]\n}"}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} {"type":"system/message","data":{"turn":1,"step":2,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:6}}"}},"sourceEventSeqs":[7],"surfaceOp":{"op":"replace","startSeq":7,"endSeq":7}} @@ -23,8 +23,8 @@ {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-code","name":"run_code","arguments":"{\"code\":\"const inspected = await tools.cordis_inspect({}); inspect(JSON.stringify(inspected.providers.map(provider => provider.id), null, 2)); return;\",\"description\":\"Discover runtime APIs through PTC\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:8}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791315715055,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1791315715055,"index":0,"dt":[],"id":"advanced-code","name":"run_code","args":["{\"code\":\"const inspected = await tools.cordis_inspect({}); inspect(JSON.stringify(inspected.providers.map(provider => provider.id), null, 2)); return;\",\"description\":\"Discover runtime APIs through PTC\"}"]},{"type":"chunk","time":1791315715055,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-code","name":"run_code","arguments":"{\"code\":\"const inspected = await tools.cordis_inspect({}); inspect(JSON.stringify(inspected.providers.map(provider => provider.id), null, 2)); return;\",\"description\":\"Discover runtime APIs through PTC\"}"}}},{"type":"chunk","time":1791315715055,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791315715055,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"advanced-code","name":"run_code","arguments":"{\"code\":\"const inspected = await tools.cordis_inspect({}); inspect(JSON.stringify(inspected.providers.map(provider => provider.id), null, 2)); return;\",\"description\":\"Discover runtime APIs through PTC\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"advanced-code","parentCallId":"advanced-code","subCallId":"advanced-code:ptc:1","name":"cordis_inspect","arguments":{}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"advanced-code","parentCallId":"advanced-code","subCallId":"advanced-code:ptc:1","name":"cordis_inspect","arguments":{},"isError":false,"content":[{"type":"text","text":"{\n \"providers\": [\n {\n \"platform\": \"host\",\n \"id\": \"Service\",\n \"description\": \"Progressive Host Service discovery: compact capability/signature directory, then one exact coding contract.\",\n \"methods\": [\n {\n \"name\": \"listService\",\n \"description\": \"Progressive Host Service discovery: compact capability/signature directory, then one exact coding contract.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"service\": {\n \"type\": \"string\",\n \"description\": \"Exact Service key. Omit it for the compact Service and method-signature directory.\"\n }\n },\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"Compact Service directory, or one exact Service contract with only its referenced type declarations.\"\n }\n }\n ]\n },\n {\n \"platform\": \"host\",\n \"id\": \"Event\",\n \"description\": \"Progressive Host Event discovery: compact listener directory, then one exact event contract.\",\n \"methods\": [\n {\n \"name\": \"listEvents\",\n \"description\": \"Progressive Host Event discovery: compact listener directory, then one exact event contract.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"event\": {\n \"type\": \"string\",\n \"description\": \"Exact Event name. Omit it for the compact Event and listener-signature directory.\"\n }\n },\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"Compact Event directory, or one exact Event contract with only its referenced type declarations.\"\n }\n }\n ]\n },\n {\n \"platform\": \"host\",\n \"id\": \"Config\",\n \"description\": \"Progressive live plugin Config discovery: paged entry directory with schema status, then one entry's exact JSON Schema.\",\n \"methods\": [\n {\n \"name\": \"listConfigs\",\n \"description\": \"Progressive live plugin Config discovery: paged entry directory with schema status, then one entry's exact JSON Schema.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"entry\": {\n \"type\": \"string\",\n \"description\": \"Exact Loader entry id from the directory; returns that entry's projected Config schema.\"\n },\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Exact plugin package name; limits the directory to its entries.\"\n },\n \"offset\": {\n \"type\": \"number\",\n \"description\": \"Zero-based directory offset; defaults to 0.\"\n },\n \"limit\": {\n \"type\": \"number\",\n \"description\": \"Directory page size, from 1 to 100; defaults to 25.\"\n }\n },\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"One directory page of live entries with patch ids, Config status, total, and nextOffset, or one entry's projected JSON Schema with shared definitions, omission acceptance, and projection limitations.\"\n }\n }\n ]\n },\n {\n \"platform\": \"host\",\n \"id\": \"Tool\",\n \"description\": \"Tools visible to the requesting Agent, including scoped and dynamic registrations.\",\n \"methods\": [\n {\n \"name\": \"listTools\",\n \"description\": \"Return every Tool schema currently callable by this Agent.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {},\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"JSON data owned by this inspect provider.\"\n }\n }\n ]\n }\n ]\n}"}]}} -{"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"advanced-code"},"toolCallId":"advanced-code","content":[{"type":"text","text":"[\n \"Service\",\n \"Event\",\n \"Config\",\n \"Tool\"\n]\n"}],"isError":false,"id":"{{message:9}}"}},"sourceEventSeqs":[22],"surfaceOp":"append"} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"advanced-code","parentCallId":"advanced-code","subCallId":"advanced-code:ptc:1","name":"cordis_inspect","arguments":{},"isError":false,"content":[{"type":"text","text":"{\n \"providers\": [\n {\n \"platform\": \"host\",\n \"id\": \"Service\",\n \"description\": \"Progressive Host Service discovery: compact capability/signature directory, then one exact coding contract.\",\n \"methods\": [\n {\n \"name\": \"listService\",\n \"description\": \"Progressive Host Service discovery: compact capability/signature directory, then one exact coding contract.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"service\": {\n \"type\": \"string\",\n \"description\": \"Exact Service key. Omit it for the compact Service and method-signature directory.\"\n }\n },\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"Compact Service directory, or one exact Service contract with only its referenced type declarations.\"\n }\n }\n ]\n },\n {\n \"platform\": \"host\",\n \"id\": \"Event\",\n \"description\": \"Progressive Host Event discovery: compact listener directory, then one exact event contract.\",\n \"methods\": [\n {\n \"name\": \"listEvents\",\n \"description\": \"Progressive Host Event discovery: compact listener directory, then one exact event contract.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"event\": {\n \"type\": \"string\",\n \"description\": \"Exact Event name. Omit it for the compact Event and listener-signature directory.\"\n }\n },\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"Compact Event directory, or one exact Event contract with only its referenced type declarations.\"\n }\n }\n ]\n },\n {\n \"platform\": \"host\",\n \"id\": \"Config\",\n \"description\": \"Progressive live plugin Config discovery: paged entry directory with schema status, then one entry's exact JSON Schema.\",\n \"methods\": [\n {\n \"name\": \"listConfigs\",\n \"description\": \"Progressive live plugin Config discovery: paged entry directory with schema status, then one entry's exact JSON Schema.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"entry\": {\n \"type\": \"string\",\n \"description\": \"Exact Loader entry id from the directory; returns that entry's projected Config schema.\"\n },\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Exact plugin package name; limits the directory to its entries.\"\n },\n \"offset\": {\n \"type\": \"number\",\n \"description\": \"Zero-based directory offset; defaults to 0.\"\n },\n \"limit\": {\n \"type\": \"number\",\n \"description\": \"Directory page size, from 1 to 100; defaults to 25.\"\n }\n },\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"One directory page of live entries with patch ids, Config status, total, and nextOffset, or one entry's projected JSON Schema with shared definitions, omission acceptance, and projection limitations.\"\n }\n }\n ]\n },\n {\n \"platform\": \"host\",\n \"id\": \"Runtime\",\n \"description\": \"Running DSH version, the version that plugin engines.dsh ranges and DSH peer dependencies are checked against.\",\n \"methods\": [\n {\n \"name\": \"getVersion\",\n \"description\": \"Running DSH version, the version that plugin engines.dsh ranges and DSH peer dependencies are checked against.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {},\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"Object whose version field is the exact running DSH version.\"\n }\n }\n ]\n },\n {\n \"platform\": \"host\",\n \"id\": \"Tool\",\n \"description\": \"Tools visible to the requesting Agent, including scoped and dynamic registrations.\",\n \"methods\": [\n {\n \"name\": \"listTools\",\n \"description\": \"Return every Tool schema currently callable by this Agent.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {},\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"JSON data owned by this inspect provider.\"\n }\n }\n ]\n }\n ]\n}"}]}} +{"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"advanced-code"},"toolCallId":"advanced-code","content":[{"type":"text","text":"[\n \"Service\",\n \"Event\",\n \"Config\",\n \"Runtime\",\n \"Tool\"\n]\n"}],"isError":false,"id":"{{message:9}}"}},"sourceEventSeqs":[22],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":2}} {"type":"step/start","data":{"turn":1,"step":3}} {"type":"system/message","data":{"turn":1,"step":3,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:10}}"}},"sourceEventSeqs":[18],"surfaceOp":{"op":"replace","startSeq":18,"endSeq":18}} @@ -51,7 +51,7 @@ {"type":"step/start","data":{"turn":1,"step":5}} {"type":"assistant/message","data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-inspect-after","name":"cordis_inspect","arguments":"{}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:17}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791315715551,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1791315715551,"index":0,"dt":[],"id":"advanced-inspect-after","name":"cordis_inspect","args":["{}"]},{"type":"chunk","time":1791315715551,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-inspect-after","name":"cordis_inspect","arguments":"{}"}}},{"type":"chunk","time":1791315715551,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791315715551,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":5,"callId":"advanced-inspect-after","name":"cordis_inspect","arguments":"{}"}} -{"type":"tool/result","data":{"turn":1,"step":5,"message":{"role":"tool","source":{"kind":"tool","callId":"advanced-inspect-after"},"toolCallId":"advanced-inspect-after","content":[{"type":"text","text":"{\n \"providers\": [\n {\n \"platform\": \"host\",\n \"id\": \"Service\",\n \"description\": \"Progressive Host Service discovery: compact capability/signature directory, then one exact coding contract.\",\n \"methods\": [\n {\n \"name\": \"listService\",\n \"description\": \"Progressive Host Service discovery: compact capability/signature directory, then one exact coding contract.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"service\": {\n \"type\": \"string\",\n \"description\": \"Exact Service key. Omit it for the compact Service and method-signature directory.\"\n }\n },\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"Compact Service directory, or one exact Service contract with only its referenced type declarations.\"\n }\n }\n ]\n },\n {\n \"platform\": \"host\",\n \"id\": \"Event\",\n \"description\": \"Progressive Host Event discovery: compact listener directory, then one exact event contract.\",\n \"methods\": [\n {\n \"name\": \"listEvents\",\n \"description\": \"Progressive Host Event discovery: compact listener directory, then one exact event contract.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"event\": {\n \"type\": \"string\",\n \"description\": \"Exact Event name. Omit it for the compact Event and listener-signature directory.\"\n }\n },\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"Compact Event directory, or one exact Event contract with only its referenced type declarations.\"\n }\n }\n ]\n },\n {\n \"platform\": \"host\",\n \"id\": \"Config\",\n \"description\": \"Progressive live plugin Config discovery: paged entry directory with schema status, then one entry's exact JSON Schema.\",\n \"methods\": [\n {\n \"name\": \"listConfigs\",\n \"description\": \"Progressive live plugin Config discovery: paged entry directory with schema status, then one entry's exact JSON Schema.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"entry\": {\n \"type\": \"string\",\n \"description\": \"Exact Loader entry id from the directory; returns that entry's projected Config schema.\"\n },\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Exact plugin package name; limits the directory to its entries.\"\n },\n \"offset\": {\n \"type\": \"number\",\n \"description\": \"Zero-based directory offset; defaults to 0.\"\n },\n \"limit\": {\n \"type\": \"number\",\n \"description\": \"Directory page size, from 1 to 100; defaults to 25.\"\n }\n },\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"One directory page of live entries with patch ids, Config status, total, and nextOffset, or one entry's projected JSON Schema with shared definitions, omission acceptance, and projection limitations.\"\n }\n }\n ]\n },\n {\n \"platform\": \"host\",\n \"id\": \"Tool\",\n \"description\": \"Tools visible to the requesting Agent, including scoped and dynamic registrations.\",\n \"methods\": [\n {\n \"name\": \"listTools\",\n \"description\": \"Return every Tool schema currently callable by this Agent.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {},\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"JSON data owned by this inspect provider.\"\n }\n }\n ]\n }\n ]\n}"}],"isError":false,"id":"{{message:18}}"}},"sourceEventSeqs":[51],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":5,"message":{"role":"tool","source":{"kind":"tool","callId":"advanced-inspect-after"},"toolCallId":"advanced-inspect-after","content":[{"type":"text","text":"{\n \"providers\": [\n {\n \"platform\": \"host\",\n \"id\": \"Service\",\n \"description\": \"Progressive Host Service discovery: compact capability/signature directory, then one exact coding contract.\",\n \"methods\": [\n {\n \"name\": \"listService\",\n \"description\": \"Progressive Host Service discovery: compact capability/signature directory, then one exact coding contract.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"service\": {\n \"type\": \"string\",\n \"description\": \"Exact Service key. Omit it for the compact Service and method-signature directory.\"\n }\n },\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"Compact Service directory, or one exact Service contract with only its referenced type declarations.\"\n }\n }\n ]\n },\n {\n \"platform\": \"host\",\n \"id\": \"Event\",\n \"description\": \"Progressive Host Event discovery: compact listener directory, then one exact event contract.\",\n \"methods\": [\n {\n \"name\": \"listEvents\",\n \"description\": \"Progressive Host Event discovery: compact listener directory, then one exact event contract.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"event\": {\n \"type\": \"string\",\n \"description\": \"Exact Event name. Omit it for the compact Event and listener-signature directory.\"\n }\n },\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"Compact Event directory, or one exact Event contract with only its referenced type declarations.\"\n }\n }\n ]\n },\n {\n \"platform\": \"host\",\n \"id\": \"Config\",\n \"description\": \"Progressive live plugin Config discovery: paged entry directory with schema status, then one entry's exact JSON Schema.\",\n \"methods\": [\n {\n \"name\": \"listConfigs\",\n \"description\": \"Progressive live plugin Config discovery: paged entry directory with schema status, then one entry's exact JSON Schema.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {\n \"entry\": {\n \"type\": \"string\",\n \"description\": \"Exact Loader entry id from the directory; returns that entry's projected Config schema.\"\n },\n \"name\": {\n \"type\": \"string\",\n \"description\": \"Exact plugin package name; limits the directory to its entries.\"\n },\n \"offset\": {\n \"type\": \"number\",\n \"description\": \"Zero-based directory offset; defaults to 0.\"\n },\n \"limit\": {\n \"type\": \"number\",\n \"description\": \"Directory page size, from 1 to 100; defaults to 25.\"\n }\n },\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"One directory page of live entries with patch ids, Config status, total, and nextOffset, or one entry's projected JSON Schema with shared definitions, omission acceptance, and projection limitations.\"\n }\n }\n ]\n },\n {\n \"platform\": \"host\",\n \"id\": \"Runtime\",\n \"description\": \"Running DSH version, the version that plugin engines.dsh ranges and DSH peer dependencies are checked against.\",\n \"methods\": [\n {\n \"name\": \"getVersion\",\n \"description\": \"Running DSH version, the version that plugin engines.dsh ranges and DSH peer dependencies are checked against.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {},\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"Object whose version field is the exact running DSH version.\"\n }\n }\n ]\n },\n {\n \"platform\": \"host\",\n \"id\": \"Tool\",\n \"description\": \"Tools visible to the requesting Agent, including scoped and dynamic registrations.\",\n \"methods\": [\n {\n \"name\": \"listTools\",\n \"description\": \"Return every Tool schema currently callable by this Agent.\",\n \"inputSchema\": {\n \"type\": \"object\",\n \"properties\": {},\n \"additionalProperties\": false\n },\n \"outputSchema\": {\n \"description\": \"JSON data owned by this inspect provider.\"\n }\n }\n ]\n }\n ]\n}"}],"isError":false,"id":"{{message:18}}"}},"sourceEventSeqs":[51],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":5}} {"type":"step/start","data":{"turn":1,"step":6}} {"type":"assistant/message","data":{"turn":1,"step":6,"message":{"role":"assistant","content":[{"type":"text","text":"ADVANCED_HEADLESS_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:19}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794196084265,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1794196084265,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"ADVANCED_HEADLESS_OK"}}},{"type":"chunk","time":1794196084265,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794196084265,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} diff --git a/snapshots/session/cua-ptc/cordis.snapshot.yml b/snapshots/session/cua-ptc/cordis.snapshot.yml index 1b9f139f20..5de7dad992 100644 --- a/snapshots/session/cua-ptc/cordis.snapshot.yml +++ b/snapshots/session/cua-ptc/cordis.snapshot.yml @@ -23,6 +23,10 @@ - id: tool-executor-ptc disabled: false +- id: ptc-runtime + config: + maxOutputBytes: 4096 + - id: system-prompt name: '@deepseek-ai/dsh-system-prompt' config: diff --git a/snapshots/session/cua-ptc/cordis.yml b/snapshots/session/cua-ptc/cordis.yml index 839efc03b9..c833801d96 100644 --- a/snapshots/session/cua-ptc/cordis.yml +++ b/snapshots/session/cua-ptc/cordis.yml @@ -16,6 +16,10 @@ - id: tool-executor-ptc disabled: false +- id: ptc-runtime + config: + maxOutputBytes: 4096 + - id: system-prompt name: '@deepseek-ai/dsh-system-prompt' config: diff --git a/snapshots/session/cua-ptc/replay.override.json b/snapshots/session/cua-ptc/replay.override.json index 79a98a26c4..4716e409a2 100644 --- a/snapshots/session/cua-ptc/replay.override.json +++ b/snapshots/session/cua-ptc/replay.override.json @@ -98,6 +98,72 @@ } ] }, + { + "kind": "chunks", + "chunks": [ + { + "type": "block-start", + "index": 0, + "blockType": "tool-call" + }, + { + "type": "block-end", + "index": 0, + "block": { + "type": "tool-call", + "id": "cua-ptc-output-limit", + "name": "run_code", + "arguments": "{\"code\":\"const { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nconst cua = connectCua(() => tools.cua);\\nconst app = await cua.getApp('test.fixture');\\nconst window = await app.getWindow('7');\\nconst tree = await window.getAccessibilityTree();\\nif (!tree.includes('Count: 1')) throw new Error('Unexpected initial action count');\\nawait window.click('0');\\ninspect(await window.getScreenshot());\\ninspect('x'.repeat(8192));\\nawait window.getAccessibilityTree();\\nawait window.click('0');\",\"description\":\"Complete planned clicks before and after output truncation\"}" + } + }, + { + "type": "usage", + "usage": { + "inputTokens": 3, + "outputTokens": 3 + } + }, + { + "type": "finish", + "reason": { + "kind": "tool-calls" + } + } + ] + }, + { + "kind": "chunks", + "chunks": [ + { + "type": "block-start", + "index": 0, + "blockType": "tool-call" + }, + { + "type": "block-end", + "index": 0, + "block": { + "type": "tool-call", + "id": "cua-ptc-observe-after-limit", + "name": "run_code", + "arguments": "{\"code\":\"const { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nconst cua = connectCua(() => tools.cua);\\nconst app = await cua.getApp('test.fixture');\\nconst tree = await app.getAccessibilityTree();\\nif (!tree.includes('Count: 3')) throw new Error('Output overflow changed the action count');\\ninspect({ count: 3, repeated: false });\",\"description\":\"Verify both planned actions completed without replaying input\"}" + } + }, + { + "type": "usage", + "usage": { + "inputTokens": 3, + "outputTokens": 3 + } + }, + { + "type": "finish", + "reason": { + "kind": "tool-calls" + } + } + ] + }, { "kind": "chunks", "chunks": [ @@ -111,7 +177,7 @@ "index": 0, "block": { "type": "text", - "text": "Received native CUA values and PNG screenshots through PTC. The object API captured a 90-byte PNG after two AX read failures and refused element input without an accessibility snapshot. Both writability probe failures left the tree readable with unknown fields and kept writes strict." + "text": "Received native CUA values and PNG screenshots through PTC. The object API captured a 90-byte PNG after two AX read failures and refused element input without an accessibility snapshot. Both writability probe failures left the tree readable with unknown fields and kept writes strict. Output truncation retained the inspected screenshot and the program completed both planned clicks. A fresh observation confirmed exactly three clicks in total, without replaying input." } }, { diff --git a/snapshots/session/cua-ptc/session.v4.jsonl b/snapshots/session/cua-ptc/session.v4.jsonl index 325f59a1ed..5892951397 100644 --- a/snapshots/session/cua-ptc/session.v4.jsonl +++ b/snapshots/session/cua-ptc/session.v4.jsonl @@ -12,7 +12,7 @@ {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"}} {"type":"session/title","data":{"title":"Use tools.cua from Node PTC","messageSeqs":[8],"source":{"kind":"fallback"}}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-ptc-native-result","name":"run_code","arguments":"{\"code\":\"const { readFile } = await import('node:fs/promises');\\nconst app = await tools.cua({ method: 'getApp', params: { selector: 'test.fixture' } });\\nconst target = { appHandle: app.appHandle, windowId: '7' };\\nconst first = await tools.cua({ method: 'getState', params: { ...target, maxElements: 1 } });\\nconst state = first.truncated ? await tools.cua({ method: 'getState', params: { ...target, maxElements: 16 } }) : first;\\nconst shot = await tools.cua({ method: 'screenshot', params: { appHandle: app.appHandle, windowId: '7' } });\\nconst bytes = await readFile(shot.path);\\ninspect({ appHandle: app.appHandle, initiallyTruncated: first.truncated, recoveredTextField: !first.tree.includes('AXTextField') && state.tree.includes('AXTextField'), hasIncrement: state.tree.includes('Increment'), pngBytes: bytes.length, signature: bytes.subarray(0, 8).toString('hex'), imageWidth: shot.width, imageHeight: shot.height }, shot); return;\",\"description\":\"Read native CUA values and receive one screenshot\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794226987185,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794226987185,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-ptc-native-result","name":"run_code","arguments":"{\"code\":\"const { readFile } = await import('node:fs/promises');\\nconst app = await tools.cua({ method: 'getApp', params: { selector: 'test.fixture' } });\\nconst target = { appHandle: app.appHandle, windowId: '7' };\\nconst first = await tools.cua({ method: 'getState', params: { ...target, maxElements: 1 } });\\nconst state = first.truncated ? await tools.cua({ method: 'getState', params: { ...target, maxElements: 16 } }) : first;\\nconst shot = await tools.cua({ method: 'screenshot', params: { appHandle: app.appHandle, windowId: '7' } });\\nconst bytes = await readFile(shot.path);\\ninspect({ appHandle: app.appHandle, initiallyTruncated: first.truncated, recoveredTextField: !first.tree.includes('AXTextField') && state.tree.includes('AXTextField'), hasIncrement: state.tree.includes('Increment'), pngBytes: bytes.length, signature: bytes.subarray(0, 8).toString('hex'), imageWidth: shot.width, imageHeight: shot.height }, shot); return;\",\"description\":\"Read native CUA values and receive one screenshot\"}"}}},{"type":"chunk","time":1794226987185,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794226987185,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-ptc-native-result","name":"run_code","arguments":"{\"code\":\"const { readFile } = await import('node:fs/promises');\\nconst app = await tools.cua({ method: 'getApp', params: { selector: 'test.fixture' } });\\nconst target = { appHandle: app.appHandle, windowId: '7' };\\nconst first = await tools.cua({ method: 'getState', params: { ...target, maxElements: 1 } });\\nconst state = first.truncated ? await tools.cua({ method: 'getState', params: { ...target, maxElements: 16 } }) : first;\\nconst shot = await tools.cua({ method: 'screenshot', params: { appHandle: app.appHandle, windowId: '7' } });\\nconst bytes = await readFile(shot.path);\\ninspect({ appHandle: app.appHandle, initiallyTruncated: first.truncated, recoveredTextField: !first.tree.includes('AXTextField') && state.tree.includes('AXTextField'), hasIncrement: state.tree.includes('Increment'), pngBytes: bytes.length, signature: bytes.subarray(0, 8).toString('hex'), imageWidth: shot.width, imageHeight: shot.height }, shot); return;\",\"description\":\"Read native CUA values and receive one screenshot\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794554858357,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794554858357,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-ptc-native-result","name":"run_code","arguments":"{\"code\":\"const { readFile } = await import('node:fs/promises');\\nconst app = await tools.cua({ method: 'getApp', params: { selector: 'test.fixture' } });\\nconst target = { appHandle: app.appHandle, windowId: '7' };\\nconst first = await tools.cua({ method: 'getState', params: { ...target, maxElements: 1 } });\\nconst state = first.truncated ? await tools.cua({ method: 'getState', params: { ...target, maxElements: 16 } }) : first;\\nconst shot = await tools.cua({ method: 'screenshot', params: { appHandle: app.appHandle, windowId: '7' } });\\nconst bytes = await readFile(shot.path);\\ninspect({ appHandle: app.appHandle, initiallyTruncated: first.truncated, recoveredTextField: !first.tree.includes('AXTextField') && state.tree.includes('AXTextField'), hasIncrement: state.tree.includes('Increment'), pngBytes: bytes.length, signature: bytes.subarray(0, 8).toString('hex'), imageWidth: shot.width, imageHeight: shot.height }, shot); return;\",\"description\":\"Read native CUA values and receive one screenshot\"}"}}},{"type":"chunk","time":1794554858357,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794554858357,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua-ptc-native-result","name":"run_code","arguments":"{\"code\":\"const { readFile } = await import('node:fs/promises');\\nconst app = await tools.cua({ method: 'getApp', params: { selector: 'test.fixture' } });\\nconst target = { appHandle: app.appHandle, windowId: '7' };\\nconst first = await tools.cua({ method: 'getState', params: { ...target, maxElements: 1 } });\\nconst state = first.truncated ? await tools.cua({ method: 'getState', params: { ...target, maxElements: 16 } }) : first;\\nconst shot = await tools.cua({ method: 'screenshot', params: { appHandle: app.appHandle, windowId: '7' } });\\nconst bytes = await readFile(shot.path);\\ninspect({ appHandle: app.appHandle, initiallyTruncated: first.truncated, recoveredTextField: !first.tree.includes('AXTextField') && state.tree.includes('AXTextField'), hasIncrement: state.tree.includes('Increment'), pngBytes: bytes.length, signature: bytes.subarray(0, 8).toString('hex'), imageWidth: shot.width, imageHeight: shot.height }, shot); return;\",\"description\":\"Read native CUA values and receive one screenshot\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-native-result","parentCallId":"cua-ptc-native-result","subCallId":"cua-ptc-native-result:ptc:1","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-native-result","parentCallId":"cua-ptc-native-result","subCallId":"cua-ptc-native-result:ptc:1","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"name\":\"Fixture\",\"bundleId\":\"test.fixture\",\"running\":true}"}]}} @@ -25,7 +25,7 @@ {"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-ptc-native-result"},"toolCallId":"cua-ptc-native-result","content":[{"type":"text","text":"{\n appHandle: 'fixture-app',\n initiallyTruncated: true,\n recoveredTextField: true,\n hasIncrement: true,\n pngBytes: 90,\n signature: '89504e470d0a1a0a',\n imageWidth: 1,\n imageHeight: 1\n}\n"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"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":"tool-call","id":"cua-ptc-ax-failure","name":"run_code","arguments":"{\"code\":\"const { readFile, writeFile, unlink } = await import('node:fs/promises');\\nconst { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nawait writeFile('fixture-ax-failure', '');\\ntry {\\n const cua = connectCua(() => tools.cua);\\n const app = await cua.getApp('test.fixture');\\n const windows = await app.getWindows();\\n const window = await app.getWindow(windows[0].windowId);\\n const failures = [];\\n for (const surface of [app, window]) {\\n try { await surface.getAccessibilityTree(); throw new Error('Expected AX failure'); }\\n catch (error) { if (!error.message.includes('Fixture accessibility read failed')) throw error; failures.push(error.message); }\\n }\\n let coordinateRefused = false;\\n try { await window.click([100, 100], { relative: true }); }\\n catch (error) { if (!error.message.includes('Window has no observation')) throw error; coordinateRefused = true; }\\n if (!coordinateRefused) throw new Error('Coordinate input accepted without observation');\\n const shot = await window.getScreenshot();\\n const coordinateDispatched = (await window.click([100, 100], { relative: true })).dispatched;\\n let elementRefused = false;\\n try { await window.invoke('0'); }\\n catch (error) { if (!error.message.includes('Read getAccessibilityTree')) throw error; elementRefused = true; }\\n if (!elementRefused) throw new Error('Element input accepted without an AX snapshot');\\n inspect({ axFailures: failures.length, screenshotWindow: window.windowId, pngBytes: (await readFile(shot.path)).byteLength, elementRefused, coordinateRefused, coordinateDispatched }, shot);\\n} finally { await unlink('fixture-ax-failure'); }\",\"description\":\"Capture through the object API despite application and window AX failures\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:6}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794226987900,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794226987900,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-ptc-ax-failure","name":"run_code","arguments":"{\"code\":\"const { readFile, writeFile, unlink } = await import('node:fs/promises');\\nconst { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nawait writeFile('fixture-ax-failure', '');\\ntry {\\n const cua = connectCua(() => tools.cua);\\n const app = await cua.getApp('test.fixture');\\n const windows = await app.getWindows();\\n const window = await app.getWindow(windows[0].windowId);\\n const failures = [];\\n for (const surface of [app, window]) {\\n try { await surface.getAccessibilityTree(); throw new Error('Expected AX failure'); }\\n catch (error) { if (!error.message.includes('Fixture accessibility read failed')) throw error; failures.push(error.message); }\\n }\\n let coordinateRefused = false;\\n try { await window.click([100, 100], { relative: true }); }\\n catch (error) { if (!error.message.includes('Window has no observation')) throw error; coordinateRefused = true; }\\n if (!coordinateRefused) throw new Error('Coordinate input accepted without observation');\\n const shot = await window.getScreenshot();\\n const coordinateDispatched = (await window.click([100, 100], { relative: true })).dispatched;\\n let elementRefused = false;\\n try { await window.invoke('0'); }\\n catch (error) { if (!error.message.includes('Read getAccessibilityTree')) throw error; elementRefused = true; }\\n if (!elementRefused) throw new Error('Element input accepted without an AX snapshot');\\n inspect({ axFailures: failures.length, screenshotWindow: window.windowId, pngBytes: (await readFile(shot.path)).byteLength, elementRefused, coordinateRefused, coordinateDispatched }, shot);\\n} finally { await unlink('fixture-ax-failure'); }\",\"description\":\"Capture through the object API despite application and window AX failures\"}"}}},{"type":"chunk","time":1794226987901,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794226987901,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-ptc-ax-failure","name":"run_code","arguments":"{\"code\":\"const { readFile, writeFile, unlink } = await import('node:fs/promises');\\nconst { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nawait writeFile('fixture-ax-failure', '');\\ntry {\\n const cua = connectCua(() => tools.cua);\\n const app = await cua.getApp('test.fixture');\\n const windows = await app.getWindows();\\n const window = await app.getWindow(windows[0].windowId);\\n const failures = [];\\n for (const surface of [app, window]) {\\n try { await surface.getAccessibilityTree(); throw new Error('Expected AX failure'); }\\n catch (error) { if (!error.message.includes('Fixture accessibility read failed')) throw error; failures.push(error.message); }\\n }\\n let coordinateRefused = false;\\n try { await window.click([100, 100], { relative: true }); }\\n catch (error) { if (!error.message.includes('Window has no observation')) throw error; coordinateRefused = true; }\\n if (!coordinateRefused) throw new Error('Coordinate input accepted without observation');\\n const shot = await window.getScreenshot();\\n const coordinateDispatched = (await window.click([100, 100], { relative: true })).dispatched;\\n let elementRefused = false;\\n try { await window.invoke('0'); }\\n catch (error) { if (!error.message.includes('Read getAccessibilityTree')) throw error; elementRefused = true; }\\n if (!elementRefused) throw new Error('Element input accepted without an AX snapshot');\\n inspect({ axFailures: failures.length, screenshotWindow: window.windowId, pngBytes: (await readFile(shot.path)).byteLength, elementRefused, coordinateRefused, coordinateDispatched }, shot);\\n} finally { await unlink('fixture-ax-failure'); }\",\"description\":\"Capture through the object API despite application and window AX failures\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:6}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794554859184,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794554859184,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-ptc-ax-failure","name":"run_code","arguments":"{\"code\":\"const { readFile, writeFile, unlink } = await import('node:fs/promises');\\nconst { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nawait writeFile('fixture-ax-failure', '');\\ntry {\\n const cua = connectCua(() => tools.cua);\\n const app = await cua.getApp('test.fixture');\\n const windows = await app.getWindows();\\n const window = await app.getWindow(windows[0].windowId);\\n const failures = [];\\n for (const surface of [app, window]) {\\n try { await surface.getAccessibilityTree(); throw new Error('Expected AX failure'); }\\n catch (error) { if (!error.message.includes('Fixture accessibility read failed')) throw error; failures.push(error.message); }\\n }\\n let coordinateRefused = false;\\n try { await window.click([100, 100], { relative: true }); }\\n catch (error) { if (!error.message.includes('Window has no observation')) throw error; coordinateRefused = true; }\\n if (!coordinateRefused) throw new Error('Coordinate input accepted without observation');\\n const shot = await window.getScreenshot();\\n const coordinateDispatched = (await window.click([100, 100], { relative: true })).dispatched;\\n let elementRefused = false;\\n try { await window.invoke('0'); }\\n catch (error) { if (!error.message.includes('Read getAccessibilityTree')) throw error; elementRefused = true; }\\n if (!elementRefused) throw new Error('Element input accepted without an AX snapshot');\\n inspect({ axFailures: failures.length, screenshotWindow: window.windowId, pngBytes: (await readFile(shot.path)).byteLength, elementRefused, coordinateRefused, coordinateDispatched }, shot);\\n} finally { await unlink('fixture-ax-failure'); }\",\"description\":\"Capture through the object API despite application and window AX failures\"}"}}},{"type":"chunk","time":1794554859184,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794554859184,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"cua-ptc-ax-failure","name":"run_code","arguments":"{\"code\":\"const { readFile, writeFile, unlink } = await import('node:fs/promises');\\nconst { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nawait writeFile('fixture-ax-failure', '');\\ntry {\\n const cua = connectCua(() => tools.cua);\\n const app = await cua.getApp('test.fixture');\\n const windows = await app.getWindows();\\n const window = await app.getWindow(windows[0].windowId);\\n const failures = [];\\n for (const surface of [app, window]) {\\n try { await surface.getAccessibilityTree(); throw new Error('Expected AX failure'); }\\n catch (error) { if (!error.message.includes('Fixture accessibility read failed')) throw error; failures.push(error.message); }\\n }\\n let coordinateRefused = false;\\n try { await window.click([100, 100], { relative: true }); }\\n catch (error) { if (!error.message.includes('Window has no observation')) throw error; coordinateRefused = true; }\\n if (!coordinateRefused) throw new Error('Coordinate input accepted without observation');\\n const shot = await window.getScreenshot();\\n const coordinateDispatched = (await window.click([100, 100], { relative: true })).dispatched;\\n let elementRefused = false;\\n try { await window.invoke('0'); }\\n catch (error) { if (!error.message.includes('Read getAccessibilityTree')) throw error; elementRefused = true; }\\n if (!elementRefused) throw new Error('Element input accepted without an AX snapshot');\\n inspect({ axFailures: failures.length, screenshotWindow: window.windowId, pngBytes: (await readFile(shot.path)).byteLength, elementRefused, coordinateRefused, coordinateDispatched }, shot);\\n} finally { await unlink('fixture-ax-failure'); }\",\"description\":\"Capture through the object API despite application and window AX failures\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemPointer\":true,\"methods\":[\"activate\",\"click\",\"drag\",\"findApps\",\"getApp\",\"getCapabilities\",\"getState\",\"invoke\",\"listActions\",\"listApps\",\"listWindows\",\"mouseMove\",\"paste\",\"performAction\",\"pressKey\",\"screenshot\",\"scroll\",\"selectText\",\"sendKeyEvent\",\"setValue\",\"show\",\"typeText\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} @@ -46,7 +46,7 @@ {"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-ptc-ax-failure"},"toolCallId":"cua-ptc-ax-failure","content":[{"type":"text","text":"{\n axFailures: 2,\n screenshotWindow: '7',\n pngBytes: 90,\n elementRefused: true,\n coordinateRefused: true,\n coordinateDispatched: true\n}\n"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"isError":false,"id":"{{message:7}}"}},"sourceEventSeqs":[27],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":2}} {"type":"step/start","data":{"turn":1,"step":3}} -{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-ptc-writability","name":"run_code","arguments":"{\"code\":\"const { writeFile, unlink } = await import('node:fs/promises');\\nconst { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nconst cua = connectCua(() => tools.cua);\\nconst app = await cua.getApp('test.fixture');\\nconst results = [];\\nfor (const attribute of ['AXValue', 'AXSelectedTextRange']) {\\n await writeFile('fixture-ax-writability-failure', attribute);\\n try {\\n const tree = await app.getAccessibilityTree();\\n const field = attribute === 'AXValue' ? 'valueWritable' : 'selectionWritable';\\n if (!tree.includes(field + '=unknown') || tree.includes(field + '=true')) throw new Error('Unknown writability was lost');\\n if (!tree.includes('Increment') || !tree.includes('Count:')) throw new Error('Other nodes were lost');\\n let writeRefused = false;\\n try {\\n if (attribute === 'AXValue') await app.setValue('1', 'must not be written');\\n else await app.selectText('1', 'Fixture');\\n } catch (error) {\\n if (!error.message.includes('writability of ' + attribute + ' failed with error -25200')) throw error;\\n writeRefused = true;\\n }\\n if (!writeRefused) throw new Error('Write accepted with unknown writability');\\n results.push({ attribute, unknown: true, otherNodesRetained: true, writeRefused });\\n } finally { await unlink('fixture-ax-writability-failure'); }\\n}\\ninspect(results);\",\"description\":\"Retain AX trees with unknown writability and reject writes\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:8}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794226988058,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794226988058,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-ptc-writability","name":"run_code","arguments":"{\"code\":\"const { writeFile, unlink } = await import('node:fs/promises');\\nconst { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nconst cua = connectCua(() => tools.cua);\\nconst app = await cua.getApp('test.fixture');\\nconst results = [];\\nfor (const attribute of ['AXValue', 'AXSelectedTextRange']) {\\n await writeFile('fixture-ax-writability-failure', attribute);\\n try {\\n const tree = await app.getAccessibilityTree();\\n const field = attribute === 'AXValue' ? 'valueWritable' : 'selectionWritable';\\n if (!tree.includes(field + '=unknown') || tree.includes(field + '=true')) throw new Error('Unknown writability was lost');\\n if (!tree.includes('Increment') || !tree.includes('Count:')) throw new Error('Other nodes were lost');\\n let writeRefused = false;\\n try {\\n if (attribute === 'AXValue') await app.setValue('1', 'must not be written');\\n else await app.selectText('1', 'Fixture');\\n } catch (error) {\\n if (!error.message.includes('writability of ' + attribute + ' failed with error -25200')) throw error;\\n writeRefused = true;\\n }\\n if (!writeRefused) throw new Error('Write accepted with unknown writability');\\n results.push({ attribute, unknown: true, otherNodesRetained: true, writeRefused });\\n } finally { await unlink('fixture-ax-writability-failure'); }\\n}\\ninspect(results);\",\"description\":\"Retain AX trees with unknown writability and reject writes\"}"}}},{"type":"chunk","time":1794226988058,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794226988058,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-ptc-writability","name":"run_code","arguments":"{\"code\":\"const { writeFile, unlink } = await import('node:fs/promises');\\nconst { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nconst cua = connectCua(() => tools.cua);\\nconst app = await cua.getApp('test.fixture');\\nconst results = [];\\nfor (const attribute of ['AXValue', 'AXSelectedTextRange']) {\\n await writeFile('fixture-ax-writability-failure', attribute);\\n try {\\n const tree = await app.getAccessibilityTree();\\n const field = attribute === 'AXValue' ? 'valueWritable' : 'selectionWritable';\\n if (!tree.includes(field + '=unknown') || tree.includes(field + '=true')) throw new Error('Unknown writability was lost');\\n if (!tree.includes('Increment') || !tree.includes('Count:')) throw new Error('Other nodes were lost');\\n let writeRefused = false;\\n try {\\n if (attribute === 'AXValue') await app.setValue('1', 'must not be written');\\n else await app.selectText('1', 'Fixture');\\n } catch (error) {\\n if (!error.message.includes('writability of ' + attribute + ' failed with error -25200')) throw error;\\n writeRefused = true;\\n }\\n if (!writeRefused) throw new Error('Write accepted with unknown writability');\\n results.push({ attribute, unknown: true, otherNodesRetained: true, writeRefused });\\n } finally { await unlink('fixture-ax-writability-failure'); }\\n}\\ninspect(results);\",\"description\":\"Retain AX trees with unknown writability and reject writes\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:8}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794554859394,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794554859394,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-ptc-writability","name":"run_code","arguments":"{\"code\":\"const { writeFile, unlink } = await import('node:fs/promises');\\nconst { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nconst cua = connectCua(() => tools.cua);\\nconst app = await cua.getApp('test.fixture');\\nconst results = [];\\nfor (const attribute of ['AXValue', 'AXSelectedTextRange']) {\\n await writeFile('fixture-ax-writability-failure', attribute);\\n try {\\n const tree = await app.getAccessibilityTree();\\n const field = attribute === 'AXValue' ? 'valueWritable' : 'selectionWritable';\\n if (!tree.includes(field + '=unknown') || tree.includes(field + '=true')) throw new Error('Unknown writability was lost');\\n if (!tree.includes('Increment') || !tree.includes('Count:')) throw new Error('Other nodes were lost');\\n let writeRefused = false;\\n try {\\n if (attribute === 'AXValue') await app.setValue('1', 'must not be written');\\n else await app.selectText('1', 'Fixture');\\n } catch (error) {\\n if (!error.message.includes('writability of ' + attribute + ' failed with error -25200')) throw error;\\n writeRefused = true;\\n }\\n if (!writeRefused) throw new Error('Write accepted with unknown writability');\\n results.push({ attribute, unknown: true, otherNodesRetained: true, writeRefused });\\n } finally { await unlink('fixture-ax-writability-failure'); }\\n}\\ninspect(results);\",\"description\":\"Retain AX trees with unknown writability and reject writes\"}"}}},{"type":"chunk","time":1794554859394,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794554859394,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":3,"callId":"cua-ptc-writability","name":"run_code","arguments":"{\"code\":\"const { writeFile, unlink } = await import('node:fs/promises');\\nconst { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nconst cua = connectCua(() => tools.cua);\\nconst app = await cua.getApp('test.fixture');\\nconst results = [];\\nfor (const attribute of ['AXValue', 'AXSelectedTextRange']) {\\n await writeFile('fixture-ax-writability-failure', attribute);\\n try {\\n const tree = await app.getAccessibilityTree();\\n const field = attribute === 'AXValue' ? 'valueWritable' : 'selectionWritable';\\n if (!tree.includes(field + '=unknown') || tree.includes(field + '=true')) throw new Error('Unknown writability was lost');\\n if (!tree.includes('Increment') || !tree.includes('Count:')) throw new Error('Other nodes were lost');\\n let writeRefused = false;\\n try {\\n if (attribute === 'AXValue') await app.setValue('1', 'must not be written');\\n else await app.selectText('1', 'Fixture');\\n } catch (error) {\\n if (!error.message.includes('writability of ' + attribute + ' failed with error -25200')) throw error;\\n writeRefused = true;\\n }\\n if (!writeRefused) throw new Error('Write accepted with unknown writability');\\n results.push({ attribute, unknown: true, otherNodesRetained: true, writeRefused });\\n } finally { await unlink('fixture-ax-writability-failure'); }\\n}\\ninspect(results);\",\"description\":\"Retain AX trees with unknown writability and reject writes\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-writability","parentCallId":"cua-ptc-writability","subCallId":"cua-ptc-writability:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-writability","parentCallId":"cua-ptc-writability","subCallId":"cua-ptc-writability:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemPointer\":true,\"methods\":[\"activate\",\"click\",\"drag\",\"findApps\",\"getApp\",\"getCapabilities\",\"getState\",\"invoke\",\"listActions\",\"listApps\",\"listWindows\",\"mouseMove\",\"paste\",\"performAction\",\"pressKey\",\"screenshot\",\"scroll\",\"selectText\",\"sendKeyEvent\",\"setValue\",\"show\",\"typeText\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} @@ -63,6 +63,36 @@ {"type":"tool/result","data":{"turn":1,"step":3,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-ptc-writability"},"toolCallId":"cua-ptc-writability","content":[{"type":"text","text":"[\n {\n attribute: 'AXValue',\n unknown: true,\n otherNodesRetained: true,\n writeRefused: true\n },\n {\n attribute: 'AXSelectedTextRange',\n unknown: true,\n otherNodesRetained: true,\n writeRefused: true\n }\n]\n"}],"isError":false,"id":"{{message:9}}"}},"sourceEventSeqs":[48],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":3}} {"type":"step/start","data":{"turn":1,"step":4}} -{"type":"assistant/message","data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"text","text":"Received native CUA values and PNG screenshots through PTC. The object API captured a 90-byte PNG after two AX read failures and refused element input without an accessibility snapshot. Both writability probe failures left the tree readable with unknown fields and kept writes strict."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:10}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794226988201,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1794226988201,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Received native CUA values and PNG screenshots through PTC. The object API captured a 90-byte PNG after two AX read failures and refused element input without an accessibility snapshot. Both writability probe failures left the tree readable with unknown fields and kept writes strict."}}},{"type":"chunk","time":1794226988201,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794226988201,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-ptc-output-limit","name":"run_code","arguments":"{\"code\":\"const { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nconst cua = connectCua(() => tools.cua);\\nconst app = await cua.getApp('test.fixture');\\nconst window = await app.getWindow('7');\\nconst tree = await window.getAccessibilityTree();\\nif (!tree.includes('Count: 1')) throw new Error('Unexpected initial action count');\\nawait window.click('0');\\ninspect(await window.getScreenshot());\\ninspect('x'.repeat(8192));\\nawait window.getAccessibilityTree();\\nawait window.click('0');\",\"description\":\"Complete planned clicks before and after output truncation\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:10}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794554859587,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794554859587,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-ptc-output-limit","name":"run_code","arguments":"{\"code\":\"const { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nconst cua = connectCua(() => tools.cua);\\nconst app = await cua.getApp('test.fixture');\\nconst window = await app.getWindow('7');\\nconst tree = await window.getAccessibilityTree();\\nif (!tree.includes('Count: 1')) throw new Error('Unexpected initial action count');\\nawait window.click('0');\\ninspect(await window.getScreenshot());\\ninspect('x'.repeat(8192));\\nawait window.getAccessibilityTree();\\nawait window.click('0');\",\"description\":\"Complete planned clicks before and after output truncation\"}"}}},{"type":"chunk","time":1794554859587,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794554859587,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":4,"callId":"cua-ptc-output-limit","name":"run_code","arguments":"{\"code\":\"const { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nconst cua = connectCua(() => tools.cua);\\nconst app = await cua.getApp('test.fixture');\\nconst window = await app.getWindow('7');\\nconst tree = await window.getAccessibilityTree();\\nif (!tree.includes('Count: 1')) throw new Error('Unexpected initial action count');\\nawait window.click('0');\\ninspect(await window.getScreenshot());\\ninspect('x'.repeat(8192));\\nawait window.getAccessibilityTree();\\nawait window.click('0');\",\"description\":\"Complete planned clicks before and after output truncation\"}"}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-output-limit","parentCallId":"cua-ptc-output-limit","subCallId":"cua-ptc-output-limit:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-output-limit","parentCallId":"cua-ptc-output-limit","subCallId":"cua-ptc-output-limit:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemPointer\":true,\"methods\":[\"activate\",\"click\",\"drag\",\"findApps\",\"getApp\",\"getCapabilities\",\"getState\",\"invoke\",\"listActions\",\"listApps\",\"listWindows\",\"mouseMove\",\"paste\",\"performAction\",\"pressKey\",\"screenshot\",\"scroll\",\"selectText\",\"sendKeyEvent\",\"setValue\",\"show\",\"typeText\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-output-limit","parentCallId":"cua-ptc-output-limit","subCallId":"cua-ptc-output-limit:ptc:2","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-output-limit","parentCallId":"cua-ptc-output-limit","subCallId":"cua-ptc-output-limit:ptc:2","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"name\":\"Fixture\",\"bundleId\":\"test.fixture\",\"running\":true}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-output-limit","parentCallId":"cua-ptc-output-limit","subCallId":"cua-ptc-output-limit:ptc:3","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-output-limit","parentCallId":"cua-ptc-output-limit","subCallId":"cua-ptc-output-limit:ptc:3","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"focusedWindowId\":\"7\",\"snapshotId\":\"fixture-snapshot-5\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 1\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":\"7\",\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":\"8\",\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":\"9\",\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-output-limit","parentCallId":"cua-ptc-output-limit","subCallId":"cua-ptc-output-limit:ptc:4","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-5","elementId":"0"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-output-limit","parentCallId":"cua-ptc-output-limit","subCallId":"cua-ptc-output-limit:ptc:4","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-5","elementId":"0"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-output-limit","parentCallId":"cua-ptc-output-limit","subCallId":"cua-ptc-output-limit:ptc:5","name":"cua","arguments":{"method":"screenshot","params":{"appHandle":"fixture-app","windowId":"7"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-output-limit","parentCallId":"cua-ptc-output-limit","subCallId":"cua-ptc-output-limit:ptc:5","name":"cua","arguments":{"method":"screenshot","params":{"appHandle":"fixture-app","windowId":"7"}},"isError":false,"content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":\"7\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-output-limit","parentCallId":"cua-ptc-output-limit","subCallId":"cua-ptc-output-limit:ptc:6","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-output-limit","parentCallId":"cua-ptc-output-limit","subCallId":"cua-ptc-output-limit:ptc:6","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"focusedWindowId\":\"7\",\"snapshotId\":\"fixture-snapshot-6\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 2\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":\"7\",\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":\"8\",\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":\"9\",\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-output-limit","parentCallId":"cua-ptc-output-limit","subCallId":"cua-ptc-output-limit:ptc:7","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-6","elementId":"0"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-output-limit","parentCallId":"cua-ptc-output-limit","subCallId":"cua-ptc-output-limit:ptc:7","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-6","elementId":"0"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} +{"type":"tool/result","data":{"turn":1,"step":4,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-ptc-output-limit"},"toolCallId":"cua-ptc-output-limit","content":[{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}},{"type":"text","text":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"},{"type":"text","text":"Program completed. Output was truncated; read current state for missing information without repeating completed actions."}],"isError":false,"id":"{{message:11}}"}},"sourceEventSeqs":[65],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":4}} +{"type":"step/start","data":{"turn":1,"step":5}} +{"type":"assistant/message","data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-ptc-observe-after-limit","name":"run_code","arguments":"{\"code\":\"const { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nconst cua = connectCua(() => tools.cua);\\nconst app = await cua.getApp('test.fixture');\\nconst tree = await app.getAccessibilityTree();\\nif (!tree.includes('Count: 3')) throw new Error('Output overflow changed the action count');\\ninspect({ count: 3, repeated: false });\",\"description\":\"Verify both planned actions completed without replaying input\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:12}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794554859782,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794554859782,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-ptc-observe-after-limit","name":"run_code","arguments":"{\"code\":\"const { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nconst cua = connectCua(() => tools.cua);\\nconst app = await cua.getApp('test.fixture');\\nconst tree = await app.getAccessibilityTree();\\nif (!tree.includes('Count: 3')) throw new Error('Output overflow changed the action count');\\ninspect({ count: 3, repeated: false });\",\"description\":\"Verify both planned actions completed without replaying input\"}"}}},{"type":"chunk","time":1794554859782,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794554859782,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":5,"callId":"cua-ptc-observe-after-limit","name":"run_code","arguments":"{\"code\":\"const { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nconst cua = connectCua(() => tools.cua);\\nconst app = await cua.getApp('test.fixture');\\nconst tree = await app.getAccessibilityTree();\\nif (!tree.includes('Count: 3')) throw new Error('Output overflow changed the action count');\\ninspect({ count: 3, repeated: false });\",\"description\":\"Verify both planned actions completed without replaying input\"}"}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-observe-after-limit","parentCallId":"cua-ptc-observe-after-limit","subCallId":"cua-ptc-observe-after-limit:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-observe-after-limit","parentCallId":"cua-ptc-observe-after-limit","subCallId":"cua-ptc-observe-after-limit:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemPointer\":true,\"methods\":[\"activate\",\"click\",\"drag\",\"findApps\",\"getApp\",\"getCapabilities\",\"getState\",\"invoke\",\"listActions\",\"listApps\",\"listWindows\",\"mouseMove\",\"paste\",\"performAction\",\"pressKey\",\"screenshot\",\"scroll\",\"selectText\",\"sendKeyEvent\",\"setValue\",\"show\",\"typeText\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-observe-after-limit","parentCallId":"cua-ptc-observe-after-limit","subCallId":"cua-ptc-observe-after-limit:ptc:2","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-observe-after-limit","parentCallId":"cua-ptc-observe-after-limit","subCallId":"cua-ptc-observe-after-limit:ptc:2","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"name\":\"Fixture\",\"bundleId\":\"test.fixture\",\"running\":true}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-observe-after-limit","parentCallId":"cua-ptc-observe-after-limit","subCallId":"cua-ptc-observe-after-limit:ptc:3","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-observe-after-limit","parentCallId":"cua-ptc-observe-after-limit","subCallId":"cua-ptc-observe-after-limit:ptc:3","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":null,\"focusedWindowId\":\"7\",\"snapshotId\":\"fixture-snapshot-7\",\"tree\":\"AX scope=application offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 3\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":\"7\",\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":\"8\",\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":\"9\",\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}]}} +{"type":"tool/result","data":{"turn":1,"step":5,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-ptc-observe-after-limit"},"toolCallId":"cua-ptc-observe-after-limit","content":[{"type":"text","text":"{ count: 3, repeated: false }\n"}],"isError":false,"id":"{{message:13}}"}},"sourceEventSeqs":[84],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":5}} +{"type":"step/start","data":{"turn":1,"step":6}} +{"type":"assistant/message","data":{"turn":1,"step":6,"message":{"role":"assistant","content":[{"type":"text","text":"Received native CUA values and PNG screenshots through PTC. The object API captured a 90-byte PNG after two AX read failures and refused element input without an accessibility snapshot. Both writability probe failures left the tree readable with unknown fields and kept writes strict. Output truncation retained the inspected screenshot and the program completed both planned clicks. A fresh observation confirmed exactly three clicks in total, without replaying input."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:14}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794554859954,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1794554859954,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Received native CUA values and PNG screenshots through PTC. The object API captured a 90-byte PNG after two AX read failures and refused element input without an accessibility snapshot. Both writability probe failures left the tree readable with unknown fields and kept writes strict. Output truncation retained the inspected screenshot and the program completed both planned clicks. A fresh observation confirmed exactly three clicks in total, without replaying input."}}},{"type":"chunk","time":1794554859955,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794554859955,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":6}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/snapshots/session/cua-run-code-ptc/system-prompt.expected.md b/snapshots/session/cua-run-code-ptc/system-prompt.expected.md index bb4eb419d5..39ddc25509 100644 --- a/snapshots/session/cua-run-code-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-run-code-ptc/system-prompt.expected.md @@ -151,7 +151,7 @@ interface ToolArgsMap { /** Optional positive safe-integer limit on automatic continuation rounds. */ max_goal_rounds?: number; } & Record; - /** 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. */ + /** 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. */ cua_run_code: { /** The TypeScript program to execute, following this tool's execution instructions. */ code: string; @@ -433,6 +433,7 @@ interface ToolOutputMap { }; cua_run_code: { logs: string[]; + outputTruncated?: boolean; sandbox?: { mode: "read-only" | "workspace-write" | "danger-full-access"; denied: boolean; diff --git a/snapshots/session/cua-run-code-scoped/tool-schemas.expected.json b/snapshots/session/cua-run-code-scoped/tool-schemas.expected.json index 59fef2f60a..f4a29792d6 100644 --- a/snapshots/session/cua-run-code-scoped/tool-schemas.expected.json +++ b/snapshots/session/cua-run-code-scoped/tool-schemas.expected.json @@ -95,7 +95,7 @@ }, { "name": "cua_run_code", - "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.", "parameters": { "type": "object", "properties": { diff --git a/snapshots/session/cua-run-code/tool-schemas.expected.json b/snapshots/session/cua-run-code/tool-schemas.expected.json index 81e69dddae..73fbe3c79a 100644 --- a/snapshots/session/cua-run-code/tool-schemas.expected.json +++ b/snapshots/session/cua-run-code/tool-schemas.expected.json @@ -95,7 +95,7 @@ }, { "name": "cua_run_code", - "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. Variables, functions, and imported modules remain in memory for this Agent across calls. Use await import(...) for modules. 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. Do not redeclare existing let, const, or class names; reuse mutable bindings or choose new names. 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. Variables, functions, and imported modules remain in memory for this Agent across calls. Use await import(...) for modules. 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. Do not redeclare existing let, const, or class names; reuse mutable bindings or choose new names. 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.", "parameters": { "type": "object", "properties": { diff --git a/snapshots/session/dsh-doc-load/session.v4.jsonl b/snapshots/session/dsh-doc-load/session.v4.jsonl index bb5d14fdd9..b8c16d3b78 100644 --- a/snapshots/session/dsh-doc-load/session.v4.jsonl +++ b/snapshots/session/dsh-doc-load/session.v4.jsonl @@ -15,7 +15,7 @@ {"type":"session/title","data":{"title":"Load dsh-doc, read .dsh/skills/dsh-doc/r","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"Load the requested skill."},{"type":"tool-call","id":"call_skill_load","name":"skill","arguments":"{\"name\":\"dsh-doc\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:5}}"},"usage":{"inputTokens":100,"outputTokens":20,"cacheReadTokens":0,"reasoningTokens":5},"stream":[{"type":"chunk","time":1788699430688,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1788699430688,"index":0,"dt":[],"texts":["Load the requested skill."]},{"type":"chunk","time":1788699430688,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1788699430688,"index":1,"dt":[],"id":"call_skill_load","name":"skill","args":["{\"name\":\"dsh-doc\"}"]},{"type":"chunk","time":1788699430688,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"Load the requested skill."}}},{"type":"chunk","time":1788699430688,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_skill_load","name":"skill","arguments":"{\"name\":\"dsh-doc\"}"}}},{"type":"chunk","time":1788699430688,"chunk":{"type":"usage","usage":{"inputTokens":100,"outputTokens":20,"cacheReadTokens":0,"reasoningTokens":5}}},{"type":"chunk","time":1788699430688,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_skill_load","name":"skill","arguments":"{\"name\":\"dsh-doc\"}"}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_skill_load"},"toolCallId":"call_skill_load","content":[{"type":"text","text":"\n\nBase directory for this skill: {{cwd}}/.dsh/skills/dsh-doc\nResolve relative paths mentioned by this skill against the base directory before using them. Load referenced resources only as needed.\n\n\n\n# DeepSeek Harness documentation\n\nAnswer questions about DSH from the documentation and source of the installed version, not from memory, and extend DSH through bundles installed in the current profile.\n\nLoading this skill does not authorize changes. Write bundle files, run mutating `plugin_manager` actions such as installing, enabling, disabling, or removing, or change a preset only when the user asks to change DSH or its profile. For a question, design, or review, read-only lookups, including `list_plugins` and `list_bundles` within your tool permissions, remain available; report findings and leave files and the profile unchanged. A request for an image, widget, or decoration that does not target DSH, such as its Web UI or profile, is not a request for a DSH plugin; deliver the ordinary artifact the task asks for.\n\n## Find facts in this order\n\n1. Runtime inspection, when `cordis_inspect` is among your tools: exact Service methods and Event modes, a mounted plugin's Config schema and `packageDir`, the Tools this Agent can call, and live Client Slots and theme tokens.\n2. The installed documentation and package sources, located as `references/locate-docs.md` describes.\n3. When an answer depends on a live API that you can neither inspect nor read, state what remains unverified. Do not change a preset or the profile to gain tools.\n\n## Read next\n\nThe files below live in this skill's base directory, which the `skill` tool reported, and the table is the complete list: do not enumerate that directory. Read them with the file-read tool, write copies into the workspace with the file-write tool, and verify a copy by reading it back. In Desktop the directory sits inside `app.asar`, which the file-read tool and the runtime that `references/locate-docs.md` describes can open; native utilities such as `ls`, `cat`, `cp`, and `cmp`, the glob and search tools, a `node` from `PATH`, and pnpm fail on it. Never install or syntax-check a template in place; copy its contents into the workspace first.\n\n| Task | File |\n|---|---|\n| Find the installed version's documentation and package sources | `references/locate-docs.md` |\n| Build, install, enable, or debug a plugin or bundle | `references/plugin-development.md` |\n| Bundle manifest, locale resources, detail document, icons, installation, Host exports and Config | `references/host-plugin.md` |\n| Bundle descriptions, optional single-image details, locale paths and preview verification | `references/plugin-details.md` |\n| Save plugin configuration or credentials | `references/configuration.md` |\n| Web UI: Client manifest, module loader, slot registration | `references/ui-plugin.md` |\n| Connect an MCP server through a configuration-only bundle | `references/mcp-bundle.md` |\n| Choose extension points, contexts, and state mechanisms | `references/practices.md` |\n| Share application operations between UI actions and agent tools | `references/user-actions.md` |\n| Verify a page or panel, review its user experience, or work without browser control | `references/verification.md` |\n| Draw icons and feature images | `references/artwork.md` |\n| Create, change, or migrate an agent preset; choose Host or preset placement | `references/compositions.md` |\n| Upgrade a plugin or profile to a newer DSH release | `references/upgrading.md` |\n| Loader patch dialect | `references/composition-reference.md` |\n| Installable plugin packages, one table per package group | `references/packages.md` |\n| Write a DSH tool definition, skill, or multi-step workflow | `references/tool-design.md` |\n| UI plugin template | `templates/decoration/package.json`, `templates/decoration/cordis.patch.yml`, `templates/decoration/index.js`, `templates/decoration/client.js`, `templates/decoration/locale`, `templates/decoration/docs/DETAIL.md`, `templates/decoration/docs/preview.svg`, `templates/decoration/icon.svg` |\n| MCP bundle template | `templates/mcp/package.json`, `templates/mcp/cordis.patch.yml`, `templates/mcp/locale`, `templates/mcp/docs/DETAIL.md`, `templates/mcp/docs/preview.svg`, `templates/mcp/icon.svg` |\n\n"}],"isError":false,"id":"{{message:6}}"}},"sourceEventSeqs":[15],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_skill_load"},"toolCallId":"call_skill_load","content":[{"type":"text","text":"\n\nBase directory for this skill: {{cwd}}/.dsh/skills/dsh-doc\nResolve relative paths mentioned by this skill against the base directory before using them. Load referenced resources only as needed.\n\n\n\n# DeepSeek Harness documentation\n\nAnswer questions about DSH from the documentation and source of the installed version, not from memory, and extend DSH through bundles installed in the current profile.\n\nLoading this skill does not authorize changes. Write bundle files, run mutating `plugin_manager` actions such as installing, enabling, disabling, or removing, or change a preset only when the user asks to change DSH or its profile. For a question, design, or review, read-only lookups, including `list_plugins` and `list_bundles` within your tool permissions, remain available; report findings and leave files and the profile unchanged. A request for an image, widget, or decoration that does not target DSH, such as its Web UI or profile, is not a request for a DSH plugin; deliver the ordinary artifact the task asks for.\n\n## Find facts in this order\n\n1. Runtime inspection, when `cordis_inspect` is among your tools: exact Service methods and Event modes, a mounted plugin's Config schema and `packageDir`, the Tools this Agent can call, and live Client Slots and theme tokens.\n2. The installed documentation and package sources, located as `references/locate-docs.md` describes.\n3. When an answer depends on a live API that you can neither inspect nor read, state what remains unverified. Do not change a preset or the profile to gain tools.\n\n## Read next\n\nThe files below live in this skill's base directory, which the `skill` tool reported, and the table is the complete list: do not enumerate that directory. Read them with the file-read tool, write copies into the workspace with the file-write tool, and verify a copy by reading it back. In Desktop the directory sits inside `app.asar`, which the file-read tool and the runtime that `references/locate-docs.md` describes can open; native utilities such as `ls`, `cat`, `cp`, and `cmp`, the glob and search tools, a `node` from `PATH`, and pnpm fail on it. Never install or syntax-check a template in place; copy its contents into the workspace first.\n\n| Task | File |\n|---|---|\n| Find the installed version's documentation and package sources | `references/locate-docs.md` |\n| Build, install, enable, or debug a plugin or bundle | `references/plugin-development.md` |\n| Bundle manifest, locale resources, detail document, icons, installation, Host exports and Config | `references/host-plugin.md` |\n| Read the running DSH version; declare `engines.dsh` | `references/dsh-version.md` |\n| Bundle descriptions, optional single-image details, locale paths and preview verification | `references/plugin-details.md` |\n| Save plugin configuration or credentials | `references/configuration.md` |\n| Web UI: Client manifest, module loader, slot registration | `references/ui-plugin.md` |\n| Connect an MCP server through a configuration-only bundle | `references/mcp-bundle.md` |\n| Choose extension points, contexts, and state mechanisms | `references/practices.md` |\n| Share application operations between UI actions and agent tools | `references/user-actions.md` |\n| Verify a page or panel, review its user experience, or work without browser control | `references/verification.md` |\n| Draw icons and feature images | `references/artwork.md` |\n| Create, change, or migrate an agent preset; choose Host or preset placement | `references/compositions.md` |\n| Upgrade a plugin or profile to a newer DSH release | `references/upgrading.md` |\n| Loader patch dialect | `references/composition-reference.md` |\n| Installable plugin packages, one table per package group | `references/packages.md` |\n| Write a DSH tool definition, skill, or multi-step workflow | `references/tool-design.md` |\n| UI plugin template | `templates/decoration/package.json`, `templates/decoration/cordis.patch.yml`, `templates/decoration/index.js`, `templates/decoration/client.js`, `templates/decoration/locale`, `templates/decoration/docs/DETAIL.md`, `templates/decoration/docs/preview.svg`, `templates/decoration/icon.svg` |\n| MCP bundle template | `templates/mcp/package.json`, `templates/mcp/cordis.patch.yml`, `templates/mcp/locale`, `templates/mcp/docs/DETAIL.md`, `templates/mcp/docs/preview.svg`, `templates/mcp/icon.svg` |\n\n"}],"isError":false,"id":"{{message:6}}"}},"sourceEventSeqs":[15],"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":"tool-call","id":"call_read_2","name":"read","arguments":"{\"file_path\":\".dsh/skills/dsh-doc/references/artwork.md\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:7}}"},"stream":[{"type":"chunk","time":1788699430711,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1788699430711,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_read_2","name":"read","arguments":"{\"file_path\":\".dsh/skills/dsh-doc/references/artwork.md\"}"}}},{"type":"chunk","time":1788699430711,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} @@ -25,12 +25,12 @@ {"type":"step/start","data":{"turn":1,"step":3}} {"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_read_3","name":"read","arguments":"{\"file_path\":\".dsh/skills/dsh-doc/references/host-plugin.md\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:9}}"},"stream":[{"type":"chunk","time":1788699430712,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1788699430712,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_read_3","name":"read","arguments":"{\"file_path\":\".dsh/skills/dsh-doc/references/host-plugin.md\"}"}}},{"type":"chunk","time":1788699430712,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":3,"callId":"call_read_3","name":"read","arguments":"{\"file_path\":\".dsh/skills/dsh-doc/references/host-plugin.md\"}"}} -{"type":"tool/result","data":{"turn":1,"step":3,"message":{"role":"tool","source":{"kind":"tool","callId":"call_read_3"},"toolCallId":"call_read_3","content":[{"type":"text","text":"{{cwd}}/.dsh/skills/dsh-doc/references/host-plugin.md\nfile\n\n1: # Bundles and Host plugins\n2: \n3: A bundle is a package whose `package.json` declares `dsh.bundle.patch`; the YAML patch inserts plugin entries. Give the package and rows unique names; use the Loader's existing YAML syntax, including `!!js` where expressions are needed. Read an existing patch before editing it: a matching override replaces the complete `config`.\n4: \n5: ## Manifest\n6: \n7: A Host-only bundle needs no dependencies, install scripts, or build tool:\n8: \n9: ```json\n10: {\n11: \"name\": \"@local/my-plugin\",\n12: \"version\": \"1.0.0\",\n13: \"private\": true,\n14: \"type\": \"module\",\n15: \"exports\": { \".\": \"./index.js\" },\n16: \"dsh\": { \"bundle\": { \"patch\": \"./cordis.patch.yml\" } }\n17: }\n18: ```\n19: \n20: `cordis.patch.yml`:\n21: \n22: ```yaml\n23: - insert:\n24: - id: my-plugin\n25: name: '@local/my-plugin'\n26: config: {}\n27: ```\n28: \n29: ## Display metadata, detail document, and icon\n30: \n31: Plugin Manager and Settings read `meta.title` and `meta.description` from exported locale JSON and an icon from exported resources without activating plugins. The bundle's page in Plugin Manager shows the detail document that `meta.detail` names, otherwise the package README. Complete this checklist before installation:\n32: \n33: - Write a recognizable title and a description of the capability in `locale/en.json` under `meta.title` and `meta.description`. Add the same fields for the user's language and other supported locales, such as `locale/zh.json`; do not leave template copy unrelated to the delivered plugin. Write English titles and other UI labels in sentence case: capitalize only the first word and proper nouns, as in `Git worktrees`.\n34: - For the bundle's detail page, keep functionality, usage, and essential limitations in `meta.description`; follow `references/plugin-details.md` for an optional single-image document, locale paths, packaging, and verification. State only behavior you implemented and verified. The page omits raw HTML and renders relative links as plain text. A malformed `meta.detail`, a missing named file, or a document exceeding `pluginManager.detailMaxBytes` (1 MiB by default) makes the detail section show the failure with **Retry** instead of falling back to the README.\n35: - Create an original icon or use artwork whose license permits redistribution, retaining any required attribution. Read `references/artwork.md` before drawing or revising an icon.\n36: - Export `./locale/*.json` and `./icon`; retain existing runtime exports. Keep the patch, locales, the detail document's directory, icon, and every runtime file in `files`, updating it whenever you add modules or assets. For a packed or published bundle, verify the actual packed file list. Local directory installation links the checkout instead, so check the files directly; `files` does not filter a linked directory.\n37: - Check that the icon is a valid image of the declared format and satisfies the path and size limits below. An accepted filename alone does not establish that its bytes render.\n38: \n39: For example, the locale file contains:\n40: \n41: ```json\n42: { \"meta\": { \"title\": \"My decoration\", \"description\": \"Draws a badge under the composer.\", \"detail\": \"docs/DETAIL.md\" } }\n43: ```\n44: \n45: ```json\n46: {\n47: \"exports\": { \"./locale/*.json\": \"./locale/*.json\", \"./icon\": \"./icon.svg\" },\n48: \"files\": [\"index.js\", \"cordis.patch.yml\", \"locale/*.json\", \"docs\", \"icon.svg\"]\n49: }\n50: ```\n51: \n52: A package-root plugin may instead declare a top-level `icon` in `package.json`; it takes priority over `./icon` and is a path relative to the manifest directory. A subpath plugin such as `my-plugins/search` is not a package and never reads a `package.json`; it exports `./search/locale/*.json` and `./search/icon` instead. Icons may be SVG, PNG, JPEG, or WebP up to 256 KiB and must stay inside the package; absolute paths, URLs, and symlinks leaving it are rejected. Missing fields of a package-root plugin fall back to `package.json` `name` and `description`, and missing images use the panel's default artwork; malformed metadata produces a diagnostic and keeps the valid text.\n53: \n54: After installation, verify the intended title, description, and detail document in bundle details and plugin rows, plus the rendered icons, in English and the user's locale where supplied. Check for metadata diagnostics and unintended fallbacks, and that each plugin row shows its own exported icon or, when it has none, the generic artwork. Without browser control, inspect the installed resources and report that rendered display remains unverified; do not claim visual success from installation alone.\n55: \n56: An existing plugin's metadata may remain unchanged when it still describes the requested result. A disposable test fixture or an explicitly requested metadata-free package may omit resources, but explain each omission in the delivery report. A Host-only or configuration-only bundle still has a visible inventory entry; neither is an exception by itself.\n57: \n58: ## Host plugin export forms\n59: \n60: `index.js` exports one of these forms; do not mix them:\n61: \n62: - `export function apply(ctx, config) {}` with optional `export const inject = ['tools']` and `export const Config`.\n63: - A service class as the default export.\n64: \n65: Register every resource inside `apply` with `ctx.effect` or `ctx.on` and return its cleanup. A plugin that declares `Config` validates the row's `config` at activation; before writing an installed plugin's `config`, read its schema from `Config.listConfigs` through `cordis_inspect`, following `$defs` references, or from the owning package's README and source when inspection is unavailable.\n66: \n67: ## Persist your own configuration\n68: \n69: Read `references/configuration.md` before saving plugin configuration or credentials.\n70: \n71: ## Install, enable, and observe\n72: \n73: `plugin_manager` `install_bundle` performs package installation and bundle selection; do not reproduce those steps with shell commands. Only pass `approvedBuilds` after the user explicitly approves the reported pending build scripts. Preserve returned failures and pending states; report success only after observing the requested capability.\n74: \n75: `list_plugins` and `list_bundles` return exact identifiers for existing installations. `set_plugin` and `set_bundle` toggle them; `remove_bundle` removes a bundle. Inspect saved-state and activation outcomes separately: `failed` requires diagnosis, `overridden` means a higher-priority layer wins, and `restart-required` means the change is not live. Installing a new bundle can activate through HMR; replacing an installed package requires restart to load a fresh JavaScript module generation. Do not infer updated browser code from an unchanged slot id.\n\n(End of file - total 75 lines)\n"}],"isError":false,"id":"{{message:10}}"},"meta":{"path":"{{cwd}}/.dsh/skills/dsh-doc/references/host-plugin.md","offset":1,"lines":[{"number":1,"text":"# Bundles and Host plugins"},{"number":2,"text":""},{"number":3,"text":"A bundle is a package whose `package.json` declares `dsh.bundle.patch`; the YAML patch inserts plugin entries. Give the package and rows unique names; use the Loader's existing YAML syntax, including `!!js` where expressions are needed. Read an existing patch before editing it: a matching override replaces the complete `config`."},{"number":4,"text":""},{"number":5,"text":"## Manifest"},{"number":6,"text":""},{"number":7,"text":"A Host-only bundle needs no dependencies, install scripts, or build tool:"},{"number":8,"text":""},{"number":9,"text":"```json"},{"number":10,"text":"{"},{"number":11,"text":" \"name\": \"@local/my-plugin\","},{"number":12,"text":" \"version\": \"1.0.0\","},{"number":13,"text":" \"private\": true,"},{"number":14,"text":" \"type\": \"module\","},{"number":15,"text":" \"exports\": { \".\": \"./index.js\" },"},{"number":16,"text":" \"dsh\": { \"bundle\": { \"patch\": \"./cordis.patch.yml\" } }"},{"number":17,"text":"}"},{"number":18,"text":"```"},{"number":19,"text":""},{"number":20,"text":"`cordis.patch.yml`:"},{"number":21,"text":""},{"number":22,"text":"```yaml"},{"number":23,"text":"- insert:"},{"number":24,"text":" - id: my-plugin"},{"number":25,"text":" name: '@local/my-plugin'"},{"number":26,"text":" config: {}"},{"number":27,"text":"```"},{"number":28,"text":""},{"number":29,"text":"## Display metadata, detail document, and icon"},{"number":30,"text":""},{"number":31,"text":"Plugin Manager and Settings read `meta.title` and `meta.description` from exported locale JSON and an icon from exported resources without activating plugins. The bundle's page in Plugin Manager shows the detail document that `meta.detail` names, otherwise the package README. Complete this checklist before installation:"},{"number":32,"text":""},{"number":33,"text":"- Write a recognizable title and a description of the capability in `locale/en.json` under `meta.title` and `meta.description`. Add the same fields for the user's language and other supported locales, such as `locale/zh.json`; do not leave template copy unrelated to the delivered plugin. Write English titles and other UI labels in sentence case: capitalize only the first word and proper nouns, as in `Git worktrees`."},{"number":34,"text":"- For the bundle's detail page, keep functionality, usage, and essential limitations in `meta.description`; follow `references/plugin-details.md` for an optional single-image document, locale paths, packaging, and verification. State only behavior you implemented and verified. The page omits raw HTML and renders relative links as plain text. A malformed `meta.detail`, a missing named file, or a document exceeding `pluginManager.detailMaxBytes` (1 MiB by default) makes the detail section show the failure with **Retry** instead of falling back to the README."},{"number":35,"text":"- Create an original icon or use artwork whose license permits redistribution, retaining any required attribution. Read `references/artwork.md` before drawing or revising an icon."},{"number":36,"text":"- Export `./locale/*.json` and `./icon`; retain existing runtime exports. Keep the patch, locales, the detail document's directory, icon, and every runtime file in `files`, updating it whenever you add modules or assets. For a packed or published bundle, verify the actual packed file list. Local directory installation links the checkout instead, so check the files directly; `files` does not filter a linked directory."},{"number":37,"text":"- Check that the icon is a valid image of the declared format and satisfies the path and size limits below. An accepted filename alone does not establish that its bytes render."},{"number":38,"text":""},{"number":39,"text":"For example, the locale file contains:"},{"number":40,"text":""},{"number":41,"text":"```json"},{"number":42,"text":"{ \"meta\": { \"title\": \"My decoration\", \"description\": \"Draws a badge under the composer.\", \"detail\": \"docs/DETAIL.md\" } }"},{"number":43,"text":"```"},{"number":44,"text":""},{"number":45,"text":"```json"},{"number":46,"text":"{"},{"number":47,"text":" \"exports\": { \"./locale/*.json\": \"./locale/*.json\", \"./icon\": \"./icon.svg\" },"},{"number":48,"text":" \"files\": [\"index.js\", \"cordis.patch.yml\", \"locale/*.json\", \"docs\", \"icon.svg\"]"},{"number":49,"text":"}"},{"number":50,"text":"```"},{"number":51,"text":""},{"number":52,"text":"A package-root plugin may instead declare a top-level `icon` in `package.json`; it takes priority over `./icon` and is a path relative to the manifest directory. A subpath plugin such as `my-plugins/search` is not a package and never reads a `package.json`; it exports `./search/locale/*.json` and `./search/icon` instead. Icons may be SVG, PNG, JPEG, or WebP up to 256 KiB and must stay inside the package; absolute paths, URLs, and symlinks leaving it are rejected. Missing fields of a package-root plugin fall back to `package.json` `name` and `description`, and missing images use the panel's default artwork; malformed metadata produces a diagnostic and keeps the valid text."},{"number":53,"text":""},{"number":54,"text":"After installation, verify the intended title, description, and detail document in bundle details and plugin rows, plus the rendered icons, in English and the user's locale where supplied. Check for metadata diagnostics and unintended fallbacks, and that each plugin row shows its own exported icon or, when it has none, the generic artwork. Without browser control, inspect the installed resources and report that rendered display remains unverified; do not claim visual success from installation alone."},{"number":55,"text":""},{"number":56,"text":"An existing plugin's metadata may remain unchanged when it still describes the requested result. A disposable test fixture or an explicitly requested metadata-free package may omit resources, but explain each omission in the delivery report. A Host-only or configuration-only bundle still has a visible inventory entry; neither is an exception by itself."},{"number":57,"text":""},{"number":58,"text":"## Host plugin export forms"},{"number":59,"text":""},{"number":60,"text":"`index.js` exports one of these forms; do not mix them:"},{"number":61,"text":""},{"number":62,"text":"- `export function apply(ctx, config) {}` with optional `export const inject = ['tools']` and `export const Config`."},{"number":63,"text":"- A service class as the default export."},{"number":64,"text":""},{"number":65,"text":"Register every resource inside `apply` with `ctx.effect` or `ctx.on` and return its cleanup. A plugin that declares `Config` validates the row's `config` at activation; before writing an installed plugin's `config`, read its schema from `Config.listConfigs` through `cordis_inspect`, following `$defs` references, or from the owning package's README and source when inspection is unavailable."},{"number":66,"text":""},{"number":67,"text":"## Persist your own configuration"},{"number":68,"text":""},{"number":69,"text":"Read `references/configuration.md` before saving plugin configuration or credentials."},{"number":70,"text":""},{"number":71,"text":"## Install, enable, and observe"},{"number":72,"text":""},{"number":73,"text":"`plugin_manager` `install_bundle` performs package installation and bundle selection; do not reproduce those steps with shell commands. Only pass `approvedBuilds` after the user explicitly approves the reported pending build scripts. Preserve returned failures and pending states; report success only after observing the requested capability."},{"number":74,"text":""},{"number":75,"text":"`list_plugins` and `list_bundles` return exact identifiers for existing installations. `set_plugin` and `set_bundle` toggle them; `remove_bundle` removes a bundle. Inspect saved-state and activation outcomes separately: `failed` requires diagnosis, `overridden` means a higher-priority layer wins, and `restart-required` means the change is not live. Installing a new bundle can activate through HMR; replacing an installed package requires restart to load a fresh JavaScript module generation. Do not infer updated browser code from an unchanged slot id."}],"totalLines":75,"lang":"md"}},"sourceEventSeqs":[25],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":3,"message":{"role":"tool","source":{"kind":"tool","callId":"call_read_3"},"toolCallId":"call_read_3","content":[{"type":"text","text":"{{cwd}}/.dsh/skills/dsh-doc/references/host-plugin.md\nfile\n\n1: # Bundles and Host plugins\n2: \n3: A bundle is a package whose `package.json` declares `dsh.bundle.patch`; the YAML patch inserts plugin entries. Give the package and rows unique names; use the Loader's existing YAML syntax, including `!!js` where expressions are needed. Read an existing patch before editing it: a matching override replaces the complete `config`.\n4: \n5: ## Manifest\n6: \n7: A Host-only bundle needs no dependencies, install scripts, or build tool:\n8: \n9: ```json\n10: {\n11: \"name\": \"@local/my-plugin\",\n12: \"version\": \"1.0.0\",\n13: \"private\": true,\n14: \"type\": \"module\",\n15: \"exports\": { \".\": \"./index.js\" },\n16: \"dsh\": { \"bundle\": { \"patch\": \"./cordis.patch.yml\" } }\n17: }\n18: ```\n19: \n20: `cordis.patch.yml`:\n21: \n22: ```yaml\n23: - insert:\n24: - id: my-plugin\n25: name: '@local/my-plugin'\n26: config: {}\n27: ```\n28: \n29: To declare the DSH versions the bundle supports in `engines.dsh`, read `references/dsh-version.md` first.\n30: \n31: ## Display metadata, detail document, and icon\n32: \n33: Plugin Manager and Settings read `meta.title` and `meta.description` from exported locale JSON and an icon from exported resources without activating plugins. The bundle's page in Plugin Manager shows the detail document that `meta.detail` names, otherwise the package README. Complete this checklist before installation:\n34: \n35: - Write a recognizable title and a description of the capability in `locale/en.json` under `meta.title` and `meta.description`. Add the same fields for the user's language and other supported locales, such as `locale/zh.json`; do not leave template copy unrelated to the delivered plugin. Write English titles and other UI labels in sentence case: capitalize only the first word and proper nouns, as in `Git worktrees`.\n36: - For the bundle's detail page, keep functionality, usage, and essential limitations in `meta.description`; follow `references/plugin-details.md` for an optional single-image document, locale paths, packaging, and verification. State only behavior you implemented and verified. The page omits raw HTML and renders relative links as plain text. A malformed `meta.detail`, a missing named file, or a document exceeding `pluginManager.detailMaxBytes` (1 MiB by default) makes the detail section show the failure with **Retry** instead of falling back to the README.\n37: - Create an original icon or use artwork whose license permits redistribution, retaining any required attribution. Read `references/artwork.md` before drawing or revising an icon.\n38: - Export `./locale/*.json` and `./icon`; retain existing runtime exports. Keep the patch, locales, the detail document's directory, icon, and every runtime file in `files`, updating it whenever you add modules or assets. For a packed or published bundle, verify the actual packed file list. Local directory installation links the checkout instead, so check the files directly; `files` does not filter a linked directory.\n39: - Check that the icon is a valid image of the declared format and satisfies the path and size limits below. An accepted filename alone does not establish that its bytes render.\n40: \n41: For example, the locale file contains:\n42: \n43: ```json\n44: { \"meta\": { \"title\": \"My decoration\", \"description\": \"Draws a badge under the composer.\", \"detail\": \"docs/DETAIL.md\" } }\n45: ```\n46: \n47: ```json\n48: {\n49: \"exports\": { \"./locale/*.json\": \"./locale/*.json\", \"./icon\": \"./icon.svg\" },\n50: \"files\": [\"index.js\", \"cordis.patch.yml\", \"locale/*.json\", \"docs\", \"icon.svg\"]\n51: }\n52: ```\n53: \n54: A package-root plugin may instead declare a top-level `icon` in `package.json`; it takes priority over `./icon` and is a path relative to the manifest directory. A subpath plugin such as `my-plugins/search` is not a package and never reads a `package.json`; it exports `./search/locale/*.json` and `./search/icon` instead. Icons may be SVG, PNG, JPEG, or WebP up to 256 KiB and must stay inside the package; absolute paths, URLs, and symlinks leaving it are rejected. Missing fields of a package-root plugin fall back to `package.json` `name` and `description`, and missing images use the panel's default artwork; malformed metadata produces a diagnostic and keeps the valid text.\n55: \n56: After installation, verify the intended title, description, and detail document in bundle details and plugin rows, plus the rendered icons, in English and the user's locale where supplied. Check for metadata diagnostics and unintended fallbacks, and that each plugin row shows its own exported icon or, when it has none, the generic artwork. Without browser control, inspect the installed resources and report that rendered display remains unverified; do not claim visual success from installation alone.\n57: \n58: An existing plugin's metadata may remain unchanged when it still describes the requested result. A disposable test fixture or an explicitly requested metadata-free package may omit resources, but explain each omission in the delivery report. A Host-only or configuration-only bundle still has a visible inventory entry; neither is an exception by itself.\n59: \n60: ## Host plugin export forms\n61: \n62: `index.js` exports one of these forms; do not mix them:\n63: \n64: - `export function apply(ctx, config) {}` with optional `export const inject = ['tools']` and `export const Config`.\n65: - A service class as the default export.\n66: \n67: Register every resource inside `apply` with `ctx.effect` or `ctx.on` and return its cleanup. A plugin that declares `Config` validates the row's `config` at activation; before writing an installed plugin's `config`, read its schema from `Config.listConfigs` through `cordis_inspect`, following `$defs` references, or from the owning package's README and source when inspection is unavailable.\n68: \n69: ## Persist your own configuration\n70: \n71: Read `references/configuration.md` before saving plugin configuration or credentials.\n72: \n73: ## Install, enable, and observe\n74: \n75: `plugin_manager` `install_bundle` performs package installation and bundle selection; do not reproduce those steps with shell commands. Only pass `approvedBuilds` after the user explicitly approves the reported pending build scripts. Preserve returned failures and pending states; report success only after observing the requested capability.\n76: \n77: `list_plugins` and `list_bundles` return exact identifiers for existing installations. `set_plugin` and `set_bundle` toggle them; `remove_bundle` removes a bundle. Inspect saved-state and activation outcomes separately: `failed` requires diagnosis, `overridden` means a higher-priority layer wins, and `restart-required` means the change is not live. Installing a new bundle can activate through HMR; replacing an installed package requires restart to load a fresh JavaScript module generation. Do not infer updated browser code from an unchanged slot id.\n\n(End of file - total 77 lines)\n"}],"isError":false,"id":"{{message:10}}"},"meta":{"path":"{{cwd}}/.dsh/skills/dsh-doc/references/host-plugin.md","offset":1,"lines":[{"number":1,"text":"# Bundles and Host plugins"},{"number":2,"text":""},{"number":3,"text":"A bundle is a package whose `package.json` declares `dsh.bundle.patch`; the YAML patch inserts plugin entries. Give the package and rows unique names; use the Loader's existing YAML syntax, including `!!js` where expressions are needed. Read an existing patch before editing it: a matching override replaces the complete `config`."},{"number":4,"text":""},{"number":5,"text":"## Manifest"},{"number":6,"text":""},{"number":7,"text":"A Host-only bundle needs no dependencies, install scripts, or build tool:"},{"number":8,"text":""},{"number":9,"text":"```json"},{"number":10,"text":"{"},{"number":11,"text":" \"name\": \"@local/my-plugin\","},{"number":12,"text":" \"version\": \"1.0.0\","},{"number":13,"text":" \"private\": true,"},{"number":14,"text":" \"type\": \"module\","},{"number":15,"text":" \"exports\": { \".\": \"./index.js\" },"},{"number":16,"text":" \"dsh\": { \"bundle\": { \"patch\": \"./cordis.patch.yml\" } }"},{"number":17,"text":"}"},{"number":18,"text":"```"},{"number":19,"text":""},{"number":20,"text":"`cordis.patch.yml`:"},{"number":21,"text":""},{"number":22,"text":"```yaml"},{"number":23,"text":"- insert:"},{"number":24,"text":" - id: my-plugin"},{"number":25,"text":" name: '@local/my-plugin'"},{"number":26,"text":" config: {}"},{"number":27,"text":"```"},{"number":28,"text":""},{"number":29,"text":"To declare the DSH versions the bundle supports in `engines.dsh`, read `references/dsh-version.md` first."},{"number":30,"text":""},{"number":31,"text":"## Display metadata, detail document, and icon"},{"number":32,"text":""},{"number":33,"text":"Plugin Manager and Settings read `meta.title` and `meta.description` from exported locale JSON and an icon from exported resources without activating plugins. The bundle's page in Plugin Manager shows the detail document that `meta.detail` names, otherwise the package README. Complete this checklist before installation:"},{"number":34,"text":""},{"number":35,"text":"- Write a recognizable title and a description of the capability in `locale/en.json` under `meta.title` and `meta.description`. Add the same fields for the user's language and other supported locales, such as `locale/zh.json`; do not leave template copy unrelated to the delivered plugin. Write English titles and other UI labels in sentence case: capitalize only the first word and proper nouns, as in `Git worktrees`."},{"number":36,"text":"- For the bundle's detail page, keep functionality, usage, and essential limitations in `meta.description`; follow `references/plugin-details.md` for an optional single-image document, locale paths, packaging, and verification. State only behavior you implemented and verified. The page omits raw HTML and renders relative links as plain text. A malformed `meta.detail`, a missing named file, or a document exceeding `pluginManager.detailMaxBytes` (1 MiB by default) makes the detail section show the failure with **Retry** instead of falling back to the README."},{"number":37,"text":"- Create an original icon or use artwork whose license permits redistribution, retaining any required attribution. Read `references/artwork.md` before drawing or revising an icon."},{"number":38,"text":"- Export `./locale/*.json` and `./icon`; retain existing runtime exports. Keep the patch, locales, the detail document's directory, icon, and every runtime file in `files`, updating it whenever you add modules or assets. For a packed or published bundle, verify the actual packed file list. Local directory installation links the checkout instead, so check the files directly; `files` does not filter a linked directory."},{"number":39,"text":"- Check that the icon is a valid image of the declared format and satisfies the path and size limits below. An accepted filename alone does not establish that its bytes render."},{"number":40,"text":""},{"number":41,"text":"For example, the locale file contains:"},{"number":42,"text":""},{"number":43,"text":"```json"},{"number":44,"text":"{ \"meta\": { \"title\": \"My decoration\", \"description\": \"Draws a badge under the composer.\", \"detail\": \"docs/DETAIL.md\" } }"},{"number":45,"text":"```"},{"number":46,"text":""},{"number":47,"text":"```json"},{"number":48,"text":"{"},{"number":49,"text":" \"exports\": { \"./locale/*.json\": \"./locale/*.json\", \"./icon\": \"./icon.svg\" },"},{"number":50,"text":" \"files\": [\"index.js\", \"cordis.patch.yml\", \"locale/*.json\", \"docs\", \"icon.svg\"]"},{"number":51,"text":"}"},{"number":52,"text":"```"},{"number":53,"text":""},{"number":54,"text":"A package-root plugin may instead declare a top-level `icon` in `package.json`; it takes priority over `./icon` and is a path relative to the manifest directory. A subpath plugin such as `my-plugins/search` is not a package and never reads a `package.json`; it exports `./search/locale/*.json` and `./search/icon` instead. Icons may be SVG, PNG, JPEG, or WebP up to 256 KiB and must stay inside the package; absolute paths, URLs, and symlinks leaving it are rejected. Missing fields of a package-root plugin fall back to `package.json` `name` and `description`, and missing images use the panel's default artwork; malformed metadata produces a diagnostic and keeps the valid text."},{"number":55,"text":""},{"number":56,"text":"After installation, verify the intended title, description, and detail document in bundle details and plugin rows, plus the rendered icons, in English and the user's locale where supplied. Check for metadata diagnostics and unintended fallbacks, and that each plugin row shows its own exported icon or, when it has none, the generic artwork. Without browser control, inspect the installed resources and report that rendered display remains unverified; do not claim visual success from installation alone."},{"number":57,"text":""},{"number":58,"text":"An existing plugin's metadata may remain unchanged when it still describes the requested result. A disposable test fixture or an explicitly requested metadata-free package may omit resources, but explain each omission in the delivery report. A Host-only or configuration-only bundle still has a visible inventory entry; neither is an exception by itself."},{"number":59,"text":""},{"number":60,"text":"## Host plugin export forms"},{"number":61,"text":""},{"number":62,"text":"`index.js` exports one of these forms; do not mix them:"},{"number":63,"text":""},{"number":64,"text":"- `export function apply(ctx, config) {}` with optional `export const inject = ['tools']` and `export const Config`."},{"number":65,"text":"- A service class as the default export."},{"number":66,"text":""},{"number":67,"text":"Register every resource inside `apply` with `ctx.effect` or `ctx.on` and return its cleanup. A plugin that declares `Config` validates the row's `config` at activation; before writing an installed plugin's `config`, read its schema from `Config.listConfigs` through `cordis_inspect`, following `$defs` references, or from the owning package's README and source when inspection is unavailable."},{"number":68,"text":""},{"number":69,"text":"## Persist your own configuration"},{"number":70,"text":""},{"number":71,"text":"Read `references/configuration.md` before saving plugin configuration or credentials."},{"number":72,"text":""},{"number":73,"text":"## Install, enable, and observe"},{"number":74,"text":""},{"number":75,"text":"`plugin_manager` `install_bundle` performs package installation and bundle selection; do not reproduce those steps with shell commands. Only pass `approvedBuilds` after the user explicitly approves the reported pending build scripts. Preserve returned failures and pending states; report success only after observing the requested capability."},{"number":76,"text":""},{"number":77,"text":"`list_plugins` and `list_bundles` return exact identifiers for existing installations. `set_plugin` and `set_bundle` toggle them; `remove_bundle` removes a bundle. Inspect saved-state and activation outcomes separately: `failed` requires diagnosis, `overridden` means a higher-priority layer wins, and `restart-required` means the change is not live. Installing a new bundle can activate through HMR; replacing an installed package requires restart to load a fresh JavaScript module generation. Do not infer updated browser code from an unchanged slot id."}],"totalLines":77,"lang":"md"}},"sourceEventSeqs":[25],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":3}} {"type":"step/start","data":{"turn":1,"step":4}} {"type":"assistant/message","data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_read_4","name":"read","arguments":"{\"file_path\":\".dsh/skills/dsh-doc/references/locate-docs.md\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:11}}"},"stream":[{"type":"chunk","time":1788699430712,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1788699430712,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_read_4","name":"read","arguments":"{\"file_path\":\".dsh/skills/dsh-doc/references/locate-docs.md\"}"}}},{"type":"chunk","time":1788699430712,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":4,"callId":"call_read_4","name":"read","arguments":"{\"file_path\":\".dsh/skills/dsh-doc/references/locate-docs.md\"}"}} -{"type":"tool/result","data":{"turn":1,"step":4,"message":{"role":"tool","source":{"kind":"tool","callId":"call_read_4"},"toolCallId":"call_read_4","content":[{"type":"text","text":"{{cwd}}/.dsh/skills/dsh-doc/references/locate-docs.md\nfile\n\n1: # Locate documentation and sources\n2: \n3: Answer for the running installation, not an unrelated checkout in the current working directory. Keep lookups read-only and cite the files and version used. The Host file-read tool can read Desktop's `app.asar`; use offset and limit for long files.\n4: \n5: ## Identify the installation\n6: \n7: These runtime facts are not necessarily in model context. Print only the needed variables: in bash, `printf '%s\\n' \"$DSH_PROFILE\" \"$DSH_INSTALL_DIR\" \"$DSH_NODE_EXECUTABLE\"`; in PowerShell, `$env:DSH_PROFILE; $env:DSH_INSTALL_DIR; $env:DSH_NODE_EXECUTABLE`. Keep the loaded skill's reported Base directory. `DSH_PROFILE=desktop` identifies the Desktop profile, including development launches; `web` can run from npm or source. Profile and distribution are not one-to-one: verify ASAR or checkout markers below. `DSH_PROFILE_DIR` holds the user's profile and added plugins, not the DSH installation root. Standard and Creator are agent modes, not installation layouts.\n8: \n9: Verify that `DSH_INSTALL_DIR/package.json` names `@deepseek-ai/dsh`; its `version` identifies the running CLI package. Resolve symlinks before comparing directories. Missing variables alone do not establish that there is no profile or no source. Use the loaded skill's location or an inspected package directory to verify a candidate; if none is verifiable, report what remains unlocated. Do not change the profile to obtain tools.\n10: \n11: ## Source checkout\n12: \n13: A source launch normally points `DSH_INSTALL_DIR` at `/apps/cli`. Verify `/pnpm-workspace.yaml`, `/package.json` with name `@deepseek-ai/dsh-root`, and `/apps/cli/package.json` with name `@deepseek-ai/dsh`. The loaded skill may instead locate the candidate root: its real directory is `/packages/preset/agent-preset/skills/dsh-doc`, five parents below the root. Verify the same markers; a matching working-directory name is not evidence of the running installation.\n14: \n15: Read `/docs/user/index.md` for user documentation and `/docs/upgrade-guide/` for migration guides. The checkout's `apps/cli/docs` need not exist. Use `/packages/README.md` to find the owning group, then `/packages///package.json` to verify the package name. Read that package's `README.md` and the owning file under `src/`; do not assume every package resolves from `apps/cli/node_modules`. Use the verified CLI manifest's version and identify the checkout used.\n16: \n17: ## npm installation\n18: \n19: For an installed package layout outside an ASAR, verify the CLI manifest at `DSH_INSTALL_DIR` and its packaged `docs/`; do not infer npm installation merely because checkout markers are absent. Read `DSH_INSTALL_DIR/docs/user/index.md` and `DSH_INSTALL_DIR/docs/upgrade-guide/README.md`, the generated index for this installed version's guides.\n20: \n21: Resolve a shipped package's exported `package.json` from this installation anchor with the runtime command below. Read its `README.md`, then the owning file under `src/` when present; `lib/` contains built code. A configuration-only bundle may instead expose its patch files. Do not resolve from the shell's cwd or assume a global npm prefix. A package unavailable from this anchor may be a user-added plugin: use Inspect's package directory when available rather than guessing another installation's files.\n22: \n23: ## Desktop\n24: \n25: For the packaged Desktop app, confirm that the installation or loaded skill path lies inside `app.asar` and the indicated runtime reports `process.versions.electron`. A Desktop development launch with verified checkout markers uses the source route above. Inside the archive, `DSH_INSTALL_DIR` still names the CLI package directory. Read its manifest, `docs/user/index.md`, and `docs/upgrade-guide/README.md` through the Host file-read tool. Resolve other packages from the same anchor and read their README and `src/` through that tool.\n26: \n27: Native grep/glob, `ls`, `cat`, and a Node executable chosen from `PATH` cannot traverse ASAR files. Do not unpack the app to answer a question. For directory listing or bounded search, use `DSH_NODE_EXECUTABLE`, the running Electron executable, with `ELECTRON_RUN_AS_NODE=1` as below. It supplies ASAR-aware filesystem reads; an ordinary Node runtime ignores that environment setting.\n28: \n29: ## Resolve a package with the running runtime\n30: \n31: With Inspect available, `Config.listConfigs` filtered by `name` lists mounted entries; querying an `entry` supplies `packageDir`. Otherwise use the installation anchor and executable verified above. In bash:\n32: \n33: ```sh\n34: ELECTRON_RUN_AS_NODE=1 \"$DSH_NODE_EXECUTABLE\" -e \"console.log(require('node:path').dirname(require.resolve(process.argv[1] + '/package.json', { paths: [process.env.DSH_INSTALL_DIR] })))\" @deepseek-ai/dsh-tool-bash\n35: ```\n36: \n37: In PowerShell, use redirected process output and wait for the exit code. Windows Desktop's Electron is a GUI-subsystem executable, for which `&` does not reliably wait. Replace `$script` and `$arguments` for other reads:\n38: \n39: ```powershell\n40: $script = @'\n41: console.log(require('node:path').dirname(require.resolve(process.argv[1] + '/package.json', { paths: [process.env.DSH_INSTALL_DIR] })))\n42: '@\n43: $arguments = @('@deepseek-ai/dsh-tool-bash')\n44: [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)\n45: $start = [System.Diagnostics.ProcessStartInfo]::new($env:DSH_NODE_EXECUTABLE)\n46: foreach ($argument in @('-e', $script, '--') + $arguments) { $start.ArgumentList.Add($argument) }\n47: $start.Environment['ELECTRON_RUN_AS_NODE'] = '1'\n48: $start.UseShellExecute = $false\n49: $start.RedirectStandardOutput = $true\n50: $start.RedirectStandardError = $true\n51: $start.StandardOutputEncoding = [System.Text.Encoding]::UTF8\n52: $start.StandardErrorEncoding = [System.Text.Encoding]::UTF8\n53: $process = [System.Diagnostics.Process]::Start($start)\n54: $stderr = $process.StandardError.ReadToEndAsync()\n55: $stdout = $process.StandardOutput.ReadToEnd()\n56: $process.WaitForExit()\n57: [Console]::Out.Write($stdout)\n58: [Console]::Error.Write($stderr.Result)\n59: exit $process.ExitCode\n60: ```\n61: \n62: If the executable or anchor is absent, do not substitute an unrelated Node from PATH. Inspect or directly read verified files. A checkout found only from the skill locates source but does not prove the running CLI version. Verify that `../../package.json` relative to the skill's base names `@deepseek-ai/dsh-agent-preset` before using its version as the shipping skill package's version. For a custom or single-executable layout, report only locations and versions actually verified.\n63: \n64: ## Bounded lookup\n65: \n66: Read one file at a time. Outside ASAR, search only a narrow known directory. Inside ASAR, run `require('node:fs').readdirSync(dir).slice(0, 200)` through the runtime above to list one directory. For search, use that runtime's `fs.statSync(file).size` to reject files above a chosen bound (for example 1 MiB) before `fs.readFileSync(file, 'utf8')`; split into lines, match a literal term, and print the path once and at most 20 matching lines of 200 characters each with line numbers and a truncation notice. Do not scan or dump whole package trees. Use the file-read tool's offsets for larger files. Read the installed upgrade index before selecting guides as `references/upgrading.md` describes. If a file is missing, state that limitation rather than substituting another version's documentation or source.\n\n(End of file - total 66 lines)\n"}],"isError":false,"id":"{{message:12}}"},"meta":{"path":"{{cwd}}/.dsh/skills/dsh-doc/references/locate-docs.md","offset":1,"lines":[{"number":1,"text":"# Locate documentation and sources"},{"number":2,"text":""},{"number":3,"text":"Answer for the running installation, not an unrelated checkout in the current working directory. Keep lookups read-only and cite the files and version used. The Host file-read tool can read Desktop's `app.asar`; use offset and limit for long files."},{"number":4,"text":""},{"number":5,"text":"## Identify the installation"},{"number":6,"text":""},{"number":7,"text":"These runtime facts are not necessarily in model context. Print only the needed variables: in bash, `printf '%s\\n' \"$DSH_PROFILE\" \"$DSH_INSTALL_DIR\" \"$DSH_NODE_EXECUTABLE\"`; in PowerShell, `$env:DSH_PROFILE; $env:DSH_INSTALL_DIR; $env:DSH_NODE_EXECUTABLE`. Keep the loaded skill's reported Base directory. `DSH_PROFILE=desktop` identifies the Desktop profile, including development launches; `web` can run from npm or source. Profile and distribution are not one-to-one: verify ASAR or checkout markers below. `DSH_PROFILE_DIR` holds the user's profile and added plugins, not the DSH installation root. Standard and Creator are agent modes, not installation layouts."},{"number":8,"text":""},{"number":9,"text":"Verify that `DSH_INSTALL_DIR/package.json` names `@deepseek-ai/dsh`; its `version` identifies the running CLI package. Resolve symlinks before comparing directories. Missing variables alone do not establish that there is no profile or no source. Use the loaded skill's location or an inspected package directory to verify a candidate; if none is verifiable, report what remains unlocated. Do not change the profile to obtain tools."},{"number":10,"text":""},{"number":11,"text":"## Source checkout"},{"number":12,"text":""},{"number":13,"text":"A source launch normally points `DSH_INSTALL_DIR` at `/apps/cli`. Verify `/pnpm-workspace.yaml`, `/package.json` with name `@deepseek-ai/dsh-root`, and `/apps/cli/package.json` with name `@deepseek-ai/dsh`. The loaded skill may instead locate the candidate root: its real directory is `/packages/preset/agent-preset/skills/dsh-doc`, five parents below the root. Verify the same markers; a matching working-directory name is not evidence of the running installation."},{"number":14,"text":""},{"number":15,"text":"Read `/docs/user/index.md` for user documentation and `/docs/upgrade-guide/` for migration guides. The checkout's `apps/cli/docs` need not exist. Use `/packages/README.md` to find the owning group, then `/packages///package.json` to verify the package name. Read that package's `README.md` and the owning file under `src/`; do not assume every package resolves from `apps/cli/node_modules`. Use the verified CLI manifest's version and identify the checkout used."},{"number":16,"text":""},{"number":17,"text":"## npm installation"},{"number":18,"text":""},{"number":19,"text":"For an installed package layout outside an ASAR, verify the CLI manifest at `DSH_INSTALL_DIR` and its packaged `docs/`; do not infer npm installation merely because checkout markers are absent. Read `DSH_INSTALL_DIR/docs/user/index.md` and `DSH_INSTALL_DIR/docs/upgrade-guide/README.md`, the generated index for this installed version's guides."},{"number":20,"text":""},{"number":21,"text":"Resolve a shipped package's exported `package.json` from this installation anchor with the runtime command below. Read its `README.md`, then the owning file under `src/` when present; `lib/` contains built code. A configuration-only bundle may instead expose its patch files. Do not resolve from the shell's cwd or assume a global npm prefix. A package unavailable from this anchor may be a user-added plugin: use Inspect's package directory when available rather than guessing another installation's files."},{"number":22,"text":""},{"number":23,"text":"## Desktop"},{"number":24,"text":""},{"number":25,"text":"For the packaged Desktop app, confirm that the installation or loaded skill path lies inside `app.asar` and the indicated runtime reports `process.versions.electron`. A Desktop development launch with verified checkout markers uses the source route above. Inside the archive, `DSH_INSTALL_DIR` still names the CLI package directory. Read its manifest, `docs/user/index.md`, and `docs/upgrade-guide/README.md` through the Host file-read tool. Resolve other packages from the same anchor and read their README and `src/` through that tool."},{"number":26,"text":""},{"number":27,"text":"Native grep/glob, `ls`, `cat`, and a Node executable chosen from `PATH` cannot traverse ASAR files. Do not unpack the app to answer a question. For directory listing or bounded search, use `DSH_NODE_EXECUTABLE`, the running Electron executable, with `ELECTRON_RUN_AS_NODE=1` as below. It supplies ASAR-aware filesystem reads; an ordinary Node runtime ignores that environment setting."},{"number":28,"text":""},{"number":29,"text":"## Resolve a package with the running runtime"},{"number":30,"text":""},{"number":31,"text":"With Inspect available, `Config.listConfigs` filtered by `name` lists mounted entries; querying an `entry` supplies `packageDir`. Otherwise use the installation anchor and executable verified above. In bash:"},{"number":32,"text":""},{"number":33,"text":"```sh"},{"number":34,"text":"ELECTRON_RUN_AS_NODE=1 \"$DSH_NODE_EXECUTABLE\" -e \"console.log(require('node:path').dirname(require.resolve(process.argv[1] + '/package.json', { paths: [process.env.DSH_INSTALL_DIR] })))\" @deepseek-ai/dsh-tool-bash"},{"number":35,"text":"```"},{"number":36,"text":""},{"number":37,"text":"In PowerShell, use redirected process output and wait for the exit code. Windows Desktop's Electron is a GUI-subsystem executable, for which `&` does not reliably wait. Replace `$script` and `$arguments` for other reads:"},{"number":38,"text":""},{"number":39,"text":"```powershell"},{"number":40,"text":"$script = @'"},{"number":41,"text":"console.log(require('node:path').dirname(require.resolve(process.argv[1] + '/package.json', { paths: [process.env.DSH_INSTALL_DIR] })))"},{"number":42,"text":"'@"},{"number":43,"text":"$arguments = @('@deepseek-ai/dsh-tool-bash')"},{"number":44,"text":"[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)"},{"number":45,"text":"$start = [System.Diagnostics.ProcessStartInfo]::new($env:DSH_NODE_EXECUTABLE)"},{"number":46,"text":"foreach ($argument in @('-e', $script, '--') + $arguments) { $start.ArgumentList.Add($argument) }"},{"number":47,"text":"$start.Environment['ELECTRON_RUN_AS_NODE'] = '1'"},{"number":48,"text":"$start.UseShellExecute = $false"},{"number":49,"text":"$start.RedirectStandardOutput = $true"},{"number":50,"text":"$start.RedirectStandardError = $true"},{"number":51,"text":"$start.StandardOutputEncoding = [System.Text.Encoding]::UTF8"},{"number":52,"text":"$start.StandardErrorEncoding = [System.Text.Encoding]::UTF8"},{"number":53,"text":"$process = [System.Diagnostics.Process]::Start($start)"},{"number":54,"text":"$stderr = $process.StandardError.ReadToEndAsync()"},{"number":55,"text":"$stdout = $process.StandardOutput.ReadToEnd()"},{"number":56,"text":"$process.WaitForExit()"},{"number":57,"text":"[Console]::Out.Write($stdout)"},{"number":58,"text":"[Console]::Error.Write($stderr.Result)"},{"number":59,"text":"exit $process.ExitCode"},{"number":60,"text":"```"},{"number":61,"text":""},{"number":62,"text":"If the executable or anchor is absent, do not substitute an unrelated Node from PATH. Inspect or directly read verified files. A checkout found only from the skill locates source but does not prove the running CLI version. Verify that `../../package.json` relative to the skill's base names `@deepseek-ai/dsh-agent-preset` before using its version as the shipping skill package's version. For a custom or single-executable layout, report only locations and versions actually verified."},{"number":63,"text":""},{"number":64,"text":"## Bounded lookup"},{"number":65,"text":""},{"number":66,"text":"Read one file at a time. Outside ASAR, search only a narrow known directory. Inside ASAR, run `require('node:fs').readdirSync(dir).slice(0, 200)` through the runtime above to list one directory. For search, use that runtime's `fs.statSync(file).size` to reject files above a chosen bound (for example 1 MiB) before `fs.readFileSync(file, 'utf8')`; split into lines, match a literal term, and print the path once and at most 20 matching lines of 200 characters each with line numbers and a truncation notice. Do not scan or dump whole package trees. Use the file-read tool's offsets for larger files. Read the installed upgrade index before selecting guides as `references/upgrading.md` describes. If a file is missing, state that limitation rather than substituting another version's documentation or source."}],"totalLines":66,"lang":"md"}},"sourceEventSeqs":[30],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":4,"message":{"role":"tool","source":{"kind":"tool","callId":"call_read_4"},"toolCallId":"call_read_4","content":[{"type":"text","text":"{{cwd}}/.dsh/skills/dsh-doc/references/locate-docs.md\nfile\n\n1: # Locate documentation and sources\n2: \n3: Answer for the running installation, not an unrelated checkout in the current working directory. Keep lookups read-only and cite the files and version used. The Host file-read tool can read Desktop's `app.asar`; use offset and limit for long files.\n4: \n5: ## Identify the installation\n6: \n7: These runtime facts are not necessarily in model context. Print only the needed variables: in bash, `printf '%s\\n' \"$DSH_PROFILE\" \"$DSH_INSTALL_DIR\" \"$DSH_NODE_EXECUTABLE\"`; in PowerShell, `$env:DSH_PROFILE; $env:DSH_INSTALL_DIR; $env:DSH_NODE_EXECUTABLE`. Keep the loaded skill's reported Base directory. `DSH_PROFILE=desktop` identifies the Desktop profile, including development launches; `web` can run from npm or source. Profile and distribution are not one-to-one: verify ASAR or checkout markers below. `DSH_PROFILE_DIR` holds the user's profile and added plugins, not the DSH installation root. Standard and Creator are agent modes, not installation layouts.\n8: \n9: When `cordis_inspect` is available, its Host `Runtime` provider's `getVersion` returns the running DSH version. Verify that `DSH_INSTALL_DIR/package.json` names `@deepseek-ai/dsh`; its `version` identifies the running CLI package. Copies of `@deepseek-ai/dsh` under the profile's `node_modules` may be stale and do not identify the running version. Resolve symlinks before comparing directories. Missing variables alone do not establish that there is no profile or no source. Use the loaded skill's location or an inspected package directory to verify a candidate; if none is verifiable, report what remains unlocated. Do not change the profile to obtain tools.\n10: \n11: ## Source checkout\n12: \n13: A source launch normally points `DSH_INSTALL_DIR` at `/apps/cli`. Verify `/pnpm-workspace.yaml`, `/package.json` with name `@deepseek-ai/dsh-root`, and `/apps/cli/package.json` with name `@deepseek-ai/dsh`. The loaded skill may instead locate the candidate root: its real directory is `/packages/preset/agent-preset/skills/dsh-doc`, five parents below the root. Verify the same markers; a matching working-directory name is not evidence of the running installation.\n14: \n15: Read `/docs/user/index.md` for user documentation and `/docs/upgrade-guide/` for migration guides. The checkout's `apps/cli/docs` need not exist. Use `/packages/README.md` to find the owning group, then `/packages///package.json` to verify the package name. Read that package's `README.md` and the owning file under `src/`; do not assume every package resolves from `apps/cli/node_modules`. Use the verified CLI manifest's version and identify the checkout used.\n16: \n17: ## npm installation\n18: \n19: For an installed package layout outside an ASAR, verify the CLI manifest at `DSH_INSTALL_DIR` and its packaged `docs/`; do not infer npm installation merely because checkout markers are absent. Read `DSH_INSTALL_DIR/docs/user/index.md` and `DSH_INSTALL_DIR/docs/upgrade-guide/README.md`, the generated index for this installed version's guides.\n20: \n21: Resolve a shipped package's exported `package.json` from this installation anchor with the runtime command below. Read its `README.md`, then the owning file under `src/` when present; `lib/` contains built code. A configuration-only bundle may instead expose its patch files. Do not resolve from the shell's cwd or assume a global npm prefix. A package unavailable from this anchor may be a user-added plugin: use Inspect's package directory when available rather than guessing another installation's files.\n22: \n23: ## Desktop\n24: \n25: For the packaged Desktop app, confirm that the installation or loaded skill path lies inside `app.asar` and the indicated runtime reports `process.versions.electron`. A Desktop development launch with verified checkout markers uses the source route above. Inside the archive, `DSH_INSTALL_DIR` still names the CLI package directory. Read its manifest, `docs/user/index.md`, and `docs/upgrade-guide/README.md` through the Host file-read tool. Resolve other packages from the same anchor and read their README and `src/` through that tool.\n26: \n27: Native grep/glob, `ls`, `cat`, and a Node executable chosen from `PATH` cannot traverse ASAR files. Do not unpack the app to answer a question. For directory listing or bounded search, use `DSH_NODE_EXECUTABLE`, the running Electron executable, with `ELECTRON_RUN_AS_NODE=1` as below. It supplies ASAR-aware filesystem reads; an ordinary Node runtime ignores that environment setting.\n28: \n29: ## Resolve a package with the running runtime\n30: \n31: With Inspect available, `Config.listConfigs` filtered by `name` lists mounted entries; querying an `entry` supplies `packageDir`. Otherwise use the installation anchor and executable verified above. In bash:\n32: \n33: ```sh\n34: ELECTRON_RUN_AS_NODE=1 \"$DSH_NODE_EXECUTABLE\" -e \"console.log(require('node:path').dirname(require.resolve(process.argv[1] + '/package.json', { paths: [process.env.DSH_INSTALL_DIR] })))\" @deepseek-ai/dsh-tool-bash\n35: ```\n36: \n37: In PowerShell, use redirected process output and wait for the exit code. Windows Desktop's Electron is a GUI-subsystem executable, for which `&` does not reliably wait. Replace `$script` and `$arguments` for other reads:\n38: \n39: ```powershell\n40: $script = @'\n41: console.log(require('node:path').dirname(require.resolve(process.argv[1] + '/package.json', { paths: [process.env.DSH_INSTALL_DIR] })))\n42: '@\n43: $arguments = @('@deepseek-ai/dsh-tool-bash')\n44: [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)\n45: $start = [System.Diagnostics.ProcessStartInfo]::new($env:DSH_NODE_EXECUTABLE)\n46: foreach ($argument in @('-e', $script, '--') + $arguments) { $start.ArgumentList.Add($argument) }\n47: $start.Environment['ELECTRON_RUN_AS_NODE'] = '1'\n48: $start.UseShellExecute = $false\n49: $start.RedirectStandardOutput = $true\n50: $start.RedirectStandardError = $true\n51: $start.StandardOutputEncoding = [System.Text.Encoding]::UTF8\n52: $start.StandardErrorEncoding = [System.Text.Encoding]::UTF8\n53: $process = [System.Diagnostics.Process]::Start($start)\n54: $stderr = $process.StandardError.ReadToEndAsync()\n55: $stdout = $process.StandardOutput.ReadToEnd()\n56: $process.WaitForExit()\n57: [Console]::Out.Write($stdout)\n58: [Console]::Error.Write($stderr.Result)\n59: exit $process.ExitCode\n60: ```\n61: \n62: If the executable or anchor is absent, do not substitute an unrelated Node from PATH. Inspect or directly read verified files. A checkout found only from the skill locates source but does not prove the running CLI version. Verify that `../../package.json` relative to the skill's base names `@deepseek-ai/dsh-agent-preset` before using its version as the shipping skill package's version. For a custom or single-executable layout, report only locations and versions actually verified.\n63: \n64: ## Bounded lookup\n65: \n66: Read one file at a time. Outside ASAR, search only a narrow known directory. Inside ASAR, run `require('node:fs').readdirSync(dir).slice(0, 200)` through the runtime above to list one directory. For search, use that runtime's `fs.statSync(file).size` to reject files above a chosen bound (for example 1 MiB) before `fs.readFileSync(file, 'utf8')`; split into lines, match a literal term, and print the path once and at most 20 matching lines of 200 characters each with line numbers and a truncation notice. Do not scan or dump whole package trees. Use the file-read tool's offsets for larger files. Read the installed upgrade index before selecting guides as `references/upgrading.md` describes. If a file is missing, state that limitation rather than substituting another version's documentation or source.\n\n(End of file - total 66 lines)\n"}],"isError":false,"id":"{{message:12}}"},"meta":{"path":"{{cwd}}/.dsh/skills/dsh-doc/references/locate-docs.md","offset":1,"lines":[{"number":1,"text":"# Locate documentation and sources"},{"number":2,"text":""},{"number":3,"text":"Answer for the running installation, not an unrelated checkout in the current working directory. Keep lookups read-only and cite the files and version used. The Host file-read tool can read Desktop's `app.asar`; use offset and limit for long files."},{"number":4,"text":""},{"number":5,"text":"## Identify the installation"},{"number":6,"text":""},{"number":7,"text":"These runtime facts are not necessarily in model context. Print only the needed variables: in bash, `printf '%s\\n' \"$DSH_PROFILE\" \"$DSH_INSTALL_DIR\" \"$DSH_NODE_EXECUTABLE\"`; in PowerShell, `$env:DSH_PROFILE; $env:DSH_INSTALL_DIR; $env:DSH_NODE_EXECUTABLE`. Keep the loaded skill's reported Base directory. `DSH_PROFILE=desktop` identifies the Desktop profile, including development launches; `web` can run from npm or source. Profile and distribution are not one-to-one: verify ASAR or checkout markers below. `DSH_PROFILE_DIR` holds the user's profile and added plugins, not the DSH installation root. Standard and Creator are agent modes, not installation layouts."},{"number":8,"text":""},{"number":9,"text":"When `cordis_inspect` is available, its Host `Runtime` provider's `getVersion` returns the running DSH version. Verify that `DSH_INSTALL_DIR/package.json` names `@deepseek-ai/dsh`; its `version` identifies the running CLI package. Copies of `@deepseek-ai/dsh` under the profile's `node_modules` may be stale and do not identify the running version. Resolve symlinks before comparing directories. Missing variables alone do not establish that there is no profile or no source. Use the loaded skill's location or an inspected package directory to verify a candidate; if none is verifiable, report what remains unlocated. Do not change the profile to obtain tools."},{"number":10,"text":""},{"number":11,"text":"## Source checkout"},{"number":12,"text":""},{"number":13,"text":"A source launch normally points `DSH_INSTALL_DIR` at `/apps/cli`. Verify `/pnpm-workspace.yaml`, `/package.json` with name `@deepseek-ai/dsh-root`, and `/apps/cli/package.json` with name `@deepseek-ai/dsh`. The loaded skill may instead locate the candidate root: its real directory is `/packages/preset/agent-preset/skills/dsh-doc`, five parents below the root. Verify the same markers; a matching working-directory name is not evidence of the running installation."},{"number":14,"text":""},{"number":15,"text":"Read `/docs/user/index.md` for user documentation and `/docs/upgrade-guide/` for migration guides. The checkout's `apps/cli/docs` need not exist. Use `/packages/README.md` to find the owning group, then `/packages///package.json` to verify the package name. Read that package's `README.md` and the owning file under `src/`; do not assume every package resolves from `apps/cli/node_modules`. Use the verified CLI manifest's version and identify the checkout used."},{"number":16,"text":""},{"number":17,"text":"## npm installation"},{"number":18,"text":""},{"number":19,"text":"For an installed package layout outside an ASAR, verify the CLI manifest at `DSH_INSTALL_DIR` and its packaged `docs/`; do not infer npm installation merely because checkout markers are absent. Read `DSH_INSTALL_DIR/docs/user/index.md` and `DSH_INSTALL_DIR/docs/upgrade-guide/README.md`, the generated index for this installed version's guides."},{"number":20,"text":""},{"number":21,"text":"Resolve a shipped package's exported `package.json` from this installation anchor with the runtime command below. Read its `README.md`, then the owning file under `src/` when present; `lib/` contains built code. A configuration-only bundle may instead expose its patch files. Do not resolve from the shell's cwd or assume a global npm prefix. A package unavailable from this anchor may be a user-added plugin: use Inspect's package directory when available rather than guessing another installation's files."},{"number":22,"text":""},{"number":23,"text":"## Desktop"},{"number":24,"text":""},{"number":25,"text":"For the packaged Desktop app, confirm that the installation or loaded skill path lies inside `app.asar` and the indicated runtime reports `process.versions.electron`. A Desktop development launch with verified checkout markers uses the source route above. Inside the archive, `DSH_INSTALL_DIR` still names the CLI package directory. Read its manifest, `docs/user/index.md`, and `docs/upgrade-guide/README.md` through the Host file-read tool. Resolve other packages from the same anchor and read their README and `src/` through that tool."},{"number":26,"text":""},{"number":27,"text":"Native grep/glob, `ls`, `cat`, and a Node executable chosen from `PATH` cannot traverse ASAR files. Do not unpack the app to answer a question. For directory listing or bounded search, use `DSH_NODE_EXECUTABLE`, the running Electron executable, with `ELECTRON_RUN_AS_NODE=1` as below. It supplies ASAR-aware filesystem reads; an ordinary Node runtime ignores that environment setting."},{"number":28,"text":""},{"number":29,"text":"## Resolve a package with the running runtime"},{"number":30,"text":""},{"number":31,"text":"With Inspect available, `Config.listConfigs` filtered by `name` lists mounted entries; querying an `entry` supplies `packageDir`. Otherwise use the installation anchor and executable verified above. In bash:"},{"number":32,"text":""},{"number":33,"text":"```sh"},{"number":34,"text":"ELECTRON_RUN_AS_NODE=1 \"$DSH_NODE_EXECUTABLE\" -e \"console.log(require('node:path').dirname(require.resolve(process.argv[1] + '/package.json', { paths: [process.env.DSH_INSTALL_DIR] })))\" @deepseek-ai/dsh-tool-bash"},{"number":35,"text":"```"},{"number":36,"text":""},{"number":37,"text":"In PowerShell, use redirected process output and wait for the exit code. Windows Desktop's Electron is a GUI-subsystem executable, for which `&` does not reliably wait. Replace `$script` and `$arguments` for other reads:"},{"number":38,"text":""},{"number":39,"text":"```powershell"},{"number":40,"text":"$script = @'"},{"number":41,"text":"console.log(require('node:path').dirname(require.resolve(process.argv[1] + '/package.json', { paths: [process.env.DSH_INSTALL_DIR] })))"},{"number":42,"text":"'@"},{"number":43,"text":"$arguments = @('@deepseek-ai/dsh-tool-bash')"},{"number":44,"text":"[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)"},{"number":45,"text":"$start = [System.Diagnostics.ProcessStartInfo]::new($env:DSH_NODE_EXECUTABLE)"},{"number":46,"text":"foreach ($argument in @('-e', $script, '--') + $arguments) { $start.ArgumentList.Add($argument) }"},{"number":47,"text":"$start.Environment['ELECTRON_RUN_AS_NODE'] = '1'"},{"number":48,"text":"$start.UseShellExecute = $false"},{"number":49,"text":"$start.RedirectStandardOutput = $true"},{"number":50,"text":"$start.RedirectStandardError = $true"},{"number":51,"text":"$start.StandardOutputEncoding = [System.Text.Encoding]::UTF8"},{"number":52,"text":"$start.StandardErrorEncoding = [System.Text.Encoding]::UTF8"},{"number":53,"text":"$process = [System.Diagnostics.Process]::Start($start)"},{"number":54,"text":"$stderr = $process.StandardError.ReadToEndAsync()"},{"number":55,"text":"$stdout = $process.StandardOutput.ReadToEnd()"},{"number":56,"text":"$process.WaitForExit()"},{"number":57,"text":"[Console]::Out.Write($stdout)"},{"number":58,"text":"[Console]::Error.Write($stderr.Result)"},{"number":59,"text":"exit $process.ExitCode"},{"number":60,"text":"```"},{"number":61,"text":""},{"number":62,"text":"If the executable or anchor is absent, do not substitute an unrelated Node from PATH. Inspect or directly read verified files. A checkout found only from the skill locates source but does not prove the running CLI version. Verify that `../../package.json` relative to the skill's base names `@deepseek-ai/dsh-agent-preset` before using its version as the shipping skill package's version. For a custom or single-executable layout, report only locations and versions actually verified."},{"number":63,"text":""},{"number":64,"text":"## Bounded lookup"},{"number":65,"text":""},{"number":66,"text":"Read one file at a time. Outside ASAR, search only a narrow known directory. Inside ASAR, run `require('node:fs').readdirSync(dir).slice(0, 200)` through the runtime above to list one directory. For search, use that runtime's `fs.statSync(file).size` to reject files above a chosen bound (for example 1 MiB) before `fs.readFileSync(file, 'utf8')`; split into lines, match a literal term, and print the path once and at most 20 matching lines of 200 characters each with line numbers and a truncation notice. Do not scan or dump whole package trees. Use the file-read tool's offsets for larger files. Read the installed upgrade index before selecting guides as `references/upgrading.md` describes. If a file is missing, state that limitation rather than substituting another version's documentation or source."}],"totalLines":66,"lang":"md"}},"sourceEventSeqs":[30],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":4}} {"type":"step/start","data":{"turn":1,"step":5}} {"type":"assistant/message","data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The skill is loaded."},{"type":"text","text":"DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:13}}"},"usage":{"inputTokens":180,"outputTokens":10,"cacheReadTokens":0,"reasoningTokens":4},"stream":[{"type":"chunk","time":1788699430709,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1788699430709,"index":0,"dt":[],"texts":["The skill is loaded."]},{"type":"chunk","time":1788699430709,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1788699430709,"index":1,"dt":[],"texts":["DONE"]},{"type":"chunk","time":1788699430709,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The skill is loaded."}}},{"type":"chunk","time":1788699430709,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"DONE"}}},{"type":"chunk","time":1788699430709,"chunk":{"type":"usage","usage":{"inputTokens":180,"outputTokens":10,"cacheReadTokens":0,"reasoningTokens":4}}},{"type":"chunk","time":1788699430709,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} diff --git a/snapshots/session/headless.snapshot.ts b/snapshots/session/headless.snapshot.ts index 54fd2ef6a1..673fd2e2d4 100644 --- a/snapshots/session/headless.snapshot.ts +++ b/snapshots/session/headless.snapshot.ts @@ -763,7 +763,7 @@ function verifyAdvancedToolchain(logs: readonly SessionLog[]): void { expect(dispatches).toEqual([expect.objectContaining({ name: 'cordis_inspect', isError: false })]) const textOf = (index: number) => results[index]!.content .flatMap(block => block.type === 'text' ? [block.text] : []).join('') - expect(JSON.parse(textOf(1))).toEqual(['Service', 'Event', 'Config', 'Tool']) + expect(JSON.parse(textOf(1))).toEqual(['Service', 'Event', 'Config', 'Runtime', 'Tool']) expect(textOf(2)).toBe('started subagent agent-1') expect(events.filter(event => event.type === 'subagent/catalog').map(event => event.data)) .toContainEqual(expect.objectContaining({ childId: logs[1]!.header.id, name: 'agent-1' })) diff --git a/snapshots/session/plugin-manager-mcp/tool-schemas.expected.json b/snapshots/session/plugin-manager-mcp/tool-schemas.expected.json index 67353604d2..80153ff8a8 100644 --- a/snapshots/session/plugin-manager-mcp/tool-schemas.expected.json +++ b/snapshots/session/plugin-manager-mcp/tool-schemas.expected.json @@ -249,7 +249,7 @@ }, { "name": "plugin_manager", - "description": "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.", + "description": "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.", "parameters": { "type": "object", "properties": { @@ -1000,7 +1000,7 @@ }, { "name": "plugin_manager", - "description": "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.", + "description": "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.", "parameters": { "type": "object", "properties": { diff --git a/snapshots/session/plugin-manager/tool-schemas.expected.json b/snapshots/session/plugin-manager/tool-schemas.expected.json index cb0de5ebb9..142be41852 100644 --- a/snapshots/session/plugin-manager/tool-schemas.expected.json +++ b/snapshots/session/plugin-manager/tool-schemas.expected.json @@ -249,7 +249,7 @@ }, { "name": "plugin_manager", - "description": "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.", + "description": "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.", "parameters": { "type": "object", "properties": { diff --git a/snapshots/session/ptc-persistent-scoped/tool-schemas.expected.json b/snapshots/session/ptc-persistent-scoped/tool-schemas.expected.json index 69a9031f80..d868230788 100644 --- a/snapshots/session/ptc-persistent-scoped/tool-schemas.expected.json +++ b/snapshots/session/ptc-persistent-scoped/tool-schemas.expected.json @@ -2,7 +2,7 @@ "initial": [ { "name": "run_code", - "description": "Execute a TypeScript program against the available tools. Takes two required arguments: `code`, the program to execute, and `description`, a short summary of what the program does. Call tools as `await tools.name(args)` per the declarations in the system prompt. Show selected text and images with inspect(...values). 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": "Execute a TypeScript program against the available tools. Takes two required arguments: `code`, the program to execute, and `description`, a short summary of what the program does. Call tools as `await tools.name(args)` per the declarations in the system prompt. Show selected text and images with inspect(...values). 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.", "parameters": { "type": "object", "properties": { diff --git a/snapshots/session/ptc-persistent/tool-schemas.expected.json b/snapshots/session/ptc-persistent/tool-schemas.expected.json index 8a46ead47b..ef1c64e6a2 100644 --- a/snapshots/session/ptc-persistent/tool-schemas.expected.json +++ b/snapshots/session/ptc-persistent/tool-schemas.expected.json @@ -2,7 +2,7 @@ "initial": [ { "name": "run_code", - "description": "Execute a TypeScript program against the available tools. Takes two required arguments: `code`, the program to execute, and `description`, a short summary of what the program does. Call tools as `await tools.name(args)` per the declarations in the system prompt. Show selected text and images with inspect(...values). 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. Variables, functions, and imported modules remain in memory for this Agent across calls. Use await import(...) for modules. 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. Do not redeclare existing let, const, or class names; reuse mutable bindings or choose new names. 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": "Execute a TypeScript program against the available tools. Takes two required arguments: `code`, the program to execute, and `description`, a short summary of what the program does. Call tools as `await tools.name(args)` per the declarations in the system prompt. Show selected text and images with inspect(...values). 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. Variables, functions, and imported modules remain in memory for this Agent across calls. Use await import(...) for modules. 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. Do not redeclare existing let, const, or class names; reuse mutable bindings or choose new names. 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.", "parameters": { "type": "object", "properties": { diff --git a/snapshots/session/ptc-reset/tool-schemas.expected.json b/snapshots/session/ptc-reset/tool-schemas.expected.json index 1d6b88ea40..143a17dcc6 100644 --- a/snapshots/session/ptc-reset/tool-schemas.expected.json +++ b/snapshots/session/ptc-reset/tool-schemas.expected.json @@ -2,7 +2,7 @@ "initial": [ { "name": "run_code", - "description": "Execute a TypeScript program against the available tools. Takes two required arguments: `code`, the program to execute, and `description`, a short summary of what the program does. Call tools as `await tools.name(args)` per the declarations in the system prompt. Show selected text and images with inspect(...values). The program contains TypeScript script 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 final expression is awaited if it is a Promise. Variables, functions, and imported modules remain in memory for this Agent across calls. Use await import(...) for modules. Relative paths use the supplied working directory. Direct filesystem access follows the environment's launch-time sandbox policy; process.env starts empty. Await asynchronous work: an uncaught callback exception or unhandled rejection terminates the process and clears its variables. Values from bindings and imports can belong to another realm; use Array.isArray for arrays and the supplied binding error classes for failures, because instanceof Array or Error may be false. 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. Do not redeclare existing let, const, or class names; reuse mutable bindings or choose new names. 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. If a native top-level let, const, or class initializer throws, its name may remain permanently uninitialized; use a new name or restart the environment. 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": "Execute a TypeScript program against the available tools. Takes two required arguments: `code`, the program to execute, and `description`, a short summary of what the program does. Call tools as `await tools.name(args)` per the declarations in the system prompt. Show selected text and images with inspect(...values). The program contains TypeScript script 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 final expression is awaited if it is a Promise. Variables, functions, and imported modules remain in memory for this Agent across calls. Use await import(...) for modules. Relative paths use the supplied working directory. Direct filesystem access follows the environment's launch-time sandbox policy; process.env starts empty. Await asynchronous work: an uncaught callback exception or unhandled rejection terminates the process and clears its variables. Values from bindings and imports can belong to another realm; use Array.isArray for arrays and the supplied binding error classes for failures, because instanceof Array or Error may be false. 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. Do not redeclare existing let, const, or class names; reuse mutable bindings or choose new names. 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. If a native top-level let, const, or class initializer throws, its name may remain permanently uninitialized; use a new name or restart the environment. 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.", "parameters": { "type": "object", "properties": { diff --git a/snapshots/session/ptc-scoped-repl/tool-schemas.expected.json b/snapshots/session/ptc-scoped-repl/tool-schemas.expected.json index 69a9031f80..d868230788 100644 --- a/snapshots/session/ptc-scoped-repl/tool-schemas.expected.json +++ b/snapshots/session/ptc-scoped-repl/tool-schemas.expected.json @@ -2,7 +2,7 @@ "initial": [ { "name": "run_code", - "description": "Execute a TypeScript program against the available tools. Takes two required arguments: `code`, the program to execute, and `description`, a short summary of what the program does. Call tools as `await tools.name(args)` per the declarations in the system prompt. Show selected text and images with inspect(...values). 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": "Execute a TypeScript program against the available tools. Takes two required arguments: `code`, the program to execute, and `description`, a short summary of what the program does. Call tools as `await tools.name(args)` per the declarations in the system prompt. Show selected text and images with inspect(...values). 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.", "parameters": { "type": "object", "properties": { diff --git a/snapshots/session/ptc-timeout-fallback/tool-schemas.expected.json b/snapshots/session/ptc-timeout-fallback/tool-schemas.expected.json index c37e3b76fa..d2ac80e11a 100644 --- a/snapshots/session/ptc-timeout-fallback/tool-schemas.expected.json +++ b/snapshots/session/ptc-timeout-fallback/tool-schemas.expected.json @@ -2,7 +2,7 @@ "initial": [ { "name": "run_code", - "description": "Execute a TypeScript program against the available tools. Takes two required arguments: `code`, the program to execute, and `description`, a short summary of what the program does. Call tools as `await tools.name(args)` per the declarations in the system prompt. Show selected text and images with inspect(...values). The program contains TypeScript script 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 final expression is awaited if it is a Promise. Variables, functions, and imported modules remain in memory for this Agent across calls. Use await import(...) for modules. Relative paths use the supplied working directory. Direct filesystem access follows the environment's launch-time sandbox policy; process.env starts empty. Await asynchronous work: an uncaught callback exception or unhandled rejection terminates the process and clears its variables. Values from bindings and imports can belong to another realm; use Array.isArray for arrays and the supplied binding error classes for failures, because instanceof Array or Error may be false. 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. Do not redeclare existing let, const, or class names; reuse mutable bindings or choose new names. 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. If a native top-level let, const, or class initializer throws, its name may remain permanently uninitialized; use a new name or restart the environment. 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": "Execute a TypeScript program against the available tools. Takes two required arguments: `code`, the program to execute, and `description`, a short summary of what the program does. Call tools as `await tools.name(args)` per the declarations in the system prompt. Show selected text and images with inspect(...values). The program contains TypeScript script 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 final expression is awaited if it is a Promise. Variables, functions, and imported modules remain in memory for this Agent across calls. Use await import(...) for modules. Relative paths use the supplied working directory. Direct filesystem access follows the environment's launch-time sandbox policy; process.env starts empty. Await asynchronous work: an uncaught callback exception or unhandled rejection terminates the process and clears its variables. Values from bindings and imports can belong to another realm; use Array.isArray for arrays and the supplied binding error classes for failures, because instanceof Array or Error may be false. 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. Do not redeclare existing let, const, or class names; reuse mutable bindings or choose new names. 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. If a native top-level let, const, or class initializer throws, its name may remain permanently uninitialized; use a new name or restart the environment. 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.", "parameters": { "type": "object", "properties": { diff --git a/snapshots/session/ralph-loop/session.1.v4.jsonl b/snapshots/session/ralph-loop/session.1.v4.jsonl index 82a097c2e3..6a594fa85e 100644 --- a/snapshots/session/ralph-loop/session.1.v4.jsonl +++ b/snapshots/session/ralph-loop/session.1.v4.jsonl @@ -3,18 +3,17 @@ {"type":"sandbox/mode","data":{"mode":"danger-full-access","source":"delegation"}} {"type":"approval/policy","data":{"policy":"never","source":"delegation"}} {"type":"permission/preset","data":{"preset":"danger-full-access"}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"You are one fresh worker in a foreground Ralph loop. You receive no parent conversation and no prior child session. Do not call the ralph tool: this round already is its worker.\n\nImmutable objective:\nProve two fresh Ralph rounds through the shipped headless app.\n\nRalph round: 1 of 2.\n\nThe shared workspace and its current working tree are the long-term memory and source of truth. Inspect them before acting, preserve existing work, perform concrete in-scope work, and verify what you change. Treat the previous report only as a bounded handoff; confirm it against the workspace.\n\nPrevious structured handoff:\n(none — this is the first round)\n\nReturn one report with exact normalized strings. Use status continue with at least one nextSteps entry while useful work remains; complete only with concrete evidence and no nextSteps; blocked only when no meaningful progress is possible without human input or an external-state change. blocker must be empty unless blocked."}],"source":{"kind":"user"},"role":"user","id":"{{message:7}}"}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"You are one fresh worker in a foreground Ralph loop. You receive no parent conversation and no prior child session. Do not call the ralph tool: this round already is its worker.\n\nImmutable objective:\nProve two fresh Ralph rounds through the shipped headless app.\n\nRalph round: 1 of 2.\n\nThe shared workspace and its current working tree are the long-term memory and source of truth. Inspect them before acting, preserve existing work, perform concrete in-scope work, and verify what you change. Treat the previous report only as a bounded handoff; confirm it against the workspace.\n\nPrevious structured handoff:\n(none — this is the first round)\n\nReturn one report with exact normalized strings. Use status continue with at least one nextSteps entry while useful work remains; complete only with concrete evidence and no nextSteps; blocked only when no meaningful progress is possible without human input or an external-state change. blocker must be empty unless blocked."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{session:1}}"},"role":"user","id":"{{message:7}}"}]}} {"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":"{{message:8}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"You are one fresh worker in a foreground Ralph loop. You receive no parent conversation and no prior child session. Do not call the ralph tool: this round already is its worker.\n\nImmutable objective:\nProve two fresh Ralph rounds through the shipped headless app.\n\nRalph round: 1 of 2.\n\nThe shared workspace and its current working tree are the long-term memory and source of truth. Inspect them before acting, preserve existing work, perform concrete in-scope work, and verify what you change. Treat the previous report only as a bounded handoff; confirm it against the workspace.\n\nPrevious structured handoff:\n(none — this is the first round)\n\nReturn one report with exact normalized strings. Use status continue with at least one nextSteps entry while useful work remains; complete only with concrete evidence and no nextSteps; blocked only when no meaningful progress is possible without human input or an external-state change. blocker must be empty unless blocked."}],"source":{"kind":"user"},"role":"user","id":"{{message:7}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", 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":"{{message:9}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"You are one fresh worker in a foreground Ralph loop. You receive no parent conversation and no prior child session. Do not call the ralph tool: this round already is its worker.\n\nImmutable objective:\nProve two fresh Ralph rounds through the shipped headless app.\n\nRalph round: 1 of 2.\n\nThe shared workspace and its current working tree are the long-term memory and source of truth. Inspect them before acting, preserve existing work, perform concrete in-scope work, and verify what you change. Treat the previous report only as a bounded handoff; confirm it against the workspace.\n\nPrevious structured handoff:\n(none — this is the first round)\n\nReturn one report with exact normalized strings. Use status continue with at least one nextSteps entry while useful work remains; complete only with concrete evidence and no nextSteps; blocked only when no meaningful progress is possible without human input or an external-state change. blocker must be empty unless blocked."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{session:1}}"},"role":"user","id":"{{message:7}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", 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 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", 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 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":"{{message:9}}"},"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":"You are one fresh worker","messageSeqs":[9],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"round-one-report","name":"structured_output","arguments":"{\"status\":\"continue\",\"summary\":\"ROUND_ONE_HANDOFF\",\"evidence\":[\"Round one inspected the workspace.\"],\"nextSteps\":[\"Finish the snapshot objective.\"],\"blocker\":\"\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:10}}"},"usage":{"inputTokens":30,"outputTokens":12},"stream":[{"type":"chunk","time":1789821421140,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1789821421140,"index":0,"dt":[],"id":"round-one-report","name":"structured_output","args":["{\"status\":\"continue\",\"summary\":\"ROUND_ONE_HANDOFF\",\"evidence\":[\"Round one inspected the workspace.\"],\"nextSteps\":[\"Finish the snapshot objective.\"],\"blocker\":\"\"}"]},{"type":"chunk","time":1789821421140,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"round-one-report","name":"structured_output","arguments":"{\"status\":\"continue\",\"summary\":\"ROUND_ONE_HANDOFF\",\"evidence\":[\"Round one inspected the workspace.\"],\"nextSteps\":[\"Finish the snapshot objective.\"],\"blocker\":\"\"}"}}},{"type":"chunk","time":1789821421140,"chunk":{"type":"usage","usage":{"inputTokens":30,"outputTokens":12}}},{"type":"chunk","time":1789821421141,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"round-one-report","name":"structured_output","arguments":"{\"status\":\"continue\",\"summary\":\"ROUND_ONE_HANDOFF\",\"evidence\":[\"Round one inspected the workspace.\"],\"nextSteps\":[\"Finish the snapshot objective.\"],\"blocker\":\"\"}"}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"round-one-report"},"toolCallId":"round-one-report","content":[{"type":"text","text":"Structured output recorded."}],"isError":false,"id":"{{message:11}}"}},"sourceEventSeqs":[15],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"round-one-report"},"toolCallId":"round-one-report","content":[{"type":"text","text":"Structured output recorded."}],"isError":false,"id":"{{message:11}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/snapshots/session/ralph-loop/session.2.v4.jsonl b/snapshots/session/ralph-loop/session.2.v4.jsonl index c73c2a1649..00f685412e 100644 --- a/snapshots/session/ralph-loop/session.2.v4.jsonl +++ b/snapshots/session/ralph-loop/session.2.v4.jsonl @@ -3,18 +3,17 @@ {"type":"sandbox/mode","data":{"mode":"danger-full-access","source":"delegation"}} {"type":"approval/policy","data":{"policy":"never","source":"delegation"}} {"type":"permission/preset","data":{"preset":"danger-full-access"}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"You are one fresh worker in a foreground Ralph loop. You receive no parent conversation and no prior child session. Do not call the ralph tool: this round already is its worker.\n\nImmutable objective:\nProve two fresh Ralph rounds through the shipped headless app.\n\nRalph round: 2 of 2.\n\nThe shared workspace and its current working tree are the long-term memory and source of truth. Inspect them before acting, preserve existing work, perform concrete in-scope work, and verify what you change. Treat the previous report only as a bounded handoff; confirm it against the workspace.\n\nPrevious structured handoff:\n{\"status\":\"continue\",\"summary\":\"ROUND_ONE_HANDOFF\",\"evidence\":[\"Round one inspected the workspace.\"],\"nextSteps\":[\"Finish the snapshot objective.\"],\"blocker\":\"\"}\n\nReturn one report with exact normalized strings. Use status continue with at least one nextSteps entry while useful work remains; complete only with concrete evidence and no nextSteps; blocked only when no meaningful progress is possible without human input or an external-state change. blocker must be empty unless blocked."}],"source":{"kind":"user"},"role":"user","id":"{{message:12}}"}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"You are one fresh worker in a foreground Ralph loop. You receive no parent conversation and no prior child session. Do not call the ralph tool: this round already is its worker.\n\nImmutable objective:\nProve two fresh Ralph rounds through the shipped headless app.\n\nRalph round: 2 of 2.\n\nThe shared workspace and its current working tree are the long-term memory and source of truth. Inspect them before acting, preserve existing work, perform concrete in-scope work, and verify what you change. Treat the previous report only as a bounded handoff; confirm it against the workspace.\n\nPrevious structured handoff:\n{\"status\":\"continue\",\"summary\":\"ROUND_ONE_HANDOFF\",\"evidence\":[\"Round one inspected the workspace.\"],\"nextSteps\":[\"Finish the snapshot objective.\"],\"blocker\":\"\"}\n\nReturn one report with exact normalized strings. Use status continue with at least one nextSteps entry while useful work remains; complete only with concrete evidence and no nextSteps; blocked only when no meaningful progress is possible without human input or an external-state change. blocker must be empty unless blocked."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{session:1}}"},"role":"user","id":"{{message:12}}"}]}} {"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":"{{message:13}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"You are one fresh worker in a foreground Ralph loop. You receive no parent conversation and no prior child session. Do not call the ralph tool: this round already is its worker.\n\nImmutable objective:\nProve two fresh Ralph rounds through the shipped headless app.\n\nRalph round: 2 of 2.\n\nThe shared workspace and its current working tree are the long-term memory and source of truth. Inspect them before acting, preserve existing work, perform concrete in-scope work, and verify what you change. Treat the previous report only as a bounded handoff; confirm it against the workspace.\n\nPrevious structured handoff:\n{\"status\":\"continue\",\"summary\":\"ROUND_ONE_HANDOFF\",\"evidence\":[\"Round one inspected the workspace.\"],\"nextSteps\":[\"Finish the snapshot objective.\"],\"blocker\":\"\"}\n\nReturn one report with exact normalized strings. Use status continue with at least one nextSteps entry while useful work remains; complete only with concrete evidence and no nextSteps; blocked only when no meaningful progress is possible without human input or an external-state change. blocker must be empty unless blocked."}],"source":{"kind":"user"},"role":"user","id":"{{message:12}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", 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":"{{message:14}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"You are one fresh worker in a foreground Ralph loop. You receive no parent conversation and no prior child session. Do not call the ralph tool: this round already is its worker.\n\nImmutable objective:\nProve two fresh Ralph rounds through the shipped headless app.\n\nRalph round: 2 of 2.\n\nThe shared workspace and its current working tree are the long-term memory and source of truth. Inspect them before acting, preserve existing work, perform concrete in-scope work, and verify what you change. Treat the previous report only as a bounded handoff; confirm it against the workspace.\n\nPrevious structured handoff:\n{\"status\":\"continue\",\"summary\":\"ROUND_ONE_HANDOFF\",\"evidence\":[\"Round one inspected the workspace.\"],\"nextSteps\":[\"Finish the snapshot objective.\"],\"blocker\":\"\"}\n\nReturn one report with exact normalized strings. Use status continue with at least one nextSteps entry while useful work remains; complete only with concrete evidence and no nextSteps; blocked only when no meaningful progress is possible without human input or an external-state change. blocker must be empty unless blocked."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{session:1}}"},"role":"user","id":"{{message:12}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", 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 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", 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 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":"{{message:14}}"},"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":"You are one fresh worker","messageSeqs":[9],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"round-two-report","name":"structured_output","arguments":"{\"status\":\"complete\",\"summary\":\"The Ralph snapshot objective is complete.\",\"evidence\":[\"Two fresh rounds completed through the shipped app.\"],\"nextSteps\":[],\"blocker\":\"\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:15}}"},"usage":{"inputTokens":40,"outputTokens":12},"stream":[{"type":"chunk","time":1789821421212,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1789821421212,"index":0,"dt":[],"id":"round-two-report","name":"structured_output","args":["{\"status\":\"complete\",\"summary\":\"The Ralph snapshot objective is complete.\",\"evidence\":[\"Two fresh rounds completed through the shipped app.\"],\"nextSteps\":[],\"blocker\":\"\"}"]},{"type":"chunk","time":1789821421212,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"round-two-report","name":"structured_output","arguments":"{\"status\":\"complete\",\"summary\":\"The Ralph snapshot objective is complete.\",\"evidence\":[\"Two fresh rounds completed through the shipped app.\"],\"nextSteps\":[],\"blocker\":\"\"}"}}},{"type":"chunk","time":1789821421212,"chunk":{"type":"usage","usage":{"inputTokens":40,"outputTokens":12}}},{"type":"chunk","time":1789821421212,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"round-two-report","name":"structured_output","arguments":"{\"status\":\"complete\",\"summary\":\"The Ralph snapshot objective is complete.\",\"evidence\":[\"Two fresh rounds completed through the shipped app.\"],\"nextSteps\":[],\"blocker\":\"\"}"}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"round-two-report"},"toolCallId":"round-two-report","content":[{"type":"text","text":"Structured output recorded."}],"isError":false,"id":"{{message:16}}"}},"sourceEventSeqs":[15],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"round-two-report"},"toolCallId":"round-two-report","content":[{"type":"text","text":"Structured output recorded."}],"isError":false,"id":"{{message:16}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/snapshots/session/subagent-agent-preset/session.1.v4.jsonl b/snapshots/session/subagent-agent-preset/session.1.v4.jsonl index 62bf1c479e..c495de1000 100644 --- a/snapshots/session/subagent-agent-preset/session.1.v4.jsonl +++ b/snapshots/session/subagent-agent-preset/session.1.v4.jsonl @@ -4,16 +4,15 @@ {"type":"sandbox/mode","data":{"mode":"danger-full-access","source":"delegation"}} {"type":"approval/policy","data":{"policy":"never","source":"delegation"}} {"type":"permission/preset","data":{"preset":"danger-full-access"}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly the word CHILD_OK and nothing else."},{"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":"{{message:9}}"}]}} +{"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 the word CHILD_OK and nothing else."},{"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":"{{session:1}}"},"role":"user","id":"{{message:9}}"}]}} {"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":"{{message:10}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly the word CHILD_OK and nothing else."},{"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":"{{message:9}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", 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\nDelegation depth for `reviewer_delegate`: current 1, maximum 1, remaining levels 0. Do not call `reviewer_delegate` 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", 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":"tool:reviewer_delegate:depth","text":"Delegation depth for `reviewer_delegate`: current 1, maximum 1, remaining levels 0. Do not call `reviewer_delegate` 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":"{{message:11}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Reply with exactly the word CHILD_OK and nothing else."},{"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":"{{session:1}}"},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", 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\nDelegation depth for `reviewer_delegate`: current 1, maximum 1, remaining levels 0. Do not call `reviewer_delegate` 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 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", 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":"tool:reviewer_delegate:depth","text":"Delegation depth for `reviewer_delegate`: current 1, maximum 1, remaining levels 0. Do not call `reviewer_delegate` 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 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":"{{message:11}}"},"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 the word","messageSeqs":[10],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to reply with exactly the word CHILD_OK and nothing else."},{"type":"text","text":"CHILD_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:12}}"},"usage":{"inputTokens":48,"outputTokens":21,"cacheReadTokens":2816,"reasoningTokens":17},"stream":[{"type":"chunk","time":1790502919138,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1790502919138,"index":0,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["The"," user"," wants"," me"," to"," reply"," with"," exactly"," the"," word"," CH","ILD","_OK"," and"," nothing"," else","."]},{"type":"chunk","time":1790502919138,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1790502919138,"index":1,"dt":[0,0],"texts":["CH","ILD","_OK"]},{"type":"chunk","time":1790502919138,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to reply with exactly the word CHILD_OK and nothing else."}}},{"type":"chunk","time":1790502919138,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"CHILD_OK"}}},{"type":"chunk","time":1790502919138,"chunk":{"type":"usage","usage":{"inputTokens":48,"outputTokens":21,"cacheReadTokens":2816,"reasoningTokens":17}}},{"type":"chunk","time":1790502919138,"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"}}} diff --git a/snapshots/session/subagent-archive-lineage/session.1.v4.jsonl b/snapshots/session/subagent-archive-lineage/session.1.v4.jsonl index ba37cda623..3b870f285c 100644 --- a/snapshots/session/subagent-archive-lineage/session.1.v4.jsonl +++ b/snapshots/session/subagent-archive-lineage/session.1.v4.jsonl @@ -3,17 +3,16 @@ {"type":"sandbox/mode","data":{"mode":"danger-full-access","source":"delegation"}} {"type":"approval/policy","data":{"policy":"never","source":"delegation"}} {"type":"permission/preset","data":{"preset":"danger-full-access"}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with DONE."}],"source":{"kind":"user"},"role":"user","id":"{{message:7}}"}]}} +{"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 DONE."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{session:1}}"},"role":"user","id":"{{message:7}}"}]}} {"type":"turn/start","data":{"turn":1}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} -{"type":"subagent/catalog","data":{"version":3,"childId":"{{session:3}}","childCreatedAt":1792738858406,"mode":"continuable","label":"{{session:3}}","name":"agent-1"}} +{"type":"subagent/catalog","data":{"version":3,"childId":"{{session:3}}","childCreatedAt":1794555188094,"mode":"continuable","label":"{{session:3}}","name":"agent-1"}} {"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":"{{message:8}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Reply with DONE."}],"source":{"kind":"user"},"role":"user","id":"{{message:7}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", 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":"{{message:9}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Reply with DONE."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{session:1}}"},"role":"user","id":"{{message:7}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", 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 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", 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 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":"{{message:9}}"},"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 DONE.","messageSeqs":[10],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:10}}"},"usage":{"inputTokens":10,"outputTokens":2},"stream":[{"type":"chunk","time":1792738858490,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1792738858490,"index":0,"dt":[],"texts":["DONE"]},{"type":"chunk","time":1792738858490,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DONE"}}},{"type":"chunk","time":1792738858490,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":2}}},{"type":"chunk","time":1792738858490,"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"}}} diff --git a/snapshots/session/subagent-archive-lineage/session.2.v4.jsonl b/snapshots/session/subagent-archive-lineage/session.2.v4.jsonl index a1127c04f6..a4bd1a89d6 100644 --- a/snapshots/session/subagent-archive-lineage/session.2.v4.jsonl +++ b/snapshots/session/subagent-archive-lineage/session.2.v4.jsonl @@ -3,17 +3,16 @@ {"type":"sandbox/mode","data":{"mode":"danger-full-access","source":"delegation"}} {"type":"approval/policy","data":{"policy":"never","source":"delegation"}} {"type":"permission/preset","data":{"preset":"danger-full-access"}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with DONE."}],"source":{"kind":"user"},"role":"user","id":"{{message:11}}"}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Agent agent-1 sent a message: "},{"type":"text","text":"Reply with DONE."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{session:2}}"},"role":"user","id":"{{message:11}}"}]}} {"type":"turn/start","data":{"turn":1}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} -{"type":"subagent/catalog","data":{"version":3,"childId":"{{session:4}}","childCreatedAt":1792738858410,"mode":"continuable","label":"{{session:4}}","name":"agent-1"}} +{"type":"subagent/catalog","data":{"version":3,"childId":"{{session:4}}","childCreatedAt":1794555188101,"mode":"continuable","label":"{{session:4}}","name":"agent-1"}} {"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":"{{message:12}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Reply with DONE."}],"source":{"kind":"user"},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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 \"agent-1\".\nYour name is \"agent-1/agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", 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 2, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 2, 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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 \"agent-1\".\nYour name is \"agent-1/agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", 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 2, 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 2, 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":"{{message:13}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Agent agent-1 sent a message: "},{"type":"text","text":"Reply with DONE."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{session:2}}"},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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 \"agent-1\".\nYour name is \"agent-1/agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", 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 2, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 2, 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 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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 \"agent-1\".\nYour name is \"agent-1/agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", 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 2, 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 2, 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 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":"{{message:13}}"},"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 DONE.","messageSeqs":[10],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:14}}"},"usage":{"inputTokens":10,"outputTokens":2},"stream":[{"type":"chunk","time":1792738858486,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1792738858486,"index":0,"dt":[],"texts":["DONE"]},{"type":"chunk","time":1792738858486,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DONE"}}},{"type":"chunk","time":1792738858486,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":2}}},{"type":"chunk","time":1792738858486,"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"}}} diff --git a/snapshots/session/subagent-archive-lineage/session.3.v4.jsonl b/snapshots/session/subagent-archive-lineage/session.3.v4.jsonl index 7adb9712f4..db865974b8 100644 --- a/snapshots/session/subagent-archive-lineage/session.3.v4.jsonl +++ b/snapshots/session/subagent-archive-lineage/session.3.v4.jsonl @@ -3,7 +3,7 @@ {"type":"sandbox/mode","data":{"mode":"danger-full-access","source":"delegation"}} {"type":"approval/policy","data":{"policy":"never","source":"delegation"}} {"type":"permission/preset","data":{"preset":"danger-full-access"}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with DONE."}],"source":{"kind":"user"},"role":"user","id":"{{message:15}}"}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Agent agent-1/agent-1 sent a message: "},{"type":"text","text":"Reply with DONE."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{session:3}}"},"role":"user","id":"{{message:15}}"}]}} {"type":"turn/start","data":{"turn":1}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"aborted","reason":{"kind":"parent"}}}} diff --git a/snapshots/session/subagent-child-question-rejection/session.1.v4.jsonl b/snapshots/session/subagent-child-question-rejection/session.1.v4.jsonl index 99c7c7736b..168c68cccf 100644 --- a/snapshots/session/subagent-child-question-rejection/session.1.v4.jsonl +++ b/snapshots/session/subagent-child-question-rejection/session.1.v4.jsonl @@ -3,19 +3,18 @@ {"type":"sandbox/mode","data":{"mode":"danger-full-access","source":"delegation"}} {"type":"approval/policy","data":{"policy":"never","source":"delegation"}} {"type":"permission/preset","data":{"preset":"danger-full-access"}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Call ask_user_question once to ask whether deployment should use the CUDA fallback. If the tool returns an error, include the unresolved question verbatim in your final result."},{"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":"{{message:9}}"}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Call ask_user_question once to ask whether deployment should use the CUDA fallback. If the tool returns an error, include the unresolved question verbatim in your final result."},{"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":"{{session:1}}"},"role":"user","id":"{{message:9}}"}]}} {"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":"{{message:10}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Call ask_user_question once to ask whether deployment should use the CUDA fallback. If the tool returns an error, include the unresolved question verbatim in your final result."},{"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":"{{message:9}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", 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":"{{message:11}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Call ask_user_question once to ask whether deployment should use the CUDA fallback. If the tool returns an error, include the unresolved question verbatim in your final result."},{"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":"{{session:1}}"},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", 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 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", 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 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":"{{message:11}}"},"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":"Call ask_user_question once to ask","messageSeqs":[9],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_child_question","name":"ask_user_question","arguments":"{\"questions\":[{\"id\":\"cuda-fallback\",\"header\":\"Deployment\",\"question\":\"Should deployment use the CUDA fallback?\"}]}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:12}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1789625677727,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1789625677727,"index":0,"dt":[],"id":"call_child_question","name":"ask_user_question","args":["{\"questions\":[{\"id\":\"cuda-fallback\",\"header\":\"Deployment\",\"question\":\"Should deployment use the CUDA fallback?\"}]}"]},{"type":"chunk","time":1789625677727,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_child_question","name":"ask_user_question","arguments":"{\"questions\":[{\"id\":\"cuda-fallback\",\"header\":\"Deployment\",\"question\":\"Should deployment use the CUDA fallback?\"}]}"}}},{"type":"chunk","time":1789625677727,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1789625677727,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_child_question","name":"ask_user_question","arguments":"{\"questions\":[{\"id\":\"cuda-fallback\",\"header\":\"Deployment\",\"question\":\"Should deployment use the CUDA fallback?\"}]}"}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_child_question"},"toolCallId":"call_child_question","content":[{"type":"text","text":"Error: human interaction is unavailable while the calling agent is owned by another live agent; include the unresolved question or decision in the child agent's final result"}],"isError":true,"id":"{{message:13}}"},"error":{"name":"UserQuestionError","code":"DELEGATED_CALLER"}},"sourceEventSeqs":[15],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_child_question"},"toolCallId":"call_child_question","content":[{"type":"text","text":"Error: human interaction is unavailable while the calling agent is owned by another live agent; include the unresolved question or decision in the child agent's final result"}],"isError":true,"id":"{{message:13}}"},"error":{"name":"UserQuestionError","code":"DELEGATED_CALLER"}},"sourceEventSeqs":[14],"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":"UNRESOLVED: Should deployment use the CUDA fallback?"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:14}}"},"usage":{"inputTokens":10,"outputTokens":4},"stream":[{"type":"chunk","time":1789625677747,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1789625677747,"index":0,"dt":[],"texts":["UNRESOLVED: Should deployment use the CUDA fallback?"]},{"type":"chunk","time":1789625677747,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"UNRESOLVED: Should deployment use the CUDA fallback?"}}},{"type":"chunk","time":1789625677747,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":4}}},{"type":"chunk","time":1789625677747,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} diff --git a/snapshots/session/subagent-depth-two-rejection/session.1.v4.jsonl b/snapshots/session/subagent-depth-two-rejection/session.1.v4.jsonl index 311b781f19..33ae6a0ddf 100644 --- a/snapshots/session/subagent-depth-two-rejection/session.1.v4.jsonl +++ b/snapshots/session/subagent-depth-two-rejection/session.1.v4.jsonl @@ -3,20 +3,19 @@ {"type":"sandbox/mode","data":{"mode":"danger-full-access","source":"delegation"}} {"type":"approval/policy","data":{"policy":"never","source":"delegation"}} {"type":"permission/preset","data":{"preset":"danger-full-access"}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Call subagent once. Ask that child to attempt one further subagent call, then report the result."},{"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":"{{message:9}}"}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Call subagent once. Ask that child to attempt one further subagent call, then report the result."},{"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":"{{session:1}}"},"role":"user","id":"{{message:9}}"}]}} {"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":"{{message:10}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Call subagent once. Ask that child to attempt one further subagent call, then report the result."},{"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":"{{message:9}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", 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_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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", 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_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":"{{message:11}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Call subagent once. Ask that child to attempt one further subagent call, then report the result."},{"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":"{{session:1}}"},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", 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_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 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", 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_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 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":"{{message:11}}"},"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":"Call subagent once. Ask that","messageSeqs":[9],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_depth_one_child","name":"subagent","arguments":"{\"description\":\"Start depth two\",\"prompt\":\"Attempt one subagent call beyond the configured cap, then report the rejection.\",\"run_in_background\":false}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:12}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1792224103513,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1792224103513,"index":0,"dt":[],"id":"call_depth_one_child","name":"subagent","args":["{\"description\":\"Start depth two\",\"prompt\":\"Attempt one subagent call beyond the configured cap, then report the rejection.\",\"run_in_background\":false}"]},{"type":"chunk","time":1792224103513,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_depth_one_child","name":"subagent","arguments":"{\"description\":\"Start depth two\",\"prompt\":\"Attempt one subagent call beyond the configured cap, then report the rejection.\",\"run_in_background\":false}"}}},{"type":"chunk","time":1792224103513,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1792224103513,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_depth_one_child","name":"subagent","arguments":"{\"description\":\"Start depth two\",\"prompt\":\"Attempt one subagent call beyond the configured cap, then report the rejection.\",\"run_in_background\":false}"}} -{"type":"subagent/catalog","data":{"version":3,"childId":"{{session:3}}","childCreatedAt":1792224103521,"mode":"continuable","label":"Start depth two","name":"agent-1"}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_depth_one_child"},"toolCallId":"call_depth_one_child","content":[{"type":"text","text":"started subagent agent-1/agent-1"}],"isError":false,"id":"{{message:13}}"},"meta":{"kind":"activation","name":"agent-1/agent-1"}},"sourceEventSeqs":[15],"surfaceOp":"append"} +{"type":"subagent/catalog","data":{"version":3,"childId":"{{session:3}}","childCreatedAt":1794555191161,"mode":"continuable","label":"Start depth two","name":"agent-1"}} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_depth_one_child"},"toolCallId":"call_depth_one_child","content":[{"type":"text","text":"started subagent agent-1/agent-1"}],"isError":false,"id":"{{message:13}}"},"meta":{"kind":"activation","name":"agent-1/agent-1"}},"sourceEventSeqs":[14],"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":"DEPTH_ONE_DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:14}}"},"usage":{"inputTokens":10,"outputTokens":2},"stream":[{"type":"chunk","time":1792224103556,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1792224103556,"index":0,"dt":[],"texts":["DEPTH_ONE_DONE"]},{"type":"chunk","time":1792224103556,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DEPTH_ONE_DONE"}}},{"type":"chunk","time":1792224103556,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":2}}},{"type":"chunk","time":1792224103556,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} diff --git a/snapshots/session/subagent-depth-two-rejection/session.2.v4.jsonl b/snapshots/session/subagent-depth-two-rejection/session.2.v4.jsonl index 8ee62bf7c6..6fd892fbe5 100644 --- a/snapshots/session/subagent-depth-two-rejection/session.2.v4.jsonl +++ b/snapshots/session/subagent-depth-two-rejection/session.2.v4.jsonl @@ -3,19 +3,18 @@ {"type":"sandbox/mode","data":{"mode":"danger-full-access","source":"delegation"}} {"type":"approval/policy","data":{"policy":"never","source":"delegation"}} {"type":"permission/preset","data":{"preset":"danger-full-access"}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Attempt one subagent call beyond the configured cap, then report the rejection."},{"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":"{{message:15}}"}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Agent agent-1 sent a message: "},{"type":"text","text":"Attempt one subagent call beyond the configured cap, then report the rejection."},{"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":"{{session:2}}"},"role":"user","id":"{{message:15}}"}]}} {"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":"{{message:16}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Attempt one subagent call beyond the configured cap, then report the rejection."},{"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":"{{message:15}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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 \"agent-1\".\nYour name is \"agent-1/agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", 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 2, maximum 2, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 2, 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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 \"agent-1\".\nYour name is \"agent-1/agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", 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 2, maximum 2, 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 2, 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":"{{message:17}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Agent agent-1 sent a message: "},{"type":"text","text":"Attempt one subagent call beyond the configured cap, then report the rejection."},{"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":"{{session:2}}"},"role":"user","id":"{{message:15}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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 \"agent-1\".\nYour name is \"agent-1/agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", 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 2, maximum 2, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 2, 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 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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 \"agent-1\".\nYour name is \"agent-1/agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", 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 2, maximum 2, 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 2, 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 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":"{{message:17}}"},"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":"Attempt one subagent call beyond","messageSeqs":[9],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_depth_three_rejected","name":"subagent","arguments":"{\"description\":\"Exceed depth cap\",\"prompt\":\"This child must never start.\",\"run_in_background\":false}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:18}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1789625678968,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1789625678968,"index":0,"dt":[],"id":"call_depth_three_rejected","name":"subagent","args":["{\"description\":\"Exceed depth cap\",\"prompt\":\"This child must never start.\",\"run_in_background\":false}"]},{"type":"chunk","time":1789625678968,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_depth_three_rejected","name":"subagent","arguments":"{\"description\":\"Exceed depth cap\",\"prompt\":\"This child must never start.\",\"run_in_background\":false}"}}},{"type":"chunk","time":1789625678968,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1789625678968,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_depth_three_rejected","name":"subagent","arguments":"{\"description\":\"Exceed depth cap\",\"prompt\":\"This child must never start.\",\"run_in_background\":false}"}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_depth_three_rejected"},"toolCallId":"call_depth_three_rejected","content":[{"type":"text","text":"Error: subagent depth 3 exceeds maxDepth 2"}],"isError":true,"id":"{{message:19}}"},"error":{"name":"SubagentDepthError","code":"DEPTH_EXCEEDED"}},"sourceEventSeqs":[15],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_depth_three_rejected"},"toolCallId":"call_depth_three_rejected","content":[{"type":"text","text":"Error: subagent depth 3 exceeds maxDepth 2"}],"isError":true,"id":"{{message:19}}"},"error":{"name":"SubagentDepthError","code":"DEPTH_EXCEEDED"}},"sourceEventSeqs":[14],"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":"DEPTH_REJECTED"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:20}}"},"usage":{"inputTokens":10,"outputTokens":2},"stream":[{"type":"chunk","time":1789625678991,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1789625678991,"index":0,"dt":[],"texts":["DEPTH_REJECTED"]},{"type":"chunk","time":1789625678991,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DEPTH_REJECTED"}}},{"type":"chunk","time":1789625678991,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":2}}},{"type":"chunk","time":1789625678991,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} diff --git a/snapshots/session/subagent-max-tokens-partial/session.1.v4.jsonl b/snapshots/session/subagent-max-tokens-partial/session.1.v4.jsonl index eeba0b0a5e..340ee1a4e4 100644 --- a/snapshots/session/subagent-max-tokens-partial/session.1.v4.jsonl +++ b/snapshots/session/subagent-max-tokens-partial/session.1.v4.jsonl @@ -3,20 +3,19 @@ {"type":"sandbox/mode","data":{"mode":"danger-full-access","source":"delegation"}} {"type":"approval/policy","data":{"policy":"never","source":"delegation"}} {"type":"permission/preset","data":{"preset":"danger-full-access"}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Write the words 'partial one', call todo_write once, then keep going until you are cut off."},{"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":"{{message:9}}"}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Write the words 'partial one', call todo_write once, then keep going until you are cut off."},{"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":"{{session:1}}"},"role":"user","id":"{{message:9}}"}]}} {"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":"{{message:10}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Write the words 'partial one', call todo_write once, then keep going until you are cut off."},{"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":"{{message:9}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", 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":"{{message:11}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Write the words 'partial one', call todo_write once, then keep going until you are cut off."},{"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":"{{session:1}}"},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", 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 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", 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 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":"{{message:11}}"},"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":"Write the words 'partial one',","messageSeqs":[9],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"partial one"},{"type":"tool-call","id":"call_child_1","name":"todo_write","arguments":"{\"todos\": [{\"content\": \"keep going\", \"status\": \"in_progress\"}]}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:12}}"},"usage":{"inputTokens":20,"outputTokens":9},"stream":[{"type":"chunk","time":1789625680223,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1789625680223,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"partial one"}}},{"type":"chunk","time":1789625680223,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}},{"type":"chunk","time":1789625680223,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_child_1","name":"todo_write","arguments":"{\"todos\": [{\"content\": \"keep going\", \"status\": \"in_progress\"}]}"}}},{"type":"chunk","time":1789625680223,"chunk":{"type":"usage","usage":{"inputTokens":20,"outputTokens":9}}},{"type":"chunk","time":1789625680223,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_child_1","name":"todo_write","arguments":"{\"todos\": [{\"content\": \"keep going\", \"status\": \"in_progress\"}]}"}} {"type":"todo/write","data":{"todos":[{"content":"keep going","status":"in_progress"}]}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_child_1"},"toolCallId":"call_child_1","content":[{"type":"text","text":"Updated todo list: 0 pending, 1 in progress, 0 completed."}],"isError":false,"id":"{{message:13}}"}},"sourceEventSeqs":[15],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_child_1"},"toolCallId":"call_child_1","content":[{"type":"text","text":"Updated todo list: 0 pending, 1 in progress, 0 completed."}],"isError":false,"id":"{{message:13}}"}},"sourceEventSeqs":[14],"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":[],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:14}}"},"usage":{"inputTokens":30,"outputTokens":4},"stream":[{"type":"chunk","time":1789625680241,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1789625680241,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_child_2","name":"todo_write","arguments":"{\"todos\": [{\"content\": \"keep going\", \"status\": \"completed\"}]}"}}},{"type":"chunk","time":1789625680241,"chunk":{"type":"usage","usage":{"inputTokens":30,"outputTokens":4}}},{"type":"chunk","time":1789625680241,"chunk":{"type":"finish","reason":{"kind":"max-tokens"}}}]},"surfaceOp":"append"} diff --git a/snapshots/session/subagent-multi/writer.1.expected.jsonl b/snapshots/session/subagent-multi/writer.1.expected.jsonl index dcd07b256c..27b27ce80e 100644 --- a/snapshots/session/subagent-multi/writer.1.expected.jsonl +++ b/snapshots/session/subagent-multi/writer.1.expected.jsonl @@ -3,16 +3,15 @@ {"type":"sandbox/mode","data":{"mode":"danger-full-access","source":"delegation"}} {"type":"approval/policy","data":{"policy":"never","source":"delegation"}} {"type":"permission/preset","data":{"preset":"danger-full-access"}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly the word ALPHA and nothing else."},{"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":"{{message:11}}"}]}} +{"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 the word ALPHA and nothing else."},{"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":"{{session:1}}"},"role":"user","id":"{{message:11}}"}]}} {"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":"{{message:12}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly the word ALPHA and nothing else."},{"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":"{{message:11}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", 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":"{{message:13}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Reply with exactly the word ALPHA and nothing else."},{"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":"{{session:1}}"},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", 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 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", 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 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":"{{message:13}}"},"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 the word","messageSeqs":[9],"source":{"kind":"fallback"}}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to reply with exactly the word \"ALPHA\" and nothing else."},{"type":"text","text":"ALPHA"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:14}}"},"usage":{"inputTokens":49,"outputTokens":23,"cacheReadTokens":2816,"reasoningTokens":19},"stream":[{"type":"chunk","time":1793605862848,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1793605862848,"index":0,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["The"," user"," wants"," me"," to"," reply"," with"," exactly"," the"," word"," \"","AL","P","HA","\""," and"," nothing"," else","."]},{"type":"chunk","time":1793605862848,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1793605862848,"index":1,"dt":[0,0],"texts":["AL","P","HA"]},{"type":"chunk","time":1793605862848,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to reply with exactly the word \"ALPHA\" and nothing else."}}},{"type":"chunk","time":1793605862848,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"ALPHA"}}},{"type":"chunk","time":1793605862848,"chunk":{"type":"usage","usage":{"inputTokens":49,"outputTokens":23,"cacheReadTokens":2816,"reasoningTokens":19}}},{"type":"chunk","time":1793605862848,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to reply with exactly the word \"ALPHA\" and nothing else."},{"type":"text","text":"ALPHA"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:14}}"},"usage":{"inputTokens":49,"outputTokens":23,"cacheReadTokens":2816,"reasoningTokens":19},"stream":[{"type":"chunk","time":1794810165144,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1794810165144,"index":0,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["The"," user"," wants"," me"," to"," reply"," with"," exactly"," the"," word"," \"","AL","P","HA","\""," and"," nothing"," else","."]},{"type":"chunk","time":1794810165144,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1794810165144,"index":1,"dt":[0,0],"texts":["AL","P","HA"]},{"type":"chunk","time":1794810165144,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to reply with exactly the word \"ALPHA\" and nothing else."}}},{"type":"chunk","time":1794810165144,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"ALPHA"}}},{"type":"chunk","time":1794810165144,"chunk":{"type":"usage","usage":{"inputTokens":49,"outputTokens":23,"cacheReadTokens":2816,"reasoningTokens":19}}},{"type":"chunk","time":1794810165144,"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"}}} diff --git a/snapshots/session/subagent-multi/writer.2.expected.jsonl b/snapshots/session/subagent-multi/writer.2.expected.jsonl index e45c4a496e..7783892e2c 100644 --- a/snapshots/session/subagent-multi/writer.2.expected.jsonl +++ b/snapshots/session/subagent-multi/writer.2.expected.jsonl @@ -3,16 +3,15 @@ {"type":"sandbox/mode","data":{"mode":"danger-full-access","source":"delegation"}} {"type":"approval/policy","data":{"policy":"never","source":"delegation"}} {"type":"permission/preset","data":{"preset":"danger-full-access"}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly the word BETA and nothing else."},{"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":"{{message:15}}"}]}} +{"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 the word BETA and nothing else."},{"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":"{{session:1}}"},"role":"user","id":"{{message:15}}"}]}} {"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":"{{message:16}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly the word BETA and nothing else."},{"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":"{{message:15}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", 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":"{{message:17}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Reply with exactly the word BETA and nothing else."},{"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":"{{session:1}}"},"role":"user","id":"{{message:15}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", 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 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", 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 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":"{{message:17}}"},"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 the word","messageSeqs":[9],"source":{"kind":"fallback"}}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to reply with exactly the word \"BETA\" and nothing else."},{"type":"text","text":"BETA"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:18}}"},"usage":{"inputTokens":48,"outputTokens":21,"cacheReadTokens":2816,"reasoningTokens":18},"stream":[{"type":"chunk","time":1793605862915,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1793605862915,"index":0,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["The"," user"," wants"," me"," to"," reply"," with"," exactly"," the"," word"," \"","B","ETA","\""," and"," nothing"," else","."]},{"type":"chunk","time":1793605862915,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1793605862915,"index":1,"dt":[0],"texts":["B","ETA"]},{"type":"chunk","time":1793605862915,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to reply with exactly the word \"BETA\" and nothing else."}}},{"type":"chunk","time":1793605862915,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"BETA"}}},{"type":"chunk","time":1793605862915,"chunk":{"type":"usage","usage":{"inputTokens":48,"outputTokens":21,"cacheReadTokens":2816,"reasoningTokens":18}}},{"type":"chunk","time":1793605862915,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to reply with exactly the word \"BETA\" and nothing else."},{"type":"text","text":"BETA"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:18}}"},"usage":{"inputTokens":48,"outputTokens":21,"cacheReadTokens":2816,"reasoningTokens":18},"stream":[{"type":"chunk","time":1794810165208,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1794810165208,"index":0,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0],"texts":["The"," user"," wants"," me"," to"," reply"," with"," exactly"," the"," word"," \"","B","ETA","\""," and"," nothing"," else","."]},{"type":"chunk","time":1794810165209,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1794810165209,"index":1,"dt":[0],"texts":["B","ETA"]},{"type":"chunk","time":1794810165209,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to reply with exactly the word \"BETA\" and nothing else."}}},{"type":"chunk","time":1794810165209,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"BETA"}}},{"type":"chunk","time":1794810165209,"chunk":{"type":"usage","usage":{"inputTokens":48,"outputTokens":21,"cacheReadTokens":2816,"reasoningTokens":18}}},{"type":"chunk","time":1794810165209,"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"}}} diff --git a/snapshots/session/subagent-no-message-tool/session.1.v4.jsonl b/snapshots/session/subagent-no-message-tool/session.1.v4.jsonl index 4ce53a57be..b4e27fcab9 100644 --- a/snapshots/session/subagent-no-message-tool/session.1.v4.jsonl +++ b/snapshots/session/subagent-no-message-tool/session.1.v4.jsonl @@ -4,21 +4,20 @@ {"type":"sandbox/mode","data":{"mode":"danger-full-access","source":"delegation"}} {"type":"approval/policy","data":{"policy":"never","source":"delegation"}} {"type":"permission/preset","data":{"preset":"danger-full-access"}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly the word CHILD_OK and nothing else."},{"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":"{{message:9}}"}]}} +{"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 the word CHILD_OK and nothing else."},{"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":"{{session:1}}"},"role":"user","id":"{{message:9}}"}]}} {"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":"{{message:10}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly the word CHILD_OK and nothing else."},{"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":"{{message:9}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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\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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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":"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":"{{message:11}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Reply with exactly the word CHILD_OK and nothing else."},{"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":"{{session:1}}"},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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\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 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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":"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 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":"{{message:11}}"},"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 the word","messageSeqs":[10],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_filtered_write","name":"write","arguments":"{\"file_path\":\"filtered-write.txt\",\"content\":\"must not be written\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:12}}"},"usage":{"inputTokens":1,"outputTokens":1},"stream":[{"type":"chunk","time":1791518803420,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791518803420,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_filtered_write","name":"write","arguments":"{\"file_path\":\"filtered-write.txt\",\"content\":\"must not be written\"}"}}},{"type":"chunk","time":1791518803420,"chunk":{"type":"usage","usage":{"inputTokens":1,"outputTokens":1}}},{"type":"chunk","time":1791518803420,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_filtered_write","name":"write","arguments":"{\"file_path\":\"filtered-write.txt\",\"content\":\"must not be written\"}"}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_filtered_write"},"toolCallId":"call_filtered_write","content":[{"type":"text","text":"Error: unknown tool \"write\""}],"isError":true,"id":"{{message:13}}"},"error":{"name":"ToolNotFoundError","code":"UNKNOWN_TOOL"}},"sourceEventSeqs":[16],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_filtered_write"},"toolCallId":"call_filtered_write","content":[{"type":"text","text":"Error: unknown tool \"write\""}],"isError":true,"id":"{{message:13}}"},"error":{"name":"ToolNotFoundError","code":"UNKNOWN_TOOL"}},"sourceEventSeqs":[15],"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":"reasoning","text":"The user wants me to reply with exactly the word CHILD_OK and nothing else."},{"type":"text","text":"CHILD_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:14}}"},"usage":{"inputTokens":48,"outputTokens":21,"cacheReadTokens":2816,"reasoningTokens":17},"stream":[{"type":"chunk","time":1791518803439,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1791518803439,"index":0,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["The"," user"," wants"," me"," to"," reply"," with"," exactly"," the"," word"," CH","ILD","_OK"," and"," nothing"," else","."]},{"type":"chunk","time":1791518803439,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1791518803439,"index":1,"dt":[0,0],"texts":["CH","ILD","_OK"]},{"type":"chunk","time":1791518803439,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to reply with exactly the word CHILD_OK and nothing else."}}},{"type":"chunk","time":1791518803439,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"CHILD_OK"}}},{"type":"chunk","time":1791518803439,"chunk":{"type":"usage","usage":{"inputTokens":48,"outputTokens":21,"cacheReadTokens":2816,"reasoningTokens":17}}},{"type":"chunk","time":1791518803439,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to reply with exactly the word CHILD_OK and nothing else."},{"type":"text","text":"CHILD_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:14}}"},"usage":{"inputTokens":48,"outputTokens":21,"cacheReadTokens":2816,"reasoningTokens":17},"stream":[{"type":"chunk","time":1794555194405,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1794555194405,"index":0,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["The"," user"," wants"," me"," to"," reply"," with"," exactly"," the"," word"," CH","ILD","_OK"," and"," nothing"," else","."]},{"type":"chunk","time":1794555194405,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1794555194405,"index":1,"dt":[0,1],"texts":["CH","ILD","_OK"]},{"type":"chunk","time":1794555194406,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to reply with exactly the word CHILD_OK and nothing else."}}},{"type":"chunk","time":1794555194406,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"CHILD_OK"}}},{"type":"chunk","time":1794555194406,"chunk":{"type":"usage","usage":{"inputTokens":48,"outputTokens":21,"cacheReadTokens":2816,"reasoningTokens":17}}},{"type":"chunk","time":1794555194406,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":2}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/snapshots/session/subagent-parallel/session.1.v4.jsonl b/snapshots/session/subagent-parallel/session.1.v4.jsonl index 7e2d815ada..bbd2e57797 100644 --- a/snapshots/session/subagent-parallel/session.1.v4.jsonl +++ b/snapshots/session/subagent-parallel/session.1.v4.jsonl @@ -3,16 +3,15 @@ {"type":"sandbox/mode","data":{"mode":"danger-full-access","source":"delegation"}} {"type":"approval/policy","data":{"policy":"never","source":"delegation"}} {"type":"permission/preset","data":{"preset":"danger-full-access"}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly the word ALPHA and nothing else."},{"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":"{{message:11}}"}]}} +{"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 the word ALPHA and nothing else."},{"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":"{{session:1}}"},"role":"user","id":"{{message:11}}"}]}} {"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":"{{message:12}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly the word ALPHA and nothing else."},{"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":"{{message:11}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", 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":"{{message:13}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Reply with exactly the word ALPHA and nothing else."},{"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":"{{session:1}}"},"role":"user","id":"{{message:11}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", 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 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", 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 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":"{{message:13}}"},"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 the word","messageSeqs":[9],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"ALPHA"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:14}}"},"stream":[{"type":"chunk","time":1789625766077,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1789625766077,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"ALPHA"}}},{"type":"chunk","time":1789625766077,"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"}}} diff --git a/snapshots/session/subagent-parallel/session.2.v4.jsonl b/snapshots/session/subagent-parallel/session.2.v4.jsonl index 28708982d9..39a43e95b9 100644 --- a/snapshots/session/subagent-parallel/session.2.v4.jsonl +++ b/snapshots/session/subagent-parallel/session.2.v4.jsonl @@ -3,16 +3,15 @@ {"type":"sandbox/mode","data":{"mode":"danger-full-access","source":"delegation"}} {"type":"approval/policy","data":{"policy":"never","source":"delegation"}} {"type":"permission/preset","data":{"preset":"danger-full-access"}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly the word ALPHA and nothing else."},{"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":"{{message:15}}"}]}} +{"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 the word ALPHA and nothing else."},{"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":"{{session:1}}"},"role":"user","id":"{{message:15}}"}]}} {"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":"{{message:16}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly the word ALPHA and nothing else."},{"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":"{{message:15}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", 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":"{{message:17}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Reply with exactly the word ALPHA and nothing else."},{"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":"{{session:1}}"},"role":"user","id":"{{message:15}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", 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 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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-2\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", 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 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":"{{message:17}}"},"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 the word","messageSeqs":[9],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"ALPHA"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:18}}"},"stream":[{"type":"chunk","time":1789625766080,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1789625766080,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"ALPHA"}}},{"type":"chunk","time":1789625766080,"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"}}} diff --git a/snapshots/session/subagent-spawn-in-process/session.1.v4.jsonl b/snapshots/session/subagent-spawn-in-process/session.1.v4.jsonl index e68b196770..5237473f0a 100644 --- a/snapshots/session/subagent-spawn-in-process/session.1.v4.jsonl +++ b/snapshots/session/subagent-spawn-in-process/session.1.v4.jsonl @@ -3,16 +3,15 @@ {"type":"sandbox/mode","data":{"mode":"danger-full-access","source":"delegation"}} {"type":"approval/policy","data":{"policy":"never","source":"delegation"}} {"type":"permission/preset","data":{"preset":"danger-full-access"}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly the word CHILD_OK and nothing else."},{"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":"{{message:9}}"}]}} +{"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 the word CHILD_OK and nothing else."},{"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":"{{session:1}}"},"role":"user","id":"{{message:9}}"}]}} {"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":"{{message:10}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly the word CHILD_OK and nothing else."},{"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":"{{message:9}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", 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":"{{message:11}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Reply with exactly the word CHILD_OK and nothing else."},{"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":"{{session:1}}"},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", 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 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", 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 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":"{{message:11}}"},"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 the word","messageSeqs":[9],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to reply with exactly the word CHILD_OK and nothing else."},{"type":"text","text":"CHILD_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:12}}"},"usage":{"inputTokens":48,"outputTokens":21,"cacheReadTokens":2816,"reasoningTokens":17},"stream":[{"type":"chunk","time":1789625684801,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1789625684801,"index":0,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["The"," user"," wants"," me"," to"," reply"," with"," exactly"," the"," word"," CH","ILD","_OK"," and"," nothing"," else","."]},{"type":"chunk","time":1789625684801,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1789625684801,"index":1,"dt":[0,0],"texts":["CH","ILD","_OK"]},{"type":"chunk","time":1789625684801,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to reply with exactly the word CHILD_OK and nothing else."}}},{"type":"chunk","time":1789625684801,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"CHILD_OK"}}},{"type":"chunk","time":1789625684801,"chunk":{"type":"usage","usage":{"inputTokens":48,"outputTokens":21,"cacheReadTokens":2816,"reasoningTokens":17}}},{"type":"chunk","time":1789625684801,"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"}}} diff --git a/snapshots/session/subagent-structured-parent/session.1.v4.jsonl b/snapshots/session/subagent-structured-parent/session.1.v4.jsonl index 73fd031599..e92fb0019b 100644 --- a/snapshots/session/subagent-structured-parent/session.1.v4.jsonl +++ b/snapshots/session/subagent-structured-parent/session.1.v4.jsonl @@ -3,26 +3,25 @@ {"type":"sandbox/mode","data":{"mode":"danger-full-access","source":"delegation"}} {"type":"approval/policy","data":{"policy":"never","source":"delegation"}} {"type":"permission/preset","data":{"preset":"danger-full-access"}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Submit answer 41 through structured_output."},{"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":"{{message:8}}"}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Submit answer 41 through structured_output."},{"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":"{{session:1}}"},"role":"user","id":"{{message:8}}"}]}} {"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":"{{message:9}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Submit answer 41 through structured_output."},{"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":"{{message:8}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", 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":"{{message:10}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Submit answer 41 through structured_output."},{"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":"{{session:1}}"},"role":"user","id":"{{message:8}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", 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 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", 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 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":"{{message:10}}"},"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":"Submit answer 41 through structured_outp","messageSeqs":[9],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_structured_answer","name":"structured_output","arguments":"{\"answer\":41}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:11}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_structured_answer","name":"structured_output","arguments":"{\"answer\":41}"}}},{"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":"call_structured_answer","name":"structured_output","arguments":"{\"answer\":41}"}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Correction: submit answer 42 instead."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{session:1}}"},"role":"user","id":"{{message:12}}"}]}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_structured_answer"},"toolCallId":"call_structured_answer","content":[{"type":"text","text":"Error: Process pending messages before submitting structured output."}],"isError":true,"id":"{{message:13}}"},"error":{"name":"SubagentError","code":"STRUCTURED_OUTPUT_PENDING_INPUT"}},"sourceEventSeqs":[15],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_structured_answer"},"toolCallId":"call_structured_answer","content":[{"type":"text","text":"Error: Process pending messages before submitting structured output."}],"isError":true,"id":"{{message:13}}"},"error":{"name":"SubagentError","code":"STRUCTURED_OUTPUT_PENDING_INPUT"}},"sourceEventSeqs":[14],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":1,"step":2}} {"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Correction: submit answer 42 instead."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{session:1}}"},"role":"user","id":"{{message:12}}"},"surfaceOp":"append"} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_corrected_answer","name":"structured_output","arguments":"{\"answer\":42}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:14}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_corrected_answer","name":"structured_output","arguments":"{\"answer\":42}"}}},{"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":2,"callId":"call_corrected_answer","name":"structured_output","arguments":"{\"answer\":42}"}} -{"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"call_corrected_answer"},"toolCallId":"call_corrected_answer","content":[{"type":"text","text":"Structured output recorded."}],"isError":false,"id":"{{message:15}}"}},"sourceEventSeqs":[23],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"call_corrected_answer"},"toolCallId":"call_corrected_answer","content":[{"type":"text","text":"Structured output recorded."}],"isError":false,"id":"{{message:15}}"}},"sourceEventSeqs":[22],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":2}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/snapshots/session/subagent-tool-filter/session.1.v4.jsonl b/snapshots/session/subagent-tool-filter/session.1.v4.jsonl index 5bc7d5d835..629adb0cb6 100644 --- a/snapshots/session/subagent-tool-filter/session.1.v4.jsonl +++ b/snapshots/session/subagent-tool-filter/session.1.v4.jsonl @@ -4,19 +4,18 @@ {"type":"sandbox/mode","data":{"mode":"danger-full-access","source":"delegation"}} {"type":"approval/policy","data":{"policy":"never","source":"delegation"}} {"type":"permission/preset","data":{"preset":"danger-full-access"}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly the word CHILD_OK and nothing else."},{"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":"{{message:9}}"}]}} +{"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 the word CHILD_OK and nothing else."},{"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":"{{session:1}}"},"role":"user","id":"{{message:9}}"}]}} {"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":"{{message:10}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly the word CHILD_OK and nothing else."},{"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":"{{message:9}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", 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":"{{message:11}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Reply with exactly the word CHILD_OK and nothing else."},{"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":"{{session:1}}"},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", 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 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", 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 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":"{{message:11}}"},"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 the word","messageSeqs":[10],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_filtered_write","name":"write","arguments":"{\"file_path\":\"filtered-write.txt\",\"content\":\"must not be written\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:12}}"},"usage":{"inputTokens":1,"outputTokens":1},"stream":[{"type":"chunk","time":1791518804347,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791518804347,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_filtered_write","name":"write","arguments":"{\"file_path\":\"filtered-write.txt\",\"content\":\"must not be written\"}"}}},{"type":"chunk","time":1791518804347,"chunk":{"type":"usage","usage":{"inputTokens":1,"outputTokens":1}}},{"type":"chunk","time":1791518804347,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_filtered_write","name":"write","arguments":"{\"file_path\":\"filtered-write.txt\",\"content\":\"must not be written\"}"}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_filtered_write"},"toolCallId":"call_filtered_write","content":[{"type":"text","text":"Error: unknown tool \"write\""}],"isError":true,"id":"{{message:13}}"},"error":{"name":"ToolNotFoundError","code":"UNKNOWN_TOOL"}},"sourceEventSeqs":[16],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_filtered_write"},"toolCallId":"call_filtered_write","content":[{"type":"text","text":"Error: unknown tool \"write\""}],"isError":true,"id":"{{message:13}}"},"error":{"name":"ToolNotFoundError","code":"UNKNOWN_TOOL"}},"sourceEventSeqs":[15],"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":"reasoning","text":"The user wants me to reply with exactly the word CHILD_OK and nothing else."},{"type":"text","text":"CHILD_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:14}}"},"usage":{"inputTokens":48,"outputTokens":21,"cacheReadTokens":2816,"reasoningTokens":17},"stream":[{"type":"chunk","time":1791518804367,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1791518804367,"index":0,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["The"," user"," wants"," me"," to"," reply"," with"," exactly"," the"," word"," CH","ILD","_OK"," and"," nothing"," else","."]},{"type":"chunk","time":1791518804367,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1791518804367,"index":1,"dt":[0,0],"texts":["CH","ILD","_OK"]},{"type":"chunk","time":1791518804367,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to reply with exactly the word CHILD_OK and nothing else."}}},{"type":"chunk","time":1791518804367,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"CHILD_OK"}}},{"type":"chunk","time":1791518804367,"chunk":{"type":"usage","usage":{"inputTokens":48,"outputTokens":21,"cacheReadTokens":2816,"reasoningTokens":17}}},{"type":"chunk","time":1791518804367,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} diff --git a/snapshots/session/team-direct-inbox/session.1.v4.jsonl b/snapshots/session/team-direct-inbox/session.1.v4.jsonl index a69f9c358e..ecdad7625d 100644 --- a/snapshots/session/team-direct-inbox/session.1.v4.jsonl +++ b/snapshots/session/team-direct-inbox/session.1.v4.jsonl @@ -3,22 +3,21 @@ {"type":"sandbox/mode","data":{"mode":"danger-full-access","source":"delegation"}} {"type":"approval/policy","data":{"policy":"never","source":"delegation"}} {"type":"permission/preset","data":{"preset":"danger-full-access"}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Create the empty file team-ready, then wait in Bash until interrupted."},{"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":"{{message:13}}"}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Create the empty file team-ready, then wait in Bash until interrupted."},{"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":"{{session:1}}"},"role":"user","id":"{{message:13}}"}]}} {"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":"{{message:14}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Create the empty file team-ready, then wait in Bash until interrupted."},{"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":"{{message:13}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", message: \"...\" }).\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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", message: \"...\" }).\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":"{{message:15}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Create the empty file team-ready, then wait in Bash until interrupted."},{"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":"{{session:1}}"},"role":"user","id":"{{message:13}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", message: \"...\" }).\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 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", message: \"...\" }).\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 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":"{{message:15}}"},"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":"Create the empty file team-ready,","messageSeqs":[9],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"direct-1","name":"bash","arguments":"{\"command\":\"touch team-ready; while :; do sleep 1; done\",\"description\":\"Signal readiness and wait for interruption\",\"timeoutMs\":60000}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:16}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791450215117,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1791450215117,"index":0,"dt":[],"id":"direct-1","name":"bash","args":["{\"command\":\"touch team-ready; while :; do sleep 1; done\",\"description\":\"Signal readiness and wait for interruption\",\"timeoutMs\":60000}"]},{"type":"chunk","time":1791450215117,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"direct-1","name":"bash","arguments":"{\"command\":\"touch team-ready; while :; do sleep 1; done\",\"description\":\"Signal readiness and wait for interruption\",\"timeoutMs\":60000}"}}},{"type":"chunk","time":1791450215117,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791450215117,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"direct-1","name":"bash","arguments":"{\"command\":\"touch team-ready; while :; do sleep 1; done\",\"description\":\"Signal readiness and wait for interruption\",\"timeoutMs\":60000}"}} -{"type":"job/registered","data":{"jobId":"{{id:2}}","owner":"{{session:2}}","kind":"bash","label":"touch team-ready; while :; do sleep 1; done","startedAt":1791450215128,"toolCall":{"callId":"direct-1","rootCallId":"direct-1"}}} +{"type":"job/registered","data":{"jobId":"{{id:2}}","owner":"{{session:2}}","kind":"bash","label":"touch team-ready; while :; do sleep 1; done","startedAt":1794555210155,"toolCall":{"callId":"direct-1","rootCallId":"direct-1"}}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Review the direct inbox delivery."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{session:1}}"},"role":"user","id":"{{message:17}}"}]}} -{"type":"job/settled","data":{"jobId":"{{id:2}}","owner":"{{session:2}}","kind":"bash","label":"touch team-ready; while :; do sleep 1; done","startedAt":1791450215128,"toolCall":{"callId":"direct-1","rootCallId":"direct-1"},"finishedAt":1791450215194,"status":"killed","cause":"kill","producerReported":true,"detail":"signal: SIGTERM; tool call aborted"}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"direct-1"},"toolCallId":"direct-1","content":[{"type":"text","text":"Error: tool call aborted"}],"isError":true,"id":"{{message:18}}"},"error":{"name":"AbortError","code":"ABORTED"}},"sourceEventSeqs":[15],"surfaceOp":"append"} +{"type":"job/settled","data":{"jobId":"{{id:2}}","owner":"{{session:2}}","kind":"bash","label":"touch team-ready; while :; do sleep 1; done","startedAt":1794555210155,"toolCall":{"callId":"direct-1","rootCallId":"direct-1"},"finishedAt":1794555210295,"status":"killed","cause":"kill","producerReported":true,"detail":"signal: SIGTERM; tool call aborted"}} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"direct-1"},"toolCallId":"direct-1","content":[{"type":"text","text":"Error: tool call aborted"}],"isError":true,"id":"{{message:18}}"},"error":{"name":"AbortError","code":"ABORTED"}},"sourceEventSeqs":[14],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"aborted","reason":{"kind":"parent"}}}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[],"outcome":"canceled"}} diff --git a/snapshots/session/team-task-inbox/session.1.v4.jsonl b/snapshots/session/team-task-inbox/session.1.v4.jsonl index bfcc1347aa..dcf0d9644f 100644 --- a/snapshots/session/team-task-inbox/session.1.v4.jsonl +++ b/snapshots/session/team-task-inbox/session.1.v4.jsonl @@ -3,29 +3,28 @@ {"type":"sandbox/mode","data":{"mode":"danger-full-access","source":"delegation"}} {"type":"approval/policy","data":{"policy":"never","source":"delegation"}} {"type":"permission/preset","data":{"preset":"danger-full-access"}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Create a shared task titled Check memory wake, claim it, complete it, then reply TASK_DONE."},{"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":"{{message:14}}"}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Create a shared task titled Check memory wake, claim it, complete it, then reply TASK_DONE."},{"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":"{{session:1}}"},"role":"user","id":"{{message:14}}"}]}} {"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":"{{message:15}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Create a shared task titled Check memory wake, claim it, complete it, then reply TASK_DONE."},{"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":"{{message:14}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", message: \"...\" }).\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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", message: \"...\" }).\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":"{{message:16}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Create a shared task titled Check memory wake, claim it, complete it, then reply TASK_DONE."},{"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":"{{session:1}}"},"role":"user","id":"{{message:14}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", message: \"...\" }).\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 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", message: \"...\" }).\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 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":"{{message:16}}"},"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":"Create a shared task titled","messageSeqs":[9],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"create-task","name":"team_task_create","arguments":"{\"subject\":\"Check memory wake\",\"description\":\"Complete this task while the root is waiting.\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:17}}"},"stream":[{"type":"chunk","time":1792379633314,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792379633314,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"create-task","name":"team_task_create","arguments":"{\"subject\":\"Check memory wake\",\"description\":\"Complete this task while the root is waiting.\"}"}}},{"type":"chunk","time":1792379633314,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"create-task","name":"team_task_create","arguments":"{\"subject\":\"Check memory wake\",\"description\":\"Complete this task while the root is waiting.\"}"}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"create-task"},"toolCallId":"create-task","content":[{"type":"text","text":"{\"id\":\"task-1\",\"revision\":1,\"subject\":\"Check memory wake\",\"description\":\"Complete this task while the root is waiting.\",\"status\":\"pending\",\"blockedBy\":[],\"writeScopes\":[],\"ready\":true,\"writeScopeWarnings\":[]}"}],"isError":false,"id":"{{message:18}}"}},"sourceEventSeqs":[15],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"create-task"},"toolCallId":"create-task","content":[{"type":"text","text":"{\"id\":\"task-1\",\"revision\":1,\"subject\":\"Check memory wake\",\"description\":\"Complete this task while the root is waiting.\",\"status\":\"pending\",\"blockedBy\":[],\"writeScopes\":[],\"ready\":true,\"writeScopeWarnings\":[]}"}],"isError":false,"id":"{{message:18}}"}},"sourceEventSeqs":[14],"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":"tool-call","id":"claim-task","name":"team_task_update","arguments":"{\"task_id\":\"task-1\",\"expected_revision\":1,\"action\":\"claim\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:19}}"},"stream":[{"type":"chunk","time":1792379633344,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792379633344,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"claim-task","name":"team_task_update","arguments":"{\"task_id\":\"task-1\",\"expected_revision\":1,\"action\":\"claim\"}"}}},{"type":"chunk","time":1792379633344,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"claim-task","name":"team_task_update","arguments":"{\"task_id\":\"task-1\",\"expected_revision\":1,\"action\":\"claim\"}"}} -{"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"claim-task"},"toolCallId":"claim-task","content":[{"type":"text","text":"{\"id\":\"task-1\",\"revision\":2,\"subject\":\"Check memory wake\",\"description\":\"Complete this task while the root is waiting.\",\"status\":\"in_progress\",\"blockedBy\":[],\"writeScopes\":[],\"ready\":false,\"writeScopeWarnings\":[],\"owner\":\"agent-1\"}"}],"isError":false,"id":"{{message:20}}"}},"sourceEventSeqs":[20],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"claim-task"},"toolCallId":"claim-task","content":[{"type":"text","text":"{\"id\":\"task-1\",\"revision\":2,\"subject\":\"Check memory wake\",\"description\":\"Complete this task while the root is waiting.\",\"status\":\"in_progress\",\"blockedBy\":[],\"writeScopes\":[],\"ready\":false,\"writeScopeWarnings\":[],\"owner\":\"agent-1\"}"}],"isError":false,"id":"{{message:20}}"}},"sourceEventSeqs":[19],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":2}} {"type":"step/start","data":{"turn":1,"step":3}} {"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"complete-task","name":"team_task_update","arguments":"{\"task_id\":\"task-1\",\"expected_revision\":2,\"action\":\"complete\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:21}}"},"stream":[{"type":"chunk","time":1792379633370,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792379633370,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"complete-task","name":"team_task_update","arguments":"{\"task_id\":\"task-1\",\"expected_revision\":2,\"action\":\"complete\"}"}}},{"type":"chunk","time":1792379633370,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":3,"callId":"complete-task","name":"team_task_update","arguments":"{\"task_id\":\"task-1\",\"expected_revision\":2,\"action\":\"complete\"}"}} -{"type":"tool/result","data":{"turn":1,"step":3,"message":{"role":"tool","source":{"kind":"tool","callId":"complete-task"},"toolCallId":"complete-task","content":[{"type":"text","text":"{\"id\":\"task-1\",\"revision\":3,\"subject\":\"Check memory wake\",\"description\":\"Complete this task while the root is waiting.\",\"status\":\"completed\",\"blockedBy\":[],\"writeScopes\":[],\"ready\":false,\"writeScopeWarnings\":[],\"owner\":\"agent-1\"}"}],"isError":false,"id":"{{message:22}}"}},"sourceEventSeqs":[25],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":3,"message":{"role":"tool","source":{"kind":"tool","callId":"complete-task"},"toolCallId":"complete-task","content":[{"type":"text","text":"{\"id\":\"task-1\",\"revision\":3,\"subject\":\"Check memory wake\",\"description\":\"Complete this task while the root is waiting.\",\"status\":\"completed\",\"blockedBy\":[],\"writeScopes\":[],\"ready\":false,\"writeScopeWarnings\":[],\"owner\":\"agent-1\"}"}],"isError":false,"id":"{{message:22}}"}},"sourceEventSeqs":[24],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":3}} {"type":"step/start","data":{"turn":1,"step":4}} {"type":"assistant/message","data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"text","text":"TASK_DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:23}}"},"stream":[{"type":"chunk","time":1792379633404,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1792379633405,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"TASK_DONE"}}},{"type":"chunk","time":1792379633405,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} diff --git a/snapshots/session/team-tree-messages/session.1.v4.jsonl b/snapshots/session/team-tree-messages/session.1.v4.jsonl index 69377a0fec..c93884d525 100644 --- a/snapshots/session/team-tree-messages/session.1.v4.jsonl +++ b/snapshots/session/team-tree-messages/session.1.v4.jsonl @@ -3,24 +3,23 @@ {"type":"sandbox/mode","data":{"mode":"danger-full-access","source":"delegation"}} {"type":"approval/policy","data":{"policy":"never","source":"delegation"}} {"type":"permission/preset","data":{"preset":"danger-full-access"}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Use workflow to create a nested reviewer that lists the entire Team, sends the Lead a message, and replies LEAF_READY. Then reply BRANCH_READY."}],"source":{"kind":"user"},"role":"user","id":"{{message:12}}"}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Use workflow to create a nested reviewer that lists the entire Team, sends the Lead a message, and replies LEAF_READY. Then reply BRANCH_READY."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{session:1}}"},"role":"user","id":"{{message:12}}"}]}} {"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":"{{message:13}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Use workflow to create a nested reviewer that lists the entire Team, sends the Lead a message, and replies LEAF_READY. Then reply BRANCH_READY."}],"source":{"kind":"user"},"role":"user","id":"{{message:12}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", message: \"...\" }).\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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", message: \"...\" }).\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":"{{message:14}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Use workflow to create a nested reviewer that lists the entire Team, sends the Lead a message, and replies LEAF_READY. Then reply BRANCH_READY."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{session:1}}"},"role":"user","id":"{{message:12}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", message: \"...\" }).\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 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", message: \"...\" }).\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 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":"{{message:14}}"},"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":"Use workflow to create a","messageSeqs":[9],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"desc-2-1","name":"workflow","arguments":"{\"meta\":{\"description\":\"Create the nested reviewer.\",\"name\":\"leaf\"},\"script\":\"return await agent(\\\"List the entire Team, send the Lead a message, then reply LEAF_READY.\\\");\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:15}}"},"stream":[{"type":"chunk","time":1792144778192,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792144778192,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"desc-2-1","name":"workflow","arguments":"{\"meta\":{\"description\":\"Create the nested reviewer.\",\"name\":\"leaf\"},\"script\":\"return await agent(\\\"List the entire Team, send the Lead a message, then reply LEAF_READY.\\\");\"}"}}},{"type":"chunk","time":1792144778192,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"desc-2-1","name":"workflow","arguments":"{\"meta\":{\"description\":\"Create the nested reviewer.\",\"name\":\"leaf\"},\"script\":\"return await agent(\\\"List the entire Team, send the Lead a message, then reply LEAF_READY.\\\");\"}"}} {"type":"tool-workflow/run-start","data":{"runId":"{{workflow:2}}","name":"leaf"}} -{"type":"subagent/catalog","data":{"version":3,"childId":"{{session:3}}","childCreatedAt":1792144778283,"mode":"continuable","label":"leaf child 1","name":"agent-1"}} +{"type":"subagent/catalog","data":{"version":3,"childId":"{{session:3}}","childCreatedAt":1794555235353,"mode":"continuable","label":"leaf child 1","name":"agent-1"}} {"type":"tool-workflow/agent-start","data":{"runId":"{{workflow:2}}","seq":1,"label":"List the entire Team, send the Lead a message, …","childId":"{{session:3}}"}} {"type":"tool-workflow/agent-end","data":{"runId":"{{workflow:2}}","seq":1,"outcome":"completed"}} {"type":"tool-workflow/run-end","data":{"runId":"{{workflow:2}}","stopReason":"completed"}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"desc-2-1"},"toolCallId":"desc-2-1","content":[{"type":"text","text":"workflow \"leaf\" completed (1 agent).\nReturn value:\n\"LEAF_READY\""}],"isError":false,"id":"{{message:16}}"}},"sourceEventSeqs":[15],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"desc-2-1"},"toolCallId":"desc-2-1","content":[{"type":"text","text":"workflow \"leaf\" completed (1 agent).\nReturn value:\n\"LEAF_READY\""}],"isError":false,"id":"{{message:16}}"}},"sourceEventSeqs":[14],"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":"BRANCH_READY"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:17}}"},"stream":[{"type":"chunk","time":1792144778359,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1792144778359,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"BRANCH_READY"}}},{"type":"chunk","time":1792144778359,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} diff --git a/snapshots/session/team-tree-messages/session.2.v4.jsonl b/snapshots/session/team-tree-messages/session.2.v4.jsonl index 5405c96d4b..ba0827bc35 100644 --- a/snapshots/session/team-tree-messages/session.2.v4.jsonl +++ b/snapshots/session/team-tree-messages/session.2.v4.jsonl @@ -3,24 +3,23 @@ {"type":"sandbox/mode","data":{"mode":"danger-full-access","source":"delegation"}} {"type":"approval/policy","data":{"policy":"never","source":"delegation"}} {"type":"permission/preset","data":{"preset":"danger-full-access"}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"List the entire Team, send the Lead a message, then reply LEAF_READY."}],"source":{"kind":"user"},"role":"user","id":"{{message:18}}"}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Agent agent-1 sent a message: "},{"type":"text","text":"List the entire Team, send the Lead a message, then reply LEAF_READY."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{session:2}}"},"role":"user","id":"{{message:18}}"}]}} {"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":"{{message:19}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"List the entire Team, send the Lead a message, then reply LEAF_READY."}],"source":{"kind":"user"},"role":"user","id":"{{message:18}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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 \"agent-1\".\nYour name is \"agent-1/agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 2, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 2, 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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 \"agent-1\".\nYour name is \"agent-1/agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 2, 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 2, 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":"{{message:20}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Agent agent-1 sent a message: "},{"type":"text","text":"List the entire Team, send the Lead a message, then reply LEAF_READY."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{session:2}}"},"role":"user","id":"{{message:18}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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 \"agent-1\".\nYour name is \"agent-1/agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 2, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 2, 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 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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 \"agent-1\".\nYour name is \"agent-1/agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 2, 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 2, 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 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":"{{message:20}}"},"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":"List the entire Team, send","messageSeqs":[9],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"leaf-list","name":"list_agents","arguments":"{}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:21}}"},"stream":[{"type":"chunk","time":1792222835431,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792222835431,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"leaf-list","name":"list_agents","arguments":"{}"}}},{"type":"chunk","time":1792222835431,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"leaf-list","name":"list_agents","arguments":"{}"}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"leaf-list"},"toolCallId":"leaf-list","content":[{"type":"text","text":"lead [running] — root agent\nagent-1 [running] — branch child 1\nagent-1/agent-1 [running] — leaf child 1"}],"isError":false,"id":"{{message:22}}"}},"sourceEventSeqs":[15],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"leaf-list"},"toolCallId":"leaf-list","content":[{"type":"text","text":"lead [running] — root agent\nagent-1 [running] — branch child 1\nagent-1/agent-1 [running] — leaf child 1"}],"isError":false,"id":"{{message:22}}"}},"sourceEventSeqs":[14],"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":"tool-call","id":"leaf-send","name":"send_message","arguments":"{\"agent\":\"lead\",\"message\":\"The nested reviewer can see and contact the Lead.\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:23}}"},"stream":[{"type":"chunk","time":1792222835461,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792222835461,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"leaf-send","name":"send_message","arguments":"{\"agent\":\"lead\",\"message\":\"The nested reviewer can see and contact the Lead.\"}"}}},{"type":"chunk","time":1792222835461,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"leaf-send","name":"send_message","arguments":"{\"agent\":\"lead\",\"message\":\"The nested reviewer can see and contact the Lead.\"}"}} -{"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"leaf-send"},"toolCallId":"leaf-send","content":[{"type":"text","text":"message delivered to agent lead"}],"isError":false,"id":"{{message:24}}"}},"sourceEventSeqs":[20],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"leaf-send"},"toolCallId":"leaf-send","content":[{"type":"text","text":"message delivered to agent lead"}],"isError":false,"id":"{{message:24}}"}},"sourceEventSeqs":[19],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":2}} {"type":"step/start","data":{"turn":1,"step":3}} {"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"text","text":"LEAF_READY"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:25}}"},"stream":[{"type":"chunk","time":1792222835491,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1792222835491,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"LEAF_READY"}}},{"type":"chunk","time":1792222835491,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} diff --git a/snapshots/session/workflow-run/session.1.v4.jsonl b/snapshots/session/workflow-run/session.1.v4.jsonl index c7a7977247..a135f4fdd1 100644 --- a/snapshots/session/workflow-run/session.1.v4.jsonl +++ b/snapshots/session/workflow-run/session.1.v4.jsonl @@ -3,16 +3,15 @@ {"type":"sandbox/mode","data":{"mode":"danger-full-access","source":"delegation"}} {"type":"approval/policy","data":{"policy":"never","source":"delegation"}} {"type":"permission/preset","data":{"preset":"danger-full-access"}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly the word WF_CHILD_OK and nothing else."}],"source":{"kind":"user"},"role":"user","id":"{{message:7}}"}]}} +{"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 the word WF_CHILD_OK and nothing else."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{session:1}}"},"role":"user","id":"{{message:7}}"}]}} {"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":"{{message:8}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly the word WF_CHILD_OK and nothing else."}],"source":{"kind":"user"},"role":"user","id":"{{message:7}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", 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":"{{message:9}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Reply with exactly the word WF_CHILD_OK and nothing else."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{session:1}}"},"role":"user","id":"{{message:7}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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: \"\", 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 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"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"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: \"\", 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 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":"{{message:9}}"},"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 the word","messageSeqs":[9],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to reply with exactly \"WF_CHILD_OK\" and nothing else."},{"type":"text","text":"WF_CHILD_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:10}}"},"usage":{"inputTokens":17,"outputTokens":23,"cacheReadTokens":3072,"reasoningTokens":18},"stream":[{"type":"chunk","time":1789626021118,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1789626021118,"index":0,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["The"," user"," wants"," me"," to"," reply"," with"," exactly"," \"","WF","_CH","ILD","_OK","\""," and"," nothing"," else","."]},{"type":"chunk","time":1789626021118,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1789626021118,"index":1,"dt":[0,0,0],"texts":["WF","_CH","ILD","_OK"]},{"type":"chunk","time":1789626021118,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to reply with exactly \"WF_CHILD_OK\" and nothing else."}}},{"type":"chunk","time":1789626021118,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"WF_CHILD_OK"}}},{"type":"chunk","time":1789626021118,"chunk":{"type":"usage","usage":{"inputTokens":17,"outputTokens":23,"cacheReadTokens":3072,"reasoningTokens":18}}},{"type":"chunk","time":1789626021118,"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"}}} diff --git a/snapshots/web/creation-recommendations/tool-schemas.expected.json b/snapshots/web/creation-recommendations/tool-schemas.expected.json index 0c320a9767..1432727bf0 100644 --- a/snapshots/web/creation-recommendations/tool-schemas.expected.json +++ b/snapshots/web/creation-recommendations/tool-schemas.expected.json @@ -368,7 +368,7 @@ }, { "name": "plugin_manager", - "description": "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.", + "description": "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.", "parameters": { "type": "object", "properties": { @@ -1361,7 +1361,7 @@ }, { "name": "plugin_manager", - "description": "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.", + "description": "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.", "parameters": { "type": "object", "properties": { diff --git a/snapshots/web/creator-persona/tool-schemas.expected.json b/snapshots/web/creator-persona/tool-schemas.expected.json index d6fdbbb612..e00a0e6138 100644 --- a/snapshots/web/creator-persona/tool-schemas.expected.json +++ b/snapshots/web/creator-persona/tool-schemas.expected.json @@ -340,7 +340,7 @@ }, { "name": "plugin_manager", - "description": "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.", + "description": "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.", "parameters": { "type": "object", "properties": { diff --git a/snapshots/web/deepseek-chat-import/tool-schemas.expected.json b/snapshots/web/deepseek-chat-import/tool-schemas.expected.json index 07278d03f4..3e11c0ab06 100644 --- a/snapshots/web/deepseek-chat-import/tool-schemas.expected.json +++ b/snapshots/web/deepseek-chat-import/tool-schemas.expected.json @@ -368,7 +368,7 @@ }, { "name": "plugin_manager", - "description": "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.", + "description": "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.", "parameters": { "type": "object", "properties": { diff --git a/snapshots/web/fresh-round-trip/tool-schemas.expected.json b/snapshots/web/fresh-round-trip/tool-schemas.expected.json index 07278d03f4..3e11c0ab06 100644 --- a/snapshots/web/fresh-round-trip/tool-schemas.expected.json +++ b/snapshots/web/fresh-round-trip/tool-schemas.expected.json @@ -368,7 +368,7 @@ }, { "name": "plugin_manager", - "description": "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.", + "description": "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.", "parameters": { "type": "object", "properties": { diff --git a/snapshots/web/mention-path-presence/session.v4.jsonl b/snapshots/web/mention-path-presence/session.v4.jsonl new file mode 100644 index 0000000000..21f9760e8d --- /dev/null +++ b/snapshots/web/mention-path-presence/session.v4.jsonl @@ -0,0 +1,19 @@ +{"type":"session","version":4,"id":"{{session:1}}","createdAt":1792123530041,"cwd":"{{cwd}}","isSeeded":false,"delegationDepth":0,"agentPreset":"standard"} +{"type":"permission/preset","data":{"preset":"workspace-write"}} +{"type":"sandbox/mode","data":{"mode":"workspace-write"}} +{"type":"approval/policy","data":{"policy":"ask"}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"@ceshi @随便写点文字 @LICENSE @docs/ mail@host"}],"source":{"kind":"user","rpcId":"{{rpc:1}}","clientTimeZone":"{{clientTimeZone}}"},"role":"user","id":"{{message:1}}"}]}} +{"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":"{{message:2}}"}},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"@ceshi @随便写点文字 @LICENSE @docs/ mail@host"}],"source":{"kind":"user","rpcId":"{{rpc:1}}","clientTimeZone":"{{clientTimeZone}}"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\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 enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\".\n"}],"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 enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `dsh-doc`: Use when a task needs facts about DeepSeek Harness (DSH) itself, such as how a feature, setting, plugin, agent preset, tool, or Cordis API of the running installation works; when the user asks to design, review, build, install, enable, or debug a DSH plugin, bundle, MCP connection, agent preset, plugin icon or detail page, or a DSH tool definition or skill; and when upgrading a plugin or profile to a newer DSH release. Loading it grants no permission to change files or the profile.\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"dsh-doc","description":"Use when a task needs facts about DeepSeek Harness (DSH) itself, such as how a feature, setting, plugin, agent preset, tool, or Cordis API of the running installation works; when the user asks to design, review, build, install, enable, or debug a DSH plugin, bundle, MCP connection, agent preset, plugin icon or detail page, or a DSH tool definition or skill; and when upgrading a plugin or profile to a newer DSH release. Loading it grants no permission to change files or the profile."},{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:5}}"},"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","contextWindow":128000}} +{"type":"session/title","data":{"title":"@ceshi @随便写点文字 @LICENSE @doc","messageSeqs":[8],"source":{"kind":"fallback"}}} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"Reference display checked."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"usage":{"inputTokens":256,"outputTokens":5},"stream":[{"type":"chunk","time":1794890874678,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1794890874690,"index":0,"dt":[],"texts":["Reference display checked."]},{"type":"chunk","time":1794890874702,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Reference display checked."}}},{"type":"chunk","time":1794890874712,"chunk":{"type":"usage","usage":{"inputTokens":256,"outputTokens":5}}},{"type":"chunk","time":1794890874723,"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"}}} diff --git a/snapshots/web/mention-path-presence/snapshot.yml b/snapshots/web/mention-path-presence/snapshot.yml new file mode 100644 index 0000000000..b667a53e7a --- /dev/null +++ b/snapshots/web/mention-path-presence/snapshot.yml @@ -0,0 +1,7 @@ +version: 1 +scenario: mention-path-presence +profile: web +composition: web-default +recording: authored +header: + class: web-default diff --git a/snapshots/web/mention-path-presence/ui.expected.md b/snapshots/web/mention-path-presence/ui.expected.md new file mode 100644 index 0000000000..484fa848b3 --- /dev/null +++ b/snapshots/web/mention-path-presence/ui.expected.md @@ -0,0 +1,29 @@ +- banner: + - navigation "Session hierarchy": "@ceshi @随便写点文字 @LICENSE @doc" + - text: Standard mode + - button "Session panel" + - button "More actions" + - tablist: + - tab "Chat" [selected] + - tab "Trajectory" + - button "More conversation views" +- text: "@ceshi @随便写点文字" +- button "LICENSE" +- text: docs mail@host {{clock}} +- button "Copy" +- status: Completed +- button "Completed in {{duration}}" +- paragraph: Reference display checked. +- button "Copy" +- button "Good response" +- button "Bad response" +- button "Branch into a new conversation" +- text: {{clock}} +- textbox "Message or run a task, / commands, @ files or sessions" +- button "Add files or run commands" +- 'button "Access mode, current: Workspace Write"': Workspace Write +- button "Select model, current DeepSeek-V4-Flash": DeepSeek-V4-Flash +- button "Send message" [disabled] +- button "1 turns 1 steps · {{throughput}} tok/s": 1 turns 1 steps{{throughput}} tok/s +- button "261 tok · Cache hit 0%": 261 tokCache hit 0% +- button "0% of context used": 0% diff --git a/snapshots/web/plugin-recommendations/tool-schemas.expected.json b/snapshots/web/plugin-recommendations/tool-schemas.expected.json index 0c320a9767..1432727bf0 100644 --- a/snapshots/web/plugin-recommendations/tool-schemas.expected.json +++ b/snapshots/web/plugin-recommendations/tool-schemas.expected.json @@ -368,7 +368,7 @@ }, { "name": "plugin_manager", - "description": "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.", + "description": "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.", "parameters": { "type": "object", "properties": { @@ -1361,7 +1361,7 @@ }, { "name": "plugin_manager", - "description": "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.", + "description": "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.", "parameters": { "type": "object", "properties": { diff --git a/snapshots/web/subagent-conversation/fork.expected.md b/snapshots/web/subagent-conversation/fork.expected.md index b525c83c86..3fc7a77729 100644 --- a/snapshots/web/subagent-conversation/fork.expected.md +++ b/snapshots/web/subagent-conversation/fork.expected.md @@ -1,4 +1,4 @@ - tree "Sessions": - treeitem "workspace" [expanded] - - treeitem "Explain event sourcing in one (1) now" [selected] + - treeitem "Now give the same explanation (1) now" [selected] - treeitem "Ask a research subagent to now" diff --git a/snapshots/web/subagent-conversation/sidebar-chat.expected.md b/snapshots/web/subagent-conversation/sidebar-chat.expected.md index f31ceae88e..61500c9fe5 100644 --- a/snapshots/web/subagent-conversation/sidebar-chat.expected.md +++ b/snapshots/web/subagent-conversation/sidebar-chat.expected.md @@ -1,5 +1,6 @@ -- text: Explain event sourcing in one sentence.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. {{clock}} -- button "Copy" +- button "Task message received {{clock}}": + - text: Task message received + - time: {{clock}} - status: Completed - button "Completed in {{duration}}" - paragraph: Event sourcing is a pattern where all changes to an application's state are stored as an immutable, append-only sequence of events, rather than persisting only the current state, enabling full auditability, temporal queries, and event-driven architectures. diff --git a/snapshots/web/subagent-conversation/ui-expanded.expected.md b/snapshots/web/subagent-conversation/ui-expanded.expected.md index f25c6f3136..4e0308e337 100644 --- a/snapshots/web/subagent-conversation/ui-expanded.expected.md +++ b/snapshots/web/subagent-conversation/ui-expanded.expected.md @@ -14,8 +14,9 @@ - navigation "Turn navigation": - button "Jump to turn 1" - button "Jump to turn 2" -- text: Explain event sourcing in one sentence.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. {{clock}} -- button "Copy" +- button "Task message received {{clock}}": + - text: Task message received + - time: {{clock}} - status: Completed - button "Completed in {{duration}}" [expanded] - button "Analysis completed" [expanded] diff --git a/snapshots/web/subagent-conversation/ui.expected.md b/snapshots/web/subagent-conversation/ui.expected.md index e450f6f156..7bb2a4f735 100644 --- a/snapshots/web/subagent-conversation/ui.expected.md +++ b/snapshots/web/subagent-conversation/ui.expected.md @@ -14,8 +14,9 @@ - navigation "Turn navigation": - button "Jump to turn 1" - button "Jump to turn 2" -- text: Explain event sourcing in one sentence.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. {{clock}} -- button "Copy" +- button "Task message received {{clock}}": + - text: Task message received + - time: {{clock}} - status: Completed - button "Completed in {{duration}}" - paragraph: Event sourcing is a pattern where all changes to an application's state are stored as an immutable, append-only sequence of events, rather than persisting only the current state, enabling full auditability, temporal queries, and event-driven architectures. diff --git a/snapshots/web/subagent-fork-schedule/session.1.v4.jsonl b/snapshots/web/subagent-fork-schedule/session.1.v4.jsonl index 12daf4b503..b7cb44e5d3 100644 --- a/snapshots/web/subagent-fork-schedule/session.1.v4.jsonl +++ b/snapshots/web/subagent-fork-schedule/session.1.v4.jsonl @@ -21,12 +21,12 @@ {"type":"subagent/descriptor","data":{"version":3,"mode":"continuable","provider":"fork","label":"Check child reminder refusal","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":"Call schedule_create and schedule_list once each, then schedule_edit with update and delete, then reply CHILD_DONE."}],"source":{"kind":"user"},"role":"user","id":"{{message:7}}"}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Call schedule_create and schedule_list once each, then schedule_edit with update and delete, then reply CHILD_DONE."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{session:1}}"},"role":"user","id":"{{message:7}}"}]}} {"type":"turn/start","data":{"turn":2}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":2,"step":1}} -{"type":"user/message","data":{"content":[{"type":"text","text":"Call schedule_create and schedule_list once each, then schedule_edit with update and delete, then reply CHILD_DONE."}],"source":{"kind":"user"},"role":"user","id":"{{message:7}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session. It replaces earlier versions of this context, including any retained in conversation summaries.\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: \"\", 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\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\".\n"}],"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: \"\", 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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:8}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Call schedule_create and schedule_list once each, then schedule_edit with update and delete, then reply CHILD_DONE."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{session:1}}"},"role":"user","id":"{{message:7}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session. It replaces earlier versions of this context, including any retained in conversation summaries.\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: \"\", 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 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\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\".\n"}],"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: \"\", 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 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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:8}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"resume"}} {"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_schedule_create","name":"schedule_create","arguments":"{\"title\":\"Child reminder\",\"prompt\":\"Check this\",\"rrule\":\"DTSTART:20990101T090000Z\\nRRULE:FREQ=DAILY;COUNT=1\",\"target\":\"this_session\"}"},{"type":"tool-call","id":"call_schedule_list","name":"schedule_list","arguments":"{}"},{"type":"tool-call","id":"call_schedule_update","name":"schedule_edit","arguments":"{\"id\":\"missing-reminder\",\"action\":\"update\",\"prompt\":\"Forbidden child edit\"}"},{"type":"tool-call","id":"call_schedule_delete","name":"schedule_edit","arguments":"{\"id\":\"missing-reminder\",\"action\":\"delete\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:9}}"},"stream":[{"type":"chunk","time":1793795800838,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1793795800838,"index":0,"dt":[],"id":"call_schedule_create","name":"schedule_create","args":["{\"title\":\"Child reminder\",\"prompt\":\"Check this\",\"rrule\":\"DTSTART:20990101T090000Z\\nRRULE:FREQ=DAILY;COUNT=1\",\"target\":\"this_session\"}"]},{"type":"chunk","time":1793795800838,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_schedule_create","name":"schedule_create","arguments":"{\"title\":\"Child reminder\",\"prompt\":\"Check this\",\"rrule\":\"DTSTART:20990101T090000Z\\nRRULE:FREQ=DAILY;COUNT=1\",\"target\":\"this_session\"}"}}},{"type":"chunk","time":1793795800838,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1793795800838,"index":1,"dt":[],"id":"call_schedule_list","name":"schedule_list","args":["{}"]},{"type":"chunk","time":1793795800838,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_schedule_list","name":"schedule_list","arguments":"{}"}}},{"type":"chunk","time":1793795800838,"chunk":{"type":"block-start","index":2,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1793795800838,"index":2,"dt":[],"id":"call_schedule_update","name":"schedule_edit","args":["{\"id\":\"missing-reminder\",\"action\":\"update\",\"prompt\":\"Forbidden child edit\"}"]},{"type":"chunk","time":1793795800838,"chunk":{"type":"block-end","index":2,"block":{"type":"tool-call","id":"call_schedule_update","name":"schedule_edit","arguments":"{\"id\":\"missing-reminder\",\"action\":\"update\",\"prompt\":\"Forbidden child edit\"}"}}},{"type":"chunk","time":1793795800838,"chunk":{"type":"block-start","index":3,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1793795800838,"index":3,"dt":[],"id":"call_schedule_delete","name":"schedule_edit","args":["{\"id\":\"missing-reminder\",\"action\":\"delete\"}"]},{"type":"chunk","time":1793795800838,"chunk":{"type":"block-end","index":3,"block":{"type":"tool-call","id":"call_schedule_delete","name":"schedule_edit","arguments":"{\"id\":\"missing-reminder\",\"action\":\"delete\"}"}}},{"type":"chunk","time":1793795800838,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":2,"step":1,"callId":"call_schedule_create","name":"schedule_create","arguments":"{\"title\":\"Child reminder\",\"prompt\":\"Check this\",\"rrule\":\"DTSTART:20990101T090000Z\\nRRULE:FREQ=DAILY;COUNT=1\",\"target\":\"this_session\"}"}} diff --git a/snapshots/web/subagent-human-message/session.1.v4.jsonl b/snapshots/web/subagent-human-message/session.1.v4.jsonl new file mode 100644 index 0000000000..da0084c428 --- /dev/null +++ b/snapshots/web/subagent-human-message/session.1.v4.jsonl @@ -0,0 +1,43 @@ +{"type":"session","version":4,"id":"{{session:2}}","createdAt":1791518804001,"cwd":"{{cwd}}","parentSession":"{{session:1}}","isSeeded":true,"origin":"subagent","delegationDepth":1,"agentPreset":"standard"} +{"type":"permission/preset","data":{"preset":"workspace-write"}} +{"type":"sandbox/mode","data":{"mode":"workspace-write"}} +{"type":"approval/policy","data":{"policy":"ask"}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Wait for delegated work."}],"source":{"kind":"user","rpcId":"{{rpc:1}}"},"role":"user","id":"{{message:1}}"}]}} +{"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":"{{message:2}}"}},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Wait for delegated work."}],"source":{"kind":"user","rpcId":"{{rpc:1}}"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\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 enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\".\n"}],"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 enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `dsh-doc`: Use when a task needs facts about DeepSeek Harness (DSH) itself, such as how a feature, setting, plugin, agent preset, tool, or Cordis API of the running installation works; when the user asks to design, review, build, install, enable, or debug a DSH plugin, bundle, MCP connection, agent preset, plugin icon or detail page, or a DSH tool definition or skill; and when upgrading a plugin or profile to a newer DSH release. Loading it grants no permission to change files or the profile.\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"dsh-doc","description":"Use when a task needs facts about DeepSeek Harness (DSH) itself, such as how a feature, setting, plugin, agent preset, tool, or Cordis API of the running installation works; when the user asks to design, review, build, install, enable, or debug a DSH plugin, bundle, MCP connection, agent preset, plugin icon or detail page, or a DSH tool definition or skill; and when upgrading a plugin or profile to a newer DSH release. Loading it grants no permission to change files or the profile."},{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Ask the user to clarify otherwise-unqualified dates and times.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Ask the user to clarify otherwise-unqualified dates and times.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:5}}"},"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","contextWindow":128000}} +{"type":"session/title","data":{"title":"Wait for delegated work.","messageSeqs":[8],"source":{"kind":"fallback"}}} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"PARENT_READY"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"usage":{"inputTokens":100,"outputTokens":20},"stream":[{"type":"chunk","time":1794555136092,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1794555136092,"index":0,"dt":[],"texts":["PARENT_READY"]},{"type":"chunk","time":1794555136092,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"PARENT_READY"}}},{"type":"chunk","time":1794555136092,"chunk":{"type":"usage","usage":{"inputTokens":100,"outputTokens":20}}},{"type":"chunk","time":1794555136092,"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"}}} +{"type":"session/end-seed","data":{"inherited":true}} +{"type":"subagent/descriptor","data":{"version":3,"mode":"continuable","provider":"fork","label":"Identify direct human messages","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":"Agent lead sent a message: "},{"type":"text","text":"Report when ready for a question."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{session:1}}"},"role":"user","id":"{{message:9}}"}]}} +{"type":"turn/start","data":{"turn":2}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} +{"type":"step/start","data":{"turn":2,"step":1}} +{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Report when ready for a question."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{session:1}}"},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session. It replaces earlier versions of this context, including any retained in conversation summaries.\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: \"\", 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 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\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\".\n"}],"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: \"\", 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 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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:10}}"},"surfaceOp":"append"} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"resume"}} +{"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"CHILD_READY"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:11}}"},"usage":{"inputTokens":100,"outputTokens":20},"stream":[{"type":"chunk","time":1794555136156,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1794555136156,"index":0,"dt":[],"texts":["CHILD_READY"]},{"type":"chunk","time":1794555136156,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"CHILD_READY"}}},{"type":"chunk","time":1794555136156,"chunk":{"type":"usage","usage":{"inputTokens":100,"outputTokens":20}}},{"type":"chunk","time":1794555136156,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"step/end","data":{"turn":2,"step":1}} +{"type":"turn/end","data":{"turn":2,"reason":{"kind":"completed"}}} +{"type":"session/end-seed","data":{}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"Who sent this message?"}],"source":{"kind":"user","rpcId":"{{rpc:2}}"},"role":"user","id":"{{message:12}}"}]}} +{"type":"turn/start","data":{"turn":3}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} +{"type":"step/start","data":{"turn":3,"step":1}} +{"type":"user/message","data":{"content":[{"type":"text","text":"Who sent this message?"}],"source":{"kind":"user","rpcId":"{{rpc:2}}"},"role":"user","id":"{{message:12}}"},"surfaceOp":"append"} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"resume"}} +{"type":"assistant/message","data":{"turn":3,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"The human user sent this message."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:13}}"},"usage":{"inputTokens":100,"outputTokens":20},"stream":[{"type":"chunk","time":1794555136226,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1794555136226,"index":0,"dt":[],"texts":["The human user sent this message."]},{"type":"chunk","time":1794555136226,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"The human user sent this message."}}},{"type":"chunk","time":1794555136226,"chunk":{"type":"usage","usage":{"inputTokens":100,"outputTokens":20}}},{"type":"chunk","time":1794555136226,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"step/end","data":{"turn":3,"step":1}} +{"type":"turn/end","data":{"turn":3,"reason":{"kind":"completed"}}} diff --git a/snapshots/web/subagent-human-message/session.v4.jsonl b/snapshots/web/subagent-human-message/session.v4.jsonl new file mode 100644 index 0000000000..d283966b56 --- /dev/null +++ b/snapshots/web/subagent-human-message/session.v4.jsonl @@ -0,0 +1,28 @@ +{"type":"session","version":4,"id":"{{session:1}}","createdAt":1791518804000,"cwd":"{{cwd}}","isSeeded":false,"delegationDepth":0,"agentPreset":"standard"} +{"type":"permission/preset","data":{"preset":"workspace-write"}} +{"type":"sandbox/mode","data":{"mode":"workspace-write"}} +{"type":"approval/policy","data":{"policy":"ask"}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Wait for delegated work."}],"source":{"kind":"user","rpcId":"{{rpc:1}}"},"role":"user","id":"{{message:1}}"}]}} +{"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":"{{message:2}}"}},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Wait for delegated work."}],"source":{"kind":"user","rpcId":"{{rpc:1}}"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\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 enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\".\n"}],"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 enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `dsh-doc`: Use when a task needs facts about DeepSeek Harness (DSH) itself, such as how a feature, setting, plugin, agent preset, tool, or Cordis API of the running installation works; when the user asks to design, review, build, install, enable, or debug a DSH plugin, bundle, MCP connection, agent preset, plugin icon or detail page, or a DSH tool definition or skill; and when upgrading a plugin or profile to a newer DSH release. Loading it grants no permission to change files or the profile.\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"dsh-doc","description":"Use when a task needs facts about DeepSeek Harness (DSH) itself, such as how a feature, setting, plugin, agent preset, tool, or Cordis API of the running installation works; when the user asks to design, review, build, install, enable, or debug a DSH plugin, bundle, MCP connection, agent preset, plugin icon or detail page, or a DSH tool definition or skill; and when upgrading a plugin or profile to a newer DSH release. Loading it grants no permission to change files or the profile."},{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Ask the user to clarify otherwise-unqualified dates and times.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Ask the user to clarify otherwise-unqualified dates and times.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:5}}"},"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","contextWindow":128000}} +{"type":"session/title","data":{"title":"Wait for delegated work.","messageSeqs":[8],"source":{"kind":"fallback"}}} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"PARENT_READY"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"usage":{"inputTokens":100,"outputTokens":20},"stream":[{"type":"chunk","time":1794553604143,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1794553604144,"index":0,"dt":[],"texts":["PARENT_READY"]},{"type":"chunk","time":1794553604144,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"PARENT_READY"}}},{"type":"chunk","time":1794553604144,"chunk":{"type":"usage","usage":{"inputTokens":100,"outputTokens":20}}},{"type":"chunk","time":1794553604144,"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"}}} +{"type":"subagent/catalog","data":{"version":3,"childId":"{{session:2}}","childCreatedAt":1794553604147,"mode":"continuable","label":"Identify direct human messages","name":"agent-1"}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Background subagent agent-1 finished and will do no further work unless you send it more."},{"type":"text","text":"Its closing message:"},{"type":"text","text":"The human user sent this message."}],"source":{"kind":"subagent-settled","form":"notice","summary":"Background subagent agent-1 finished and will do no further work unless you send it more.","stopReason":"completed","senderSessionId":"{{session:2}}"},"role":"user","id":"{{message:7}}"}]}} +{"type":"turn/start","data":{"turn":2}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} +{"type":"step/start","data":{"turn":2,"step":1}} +{"type":"user/message","data":{"content":[{"type":"text","text":"Background subagent agent-1 finished and will do no further work unless you send it more."},{"type":"text","text":"Its closing message:"},{"type":"text","text":"The human user sent this message."}],"source":{"kind":"subagent-settled","form":"notice","summary":"Background subagent agent-1 finished and will do no further work unless you send it more.","stopReason":"completed","senderSessionId":"{{session:2}}"},"role":"user","id":"{{message:7}}"},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"PARENT_ACKNOWLEDGED"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:8}}"},"usage":{"inputTokens":100,"outputTokens":20},"stream":[{"type":"chunk","time":1794553604277,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1794553604277,"index":0,"dt":[],"texts":["PARENT_ACKNOWLEDGED"]},{"type":"chunk","time":1794553604277,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"PARENT_ACKNOWLEDGED"}}},{"type":"chunk","time":1794553604277,"chunk":{"type":"usage","usage":{"inputTokens":100,"outputTokens":20}}},{"type":"chunk","time":1794553604277,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"step/end","data":{"turn":2,"step":1}} +{"type":"turn/end","data":{"turn":2,"reason":{"kind":"completed"}}} diff --git a/snapshots/web/subagent-human-message/snapshot.yml b/snapshots/web/subagent-human-message/snapshot.yml new file mode 100644 index 0000000000..8b1d0064c0 --- /dev/null +++ b/snapshots/web/subagent-human-message/snapshot.yml @@ -0,0 +1,7 @@ +version: 1 +scenario: subagent-human-message +profile: web +composition: web-default +recording: authored +header: + class: web-default diff --git a/snapshots/web/subagent-interrupt/image-queue.expected.md b/snapshots/web/subagent-interrupt/image-queue.expected.md index bd9f9fb6e8..bd92463899 100644 --- a/snapshots/web/subagent-interrupt/image-queue.expected.md +++ b/snapshots/web/subagent-interrupt/image-queue.expected.md @@ -14,8 +14,9 @@ - navigation "Turn navigation": - button "Jump to turn 1" - button "Jump to turn 2" -- text: Explain event sourcing in one sentence.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. {{clock}} -- button "Copy" +- button "Task message received {{clock}}": + - text: Task message received + - time: {{clock}} - status: Stopped - button "Stopped" [disabled] [expanded] - button "Injected context" diff --git a/snapshots/web/subagent-interrupt/offline-composer.expected.md b/snapshots/web/subagent-interrupt/offline-composer.expected.md index 749a55388c..f0be856185 100644 --- a/snapshots/web/subagent-interrupt/offline-composer.expected.md +++ b/snapshots/web/subagent-interrupt/offline-composer.expected.md @@ -11,8 +11,9 @@ - tab "Chat" [selected] - tab "Trajectory" - button "More conversation views" -- text: Explain event sourcing in one sentence.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. {{clock}} -- button "Copy" +- button "Task message received {{clock}}": + - text: Task message received + - time: {{clock}} - button "Context injection runtime-context" - button "Context injection skill-catalog" - button "Context injection time-context" diff --git a/tsconfig.base.json b/tsconfig.base.json index 7ede9fbc5c..25774a0a52 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -310,8 +310,14 @@ "@deepseek-ai/dsh-client-file-upload/types": ["./packages/client/file-upload/src/types.ts"], "@deepseek-ai/dsh-api-remotes": ["./packages/api/remotes/src"], "@deepseek-ai/dsh-api-remotes/client": ["./packages/api/remotes/src/client/index.ts"], + "@deepseek-ai/dsh-client-config": ["./packages/client/config/src"], + "@deepseek-ai/dsh-client-config/client": ["./packages/client/config/src/client"], + "@deepseek-ai/dsh-client-config/types": ["./packages/client/config/src/types.ts"], "@deepseek-ai/dsh-client-hmr": ["./packages/client/hmr/src"], + "@deepseek-ai/dsh-client-hmr/client": ["./packages/client/hmr/src/client"], + "@deepseek-ai/dsh-client-hmr/types": ["./packages/client/hmr/src/types.ts"], "@deepseek-ai/dsh-client-modules": ["./packages/client/modules/src"], + "@deepseek-ai/dsh-client-modules/types": ["./packages/client/modules/src/types.ts"], "@deepseek-ai/dsh-cordis-client-runner": ["./packages/extensions/cordis-client-runner/src"], "@deepseek-ai/dsh-cordis-client-runner/client": ["./packages/extensions/cordis-client-runner/src/client"], "@deepseek-ai/dsh-client-ui-cordis": ["./packages/extensions/ui-cordis/src"], @@ -559,6 +565,7 @@ "@deepseek-ai/dsh-session-log-export": ["./packages/session-query/session-log-export/src"], "@deepseek-ai/dsh-session-persistence": ["./packages/session/session-persistence/src"], "@deepseek-ai/dsh-session-persistence-jsonl": ["./packages/session/session-persistence-jsonl/src"], + "@deepseek-ai/dsh-session-persistence-sqlite": ["./packages/session/session-persistence-sqlite/src"], "@deepseek-ai/dsh-session-projection": ["./packages/session/session-projection/src"], "@deepseek-ai/dsh-session-projection-cache": ["./packages/session/session-projection-cache/src"], "@deepseek-ai/dsh-session-query": ["./packages/session-query/session-query/src"], diff --git a/tsconfig.client.json b/tsconfig.client.json index e9970cfac2..23e80ae3c6 100644 --- a/tsconfig.client.json +++ b/tsconfig.client.json @@ -96,7 +96,8 @@ { "path": "./packages/experimental/liveshare/tsconfig.client.json" }, { "path": "./packages/experimental/session-inspector" }, { "path": "./packages/experimental/client-ui-forge/tsconfig.client.json" }, - { "path": "./packages/client/hmr" }, + { "path": "./packages/client/config" }, + { "path": "./packages/client/hmr/tsconfig.client.json" }, { "path": "./packages/client/connection/tsconfig.client.json" }, { "path": "./packages/client/file-upload/tsconfig.client.json" }, { "path": "./packages/typert/registry" }, diff --git a/tsconfig.host.json b/tsconfig.host.json index 84205c7074..1f51b6ee93 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -119,6 +119,7 @@ "apps/web/tests/plugin-install-github.e2e.ts", "apps/web/tests/plugin-install-silent-failure.e2e.ts", "apps/web/tests/client-plugin-live.e2e.ts", + "apps/web/tests/client-config-sync.e2e.ts", "apps/web/tests/icon-skin.e2e.ts", "apps/web/tests/draft-initialization.e2e.ts", "apps/web/tests/settings-chrome.e2e.ts", @@ -190,6 +191,7 @@ "apps/web/tests/markdown-file-links.e2e.ts", "apps/web/tests/user-text-secret-mask.e2e.ts", "apps/web/tests/reference-composer.e2e.ts", + "apps/web/tests/mention-path-presence.e2e.ts", "apps/web/tests/markdown-wide-table.e2e.ts", "apps/web/tests/thinking-markdown.e2e.ts", "apps/web/tests/math-rendering.e2e.ts", @@ -373,6 +375,7 @@ { "path": "./packages/util/home-paths" }, { "path": "./packages/client/ui-plugin-manager/tsconfig.host.json" }, { "path": "./packages/client/ui-trajectory/tsconfig.host.json" }, + { "path": "./packages/client/hmr/tsconfig.host.json" }, { "path": "./packages/client/ui-session-status/tsconfig.host.json" }, { "path": "./packages/util/time" }, { "path": "./packages/util/timeout" }, @@ -415,6 +418,7 @@ { "path": "./packages/session/session-checkpoint-policy" }, { "path": "./packages/session/session-log-deepseek" }, { "path": "./packages/session/session-persistence-jsonl" }, + { "path": "./packages/session/session-persistence-sqlite" }, { "path": "./packages/session/session-projection" }, { "path": "./packages/session/session-projection-cache" }, { "path": "./packages/session/session-stats" }, diff --git a/vitest.config.ts b/vitest.config.ts index de51c1d2cc..2925690a66 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -106,6 +106,7 @@ const windowsRunnerCoverageExclusions = process.platform === 'win32' // win32.spec's injected bindings and exercised natively by every // Windows suite through the real backend. 'packages/session/session-persistence-jsonl/src/lease.ts', + 'packages/session/session-persistence-sqlite/src/lease.ts', // The macOS provider transport uses Unix sockets; POSIX lanes cover its real socket lifecycle. 'packages/experimental/cua-macos/src/shared-native.ts', // The GitHub CLI runner's suite stands in for `gh` with POSIX shell @@ -188,12 +189,16 @@ const claudeCodeTestingAliases = { 'claude-code': fileURLToPath(new URL('./packages/experimental/claude-code-mods/tests/support/claude-code.ts', import.meta.url)), } -// The LiveShare client entry statically imports its generated `./remote` contribution, which exists +// These client entries statically import their generated `./remote` contribution, which exists // only in built `lib/` output. On a clean checkout Vite resolves that import while transforming the // entry, before `vi.mock` can answer it, so the jsdom assembly suites need a resolvable stand-in. const liveshareRemoteBuild = fileURLToPath(new URL('./packages/experimental/liveshare/lib/typert.remote-client.js', import.meta.url)) const chatImportRemoteBuild = fileURLToPath(new URL('./packages/experimental/deepseek-chat-import/lib/typert.remote-client.js', import.meta.url)) +const hmrRemoteBuild = fileURLToPath(new URL('./packages/client/hmr/lib/typert.remote-client.js', import.meta.url)) const generatedRemoteAliases = { + ...existsSync(hmrRemoteBuild) ? {} : { + '@deepseek-ai/dsh-client-hmr/remote': fileURLToPath(new URL('./packages/client/hmr/tests/generated-remote-stub.ts', import.meta.url)), + }, ...existsSync(liveshareRemoteBuild) ? {} : { '@deepseek-ai/dsh-experimental-liveshare/remote': fileURLToPath(new URL('./packages/experimental/liveshare/tests/generated-remote-stub.ts', import.meta.url)), },