From a8f3badfeef6470aabfd8b43615fafe9c3bd4155 Mon Sep 17 00:00:00 2001 From: gengruilin Date: Fri, 6 Nov 2026 19:21:03 +0800 Subject: [PATCH 01/31] feat(connector-account): add one Host registry and Plugins page surfaces for connector accounts `@deepseek-ai/dsh-client-ui-connector-account` provides `ctx.connectorAccounts`, where CLI app plugins and MCP connectors register an account with its source, page operations, copy, and Host-side presentation, and the `connectorAccounts` Remote (`watch`, `start`, `cancel`). The browser half follows every account through one stream and renders each bundle's section, title tag, activation prompt, confirmation, and notice from the Host display; it opens authorization pages and reports notices only for the operations this browser started. `dsh-api-remotes` mounts the generated Remote, `dsh-web-app` loads the package, LiveShare classifies the three endpoints as owner-only, and the client test runtime answers `connectorAccounts/watch` with no accounts. --- ...11-06-connector-account-registry.i18n.yaml | 19 + .../2026-11-06-connector-account-registry.md | 42 +++ ...026-11-06-connector-account-registry.zh.md | 42 +++ docs/capability-seams.i18n.yaml | 4 +- docs/capability-seams.md | 4 + docs/capability-seams.zh.md | 4 + docs/config-catalog.md | 1 + docs/config-catalog.zh.md | 1 + docs/module-graph.md | 2 + docs/module-graph.zh.md | 2 + docs/subsystems/boot.md | 44 +++ docs/subsystems/boot.zh.md | 44 +++ packages/api/remotes/README.i18n.yaml | 4 +- packages/api/remotes/README.md | 2 +- packages/api/remotes/README.zh.md | 2 +- packages/api/remotes/package.json | 1 + packages/api/remotes/src/client/index.ts | 3 + packages/bundle/web-app/cordis.patch.yml | 5 + packages/bundle/web-app/package.json | 1 + packages/client/README.i18n.yaml | 4 +- packages/client/README.md | 1 + packages/client/README.zh.md | 1 + .../ui-connector-account/README.i18n.yaml | 49 +++ .../client/ui-connector-account/README.md | 138 +++++++ .../client/ui-connector-account/README.zh.md | 138 +++++++ .../ui-connector-account/locale/de.json | 6 + .../ui-connector-account/locale/en.json | 6 + .../ui-connector-account/locale/es.json | 6 + .../ui-connector-account/locale/fr.json | 6 + .../ui-connector-account/locale/ja.json | 6 + .../ui-connector-account/locale/pt.json | 6 + .../ui-connector-account/locale/ru.json | 6 + .../ui-connector-account/locale/zh.json | 6 + .../client/ui-connector-account/package.json | 96 +++++ .../src/client/ConnectorAccount.module.css | 51 +++ .../src/client/components.tsx | 337 ++++++++++++++++++ .../ui-connector-account/src/client/index.ts | 90 +++++ .../src/client/locales.ts | 118 ++++++ .../ui-connector-account/src/client/state.ts | 157 ++++++++ .../ui-connector-account/src/client/types.ts | 50 +++ .../ui-connector-account/src/css-modules.d.ts | 6 + .../client/ui-connector-account/src/index.ts | 163 +++++++++ .../client/ui-connector-account/src/types.ts | 164 +++++++++ .../tests/apply.client.spec.ts | 156 ++++++++ .../tests/components.client.spec.tsx | 264 ++++++++++++++ .../tests/registry.host.spec.ts | 166 +++++++++ .../tests/state.client.spec.ts | 194 ++++++++++ .../ui-connector-account/tsconfig.client.json | 57 +++ .../ui-connector-account/tsconfig.host.json | 26 ++ .../client/ui-connector-account/tsconfig.json | 11 + .../ui-connector-account/tsdown.config.ts | 3 + .../liveshare/src/endpoint-classification.ts | 3 + .../src/client/slot-catalog.ts | 7 +- .../extensions/tool-cordis/src/api-catalog.ts | 110 ++++++ .../skills/dsh-doc/references/packages.md | 1 + .../src/assembly/remote-default-responses.ts | 2 + pnpm-lock.yaml | 67 ++++ scripts/gen-cordis-catalog.ts | 5 + scripts/gen-doc-graphs.ts | 7 + .../verify-package-readme-model-experience.ts | 1 + tsconfig.base.json | 2 + tsconfig.client.json | 1 + tsconfig.host.json | 1 + 63 files changed, 2913 insertions(+), 9 deletions(-) create mode 100644 .agents/notes/implemented/architecture/2026-11-06-connector-account-registry.i18n.yaml create mode 100644 .agents/notes/implemented/architecture/2026-11-06-connector-account-registry.md create mode 100644 .agents/notes/implemented/architecture/2026-11-06-connector-account-registry.zh.md create mode 100644 packages/client/ui-connector-account/README.i18n.yaml create mode 100644 packages/client/ui-connector-account/README.md create mode 100644 packages/client/ui-connector-account/README.zh.md create mode 100644 packages/client/ui-connector-account/locale/de.json create mode 100644 packages/client/ui-connector-account/locale/en.json create mode 100644 packages/client/ui-connector-account/locale/es.json create mode 100644 packages/client/ui-connector-account/locale/fr.json create mode 100644 packages/client/ui-connector-account/locale/ja.json create mode 100644 packages/client/ui-connector-account/locale/pt.json create mode 100644 packages/client/ui-connector-account/locale/ru.json create mode 100644 packages/client/ui-connector-account/locale/zh.json create mode 100644 packages/client/ui-connector-account/package.json create mode 100644 packages/client/ui-connector-account/src/client/ConnectorAccount.module.css create mode 100644 packages/client/ui-connector-account/src/client/components.tsx create mode 100644 packages/client/ui-connector-account/src/client/index.ts create mode 100644 packages/client/ui-connector-account/src/client/locales.ts create mode 100644 packages/client/ui-connector-account/src/client/state.ts create mode 100644 packages/client/ui-connector-account/src/client/types.ts create mode 100644 packages/client/ui-connector-account/src/css-modules.d.ts create mode 100644 packages/client/ui-connector-account/src/index.ts create mode 100644 packages/client/ui-connector-account/src/types.ts create mode 100644 packages/client/ui-connector-account/tests/apply.client.spec.ts create mode 100644 packages/client/ui-connector-account/tests/components.client.spec.tsx create mode 100644 packages/client/ui-connector-account/tests/registry.host.spec.ts create mode 100644 packages/client/ui-connector-account/tests/state.client.spec.ts create mode 100644 packages/client/ui-connector-account/tsconfig.client.json create mode 100644 packages/client/ui-connector-account/tsconfig.host.json create mode 100644 packages/client/ui-connector-account/tsconfig.json create mode 100644 packages/client/ui-connector-account/tsdown.config.ts diff --git a/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.i18n.yaml new file mode 100644 index 0000000000..121a9d669b --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-11-06-connector-account-registry.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-06-connector-account-registry.md +/agent-note-one-host-registry-and-one-browser-half-for-connector-accounts: + en: 3950421fb526f6b7 + zh: 47c5f6cc4b735058 +/agent-note-one-host-registry-and-one-browser-half-for-connector-accounts/problem: + en: 2a7b59cd509a0b9a + zh: 38130ce17829342d +/agent-note-one-host-registry-and-one-browser-half-for-connector-accounts/decision: + en: d96b43106a1ba837 + zh: 97bc8f9436ec07d0 +/agent-note-one-host-registry-and-one-browser-half-for-connector-accounts/alternatives-considered: + en: ee0aa3f9ea40ef15 + zh: fded69a6dcc8ca87 +/agent-note-one-host-registry-and-one-browser-half-for-connector-accounts/consequences: + en: 5228f32becfbdec3 + zh: 013f1073e70d46f7 diff --git a/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.md b/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.md new file mode 100644 index 0000000000..93138b065e --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.md @@ -0,0 +1,42 @@ +# Agent Note: One Host registry and one browser half for connector accounts + +Status: implemented + +English | [中文](2026-11-06-connector-account-registry.zh.md) + +## Problem + +Connector plugins show an account section on the Plugins page. CLI app plugins keep the account in their vendor CLI; MCP connectors keep an OAuth grant through the MCP manager. Both kinds need the same surfaces: a bundle's section, title tag, and activation prompt, a confirmation before an action that changes the account outside DSH, and a notice in the browser that started the operation. A client plugin cannot share runtime code with another feature plugin ([packages/client/AGENTS.md](../../../../packages/client/AGENTS.md) rule 3), so one browser half per connector kind duplicates the same code and lets the copies drift. When the browser decides an account's state or relays an identifier from one Remote to another, the Host can no longer run the flow without the browser. + +## Decision + +[`@deepseek-ai/dsh-client-ui-connector-account`](../../../../packages/client/ui-connector-account/README.md) provides one Host registry, `ctx.connectorAccounts`, one `connectorAccounts` Remote, and one browser half for every connector kind. + +| Part | Contract | +|---|---| +| Registration | `register({ key, packageName?, source, operations, copy, present })` returns the disposer that withdraws the account | +| Key | Unique among registered accounts and independent of the package, so an account that no bundle owns, such as a server configured in Settings, registers too | +| Package | Decides which bundle page carries the section and tag; a package carries at most one account | +| Source | The registrant's account: `snapshot`, `observe`, `refresh`, `start`, and `cancel` | +| Display | `present(view)` on the Host gives the phase, status text, title tag, buttons and their commands, confirmations, failure, and the operation the activation prompt starts | +| Remote | `watch`, plus `start(key, operation)` and `cancel(key, id)`, which route by key to the account's source | + +The Host decides everything except opening the authorization page. The browser never learns how an account connects: it receives only the display, the operation in progress with its authorization page, and the latest result with its success text. The browser half keeps only what belongs to one browser: the operations it started, so their authorization pages open and their success is reported only there; the latest notice; and whether its stream is delivering. Buttons call `start` and `cancel` on the Remote themselves, and each surface keeps its own pending state. + +The page registers one title tag entry and one notice entry. It also registers a section and an activation prompt for each account that names a package, because those two slots are keyed by package. + +## Alternatives considered + +**Two registries behind one browser half.** Rejected: the browser would follow both Remotes and choose which one each button calls, which relays between Host services again, and the two Host registries would hold the same code. + +**One browser half per connector kind.** Rejected: client plugins cannot import each other's values, so the shared surfaces would be written twice and diverge. + +**Share the browser half through `PLATFORM_MODULES` or a browser-side service.** Rejected: the module table is reserved for shell-seeded and static infrastructure libraries, and a browser-side service would keep the registrations in the browser, which only repeat what the Host knows. + +**Let the browser derive an account's phase and actions from the registrant's raw state.** Rejected: the rules for which actions apply would live where the Host cannot test or run them, and the browser would need the registrant's own Remote. + +## Consequences + +The registry and browser half exist once. A new connector kind writes a source and `present` on the Host and needs no browser code. The account rules live beside the services that own them, and the Host can run every operation without a browser. + +Registrants map their account states onto five phases (checking, connecting, connected, disconnected, unavailable); a state outside them shows through its status text and detail. The Web and Desktop compositions load the registry whether or not a connector plugin is installed. An authorization page that opens after the start call answers can be blocked by the browser; the section's open button shows it again. diff --git a/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.zh.md b/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.zh.md new file mode 100644 index 0000000000..e2c7a56b41 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.zh.md @@ -0,0 +1,42 @@ +# Agent Note:连接器账号使用一个 Host 注册表和一个浏览器一半 + +Status: implemented + +[English](2026-11-06-connector-account-registry.md) | 中文 + +## 问题 + +连接器插件会在插件页显示账号区块。CLI 应用插件的账号保存在厂商 CLI 中;MCP 连接器通过 MCP 管理器保存 OAuth 授权。两类插件需要同样的界面:插件包的区块、标题旁标签和开启引导,在会改变 DSH 之外账号状态的操作前确认,以及只在发起操作的浏览器中显示的提示。客户端插件不能与其他功能插件共享运行时代码([packages/client/AGENTS.md](../../../../packages/client/AGENTS.md) 第 3 条),因此每类连接器各有一个浏览器一半,就会把同样的代码写两遍,副本还会逐渐不一致。如果由浏览器决定账号状态,或在两个 Remote 之间转发标识,Host 就无法在没有浏览器的情况下完成流程。 + +## 决定 + +[`@deepseek-ai/dsh-client-ui-connector-account`](../../../../packages/client/ui-connector-account/README.zh.md) 为所有连接器类型提供一个 Host 注册表 `ctx.connectorAccounts`、一个 `connectorAccounts` Remote 和一个浏览器一半。 + +| 部分 | 约定 | +|---|---| +| 注册 | `register({ key, packageName?, source, operations, copy, present })` 返回撤下账号的销毁函数 | +| 键 | 在已注册账号中唯一,且与包无关,因此没有插件包承载的账号(如在 Settings 中配置的服务器)也能注册 | +| 包 | 决定由哪个插件包页面承载区块和标签;一个包最多承载一个账号 | +| 来源 | 注册方的账号:`snapshot`、`observe`、`refresh`、`start` 和 `cancel` | +| 展示 | Host 上的 `present(view)` 给出阶段、状态文字、标题旁标签、按钮及其命令、确认、失败信息,以及开启引导启动的操作 | +| Remote | `watch`,以及按键路由到账号来源的 `start(key, operation)` 和 `cancel(key, id)` | + +除了打开授权页,其余都由 Host 决定。浏览器不知道账号如何连接:它只收到展示内容、进行中的操作及其授权页,以及带成功文本的最新结果。浏览器一半只保存属于本浏览器的东西:它发起的操作(授权页只在这里打开,成功只在这里报告)、最新提示,以及它的流是否在推送。按钮自己调用 Remote 的 `start` 和 `cancel`,每个界面自己保存未完成状态。 + +页面只注册一个标题旁标签条目和一个提示条目;对每个带包名的账号,再注册一个区块和一个开启引导,因为这两个插槽以包为键。 + +## 考虑过的替代方案 + +**一个浏览器一半背后有两个注册表。** 否决:浏览器要同时跟随两个 Remote,并为每个按钮选择调用哪一个,这又是在 Host 服务之间转发;两个 Host 注册表的代码也会相同。 + +**每类连接器各有一个浏览器一半。** 否决:客户端插件不能导入彼此的值,共用界面就要写两遍,并逐渐不一致。 + +**通过 `PLATFORM_MODULES` 或浏览器端服务共享浏览器一半。** 否决:模块表只留给由 shell 预置的基础设施和静态库;浏览器端服务会把注册留在浏览器中,而这些注册只是重复 Host 已知的信息。 + +**由浏览器根据注册方的原始状态推算账号阶段和操作。** 否决:哪些操作可用的规则会放在 Host 无法测试和执行的地方,浏览器还需要注册方自己的 Remote。 + +## 后果 + +注册表和浏览器一半只有一份。新的连接器类型只需在 Host 上编写来源和 `present`,不需要浏览器代码。账号规则与拥有它们的服务在一起,Host 不依赖浏览器就能执行每个操作。 + +注册方需要把账号状态映射到五个阶段(检查中、连接中、已连接、未连接、不可用);超出这些阶段的状态通过状态文字和说明表达。无论是否安装了连接器插件,Web 与桌面端组合都会加载注册表。启动调用返回后才打开的授权页可能被浏览器拦截;区块中的打开按钮可以再次打开它。 diff --git a/docs/capability-seams.i18n.yaml b/docs/capability-seams.i18n.yaml index 77f025f1e9..38090bd827 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: b76743a3ff14d2f4 - zh: 82431aa3ded14a89 + en: b3be76b595765ee3 + zh: 85de5f625a7a15a6 diff --git a/docs/capability-seams.md b/docs/capability-seams.md index 145a4f5317..b4fcad0d21 100644 --- a/docs/capability-seams.md +++ b/docs/capability-seams.md @@ -28,6 +28,8 @@ flowchart LR pkg_plugin_manager["plugin-manager"] svc_pluginManager["ctx.pluginManager
Current-profile plugin and bundle management"] pkg_ui_settings_plugin_inventory["ui-settings-plugin-inventory"] + pkg_client_ui_connector_account["client-ui-connector-account"] + svc_connectorAccounts["ctx.connectorAccounts
Connector accounts on the Plugins page"] pkg_plugin_market["plugin-market"] svc_pluginMarket["ctx.pluginMarket
Plugin market index reader"] pkg_client_ui_plugin_market["client-ui-plugin-market"] @@ -344,6 +346,7 @@ flowchart LR pkg_client_file_upload --> svc_fileUploads pkg_client_modules --> svc_clientModules pkg_client_product_analytics --> svc_productAnalytics + pkg_client_ui_connector_account --> svc_connectorAccounts pkg_client_ui_plugin_manager --> svc_pluginRegistryProbe pkg_command_feedback --> svc_sessionFeedback pkg_commands --> svc_commands @@ -659,6 +662,7 @@ flowchart LR | `ctx.hmr` | `core` | [`hmr`](../packages/boot/hmr) | - | [`app-boot`](../packages/boot/app-boot) | - | Owns module and exact configuration watchers; application mutations share its queue and automatic reloads await the application file lock. | | `ctx.pluginRegistryProbe` | `core` | [`client-ui-plugin-manager`](../packages/client/ui-plugin-manager) | - | [`client-ui-plugin-manager`](../packages/client/ui-plugin-manager) | - | Races public registry responses on the Host; the Client owns the initial registry recommendation. | | `ctx.pluginManager` | `core` | [`plugin-manager`](../packages/boot/plugin-manager) | - | [`plugin-manager`](../packages/boot/plugin-manager), `ui-settings-plugin-inventory` | - | Shares profile package operations with the CLI and reports persisted and running state to Web and agent callers. | +| `ctx.connectorAccounts` | `service` | [`client-ui-connector-account`](../packages/client/ui-connector-account) | - | - | - | Holds the accounts CLI app plugins and MCP connectors register and serves their Host-computed displays to the Plugins page through one Remote; authorization pages and notices stay in the browser that started the operation. | | `ctx.pluginMarket` | `core` | [`plugin-market`](../packages/boot/plugin-market) | - | [`client-ui-plugin-market`](../packages/client/ui-plugin-market), [`plugin-market`](../packages/boot/plugin-market) | - | Fetches and validates the index sources the user configures; installation goes through the plugin manager. | | `ctx.profileContext` | `core` | [`app-boot`](../packages/boot/app-boot) | - | [`plugin-manager`](../packages/boot/plugin-manager) | - | The dsh launcher supplies data-only profile locations and composition inputs; reload scheduling belongs to dsh-hmr. | | `ctx.connection` | `core` | [`client-connection`](../packages/client/connection) | - | [`api-gateway`](../packages/api/gateway), [`host-frontend-static`](../packages/host/frontend-static) | - | Owns browser authentication and shared HTTP request dispatch; API adapters register endpoints and streams. | diff --git a/docs/capability-seams.zh.md b/docs/capability-seams.zh.md index 5effa1f8c4..57543c3bd5 100644 --- a/docs/capability-seams.zh.md +++ b/docs/capability-seams.zh.md @@ -30,6 +30,8 @@ flowchart LR pkg_plugin_manager["plugin-manager"] svc_pluginManager["ctx.pluginManager
Current-profile plugin and bundle management"] pkg_ui_settings_plugin_inventory["ui-settings-plugin-inventory"] + pkg_client_ui_connector_account["client-ui-connector-account"] + svc_connectorAccounts["ctx.connectorAccounts
Connector accounts on the Plugins page"] pkg_plugin_market["plugin-market"] svc_pluginMarket["ctx.pluginMarket
Plugin market index reader"] pkg_client_ui_plugin_market["client-ui-plugin-market"] @@ -346,6 +348,7 @@ flowchart LR pkg_client_file_upload --> svc_fileUploads pkg_client_modules --> svc_clientModules pkg_client_product_analytics --> svc_productAnalytics + pkg_client_ui_connector_account --> svc_connectorAccounts pkg_client_ui_plugin_manager --> svc_pluginRegistryProbe pkg_command_feedback --> svc_sessionFeedback pkg_commands --> svc_commands @@ -661,6 +664,7 @@ flowchart LR | `ctx.hmr` | `core` | [`hmr`](../packages/boot/hmr) | - | [`app-boot`](../packages/boot/app-boot) | - | 负责模块和精确配置监听;应用修改共用其队列,自动重载等待应用文件锁。 | | `ctx.pluginRegistryProbe` | `core` | [`client-ui-plugin-manager`](../packages/client/ui-plugin-manager) | - | [`client-ui-plugin-manager`](../packages/client/ui-plugin-manager) | - | 在 Host 上并发比较公共安装源响应;初始安装源推荐由 Client 负责。 | | `ctx.pluginManager` | `core` | [`plugin-manager`](../packages/boot/plugin-manager) | - | [`plugin-manager`](../packages/boot/plugin-manager), `ui-settings-plugin-inventory` | - | 与 CLI 共享 profile 包操作,并向 Web 和 Agent 调用方分别报告持久状态与运行状态。 | +| `ctx.connectorAccounts` | `service` | [`client-ui-connector-account`](../packages/client/ui-connector-account) | - | - | - | 保存 CLI 应用插件和 MCP 连接器注册的账号,并通过一个 Remote 把 Host 算好的展示内容提供给插件页;授权页和提示只出现在发起操作的浏览器中。 | | `ctx.pluginMarket` | `core` | [`plugin-market`](../packages/boot/plugin-market) | - | [`client-ui-plugin-market`](../packages/client/ui-plugin-market), [`plugin-market`](../packages/boot/plugin-market) | - | 获取并校验用户配置的索引源;安装通过插件管理器完成。 | | `ctx.profileContext` | `core` | [`app-boot`](../packages/boot/app-boot) | - | [`plugin-manager`](../packages/boot/plugin-manager) | - | dsh launcher 提供纯数据形式的 profile 位置与组合输入;重载调度由 dsh-hmr 负责。 | | `ctx.connection` | `core` | [`client-connection`](../packages/client/connection) | - | [`api-gateway`](../packages/api/gateway), [`host-frontend-static`](../packages/host/frontend-static) | - | 负责浏览器认证与共享 HTTP 请求分发;API 适配器注册端点和流。 | diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 6c75efde1d..3a24364ee1 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -5022,6 +5022,7 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co | `@deepseek-ai/dsh-client-ui-brand-official` | — | [`packages/client/ui-brand-official/src/index.ts`](../packages/client/ui-brand-official/src/index.ts) | | `@deepseek-ai/dsh-client-ui-chat` | — | [`packages/client/ui-chat/src/index.ts`](../packages/client/ui-chat/src/index.ts) | | `@deepseek-ai/dsh-client-ui-commands` | — | [`packages/client/ui-commands/src/index.ts`](../packages/client/ui-commands/src/index.ts) | +| `@deepseek-ai/dsh-client-ui-connector-account` | — | [`packages/client/ui-connector-account/src/index.ts`](../packages/client/ui-connector-account/src/index.ts) | | `@deepseek-ai/dsh-client-ui-context-menu` | — | [`packages/client/ui-context-menu/src/index.ts`](../packages/client/ui-context-menu/src/index.ts) | | `@deepseek-ai/dsh-client-ui-conversation` | — | [`packages/client/ui-conversation/src/index.ts`](../packages/client/ui-conversation/src/index.ts) | | `@deepseek-ai/dsh-client-ui-cordis` | — | [`packages/extensions/ui-cordis/src/index.ts`](../packages/extensions/ui-cordis/src/index.ts) | diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index c7a7ba3c7a..9535e76458 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -5024,6 +5024,7 @@ export interface Config { | `@deepseek-ai/dsh-client-ui-brand-official` | — | [`packages/client/ui-brand-official/src/index.ts`](../packages/client/ui-brand-official/src/index.ts) | | `@deepseek-ai/dsh-client-ui-chat` | — | [`packages/client/ui-chat/src/index.ts`](../packages/client/ui-chat/src/index.ts) | | `@deepseek-ai/dsh-client-ui-commands` | — | [`packages/client/ui-commands/src/index.ts`](../packages/client/ui-commands/src/index.ts) | +| `@deepseek-ai/dsh-client-ui-connector-account` | — | [`packages/client/ui-connector-account/src/index.ts`](../packages/client/ui-connector-account/src/index.ts) | | `@deepseek-ai/dsh-client-ui-context-menu` | — | [`packages/client/ui-context-menu/src/index.ts`](../packages/client/ui-context-menu/src/index.ts) | | `@deepseek-ai/dsh-client-ui-conversation` | — | [`packages/client/ui-conversation/src/index.ts`](../packages/client/ui-conversation/src/index.ts) | | `@deepseek-ai/dsh-client-ui-cordis` | — | [`packages/extensions/ui-cordis/src/index.ts`](../packages/extensions/ui-cordis/src/index.ts) | diff --git a/docs/module-graph.md b/docs/module-graph.md index 2e73bd13bc..e63ca7d1c6 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -166,6 +166,7 @@ flowchart TD pkg_client_ui_brand_official["client-ui-brand-official"] pkg_client_ui_chat["client-ui-chat"] pkg_client_ui_commands["client-ui-commands"] + pkg_client_ui_connector_account["client-ui-connector-account"] pkg_client_ui_context_menu["client-ui-context-menu"] pkg_client_ui_conversation["client-ui-conversation"] pkg_client_ui_deliverables["client-ui-deliverables"] @@ -1586,6 +1587,7 @@ flowchart TD | [`client-ui-brand-official`](../packages/client/ui-brand-official) | `client` | — | | [`client-ui-chat`](../packages/client/ui-chat) | `client` | — | | [`client-ui-commands`](../packages/client/ui-commands) | `client` | — | +| [`client-ui-connector-account`](../packages/client/ui-connector-account) | `client` | — | | [`client-ui-context-menu`](../packages/client/ui-context-menu) | `client` | — | | [`client-ui-conversation`](../packages/client/ui-conversation) | `client` | — | | [`client-ui-deliverables`](../packages/client/ui-deliverables) | `client` | — | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index 1b697fe591..fb305c3557 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -168,6 +168,7 @@ flowchart TD pkg_client_ui_brand_official["client-ui-brand-official"] pkg_client_ui_chat["client-ui-chat"] pkg_client_ui_commands["client-ui-commands"] + pkg_client_ui_connector_account["client-ui-connector-account"] pkg_client_ui_context_menu["client-ui-context-menu"] pkg_client_ui_conversation["client-ui-conversation"] pkg_client_ui_deliverables["client-ui-deliverables"] @@ -1588,6 +1589,7 @@ flowchart TD | [`client-ui-brand-official`](../packages/client/ui-brand-official) | `client` | — | | [`client-ui-chat`](../packages/client/ui-chat) | `client` | — | | [`client-ui-commands`](../packages/client/ui-commands) | `client` | — | +| [`client-ui-connector-account`](../packages/client/ui-connector-account) | `client` | — | | [`client-ui-context-menu`](../packages/client/ui-context-menu) | `client` | — | | [`client-ui-conversation`](../packages/client/ui-conversation) | `client` | — | | [`client-ui-deliverables`](../packages/client/ui-deliverables) | `client` | — | diff --git a/docs/subsystems/boot.md b/docs/subsystems/boot.md index 6780e92c43..c8f36d14e2 100644 --- a/docs/subsystems/boot.md +++ b/docs/subsystems/boot.md @@ -143,6 +143,50 @@ async edit( entry: Entry, change: (current: Record, inherited: Source: [`packages/boot/config-editor/src/index.ts`](../../packages/boot/config-editor/src/index.ts) + + +### `ctx.connectorAccounts` — `ConnectorAccounts` + +Holds the registered accounts and serves them to the Plugins page. + +```ts cordis-catalog +/** + * Show one account on the Plugins page for as long as the returned disposer has not run. + * @param registration - the account key, its bundle package, the account source, the page operations, and the + * presentation. + * @returns an idempotent disposer that withdraws the account. + * @throws when another account already uses the key or the package. + */ +register(registration: ConnectorAccountRegistration): () => void + +/** + * Follow every registered account; each new subscriber starts a check of each account that runs no operation. + * @param signal - the Client's observation lifetime; disposal also ends the stream. + * @returns the current accounts, then each changed set, coalescing changes that arrive before the next read. + */ +@Remote({ mode: 'stream' }) async *watch(signal: AbortSignal): AsyncIterable + +/** + * Start one of the operations the account registered as page actions. + * @param key - the account key. + * @param operation - the operation kind. + * @returns the operation identity. + * @throws for an unknown account or operation, or whatever the account's source refuses, such as a second operation. + */ +@Remote start(key: string, operation: string): ConnectorOperationId + +/** + * Cancel one operation while its phase is cancellable, and wait for it to settle. + * @param key - the account key. + * @param id - the operation to cancel; a finished one or a phase that is not cancellable is ignored. + * @returns after the operation settles, or at once when nothing is cancelled. + * @throws for an unknown account. + */ +@Remote cancel(key: string, id: ConnectorOperationId): Promise +``` + +Source: [`packages/client/ui-connector-account/src/index.ts`](../../packages/client/ui-connector-account/src/index.ts) + ### `ctx.headlessStartup` — `HeadlessStartupValues` diff --git a/docs/subsystems/boot.zh.md b/docs/subsystems/boot.zh.md index 915b6e8112..ab6383e0b3 100644 --- a/docs/subsystems/boot.zh.md +++ b/docs/subsystems/boot.zh.md @@ -143,6 +143,50 @@ async edit( entry: Entry, change: (current: Record, inherited: Source: [`packages/boot/config-editor/src/index.ts`](../../packages/boot/config-editor/src/index.ts) + + +### `ctx.connectorAccounts` — `ConnectorAccounts` + +Holds the registered accounts and serves them to the Plugins page. + +```ts cordis-catalog +/** + * Show one account on the Plugins page for as long as the returned disposer has not run. + * @param registration - the account key, its bundle package, the account source, the page operations, and the + * presentation. + * @returns an idempotent disposer that withdraws the account. + * @throws when another account already uses the key or the package. + */ +register(registration: ConnectorAccountRegistration): () => void + +/** + * Follow every registered account; each new subscriber starts a check of each account that runs no operation. + * @param signal - the Client's observation lifetime; disposal also ends the stream. + * @returns the current accounts, then each changed set, coalescing changes that arrive before the next read. + */ +@Remote({ mode: 'stream' }) async *watch(signal: AbortSignal): AsyncIterable + +/** + * Start one of the operations the account registered as page actions. + * @param key - the account key. + * @param operation - the operation kind. + * @returns the operation identity. + * @throws for an unknown account or operation, or whatever the account's source refuses, such as a second operation. + */ +@Remote start(key: string, operation: string): ConnectorOperationId + +/** + * Cancel one operation while its phase is cancellable, and wait for it to settle. + * @param key - the account key. + * @param id - the operation to cancel; a finished one or a phase that is not cancellable is ignored. + * @returns after the operation settles, or at once when nothing is cancelled. + * @throws for an unknown account. + */ +@Remote cancel(key: string, id: ConnectorOperationId): Promise +``` + +Source: [`packages/client/ui-connector-account/src/index.ts`](../../packages/client/ui-connector-account/src/index.ts) + ### `ctx.headlessStartup` — `HeadlessStartupValues` diff --git a/packages/api/remotes/README.i18n.yaml b/packages/api/remotes/README.i18n.yaml index 4178adfa26..b05bc795e0 100644 --- a/packages/api/remotes/README.i18n.yaml +++ b/packages/api/remotes/README.i18n.yaml @@ -15,8 +15,8 @@ en: a7a78c6d1aeebeb3 zh: 4bb69f32d8b05ba3 /deepseek-ai-dsh-api-remotes/use-this-package: - en: 5e5770cc1cbf49db - zh: b9ee3c309d0cd93c + en: d8622091b217f050 + zh: c36cb87f10e7802a /deepseek-ai-dsh-api-remotes/forwarded-host-events: en: 1dea001229f8c06a zh: 3acb1fa1c5d24f8c diff --git a/packages/api/remotes/README.md b/packages/api/remotes/README.md index 71e5dc385f..a01a776f3e 100644 --- a/packages/api/remotes/README.md +++ b/packages/api/remotes/README.md @@ -29,7 +29,7 @@ Two-sided BFF for Host Remote capabilities selected by this application. The Hos [`@deepseek-ai/dsh-api-session-controller`](../session-controller/README.md) owns Agent and Session identity policy, including the Typert lookup resolvers used by other namespaces. This package selects and mounts that generated Session contribution without a direct runtime dependency on `@deepseek-ai/dsh-session`; activation policy stays with Session Controller. -The Client assembly mounts Office conversion, Commands, Agent Teams, credentials, settings, Goal, Schedule, dynamic Cordis, file and Session references, read-only Host plugin inventory, plugin-installation registry response comparison, message feedback, permission presets, Session Controller, subagents, web provider list, and Workspace Controller contributions. The `permissionPresets` namespace returns the complete process-level catalog used by current-session controls. Cordis effect ownership withdraws every contribution when this assembly unloads, while `@deepseek-ai/dsh-api-gateway/client` owns descriptor validation, traced namespace Services, direct and scoped methods, invocation, streams, and cancellation. The Client entry consumes the shared `TypertClientRemote` interface through Cordis and does not import the concrete Gateway. It re-exports the Gateway Client face's declaration merges type-only, so a consumer reaching the forwarded-event vocabulary through this facade gains no runtime edge to the Gateway implementation. +The Client assembly mounts Office conversion, Commands, Agent Teams, credentials, settings, Goal, Schedule, dynamic Cordis, file and Session references, read-only Host plugin inventory, plugin-installation registry response comparison, connector accounts, message feedback, permission presets, Session Controller, subagents, web provider list, and Workspace Controller contributions. The `permissionPresets` namespace returns the complete process-level catalog used by current-session controls. Cordis effect ownership withdraws every contribution when this assembly unloads, while `@deepseek-ai/dsh-api-gateway/client` owns descriptor validation, traced namespace Services, direct and scoped methods, invocation, streams, and cancellation. The Client entry consumes the shared `TypertClientRemote` interface through Cordis and does not import the concrete Gateway. It re-exports the Gateway Client face's declaration merges type-only, so a consumer reaching the forwarded-event vocabulary through this facade gains no runtime edge to the Gateway implementation. This facade is also the front door for the wire type vocabulary a Client package names. It re-exports, type-only, the Remote failure vocabulary (`RemoteResult`, `RemoteFailure`, `RemoteErrorCode`, `RemoteErrorDetailsMap`), the Host facts (`RemoteHostFacts`), and each selected domain's client-safe payload types, so a Client feature package imports one specifier instead of reaching into `dsh-typert-protocol`, the Gateway, or an owner's Host entry. Two kinds of package deliberately skip this door: the API-layer packages this assembly itself selects — importing it back would close a dependency cycle — and their tests, which take the failure vocabulary from `dsh-typert-protocol` directly. A UI package's tests instead take the `RemoteError` constructor from [`dsh-client-test-runtime`](../../test-support/client-runtime/README.md). diff --git a/packages/api/remotes/README.zh.md b/packages/api/remotes/README.zh.md index 5bef7cb29c..cc3c407f49 100644 --- a/packages/api/remotes/README.zh.md +++ b/packages/api/remotes/README.zh.md @@ -29,7 +29,7 @@ kind: "package-reference" [`@deepseek-ai/dsh-api-session-controller`](../session-controller/README.zh.md) 拥有 agent(智能体)与会话身份策略,包括供其他 namespace 使用的 Typert lookup 解析器。本包选择并挂载生成的会话 contribution,无需直接依赖 `@deepseek-ai/dsh-session` 的运行时;激活策略由会话控制器负责。 -Client 组合挂载 Office 转换、Commands、Agent Teams、凭据、settings、Goal、Schedule、动态 Cordis、文件与会话引用、只读 Host 插件清单、插件安装源响应比较、消息反馈、权限预设、会话控制器、subagents、Web 提供方列表和 Workspace 控制器 contribution。`permissionPresets` namespace 返回 current-session 控件使用的完整进程级目录。该组合卸载时,Cordis effect 的所有权机制会撤回所有贡献;`@deepseek-ai/dsh-api-gateway/client` 负责描述符校验、可追踪的 namespace 服务、直接与作用域方法、调用、流与取消。Client 入口通过 Cordis 消费共享的 `TypertClientRemote` 接口,不导入具体 Gateway;它只以 type-only 形式重新导出 Gateway Client face 的声明合并,因此消费端经由本外观取到转发事件词汇时,运行时不会多出一条通往 Gateway 实现的边。 +Client 组合挂载 Office 转换、Commands、Agent Teams、凭据、settings、Goal、Schedule、动态 Cordis、文件与会话引用、只读 Host 插件清单、插件安装源响应比较、连接器账号、消息反馈、权限预设、会话控制器、subagents、Web 提供方列表和 Workspace 控制器 contribution。`permissionPresets` namespace 返回 current-session 控件使用的完整进程级目录。该组合卸载时,Cordis effect 的所有权机制会撤回所有贡献;`@deepseek-ai/dsh-api-gateway/client` 负责描述符校验、可追踪的 namespace 服务、直接与作用域方法、调用、流与取消。Client 入口通过 Cordis 消费共享的 `TypertClientRemote` 接口,不导入具体 Gateway;它只以 type-only 形式重新导出 Gateway Client face 的声明合并,因此消费端经由本外观取到转发事件词汇时,运行时不会多出一条通往 Gateway 实现的边。 本 facade 同时是 Client 包指称 wire 类型词汇的正门。它以 type-only 方式转出 Remote 失败词汇(`RemoteResult`、`RemoteFailure`、`RemoteErrorCode`、`RemoteErrorDetailsMap`)、Host 事实(`RemoteHostFacts`),以及各已选领域对 Client 安全的载荷类型,因此 Client 功能包只 import 一个 specifier,不必伸手进 `dsh-typert-protocol`、Gateway 或某个拥有方的 Host 入口。有两类包刻意不走这道门:本装配自己选中的 API 层包——反向 import 会形成依赖环——以及它们的测试,后者直接从 `dsh-typert-protocol` 取失败词汇。UI 包的测试则从 [`dsh-client-test-runtime`](../../test-support/client-runtime/README.zh.md) 取 `RemoteError` 构造器。 diff --git a/packages/api/remotes/package.json b/packages/api/remotes/package.json index 25718e223b..ffc73c917b 100644 --- a/packages/api/remotes/package.json +++ b/packages/api/remotes/package.json @@ -98,6 +98,7 @@ "@deepseek-ai/dsh-plugin-manager": "workspace:*", "@deepseek-ai/dsh-mcp-manager": "workspace:*", "@deepseek-ai/dsh-plugin-market": "workspace:*", + "@deepseek-ai/dsh-client-ui-connector-account": "workspace:*", "@deepseek-ai/dsh-client-ui-plugin-manager": "workspace:*", "@deepseek-ai/dsh-office-kit": "workspace:*", "@deepseek-ai/dsh-deepseek-account": "workspace:*", diff --git a/packages/api/remotes/src/client/index.ts b/packages/api/remotes/src/client/index.ts index 5d91957c0a..ade29eff4e 100644 --- a/packages/api/remotes/src/client/index.ts +++ b/packages/api/remotes/src/client/index.ts @@ -19,6 +19,7 @@ import pluginManagerRemote from '@deepseek-ai/dsh-plugin-manager/remote' import mcpManagerRemote from '@deepseek-ai/dsh-mcp-manager/remote' import toolResultsRemote from '@deepseek-ai/dsh-client-ui-trajectory/remote' import pluginRegistryProbeRemote from '@deepseek-ai/dsh-client-ui-plugin-manager/remote' +import connectorAccountsRemote from '@deepseek-ai/dsh-client-ui-connector-account/remote' import pluginMarketRemote from '@deepseek-ai/dsh-plugin-market/remote' import pluginInventoryRemote from '@deepseek-ai/dsh-host-plugin-inventory/remote' import messageFeedbackRemote from '@deepseek-ai/dsh-message-feedback/remote' @@ -48,6 +49,7 @@ export type { McpManagedServerStatus, McpManagedServerView } from '@deepseek-ai/ export type {} from '@deepseek-ai/dsh-plugin-manager/remote' export type {} from '@deepseek-ai/dsh-mcp-manager/remote' export type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/remote' +export type {} from '@deepseek-ai/dsh-client-ui-connector-account/remote' export type {} from '@deepseek-ai/dsh-client-ui-trajectory/remote' export type {} from '@deepseek-ai/dsh-plugin-market/remote' export type { @@ -200,6 +202,7 @@ export async function apply(ctx: Context): Promise<() => Promise> { productAnalyticsRemote, agentPresetsRemote, commandsRemote, agentTeamsRemote, settingsControllerRemote, accountRemote, goalsRemote, llmRemote, dynamicRemote, scheduleRemote, pluginInventoryRemote, pluginManagerRemote, mcpManagerRemote, pluginMarketRemote, pluginRegistryProbeRemote, + connectorAccountsRemote, toolResultsRemote, messageFeedbackRemote, sessionFeedbackRemote, fileUploadsRemote, sessionReferencesRemote, diff --git a/packages/bundle/web-app/cordis.patch.yml b/packages/bundle/web-app/cordis.patch.yml index e842d8e3e1..fc7b384795 100644 --- a/packages/bundle/web-app/cordis.patch.yml +++ b/packages/bundle/web-app/cordis.patch.yml @@ -341,6 +341,11 @@ - id: ui-plugin-manager name: '@deepseek-ai/dsh-client-ui-plugin-manager' + # Connector account sections on the Plugins page; CLI app plugins and MCP + # connectors register their accounts with `ctx.connectorAccounts`. + - id: ui-connector-account + name: '@deepseek-ai/dsh-client-ui-connector-account' + # Read-only Plugin list tab in the Settings Plugins section; the built-in # bundles the sidebar page leaves out are inspected here. - id: ui-settings-plugin-inventory diff --git a/packages/bundle/web-app/package.json b/packages/bundle/web-app/package.json index 2858130d13..82ce2dd4a3 100644 --- a/packages/bundle/web-app/package.json +++ b/packages/bundle/web-app/package.json @@ -86,6 +86,7 @@ "@deepseek-ai/dsh-client-ui-brand-official": "workspace:*", "@deepseek-ai/dsh-client-ui-chat": "workspace:*", "@deepseek-ai/dsh-client-ui-commands": "workspace:*", + "@deepseek-ai/dsh-client-ui-connector-account": "workspace:*", "@deepseek-ai/dsh-client-ui-context-menu": "workspace:*", "@deepseek-ai/dsh-client-ui-conversation": "workspace:*", "@deepseek-ai/dsh-client-ui-cordis": "workspace:*", diff --git a/packages/client/README.i18n.yaml b/packages/client/README.i18n.yaml index f77d3835d7..54854f5f19 100644 --- a/packages/client/README.i18n.yaml +++ b/packages/client/README.i18n.yaml @@ -15,8 +15,8 @@ en: 1eb35b015a6c423f zh: a8a3dceee2c9e943 /client-web-gui-browser-half/packages: - en: 2165938f26300774 - zh: 5f739534a8509545 + en: affd6d8506276e34 + zh: 92730ec91d83d609 /client-web-gui-browser-half/related-documentation: en: d1d506e68fab7333 zh: 1a90fe6f3f8f24a9 diff --git a/packages/client/README.md b/packages/client/README.md index 3047a181c1..6edf512eb4 100644 --- a/packages/client/README.md +++ b/packages/client/README.md @@ -83,6 +83,7 @@ The kernel packages boot and serve the page; the UI feature packages present it. | [`ui-settings-subagent/`](ui-settings-subagent/README.md) | Provides the Subagent settings page on the Plugins page | — | | [`ui-settings-web-search/`](ui-settings-web-search/README.md) | Provides the web search and fetch settings page on the Plugins page | — | | [`ui-plugin-manager/`](ui-plugin-manager/README.md) | Contributes the sidebar Plugins panel: install, enable, disable, retry, and compose installed packages | — | +| [`ui-connector-account/`](ui-connector-account/README.md) | Holds the accounts connector plugins register on the Host and shows each bundle's account section, tag, activation prompt, confirmations, and notices on the Plugins page | `ctx.connectorAccounts` | | [`ui-entry-customization/`](ui-entry-customization/README.md) | Adds region-local More menus that pin or unpin plugin launchers and start a plugin draft | — | | [`ui-plugin-market/`](ui-plugin-market/README.md) | Contributes the Discover tab to the Plugins page: browse market indexes and install their bundles | — | | [`ui-settings-plugin-inventory/`](ui-settings-plugin-inventory/README.md) | Contributes the read-only Host Loader inventory tab to Plugins settings | — | diff --git a/packages/client/README.zh.md b/packages/client/README.zh.md index e327a717d9..635750069e 100644 --- a/packages/client/README.zh.md +++ b/packages/client/README.zh.md @@ -83,6 +83,7 @@ kind: "package-group" | [`ui-settings-subagent/`](ui-settings-subagent/README.zh.md) | 在插件页提供子智能体设置页 | — | | [`ui-settings-web-search/`](ui-settings-web-search/README.zh.md) | 在插件页提供网页搜索与获取设置页 | — | | [`ui-plugin-manager/`](ui-plugin-manager/README.zh.md) | 贡献侧栏的“插件”面板:安装、启用、停用、重试与组合已安装的包 | — | +| [`ui-connector-account/`](ui-connector-account/README.zh.md) | 保存连接器插件在 Host 上注册的账号,并在插件页显示每个插件包的账号区块、标签、开启引导、确认和提示 | `ctx.connectorAccounts` | | [`ui-entry-customization/`](ui-entry-customization/README.zh.md) | 添加分区域的“更多”菜单,固定或收起插件入口,并开始创建插件的草稿 | — | | [`ui-plugin-market/`](ui-plugin-market/README.zh.md) | 为“插件”页面贡献“发现”标签页:浏览市场索引并安装其中的组合包 | — | | [`ui-settings-plugin-inventory/`](ui-settings-plugin-inventory/README.zh.md) | 向「插件」设置贡献只读的 Host Loader 清单标签页 | — | diff --git a/packages/client/ui-connector-account/README.i18n.yaml b/packages/client/ui-connector-account/README.i18n.yaml new file mode 100644 index 0000000000..347d021162 --- /dev/null +++ b/packages/client/ui-connector-account/README.i18n.yaml @@ -0,0 +1,49 @@ +# 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/ui-connector-account/README.md +/: + en: f09638e4097c52fb + zh: 2fb344b05a189ad0 +/deepseek-ai-dsh-client-ui-connector-account: + en: bdb528546ec26353 + zh: 0dd55dbc0c8e837a +/deepseek-ai-dsh-client-ui-connector-account/summary: + en: b25fc16fb18a63c1 + zh: 4508e8a44745b08d +/deepseek-ai-dsh-client-ui-connector-account/table-of-contents: + en: d152484eb41ac6b4 + zh: 5b6bd00fce5371c3 +/deepseek-ai-dsh-client-ui-connector-account/use-this-package: + en: 9d8d49a0b1b3ce24 + zh: 8eba3710036afa00 +/deepseek-ai-dsh-client-ui-connector-account/use-this-package/register-an-account: + en: e618281ea7721daf + zh: a5d5f5e307ea3435 +/deepseek-ai-dsh-client-ui-connector-account/use-this-package/present-the-section: + en: 73ca134d685b5872 + zh: 05b929fd28dc955e +/deepseek-ai-dsh-client-ui-connector-account/use-this-package/following-operations: + en: a9e64f316efcac3e + zh: d059d31b65573bf5 +/deepseek-ai-dsh-client-ui-connector-account/use-this-package/shared-copy: + en: f88db8d50a68a0ca + zh: 6169fd1ffc9c79a0 +/deepseek-ai-dsh-client-ui-connector-account/understand-the-implementation: + en: da424b56f995bef5 + zh: 298fc8e50149fea5 +/deepseek-ai-dsh-client-ui-connector-account/further-exploration: + en: 029949903a73d283 + zh: 6f9a8c2f7620de69 +/deepseek-ai-dsh-client-ui-connector-account/model-experience: + en: bdbc56a07884f8d6 + zh: 22ca2ee613472c0b +/deepseek-ai-dsh-client-ui-connector-account/model-experience/kv-cache-effect: + en: 4cd0965a7997970e + zh: 690e5a9d945f7f6e +/deepseek-ai-dsh-client-ui-connector-account/known-limitations-and-deferred-work: + en: d2c5f54b80b86b15 + zh: 8b637f97ac1d0223 +/deepseek-ai-dsh-client-ui-connector-account/known-limitations-and-deferred-work/dev-note: + en: 2ab3c4acae06850c + zh: bd2093ba1fdd6860 diff --git a/packages/client/ui-connector-account/README.md b/packages/client/ui-connector-account/README.md new file mode 100644 index 0000000000..1013fb4f48 --- /dev/null +++ b/packages/client/ui-connector-account/README.md @@ -0,0 +1,138 @@ +--- +description: "Register a connector plugin's account on the Host with `ctx.connectorAccounts` and show its section, title tag, activation prompt, confirmations, and notices on the Plugins page through one `connectorAccounts` Remote, with the registrant's own text and the shared copy of this package." +kind: "package-reference" +--- + +# @deepseek-ai/dsh-client-ui-connector-account + +English | [中文](README.zh.md) + +## Summary + +Connector plugins register their account on the Host with `ctx.connectorAccounts` to show it on the Plugins page: CLI app plugins register the account their vendor CLI keeps, and MCP connectors their OAuth server's account. The Host decides what the page shows and does: each registrant maps its account to a display, and the registry starts or cancels only the operations the account lists. The browser half renders each bundle's section, title tag, and activation prompt, and opens authorization pages and reports notices only in the browser that started the operation. The Web and Desktop compositions load both halves through [`dsh-web-app`](../../bundle/web-app/README.md). + +## 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 registrant's Host row registers its account once; the registrant ships no browser code for the account. + +### Register an account + +The registrant's Host row registers its account source while the registry runs, so a composition without the registry, such as a headless profile, skips the registration: + +```ts ignore-check +import type {} from '@deepseek-ai/dsh-client-ui-connector-account' + +export function apply(ctx: Context): void { + const account = new AcmeAccount(options) + ctx.effect(() => () => account.dispose(), 'acme: account') + ctx.inject(['connectorAccounts'], (scope) => { + scope.effect(() => scope.connectorAccounts.register({ + key: '@acme/cli', packageName: '@acme/cli', source: account, copy, + operations: [{ kind: 'check' }, { kind: 'connect', notice: { en: 'Acme connected', zh: 'Acme 已连接' } }], + present: presentAccount, + }), 'acme: Plugins page account') + }) +} +``` + +- `key` identifies the account in the Remote; the page passes it back to start and cancel operations. A second registration with the same key throws. +- `packageName` is the npm package whose bundle page carries the section and tag; a package carries at most one account. An account without one, such as a server configured in Settings, appears on no bundle page. +- `source` is the account: its current view, change observation, a check, and starting and cancelling operations. +- `operations` lists the kinds a page button may start, each with the optional text its success reports in the browser that started it; the registry rejects any other kind. +- `copy` holds the section title, the hint under it, and the activation prompt's title, body, and Connect label. + +The registrant imports the registry's types with `import type` from the package root or `./types`. The returned disposer withdraws the account from every page. + +### Present the section + +`present(view)` maps the account view to a `ConnectorAccountDisplay`: the phase, the status line, the optional title tag, buttons, the operation Connect starts in the activation prompt, detail, notes, and failure with its untranslated diagnostic items. The registry calls it for every stream on each change, so it only maps the view. Every string is `LocalizedText`, which each browser resolves in its active language. A button carries a command: `start` with one of the registered operation kinds, `cancel` for the operation in progress, which the source ignores in a phase that is not cancellable, or `open` to reopen its authorization page. A button with `confirm` asks first and runs only after the user accepts. + +| Surface | Behavior | +|---|---| +| Section | Title, status, buttons, detail, notes, failure, and hint. Buttons are disabled while a call the section made is pending or the Host stream is down. A failure shows the registrant's text, then its diagnostic items | +| Title tag | The display's `badge`, shown only on the enabled bundle's page or one of its row pages, and only while the display has one | +| Activation prompt | Open while the phase is `disconnected` after the bundle is switched on; Connect opens the bundle page and starts the display's `connect` operation, if it names one. It dismisses itself once the phase settles elsewhere | +| Notice | The latest outcome in this browser, outside the Plugins panel's lifetime: the operation's success text, or the shared failure copy with a warning icon | + +### Following operations + +Each browser opens one stream when the Web app loads, and the Host checks every account that runs no operation for each new stream; an account registered while a stream is open is checked at once. A browser follows the operation its latest start returned, from that answer until the stream delivers the operation's result. Each page the followed operation offers opens once in a new tab, over HTTPS or over HTTP on a loopback address; other browsers show the same section but open no page and report no notice. A second click before the first call answers starts nothing. A stream that fails for good shows the account service as not running with Retry, which reopens the stream once however often it is pressed. Unloading the browser half closes the stream; Host-owned operations keep running. + +### Shared copy + +The `connectorAccount` dictionary holds the copy every account shares: Close, Cancel, Retry, Later, the diagnostic label, the failure notice, and the not-running status, tag, and detail. Every other string comes from the registrant. + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +The Host half, `ConnectorAccounts`, is a Remote service. `register()` observes the account's source, and each `watch` stream reads every account's entry after each change, coalescing changes that arrive before the next read: the key and package, the copy, `present(view)`, the operation in progress, and the latest result with its success text. `start` and `cancel` route by key to the account's source. + +[`dsh-api-remotes`](../../api/remotes/README.md) mounts the generated `connectorAccounts` Remote. The browser half opens one `watch` stream through `BrowserAccounts`, whose one store holds the Host's accounts by key, whether the stream is delivering or has stopped, and the latest notice; it also remembers the operations this browser started. It registers one `plugins.detail.badge` entry and one `shell.overlay` notice for the page, and for each account with a package, `plugins.bundle.config` and `plugins.bundle.activation` keyed by the package name, all under the `connectorAccount` namespace. The buttons call `start` and `cancel` on the Remote themselves and report the started operation to `BrowserAccounts`. An account the Host drops loses its bundle entries, and unloading withdraws every entry and the stream. + +| File | Role | +|---|---| +| [`src/index.ts`](src/index.ts) | The `ctx.connectorAccounts` registry and its Remote | +| [`src/types.ts`](src/types.ts) | Registration, source, view, display, and entry types | +| [`src/client/index.ts`](src/client/index.ts) | The browser entry: the dictionary and the slot registrations | +| [`src/client/state.ts`](src/client/state.ts) | The stream store, the operations this browser started, and their pages and notices | +| [`src/client/components.tsx`](src/client/components.tsx) | The surfaces, the slot entries, and the buttons' Remote calls | +| [`src/client/locales.ts`](src/client/locales.ts) | The shared dictionary | +| [`src/client/types.ts`](src/client/types.ts) | Browser state, notice, Remote, and face types | + +
+ +----- + + +## Further Exploration + +- [Plugin manager page](../ui-plugin-manager/README.md) — the Plugins page and its bundle slots. +- [Client package map](../README.md) — adjacent browser UI packages. + +----- + + +## Model Experience + +None, as the registry and its surfaces are Plugins page UI and add no model input. Each registrant documents the tools and skills its account enables. + +#### KV Cache effect + +None; registering or removing an account changes no model-visible text. + +## Known Limitations and Deferred Work + + + +- The five display phases are fixed; a registrant maps any further account state onto one of them. +- A registrant whose Host row fails to load shows no account section; the Plugins page still lists the bundle with its load failure. +- Each browser that loads the Web app starts a check of every idle account. +- The Web and Desktop compositions load the registry whether or not a connector plugin is installed. +- An authorization page that opens after the call answers can be blocked by the browser; the section's open button shows it again. + + +### Dev Note + +
+Working context for maintainers — click to expand + +Host specs drive the registry with fake account sources. Client specs drive `BrowserAccounts` with a fake Remote stream, render the surfaces with the Chinese dictionary and a fake Remote, and mount the browser half against a real slot registry and locale runtime. + +
diff --git a/packages/client/ui-connector-account/README.zh.md b/packages/client/ui-connector-account/README.zh.md new file mode 100644 index 0000000000..a32ed876b2 --- /dev/null +++ b/packages/client/ui-connector-account/README.zh.md @@ -0,0 +1,138 @@ +--- +description: "通过 `ctx.connectorAccounts` 在 Host 上注册连接器插件的账号,并经由一个 `connectorAccounts` Remote 在插件页显示其区块、标题旁标签、开启引导、确认和提示,文案来自注册方自己的文本和本包的共用文案。" +kind: "package-reference" +--- + +# @deepseek-ai/dsh-client-ui-connector-account + +[English](README.md) | 中文 + +## 概述 + +连接器插件在 Host 上通过 `ctx.connectorAccounts` 注册账号,在插件页显示账号:CLI 应用插件注册其厂商 CLI 保存的账号,MCP 连接器注册其 OAuth 服务器的账号。页面显示什么、能做什么由 Host 决定:每个注册方把自己的账号映射为展示内容,注册表只启动或取消该账号列出的操作。浏览器一半渲染每个插件包的区块、标题旁标签和开启引导,并且只在发起操作的浏览器中打开授权页、报告提示。Web 与桌面端组合通过 [`dsh-web-app`](../../bundle/web-app/README.zh.md) 加载这两半。 + +## 目录 + +- [使用此包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [延伸阅读](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与后续工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用此包 + +注册方的 Host 行注册一次账号;注册方不为账号提供任何浏览器代码。 + +### 注册账号 + +注册方的 Host 行在注册表运行时注册其账号来源,因此没有注册表的组合(如 headless profile)会跳过注册: + +```ts ignore-check +import type {} from '@deepseek-ai/dsh-client-ui-connector-account' + +export function apply(ctx: Context): void { + const account = new AcmeAccount(options) + ctx.effect(() => () => account.dispose(), 'acme: account') + ctx.inject(['connectorAccounts'], (scope) => { + scope.effect(() => scope.connectorAccounts.register({ + key: '@acme/cli', packageName: '@acme/cli', source: account, copy, + operations: [{ kind: 'check' }, { kind: 'connect', notice: { en: 'Acme connected', zh: 'Acme 已连接' } }], + present: presentAccount, + }), 'acme: Plugins page account') + }) +} +``` + +- `key` 在 Remote 中标识该账号;页面启动和取消操作时把它传回。用同一个键再次注册会抛出异常。 +- `packageName` 是其插件包页面承载区块和标签的 npm 包;一个包最多承载一个账号。没有包名的账号(如在 Settings 中配置的服务器)不出现在任何插件包页面上。 +- `source` 是账号:其当前视图、变化观察、检查,以及启动和取消操作。 +- `operations` 列出页面按钮可以启动的操作类型,每项可带该操作成功时在发起它的浏览器中报告的文本;注册表拒绝其他类型。 +- `copy` 包含区块标题、区块下方的提示,以及开启引导的标题、正文和连接按钮文案。 + +注册方用 `import type` 从包根或 `./types` 导入注册表的类型。返回的销毁函数会把账号从所有页面撤下。 + +### 展示区块 + +`present(view)` 把账号视图映射为 `ConnectorAccountDisplay`:阶段、状态行、可选的标题旁标签、按钮、开启引导中“连接”启动的操作、说明、附加行,以及带不翻译诊断项的失败信息。注册表在每次变化时为每条流调用它,因此它只做视图映射。所有文案都是 `LocalizedText`,由各浏览器按当前语言解析。按钮携带一个命令:`start` 启动某个已注册的操作类型,`cancel` 取消进行中的操作(处于不可取消的阶段时来源会忽略),`open` 重新打开其授权页。带 `confirm` 的按钮会先询问,用户确认后才执行。 + +| 界面 | 行为 | +|---|---| +| 区块 | 标题、状态、按钮、说明、附加行、失败信息和提示。区块发起的调用未返回,或 Host 流中断时,按钮不可用。失败时先显示注册方的文案,再显示其诊断项 | +| 标题旁标签 | 显示 display 的 `badge`,只出现在已启用插件包的页面或其某一行的页面上,且只在 display 带有标签时显示 | +| 开启引导 | 插件包开启后,阶段为 `disconnected` 时打开;“连接”会打开插件包页面,并在 display 给出 `connect` 时启动该操作。阶段确定为其他值后自动关闭 | +| 提示 | 本浏览器的最新结果,不受插件面板生命周期限制:操作成功的文本,或带警告图标的共用失败文案 | + +### 跟随操作 + +每个浏览器在 Web 应用加载时打开一条流,Host 为每条新流检查每个没有在运行操作的账号;流打开期间注册的账号会立即检查。浏览器跟随其最近一次启动返回的操作,从返回时起,直到流推送该操作的结果。被跟随的操作提供的每个页面只在新标签页中打开一次,只打开 HTTPS 页面或回环地址上的 HTTP 页面;其他浏览器显示同样的区块,但不打开页面,也不报告提示。第一次调用返回前的第二次点击不会启动任何操作。流永久失败时,区块显示账号服务未运行,并提供“重试”;无论按多少次,都只重新打开流一次。卸载浏览器一半会关闭流;Host 持有的操作继续运行。 + +### 共用文案 + +`connectorAccount` 字典包含所有账号共用的文案:关闭、取消、重试、稍后、排障信息标签、失败提示,以及未运行时的状态、标签和说明。其余文案都来自注册方。 + +----- + + +## 理解实现 + +
+实现细节——点击展开 + +Host 一半 `ConnectorAccounts` 是一个 Remote 服务。`register()` 观察账号来源,每条 `watch` 流在每次变化后读取每个账号的条目,并合并在下一次读取前到达的变化:键和包、文案、`present(view)`、进行中的操作,以及带成功文本的最新结果。`start` 和 `cancel` 按键路由到该账号的来源。 + +[`dsh-api-remotes`](../../api/remotes/README.zh.md) 挂载生成的 `connectorAccounts` Remote。浏览器一半通过 `BrowserAccounts` 打开一条 `watch` 流;它的一个 store 保存按键索引的 Host 账号、流是否在推送或已停止,以及最新提示,同时记住本浏览器发起的操作。它为页面注册一个 `plugins.detail.badge` 条目和一个 `shell.overlay` 提示,并为每个带包名的账号注册以包名为键的 `plugins.bundle.config` 和 `plugins.bundle.activation`,全部使用 `connectorAccount` 命名空间。按钮自己调用 Remote 的 `start` 和 `cancel`,并把启动的操作报告给 `BrowserAccounts`。Host 撤下的账号会失去其插件包条目;卸载时撤下所有条目和流。 + +| 文件 | 职责 | +|---|---| +| [`src/index.ts`](src/index.ts) | `ctx.connectorAccounts` 注册表及其 Remote | +| [`src/types.ts`](src/types.ts) | 注册、来源、视图、display 和条目类型 | +| [`src/client/index.ts`](src/client/index.ts) | 浏览器入口:字典和插槽注册 | +| [`src/client/state.ts`](src/client/state.ts) | 流的 store、本浏览器发起的操作,以及它们的页面和提示 | +| [`src/client/components.tsx`](src/client/components.tsx) | 各界面、插槽条目,以及按钮的 Remote 调用 | +| [`src/client/locales.ts`](src/client/locales.ts) | 共用字典 | +| [`src/client/types.ts`](src/client/types.ts) | 浏览器状态、提示、Remote 和 face 类型 | + +
+ +----- + + +## 延伸阅读 + +- [插件管理页](../ui-plugin-manager/README.zh.md)——插件页及其插件包插槽。 +- [客户端包地图](../README.zh.md)——相邻的浏览器 UI 包。 + +----- + + +## 模型体验 + +无,注册表及其界面属于插件页 UI,不增加模型输入。各注册方自行说明其账号启用的工具和技能。 + +#### KV Cache 影响 + +无;注册或移除账号不改变任何模型可见文本。 + +## 已知限制与后续工作 + + + +- 五个显示阶段固定不变;注册方需把其他账号状态映射到其中之一。 +- Host 行加载失败的注册方不显示账号区块;插件页仍会列出该插件包及其加载失败。 +- 每个加载 Web 应用的浏览器都会触发一次对所有空闲账号的检查。 +- 无论是否安装了连接器插件,Web 与桌面端组合都会加载注册表。 +- 调用返回后才打开的授权页可能被浏览器拦截;区块中的打开按钮可以再次打开它。 + + +### 开发备注 + +
+维护者工作上下文——点击展开 + +Host 测试用假的账号来源驱动注册表。客户端测试用假的 Remote 流驱动 `BrowserAccounts`,用中文字典和假的 Remote 渲染各界面,并在真实的插槽注册表和 locale 运行时上挂载浏览器一半。 + +
diff --git a/packages/client/ui-connector-account/locale/de.json b/packages/client/ui-connector-account/locale/de.json new file mode 100644 index 0000000000..98f0f64dea --- /dev/null +++ b/packages/client/ui-connector-account/locale/de.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Connector-Kontoverbindung", + "description": "Kontobereich, Titel-Tag, Aktivierungshinweis und Benachrichtigungen auf der Seite „Plugins“ für Connector-Plugins." + } +} diff --git a/packages/client/ui-connector-account/locale/en.json b/packages/client/ui-connector-account/locale/en.json new file mode 100644 index 0000000000..f0d6ca2f20 --- /dev/null +++ b/packages/client/ui-connector-account/locale/en.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Connector account connection", + "description": "Account section, title tag, activation prompt, and notices on the Plugins page for connector plugins." + } +} diff --git a/packages/client/ui-connector-account/locale/es.json b/packages/client/ui-connector-account/locale/es.json new file mode 100644 index 0000000000..90e3835555 --- /dev/null +++ b/packages/client/ui-connector-account/locale/es.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Conexión de cuenta de conectores", + "description": "Sección de cuenta, etiqueta del título, aviso de activación y notificaciones en la página Complementos para los complementos de conectores." + } +} diff --git a/packages/client/ui-connector-account/locale/fr.json b/packages/client/ui-connector-account/locale/fr.json new file mode 100644 index 0000000000..6aa61577ee --- /dev/null +++ b/packages/client/ui-connector-account/locale/fr.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Connexion de compte de connecteur", + "description": "Section de compte, étiquette de titre, invite d’activation et notifications sur la page Plugins pour les plugins de connecteur." + } +} diff --git a/packages/client/ui-connector-account/locale/ja.json b/packages/client/ui-connector-account/locale/ja.json new file mode 100644 index 0000000000..d8a18a8135 --- /dev/null +++ b/packages/client/ui-connector-account/locale/ja.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "コネクターアカウント接続", + "description": "コネクタープラグイン向けに、「プラグイン」ページでのアカウントセクション、タイトルタグ、有効化時の案内、通知を提供します。" + } +} diff --git a/packages/client/ui-connector-account/locale/pt.json b/packages/client/ui-connector-account/locale/pt.json new file mode 100644 index 0000000000..abec0eafe9 --- /dev/null +++ b/packages/client/ui-connector-account/locale/pt.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Conexão de conta de conector", + "description": "Seção da conta, etiqueta do título, aviso de ativação e notificações na página Plug-ins para plugins de conector." + } +} diff --git a/packages/client/ui-connector-account/locale/ru.json b/packages/client/ui-connector-account/locale/ru.json new file mode 100644 index 0000000000..be0914f34b --- /dev/null +++ b/packages/client/ui-connector-account/locale/ru.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Подключение аккаунта коннектора", + "description": "Раздел аккаунта, метка у заголовка, подсказка при включении и уведомления на странице «Плагины» для плагинов-коннекторов." + } +} diff --git a/packages/client/ui-connector-account/locale/zh.json b/packages/client/ui-connector-account/locale/zh.json new file mode 100644 index 0000000000..af4aade6f6 --- /dev/null +++ b/packages/client/ui-connector-account/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "连接器账号连接", + "description": "在插件页为连接器插件提供账号区块、标题标签、开启引导与提示。" + } +} diff --git a/packages/client/ui-connector-account/package.json b/packages/client/ui-connector-account/package.json new file mode 100644 index 0000000000..a571731e29 --- /dev/null +++ b/packages/client/ui-connector-account/package.json @@ -0,0 +1,96 @@ +{ + "name": "@deepseek-ai/dsh-client-ui-connector-account", + "description": "Connector account surfaces: the Host registry CLI app plugins and MCP connectors register their accounts with, and the Plugins page section, title tag, activation prompt, and notices it serves over one Remote", + "version": "0.2.2-rc.1", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/client/ui-connector-account" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./client": { + "types": "./lib/types/client/index.d.ts", + "default": "./lib/client.js" + }, + "./types": { + "types": "./lib/types/types.d.ts" + }, + "./src/*": "./src/*", + "./package.json": "./package.json", + "./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" + }, + "./locale/*.json": "./locale/*.json" + }, + "dsh": { + "client": { + "inject": [ + "@deepseek-ai/dsh-api-remotes", + "@deepseek-ai/dsh-client-locale", + "@deepseek-ai/dsh-client-ui-layout", + "@deepseek-ai/dsh-client-ui-plugin-manager" + ], + "platform": "web" + } + }, + "scripts": { + "bundle": "tsdown", + "watch": "tsdown --watch" + }, + "license": "MIT", + "dependencies": { + "@deepseek-ai/dsh-typert-protocol": "workspace:*", + "zod": "4.6.6" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:~" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-api-gateway": "workspace:*", + "@deepseek-ai/dsh-api-remotes": "workspace:*", + "@deepseek-ai/dsh-brand": "workspace:*", + "@deepseek-ai/dsh-client-locale": "workspace:*", + "@deepseek-ai/dsh-client-store": "workspace:*", + "@deepseek-ai/dsh-client-test-runtime": "workspace:*", + "@deepseek-ai/dsh-client-ui-layout": "workspace:*", + "@deepseek-ai/dsh-client-ui-plugin-manager": "workspace:*", + "@deepseek-ai/dsh-client-ui-primitives": "workspace:*", + "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", + "@deepseek-ai/dsh-client-ui-slots": "workspace:*", + "@deepseek-ai/dsh-package-manifest": "workspace:*", + "@deepseek-ai/dsh-util-values": "workspace:*", + "@testing-library/react": "^16.3.3", + "react": "^18.2.0", + "react-dom": "^18.2.0" + }, + "files": [ + "locale/*.json", + "lib/index.js", + "lib/client.js", + "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/ui-connector-account/src/client/ConnectorAccount.module.css b/packages/client/ui-connector-account/src/client/ConnectorAccount.module.css new file mode 100644 index 0000000000..c15f495d50 --- /dev/null +++ b/packages/client/ui-connector-account/src/client/ConnectorAccount.module.css @@ -0,0 +1,51 @@ +.section { + display: flex; + flex-direction: column; + gap: 8px; +} + +.title { + margin: 0 0 4px; + font-size: 14px; + line-height: 20px; + font-weight: 500; +} + +.status { + display: flex; + align-items: center; + gap: 8px; + min-height: 28px; +} + +.label { + font-size: 13px; + line-height: 20px; + color: var(--dsw-alias-label-primary); +} + +.actions { + display: flex; + gap: 8px; + margin-left: auto; +} + +.detail, +.hint, +.failure { + margin: 0; + font-size: 13px; + line-height: 20px; +} + +.detail { + color: var(--dsw-alias-label-secondary); +} + +.hint { + color: var(--dsw-alias-label-tertiary); +} + +.failure { + color: var(--dsw-alias-state-error-primary); +} diff --git a/packages/client/ui-connector-account/src/client/components.tsx b/packages/client/ui-connector-account/src/client/components.tsx new file mode 100644 index 0000000000..93bc807582 --- /dev/null +++ b/packages/client/ui-connector-account/src/client/components.tsx @@ -0,0 +1,337 @@ +/** + * The account surfaces the Plugins page shows for registered connector accounts: a bundle's section, title tag, and + * activation prompt, the confirmation a button asks for, and the notice, with the slot entries that read them. + */ +import { useEffect, useRef, useState, type ReactNode } from 'react' +import { Button, IconWarningOutlineRegular, Modal, StateDot, Tag, Toast, type StateDotState, type TagTone } from '@deepseek-ai/dsh-client-ui-primitives' +import type { InjectFace, PropsRuntime, Translate } from '@deepseek-ai/dsh-client-ui-slots' +import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client' +import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' +import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import { assertNever } from '@deepseek-ai/dsh-util-values' +import type { + ConnectorAccountButton, ConnectorAccountCommand, ConnectorAccountEntry, ConnectorAccountFailure, ConnectorAccountPhase, +} from '../types.ts' +import css from './ConnectorAccount.module.css' +import type { ConnectorAccountKey } from './locales.ts' +import { openAuthorizationPage } from './state.ts' +import type { ConnectorAccountFace, ConnectorAccountNotice, ConnectorAccountsState, ConnectorBundleAccountFace } from './types.ts' + +type FaceProps = InjectFace & { t: Translate } +type BundleFaceProps = InjectFace & { t: Translate } +type Resolve = (text: LocalizedText) => string +/** The phase a surface shows: the Host's, or `stopped` once this browser's stream failed for good. */ +type ShownPhase = ConnectorAccountPhase | 'stopped' + +const TONE: Record = { + checking: 'ongoing', connecting: 'ongoing', connected: 'done', disconnected: 'idle', unavailable: 'warning', stopped: 'warning', +} + +const BADGE_TONE: Record = { + checking: 'outline', connecting: 'info', connected: 'success', disconnected: 'outline', unavailable: 'warning', stopped: 'warning', +} + +function shownPhase(entry: ConnectorAccountEntry, stopped: boolean): ShownPhase { + return stopped ? 'stopped' : entry.display.phase +} + +async function settle(call: Promise>): Promise { + const result = await call + if (!result.ok) throw new Error(result.error.message) + return result.value +} + +/** + * Run a section button's command against the Host: start and cancel call the Remote directly, and open shows the + * operation's authorization page again in this browser. + * @param face - the Remote and the browser state the commands report to. + * @returns whether a call this surface made has not answered, and the runner of one account's command. + */ +function useAccountCommand( + face: Pick, +): { readonly busy: boolean; readonly run: (entry: ConnectorAccountEntry, command: ConnectorAccountCommand) => void } { + const [busy, setBusy] = useState(false) + // A second click before the re-render still finds the first call pending. + const pending = useRef(false) + const call = (operation: () => Promise): void => { + if (pending.current) return + pending.current = true + setBusy(true) + // The Host keeps the diagnostic; the page reports one retryable outcome. + void operation().catch(() => { face.failed() }).finally(() => { pending.current = false; setBusy(false) }) + } + const run = (entry: ConnectorAccountEntry, command: ConnectorAccountCommand): void => { + const { key } = entry + switch (command.kind) { + case 'start': + call(async () => { face.follow(key, await settle(face.remote.start(key, command.operation))) }) + return + case 'cancel': { + const operation = entry.operation + if (operation !== undefined) call(async () => { await settle(face.remote.cancel(key, operation.id)) }) + return + } + case 'open': + openAuthorizationPage(entry.operation?.authorizationUrl) + return + /* v8 ignore next -- closed command union */ + default: assertNever(command) + } + } + return { busy, run } +} + +/** What the section shows about one account in this browser. */ +export interface ConnectorAccountSectionProps { + readonly t: Translate + readonly resolveText: Resolve + readonly entry: ConnectorAccountEntry + /** Whether the Host stream is delivering. */ + readonly linked: boolean + /** Whether the Host stream failed for good. */ + readonly stopped: boolean + /** Whether a call the section made has not answered. */ + readonly busy: boolean + readonly onCommand: (command: ConnectorAccountCommand) => void + readonly onRetry: () => void +} + +function describe(t: Translate, failure: ConnectorAccountFailure): string | undefined { + const details = failure.details ?? [] + return details.length === 0 ? undefined : t('failure.details', { details: details.join(' · ') }) +} + +/** + * The account section on a bundle page. + * @param props - the account, the stream state, the command and retry callbacks, and the translators. + * @returns the title, status line, detail, rows, failure, hint, and the confirmation a button asked for. + */ +export function ConnectorAccountSection(props: ConnectorAccountSectionProps): ReactNode { + const { t, resolveText, entry, linked, stopped, busy, onCommand, onRetry } = props + const [confirming, setConfirming] = useState() + const display = entry.display + const phase = shownPhase(entry, stopped) + // Reopening a stopped stream is the one action that does not need the Host stream. + const disabled = busy || (!linked && !stopped) + const button = (item: ConnectorAccountButton): ReactNode => { + const label = resolveText(item.label) + const onClick = item.confirm === undefined ? () => { onCommand(item.command) } : () => { setConfirming(item) } + return + } + const failure = stopped ? undefined : display.failure + const diagnostic = failure === undefined ? undefined : describe(t, failure) + const confirm = confirming?.confirm + return ( +
+

{resolveText(entry.copy.title)}

+
+ + {stopped ? t('status.stopped') : resolveText(display.status)} +
+ {stopped + ? + : display.buttons.map(button)} +
+
+ {stopped + ?

{t('detail.stopped')}

+ : display.detail === undefined ? null :

{resolveText(display.detail)}

} + {stopped ? null : display.notes.map((note) => { + const text = resolveText(note.text) + return ( +
+ {text} + {note.button === undefined ? null :
{button(note.button)}
} +
+ ) + })} + {failure === undefined ? null : ( +

{resolveText(failure.text)}{diagnostic === undefined ? null : <> {diagnostic}}

+ )} +

{resolveText(entry.copy.hint)}

+ {confirming === undefined || confirm === undefined ? null : ( + { setConfirming(undefined) }} + onConfirm={() => { onCommand(confirming.command) }} /> + )} +
+ ) +} + +/** The Plugins page detail the tag sits on: an item page, or a bundle or row page with its package. */ +export type ConnectorAccountBadgeSubject = + | { readonly kind: 'item' } + | { readonly kind: 'bundle' | 'row'; readonly pkg: { readonly name: string; readonly enabled: boolean } } + +/** The tag's phase and text. */ +export interface ConnectorAccountBadgeProps { + readonly phase: ShownPhase + /** The tag's text; absent while nothing is settled. */ + readonly text: string | undefined +} + +/** + * The account tag beside a bundle's title. + * @param props - the account's phase and the tag's text. + * @returns the tag, or null while nothing is settled. + */ +export function ConnectorAccountBadge({ phase, text }: ConnectorAccountBadgeProps): ReactNode { + return text === undefined ? null : {text} +} + +/** The prompt's phase, text, and callbacks. */ +export interface ConnectorAccountActivationProps { + readonly t: Translate + readonly phase: ShownPhase + readonly title: string + readonly body: string + /** The connect button's label. */ + readonly connect: string + readonly onDismiss: () => void + readonly onConnect: () => void +} + +/** + * Guidance after the user switches a bundle on while its account is not connected. + * @param props - the phase, the registrant's text, the dismiss and connect callbacks, and the translator. + * @returns a prompt shown while disconnected; it dismisses itself once the phase settles elsewhere. + */ +export function ConnectorAccountActivation(props: ConnectorAccountActivationProps): ReactNode { + const { t, phase, title, body, connect, onDismiss, onConnect } = props + const needed = phase === 'disconnected' + useEffect(() => { + if (phase !== 'checking' && !needed) onDismiss() + }, [phase, needed, onDismiss]) + return ( + + + + }> +

{body}

+
+ ) +} + +/** A confirmation's text and callbacks, with the translator for the shared buttons. */ +export interface ConnectorAccountConfirmProps { + readonly t: Translate + readonly title: string + readonly body: string + /** The confirm button's label. */ + readonly label: string + readonly onClose: () => void + readonly onConfirm: () => void +} + +/** + * Confirm an action that changes the account outside DSH. + * @param props - the question and the close and confirm callbacks. + * @returns a dialog that closes before it confirms. + */ +export function ConnectorAccountConfirm({ t, title, body, label, onClose, onConfirm }: ConnectorAccountConfirmProps): ReactNode { + return ( + + + + }> +

{body}

+
+ ) +} + +/** The latest notice and its dismissal, with both translators. */ +export interface ConnectorAccountToastProps { + readonly t: Translate + readonly resolveText: Resolve + readonly notice: ConnectorAccountNotice | undefined + readonly onDone: () => void +} + +/** + * Account outcomes reported outside the Plugins panel's lifetime. + * @param props - the latest notice, its dismissal, and the translators. + * @returns the toast for the notice, or null. + */ +export function ConnectorAccountToast({ t, resolveText, notice, onDone }: ConnectorAccountToastProps): ReactNode { + if (notice === undefined) return null + if (notice.kind === 'action-failed') { + return } onDone={onDone} /> + } + return +} + +/** + * The `plugins.bundle.config` entry of a bundle that owns an account. + * @param props - the bundle's face and the translator. + * @returns the section for the account, or null before the Host lists it. + */ +export function ConnectorAccountSectionEntry(props: BundleFaceProps): ReactNode { + const { useConnectorAccounts, account, resolveText, retry, t } = props + const entry = useConnectorAccounts(state => state.accounts.get(account)) + const linked = useConnectorAccounts(state => state.linked) + const stopped = useConnectorAccounts(state => state.stopped) + const { busy, run } = useAccountCommand(props) + if (entry === undefined) return null + return { run(entry, command) }} onRetry={retry} /> +} + +function accountOf(state: ConnectorAccountsState, packageName: string): ConnectorAccountEntry | undefined { + for (const entry of state.accounts.values()) if (entry.packageName === packageName) return entry + return undefined +} + +/** + * The `plugins.detail.badge` entry shared by every bundle that owns an account. + * @param props - the open detail page's subject, the face, and the translator. + * @returns the tag on the page of an enabled bundle that owns an account, or of one of its rows, or null. + */ +export function ConnectorAccountBadgeEntry(props: FaceProps & Pick, 'subject'>): ReactNode { + const { useConnectorAccounts, resolveText, subject, t } = props + const page: ConnectorAccountBadgeSubject = subject + const packageName = page.kind === 'item' || !page.pkg.enabled ? undefined : page.pkg.name + const entry = useConnectorAccounts(state => packageName === undefined ? undefined : accountOf(state, packageName)) + const stopped = useConnectorAccounts(state => state.stopped) + if (entry === undefined) return null + const badge = entry.display.badge + const text = stopped ? t('badge.stopped') : badge === undefined ? undefined : resolveText(badge) + return +} + +/** + * The `plugins.bundle.activation` entry of a bundle that owns an account; Connect opens the bundle page and starts the + * display's `connect` command. + * @param props - activation callbacks, the bundle's face, and the translator. + * @returns the prompt for the account, or null before the Host lists it. + */ +export function ConnectorAccountActivationEntry( + props: BundleFaceProps & Pick, 'onDismiss' | 'onOpenDetails'>, +): ReactNode { + const { useConnectorAccounts, account, resolveText, onDismiss, onOpenDetails, t } = props + const entry = useConnectorAccounts(state => state.accounts.get(account)) + const stopped = useConnectorAccounts(state => state.stopped) + const { run } = useAccountCommand(props) + if (entry === undefined) return null + const { activation } = entry.copy + const { connect } = entry.display + const onConnect = (): void => { + onOpenDetails() + if (connect !== undefined) run(entry, connect) + } + return ( + + ) +} + +/** + * The `shell.overlay` entry. + * @param props - the face and the translator. + * @returns the toast for the latest notice, or null. + */ +export function ConnectorAccountToastEntry({ useConnectorAccounts, resolveText, dismissNotice, t }: FaceProps): ReactNode { + const notice = useConnectorAccounts(state => state.notice) + return +} diff --git a/packages/client/ui-connector-account/src/client/index.ts b/packages/client/ui-connector-account/src/client/index.ts new file mode 100644 index 0000000000..c76264c8f5 --- /dev/null +++ b/packages/client/ui-connector-account/src/client/index.ts @@ -0,0 +1,90 @@ +/** + * Connector account surfaces, browser half: follows the accounts CLI app plugins and MCP connectors register on the Host, + * and shows each bundle's section, title tag, and activation prompt on its Plugins page, with the notices of the + * operations this browser started. The surfaces read the shared copy from this package's dictionary and each + * registrant's text from the Host. + */ +import type { Context } from '@deepseek-ai/cordis' +import type {} from '@deepseek-ai/dsh-api-remotes/client' +import type {} from '@deepseek-ai/dsh-client-locale/client' +import type {} from '@deepseek-ai/dsh-client-ui-layout/client' +import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client' +import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' +import { + ConnectorAccountActivationEntry, ConnectorAccountBadgeEntry, ConnectorAccountSectionEntry, ConnectorAccountToastEntry, +} from './components.tsx' +import { de, en, es, fr, ja, NS, pt, ru, zh } from './locales.ts' +import { BrowserAccounts } from './state.ts' +import type { ConnectorAccountFace } from './types.ts' + +export type { ConnectorAccountKey } from './locales.ts' +export type { + ConnectorAccountFace, ConnectorAccountNotice, ConnectorAccountsState, ConnectorBundleAccountFace, +} from './types.ts' + +/** The `connectorAccounts` Remote that `dsh-api-remotes` mounts, and the services the slot registrations need. */ +export const inject = ['remote', 'remote.connectorAccounts', 'slots', 'locale'] + +function registerBundle(ctx: Context, face: ConnectorAccountFace, packageName: string, account: string): () => void { + const bundle = { ...face, account } + const dispose = ctx.effect(function* () { + yield ctx.slots.inject('plugins.bundle.config', () => ctx.slots.register({ + name: 'plugins.bundle.config', key: packageName, locale: NS, inject: () => bundle, + }, ConnectorAccountSectionEntry)) + yield ctx.slots.inject('plugins.bundle.activation', () => ctx.slots.register({ + name: 'plugins.bundle.activation', key: packageName, locale: NS, inject: () => bundle, + }, ConnectorAccountActivationEntry)) + }, `connector-account: ${packageName}`) + return () => void dispose() +} + +/** + * Show the registered connector accounts for one plugin lifetime: one tag and one notice entry for the page, and a + * section and activation prompt for each bundle that owns an account. + * @param ctx - the browser plugin context. + */ +export function apply(ctx: Context): void { + ctx.effect(() => ctx.locale.register(NS, { zh, en, ja, es, fr, de, ru, pt }), 'connector-account: dictionaries') + const browser = new BrowserAccounts(ctx, ctx.remote.connectorAccounts) + ctx.effect(() => async () => { await browser.dispose() }, 'connector-account: stream') + const face: ConnectorAccountFace = { + hooks: { connectorAccounts: browser.state }, + remote: ctx.remote.connectorAccounts, + resolveText: text => ctx.locale.resolveText(text), + follow: (key, id) => { browser.follow(key, id) }, + failed: () => { browser.failed() }, + retry: () => { browser.retry() }, + dismissNotice: () => { browser.dismissNotice() }, + } + ctx.effect(function* () { + yield ctx.slots.inject('plugins.detail.badge', () => ctx.slots.register({ + name: 'plugins.detail.badge', id: 'connector-account.badge', locale: NS, inject: () => face, + }, ConnectorAccountBadgeEntry)) + yield ctx.slots.inject('shell.overlay', () => ctx.slots.register({ + name: 'shell.overlay', id: 'connector-account.notice', locale: NS, inject: () => face, + }, ConnectorAccountToastEntry)) + }, 'connector-account: page surfaces') + ctx.effect(() => { + const shown = new Map void }>() + const sync = (): void => { + const owned = new Map() + for (const entry of browser.state.getSnapshot().accounts.values()) { + if (entry.packageName !== undefined) owned.set(entry.packageName, entry.key) + } + for (const [packageName, surfaces] of shown) { + if (owned.get(packageName) === surfaces.account) continue + surfaces.withdraw() + shown.delete(packageName) + } + for (const [packageName, account] of owned) { + if (!shown.has(packageName)) shown.set(packageName, { account, withdraw: registerBundle(ctx, face, packageName, account) }) + } + } + sync() + const stop = browser.state.subscribe(sync) + return () => { + stop() + for (const surfaces of shown.values()) surfaces.withdraw() + } + }, 'connector-account: bundle surfaces') +} diff --git a/packages/client/ui-connector-account/src/client/locales.ts b/packages/client/ui-connector-account/src/client/locales.ts new file mode 100644 index 0000000000..57e76d24f1 --- /dev/null +++ b/packages/client/ui-connector-account/src/client/locales.ts @@ -0,0 +1,118 @@ +/** Locale-owned copy the connector account surfaces share; each registrant's own text arrives from the Host. */ +import type {} from '@deepseek-ai/dsh-client-ui-slots' + +/** Dictionary namespace of the shared account copy. */ +export const NS = 'connectorAccount' + +/** Chinese dictionary and key source. */ +export const zh = { + close: '关闭', + 'action.cancel': '取消', + 'action.retry': '重试', + 'activation.later': '稍后', + 'failure.details': '排障信息:{details}', + 'notice.action-failed': '操作未完成,请重试', + 'badge.stopped': '未运行', + 'status.stopped': '账号服务未运行', + 'detail.stopped': '暂时无法读取账号状态,可以重试。', +} + +/** Every key the shared account surfaces translate. */ +export type ConnectorAccountKey = keyof typeof zh + +/** English dictionary. */ +export const en: Record = { + close: 'Close', + 'action.cancel': 'Cancel', + 'action.retry': 'Retry', + 'activation.later': 'Later', + 'failure.details': 'Diagnostic: {details}', + 'notice.action-failed': 'The action did not finish. Try again.', + 'badge.stopped': 'Not running', + 'status.stopped': 'Account service not running', + 'detail.stopped': 'The account status cannot be read right now. Retry to reconnect.', +} + +/** Japanese dictionary. */ +export const ja: Record = { + close: '閉じる', + 'action.cancel': 'キャンセル', + 'action.retry': '再試行', + 'activation.later': '後で', + 'failure.details': '診断情報:{details}', + 'notice.action-failed': '操作が完了しませんでした。もう一度お試しください。', + 'badge.stopped': '未稼働', + 'status.stopped': 'アカウントサービスが稼働していません', + 'detail.stopped': 'アカウントの状態を現在読み取れません。再試行して再接続してください。', +} + +/** Spanish dictionary. */ +export const es: Record = { + close: 'Cerrar', + 'action.cancel': 'Cancelar', + 'action.retry': 'Reintentar', + 'activation.later': 'Más tarde', + 'failure.details': 'Diagnóstico: {details}', + 'notice.action-failed': 'La acción no se completó. Inténtelo de nuevo.', + 'badge.stopped': 'No está en ejecución', + 'status.stopped': 'El servicio de cuentas no está en ejecución', + 'detail.stopped': 'No se puede leer el estado de la cuenta en este momento. Reintente para volver a conectar.', +} + +/** French dictionary. */ +export const fr: Record = { + close: 'Fermer', + 'action.cancel': 'Annuler', + 'action.retry': 'Réessayer', + 'activation.later': 'Plus tard', + 'failure.details': 'Diagnostic : {details}', + 'notice.action-failed': 'L’action n’a pas abouti. Réessayez.', + 'badge.stopped': 'Ne fonctionne pas', + 'status.stopped': 'Le service de comptes ne fonctionne pas', + 'detail.stopped': 'L’état du compte ne peut pas être lu pour le moment. Réessayez pour vous reconnecter.', +} + +/** German dictionary. */ +export const de: Record = { + close: 'Schließen', + 'action.cancel': 'Abbrechen', + 'action.retry': 'Erneut versuchen', + 'activation.later': 'Später', + 'failure.details': 'Diagnose: {details}', + 'notice.action-failed': 'Die Aktion wurde nicht abgeschlossen. Versuchen Sie es erneut.', + 'badge.stopped': 'Läuft nicht', + 'status.stopped': 'Kontodienst läuft nicht', + 'detail.stopped': 'Der Kontostatus kann gerade nicht gelesen werden. Versuchen Sie es erneut, um die Verbindung wiederherzustellen.', +} + +/** Russian dictionary. */ +export const ru: Record = { + close: 'Закрыть', + 'action.cancel': 'Отмена', + 'action.retry': 'Повторить', + 'activation.later': 'Позже', + 'failure.details': 'Диагностика: {details}', + 'notice.action-failed': 'Действие не завершено. Повторите попытку.', + 'badge.stopped': 'Не работает', + 'status.stopped': 'Служба аккаунтов не работает', + 'detail.stopped': 'Сейчас не удаётся прочитать состояние аккаунта. Повторите попытку, чтобы переподключиться.', +} + +/** Portuguese dictionary. */ +export const pt: Record = { + close: 'Fechar', + 'action.cancel': 'Cancelar', + 'action.retry': 'Tentar novamente', + 'activation.later': 'Mais tarde', + 'failure.details': 'Diagnóstico: {details}', + 'notice.action-failed': 'A ação não foi concluída. Tente novamente.', + 'badge.stopped': 'Não está em execução', + 'status.stopped': 'O serviço de contas não está em execução', + 'detail.stopped': 'Não é possível ler o estado da conta agora. Tente novamente para reconectar.', +} + +declare module '@deepseek-ai/dsh-client-ui-slots' { + interface LocaleNamespaceMap { + connectorAccount: ConnectorAccountKey + } +} diff --git a/packages/client/ui-connector-account/src/client/state.ts b/packages/client/ui-connector-account/src/client/state.ts new file mode 100644 index 0000000000..2d4954ddb8 --- /dev/null +++ b/packages/client/ui-connector-account/src/client/state.ts @@ -0,0 +1,157 @@ +/** + * The page's one subscription to the registered accounts, and what only this browser knows about them: the operations + * it started, whose authorization pages open here, and the notice to show. + */ +import type { Context } from '@deepseek-ai/cordis' +import type { RemoteStream } from '@deepseek-ai/dsh-api-gateway/client' +import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' +import type { ConnectorAccountEntry, ConnectorAccountsView, ConnectorOperationId } from '../types.ts' +import type { ConnectorAccountNotice, ConnectorAccountsRemote, ConnectorAccountsState } from './types.ts' + +const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '[::1]']) + +/** + * Open an authorization page in a new tab when it is HTTPS, or HTTP on a loopback address such as a local + * authorization server. + * @param url - the page an operation waits on; other values open nothing. + */ +export function openAuthorizationPage(url: string | undefined): void { + if (url === undefined || !URL.canParse(url)) return + const parsed = new URL(url) + if (parsed.protocol === 'https:' || (parsed.protocol === 'http:' && LOOPBACK_HOSTS.has(parsed.hostname))) { + window.open(url, '_blank', 'noopener,noreferrer') + } +} + +/** One Host subscription per browser, shared by every account surface on the page. */ +export class BrowserAccounts { + /** The accounts, stream state, and notice every surface on the page reads. */ + readonly state: SnapshotStore = createSnapshotStore({ + accounts: new Map(), linked: true, stopped: false, notice: undefined, + }) + + /** + * The operation each account's latest start in this browser returned, with the pages already opened for it. It lasts + * until the stream delivers its result or the account leaves. + */ + private readonly followed = new Map }>() + private seq = 0 + private disposed = false + private stream!: RemoteStream + private observing!: Promise + + /** + * @param ctx - the browser context carrying the Remote client. + * @param remote - the `connectorAccounts` Remote. + */ + constructor(private readonly ctx: Context, private readonly remote: Pick) { + this.subscribe() + } + + /** + * Follow an operation this browser started, replacing the account's previous one. + * @param key - the account key. + * @param id - the operation the Host started. + */ + follow(key: string, id: ConnectorOperationId): void { + if (this.disposed) return + this.followed.set(key, { id, opened: new Set() }) + // The stream may have delivered the operation before the start call answered. + const entry = this.state.getSnapshot().accounts.get(key) + if (entry !== undefined) this.track(entry) + } + + /** Report that a Remote call this browser made did not finish; the Host keeps the diagnostic. */ + failed(): void { + this.notify({ kind: 'action-failed' }) + } + + /** Clear the notice once it has been shown. */ + dismissNotice(): void { + this.patch({ notice: undefined }) + } + + /** Reopen the Host stream after it stopped; ignored while it runs, while a reopen is pending, or after disposal. */ + retry(): void { + if (this.disposed || !this.state.getSnapshot().stopped) return + // Clearing `stopped` before the reopen awaits claims it, so a second retry finds nothing to reopen. + this.patch({ stopped: false }) + void this.reopen() + } + + /** + * Stop observing the Host; afterwards the page opens no page, reports nothing more, and a pending retry opens no stream. + * Host-owned operations keep running. + * @returns after the stream closes. + */ + async dispose(): Promise { + this.disposed = true + await this.stream.dispose() + await this.observing + } + + private subscribe(): void { + this.stream = this.ctx.remote.$stream({ + name: 'Connector accounts', open: signal => this.remote.watch(signal), + ended: () => new Error('Connector accounts stream ended'), + carrierFailed: () => { this.patch({ linked: false }) }, + }) + this.observing = this.observe(this.stream) + } + + private async observe(stream: RemoteStream): Promise { + try { + for await (const item of stream) { + // An item the stream yielded just before disposal must not reach the disposed page. + if (this.disposed) return + this.show(item.value.accounts) + item.accept() + } + } catch { + // A terminal failure, such as a Host without the registry, ends the stream; a disposed page shows nothing. + if (!this.disposed) this.patch({ linked: false, stopped: true }) + } + } + + private async reopen(): Promise { + await this.stream.dispose() + await this.observing + if (!this.disposed) this.subscribe() + } + + private show(entries: readonly ConnectorAccountEntry[]): void { + const accounts = new Map(entries.map(entry => [entry.key, entry])) + for (const key of [...this.followed.keys()]) if (!accounts.has(key)) this.followed.delete(key) + this.patch({ accounts, linked: true, stopped: false }) + for (const entry of entries) this.track(entry) + } + + /** Open each new page of the account's followed operation once, and report its success once its result arrives. */ + private track(entry: ConnectorAccountEntry): void { + const followed = this.followed.get(entry.key) + if (followed === undefined) return + const url = entry.operation?.id === followed.id ? entry.operation.authorizationUrl : undefined + if (url !== undefined && !followed.opened.has(url)) { + followed.opened.add(url) + openAuthorizationPage(url) + } + const result = entry.result + if (result?.id !== followed.id) return + this.followed.delete(entry.key) + if (result.notice !== undefined) this.notify({ kind: 'succeeded', text: result.notice }) + } + + private notify( + notice: { readonly kind: 'succeeded'; readonly text: LocalizedText } | { readonly kind: 'action-failed' }, + ): void { + if (this.disposed) return + this.seq += 1 + const next: ConnectorAccountNotice = { ...notice, seq: this.seq } + this.patch({ notice: next }) + } + + private patch(change: Partial): void { + this.state.set({ ...this.state.getSnapshot(), ...change }) + } +} diff --git a/packages/client/ui-connector-account/src/client/types.ts b/packages/client/ui-connector-account/src/client/types.ts new file mode 100644 index 0000000000..8ed18a7c81 --- /dev/null +++ b/packages/client/ui-connector-account/src/client/types.ts @@ -0,0 +1,50 @@ +/** Browser-side state and face of the accounts the Plugins page shows. */ +import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots' +import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' +import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import type { ConnectorAccountEntry, ConnectorAccountsView, ConnectorOperationId } from '../types.ts' + +/** A transient outcome the page reports outside its own lifetime; `seq` distinguishes repeats. */ +export type ConnectorAccountNotice = + | { readonly seq: number; readonly kind: 'succeeded'; readonly text: LocalizedText } + | { readonly seq: number; readonly kind: 'action-failed' } + +/** What this browser shows: the Host's accounts, the stream state, and the latest notice. */ +export interface ConnectorAccountsState { + /** Registered accounts by key, as the Host last published them. */ + readonly accounts: ReadonlyMap + /** Whether the Host stream is delivering. */ + readonly linked: boolean + /** Whether the Host stream failed for good; `retry` reopens it. */ + readonly stopped: boolean + readonly notice: ConnectorAccountNotice | undefined +} + +/** The `connectorAccounts` Remote methods the page uses. */ +export interface ConnectorAccountsRemote { + watch(signal: AbortSignal): AsyncIterable + start(key: string, operation: string): Promise> + cancel(key: string, id: ConnectorOperationId): Promise> +} + +/** The face every surface entry injects. */ +export interface ConnectorAccountFace { + hooks: { connectorAccounts: HostObservable } + /** The Remote the buttons call directly. */ + readonly remote: Pick + /** Pick the active language's entry of a registrant's text. */ + readonly resolveText: (text: LocalizedText) => string + /** Remember an operation this browser started: its authorization page opens here, and its success is reported here. */ + readonly follow: (key: string, id: ConnectorOperationId) => void + /** Report that a Remote call this browser made did not finish. */ + readonly failed: () => void + /** Reopen the Host stream after it stopped. */ + readonly retry: () => void + readonly dismissNotice: () => void +} + +/** The face of a bundle's own surfaces, which show the bundle's account. */ +export interface ConnectorBundleAccountFace extends ConnectorAccountFace { + /** The key of the account the bundle owns. */ + readonly account: string +} diff --git a/packages/client/ui-connector-account/src/css-modules.d.ts b/packages/client/ui-connector-account/src/css-modules.d.ts new file mode 100644 index 0000000000..bc5e482353 --- /dev/null +++ b/packages/client/ui-connector-account/src/css-modules.d.ts @@ -0,0 +1,6 @@ +declare module '*.module.css' { + const classes: Record + export default classes +} + +declare module '*.css' diff --git a/packages/client/ui-connector-account/src/index.ts b/packages/client/ui-connector-account/src/index.ts new file mode 100644 index 0000000000..691e56d90a --- /dev/null +++ b/packages/client/ui-connector-account/src/index.ts @@ -0,0 +1,163 @@ +/** + * Connector account surfaces, Host half. CLI app plugins and MCP connectors register their accounts with + * `ctx.connectorAccounts`; the Plugins page follows every registered account through the `connectorAccounts` Remote and + * starts or cancels operations through it, so the browser never learns how an account connects. + * @module @deepseek-ai/dsh-client-ui-connector-account + */ + +import type { Context } from '@deepseek-ai/cordis' +import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' +import type { + AnyConnectorAccountView, ConnectorAccountEntry, ConnectorAccountRegistration, ConnectorAccountsView, ConnectorOperationId, +} from './types.ts' + +export type * from './types.ts' + +declare module '@deepseek-ai/cordis' { + interface Context { + /** Connector accounts on the Plugins page. */ + connectorAccounts: ConnectorAccounts + } +} + +interface Registered { + readonly packageName: string | undefined + readonly entry: () => ConnectorAccountEntry + readonly refresh: () => void + readonly start: (operation: string) => ConnectorOperationId + readonly cancel: (id: ConnectorOperationId) => Promise +} + +function registeredOf(registration: ConnectorAccountRegistration): Registered { + const { key, packageName, source, operations, copy, present } = registration + return { + packageName, + entry: () => { + const view = source.snapshot() + const { operation, result } = view + const notice = result?.outcome === 'succeeded' ? operations.find(candidate => candidate.kind === result.kind)?.notice : undefined + return { + key, ...packageName === undefined ? {} : { packageName }, copy, display: present(view), + ...operation === undefined ? {} : { + operation: { + id: operation.id, ...operation.authorizationUrl === undefined ? {} : { authorizationUrl: operation.authorizationUrl }, + }, + }, + ...result === undefined ? {} : { result: { id: result.id, ...notice === undefined ? {} : { notice } } }, + } + }, + refresh: () => { source.refresh() }, + start: (operation) => { + const kind = operations.find(candidate => candidate.kind === operation)?.kind + if (kind === undefined) throw new Error(`connectorAccounts: ${key} has no page operation ${operation}`) + return source.start(kind) + }, + cancel: id => source.cancel(id), + } +} + +/** Holds the registered accounts and serves them to the Plugins page. */ +export default class ConnectorAccounts extends TypertRemoteService { + private readonly accounts = new Map() + private readonly listeners = new Set<() => void>() + private readonly lifetime = new AbortController() + private subscribers = 0 + + /** @param ctx - the Host context the registry serves the page from. */ + constructor(ctx: Context) { + super(ctx, 'connectorAccounts') + ctx.effect(() => () => { this.lifetime.abort(new Error('connectorAccounts: registry disposed')) }) + } + + /** + * Show one account on the Plugins page for as long as the returned disposer has not run. + * @param registration - the account key, its bundle package, the account source, the page operations, and the + * presentation. + * @returns an idempotent disposer that withdraws the account. + * @throws when another account already uses the key or the package. + */ + register(registration: ConnectorAccountRegistration): () => void { + const { key, packageName } = registration + if (this.accounts.has(key)) throw new Error(`connectorAccounts: ${key} is already registered`) + if (packageName !== undefined && [...this.accounts.values()].some(account => account.packageName === packageName)) { + throw new Error(`connectorAccounts: ${packageName} already has an account`) + } + this.accounts.set(key, registeredOf(registration)) + const stop = registration.source.observe(() => { this.changed() }) + // A page that already follows the accounts checks a newly registered one, as it checks each account it subscribes to. + if (this.subscribers > 0) registration.source.refresh() + this.changed() + let active = true + return () => { + if (!active) return + active = false + stop() + this.accounts.delete(key) + this.changed() + } + } + + /** + * Follow every registered account; each new subscriber starts a check of each account that runs no operation. + * @param signal - the Client's observation lifetime; disposal also ends the stream. + * @returns the current accounts, then each changed set, coalescing changes that arrive before the next read. + */ + @Remote({ mode: 'stream' }) + async *watch(signal: AbortSignal): AsyncIterable { + const combined = AbortSignal.any([signal, this.lifetime.signal]) + let wake = Promise.withResolvers() + let changed = true + const notify = (): void => { changed = true; wake.resolve() } + this.listeners.add(notify) + combined.addEventListener('abort', notify, { once: true }) + this.subscribers += 1 + try { + for (const account of this.accounts.values()) account.refresh() + for (;;) { + if (!changed) await wake.promise + if (combined.aborted) break + wake = Promise.withResolvers() + changed = false + yield { accounts: [...this.accounts.values()].map(account => account.entry()) } + } + } finally { + this.subscribers -= 1 + this.listeners.delete(notify) + combined.removeEventListener('abort', notify) + } + } + + /** + * Start one of the operations the account registered as page actions. + * @param key - the account key. + * @param operation - the operation kind. + * @returns the operation identity. + * @throws for an unknown account or operation, or whatever the account's source refuses, such as a second operation. + */ + @Remote + start(key: string, operation: string): ConnectorOperationId { + return this.account(key).start(operation) + } + + /** + * Cancel one operation while its phase is cancellable, and wait for it to settle. + * @param key - the account key. + * @param id - the operation to cancel; a finished one or a phase that is not cancellable is ignored. + * @returns after the operation settles, or at once when nothing is cancelled. + * @throws for an unknown account. + */ + @Remote + cancel(key: string, id: ConnectorOperationId): Promise { + return this.account(key).cancel(id) + } + + private account(key: string): Registered { + const account = this.accounts.get(key) + if (account === undefined) throw new Error(`connectorAccounts: ${key} is not registered`) + return account + } + + private changed(): void { + for (const notify of this.listeners) notify() + } +} diff --git a/packages/client/ui-connector-account/src/types.ts b/packages/client/ui-connector-account/src/types.ts new file mode 100644 index 0000000000..a04cbf4a1d --- /dev/null +++ b/packages/client/ui-connector-account/src/types.ts @@ -0,0 +1,164 @@ +/** + * Credential-free account views of connector plugins, and what the Plugins page receives about them. Each registrant + * supplies its own account, operation, phase, and failure types and maps its views to the page's display, so CLI app + * plugins and MCP connectors share one registry and one page. + */ + +import type { Branded } from '@deepseek-ai/dsh-brand' +import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' + +/** Identifies one Host-owned account operation across the browsers that show the account. */ +export type ConnectorOperationId = Branded<'ConnectorOperationId'> + +/** The account operation in progress; `Phase` names the registrant's own steps. */ +export interface ConnectorOperation { + readonly id: ConnectorOperationId + readonly kind: Kind + readonly phase: Phase + /** Whether the source cancels the operation in its current phase. */ + readonly cancellable: boolean + /** The page the user authorizes in, while the operation waits for one; only the browser that started it opens it. */ + readonly authorizationUrl?: string +} + +/** The most recent finished operation, kept until another one starts. */ +export interface ConnectorOperationResult { + readonly id: ConnectorOperationId + readonly kind: Kind + readonly outcome: 'succeeded' | 'cancelled' | 'failed' + /** The registrant's classified failure, for its own presentation; does not imply rollback or a safe retry. */ + readonly failure?: Failure +} + +/** The complete account view; observers reread it after each change. */ +export interface ConnectorAccountView { + /** The account as the source last published it. */ + readonly account: Account + readonly operation?: ConnectorOperation + readonly result?: ConnectorOperationResult +} + +/** Any registrant's account view. */ +export type AnyConnectorAccountView = ConnectorAccountView + +/** The operation kinds a view reports. */ +export type ConnectorOperationKindOf = NonNullable['kind'] + +/** What the Plugins page shows about an account; each registrant maps its own account states onto these phases. */ +export type ConnectorAccountPhase = 'checking' | 'connecting' | 'connected' | 'disconnected' | 'unavailable' + +/** What a section button does. */ +export type ConnectorAccountCommand = + /** Start one of the operations the account registered as page actions. */ + | { readonly kind: 'start'; readonly operation: string } + /** Cancel the operation in progress when it is cancellable. */ + | { readonly kind: 'cancel' } + /** Open the current operation's authorization page again in this browser. */ + | { readonly kind: 'open' } + +/** The question a button asks before it runs. */ +export interface ConnectorAccountConfirmation { + readonly title: LocalizedText + readonly body: LocalizedText + /** The confirm button's label. */ + readonly label: LocalizedText +} + +/** One button in the section. */ +export interface ConnectorAccountButton { + readonly label: LocalizedText + readonly command: ConnectorAccountCommand + /** Defaults to an outline button. */ + readonly variant?: 'primary' | 'ghost' + /** Ask first, for an action that changes the account outside DSH, such as signing out. */ + readonly confirm?: ConnectorAccountConfirmation +} + +/** One extra row under the status line, such as the linked app, with an optional button. */ +export interface ConnectorAccountNote { + readonly text: LocalizedText + readonly button?: ConnectorAccountButton +} + +/** A failed operation as the section reports it. */ +export interface ConnectorAccountFailure { + /** The registrant's recovery guidance. */ + readonly text: LocalizedText + /** Untranslated diagnostic items shown after the guidance in order. */ + readonly details?: readonly string[] +} + +/** What the section shows for the current view; every text carries each shipped language. */ +export interface ConnectorAccountDisplay { + readonly phase: ConnectorAccountPhase + readonly status: LocalizedText + /** The tag beside the bundle title; absent while nothing is settled. */ + readonly badge?: LocalizedText + readonly buttons: readonly ConnectorAccountButton[] + /** What Connect in the activation prompt starts after opening the bundle page; absent, Connect only opens the page. */ + readonly connect?: Extract + readonly detail?: LocalizedText + readonly notes: readonly ConnectorAccountNote[] + readonly failure?: ConnectorAccountFailure +} + +/** The section's fixed text that names the service or uses its wording. */ +export interface ConnectorAccountCopy { + readonly title: LocalizedText + /** The line under the section, such as where the account is shared or authorized. */ + readonly hint: LocalizedText + /** The prompt after the bundle is switched on while the account is disconnected. */ + readonly activation: { readonly title: LocalizedText; readonly body: LocalizedText; readonly connect: LocalizedText } +} + +/** One registered account as the Plugins page receives it. */ +export interface ConnectorAccountEntry { + /** The registrant's stable account key, which the page passes back to start and cancel operations. */ + readonly key: string + /** npm package whose bundle page carries the section and tag; absent for an account no bundle owns. */ + readonly packageName?: string + readonly copy: ConnectorAccountCopy + readonly display: ConnectorAccountDisplay + /** The operation in progress, which a browser follows when it started it. */ + readonly operation?: { readonly id: ConnectorOperationId; readonly authorizationUrl?: string } + /** The most recent finished operation, with the registrant's text when it succeeded. */ + readonly result?: { readonly id: ConnectorOperationId; readonly notice?: LocalizedText } +} + +/** Every registered account, as each change publishes it. */ +export interface ConnectorAccountsView { + readonly accounts: readonly ConnectorAccountEntry[] +} + +/** The account a registration exposes to the page. */ +export interface ConnectorAccountSource { + snapshot(): View + /** @returns a disposer; the listener runs after each change without starting a check. */ + observe(listener: () => void): () => void + /** Start a check unless an operation runs; a source whose view is always current does nothing. */ + refresh(): void + /** @returns the started operation's identity. */ + start(kind: ConnectorOperationKindOf): ConnectorOperationId + /** @returns after the named operation settles, or at once when it is not cancellable. */ + cancel(id: ConnectorOperationId): Promise +} + +/** One operation a page button may start, with the text its success reports in the browser that started it. */ +export interface ConnectorAccountOperation { + readonly kind: Kind + readonly notice?: LocalizedText +} + +/** One connector account, registered with the Host's `ctx.connectorAccounts`. */ +export interface ConnectorAccountRegistration { + /** Stable key, unique among registered accounts, such as the bundle's package name. */ + readonly key: string + /** npm package whose bundle page carries the section and tag; at most one account per package. */ + readonly packageName?: string + readonly source: ConnectorAccountSource + /** The operations a page button may start; the registry rejects any other. */ + readonly operations: readonly ConnectorAccountOperation>[] + readonly copy: ConnectorAccountCopy + /** Map the current view to what the section shows; called on each change for each subscriber. */ + readonly present: (view: View) => ConnectorAccountDisplay +} diff --git a/packages/client/ui-connector-account/tests/apply.client.spec.ts b/packages/client/ui-connector-account/tests/apply.client.spec.ts new file mode 100644 index 0000000000..20481db45e --- /dev/null +++ b/packages/client/ui-connector-account/tests/apply.client.spec.ts @@ -0,0 +1,156 @@ +/** + * The browser plugin shows one tag and one notice entry for the page, and a section and activation prompt for each bundle + * that owns an account, withdrawing them with the account or the plugin. + */ +import assert from 'node:assert/strict' +import { Context, Service } from '@deepseek-ai/cordis' +import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' +import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' +import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import { expect, it, onTestFinished, vi } from 'vitest' +import { + ConnectorAccountActivationEntry, ConnectorAccountBadgeEntry, ConnectorAccountSectionEntry, ConnectorAccountToastEntry, +} from '../src/client/components.tsx' +import { NS } from '../src/client/locales.ts' +import { apply, inject } from '../src/client/index.ts' +import type { ConnectorAccountFace, ConnectorBundleAccountFace } from '../src/client/types.ts' +import type { ConnectorAccountEntry, ConnectorAccountsView, ConnectorOperationId } from '../src/types.ts' + +const FIXTURE = '@acme/fixture' +const OTHER = '@acme/other' +const OP = 'op-1' as ConnectorOperationId + +function isFace(value: Record): asserts value is Record & ConnectorAccountFace { + assert(typeof value.resolveText === 'function' && typeof value.follow === 'function' && typeof value.remote === 'object') + assert(typeof value.hooks === 'object' && value.hooks !== null) +} + +/** Read the face a slot entry injects. */ +function faceOf(item: { readonly inject?: (() => Record) | undefined }): ConnectorAccountFace { + assert(item.inject !== undefined) + const face = item.inject() + isFace(face) + return face +} + +function bundleFaceOf(item: { readonly inject?: (() => Record) | undefined }): ConnectorBundleAccountFace { + const face = faceOf(item) + assert('account' in face && typeof face.account === 'string') + return face as ConnectorBundleAccountFace +} + +function entry(key: string, packageName: string | null = key): ConnectorAccountEntry { + return { + key, ...packageName === null ? {} : { packageName }, + copy: { title: 'Fixture account', hint: 'Shared.', activation: { title: 'Connect', body: 'On.', connect: 'Connect' } }, + display: { phase: 'disconnected', status: 'Not connected', buttons: [], notes: [] }, + } +} + +async function bench() { + const ctx = new Context() + onTestFinished(async () => { await ctx.fiber.dispose() }) + const queue: ConnectorAccountsView[] = [] + let wake: (() => void) | undefined, closed = false, accepted = 0 + const closeStream = vi.fn(async () => { closed = true; wake?.() }) + const start = vi.fn(async (_key: string, _operation: string): Promise> => ({ ok: true, value: OP })) + class Remote extends Service { + constructor() { super(ctx, 'remote') } + $stream() { + return { + async *[Symbol.asyncIterator]() { + for (;;) { + const next = queue.shift() + if (next !== undefined) { yield { value: next, accept: () => { accepted++ } }; continue } + if (closed) return + await new Promise((resolve) => { wake = resolve }) + } + }, + dispose: closeStream, + } + } + } + new Remote() + ctx.provide('remote.connectorAccounts', { watch: vi.fn(), start, cancel: vi.fn() }) + const locale = new LocaleRuntime(ctx) + ctx.provide('locale', locale) + await ctx.plugin(SlotRegistry) + ctx.slots.register({ name: 'root', children: { + 'plugins.bundle.activation': { kind: 'keyed', scope: 'root' }, + 'plugins.bundle.config': { kind: 'keyed', scope: 'root' }, + 'plugins.detail.badge': { kind: 'list', scope: 'root' }, + 'shell.overlay': { kind: 'list', scope: 'root' }, + } } as never, () => null) + const bundles = (slot: 'plugins.bundle.config' | 'plugins.bundle.activation') => + ctx.slots.entries(slot).map(item => [item.options.key, bundleFaceOf(item).account]) + return { + ctx, locale, start, closeStream, bundles, + mount: () => ctx.plugin({ inject: [...inject], apply }), + async publish(...entries: ConnectorAccountEntry[]) { + const target = accepted + 1 + queue.push({ accounts: entries }) + wake?.() + await vi.waitFor(() => { expect(accepted).toBe(target) }) + }, + } +} + +it('shows one tag and one notice entry for the page and each bundle\'s section and prompt under the shared dictionary', async () => { + const b = await bench() + await b.mount() + expect(b.locale.bind(NS)('action.retry')).toBe('Retry') + expect(b.ctx.slots.entries('plugins.detail.badge').map(item => [item.options.id, item.component])).toEqual([ + ['connector-account.badge', ConnectorAccountBadgeEntry], + ]) + expect(b.ctx.slots.entries('shell.overlay').map(item => [item.options.id, item.component])).toEqual([ + ['connector-account.notice', ConnectorAccountToastEntry], + ]) + expect(b.bundles('plugins.bundle.config')).toEqual([]) + + // An account no bundle owns gets no bundle surfaces. + await b.publish(entry(FIXTURE), entry(OTHER), entry('mcp:custom', null)) + expect(b.bundles('plugins.bundle.config')).toEqual([[FIXTURE, FIXTURE], [OTHER, OTHER]]) + expect(b.bundles('plugins.bundle.activation')).toEqual([[FIXTURE, FIXTURE], [OTHER, OTHER]]) + const [section] = b.ctx.slots.entries('plugins.bundle.config') + assert(section !== undefined) + expect(section).toMatchObject({ locale: NS, component: ConnectorAccountSectionEntry }) + expect(b.ctx.slots.entries('plugins.bundle.activation')[0]).toMatchObject({ locale: NS, component: ConnectorAccountActivationEntry }) + const face = bundleFaceOf(section) + const [badge] = b.ctx.slots.entries('plugins.detail.badge') + assert(badge !== undefined) + const [toast] = b.ctx.slots.entries('shell.overlay') + assert(toast !== undefined) + expect(faceOf(badge).hooks.connectorAccounts).toBe(face.hooks.connectorAccounts) + expect(faceOf(toast).hooks.connectorAccounts).toBe(face.hooks.connectorAccounts) + expect([...face.hooks.connectorAccounts.getSnapshot().accounts.keys()]).toEqual([FIXTURE, OTHER, 'mcp:custom']) + expect(face.resolveText({ en: 'Connected', zh: '已连接' })).toBe('Connected') + await face.remote.start(FIXTURE, 'connect') + expect(b.start).toHaveBeenCalledWith(FIXTURE, 'connect') + face.follow(FIXTURE, OP) + face.failed() + expect(face.hooks.connectorAccounts.getSnapshot().notice).toEqual({ seq: 1, kind: 'action-failed' }) + face.dismissNotice() + face.retry() + expect(face.hooks.connectorAccounts.getSnapshot().notice).toBeUndefined() + + // A dropped account withdraws its bundle's surfaces, and a bundle whose account changed key shows the new one. + await b.publish(entry(OTHER)) + expect(b.bundles('plugins.bundle.config')).toEqual([[OTHER, OTHER]]) + await b.publish(entry('mcp:other', OTHER)) + expect(b.bundles('plugins.bundle.config')).toEqual([[OTHER, 'mcp:other']]) + expect(b.bundles('plugins.bundle.activation')).toEqual([[OTHER, 'mcp:other']]) +}) + +it('withdraws every surface, the dictionaries, and the stream when the plugin unloads', async () => { + const b = await bench() + const fiber = b.mount() + await fiber + await b.publish(entry(FIXTURE), entry(OTHER)) + expect(b.bundles('plugins.bundle.config')).toHaveLength(2) + await fiber.dispose() + for (const slot of ['plugins.bundle.config', 'plugins.bundle.activation', 'plugins.detail.badge', 'shell.overlay'] as const) { + expect(b.ctx.slots.entries(slot)).toEqual([]) + } + expect(b.locale.bind(NS)('action.retry')).toBe('action.retry') + expect(b.closeStream).toHaveBeenCalledOnce() +}) diff --git a/packages/client/ui-connector-account/tests/components.client.spec.tsx b/packages/client/ui-connector-account/tests/components.client.spec.tsx new file mode 100644 index 0000000000..c84907ffed --- /dev/null +++ b/packages/client/ui-connector-account/tests/components.client.spec.tsx @@ -0,0 +1,264 @@ +// @vitest-environment jsdom +/** The surfaces render each registrant's display from the Host with the shared copy, and buttons call the Remote directly. */ +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import type { PluginsSubject } from '@deepseek-ai/dsh-client-ui-plugin-manager/client' +import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' +import { RemoteError, type RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import { afterEach, expect, it, onTestFinished, vi } from 'vitest' +import { + ConnectorAccountActivation, ConnectorAccountActivationEntry, ConnectorAccountBadgeEntry, ConnectorAccountSection, + ConnectorAccountSectionEntry, ConnectorAccountToast, ConnectorAccountToastEntry, +} from '../src/client/components.tsx' +import { zh } from '../src/client/locales.ts' +import type { ConnectorAccountsState } from '../src/client/types.ts' +import type { ConnectorAccountDisplay, ConnectorAccountEntry, ConnectorOperationId } from '../src/types.ts' + +afterEach(cleanup) + +const KEY = '@acme/fixture' +const OP = 'op-1' as ConnectorOperationId +const t = makeTranslate(zh) +const resolveText = (text: LocalizedText): string => typeof text === 'string' ? text : text.zh ?? text.en +const button = (name: string) => screen.getByRole('button', { name }) +const disabled = (): boolean[] => screen.getAllByRole('button').map(element => (element as HTMLButtonElement).disabled) + +const DISCONNECTED: ConnectorAccountDisplay = { + phase: 'disconnected', status: { en: 'Not connected', zh: '未连接' }, badge: '未连接', + buttons: [{ label: '连接演示', command: { kind: 'start', operation: 'connect' }, variant: 'primary' }], notes: [], +} + +function entry(display: ConnectorAccountDisplay = DISCONNECTED, extra: Partial = {}): ConnectorAccountEntry { + return { + key: KEY, packageName: KEY, display, + copy: { title: { en: 'Fixture account', zh: '演示账号' }, hint: '与终端共用。', activation: { title: '连接演示', body: '插件已开启。', connect: '连接演示' } }, + ...extra, + } +} + +function section(change: Partial<{ linked: boolean; stopped: boolean; busy: boolean }> = {}, display?: ConnectorAccountDisplay) { + const onCommand = vi.fn() + const onRetry = vi.fn() + const view = render( + , + ) + return { ...view, onCommand, onRetry } +} + +it('shows the registrant title, status, detail, notes, and hint, and runs each button as its command', () => { + const display: ConnectorAccountDisplay = { + ...DISCONNECTED, detail: '先关联一个应用。', + notes: [{ text: '应用:cli_a', button: { label: '更换', command: { kind: 'start', operation: 'link-app' }, variant: 'ghost' } }, { text: '普通说明' }], + } + const { container, onCommand } = section({}, display) + expect(screen.getByText('演示账号')).toBeTruthy() + expect(screen.getByText('未连接')).toBeTruthy() + expect(screen.getByText('先关联一个应用。')).toBeTruthy() + expect(screen.getByText('普通说明')).toBeTruthy() + expect(screen.getByText('与终端共用。')).toBeTruthy() + expect(container.querySelector('[data-connector-account="disconnected"][data-connector-account-key="@acme/fixture"]')).toBeTruthy() + fireEvent.click(button('连接演示')) + fireEvent.click(button('更换')) + expect(onCommand.mock.calls).toEqual([[{ kind: 'start', operation: 'connect' }], [{ kind: 'start', operation: 'link-app' }]]) +}) + +it('disables the buttons while a call is pending or the Host stream is down', () => { + const { rerender } = section({ busy: true }) + expect(disabled()).toEqual([true]) + rerender( + , + ) + expect(disabled()).toEqual([true]) +}) + +it('asks before a button that changes the account outside DSH and runs it only after the user accepts', () => { + const display: ConnectorAccountDisplay = { + phase: 'connected', status: '已连接', notes: [], + buttons: [{ label: '退出登录', command: { kind: 'start', operation: 'sign-out' }, confirm: { title: '退出演示?', body: '终端也会退出。', label: '确认退出' } }], + } + const { onCommand } = section({}, display) + fireEvent.click(button('退出登录')) + expect(screen.getByRole('dialog', { name: '退出演示?' })).toBeTruthy() + expect(screen.getByText('终端也会退出。')).toBeTruthy() + fireEvent.click(button(zh['action.cancel'])) + expect(screen.queryByRole('dialog')).toBeNull() + fireEvent.click(button('退出登录')) + fireEvent.click(button('确认退出')) + expect(screen.queryByRole('dialog')).toBeNull() + expect(onCommand.mock.calls).toEqual([[{ kind: 'start', operation: 'sign-out' }]]) +}) + +it.each<[string, ConnectorAccountDisplay['failure'], string]>([ + ['the guidance, then its diagnostic items', { text: '失败。', details: ['login', 'exit 3', 'internal'] }, '失败。 排障信息:login · exit 3 · internal'], + ['the guidance alone without diagnostic items', { text: '失败。' }, '失败。'], + ['the guidance alone for an empty diagnostic list', { text: '失败。', details: [] }, '失败。'], +])('reports %s', (_name, failure, expected) => { + section({}, { ...DISCONNECTED, ...failure === undefined ? {} : { failure } }) + expect(screen.getByRole('alert').textContent).toBe(expected) +}) + +it('explains a stopped stream with the shared copy and reopens it even while offline', () => { + const { container, onRetry } = section({ stopped: true, linked: false }, { ...DISCONNECTED, failure: { text: '失败。' }, notes: [{ text: '说明' }] }) + expect(screen.getByText(zh['status.stopped'])).toBeTruthy() + expect(screen.getByText(zh['detail.stopped'])).toBeTruthy() + expect(screen.queryByRole('alert')).toBeNull() + expect(screen.queryByText('说明')).toBeNull() + expect(container.querySelector('[data-connector-account="stopped"]')).toBeTruthy() + fireEvent.click(button(zh['action.retry'])) + expect(onRetry).toHaveBeenCalledOnce() +}) + +it('prompts to connect only while disconnected and steps aside once the phase settles elsewhere', () => { + const onDismiss = vi.fn() + const onConnect = vi.fn() + const prompt = (phase: 'checking' | 'disconnected' | 'connected') => + + const { rerender } = render(prompt('checking')) + expect(screen.queryByRole('dialog')).toBeNull() + expect(onDismiss).not.toHaveBeenCalled() + rerender(prompt('disconnected')) + expect(screen.getByRole('dialog', { name: '连接演示' })).toBeTruthy() + expect(screen.getByText('插件已开启。')).toBeTruthy() + fireEvent.click(button('立即连接')) + expect(onConnect).toHaveBeenCalledOnce() + fireEvent.click(button(zh['activation.later'])) + expect(onDismiss).toHaveBeenCalledOnce() + rerender(prompt('connected')) + expect(onDismiss).toHaveBeenCalledTimes(2) +}) + +it('shows the latest notice with the registrant text or the shared failure copy', () => { + const onDone = vi.fn() + const toast = (notice: ConnectorAccountsState['notice']) => + + const { rerender } = render(toast(undefined)) + expect(document.body.textContent).toBe('') + rerender(toast({ seq: 1, kind: 'succeeded', text: { en: 'Connected', zh: '演示已连接' } })) + expect(screen.getByText('演示已连接')).toBeTruthy() + rerender(toast({ seq: 2, kind: 'action-failed' })) + expect(screen.getByText(zh['notice.action-failed'])).toBeTruthy() +}) + +const ok = (value: T): RemoteResult => ({ ok: true, value }) +const refused = (): RemoteResult => ({ ok: false, error: new RemoteError('gateway/internal', 'offline', {}) }) as never + +function face(change: Partial = {}, accounts: readonly ConnectorAccountEntry[] = [entry()]) { + const current: ConnectorAccountsState = { + accounts: new Map(accounts.map(item => [item.key, item])), linked: true, stopped: false, notice: undefined, ...change, + } + return { + useConnectorAccounts: (selector: (value: ConnectorAccountsState) => R): R => selector(current), + remote: { + start: vi.fn(async (_key: string, _operation: string) => ok(OP)), + cancel: vi.fn(async (_key: string, _id: ConnectorOperationId): Promise> => ok(undefined)), + }, + account: KEY, resolveText, follow: vi.fn(), failed: vi.fn(), retry: vi.fn(), dismissNotice: vi.fn(), t, + } +} + +it('starts an operation through the Remote, follows it, and stays busy until the call answers', async () => { + const props = face() + const answer = Promise.withResolvers>() + props.remote.start.mockReturnValueOnce(answer.promise) + render() + fireEvent.click(button('连接演示')) + expect(props.remote.start).toHaveBeenCalledWith(KEY, 'connect') + expect(disabled()).toEqual([true]) + await act(async () => { answer.resolve(ok(OP)) }) + expect(props.follow).toHaveBeenCalledWith(KEY, OP) + expect(disabled()).toEqual([false]) + expect(props.failed).not.toHaveBeenCalled() +}) + +it('reports a start the Host refused or that never answered, without following it', async () => { + const props = face() + props.remote.start.mockResolvedValueOnce(refused()).mockRejectedValueOnce(new Error('carrier lost')) + render() + await act(async () => { fireEvent.click(button('连接演示')) }) + await act(async () => { fireEvent.click(button('连接演示')) }) + expect(props.failed).toHaveBeenCalledTimes(2) + expect(props.follow).not.toHaveBeenCalled() +}) + +it('cancels the operation in progress and opens its authorization page again on request', async () => { + const windowOpen = vi.spyOn(window, 'open').mockReturnValue(null) + onTestFinished(() => { windowOpen.mockRestore() }) + const display: ConnectorAccountDisplay = { + phase: 'connecting', status: '等待浏览器', notes: [], + buttons: [{ label: '打开授权页', command: { kind: 'open' } }, { label: '取消', command: { kind: 'cancel' }, variant: 'ghost' }], + } + const props = face({}, [entry(display, { operation: { id: OP, authorizationUrl: 'https://example.com/a' } })]) + render() + fireEvent.click(button('打开授权页')) + expect(windowOpen).toHaveBeenCalledWith('https://example.com/a', '_blank', 'noopener,noreferrer') + await act(async () => { fireEvent.click(button('取消')) }) + expect(props.remote.cancel).toHaveBeenCalledWith(KEY, OP) + // A cancel button with no operation in progress calls nothing. + cleanup() + const idle = face({}, [entry(display)]) + render() + await act(async () => { fireEvent.click(button('取消')) }) + expect(idle.remote.cancel).not.toHaveBeenCalled() +}) + +const prompt = (props: ReturnType, onOpenDetails = vi.fn()) => + + +it('renders nothing for a bundle whose account the Host has not listed', () => { + render() + render(prompt(face({}, []))) + expect(document.body.textContent).toBe('') +}) + +it('tags only the enabled bundle that owns an account, with the Host text or the shared copy once the stream stopped', () => { + const pkg = (name: string, enabled = true) => ({ name, installed: true, availability: 'profile', official: false, enabled, rows: [] } as const) + const page = (name: string, enabled = true): PluginsSubject => ({ kind: 'bundle', pkg: pkg(name, enabled) }) + const row: PluginsSubject = { kind: 'row', pkg: pkg(KEY), row: { rowId: 'fixture', moduleName: '@acme/fixture-row', enabled: true } } + const tag = (props: ReturnType, subject: PluginsSubject) => + const { rerender } = render(tag(face(), page(KEY))) + expect(screen.getByText('未连接')).toBeTruthy() + rerender(tag(face(), row)) + expect(screen.getByText('未连接')).toBeTruthy() + rerender(tag(face({ stopped: true }), page(KEY))) + expect(screen.getByText(zh['badge.stopped'])).toBeTruthy() + for (const [props, subject] of [ + [face(), page(KEY, false)], [face(), page('@acme/other')], [face(), { kind: 'item', id: 'fixture-item' }], + [face({}, [entry({ phase: 'checking', status: '检查中', buttons: [], notes: [] })]), page(KEY)], + ] as const) { + rerender(tag(props, subject)) + expect(document.body.textContent).toBe('') + } +}) + +it('connects from the prompt through the operation the display names, or only opens the page', async () => { + const onOpenDetails = vi.fn() + const named = face({}, [entry({ ...DISCONNECTED, connect: { kind: 'start', operation: 'link-app' } })]) + const { rerender } = render(prompt(named, onOpenDetails)) + await act(async () => { fireEvent.click(button('连接演示')) }) + expect(onOpenDetails).toHaveBeenCalledOnce() + expect(named.remote.start).toHaveBeenCalledWith(KEY, 'link-app') + const bare = face() + rerender(prompt(bare, onOpenDetails)) + fireEvent.click(button('连接演示')) + expect(onOpenDetails).toHaveBeenCalledTimes(2) + expect(bare.remote.start).not.toHaveBeenCalled() +}) + +it('starts once for a second click before the first call answers', async () => { + const props = face({}, [entry({ ...DISCONNECTED, connect: { kind: 'start', operation: 'connect' } })]) + const answer = Promise.withResolvers>() + props.remote.start.mockReturnValueOnce(answer.promise) + render(prompt(props)) + fireEvent.click(button('连接演示')) + fireEvent.click(button('连接演示')) + await act(async () => { answer.resolve(ok(OP)) }) + expect(props.remote.start).toHaveBeenCalledOnce() + expect(props.follow).toHaveBeenCalledOnce() +}) + +it('shows the account notice through the toast entry', () => { + render() + expect(screen.getByText('演示已连接')).toBeTruthy() +}) diff --git a/packages/client/ui-connector-account/tests/registry.host.spec.ts b/packages/client/ui-connector-account/tests/registry.host.spec.ts new file mode 100644 index 0000000000..f5062b9596 --- /dev/null +++ b/packages/client/ui-connector-account/tests/registry.host.spec.ts @@ -0,0 +1,166 @@ +/** The registry serves every registered account to the Plugins page and routes page operations to the account that owns them. */ +import { Context } from '@deepseek-ai/cordis' +import { expect, it, onTestFinished, vi } from 'vitest' +import ConnectorAccounts from '../src/index.ts' +import type { + ConnectorAccountDisplay, ConnectorAccountRegistration, ConnectorAccountSource, ConnectorAccountsView, ConnectorAccountView, + ConnectorOperationId, +} from '../src/types.ts' + +type View = ConnectorAccountView<{ readonly state: 'out' | 'in' }, 'check' | 'connect', 'authorizing'> + +const OP = 'op-1' as ConnectorOperationId +const COPY = { + title: { en: 'Fixture account', zh: '演示账号' }, + hint: 'Shared with the terminal.', + activation: { title: 'Connect Fixture', body: 'The plugin is on.', connect: 'Connect' }, +} + +function source(initial: View = { account: { state: 'out' } }) { + let view = initial + const listeners = new Set<() => void>() + const fake = { + snapshot: () => view, + observe: vi.fn((listener: () => void) => { listeners.add(listener); return () => { listeners.delete(listener) } }), + refresh: vi.fn(), + start: vi.fn((_kind: 'check' | 'connect') => OP), + cancel: vi.fn(async (_id: ConnectorOperationId) => {}), + } satisfies ConnectorAccountSource + return { fake, listeners, publish: (next: View) => { view = next; for (const listener of listeners) listener() } } +} + +function display(view: View): ConnectorAccountDisplay { + return view.account.state === 'in' + ? { phase: 'connected', status: 'Connected', badge: 'Connected', buttons: [], notes: [] } + : { phase: 'disconnected', status: 'Not connected', buttons: [{ label: 'Connect', command: { kind: 'start', operation: 'connect' }, variant: 'primary' }], notes: [] } +} + +/** A registration whose bundle package defaults to its key; `null` registers an account no bundle owns. */ +function registration(key: string, account = source(), packageName: string | null = key): ConnectorAccountRegistration { + return { + key, ...packageName === null ? {} : { packageName }, source: account.fake, copy: COPY, present: display, + operations: [{ kind: 'check' }, { kind: 'connect', notice: { en: 'Fixture connected', zh: '演示已连接' } }], + } +} + +async function registry() { + const ctx = new Context() + onTestFinished(async () => { await ctx.fiber.dispose() }) + await ctx.plugin(ConnectorAccounts) + return ctx +} + +/** Read the stream until a view satisfies the predicate. */ +async function until( + stream: AsyncIterator, predicate: (view: ConnectorAccountsView) => boolean, +): Promise { + for (;;) { + const next = await stream.next() + if (next.done === true) throw new Error('stream ended') + if (predicate(next.value)) return next.value + } +} + +it('publishes each account with its key, package, copy, display, operation, and result, and checks it for each new subscriber', async () => { + const ctx = await registry() + const account = source() + const withdraw = ctx.connectorAccounts.register(registration('@acme/fixture', account)) + expect(account.fake.refresh).not.toHaveBeenCalled() + const controller = new AbortController() + const stream = ctx.connectorAccounts.watch(controller.signal)[Symbol.asyncIterator]() + const first = await until(stream, () => true) + expect(account.fake.refresh).toHaveBeenCalledOnce() + expect(first.accounts).toEqual([ + { key: '@acme/fixture', packageName: '@acme/fixture', copy: COPY, display: display({ account: { state: 'out' } }) }, + ]) + + account.publish({ account: { state: 'out' }, operation: { id: OP, kind: 'connect', phase: 'authorizing', cancellable: true, authorizationUrl: 'https://example.com/a' } }) + const waiting = await until(stream, view => view.accounts[0]?.operation !== undefined) + expect(waiting.accounts[0]?.operation).toEqual({ id: OP, authorizationUrl: 'https://example.com/a' }) + + account.publish({ account: { state: 'out' }, operation: { id: OP, kind: 'connect', phase: 'authorizing', cancellable: false } }) + const checking = await until(stream, (view) => { + const operation = view.accounts[0]?.operation + return operation !== undefined && operation.authorizationUrl === undefined + }) + expect(checking.accounts[0]?.operation).toEqual({ id: OP }) + + account.publish({ account: { state: 'in' }, result: { id: OP, kind: 'connect', outcome: 'succeeded' } }) + const connected = await until(stream, view => view.accounts[0]?.result !== undefined) + expect(connected.accounts[0]).toMatchObject({ + display: { phase: 'connected' }, result: { id: OP, notice: { en: 'Fixture connected', zh: '演示已连接' } }, + }) + + // Only a success reports a notice, and only for an operation that registered one. + account.publish({ account: { state: 'out' }, result: { id: OP, kind: 'connect', outcome: 'failed' } }) + expect((await until(stream, view => view.accounts[0]?.display.phase === 'disconnected')).accounts[0]?.result).toEqual({ id: OP }) + account.publish({ account: { state: 'in' }, result: { id: OP, kind: 'check', outcome: 'succeeded' } }) + expect((await until(stream, view => view.accounts[0]?.display.phase === 'connected')).accounts[0]?.result).toEqual({ id: OP }) + + withdraw() + expect((await until(stream, view => view.accounts.length === 0)).accounts).toEqual([]) + withdraw() + expect(account.listeners.size).toBe(0) + controller.abort() + expect((await stream.next()).done).toBe(true) +}) + +it('publishes an account that no bundle owns without a package', async () => { + const ctx = await registry() + ctx.connectorAccounts.register(registration('mcp:custom', source(), null)) + const stream = ctx.connectorAccounts.watch(new AbortController().signal)[Symbol.asyncIterator]() + const [entry] = (await until(stream, () => true)).accounts + expect(entry).toEqual({ key: 'mcp:custom', copy: COPY, display: display({ account: { state: 'out' } }) }) +}) + +it('checks an account registered while the page follows, and none registered while nobody follows', async () => { + const ctx = await registry() + const idle = source() + ctx.connectorAccounts.register(registration('@acme/idle', idle)) + const controller = new AbortController() + const stream = ctx.connectorAccounts.watch(controller.signal)[Symbol.asyncIterator]() + await until(stream, view => view.accounts.length === 1) + const late = source() + ctx.connectorAccounts.register(registration('@acme/late', late)) + expect(late.fake.refresh).toHaveBeenCalledOnce() + expect((await until(stream, view => view.accounts.length === 2)).accounts.map(entry => entry.key)).toEqual(['@acme/idle', '@acme/late']) + controller.abort() + await stream.next() + const after = source() + ctx.connectorAccounts.register(registration('@acme/after', after)) + expect(after.fake.refresh).not.toHaveBeenCalled() +}) + +it('starts only the operations an account registered and cancels through its source', async () => { + const ctx = await registry() + const account = source() + ctx.connectorAccounts.register(registration('@acme/fixture', account)) + expect(ctx.connectorAccounts.start('@acme/fixture', 'connect')).toBe(OP) + expect(account.fake.start).toHaveBeenCalledWith('connect') + expect(() => ctx.connectorAccounts.start('@acme/fixture', 'sign-out')).toThrow('@acme/fixture has no page operation sign-out') + expect(() => ctx.connectorAccounts.start('@acme/other', 'connect')).toThrow('@acme/other is not registered') + await ctx.connectorAccounts.cancel('@acme/fixture', OP) + expect(account.fake.cancel).toHaveBeenCalledWith(OP) + expect(() => ctx.connectorAccounts.cancel('@acme/other', OP)).toThrow('@acme/other is not registered') +}) + +it('refuses a second account for a key or for a package', async () => { + const ctx = await registry() + ctx.connectorAccounts.register(registration('@acme/fixture')) + expect(() => ctx.connectorAccounts.register(registration('@acme/fixture'))).toThrow('@acme/fixture is already registered') + expect(() => ctx.connectorAccounts.register(registration('mcp:fixture', source(), '@acme/fixture'))) + .toThrow('@acme/fixture already has an account') + expect(() => ctx.connectorAccounts.register(registration('mcp:custom', source(), null))).not.toThrow() +}) + +it('ends every stream when the registry unloads', async () => { + const ctx = new Context() + const fiber = ctx.plugin(ConnectorAccounts) + await fiber + const stream = ctx.connectorAccounts.watch(new AbortController().signal)[Symbol.asyncIterator]() + await until(stream, () => true) + const pending = stream.next() + await fiber.dispose() + expect((await pending).done).toBe(true) + await ctx.fiber.dispose() +}) diff --git a/packages/client/ui-connector-account/tests/state.client.spec.ts b/packages/client/ui-connector-account/tests/state.client.spec.ts new file mode 100644 index 0000000000..490b4dcae3 --- /dev/null +++ b/packages/client/ui-connector-account/tests/state.client.spec.ts @@ -0,0 +1,194 @@ +// @vitest-environment jsdom +/** The browser follows every registered account through one Host stream and keeps only what this browser started. */ +import { Context } from '@deepseek-ai/cordis' +import { RemoteStreamCarrierError, type RemoteStreamOptions } from '@deepseek-ai/dsh-api-gateway/client' +import { expect, it, onTestFinished, vi } from 'vitest' +import { BrowserAccounts, openAuthorizationPage } from '../src/client/state.ts' +import type { ConnectorAccountEntry, ConnectorAccountsView, ConnectorOperationId } from '../src/types.ts' + +const OP = 'op-1' as ConnectorOperationId +const NEXT = 'op-2' as ConnectorOperationId +const FIXTURE = '@acme/fixture' +const OTHER = 'mcp:other' +const COPY = { title: 'Fixture account', hint: 'Shared.', activation: { title: 'Connect', body: 'On.', connect: 'Connect' } } + +function entry(key: string, extra: Partial = {}): ConnectorAccountEntry { + return { key, copy: COPY, display: { phase: 'disconnected', status: 'Not connected', buttons: [], notes: [] }, ...extra } +} + +const waiting = (url?: string, id = OP): Partial => + ({ operation: { id, ...url === undefined ? {} : { authorizationUrl: url } } }) + +function fixture() { + const queue: ConnectorAccountsView[] = [] + let wake: (() => void) | undefined, closed = false, failure: Error | undefined, accepted = 0 + let options!: RemoteStreamOptions + const open = () => ({ + async *[Symbol.asyncIterator]() { + for (;;) { + if (failure !== undefined) throw failure + // A queued item still arrives after close, as an item the stream yielded just before disposal does. + const next = queue.shift() + if (next !== undefined) { yield { value: next, accept: () => { accepted++ } }; continue } + if (closed) return + await new Promise((resolve) => { wake = resolve }) + } + }, + dispose: vi.fn(async () => { closed = true; wake?.() }), + }) + const streams: Array> = [] + const remote = { watch: vi.fn() } + const ctx = new Context() + ctx.provide('remote', { + $stream: (value: typeof options) => { + options = value + closed = false + failure = undefined + streams.push(open()) + return streams.at(-1) + }, + }) + const windowOpen = vi.spyOn(window, 'open').mockReturnValue(null) + const browser = new BrowserAccounts(ctx, remote) + onTestFinished(async () => { await browser.dispose(); windowOpen.mockRestore(); await ctx.fiber.dispose() }) + return { + browser, remote, open: windowOpen, streams, options: () => options, + state: () => browser.state.getSnapshot(), + deliver(view: ConnectorAccountsView) { queue.push(view); wake?.() }, + async publish(...entries: ConnectorAccountEntry[]) { + const target = accepted + 1 + this.deliver({ accounts: entries }) + await vi.waitFor(() => { expect(accepted).toBe(target) }) + }, + fail(error: Error) { failure = error; wake?.() }, + } +} + +// Every fixture step settles through microtasks, so one macrotask lets a pending reopen finish. +const drain = () => new Promise((resolve) => { setTimeout(resolve, 0) }) + +it('mirrors the Host accounts by key and reports carrier loss until the next item', async () => { + const b = fixture() + expect(b.state()).toEqual({ accounts: new Map(), linked: true, stopped: false, notice: undefined }) + const open = b.options().open(new AbortController().signal) + expect(b.remote.watch).toHaveBeenCalledOnce() + expect(open).toBe(b.remote.watch.mock.results[0]?.value) + await b.publish(entry(FIXTURE), entry(OTHER)) + expect([...b.state().accounts.keys()]).toEqual([FIXTURE, OTHER]) + b.options().carrierFailed?.(new RemoteStreamCarrierError('offline')) + expect(b.state().linked).toBe(false) + await b.publish(entry(FIXTURE)) + expect(b.state()).toMatchObject({ linked: true, stopped: false }) + expect([...b.state().accounts.keys()]).toEqual([FIXTURE]) + expect(b.options().ended(true).message).toBe('Connector accounts stream ended') +}) + +it('opens each new authorization page of an operation this browser started once, and no other account\'s', async () => { + const b = fixture() + b.browser.follow(FIXTURE, OP) + await b.publish(entry(FIXTURE, waiting('https://example.com/a')), entry(OTHER, waiting('https://example.com/other'))) + expect(b.open.mock.calls).toEqual([['https://example.com/a', '_blank', 'noopener,noreferrer']]) + await b.publish(entry(FIXTURE, waiting('https://example.com/a'))) + await b.publish(entry(FIXTURE, waiting('http://127.0.0.1:8123/authorize'))) + // Another browser's operation on the same account opens nothing here. + await b.publish(entry(FIXTURE, waiting('https://example.com/b', NEXT))) + expect(b.open.mock.calls.map(([url]) => url)).toEqual(['https://example.com/a', 'http://127.0.0.1:8123/authorize']) +}) + +it('opens the page at once when the stream delivered the operation before the start call answered', async () => { + const b = fixture() + await b.publish(entry(FIXTURE, waiting('https://example.com/a'))) + expect(b.open).not.toHaveBeenCalled() + b.browser.follow(FIXTURE, OP) + expect(b.open).toHaveBeenCalledWith('https://example.com/a', '_blank', 'noopener,noreferrer') +}) + +it('reports the success of an operation this browser started once, and stops following it', async () => { + const b = fixture() + b.browser.follow(FIXTURE, OP) + await b.publish(entry(FIXTURE, { result: { id: NEXT, notice: 'Other browser connected' } })) + expect(b.state().notice).toBeUndefined() + await b.publish(entry(FIXTURE, { result: { id: OP, notice: 'Fixture connected' } })) + expect(b.state().notice).toEqual({ seq: 1, kind: 'succeeded', text: 'Fixture connected' }) + b.browser.dismissNotice() + await b.publish(entry(FIXTURE, { result: { id: OP, notice: 'Fixture connected' } })) + expect(b.state().notice).toBeUndefined() + + // A result without the registrant's text, or a cancelled or failed one, reports nothing. + b.browser.follow(FIXTURE, NEXT) + await b.publish(entry(FIXTURE, { result: { id: NEXT } })) + expect(b.state().notice).toBeUndefined() +}) + +it('forgets the operation of an account the Host withdrew', async () => { + const b = fixture() + b.browser.follow(FIXTURE, OP) + await b.publish(entry(OTHER)) + await b.publish(entry(FIXTURE, waiting('https://example.com/a'))) + expect(b.open).not.toHaveBeenCalled() +}) + +it('reports a call that did not finish with a fresh notice each time', () => { + const b = fixture() + b.browser.failed() + b.browser.failed() + expect(b.state().notice).toEqual({ seq: 2, kind: 'action-failed' }) +}) + +it('stops after a terminal stream failure and reopens on retry', async () => { + const b = fixture() + await b.publish(entry(FIXTURE)) + b.browser.retry() + expect(b.streams).toHaveLength(1) + b.fail(new Error('Host without the registry')) + await vi.waitFor(() => { expect(b.state().stopped).toBe(true) }) + expect(b.state().linked).toBe(false) + b.browser.retry() + b.browser.retry() + await drain() + expect(b.streams).toHaveLength(2) + expect(b.streams[0]?.dispose).toHaveBeenCalledOnce() + await b.publish(entry(FIXTURE)) + expect(b.state()).toMatchObject({ linked: true, stopped: false }) +}) + +it('opens nothing and reports nothing after disposal, and a retry pending at disposal opens no stream', async () => { + const b = fixture() + b.fail(new Error('Host without the registry')) + await vi.waitFor(() => { expect(b.state().stopped).toBe(true) }) + b.browser.retry() + await b.browser.dispose() + await drain() + expect(b.streams).toHaveLength(1) + b.browser.follow(FIXTURE, OP) + b.browser.failed() + b.browser.retry() + expect(b.state().notice).toBeUndefined() +}) + +it('shows nothing for a stream that fails while the page disposes it', async () => { + const b = fixture() + const disposing = b.browser.dispose() + b.fail(new Error('carrier lost')) + await disposing + expect(b.state()).toMatchObject({ linked: true, stopped: false }) +}) + +it('ignores an item the stream yielded just before disposal', async () => { + const b = fixture() + const disposing = b.browser.dispose() + b.deliver({ accounts: [entry(FIXTURE)] }) + await disposing + expect(b.state().accounts.size).toBe(0) +}) + +it('opens only HTTPS pages and HTTP pages on loopback addresses', () => { + const windowOpen = vi.spyOn(window, 'open').mockReturnValue(null) + onTestFinished(() => { windowOpen.mockRestore() }) + for (const url of [undefined, 'not a url', 'http://example.com/a', 'javascript:alert(1)']) openAuthorizationPage(url) + expect(windowOpen).not.toHaveBeenCalled() + for (const url of ['https://example.com/a', 'http://localhost:1/a', 'http://[::1]:1/a', 'http://127.0.0.1:1/a']) openAuthorizationPage(url) + expect(windowOpen.mock.calls.map(([url]) => url)).toEqual([ + 'https://example.com/a', 'http://localhost:1/a', 'http://[::1]:1/a', 'http://127.0.0.1:1/a', + ]) +}) diff --git a/packages/client/ui-connector-account/tsconfig.client.json b/packages/client/ui-connector-account/tsconfig.client.json new file mode 100644 index 0000000000..115af386fd --- /dev/null +++ b/packages/client/ui-connector-account/tsconfig.client.json @@ -0,0 +1,57 @@ +{ + "extends": "../../../tsconfig.base.client.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types", + "tsBuildInfoFile": "lib/tsconfig.client.tsbuildinfo" + }, + "include": [ + "src/client", + "src/css-modules.d.ts", + "src/types.ts" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../api/gateway/tsconfig.client.json" + }, + { + "path": "../../api/remotes/tsconfig.client.json" + }, + { + "path": "../store" + }, + { + "path": "../ui-layout" + }, + { + "path": "../ui-plugin-manager/tsconfig.client.json" + }, + { + "path": "../ui-primitives" + }, + { + "path": "../ui-renderer" + }, + { + "path": "../ui-slots" + }, + { + "path": "../../typert/protocol" + }, + { + "path": "../locale/tsconfig.client.json" + }, + { + "path": "../../util/brand" + }, + { + "path": "../../util/package-manifest" + }, + { + "path": "../../util/values" + } + ] +} diff --git a/packages/client/ui-connector-account/tsconfig.host.json b/packages/client/ui-connector-account/tsconfig.host.json new file mode 100644 index 0000000000..564ba19f3b --- /dev/null +++ b/packages/client/ui-connector-account/tsconfig.host.json @@ -0,0 +1,26 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types", + "tsBuildInfoFile": "lib/tsconfig.host.tsbuildinfo" + }, + "files": [ + "src/index.ts", + "src/types.ts" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../typert/protocol" + }, + { + "path": "../../util/brand" + }, + { + "path": "../../util/package-manifest" + } + ] +} diff --git a/packages/client/ui-connector-account/tsconfig.json b/packages/client/ui-connector-account/tsconfig.json new file mode 100644 index 0000000000..2eca820546 --- /dev/null +++ b/packages/client/ui-connector-account/tsconfig.json @@ -0,0 +1,11 @@ +{ + "files": [], + "references": [ + { + "path": "./tsconfig.host.json" + }, + { + "path": "./tsconfig.client.json" + } + ] +} diff --git a/packages/client/ui-connector-account/tsdown.config.ts b/packages/client/ui-connector-account/tsdown.config.ts new file mode 100644 index 0000000000..620261533c --- /dev/null +++ b/packages/client/ui-connector-account/tsdown.config.ts @@ -0,0 +1,3 @@ +import { clientBundle } from '../tsdown.client.ts' + +export default clientBundle(import.meta.dirname, ['lib/types/index.js'], { hostPhase: true }) diff --git a/packages/experimental/liveshare/src/endpoint-classification.ts b/packages/experimental/liveshare/src/endpoint-classification.ts index a868012bd6..f6d4651fcc 100644 --- a/packages/experimental/liveshare/src/endpoint-classification.ts +++ b/packages/experimental/liveshare/src/endpoint-classification.ts @@ -163,6 +163,9 @@ export const VIEWER_ENDPOINT_CLASSES = { 'productAnalytics/report': 'owner-only', // owner product analytics 'productAnalytics/watchPolicy': 'owner-only', // owner product analytics 'pluginRegistryProbe/fastest': 'owner-only', // owner plugin registry probe + 'connectorAccounts/cancel': 'owner-only', // owner connector accounts on the Plugins page + 'connectorAccounts/start': 'owner-only', // owner connector accounts on the Plugins page + 'connectorAccounts/watch': 'owner-only', // owner connector accounts on the Plugins page 'sessionReferenceResolver/candidates': 'owner-only', // owner composer reference resolution 'officeKit/generation': 'owner-only', // owner document export 'officeKit/render': 'owner-only', // owner document export 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 41f4010684..3f81339648 100644 --- a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts @@ -2831,6 +2831,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ slotInject: '', declaredBy: 'an entry in \'main\' (client-ui-plugin-manager), so it exists while that entry is mounted', occupants: [ + 'client-ui-connector-account ConnectorAccountActivationEntry', 'experimental-client-ui-voice-input VoiceSetupPrompt key \'@deepseek-ai/dsh-experimental-voice-input-bundle\'', 'cua PermissionSetup key \'@deepseek-ai/dsh-cua-bundle\'', ], @@ -2875,6 +2876,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ slotInject: '', declaredBy: 'an entry in \'main\' (client-ui-plugin-manager), so it exists while that entry is mounted', occupants: [ + 'client-ui-connector-account ConnectorAccountSectionEntry', 'experimental-client-ui-cot-translation TranslationSettings key \'@deepseek-ai/dsh-experimental-cot-translation-bundle\'', 'experimental-client-ui-voice-input VoicePreparation key \'@deepseek-ai/dsh-experimental-voice-input-bundle\'', 'cua PermissionPanel key \'@deepseek-ai/dsh-cua-bundle\'', @@ -2984,7 +2986,9 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ hookContext: '', slotInject: '', declaredBy: 'an entry in \'main\' (client-ui-plugin-manager), so it exists while that entry is mounted', - occupants: [], + occupants: [ + 'client-ui-connector-account ConnectorAccountBadgeEntry id \'connector-account.badge\'', + ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'plugins.detail.badge\', () => ctx.slots.register(\n { name: \'plugins.detail.badge\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', source: 'packages/client/ui-plugin-manager/src/client/slot-contract.ts:178', @@ -4052,6 +4056,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ occupants: [ 'client-ui-agent-team TeamDisableConfirmation id \'agent-team.disable\'', 'client-ui-chat QuotaNoticeHost id \'chat.quota-notice\'', + 'client-ui-connector-account ConnectorAccountToastEntry id \'connector-account.notice\'', 'client-ui-context-menu MenuOverlay id \'context-menu\'', 'client-ui-file-drag FileDragFeedback id \'file-drag.feedback\'', 'client-ui-open-in-app OpenInAppToast id \'open-in-app.toast\'', diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 0ac2e9e122..7dab041b4e 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -812,6 +812,40 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, ], }, + { + key: 'connectorAccounts', + summary: 'Holds the registered accounts and serves them to the Plugins page.', + description: 'Holds the registered accounts and serves them to the Plugins page.', + methods: [ + { + signature: 'register(registration: ConnectorAccountRegistration): () => void', + description: 'Show one account on the Plugins page for as long as the returned disposer has not run.', + parameters: [{ name: 'registration', description: 'the account key, its bundle package, the account source, the page operations, and the presentation.' }], + returns: 'an idempotent disposer that withdraws the account.', + throws: ['when another account already uses the key or the package.'], + }, + { + signature: '@Remote({ mode: \'stream\' }) async *watch(signal: AbortSignal): AsyncIterable', + description: 'Follow every registered account; each new subscriber starts a check of each account that runs no operation.', + parameters: [{ name: 'signal', description: 'the Client\'s observation lifetime; disposal also ends the stream.' }], + returns: 'the current accounts, then each changed set, coalescing changes that arrive before the next read.', + }, + { + signature: '@Remote start(key: string, operation: string): ConnectorOperationId', + description: 'Start one of the operations the account registered as page actions.', + parameters: [{ name: 'key', description: 'the account key.' }, { name: 'operation', description: 'the operation kind.' }], + returns: 'the operation identity.', + throws: ['for an unknown account or operation, or whatever the account\'s source refuses, such as a second operation.'], + }, + { + signature: '@Remote cancel(key: string, id: ConnectorOperationId): Promise', + description: 'Cancel one operation while its phase is cancellable, and wait for it to settle.', + parameters: [{ name: 'key', description: 'the account key.' }, { name: 'id', description: 'the operation to cancel; a finished one or a phase that is not cancellable is ignored.' }], + returns: 'after the operation settles, or at once when nothing is cancelled.', + throws: ['for an unknown account.'], + }, + ], + }, { key: 'cotTranslation', summary: 'Optional reasoning translation delegates Session-bound storage to the translator.', @@ -5754,6 +5788,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'AnonymousTranslationSpec', declaration: 'export interface AnonymousTranslationSpec extends TranslationSpecFields {\n readonly provider: AnonymousTranslationProvider;\n}', }, + { + name: 'AnyConnectorAccountView', + declaration: 'export type AnyConnectorAccountView = ConnectorAccountView;', + }, { name: 'AnyHook', declaration: 'export type AnyHook = ModHook;', @@ -6178,6 +6216,78 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'ConnectionTrustRequest', declaration: 'export interface ConnectionTrustRequest {\n readonly headers: Headers | Readonly>;\n}', }, + { + name: 'ConnectorAccountButton', + declaration: 'export interface ConnectorAccountButton {\n readonly label: LocalizedText;\n readonly command: ConnectorAccountCommand;\n readonly variant?: \'primary\' | \'ghost\';\n readonly confirm?: ConnectorAccountConfirmation;\n}', + }, + { + name: 'ConnectorAccountCommand', + declaration: 'export type ConnectorAccountCommand = {\n readonly kind: \'start\';\n readonly operation: string;\n} | {\n readonly kind: \'cancel\';\n} | {\n readonly kind: \'open\';\n};', + }, + { + name: 'ConnectorAccountConfirmation', + declaration: 'export interface ConnectorAccountConfirmation {\n readonly title: LocalizedText;\n readonly body: LocalizedText;\n readonly label: LocalizedText;\n}', + }, + { + name: 'ConnectorAccountCopy', + declaration: 'export interface ConnectorAccountCopy {\n readonly title: LocalizedText;\n readonly hint: LocalizedText;\n readonly activation: {\n readonly title: LocalizedText;\n readonly body: LocalizedText;\n readonly connect: LocalizedText;\n };\n}', + }, + { + name: 'ConnectorAccountDisplay', + declaration: 'export interface ConnectorAccountDisplay {\n readonly phase: ConnectorAccountPhase;\n readonly status: LocalizedText;\n readonly badge?: LocalizedText;\n readonly buttons: readonly ConnectorAccountButton[];\n readonly connect?: Extract;\n readonly detail?: LocalizedText;\n readonly notes: readonly ConnectorAccountNote[];\n readonly failure?: ConnectorAccountFailure;\n}', + }, + { + name: 'ConnectorAccountEntry', + declaration: 'export interface ConnectorAccountEntry {\n readonly key: string;\n readonly packageName?: string;\n readonly copy: ConnectorAccountCopy;\n readonly display: ConnectorAccountDisplay;\n readonly operation?: {\n readonly id: ConnectorOperationId;\n readonly authorizationUrl?: string;\n };\n readonly result?: {\n readonly id: ConnectorOperationId;\n readonly notice?: LocalizedText;\n };\n}', + }, + { + name: 'ConnectorAccountFailure', + declaration: 'export interface ConnectorAccountFailure {\n readonly text: LocalizedText;\n readonly details?: readonly string[];\n}', + }, + { + name: 'ConnectorAccountNote', + declaration: 'export interface ConnectorAccountNote {\n readonly text: LocalizedText;\n readonly button?: ConnectorAccountButton;\n}', + }, + { + name: 'ConnectorAccountOperation', + declaration: 'export interface ConnectorAccountOperation {\n readonly kind: Kind;\n readonly notice?: LocalizedText;\n}', + }, + { + name: 'ConnectorAccountPhase', + declaration: 'export type ConnectorAccountPhase = \'checking\' | \'connecting\' | \'connected\' | \'disconnected\' | \'unavailable\';', + }, + { + name: 'ConnectorAccountRegistration', + declaration: 'export interface ConnectorAccountRegistration {\n readonly key: string;\n readonly packageName?: string;\n readonly source: ConnectorAccountSource;\n readonly operations: readonly ConnectorAccountOperation>[];\n readonly copy: ConnectorAccountCopy;\n readonly present: (view: View) => ConnectorAccountDisplay;\n}', + }, + { + name: 'ConnectorAccountSource', + declaration: 'export interface ConnectorAccountSource {\n snapshot(): View;\n observe(listener: () => void): () => void;\n refresh(): void;\n start(kind: ConnectorOperationKindOf): ConnectorOperationId;\n cancel(id: ConnectorOperationId): Promise;\n}', + }, + { + name: 'ConnectorAccountsView', + declaration: 'export interface ConnectorAccountsView {\n readonly accounts: readonly ConnectorAccountEntry[];\n}', + }, + { + name: 'ConnectorAccountView', + declaration: 'export interface ConnectorAccountView {\n readonly account: Account;\n readonly operation?: ConnectorOperation;\n readonly result?: ConnectorOperationResult;\n}', + }, + { + name: 'ConnectorOperation', + declaration: 'export interface ConnectorOperation {\n readonly id: ConnectorOperationId;\n readonly kind: Kind;\n readonly phase: Phase;\n readonly cancellable: boolean;\n readonly authorizationUrl?: string;\n}', + }, + { + name: 'ConnectorOperationId', + declaration: 'export type ConnectorOperationId = Branded<\'ConnectorOperationId\'>;', + }, + { + name: 'ConnectorOperationKindOf', + declaration: 'export type ConnectorOperationKindOf = NonNullable[\'kind\'];', + }, + { + name: 'ConnectorOperationResult', + declaration: 'export interface ConnectorOperationResult {\n readonly id: ConnectorOperationId;\n readonly kind: Kind;\n readonly outcome: \'succeeded\' | \'cancelled\' | \'failed\';\n readonly failure?: Failure;\n}', + }, { name: 'ContentBlockMap', declaration: 'export interface ContentBlockMap {\n \'text\': TextBlock;\n \'reasoning\': ReasoningBlock;\n \'image\': ImageBlock;\n \'file\': FileBlock;\n \'tool-call\': ToolCallBlock;\n \'tool-addition\': ToolAdditionBlock;\n \'tool-removal\': ToolRemovalBlock;\n}', 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 489d3c98ce..4e85565b18 100644 --- a/packages/preset/agent-preset/skills/dsh-doc/references/packages.md +++ b/packages/preset/agent-preset/skills/dsh-doc/references/packages.md @@ -74,6 +74,7 @@ Every package below exports a Cordis plugin that a bundle patch can name in a Lo | `@deepseek-ai/dsh-client-ui-brand-official` | no | Official DeepSeek Harness brand artwork and click-triggered home background | | `@deepseek-ai/dsh-client-ui-chat` | no | Chat Conversation target, node definitions, renderers, and details surface | | `@deepseek-ai/dsh-client-ui-commands` | no | Client command surface: global directory cache, '/' source, three command UI kinds, popupSelect registry | +| `@deepseek-ai/dsh-client-ui-connector-account` | no | Connector account surfaces: the Host registry CLI app plugins and MCP connectors register their accounts with, and the Plugins page section, title tag, activation prompt, and notices it serves over one Remote | | `@deepseek-ai/dsh-client-ui-context-menu` | no | Typed, plugin-extensible context menus with captured targets and shared Web presentation | | `@deepseek-ai/dsh-client-ui-conversation` | no | Target-neutral Conversation assembly, shell, composer, queue, and view navigation | | `@deepseek-ai/dsh-client-ui-deliverables` | no | Changed-files card with per-file comparison tabs, delivery cards, and clickable final-response file references for Web | 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 f43eae5217..faa5009098 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 @@ -60,5 +60,7 @@ export const remoteDefaultResponses: RemoteTable = { 'remoteAccess/follow': openStream([{ type: 'baseline', owner: true }]), // ui-sidebar-terminal header entry `agent-terminals`: the displayed Session's terminal roster, then open. 'terminal/watch': openStream([[]]), + // ui-connector-account `apply`: the registered connector accounts, none in a default composition, then open. + 'connectorAccounts/watch': openStream([{ accounts: [] }]), }, } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b48c3c87c1..b8e66b0ebf 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1482,6 +1482,9 @@ importers: '@deepseek-ai/dsh-client-product-analytics': specifier: workspace:* version: link:../../client/product-analytics + '@deepseek-ai/dsh-client-ui-connector-account': + specifier: workspace:* + version: link:../../client/ui-connector-account '@deepseek-ai/dsh-client-ui-plugin-manager': specifier: workspace:* version: link:../../client/ui-plugin-manager @@ -2992,6 +2995,9 @@ importers: '@deepseek-ai/dsh-client-ui-commands': specifier: workspace:* version: link:../../client/ui-commands + '@deepseek-ai/dsh-client-ui-connector-account': + specifier: workspace:* + version: link:../../client/ui-connector-account '@deepseek-ai/dsh-client-ui-context-menu': specifier: workspace:* version: link:../../client/ui-context-menu @@ -4184,6 +4190,67 @@ importers: specifier: ^18.2.0 version: 18.3.1 + packages/client/ui-connector-account: + dependencies: + '@deepseek-ai/dsh-typert-protocol': + specifier: workspace:* + version: link:../../typert/protocol + zod: + specifier: 4.6.6 + version: 4.6.6 + devDependencies: + '@deepseek-ai/cordis': + specifier: workspace:~ + version: link:../../../vendor/cordis + '@deepseek-ai/dsh-api-gateway': + specifier: workspace:* + version: link:../../api/gateway + '@deepseek-ai/dsh-api-remotes': + specifier: workspace:* + version: link:../../api/remotes + '@deepseek-ai/dsh-brand': + specifier: workspace:* + version: link:../../util/brand + '@deepseek-ai/dsh-client-locale': + specifier: workspace:* + version: link:../locale + '@deepseek-ai/dsh-client-store': + specifier: workspace:* + version: link:../store + '@deepseek-ai/dsh-client-test-runtime': + specifier: workspace:* + version: link:../../test-support/client-runtime + '@deepseek-ai/dsh-client-ui-layout': + specifier: workspace:* + version: link:../ui-layout + '@deepseek-ai/dsh-client-ui-plugin-manager': + specifier: workspace:* + version: link:../ui-plugin-manager + '@deepseek-ai/dsh-client-ui-primitives': + specifier: workspace:* + version: link:../ui-primitives + '@deepseek-ai/dsh-client-ui-renderer': + specifier: workspace:* + version: link:../ui-renderer + '@deepseek-ai/dsh-client-ui-slots': + specifier: workspace:* + version: link:../ui-slots + '@deepseek-ai/dsh-package-manifest': + specifier: workspace:* + version: link:../../util/package-manifest + '@deepseek-ai/dsh-util-values': + specifier: workspace:* + version: link:../../util/values + '@testing-library/react': + specifier: ^16.3.3 + version: 16.3.3(@testing-library/dom@10.4.2)(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + react: + specifier: ^18.2.0 + version: 18.3.1 + react-dom: + specifier: ^18.2.0 + version: 18.3.1(react@18.3.1) + packages/client/ui-context-menu: devDependencies: '@deepseek-ai/cordis': diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index 9e5119387d..4086cfb588 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -63,6 +63,7 @@ export const SERVICE_PAGE: Record = { actionCards: 'boot.md', pluginRecommendations: 'boot.md', pluginMarket: 'boot.md', + connectorAccounts: 'boot.md', pluginRegistryProbe: 'boot.md', configEditor: 'boot.md', profileContext: 'boot.md', @@ -1009,6 +1010,10 @@ export const FOUNDATION_TYPE_NAMES: ReadonlySet = new Set([ /** Project types deliberately documented outside the subsystems catalog. */ export const TYPE_LINK_EXEMPTIONS: Readonly> = { + AnyConnectorAccountView: 'generic connector account view is owned by packages/client/ui-connector-account/README.md', + 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', 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 6643bd5b44..f37c4165b3 100644 --- a/scripts/gen-doc-graphs.ts +++ b/scripts/gen-doc-graphs.ts @@ -170,6 +170,13 @@ const SERVICE_ROLES: ServiceRole[] = [ consumers: ['plugin-manager', 'ui-settings-plugin-inventory'], note: 'Shares profile package operations with the CLI and reports persisted and running state to Web and agent callers.', }, + { + key: 'connectorAccounts', + pkg: 'client-ui-connector-account', + title: 'Connector accounts on the Plugins page', + mode: 'service', + note: 'Holds the accounts CLI app plugins and MCP connectors register and serves their Host-computed displays to the Plugins page through one Remote; authorization pages and notices stay in the browser that started the operation.', + }, { key: 'pluginMarket', pkg: 'plugin-market', diff --git a/scripts/verify-package-readme-model-experience.ts b/scripts/verify-package-readme-model-experience.ts index d5001cd021..1438911741 100644 --- a/scripts/verify-package-readme-model-experience.ts +++ b/scripts/verify-package-readme-model-experience.ts @@ -150,6 +150,7 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly> = { 'packages/client/ui-brand-official': { kind: 'none', reason: 'Browser-side presentation occupants; registers nothing model-facing.' }, 'packages/client/ui-approval': { kind: 'none', reason: 'Browser-side approval presentation; registers nothing model-facing.' }, 'packages/client/ui-chat': { kind: 'none', reason: 'Browser-side Chat presentation; registers nothing model-facing.' }, + 'packages/client/ui-connector-account': { kind: 'none', reason: 'Plugins page account surfaces over Host-registered accounts; each registrant documents the tools and skills its account enables.' }, 'packages/client/ui-message-feedback': { kind: 'none', reason: 'Browser-side controls over log-only message feedback; ratings and notes never enter model context or change model-input tokens.' }, 'packages/client/ui-tool': { kind: 'none', reason: 'Browser-side Tool presentation layer; renders logged calls without changing model context.' }, 'packages/client/ui-schedule': { kind: 'none', reason: 'Browser-side catalog, editing, and deletion of Host Schedule records; dsh-schedule owns storage and delivery, and dsh-tool-schedule contributes the model-facing tools in a preset that mounts it.' }, diff --git a/tsconfig.base.json b/tsconfig.base.json index 2121904985..adbdc839ee 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -323,6 +323,8 @@ "@deepseek-ai/dsh-client-ui-input-trigger": ["./packages/client/ui-input-trigger/src"], "@deepseek-ai/dsh-client-ui-reference": ["./packages/client/ui-reference/src"], "@deepseek-ai/dsh-client-ui-commands": ["./packages/client/ui-commands/src"], + "@deepseek-ai/dsh-client-ui-connector-account": ["./packages/client/ui-connector-account/src"], + "@deepseek-ai/dsh-client-ui-connector-account/types": ["./packages/client/ui-connector-account/src/types.ts"], "@deepseek-ai/dsh-client-ui-model-selection": ["./packages/client/ui-model-selection/src"], "@deepseek-ai/dsh-client-ui-goal": ["./packages/client/ui-goal/src"], "@deepseek-ai/dsh-client-ui-message-feedback": ["./packages/client/ui-message-feedback/src"], diff --git a/tsconfig.client.json b/tsconfig.client.json index f15b78502b..a6da608953 100644 --- a/tsconfig.client.json +++ b/tsconfig.client.json @@ -142,6 +142,7 @@ { "path": "./packages/client/ui-directory-picker-native" }, { "path": "./packages/client/ui-goal" }, { "path": "./packages/client/ui-message-feedback" }, + { "path": "./packages/client/ui-connector-account/tsconfig.client.json" }, { "path": "./packages/client/ui-model-selection" }, { "path": "./packages/client/ui-agent-preset" }, { "path": "./packages/client/ui-permission-presets" }, diff --git a/tsconfig.host.json b/tsconfig.host.json index c926055be3..f4d9239e0e 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -305,6 +305,7 @@ { "path": "./packages/client/ui-theme/tsconfig.host.json" }, { "path": "./packages/client/ui-chat/tsconfig.host.json" }, { "path": "./packages/client/ui-conversation/tsconfig.host.json" }, + { "path": "./packages/client/ui-connector-account/tsconfig.host.json" }, { "path": "./packages/client/ui-settings/tsconfig.host.json" }, { "path": "./packages/client/ui-settings-general/tsconfig.host.json" }, From fadd1c28582a362f2d63034fe839dba435ba0226 Mon Sep 17 00:00:00 2001 From: gengruilin Date: Sun, 8 Nov 2026 04:15:16 +0800 Subject: [PATCH 02/31] feat(connector-account): let an account source start its operation asynchronously An MCP server's authorization starts only after the previous attempt's cleanup settles, so its source learns the operation identity after an await. `ConnectorAccountSource.start` may now return a Promise, and the registry's `start` answers once the source has the identity. --- docs/subsystems/boot.md | 4 ++-- docs/subsystems/boot.zh.md | 4 ++-- packages/client/ui-connector-account/src/index.ts | 8 ++++---- packages/client/ui-connector-account/src/types.ts | 4 ++-- .../ui-connector-account/tests/registry.host.spec.ts | 12 ++++++++---- packages/extensions/tool-cordis/src/api-catalog.ts | 6 +++--- 6 files changed, 21 insertions(+), 17 deletions(-) diff --git a/docs/subsystems/boot.md b/docs/subsystems/boot.md index c8f36d14e2..5c131881f7 100644 --- a/docs/subsystems/boot.md +++ b/docs/subsystems/boot.md @@ -170,10 +170,10 @@ register(registration: ConnectorAccountReg * Start one of the operations the account registered as page actions. * @param key - the account key. * @param operation - the operation kind. - * @returns the operation identity. + * @returns the operation identity once the account's source has started it. * @throws for an unknown account or operation, or whatever the account's source refuses, such as a second operation. */ -@Remote start(key: string, operation: string): ConnectorOperationId +@Remote async start(key: string, operation: string): Promise /** * Cancel one operation while its phase is cancellable, and wait for it to settle. diff --git a/docs/subsystems/boot.zh.md b/docs/subsystems/boot.zh.md index ab6383e0b3..0a48541725 100644 --- a/docs/subsystems/boot.zh.md +++ b/docs/subsystems/boot.zh.md @@ -170,10 +170,10 @@ register(registration: ConnectorAccountReg * Start one of the operations the account registered as page actions. * @param key - the account key. * @param operation - the operation kind. - * @returns the operation identity. + * @returns the operation identity once the account's source has started it. * @throws for an unknown account or operation, or whatever the account's source refuses, such as a second operation. */ -@Remote start(key: string, operation: string): ConnectorOperationId +@Remote async start(key: string, operation: string): Promise /** * Cancel one operation while its phase is cancellable, and wait for it to settle. diff --git a/packages/client/ui-connector-account/src/index.ts b/packages/client/ui-connector-account/src/index.ts index 691e56d90a..aa7ec1d6d4 100644 --- a/packages/client/ui-connector-account/src/index.ts +++ b/packages/client/ui-connector-account/src/index.ts @@ -24,7 +24,7 @@ interface Registered { readonly packageName: string | undefined readonly entry: () => ConnectorAccountEntry readonly refresh: () => void - readonly start: (operation: string) => ConnectorOperationId + readonly start: (operation: string) => ConnectorOperationId | Promise readonly cancel: (id: ConnectorOperationId) => Promise } @@ -131,12 +131,12 @@ export default class ConnectorAccounts extends TypertRemoteService { * Start one of the operations the account registered as page actions. * @param key - the account key. * @param operation - the operation kind. - * @returns the operation identity. + * @returns the operation identity once the account's source has started it. * @throws for an unknown account or operation, or whatever the account's source refuses, such as a second operation. */ @Remote - start(key: string, operation: string): ConnectorOperationId { - return this.account(key).start(operation) + async start(key: string, operation: string): Promise { + return await this.account(key).start(operation) } /** diff --git a/packages/client/ui-connector-account/src/types.ts b/packages/client/ui-connector-account/src/types.ts index a04cbf4a1d..debd04d302 100644 --- a/packages/client/ui-connector-account/src/types.ts +++ b/packages/client/ui-connector-account/src/types.ts @@ -137,8 +137,8 @@ export interface ConnectorAccountSource { observe(listener: () => void): () => void /** Start a check unless an operation runs; a source whose view is always current does nothing. */ refresh(): void - /** @returns the started operation's identity. */ - start(kind: ConnectorOperationKindOf): ConnectorOperationId + /** @returns the started operation's identity, at once or after the source has started the operation. */ + start(kind: ConnectorOperationKindOf): ConnectorOperationId | Promise /** @returns after the named operation settles, or at once when it is not cancellable. */ cancel(id: ConnectorOperationId): Promise } diff --git a/packages/client/ui-connector-account/tests/registry.host.spec.ts b/packages/client/ui-connector-account/tests/registry.host.spec.ts index f5062b9596..ee8e24276f 100644 --- a/packages/client/ui-connector-account/tests/registry.host.spec.ts +++ b/packages/client/ui-connector-account/tests/registry.host.spec.ts @@ -10,6 +10,7 @@ import type { type View = ConnectorAccountView<{ readonly state: 'out' | 'in' }, 'check' | 'connect', 'authorizing'> const OP = 'op-1' as ConnectorOperationId +const NEXT = 'op-2' as ConnectorOperationId const COPY = { title: { en: 'Fixture account', zh: '演示账号' }, hint: 'Shared with the terminal.', @@ -23,7 +24,7 @@ function source(initial: View = { account: { state: 'out' } }) { snapshot: () => view, observe: vi.fn((listener: () => void) => { listeners.add(listener); return () => { listeners.delete(listener) } }), refresh: vi.fn(), - start: vi.fn((_kind: 'check' | 'connect') => OP), + start: vi.fn((_kind: 'check' | 'connect'): ConnectorOperationId | Promise => OP), cancel: vi.fn(async (_id: ConnectorOperationId) => {}), } satisfies ConnectorAccountSource return { fake, listeners, publish: (next: View) => { view = next; for (const listener of listeners) listener() } } @@ -135,10 +136,13 @@ it('starts only the operations an account registered and cancels through its sou const ctx = await registry() const account = source() ctx.connectorAccounts.register(registration('@acme/fixture', account)) - expect(ctx.connectorAccounts.start('@acme/fixture', 'connect')).toBe(OP) + await expect(ctx.connectorAccounts.start('@acme/fixture', 'connect')).resolves.toBe(OP) expect(account.fake.start).toHaveBeenCalledWith('connect') - expect(() => ctx.connectorAccounts.start('@acme/fixture', 'sign-out')).toThrow('@acme/fixture has no page operation sign-out') - expect(() => ctx.connectorAccounts.start('@acme/other', 'connect')).toThrow('@acme/other is not registered') + // A source that starts its operation asynchronously answers once it has the identity. + account.fake.start.mockImplementationOnce(async () => NEXT) + await expect(ctx.connectorAccounts.start('@acme/fixture', 'connect')).resolves.toBe(NEXT) + await expect(ctx.connectorAccounts.start('@acme/fixture', 'sign-out')).rejects.toThrow('@acme/fixture has no page operation sign-out') + await expect(ctx.connectorAccounts.start('@acme/other', 'connect')).rejects.toThrow('@acme/other is not registered') await ctx.connectorAccounts.cancel('@acme/fixture', OP) expect(account.fake.cancel).toHaveBeenCalledWith(OP) expect(() => ctx.connectorAccounts.cancel('@acme/other', OP)).toThrow('@acme/other is not registered') diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 7dab041b4e..ca4b751e86 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -831,10 +831,10 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ returns: 'the current accounts, then each changed set, coalescing changes that arrive before the next read.', }, { - signature: '@Remote start(key: string, operation: string): ConnectorOperationId', + signature: '@Remote async start(key: string, operation: string): Promise', description: 'Start one of the operations the account registered as page actions.', parameters: [{ name: 'key', description: 'the account key.' }, { name: 'operation', description: 'the operation kind.' }], - returns: 'the operation identity.', + returns: 'the operation identity once the account\'s source has started it.', throws: ['for an unknown account or operation, or whatever the account\'s source refuses, such as a second operation.'], }, { @@ -6262,7 +6262,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'ConnectorAccountSource', - declaration: 'export interface ConnectorAccountSource {\n snapshot(): View;\n observe(listener: () => void): () => void;\n refresh(): void;\n start(kind: ConnectorOperationKindOf): ConnectorOperationId;\n cancel(id: ConnectorOperationId): Promise;\n}', + declaration: 'export interface ConnectorAccountSource {\n snapshot(): View;\n observe(listener: () => void): () => void;\n refresh(): void;\n start(kind: ConnectorOperationKindOf): ConnectorOperationId | Promise;\n cancel(id: ConnectorOperationId): Promise;\n}', }, { name: 'ConnectorAccountsView', From fcf5908ff7cf1fe748e92c6c5d60bde69eb6246d Mon Sep 17 00:00:00 2001 From: gengruilin Date: Sun, 8 Nov 2026 04:36:33 +0800 Subject: [PATCH 03/31] fix(connector-account): keep the activation prompt while the account is connecting An MCP server switched on connects before it reports that it needs authorization, so the prompt now waits while the account is checking or connecting and dismisses itself only once the account is connected, unavailable, or not running. --- packages/client/ui-connector-account/README.i18n.yaml | 4 ++-- packages/client/ui-connector-account/README.md | 2 +- packages/client/ui-connector-account/README.zh.md | 2 +- .../ui-connector-account/src/client/components.tsx | 7 ++++--- .../tests/components.client.spec.tsx | 9 +++++++-- 5 files changed, 15 insertions(+), 9 deletions(-) diff --git a/packages/client/ui-connector-account/README.i18n.yaml b/packages/client/ui-connector-account/README.i18n.yaml index 347d021162..010f9d34c4 100644 --- a/packages/client/ui-connector-account/README.i18n.yaml +++ b/packages/client/ui-connector-account/README.i18n.yaml @@ -21,8 +21,8 @@ en: e618281ea7721daf zh: a5d5f5e307ea3435 /deepseek-ai-dsh-client-ui-connector-account/use-this-package/present-the-section: - en: 73ca134d685b5872 - zh: 05b929fd28dc955e + en: 4ed05fa030f31fed + zh: 4d9597b68959be93 /deepseek-ai-dsh-client-ui-connector-account/use-this-package/following-operations: en: a9e64f316efcac3e zh: d059d31b65573bf5 diff --git a/packages/client/ui-connector-account/README.md b/packages/client/ui-connector-account/README.md index 1013fb4f48..a8c6386a7b 100644 --- a/packages/client/ui-connector-account/README.md +++ b/packages/client/ui-connector-account/README.md @@ -63,7 +63,7 @@ The registrant imports the registry's types with `import type` from the package |---|---| | Section | Title, status, buttons, detail, notes, failure, and hint. Buttons are disabled while a call the section made is pending or the Host stream is down. A failure shows the registrant's text, then its diagnostic items | | Title tag | The display's `badge`, shown only on the enabled bundle's page or one of its row pages, and only while the display has one | -| Activation prompt | Open while the phase is `disconnected` after the bundle is switched on; Connect opens the bundle page and starts the display's `connect` operation, if it names one. It dismisses itself once the phase settles elsewhere | +| Activation prompt | Open while the phase is `disconnected` after the bundle is switched on; Connect opens the bundle page and starts the display's `connect` operation, if it names one. It waits while the account is checking or connecting and dismisses itself once the account is connected, unavailable, or not running | | Notice | The latest outcome in this browser, outside the Plugins panel's lifetime: the operation's success text, or the shared failure copy with a warning icon | ### Following operations diff --git a/packages/client/ui-connector-account/README.zh.md b/packages/client/ui-connector-account/README.zh.md index a32ed876b2..2de3b35071 100644 --- a/packages/client/ui-connector-account/README.zh.md +++ b/packages/client/ui-connector-account/README.zh.md @@ -63,7 +63,7 @@ export function apply(ctx: Context): void { |---|---| | 区块 | 标题、状态、按钮、说明、附加行、失败信息和提示。区块发起的调用未返回,或 Host 流中断时,按钮不可用。失败时先显示注册方的文案,再显示其诊断项 | | 标题旁标签 | 显示 display 的 `badge`,只出现在已启用插件包的页面或其某一行的页面上,且只在 display 带有标签时显示 | -| 开启引导 | 插件包开启后,阶段为 `disconnected` 时打开;“连接”会打开插件包页面,并在 display 给出 `connect` 时启动该操作。阶段确定为其他值后自动关闭 | +| 开启引导 | 插件包开启后,阶段为 `disconnected` 时打开;“连接”会打开插件包页面,并在 display 给出 `connect` 时启动该操作。账号检查中或连接中时继续等待,已连接、不可用或服务未运行时自动关闭 | | 提示 | 本浏览器的最新结果,不受插件面板生命周期限制:操作成功的文本,或带警告图标的共用失败文案 | ### 跟随操作 diff --git a/packages/client/ui-connector-account/src/client/components.tsx b/packages/client/ui-connector-account/src/client/components.tsx index 93bc807582..9d115051cd 100644 --- a/packages/client/ui-connector-account/src/client/components.tsx +++ b/packages/client/ui-connector-account/src/client/components.tsx @@ -194,14 +194,15 @@ export interface ConnectorAccountActivationProps { /** * Guidance after the user switches a bundle on while its account is not connected. * @param props - the phase, the registrant's text, the dismiss and connect callbacks, and the translator. - * @returns a prompt shown while disconnected; it dismisses itself once the phase settles elsewhere. + * @returns a prompt shown while disconnected; it waits while the account is checking or connecting, which may still end + * disconnected, and dismisses itself once the account is connected or unavailable. */ export function ConnectorAccountActivation(props: ConnectorAccountActivationProps): ReactNode { const { t, phase, title, body, connect, onDismiss, onConnect } = props const needed = phase === 'disconnected' useEffect(() => { - if (phase !== 'checking' && !needed) onDismiss() - }, [phase, needed, onDismiss]) + if (phase === 'connected' || phase === 'unavailable' || phase === 'stopped') onDismiss() + }, [phase, onDismiss]) return ( diff --git a/packages/client/ui-connector-account/tests/components.client.spec.tsx b/packages/client/ui-connector-account/tests/components.client.spec.tsx index c84907ffed..df9a0d0e80 100644 --- a/packages/client/ui-connector-account/tests/components.client.spec.tsx +++ b/packages/client/ui-connector-account/tests/components.client.spec.tsx @@ -110,12 +110,14 @@ it('explains a stopped stream with the shared copy and reopens it even while off expect(onRetry).toHaveBeenCalledOnce() }) -it('prompts to connect only while disconnected and steps aside once the phase settles elsewhere', () => { +it('prompts to connect only while disconnected, waits while checking or connecting, and steps aside once settled', () => { const onDismiss = vi.fn() const onConnect = vi.fn() - const prompt = (phase: 'checking' | 'disconnected' | 'connected') => + const prompt = (phase: 'checking' | 'connecting' | 'disconnected' | 'connected' | 'unavailable' | 'stopped') => const { rerender } = render(prompt('checking')) + // An account still connecting after the bundle is switched on may end disconnected. + rerender(prompt('connecting')) expect(screen.queryByRole('dialog')).toBeNull() expect(onDismiss).not.toHaveBeenCalled() rerender(prompt('disconnected')) @@ -127,6 +129,9 @@ it('prompts to connect only while disconnected and steps aside once the phase se expect(onDismiss).toHaveBeenCalledOnce() rerender(prompt('connected')) expect(onDismiss).toHaveBeenCalledTimes(2) + rerender(prompt('unavailable')) + rerender(prompt('stopped')) + expect(onDismiss).toHaveBeenCalledTimes(4) }) it('shows the latest notice with the registrant text or the shared failure copy', () => { From 3f718d826c7d90a5203e4160a19ea13ce9a66c84 Mon Sep 17 00:00:00 2001 From: gengruilin Date: Sun, 8 Nov 2026 20:09:29 +0800 Subject: [PATCH 04/31] refactor(connector-account): reconnect through the Remote stream and render each surface from its slot entry The browser half no longer reopens a failed stream itself: `$stream` reconnects after a lost connection, and a stream that fails for good keeps the last accounts with their buttons disabled and logs a warning, as other client streams do. The not-running status, tag, detail, and Retry button, with their four shared strings, are removed. Each surface is now one slot entry that reads the browser state and calls the Remote; the separate presentational components and their props types are removed. --- .../ui-connector-account/README.i18n.yaml | 16 +- .../client/ui-connector-account/README.md | 10 +- .../client/ui-connector-account/README.zh.md | 10 +- .../src/client/components.tsx | 295 +++++------------- .../ui-connector-account/src/client/index.ts | 1 - .../src/client/locales.ts | 32 -- .../ui-connector-account/src/client/state.ts | 56 ++-- .../ui-connector-account/src/client/types.ts | 4 - .../tests/apply.client.spec.ts | 5 +- .../tests/components.client.spec.tsx | 227 ++++++-------- .../tests/state.client.spec.ts | 37 +-- 11 files changed, 227 insertions(+), 466 deletions(-) diff --git a/packages/client/ui-connector-account/README.i18n.yaml b/packages/client/ui-connector-account/README.i18n.yaml index 010f9d34c4..63dcb56e37 100644 --- a/packages/client/ui-connector-account/README.i18n.yaml +++ b/packages/client/ui-connector-account/README.i18n.yaml @@ -21,17 +21,17 @@ en: e618281ea7721daf zh: a5d5f5e307ea3435 /deepseek-ai-dsh-client-ui-connector-account/use-this-package/present-the-section: - en: 4ed05fa030f31fed - zh: 4d9597b68959be93 + en: f2bb2f05e2e122a4 + zh: f3dc9945b3f30736 /deepseek-ai-dsh-client-ui-connector-account/use-this-package/following-operations: - en: a9e64f316efcac3e - zh: d059d31b65573bf5 + en: 0f6140d7ed6427b9 + zh: feadef500ee4fd98 /deepseek-ai-dsh-client-ui-connector-account/use-this-package/shared-copy: - en: f88db8d50a68a0ca - zh: 6169fd1ffc9c79a0 + en: 353a48db7e7dd0f7 + zh: 653f3d983d3fd572 /deepseek-ai-dsh-client-ui-connector-account/understand-the-implementation: - en: da424b56f995bef5 - zh: 298fc8e50149fea5 + en: 890bd2109a5b5c4f + zh: f4373b71cb4f2018 /deepseek-ai-dsh-client-ui-connector-account/further-exploration: en: 029949903a73d283 zh: 6f9a8c2f7620de69 diff --git a/packages/client/ui-connector-account/README.md b/packages/client/ui-connector-account/README.md index a8c6386a7b..9f1ac26602 100644 --- a/packages/client/ui-connector-account/README.md +++ b/packages/client/ui-connector-account/README.md @@ -63,16 +63,16 @@ The registrant imports the registry's types with `import type` from the package |---|---| | Section | Title, status, buttons, detail, notes, failure, and hint. Buttons are disabled while a call the section made is pending or the Host stream is down. A failure shows the registrant's text, then its diagnostic items | | Title tag | The display's `badge`, shown only on the enabled bundle's page or one of its row pages, and only while the display has one | -| Activation prompt | Open while the phase is `disconnected` after the bundle is switched on; Connect opens the bundle page and starts the display's `connect` operation, if it names one. It waits while the account is checking or connecting and dismisses itself once the account is connected, unavailable, or not running | +| Activation prompt | Open while the phase is `disconnected` after the bundle is switched on; Connect opens the bundle page and starts the display's `connect` operation, if it names one. It waits while the account is checking or connecting and dismisses itself once the account is connected or unavailable | | Notice | The latest outcome in this browser, outside the Plugins panel's lifetime: the operation's success text, or the shared failure copy with a warning icon | ### Following operations -Each browser opens one stream when the Web app loads, and the Host checks every account that runs no operation for each new stream; an account registered while a stream is open is checked at once. A browser follows the operation its latest start returned, from that answer until the stream delivers the operation's result. Each page the followed operation offers opens once in a new tab, over HTTPS or over HTTP on a loopback address; other browsers show the same section but open no page and report no notice. A second click before the first call answers starts nothing. A stream that fails for good shows the account service as not running with Retry, which reopens the stream once however often it is pressed. Unloading the browser half closes the stream; Host-owned operations keep running. +Each browser opens one stream when the Web app loads, and the Host checks every account that runs no operation for each new stream; an account registered while a stream is open is checked at once. A browser follows the operation its latest start returned, from that answer until the stream delivers the operation's result. Each page the followed operation offers opens once in a new tab, over HTTPS or over HTTP on a loopback address; other browsers show the same section but open no page and report no notice. A second click before the first call answers starts nothing. The stream reconnects after a lost connection; when it fails for good, the sections keep the last accounts with their buttons disabled until the page reloads. Unloading the browser half closes the stream; Host-owned operations keep running. ### Shared copy -The `connectorAccount` dictionary holds the copy every account shares: Close, Cancel, Retry, Later, the diagnostic label, the failure notice, and the not-running status, tag, and detail. Every other string comes from the registrant. +The `connectorAccount` dictionary holds the copy every account shares: Close, Cancel, Later, the diagnostic label, and the failure notice. Every other string comes from the registrant. ----- @@ -84,7 +84,7 @@ The `connectorAccount` dictionary holds the copy every account shares: Close, Ca The Host half, `ConnectorAccounts`, is a Remote service. `register()` observes the account's source, and each `watch` stream reads every account's entry after each change, coalescing changes that arrive before the next read: the key and package, the copy, `present(view)`, the operation in progress, and the latest result with its success text. `start` and `cancel` route by key to the account's source. -[`dsh-api-remotes`](../../api/remotes/README.md) mounts the generated `connectorAccounts` Remote. The browser half opens one `watch` stream through `BrowserAccounts`, whose one store holds the Host's accounts by key, whether the stream is delivering or has stopped, and the latest notice; it also remembers the operations this browser started. It registers one `plugins.detail.badge` entry and one `shell.overlay` notice for the page, and for each account with a package, `plugins.bundle.config` and `plugins.bundle.activation` keyed by the package name, all under the `connectorAccount` namespace. The buttons call `start` and `cancel` on the Remote themselves and report the started operation to `BrowserAccounts`. An account the Host drops loses its bundle entries, and unloading withdraws every entry and the stream. +[`dsh-api-remotes`](../../api/remotes/README.md) mounts the generated `connectorAccounts` Remote. The browser half opens one `watch` stream through `BrowserAccounts`, whose one store holds the Host's accounts by key, whether the stream is delivering, and the latest notice; it also remembers the operations this browser started. It registers one `plugins.detail.badge` entry and one `shell.overlay` notice for the page, and for each account with a package, `plugins.bundle.config` and `plugins.bundle.activation` keyed by the package name, all under the `connectorAccount` namespace. The buttons call `start` and `cancel` on the Remote themselves and report the started operation to `BrowserAccounts`. An account the Host drops loses its bundle entries, and unloading withdraws every entry and the stream. | File | Role | |---|---| @@ -92,7 +92,7 @@ The Host half, `ConnectorAccounts`, is a Remote service. `register()` observes t | [`src/types.ts`](src/types.ts) | Registration, source, view, display, and entry types | | [`src/client/index.ts`](src/client/index.ts) | The browser entry: the dictionary and the slot registrations | | [`src/client/state.ts`](src/client/state.ts) | The stream store, the operations this browser started, and their pages and notices | -| [`src/client/components.tsx`](src/client/components.tsx) | The surfaces, the slot entries, and the buttons' Remote calls | +| [`src/client/components.tsx`](src/client/components.tsx) | The slot entries of each surface and the buttons' Remote calls | | [`src/client/locales.ts`](src/client/locales.ts) | The shared dictionary | | [`src/client/types.ts`](src/client/types.ts) | Browser state, notice, Remote, and face types | diff --git a/packages/client/ui-connector-account/README.zh.md b/packages/client/ui-connector-account/README.zh.md index 2de3b35071..5c00f7a229 100644 --- a/packages/client/ui-connector-account/README.zh.md +++ b/packages/client/ui-connector-account/README.zh.md @@ -63,16 +63,16 @@ export function apply(ctx: Context): void { |---|---| | 区块 | 标题、状态、按钮、说明、附加行、失败信息和提示。区块发起的调用未返回,或 Host 流中断时,按钮不可用。失败时先显示注册方的文案,再显示其诊断项 | | 标题旁标签 | 显示 display 的 `badge`,只出现在已启用插件包的页面或其某一行的页面上,且只在 display 带有标签时显示 | -| 开启引导 | 插件包开启后,阶段为 `disconnected` 时打开;“连接”会打开插件包页面,并在 display 给出 `connect` 时启动该操作。账号检查中或连接中时继续等待,已连接、不可用或服务未运行时自动关闭 | +| 开启引导 | 插件包开启后,阶段为 `disconnected` 时打开;“连接”会打开插件包页面,并在 display 给出 `connect` 时启动该操作。账号检查中或连接中时继续等待,已连接或不可用时自动关闭 | | 提示 | 本浏览器的最新结果,不受插件面板生命周期限制:操作成功的文本,或带警告图标的共用失败文案 | ### 跟随操作 -每个浏览器在 Web 应用加载时打开一条流,Host 为每条新流检查每个没有在运行操作的账号;流打开期间注册的账号会立即检查。浏览器跟随其最近一次启动返回的操作,从返回时起,直到流推送该操作的结果。被跟随的操作提供的每个页面只在新标签页中打开一次,只打开 HTTPS 页面或回环地址上的 HTTP 页面;其他浏览器显示同样的区块,但不打开页面,也不报告提示。第一次调用返回前的第二次点击不会启动任何操作。流永久失败时,区块显示账号服务未运行,并提供“重试”;无论按多少次,都只重新打开流一次。卸载浏览器一半会关闭流;Host 持有的操作继续运行。 +每个浏览器在 Web 应用加载时打开一条流,Host 为每条新流检查每个没有在运行操作的账号;流打开期间注册的账号会立即检查。浏览器跟随其最近一次启动返回的操作,从返回时起,直到流推送该操作的结果。被跟随的操作提供的每个页面只在新标签页中打开一次,只打开 HTTPS 页面或回环地址上的 HTTP 页面;其他浏览器显示同样的区块,但不打开页面,也不报告提示。第一次调用返回前的第二次点击不会启动任何操作。连接断开后流会自动重连;流永久失败时,区块保留最后的账号,按钮不可用,直到页面重新加载。卸载浏览器一半会关闭流;Host 持有的操作继续运行。 ### 共用文案 -`connectorAccount` 字典包含所有账号共用的文案:关闭、取消、重试、稍后、排障信息标签、失败提示,以及未运行时的状态、标签和说明。其余文案都来自注册方。 +`connectorAccount` 字典包含所有账号共用的文案:关闭、取消、稍后、排障信息标签和失败提示。其余文案都来自注册方。 ----- @@ -84,7 +84,7 @@ export function apply(ctx: Context): void { Host 一半 `ConnectorAccounts` 是一个 Remote 服务。`register()` 观察账号来源,每条 `watch` 流在每次变化后读取每个账号的条目,并合并在下一次读取前到达的变化:键和包、文案、`present(view)`、进行中的操作,以及带成功文本的最新结果。`start` 和 `cancel` 按键路由到该账号的来源。 -[`dsh-api-remotes`](../../api/remotes/README.zh.md) 挂载生成的 `connectorAccounts` Remote。浏览器一半通过 `BrowserAccounts` 打开一条 `watch` 流;它的一个 store 保存按键索引的 Host 账号、流是否在推送或已停止,以及最新提示,同时记住本浏览器发起的操作。它为页面注册一个 `plugins.detail.badge` 条目和一个 `shell.overlay` 提示,并为每个带包名的账号注册以包名为键的 `plugins.bundle.config` 和 `plugins.bundle.activation`,全部使用 `connectorAccount` 命名空间。按钮自己调用 Remote 的 `start` 和 `cancel`,并把启动的操作报告给 `BrowserAccounts`。Host 撤下的账号会失去其插件包条目;卸载时撤下所有条目和流。 +[`dsh-api-remotes`](../../api/remotes/README.zh.md) 挂载生成的 `connectorAccounts` Remote。浏览器一半通过 `BrowserAccounts` 打开一条 `watch` 流;它的一个 store 保存按键索引的 Host 账号、流是否在推送,以及最新提示,同时记住本浏览器发起的操作。它为页面注册一个 `plugins.detail.badge` 条目和一个 `shell.overlay` 提示,并为每个带包名的账号注册以包名为键的 `plugins.bundle.config` 和 `plugins.bundle.activation`,全部使用 `connectorAccount` 命名空间。按钮自己调用 Remote 的 `start` 和 `cancel`,并把启动的操作报告给 `BrowserAccounts`。Host 撤下的账号会失去其插件包条目;卸载时撤下所有条目和流。 | 文件 | 职责 | |---|---| @@ -92,7 +92,7 @@ Host 一半 `ConnectorAccounts` 是一个 Remote 服务。`register()` 观察账 | [`src/types.ts`](src/types.ts) | 注册、来源、视图、display 和条目类型 | | [`src/client/index.ts`](src/client/index.ts) | 浏览器入口:字典和插槽注册 | | [`src/client/state.ts`](src/client/state.ts) | 流的 store、本浏览器发起的操作,以及它们的页面和提示 | -| [`src/client/components.tsx`](src/client/components.tsx) | 各界面、插槽条目,以及按钮的 Remote 调用 | +| [`src/client/components.tsx`](src/client/components.tsx) | 各界面的插槽条目,以及按钮的 Remote 调用 | | [`src/client/locales.ts`](src/client/locales.ts) | 共用字典 | | [`src/client/types.ts`](src/client/types.ts) | 浏览器状态、提示、Remote 和 face 类型 | diff --git a/packages/client/ui-connector-account/src/client/components.tsx b/packages/client/ui-connector-account/src/client/components.tsx index 9d115051cd..e0293d02b2 100644 --- a/packages/client/ui-connector-account/src/client/components.tsx +++ b/packages/client/ui-connector-account/src/client/components.tsx @@ -1,38 +1,29 @@ /** - * The account surfaces the Plugins page shows for registered connector accounts: a bundle's section, title tag, and - * activation prompt, the confirmation a button asks for, and the notice, with the slot entries that read them. + * The account surfaces the Plugins page shows for registered connector accounts: a bundle's section with the + * confirmation a button asks for, the title tag, the activation prompt, and the notice. Each is the slot entry that reads + * this browser's state and calls the Remote. */ import { useEffect, useRef, useState, type ReactNode } from 'react' import { Button, IconWarningOutlineRegular, Modal, StateDot, Tag, Toast, type StateDotState, type TagTone } from '@deepseek-ai/dsh-client-ui-primitives' import type { InjectFace, PropsRuntime, Translate } from '@deepseek-ai/dsh-client-ui-slots' import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client' -import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' import { assertNever } from '@deepseek-ai/dsh-util-values' -import type { - ConnectorAccountButton, ConnectorAccountCommand, ConnectorAccountEntry, ConnectorAccountFailure, ConnectorAccountPhase, -} from '../types.ts' +import type { ConnectorAccountButton, ConnectorAccountCommand, ConnectorAccountEntry, ConnectorAccountPhase } from '../types.ts' import css from './ConnectorAccount.module.css' import type { ConnectorAccountKey } from './locales.ts' import { openAuthorizationPage } from './state.ts' -import type { ConnectorAccountFace, ConnectorAccountNotice, ConnectorAccountsState, ConnectorBundleAccountFace } from './types.ts' +import type { ConnectorAccountFace, ConnectorAccountsState, ConnectorBundleAccountFace } from './types.ts' type FaceProps = InjectFace & { t: Translate } type BundleFaceProps = InjectFace & { t: Translate } -type Resolve = (text: LocalizedText) => string -/** The phase a surface shows: the Host's, or `stopped` once this browser's stream failed for good. */ -type ShownPhase = ConnectorAccountPhase | 'stopped' -const TONE: Record = { - checking: 'ongoing', connecting: 'ongoing', connected: 'done', disconnected: 'idle', unavailable: 'warning', stopped: 'warning', +const TONE: Record = { + checking: 'ongoing', connecting: 'ongoing', connected: 'done', disconnected: 'idle', unavailable: 'warning', } -const BADGE_TONE: Record = { - checking: 'outline', connecting: 'info', connected: 'success', disconnected: 'outline', unavailable: 'warning', stopped: 'warning', -} - -function shownPhase(entry: ConnectorAccountEntry, stopped: boolean): ShownPhase { - return stopped ? 'stopped' : entry.display.phase +const BADGE_TONE: Record = { + checking: 'outline', connecting: 'info', connected: 'success', disconnected: 'outline', unavailable: 'warning', } async function settle(call: Promise>): Promise { @@ -42,8 +33,8 @@ async function settle(call: Promise>): Promise { } /** - * Run a section button's command against the Host: start and cancel call the Remote directly, and open shows the - * operation's authorization page again in this browser. + * Run a button's command against the Host: start and cancel call the Remote directly, and open shows the operation's + * authorization page again in this browser. * @param face - the Remote and the browser state the commands report to. * @returns whether a call this surface made has not answered, and the runner of one account's command. */ @@ -81,156 +72,16 @@ function useAccountCommand( return { busy, run } } -/** What the section shows about one account in this browser. */ -export interface ConnectorAccountSectionProps { - readonly t: Translate - readonly resolveText: Resolve - readonly entry: ConnectorAccountEntry - /** Whether the Host stream is delivering. */ - readonly linked: boolean - /** Whether the Host stream failed for good. */ - readonly stopped: boolean - /** Whether a call the section made has not answered. */ - readonly busy: boolean - readonly onCommand: (command: ConnectorAccountCommand) => void - readonly onRetry: () => void -} - -function describe(t: Translate, failure: ConnectorAccountFailure): string | undefined { - const details = failure.details ?? [] - return details.length === 0 ? undefined : t('failure.details', { details: details.join(' · ') }) -} - -/** - * The account section on a bundle page. - * @param props - the account, the stream state, the command and retry callbacks, and the translators. - * @returns the title, status line, detail, rows, failure, hint, and the confirmation a button asked for. - */ -export function ConnectorAccountSection(props: ConnectorAccountSectionProps): ReactNode { - const { t, resolveText, entry, linked, stopped, busy, onCommand, onRetry } = props - const [confirming, setConfirming] = useState() - const display = entry.display - const phase = shownPhase(entry, stopped) - // Reopening a stopped stream is the one action that does not need the Host stream. - const disabled = busy || (!linked && !stopped) - const button = (item: ConnectorAccountButton): ReactNode => { - const label = resolveText(item.label) - const onClick = item.confirm === undefined ? () => { onCommand(item.command) } : () => { setConfirming(item) } - return - } - const failure = stopped ? undefined : display.failure - const diagnostic = failure === undefined ? undefined : describe(t, failure) - const confirm = confirming?.confirm - return ( -
-

{resolveText(entry.copy.title)}

-
- - {stopped ? t('status.stopped') : resolveText(display.status)} -
- {stopped - ? - : display.buttons.map(button)} -
-
- {stopped - ?

{t('detail.stopped')}

- : display.detail === undefined ? null :

{resolveText(display.detail)}

} - {stopped ? null : display.notes.map((note) => { - const text = resolveText(note.text) - return ( -
- {text} - {note.button === undefined ? null :
{button(note.button)}
} -
- ) - })} - {failure === undefined ? null : ( -

{resolveText(failure.text)}{diagnostic === undefined ? null : <> {diagnostic}}

- )} -

{resolveText(entry.copy.hint)}

- {confirming === undefined || confirm === undefined ? null : ( - { setConfirming(undefined) }} - onConfirm={() => { onCommand(confirming.command) }} /> - )} -
- ) -} - -/** The Plugins page detail the tag sits on: an item page, or a bundle or row page with its package. */ -export type ConnectorAccountBadgeSubject = - | { readonly kind: 'item' } - | { readonly kind: 'bundle' | 'row'; readonly pkg: { readonly name: string; readonly enabled: boolean } } - -/** The tag's phase and text. */ -export interface ConnectorAccountBadgeProps { - readonly phase: ShownPhase - /** The tag's text; absent while nothing is settled. */ - readonly text: string | undefined -} - -/** - * The account tag beside a bundle's title. - * @param props - the account's phase and the tag's text. - * @returns the tag, or null while nothing is settled. - */ -export function ConnectorAccountBadge({ phase, text }: ConnectorAccountBadgeProps): ReactNode { - return text === undefined ? null : {text} -} - -/** The prompt's phase, text, and callbacks. */ -export interface ConnectorAccountActivationProps { - readonly t: Translate - readonly phase: ShownPhase - readonly title: string - readonly body: string - /** The connect button's label. */ - readonly connect: string - readonly onDismiss: () => void - readonly onConnect: () => void -} - -/** - * Guidance after the user switches a bundle on while its account is not connected. - * @param props - the phase, the registrant's text, the dismiss and connect callbacks, and the translator. - * @returns a prompt shown while disconnected; it waits while the account is checking or connecting, which may still end - * disconnected, and dismisses itself once the account is connected or unavailable. - */ -export function ConnectorAccountActivation(props: ConnectorAccountActivationProps): ReactNode { - const { t, phase, title, body, connect, onDismiss, onConnect } = props - const needed = phase === 'disconnected' - useEffect(() => { - if (phase === 'connected' || phase === 'unavailable' || phase === 'stopped') onDismiss() - }, [phase, onDismiss]) - return ( - - - - }> -

{body}

-
- ) -} - -/** A confirmation's text and callbacks, with the translator for the shared buttons. */ -export interface ConnectorAccountConfirmProps { +/** Ask before an action that changes the account outside DSH; the dialog closes before it confirms. */ +function Confirm(props: { readonly t: Translate readonly title: string readonly body: string - /** The confirm button's label. */ readonly label: string readonly onClose: () => void readonly onConfirm: () => void -} - -/** - * Confirm an action that changes the account outside DSH. - * @param props - the question and the close and confirm callbacks. - * @returns a dialog that closes before it confirms. - */ -export function ConnectorAccountConfirm({ t, title, body, label, onClose, onConfirm }: ConnectorAccountConfirmProps): ReactNode { +}): ReactNode { + const { t, title, body, label, onClose, onConfirm } = props return ( @@ -242,41 +93,58 @@ export function ConnectorAccountConfirm({ t, title, body, label, onClose, onConf ) } -/** The latest notice and its dismissal, with both translators. */ -export interface ConnectorAccountToastProps { - readonly t: Translate - readonly resolveText: Resolve - readonly notice: ConnectorAccountNotice | undefined - readonly onDone: () => void -} - /** - * Account outcomes reported outside the Plugins panel's lifetime. - * @param props - the latest notice, its dismissal, and the translators. - * @returns the toast for the notice, or null. - */ -export function ConnectorAccountToast({ t, resolveText, notice, onDone }: ConnectorAccountToastProps): ReactNode { - if (notice === undefined) return null - if (notice.kind === 'action-failed') { - return } onDone={onDone} /> - } - return -} - -/** - * The `plugins.bundle.config` entry of a bundle that owns an account. + * The `plugins.bundle.config` entry: the account section on its bundle's page. * @param props - the bundle's face and the translator. - * @returns the section for the account, or null before the Host lists it. + * @returns the title, status line, buttons, detail, notes, failure, hint, and the confirmation a button asked for, or + * null before the Host lists the account. */ export function ConnectorAccountSectionEntry(props: BundleFaceProps): ReactNode { - const { useConnectorAccounts, account, resolveText, retry, t } = props + const { useConnectorAccounts, account, resolveText, t } = props const entry = useConnectorAccounts(state => state.accounts.get(account)) const linked = useConnectorAccounts(state => state.linked) - const stopped = useConnectorAccounts(state => state.stopped) const { busy, run } = useAccountCommand(props) + const [confirming, setConfirming] = useState() if (entry === undefined) return null - return { run(entry, command) }} onRetry={retry} /> + const { display } = entry + const button = (item: ConnectorAccountButton): ReactNode => { + const label = resolveText(item.label) + const onClick = item.confirm === undefined ? () => { run(entry, item.command) } : () => { setConfirming(item) } + return + } + const details = display.failure?.details ?? [] + const confirm = confirming?.confirm + return ( +
+

{resolveText(entry.copy.title)}

+
+ + {resolveText(display.status)} +
{display.buttons.map(button)}
+
+ {display.detail === undefined ? null :

{resolveText(display.detail)}

} + {display.notes.map((note) => { + const text = resolveText(note.text) + return ( +
+ {text} + {note.button === undefined ? null :
{button(note.button)}
} +
+ ) + })} + {display.failure === undefined ? null : ( +

+ {resolveText(display.failure.text)} + {details.length === 0 ? null : <> {t('failure.details', { details: details.join(' · ') })}} +

+ )} +

{resolveText(entry.copy.hint)}

+ {confirming === undefined || confirm === undefined ? null : ( + { setConfirming(undefined) }} onConfirm={() => { run(entry, confirming.command) }} /> + )} +
+ ) } function accountOf(state: ConnectorAccountsState, packageName: string): ConnectorAccountEntry | undefined { @@ -286,34 +154,35 @@ function accountOf(state: ConnectorAccountsState, packageName: string): Connecto /** * The `plugins.detail.badge` entry shared by every bundle that owns an account. - * @param props - the open detail page's subject, the face, and the translator. - * @returns the tag on the page of an enabled bundle that owns an account, or of one of its rows, or null. + * @param props - the open detail page's subject and the face. + * @returns the display's tag on the page of an enabled bundle that owns an account, or of one of its rows, or null. */ export function ConnectorAccountBadgeEntry(props: FaceProps & Pick, 'subject'>): ReactNode { - const { useConnectorAccounts, resolveText, subject, t } = props - const page: ConnectorAccountBadgeSubject = subject - const packageName = page.kind === 'item' || !page.pkg.enabled ? undefined : page.pkg.name + const { useConnectorAccounts, resolveText, subject } = props + const packageName = subject.kind === 'item' || !subject.pkg.enabled ? undefined : subject.pkg.name const entry = useConnectorAccounts(state => packageName === undefined ? undefined : accountOf(state, packageName)) - const stopped = useConnectorAccounts(state => state.stopped) - if (entry === undefined) return null - const badge = entry.display.badge - const text = stopped ? t('badge.stopped') : badge === undefined ? undefined : resolveText(badge) - return + const badge = entry?.display.badge + return entry === undefined || badge === undefined ? null : {resolveText(badge)} } /** - * The `plugins.bundle.activation` entry of a bundle that owns an account; Connect opens the bundle page and starts the - * display's `connect` command. + * The `plugins.bundle.activation` entry: guidance after the user switches a bundle on while its account is not + * connected. Connect opens the bundle page and starts the display's `connect` command. * @param props - activation callbacks, the bundle's face, and the translator. - * @returns the prompt for the account, or null before the Host lists it. + * @returns a prompt shown while disconnected, or null before the Host lists the account. It waits while the account is + * checking or connecting, which may still end disconnected, and dismisses itself once the account is connected or + * unavailable. */ export function ConnectorAccountActivationEntry( props: BundleFaceProps & Pick, 'onDismiss' | 'onOpenDetails'>, ): ReactNode { const { useConnectorAccounts, account, resolveText, onDismiss, onOpenDetails, t } = props const entry = useConnectorAccounts(state => state.accounts.get(account)) - const stopped = useConnectorAccounts(state => state.stopped) const { run } = useAccountCommand(props) + const phase = entry?.display.phase + useEffect(() => { + if (phase === 'connected' || phase === 'unavailable') onDismiss() + }, [phase, onDismiss]) if (entry === undefined) return null const { activation } = entry.copy const { connect } = entry.display @@ -322,17 +191,25 @@ export function ConnectorAccountActivationEntry( if (connect !== undefined) run(entry, connect) } return ( - + + + + }> +

{resolveText(activation.body)}

+
) } /** - * The `shell.overlay` entry. + * The `shell.overlay` entry: account outcomes reported outside the Plugins panel's lifetime. * @param props - the face and the translator. * @returns the toast for the latest notice, or null. */ export function ConnectorAccountToastEntry({ useConnectorAccounts, resolveText, dismissNotice, t }: FaceProps): ReactNode { const notice = useConnectorAccounts(state => state.notice) - return + if (notice === undefined) return null + return notice.kind === 'action-failed' + ? } onDone={dismissNotice} /> + : } diff --git a/packages/client/ui-connector-account/src/client/index.ts b/packages/client/ui-connector-account/src/client/index.ts index c76264c8f5..2c15e0ec09 100644 --- a/packages/client/ui-connector-account/src/client/index.ts +++ b/packages/client/ui-connector-account/src/client/index.ts @@ -53,7 +53,6 @@ export function apply(ctx: Context): void { resolveText: text => ctx.locale.resolveText(text), follow: (key, id) => { browser.follow(key, id) }, failed: () => { browser.failed() }, - retry: () => { browser.retry() }, dismissNotice: () => { browser.dismissNotice() }, } ctx.effect(function* () { diff --git a/packages/client/ui-connector-account/src/client/locales.ts b/packages/client/ui-connector-account/src/client/locales.ts index 57e76d24f1..c0a30b7555 100644 --- a/packages/client/ui-connector-account/src/client/locales.ts +++ b/packages/client/ui-connector-account/src/client/locales.ts @@ -8,13 +8,9 @@ export const NS = 'connectorAccount' export const zh = { close: '关闭', 'action.cancel': '取消', - 'action.retry': '重试', 'activation.later': '稍后', 'failure.details': '排障信息:{details}', 'notice.action-failed': '操作未完成,请重试', - 'badge.stopped': '未运行', - 'status.stopped': '账号服务未运行', - 'detail.stopped': '暂时无法读取账号状态,可以重试。', } /** Every key the shared account surfaces translate. */ @@ -24,91 +20,63 @@ export type ConnectorAccountKey = keyof typeof zh export const en: Record = { close: 'Close', 'action.cancel': 'Cancel', - 'action.retry': 'Retry', 'activation.later': 'Later', 'failure.details': 'Diagnostic: {details}', 'notice.action-failed': 'The action did not finish. Try again.', - 'badge.stopped': 'Not running', - 'status.stopped': 'Account service not running', - 'detail.stopped': 'The account status cannot be read right now. Retry to reconnect.', } /** Japanese dictionary. */ export const ja: Record = { close: '閉じる', 'action.cancel': 'キャンセル', - 'action.retry': '再試行', 'activation.later': '後で', 'failure.details': '診断情報:{details}', 'notice.action-failed': '操作が完了しませんでした。もう一度お試しください。', - 'badge.stopped': '未稼働', - 'status.stopped': 'アカウントサービスが稼働していません', - 'detail.stopped': 'アカウントの状態を現在読み取れません。再試行して再接続してください。', } /** Spanish dictionary. */ export const es: Record = { close: 'Cerrar', 'action.cancel': 'Cancelar', - 'action.retry': 'Reintentar', 'activation.later': 'Más tarde', 'failure.details': 'Diagnóstico: {details}', 'notice.action-failed': 'La acción no se completó. Inténtelo de nuevo.', - 'badge.stopped': 'No está en ejecución', - 'status.stopped': 'El servicio de cuentas no está en ejecución', - 'detail.stopped': 'No se puede leer el estado de la cuenta en este momento. Reintente para volver a conectar.', } /** French dictionary. */ export const fr: Record = { close: 'Fermer', 'action.cancel': 'Annuler', - 'action.retry': 'Réessayer', 'activation.later': 'Plus tard', 'failure.details': 'Diagnostic : {details}', 'notice.action-failed': 'L’action n’a pas abouti. Réessayez.', - 'badge.stopped': 'Ne fonctionne pas', - 'status.stopped': 'Le service de comptes ne fonctionne pas', - 'detail.stopped': 'L’état du compte ne peut pas être lu pour le moment. Réessayez pour vous reconnecter.', } /** German dictionary. */ export const de: Record = { close: 'Schließen', 'action.cancel': 'Abbrechen', - 'action.retry': 'Erneut versuchen', 'activation.later': 'Später', 'failure.details': 'Diagnose: {details}', 'notice.action-failed': 'Die Aktion wurde nicht abgeschlossen. Versuchen Sie es erneut.', - 'badge.stopped': 'Läuft nicht', - 'status.stopped': 'Kontodienst läuft nicht', - 'detail.stopped': 'Der Kontostatus kann gerade nicht gelesen werden. Versuchen Sie es erneut, um die Verbindung wiederherzustellen.', } /** Russian dictionary. */ export const ru: Record = { close: 'Закрыть', 'action.cancel': 'Отмена', - 'action.retry': 'Повторить', 'activation.later': 'Позже', 'failure.details': 'Диагностика: {details}', 'notice.action-failed': 'Действие не завершено. Повторите попытку.', - 'badge.stopped': 'Не работает', - 'status.stopped': 'Служба аккаунтов не работает', - 'detail.stopped': 'Сейчас не удаётся прочитать состояние аккаунта. Повторите попытку, чтобы переподключиться.', } /** Portuguese dictionary. */ export const pt: Record = { close: 'Fechar', 'action.cancel': 'Cancelar', - 'action.retry': 'Tentar novamente', 'activation.later': 'Mais tarde', 'failure.details': 'Diagnóstico: {details}', 'notice.action-failed': 'A ação não foi concluída. Tente novamente.', - 'badge.stopped': 'Não está em execução', - 'status.stopped': 'O serviço de contas não está em execução', - 'detail.stopped': 'Não é possível ler o estado da conta agora. Tente novamente para reconectar.', } declare module '@deepseek-ai/dsh-client-ui-slots' { diff --git a/packages/client/ui-connector-account/src/client/state.ts b/packages/client/ui-connector-account/src/client/state.ts index 2d4954ddb8..332715e431 100644 --- a/packages/client/ui-connector-account/src/client/state.ts +++ b/packages/client/ui-connector-account/src/client/state.ts @@ -28,7 +28,7 @@ export function openAuthorizationPage(url: string | undefined): void { export class BrowserAccounts { /** The accounts, stream state, and notice every surface on the page reads. */ readonly state: SnapshotStore = createSnapshotStore({ - accounts: new Map(), linked: true, stopped: false, notice: undefined, + accounts: new Map(), linked: true, notice: undefined, }) /** @@ -38,15 +38,20 @@ export class BrowserAccounts { private readonly followed = new Map }>() private seq = 0 private disposed = false - private stream!: RemoteStream - private observing!: Promise + private readonly stream: RemoteStream + private readonly observing: Promise /** * @param ctx - the browser context carrying the Remote client. * @param remote - the `connectorAccounts` Remote. */ - constructor(private readonly ctx: Context, private readonly remote: Pick) { - this.subscribe() + constructor(private readonly ctx: Context, remote: Pick) { + this.stream = ctx.remote.$stream({ + name: 'Connector accounts', open: signal => remote.watch(signal), + ended: () => new Error('Connector accounts stream ended'), + carrierFailed: () => { this.patch({ linked: false }) }, + }) + this.observing = this.observe() } /** @@ -72,17 +77,9 @@ export class BrowserAccounts { this.patch({ notice: undefined }) } - /** Reopen the Host stream after it stopped; ignored while it runs, while a reopen is pending, or after disposal. */ - retry(): void { - if (this.disposed || !this.state.getSnapshot().stopped) return - // Clearing `stopped` before the reopen awaits claims it, so a second retry finds nothing to reopen. - this.patch({ stopped: false }) - void this.reopen() - } - /** - * Stop observing the Host; afterwards the page opens no page, reports nothing more, and a pending retry opens no stream. - * Host-owned operations keep running. + * Stop observing the Host; afterwards the page opens no page and reports nothing more. Host-owned operations keep + * running. * @returns after the stream closes. */ async dispose(): Promise { @@ -91,39 +88,26 @@ export class BrowserAccounts { await this.observing } - private subscribe(): void { - this.stream = this.ctx.remote.$stream({ - name: 'Connector accounts', open: signal => this.remote.watch(signal), - ended: () => new Error('Connector accounts stream ended'), - carrierFailed: () => { this.patch({ linked: false }) }, - }) - this.observing = this.observe(this.stream) - } - - private async observe(stream: RemoteStream): Promise { + private async observe(): Promise { try { - for await (const item of stream) { + for await (const item of this.stream) { // An item the stream yielded just before disposal must not reach the disposed page. if (this.disposed) return this.show(item.value.accounts) item.accept() } - } catch { - // A terminal failure, such as a Host without the registry, ends the stream; a disposed page shows nothing. - if (!this.disposed) this.patch({ linked: false, stopped: true }) + } catch (error) { + // A terminal failure, such as a Host without the registry, leaves the buttons disabled until the page reloads. + if (this.disposed) return + this.patch({ linked: false }) + this.ctx.logger.warn('connector accounts stream failed; reload the page to reconnect: %s', error) } } - private async reopen(): Promise { - await this.stream.dispose() - await this.observing - if (!this.disposed) this.subscribe() - } - private show(entries: readonly ConnectorAccountEntry[]): void { const accounts = new Map(entries.map(entry => [entry.key, entry])) for (const key of [...this.followed.keys()]) if (!accounts.has(key)) this.followed.delete(key) - this.patch({ accounts, linked: true, stopped: false }) + this.patch({ accounts, linked: true }) for (const entry of entries) this.track(entry) } diff --git a/packages/client/ui-connector-account/src/client/types.ts b/packages/client/ui-connector-account/src/client/types.ts index 8ed18a7c81..482363c688 100644 --- a/packages/client/ui-connector-account/src/client/types.ts +++ b/packages/client/ui-connector-account/src/client/types.ts @@ -15,8 +15,6 @@ export interface ConnectorAccountsState { readonly accounts: ReadonlyMap /** Whether the Host stream is delivering. */ readonly linked: boolean - /** Whether the Host stream failed for good; `retry` reopens it. */ - readonly stopped: boolean readonly notice: ConnectorAccountNotice | undefined } @@ -38,8 +36,6 @@ export interface ConnectorAccountFace { readonly follow: (key: string, id: ConnectorOperationId) => void /** Report that a Remote call this browser made did not finish. */ readonly failed: () => void - /** Reopen the Host stream after it stopped. */ - readonly retry: () => void readonly dismissNotice: () => void } diff --git a/packages/client/ui-connector-account/tests/apply.client.spec.ts b/packages/client/ui-connector-account/tests/apply.client.spec.ts index 20481db45e..d01ff8c3f2 100644 --- a/packages/client/ui-connector-account/tests/apply.client.spec.ts +++ b/packages/client/ui-connector-account/tests/apply.client.spec.ts @@ -98,7 +98,7 @@ async function bench() { it('shows one tag and one notice entry for the page and each bundle\'s section and prompt under the shared dictionary', async () => { const b = await bench() await b.mount() - expect(b.locale.bind(NS)('action.retry')).toBe('Retry') + expect(b.locale.bind(NS)('action.cancel')).toBe('Cancel') expect(b.ctx.slots.entries('plugins.detail.badge').map(item => [item.options.id, item.component])).toEqual([ ['connector-account.badge', ConnectorAccountBadgeEntry], ]) @@ -130,7 +130,6 @@ it('shows one tag and one notice entry for the page and each bundle\'s section a face.failed() expect(face.hooks.connectorAccounts.getSnapshot().notice).toEqual({ seq: 1, kind: 'action-failed' }) face.dismissNotice() - face.retry() expect(face.hooks.connectorAccounts.getSnapshot().notice).toBeUndefined() // A dropped account withdraws its bundle's surfaces, and a bundle whose account changed key shows the new one. @@ -151,6 +150,6 @@ it('withdraws every surface, the dictionaries, and the stream when the plugin un for (const slot of ['plugins.bundle.config', 'plugins.bundle.activation', 'plugins.detail.badge', 'shell.overlay'] as const) { expect(b.ctx.slots.entries(slot)).toEqual([]) } - expect(b.locale.bind(NS)('action.retry')).toBe('action.retry') + expect(b.locale.bind(NS)('action.cancel')).toBe('action.cancel') expect(b.closeStream).toHaveBeenCalledOnce() }) diff --git a/packages/client/ui-connector-account/tests/components.client.spec.tsx b/packages/client/ui-connector-account/tests/components.client.spec.tsx index df9a0d0e80..25978b5ac3 100644 --- a/packages/client/ui-connector-account/tests/components.client.spec.tsx +++ b/packages/client/ui-connector-account/tests/components.client.spec.tsx @@ -1,5 +1,5 @@ // @vitest-environment jsdom -/** The surfaces render each registrant's display from the Host with the shared copy, and buttons call the Remote directly. */ +/** The slot entries render each registrant's display from the Host with the shared copy, and buttons call the Remote directly. */ import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' import type { PluginsSubject } from '@deepseek-ai/dsh-client-ui-plugin-manager/client' @@ -7,8 +7,7 @@ import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' import { RemoteError, type RemoteResult } from '@deepseek-ai/dsh-typert-protocol' import { afterEach, expect, it, onTestFinished, vi } from 'vitest' import { - ConnectorAccountActivation, ConnectorAccountActivationEntry, ConnectorAccountBadgeEntry, ConnectorAccountSection, - ConnectorAccountSectionEntry, ConnectorAccountToast, ConnectorAccountToastEntry, + ConnectorAccountActivationEntry, ConnectorAccountBadgeEntry, ConnectorAccountSectionEntry, ConnectorAccountToastEntry, } from '../src/client/components.tsx' import { zh } from '../src/client/locales.ts' import type { ConnectorAccountsState } from '../src/client/types.ts' @@ -22,6 +21,7 @@ const t = makeTranslate(zh) const resolveText = (text: LocalizedText): string => typeof text === 'string' ? text : text.zh ?? text.en const button = (name: string) => screen.getByRole('button', { name }) const disabled = (): boolean[] => screen.getAllByRole('button').map(element => (element as HTMLButtonElement).disabled) +const click = async (name: string) => { await act(async () => { fireEvent.click(button(name)) }) } const DISCONNECTED: ConnectorAccountDisplay = { phase: 'disconnected', status: { en: 'Not connected', zh: '未连接' }, badge: '未连接', @@ -36,122 +36,12 @@ function entry(display: ConnectorAccountDisplay = DISCONNECTED, extra: Partial = {}, display?: ConnectorAccountDisplay) { - const onCommand = vi.fn() - const onRetry = vi.fn() - const view = render( - , - ) - return { ...view, onCommand, onRetry } -} - -it('shows the registrant title, status, detail, notes, and hint, and runs each button as its command', () => { - const display: ConnectorAccountDisplay = { - ...DISCONNECTED, detail: '先关联一个应用。', - notes: [{ text: '应用:cli_a', button: { label: '更换', command: { kind: 'start', operation: 'link-app' }, variant: 'ghost' } }, { text: '普通说明' }], - } - const { container, onCommand } = section({}, display) - expect(screen.getByText('演示账号')).toBeTruthy() - expect(screen.getByText('未连接')).toBeTruthy() - expect(screen.getByText('先关联一个应用。')).toBeTruthy() - expect(screen.getByText('普通说明')).toBeTruthy() - expect(screen.getByText('与终端共用。')).toBeTruthy() - expect(container.querySelector('[data-connector-account="disconnected"][data-connector-account-key="@acme/fixture"]')).toBeTruthy() - fireEvent.click(button('连接演示')) - fireEvent.click(button('更换')) - expect(onCommand.mock.calls).toEqual([[{ kind: 'start', operation: 'connect' }], [{ kind: 'start', operation: 'link-app' }]]) -}) - -it('disables the buttons while a call is pending or the Host stream is down', () => { - const { rerender } = section({ busy: true }) - expect(disabled()).toEqual([true]) - rerender( - , - ) - expect(disabled()).toEqual([true]) -}) - -it('asks before a button that changes the account outside DSH and runs it only after the user accepts', () => { - const display: ConnectorAccountDisplay = { - phase: 'connected', status: '已连接', notes: [], - buttons: [{ label: '退出登录', command: { kind: 'start', operation: 'sign-out' }, confirm: { title: '退出演示?', body: '终端也会退出。', label: '确认退出' } }], - } - const { onCommand } = section({}, display) - fireEvent.click(button('退出登录')) - expect(screen.getByRole('dialog', { name: '退出演示?' })).toBeTruthy() - expect(screen.getByText('终端也会退出。')).toBeTruthy() - fireEvent.click(button(zh['action.cancel'])) - expect(screen.queryByRole('dialog')).toBeNull() - fireEvent.click(button('退出登录')) - fireEvent.click(button('确认退出')) - expect(screen.queryByRole('dialog')).toBeNull() - expect(onCommand.mock.calls).toEqual([[{ kind: 'start', operation: 'sign-out' }]]) -}) - -it.each<[string, ConnectorAccountDisplay['failure'], string]>([ - ['the guidance, then its diagnostic items', { text: '失败。', details: ['login', 'exit 3', 'internal'] }, '失败。 排障信息:login · exit 3 · internal'], - ['the guidance alone without diagnostic items', { text: '失败。' }, '失败。'], - ['the guidance alone for an empty diagnostic list', { text: '失败。', details: [] }, '失败。'], -])('reports %s', (_name, failure, expected) => { - section({}, { ...DISCONNECTED, ...failure === undefined ? {} : { failure } }) - expect(screen.getByRole('alert').textContent).toBe(expected) -}) - -it('explains a stopped stream with the shared copy and reopens it even while offline', () => { - const { container, onRetry } = section({ stopped: true, linked: false }, { ...DISCONNECTED, failure: { text: '失败。' }, notes: [{ text: '说明' }] }) - expect(screen.getByText(zh['status.stopped'])).toBeTruthy() - expect(screen.getByText(zh['detail.stopped'])).toBeTruthy() - expect(screen.queryByRole('alert')).toBeNull() - expect(screen.queryByText('说明')).toBeNull() - expect(container.querySelector('[data-connector-account="stopped"]')).toBeTruthy() - fireEvent.click(button(zh['action.retry'])) - expect(onRetry).toHaveBeenCalledOnce() -}) - -it('prompts to connect only while disconnected, waits while checking or connecting, and steps aside once settled', () => { - const onDismiss = vi.fn() - const onConnect = vi.fn() - const prompt = (phase: 'checking' | 'connecting' | 'disconnected' | 'connected' | 'unavailable' | 'stopped') => - - const { rerender } = render(prompt('checking')) - // An account still connecting after the bundle is switched on may end disconnected. - rerender(prompt('connecting')) - expect(screen.queryByRole('dialog')).toBeNull() - expect(onDismiss).not.toHaveBeenCalled() - rerender(prompt('disconnected')) - expect(screen.getByRole('dialog', { name: '连接演示' })).toBeTruthy() - expect(screen.getByText('插件已开启。')).toBeTruthy() - fireEvent.click(button('立即连接')) - expect(onConnect).toHaveBeenCalledOnce() - fireEvent.click(button(zh['activation.later'])) - expect(onDismiss).toHaveBeenCalledOnce() - rerender(prompt('connected')) - expect(onDismiss).toHaveBeenCalledTimes(2) - rerender(prompt('unavailable')) - rerender(prompt('stopped')) - expect(onDismiss).toHaveBeenCalledTimes(4) -}) - -it('shows the latest notice with the registrant text or the shared failure copy', () => { - const onDone = vi.fn() - const toast = (notice: ConnectorAccountsState['notice']) => - - const { rerender } = render(toast(undefined)) - expect(document.body.textContent).toBe('') - rerender(toast({ seq: 1, kind: 'succeeded', text: { en: 'Connected', zh: '演示已连接' } })) - expect(screen.getByText('演示已连接')).toBeTruthy() - rerender(toast({ seq: 2, kind: 'action-failed' })) - expect(screen.getByText(zh['notice.action-failed'])).toBeTruthy() -}) - const ok = (value: T): RemoteResult => ({ ok: true, value }) const refused = (): RemoteResult => ({ ok: false, error: new RemoteError('gateway/internal', 'offline', {}) }) as never function face(change: Partial = {}, accounts: readonly ConnectorAccountEntry[] = [entry()]) { const current: ConnectorAccountsState = { - accounts: new Map(accounts.map(item => [item.key, item])), linked: true, stopped: false, notice: undefined, ...change, + accounts: new Map(accounts.map(item => [item.key, item])), linked: true, notice: undefined, ...change, } return { useConnectorAccounts: (selector: (value: ConnectorAccountsState) => R): R => selector(current), @@ -159,30 +49,75 @@ function face(change: Partial = {}, accounts: readonly C start: vi.fn(async (_key: string, _operation: string) => ok(OP)), cancel: vi.fn(async (_key: string, _id: ConnectorOperationId): Promise> => ok(undefined)), }, - account: KEY, resolveText, follow: vi.fn(), failed: vi.fn(), retry: vi.fn(), dismissNotice: vi.fn(), t, + account: KEY, resolveText, follow: vi.fn(), failed: vi.fn(), dismissNotice: vi.fn(), t, } } -it('starts an operation through the Remote, follows it, and stays busy until the call answers', async () => { +const sectionOf = (display: ConnectorAccountDisplay, change: Partial = {}) => face(change, [entry(display)]) +const prompt = (props: ReturnType, onDismiss = vi.fn(), onOpenDetails = vi.fn()) => + + +it('shows the registrant title, status, detail, notes, and hint, and starts each button\'s operation through the Remote', async () => { + const props = sectionOf({ + ...DISCONNECTED, detail: '先关联一个应用。', + notes: [{ text: '应用:cli_a', button: { label: '更换', command: { kind: 'start', operation: 'link-app' }, variant: 'ghost' } }, { text: '普通说明' }], + }) + const { container } = render() + for (const text of ['演示账号', '未连接', '先关联一个应用。', '普通说明', '与终端共用。']) expect(screen.getByText(text)).toBeTruthy() + expect(container.querySelector('[data-connector-account="disconnected"][data-connector-account-key="@acme/fixture"]')).toBeTruthy() + await click('连接演示') + await click('更换') + expect(props.remote.start.mock.calls).toEqual([[KEY, 'connect'], [KEY, 'link-app']]) + expect(props.follow.mock.calls).toEqual([[KEY, OP], [KEY, OP]]) +}) + +it('disables the buttons while a call is pending or the Host stream is down', async () => { const props = face() const answer = Promise.withResolvers>() props.remote.start.mockReturnValueOnce(answer.promise) render() fireEvent.click(button('连接演示')) - expect(props.remote.start).toHaveBeenCalledWith(KEY, 'connect') expect(disabled()).toEqual([true]) await act(async () => { answer.resolve(ok(OP)) }) - expect(props.follow).toHaveBeenCalledWith(KEY, OP) expect(disabled()).toEqual([false]) expect(props.failed).not.toHaveBeenCalled() + cleanup() + render() + expect(disabled()).toEqual([true]) +}) + +it('asks before a button that changes the account outside DSH and starts it only after the user accepts', async () => { + const props = sectionOf({ + phase: 'connected', status: '已连接', notes: [], + buttons: [{ label: '退出登录', command: { kind: 'start', operation: 'sign-out' }, confirm: { title: '退出演示?', body: '终端也会退出。', label: '确认退出' } }], + }) + render() + fireEvent.click(button('退出登录')) + expect(screen.getByRole('dialog', { name: '退出演示?' })).toBeTruthy() + expect(screen.getByText('终端也会退出。')).toBeTruthy() + fireEvent.click(button(zh['action.cancel'])) + expect(screen.queryByRole('dialog')).toBeNull() + fireEvent.click(button('退出登录')) + await click('确认退出') + expect(screen.queryByRole('dialog')).toBeNull() + expect(props.remote.start.mock.calls).toEqual([[KEY, 'sign-out']]) +}) + +it.each<[string, ConnectorAccountDisplay['failure'], string]>([ + ['the guidance, then its diagnostic items', { text: '失败。', details: ['login', 'exit 3', 'internal'] }, '失败。 排障信息:login · exit 3 · internal'], + ['the guidance alone without diagnostic items', { text: '失败。' }, '失败。'], + ['the guidance alone for an empty diagnostic list', { text: '失败。', details: [] }, '失败。'], +])('reports %s', (_name, failure, expected) => { + render() + expect(screen.getByRole('alert').textContent).toBe(expected) }) it('reports a start the Host refused or that never answered, without following it', async () => { const props = face() props.remote.start.mockResolvedValueOnce(refused()).mockRejectedValueOnce(new Error('carrier lost')) render() - await act(async () => { fireEvent.click(button('连接演示')) }) - await act(async () => { fireEvent.click(button('连接演示')) }) + await click('连接演示') + await click('连接演示') expect(props.failed).toHaveBeenCalledTimes(2) expect(props.follow).not.toHaveBeenCalled() }) @@ -198,26 +133,23 @@ it('cancels the operation in progress and opens its authorization page again on render() fireEvent.click(button('打开授权页')) expect(windowOpen).toHaveBeenCalledWith('https://example.com/a', '_blank', 'noopener,noreferrer') - await act(async () => { fireEvent.click(button('取消')) }) + await click('取消') expect(props.remote.cancel).toHaveBeenCalledWith(KEY, OP) // A cancel button with no operation in progress calls nothing. cleanup() - const idle = face({}, [entry(display)]) + const idle = sectionOf(display) render() - await act(async () => { fireEvent.click(button('取消')) }) + await click('取消') expect(idle.remote.cancel).not.toHaveBeenCalled() }) -const prompt = (props: ReturnType, onOpenDetails = vi.fn()) => - - it('renders nothing for a bundle whose account the Host has not listed', () => { render() render(prompt(face({}, []))) expect(document.body.textContent).toBe('') }) -it('tags only the enabled bundle that owns an account, with the Host text or the shared copy once the stream stopped', () => { +it('tags only the enabled bundle that owns an account, with the display\'s tag', () => { const pkg = (name: string, enabled = true) => ({ name, installed: true, availability: 'profile', official: false, enabled, rows: [] } as const) const page = (name: string, enabled = true): PluginsSubject => ({ kind: 'bundle', pkg: pkg(name, enabled) }) const row: PluginsSubject = { kind: 'row', pkg: pkg(KEY), row: { rowId: 'fixture', moduleName: '@acme/fixture-row', enabled: true } } @@ -226,33 +158,49 @@ it('tags only the enabled bundle that owns an account, with the Host text or the expect(screen.getByText('未连接')).toBeTruthy() rerender(tag(face(), row)) expect(screen.getByText('未连接')).toBeTruthy() - rerender(tag(face({ stopped: true }), page(KEY))) - expect(screen.getByText(zh['badge.stopped'])).toBeTruthy() for (const [props, subject] of [ [face(), page(KEY, false)], [face(), page('@acme/other')], [face(), { kind: 'item', id: 'fixture-item' }], - [face({}, [entry({ phase: 'checking', status: '检查中', buttons: [], notes: [] })]), page(KEY)], + [sectionOf({ phase: 'checking', status: '检查中', buttons: [], notes: [] }), page(KEY)], ] as const) { rerender(tag(props, subject)) expect(document.body.textContent).toBe('') } }) +it('prompts to connect only while disconnected, waits while checking or connecting, and dismisses itself once settled', () => { + const onDismiss = vi.fn() + const at = (phase: ConnectorAccountDisplay['phase']) => prompt(sectionOf({ phase, status: phase, buttons: [], notes: [] }), onDismiss) + const { rerender } = render(at('checking')) + // An account still connecting after the bundle is switched on may end disconnected. + rerender(at('connecting')) + expect(screen.queryByRole('dialog')).toBeNull() + expect(onDismiss).not.toHaveBeenCalled() + rerender(at('disconnected')) + expect(screen.getByRole('dialog', { name: '连接演示' })).toBeTruthy() + expect(screen.getByText('插件已开启。')).toBeTruthy() + fireEvent.click(button(zh['activation.later'])) + expect(onDismiss).toHaveBeenCalledOnce() + rerender(at('connected')) + rerender(at('unavailable')) + expect(onDismiss).toHaveBeenCalledTimes(3) +}) + it('connects from the prompt through the operation the display names, or only opens the page', async () => { const onOpenDetails = vi.fn() - const named = face({}, [entry({ ...DISCONNECTED, connect: { kind: 'start', operation: 'link-app' } })]) - const { rerender } = render(prompt(named, onOpenDetails)) - await act(async () => { fireEvent.click(button('连接演示')) }) + const named = sectionOf({ ...DISCONNECTED, connect: { kind: 'start', operation: 'link-app' } }) + const { rerender } = render(prompt(named, vi.fn(), onOpenDetails)) + await click('连接演示') expect(onOpenDetails).toHaveBeenCalledOnce() expect(named.remote.start).toHaveBeenCalledWith(KEY, 'link-app') const bare = face() - rerender(prompt(bare, onOpenDetails)) + rerender(prompt(bare, vi.fn(), onOpenDetails)) fireEvent.click(button('连接演示')) expect(onOpenDetails).toHaveBeenCalledTimes(2) expect(bare.remote.start).not.toHaveBeenCalled() }) it('starts once for a second click before the first call answers', async () => { - const props = face({}, [entry({ ...DISCONNECTED, connect: { kind: 'start', operation: 'connect' } })]) + const props = sectionOf({ ...DISCONNECTED, connect: { kind: 'start', operation: 'connect' } }) const answer = Promise.withResolvers>() props.remote.start.mockReturnValueOnce(answer.promise) render(prompt(props)) @@ -263,7 +211,12 @@ it('starts once for a second click before the first call answers', async () => { expect(props.follow).toHaveBeenCalledOnce() }) -it('shows the account notice through the toast entry', () => { - render() +it('shows the latest notice with the registrant text or the shared failure copy', () => { + const toast = (notice: ConnectorAccountsState['notice']) => + const { rerender } = render(toast(undefined)) + expect(document.body.textContent).toBe('') + rerender(toast({ seq: 1, kind: 'succeeded', text: { en: 'Connected', zh: '演示已连接' } })) expect(screen.getByText('演示已连接')).toBeTruthy() + rerender(toast({ seq: 2, kind: 'action-failed' })) + expect(screen.getByText(zh['notice.action-failed'])).toBeTruthy() }) diff --git a/packages/client/ui-connector-account/tests/state.client.spec.ts b/packages/client/ui-connector-account/tests/state.client.spec.ts index 490b4dcae3..4c11668ac2 100644 --- a/packages/client/ui-connector-account/tests/state.client.spec.ts +++ b/packages/client/ui-connector-account/tests/state.client.spec.ts @@ -52,7 +52,7 @@ function fixture() { const browser = new BrowserAccounts(ctx, remote) onTestFinished(async () => { await browser.dispose(); windowOpen.mockRestore(); await ctx.fiber.dispose() }) return { - browser, remote, open: windowOpen, streams, options: () => options, + ctx, browser, remote, open: windowOpen, streams, options: () => options, state: () => browser.state.getSnapshot(), deliver(view: ConnectorAccountsView) { queue.push(view); wake?.() }, async publish(...entries: ConnectorAccountEntry[]) { @@ -64,12 +64,9 @@ function fixture() { } } -// Every fixture step settles through microtasks, so one macrotask lets a pending reopen finish. -const drain = () => new Promise((resolve) => { setTimeout(resolve, 0) }) - it('mirrors the Host accounts by key and reports carrier loss until the next item', async () => { const b = fixture() - expect(b.state()).toEqual({ accounts: new Map(), linked: true, stopped: false, notice: undefined }) + expect(b.state()).toEqual({ accounts: new Map(), linked: true, notice: undefined }) const open = b.options().open(new AbortController().signal) expect(b.remote.watch).toHaveBeenCalledOnce() expect(open).toBe(b.remote.watch.mock.results[0]?.value) @@ -78,7 +75,7 @@ it('mirrors the Host accounts by key and reports carrier loss until the next ite b.options().carrierFailed?.(new RemoteStreamCarrierError('offline')) expect(b.state().linked).toBe(false) await b.publish(entry(FIXTURE)) - expect(b.state()).toMatchObject({ linked: true, stopped: false }) + expect(b.state().linked).toBe(true) expect([...b.state().accounts.keys()]).toEqual([FIXTURE]) expect(b.options().ended(true).message).toBe('Connector accounts stream ended') }) @@ -135,34 +132,22 @@ it('reports a call that did not finish with a fresh notice each time', () => { expect(b.state().notice).toEqual({ seq: 2, kind: 'action-failed' }) }) -it('stops after a terminal stream failure and reopens on retry', async () => { +it('keeps the buttons disabled and logs a terminal stream failure, opening no second stream', async () => { const b = fixture() + const warn = vi.spyOn(b.ctx.logger, 'warn').mockImplementation(() => {}) await b.publish(entry(FIXTURE)) - b.browser.retry() - expect(b.streams).toHaveLength(1) b.fail(new Error('Host without the registry')) - await vi.waitFor(() => { expect(b.state().stopped).toBe(true) }) - expect(b.state().linked).toBe(false) - b.browser.retry() - b.browser.retry() - await drain() - expect(b.streams).toHaveLength(2) - expect(b.streams[0]?.dispose).toHaveBeenCalledOnce() - await b.publish(entry(FIXTURE)) - expect(b.state()).toMatchObject({ linked: true, stopped: false }) + await vi.waitFor(() => { expect(b.state().linked).toBe(false) }) + expect(warn).toHaveBeenCalledWith(expect.stringContaining('connector accounts stream failed'), expect.any(Error)) + expect(b.streams).toHaveLength(1) + expect([...b.state().accounts.keys()]).toEqual([FIXTURE]) }) -it('opens nothing and reports nothing after disposal, and a retry pending at disposal opens no stream', async () => { +it('opens nothing and reports nothing after disposal', async () => { const b = fixture() - b.fail(new Error('Host without the registry')) - await vi.waitFor(() => { expect(b.state().stopped).toBe(true) }) - b.browser.retry() await b.browser.dispose() - await drain() - expect(b.streams).toHaveLength(1) b.browser.follow(FIXTURE, OP) b.browser.failed() - b.browser.retry() expect(b.state().notice).toBeUndefined() }) @@ -171,7 +156,7 @@ it('shows nothing for a stream that fails while the page disposes it', async () const disposing = b.browser.dispose() b.fail(new Error('carrier lost')) await disposing - expect(b.state()).toMatchObject({ linked: true, stopped: false }) + expect(b.state().linked).toBe(true) }) it('ignores an item the stream yielded just before disposal', async () => { From a5859c3fc4e4a62a35094af0237580fa13ef01a3 Mon Sep 17 00:00:00 2001 From: gengruilin Date: Mon, 9 Nov 2026 14:21:58 +0800 Subject: [PATCH 05/31] fix(connector-account): inject Host callbacks, gate dialogs on the stream, and wrap narrow rows The surfaces receive `start` and `cancel` callbacks that unwrap the Remote result in the apply closure instead of the Remote itself, as the client inject rule requires. An open confirmation disables its button under the same conditions as the section's buttons, and the activation prompt's Connect is disabled while the Host stream is down. The status row and its buttons wrap, so a long status or long button labels stay inside a narrow panel. --- .../ui-connector-account/README.i18n.yaml | 8 +-- .../client/ui-connector-account/README.md | 6 +- .../client/ui-connector-account/README.zh.md | 6 +- .../src/client/ConnectorAccount.module.css | 5 ++ .../src/client/components.tsx | 50 +++++++------- .../ui-connector-account/src/client/index.ts | 14 +++- .../ui-connector-account/src/client/types.ts | 9 ++- .../tests/apply.client.spec.ts | 17 +++-- .../tests/components.client.spec.tsx | 65 ++++++++++++------- 9 files changed, 111 insertions(+), 69 deletions(-) diff --git a/packages/client/ui-connector-account/README.i18n.yaml b/packages/client/ui-connector-account/README.i18n.yaml index 63dcb56e37..64303c4159 100644 --- a/packages/client/ui-connector-account/README.i18n.yaml +++ b/packages/client/ui-connector-account/README.i18n.yaml @@ -21,8 +21,8 @@ en: e618281ea7721daf zh: a5d5f5e307ea3435 /deepseek-ai-dsh-client-ui-connector-account/use-this-package/present-the-section: - en: f2bb2f05e2e122a4 - zh: f3dc9945b3f30736 + en: fcbc46fc932ed5c8 + zh: 2f1cce21453bced6 /deepseek-ai-dsh-client-ui-connector-account/use-this-package/following-operations: en: 0f6140d7ed6427b9 zh: feadef500ee4fd98 @@ -30,8 +30,8 @@ en: 353a48db7e7dd0f7 zh: 653f3d983d3fd572 /deepseek-ai-dsh-client-ui-connector-account/understand-the-implementation: - en: 890bd2109a5b5c4f - zh: f4373b71cb4f2018 + en: 8c16bb36ce00d4cc + zh: d52d2a6f2beacf21 /deepseek-ai-dsh-client-ui-connector-account/further-exploration: en: 029949903a73d283 zh: 6f9a8c2f7620de69 diff --git a/packages/client/ui-connector-account/README.md b/packages/client/ui-connector-account/README.md index 9f1ac26602..1226880ada 100644 --- a/packages/client/ui-connector-account/README.md +++ b/packages/client/ui-connector-account/README.md @@ -61,9 +61,9 @@ The registrant imports the registry's types with `import type` from the package | Surface | Behavior | |---|---| -| Section | Title, status, buttons, detail, notes, failure, and hint. Buttons are disabled while a call the section made is pending or the Host stream is down. A failure shows the registrant's text, then its diagnostic items | +| Section | Title, status, buttons, detail, notes, failure, and hint. Buttons, including a confirmation's, are disabled while a call the section made is pending or the Host stream is down. A failure shows the registrant's text, then its diagnostic items | | Title tag | The display's `badge`, shown only on the enabled bundle's page or one of its row pages, and only while the display has one | -| Activation prompt | Open while the phase is `disconnected` after the bundle is switched on; Connect opens the bundle page and starts the display's `connect` operation, if it names one. It waits while the account is checking or connecting and dismisses itself once the account is connected or unavailable | +| Activation prompt | Open while the phase is `disconnected` after the bundle is switched on; Connect opens the bundle page and starts the display's `connect` operation, if it names one, and is disabled while the Host stream is down. It waits while the account is checking or connecting and dismisses itself once the account is connected or unavailable | | Notice | The latest outcome in this browser, outside the Plugins panel's lifetime: the operation's success text, or the shared failure copy with a warning icon | ### Following operations @@ -84,7 +84,7 @@ The `connectorAccount` dictionary holds the copy every account shares: Close, Ca The Host half, `ConnectorAccounts`, is a Remote service. `register()` observes the account's source, and each `watch` stream reads every account's entry after each change, coalescing changes that arrive before the next read: the key and package, the copy, `present(view)`, the operation in progress, and the latest result with its success text. `start` and `cancel` route by key to the account's source. -[`dsh-api-remotes`](../../api/remotes/README.md) mounts the generated `connectorAccounts` Remote. The browser half opens one `watch` stream through `BrowserAccounts`, whose one store holds the Host's accounts by key, whether the stream is delivering, and the latest notice; it also remembers the operations this browser started. It registers one `plugins.detail.badge` entry and one `shell.overlay` notice for the page, and for each account with a package, `plugins.bundle.config` and `plugins.bundle.activation` keyed by the package name, all under the `connectorAccount` namespace. The buttons call `start` and `cancel` on the Remote themselves and report the started operation to `BrowserAccounts`. An account the Host drops loses its bundle entries, and unloading withdraws every entry and the stream. +[`dsh-api-remotes`](../../api/remotes/README.md) mounts the generated `connectorAccounts` Remote. The browser half opens one `watch` stream through `BrowserAccounts`, whose one store holds the Host's accounts by key, whether the stream is delivering, and the latest notice; it also remembers the operations this browser started. It registers one `plugins.detail.badge` entry and one `shell.overlay` notice for the page, and for each account with a package, `plugins.bundle.config` and `plugins.bundle.activation` keyed by the package name, all under the `connectorAccount` namespace. The surfaces receive `start` and `cancel` callbacks that call the Remote and reject when the Host refuses or the call does not answer; the buttons await them and report the started operation to `BrowserAccounts`. An account the Host drops loses its bundle entries, and unloading withdraws every entry and the stream. | File | Role | |---|---| diff --git a/packages/client/ui-connector-account/README.zh.md b/packages/client/ui-connector-account/README.zh.md index 5c00f7a229..845d244b47 100644 --- a/packages/client/ui-connector-account/README.zh.md +++ b/packages/client/ui-connector-account/README.zh.md @@ -61,9 +61,9 @@ export function apply(ctx: Context): void { | 界面 | 行为 | |---|---| -| 区块 | 标题、状态、按钮、说明、附加行、失败信息和提示。区块发起的调用未返回,或 Host 流中断时,按钮不可用。失败时先显示注册方的文案,再显示其诊断项 | +| 区块 | 标题、状态、按钮、说明、附加行、失败信息和提示。区块发起的调用未返回,或 Host 流中断时,按钮(包括确认框的按钮)不可用。失败时先显示注册方的文案,再显示其诊断项 | | 标题旁标签 | 显示 display 的 `badge`,只出现在已启用插件包的页面或其某一行的页面上,且只在 display 带有标签时显示 | -| 开启引导 | 插件包开启后,阶段为 `disconnected` 时打开;“连接”会打开插件包页面,并在 display 给出 `connect` 时启动该操作。账号检查中或连接中时继续等待,已连接或不可用时自动关闭 | +| 开启引导 | 插件包开启后,阶段为 `disconnected` 时打开;“连接”会打开插件包页面,并在 display 给出 `connect` 时启动该操作;Host 流中断时它不可用。账号检查中或连接中时继续等待,已连接或不可用时自动关闭 | | 提示 | 本浏览器的最新结果,不受插件面板生命周期限制:操作成功的文本,或带警告图标的共用失败文案 | ### 跟随操作 @@ -84,7 +84,7 @@ export function apply(ctx: Context): void { Host 一半 `ConnectorAccounts` 是一个 Remote 服务。`register()` 观察账号来源,每条 `watch` 流在每次变化后读取每个账号的条目,并合并在下一次读取前到达的变化:键和包、文案、`present(view)`、进行中的操作,以及带成功文本的最新结果。`start` 和 `cancel` 按键路由到该账号的来源。 -[`dsh-api-remotes`](../../api/remotes/README.zh.md) 挂载生成的 `connectorAccounts` Remote。浏览器一半通过 `BrowserAccounts` 打开一条 `watch` 流;它的一个 store 保存按键索引的 Host 账号、流是否在推送,以及最新提示,同时记住本浏览器发起的操作。它为页面注册一个 `plugins.detail.badge` 条目和一个 `shell.overlay` 提示,并为每个带包名的账号注册以包名为键的 `plugins.bundle.config` 和 `plugins.bundle.activation`,全部使用 `connectorAccount` 命名空间。按钮自己调用 Remote 的 `start` 和 `cancel`,并把启动的操作报告给 `BrowserAccounts`。Host 撤下的账号会失去其插件包条目;卸载时撤下所有条目和流。 +[`dsh-api-remotes`](../../api/remotes/README.zh.md) 挂载生成的 `connectorAccounts` Remote。浏览器一半通过 `BrowserAccounts` 打开一条 `watch` 流;它的一个 store 保存按键索引的 Host 账号、流是否在推送,以及最新提示,同时记住本浏览器发起的操作。它为页面注册一个 `plugins.detail.badge` 条目和一个 `shell.overlay` 提示,并为每个带包名的账号注册以包名为键的 `plugins.bundle.config` 和 `plugins.bundle.activation`,全部使用 `connectorAccount` 命名空间。各界面收到 `start` 和 `cancel` 两个回调:它们调用 Remote,在 Host 拒绝或调用没有回应时 reject;按钮等待回调结果,并把启动的操作报告给 `BrowserAccounts`。Host 撤下的账号会失去其插件包条目;卸载时撤下所有条目和流。 | 文件 | 职责 | |---|---| diff --git a/packages/client/ui-connector-account/src/client/ConnectorAccount.module.css b/packages/client/ui-connector-account/src/client/ConnectorAccount.module.css index c15f495d50..0ad221ae6f 100644 --- a/packages/client/ui-connector-account/src/client/ConnectorAccount.module.css +++ b/packages/client/ui-connector-account/src/client/ConnectorAccount.module.css @@ -13,12 +13,16 @@ .status { display: flex; + flex-wrap: wrap; align-items: center; gap: 8px; min-height: 28px; } .label { + flex: 1 1 auto; + min-width: 0; + overflow-wrap: anywhere; font-size: 13px; line-height: 20px; color: var(--dsw-alias-label-primary); @@ -26,6 +30,7 @@ .actions { display: flex; + flex-wrap: wrap; gap: 8px; margin-left: auto; } diff --git a/packages/client/ui-connector-account/src/client/components.tsx b/packages/client/ui-connector-account/src/client/components.tsx index e0293d02b2..483d8924ff 100644 --- a/packages/client/ui-connector-account/src/client/components.tsx +++ b/packages/client/ui-connector-account/src/client/components.tsx @@ -1,13 +1,12 @@ /** * The account surfaces the Plugins page shows for registered connector accounts: a bundle's section with the * confirmation a button asks for, the title tag, the activation prompt, and the notice. Each is the slot entry that reads - * this browser's state and calls the Remote. + * this browser's state and calls the Host through the injected callbacks. */ import { useEffect, useRef, useState, type ReactNode } from 'react' import { Button, IconWarningOutlineRegular, Modal, StateDot, Tag, Toast, type StateDotState, type TagTone } from '@deepseek-ai/dsh-client-ui-primitives' import type { InjectFace, PropsRuntime, Translate } from '@deepseek-ai/dsh-client-ui-slots' import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client' -import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' import { assertNever } from '@deepseek-ai/dsh-util-values' import type { ConnectorAccountButton, ConnectorAccountCommand, ConnectorAccountEntry, ConnectorAccountPhase } from '../types.ts' import css from './ConnectorAccount.module.css' @@ -26,21 +25,21 @@ const BADGE_TONE: Record = { checking: 'outline', connecting: 'info', connected: 'success', disconnected: 'outline', unavailable: 'warning', } -async function settle(call: Promise>): Promise { - const result = await call - if (!result.ok) throw new Error(result.error.message) - return result.value -} - /** - * Run a button's command against the Host: start and cancel call the Remote directly, and open shows the operation's - * authorization page again in this browser. - * @param face - the Remote and the browser state the commands report to. - * @returns whether a call this surface made has not answered, and the runner of one account's command. + * Run a button's command against the Host: start and cancel call the face's callbacks, and open shows the + * operation's authorization page again in this browser. + * @param face - the Host callbacks and the browser state the commands read and report to. + * @returns whether a call this surface made has not answered, whether the Host stream is delivering, and the runner of + * one account's command. */ function useAccountCommand( - face: Pick, -): { readonly busy: boolean; readonly run: (entry: ConnectorAccountEntry, command: ConnectorAccountCommand) => void } { + face: Pick, +): { + readonly busy: boolean + readonly linked: boolean + readonly run: (entry: ConnectorAccountEntry, command: ConnectorAccountCommand) => void +} { + const linked = face.useConnectorAccounts(state => state.linked) const [busy, setBusy] = useState(false) // A second click before the re-render still finds the first call pending. const pending = useRef(false) @@ -55,11 +54,11 @@ function useAccountCommand( const { key } = entry switch (command.kind) { case 'start': - call(async () => { face.follow(key, await settle(face.remote.start(key, command.operation))) }) + call(async () => { face.follow(key, await face.start(key, command.operation)) }) return case 'cancel': { const operation = entry.operation - if (operation !== undefined) call(async () => { await settle(face.remote.cancel(key, operation.id)) }) + if (operation !== undefined) call(async () => { await face.cancel(key, operation.id) }) return } case 'open': @@ -69,7 +68,7 @@ function useAccountCommand( default: assertNever(command) } } - return { busy, run } + return { busy, linked, run } } /** Ask before an action that changes the account outside DSH; the dialog closes before it confirms. */ @@ -78,15 +77,16 @@ function Confirm(props: { readonly title: string readonly body: string readonly label: string + readonly disabled: boolean readonly onClose: () => void readonly onConfirm: () => void }): ReactNode { - const { t, title, body, label, onClose, onConfirm } = props + const { t, title, body, label, disabled, onClose, onConfirm } = props return ( - + }>

{body}

@@ -102,15 +102,15 @@ function Confirm(props: { export function ConnectorAccountSectionEntry(props: BundleFaceProps): ReactNode { const { useConnectorAccounts, account, resolveText, t } = props const entry = useConnectorAccounts(state => state.accounts.get(account)) - const linked = useConnectorAccounts(state => state.linked) - const { busy, run } = useAccountCommand(props) + const { busy, linked, run } = useAccountCommand(props) + const disabled = busy || !linked const [confirming, setConfirming] = useState() if (entry === undefined) return null const { display } = entry const button = (item: ConnectorAccountButton): ReactNode => { const label = resolveText(item.label) const onClick = item.confirm === undefined ? () => { run(entry, item.command) } : () => { setConfirming(item) } - return + return } const details = display.failure?.details ?? [] const confirm = confirming?.confirm @@ -141,7 +141,7 @@ export function ConnectorAccountSectionEntry(props: BundleFaceProps): ReactNode

{resolveText(entry.copy.hint)}

{confirming === undefined || confirm === undefined ? null : ( { setConfirming(undefined) }} onConfirm={() => { run(entry, confirming.command) }} /> + disabled={disabled} onClose={() => { setConfirming(undefined) }} onConfirm={() => { run(entry, confirming.command) }} /> )} ) @@ -178,7 +178,7 @@ export function ConnectorAccountActivationEntry( ): ReactNode { const { useConnectorAccounts, account, resolveText, onDismiss, onOpenDetails, t } = props const entry = useConnectorAccounts(state => state.accounts.get(account)) - const { run } = useAccountCommand(props) + const { linked, run } = useAccountCommand(props) const phase = entry?.display.phase useEffect(() => { if (phase === 'connected' || phase === 'unavailable') onDismiss() @@ -194,7 +194,7 @@ export function ConnectorAccountActivationEntry( - + }>

{resolveText(activation.body)}

diff --git a/packages/client/ui-connector-account/src/client/index.ts b/packages/client/ui-connector-account/src/client/index.ts index 2c15e0ec09..d0e9f7cb05 100644 --- a/packages/client/ui-connector-account/src/client/index.ts +++ b/packages/client/ui-connector-account/src/client/index.ts @@ -10,6 +10,7 @@ import type {} from '@deepseek-ai/dsh-client-locale/client' import type {} from '@deepseek-ai/dsh-client-ui-layout/client' import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client' import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' +import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' import { ConnectorAccountActivationEntry, ConnectorAccountBadgeEntry, ConnectorAccountSectionEntry, ConnectorAccountToastEntry, } from './components.tsx' @@ -25,6 +26,13 @@ export type { /** The `connectorAccounts` Remote that `dsh-api-remotes` mounts, and the services the slot registrations need. */ export const inject = ['remote', 'remote.connectorAccounts', 'slots', 'locale'] +/** The value of a Remote call, or a rejection with the Host's message when the Host refused it. */ +async function settle(call: Promise>): Promise { + const result = await call + if (!result.ok) throw new Error(result.error.message) + return result.value +} + function registerBundle(ctx: Context, face: ConnectorAccountFace, packageName: string, account: string): () => void { const bundle = { ...face, account } const dispose = ctx.effect(function* () { @@ -45,11 +53,13 @@ function registerBundle(ctx: Context, face: ConnectorAccountFace, packageName: s */ export function apply(ctx: Context): void { ctx.effect(() => ctx.locale.register(NS, { zh, en, ja, es, fr, de, ru, pt }), 'connector-account: dictionaries') - const browser = new BrowserAccounts(ctx, ctx.remote.connectorAccounts) + const remote = ctx.remote.connectorAccounts + const browser = new BrowserAccounts(ctx, remote) ctx.effect(() => async () => { await browser.dispose() }, 'connector-account: stream') const face: ConnectorAccountFace = { hooks: { connectorAccounts: browser.state }, - remote: ctx.remote.connectorAccounts, + start: (key, operation) => settle(remote.start(key, operation)), + cancel: (key, id) => settle(remote.cancel(key, id)), resolveText: text => ctx.locale.resolveText(text), follow: (key, id) => { browser.follow(key, id) }, failed: () => { browser.failed() }, diff --git a/packages/client/ui-connector-account/src/client/types.ts b/packages/client/ui-connector-account/src/client/types.ts index 482363c688..89a7a333b0 100644 --- a/packages/client/ui-connector-account/src/client/types.ts +++ b/packages/client/ui-connector-account/src/client/types.ts @@ -28,8 +28,13 @@ export interface ConnectorAccountsRemote { /** The face every surface entry injects. */ export interface ConnectorAccountFace { hooks: { connectorAccounts: HostObservable } - /** The Remote the buttons call directly. */ - readonly remote: Pick + /** + * Start an operation of an account on the Host. Resolves to the operation the Host started, and rejects when the Host + * refuses or the call does not answer. + */ + readonly start: (key: string, operation: string) => Promise + /** Cancel an account's operation on the Host; rejects like `start`. */ + readonly cancel: (key: string, id: ConnectorOperationId) => Promise /** Pick the active language's entry of a registrant's text. */ readonly resolveText: (text: LocalizedText) => string /** Remember an operation this browser started: its authorization page opens here, and its success is reported here. */ diff --git a/packages/client/ui-connector-account/tests/apply.client.spec.ts b/packages/client/ui-connector-account/tests/apply.client.spec.ts index d01ff8c3f2..6c6ad38b68 100644 --- a/packages/client/ui-connector-account/tests/apply.client.spec.ts +++ b/packages/client/ui-connector-account/tests/apply.client.spec.ts @@ -6,7 +6,7 @@ import assert from 'node:assert/strict' import { Context, Service } from '@deepseek-ai/cordis' import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' -import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import { RemoteError, type RemoteResult } from '@deepseek-ai/dsh-typert-protocol' import { expect, it, onTestFinished, vi } from 'vitest' import { ConnectorAccountActivationEntry, ConnectorAccountBadgeEntry, ConnectorAccountSectionEntry, ConnectorAccountToastEntry, @@ -21,7 +21,8 @@ const OTHER = '@acme/other' const OP = 'op-1' as ConnectorOperationId function isFace(value: Record): asserts value is Record & ConnectorAccountFace { - assert(typeof value.resolveText === 'function' && typeof value.follow === 'function' && typeof value.remote === 'object') + assert(typeof value.resolveText === 'function' && typeof value.follow === 'function') + assert(typeof value.start === 'function' && typeof value.cancel === 'function') assert(typeof value.hooks === 'object' && value.hooks !== null) } @@ -54,6 +55,7 @@ async function bench() { let wake: (() => void) | undefined, closed = false, accepted = 0 const closeStream = vi.fn(async () => { closed = true; wake?.() }) const start = vi.fn(async (_key: string, _operation: string): Promise> => ({ ok: true, value: OP })) + const cancel = vi.fn(async (_key: string, _id: ConnectorOperationId): Promise> => ({ ok: true, value: undefined })) class Remote extends Service { constructor() { super(ctx, 'remote') } $stream() { @@ -71,7 +73,7 @@ async function bench() { } } new Remote() - ctx.provide('remote.connectorAccounts', { watch: vi.fn(), start, cancel: vi.fn() }) + ctx.provide('remote.connectorAccounts', { watch: vi.fn(), start, cancel }) const locale = new LocaleRuntime(ctx) ctx.provide('locale', locale) await ctx.plugin(SlotRegistry) @@ -84,7 +86,7 @@ async function bench() { const bundles = (slot: 'plugins.bundle.config' | 'plugins.bundle.activation') => ctx.slots.entries(slot).map(item => [item.options.key, bundleFaceOf(item).account]) return { - ctx, locale, start, closeStream, bundles, + ctx, locale, start, cancel, closeStream, bundles, mount: () => ctx.plugin({ inject: [...inject], apply }), async publish(...entries: ConnectorAccountEntry[]) { const target = accepted + 1 @@ -124,8 +126,13 @@ it('shows one tag and one notice entry for the page and each bundle\'s section a expect(faceOf(toast).hooks.connectorAccounts).toBe(face.hooks.connectorAccounts) expect([...face.hooks.connectorAccounts.getSnapshot().accounts.keys()]).toEqual([FIXTURE, OTHER, 'mcp:custom']) expect(face.resolveText({ en: 'Connected', zh: '已连接' })).toBe('Connected') - await face.remote.start(FIXTURE, 'connect') + expect(await face.start(FIXTURE, 'connect')).toBe(OP) expect(b.start).toHaveBeenCalledWith(FIXTURE, 'connect') + await face.cancel(FIXTURE, OP) + expect(b.cancel).toHaveBeenCalledWith(FIXTURE, OP) + // A refusal reaches the buttons as a rejection with the Host's message. + b.start.mockResolvedValueOnce({ ok: false, error: new RemoteError('gateway/internal', 'offline', {}) } as never) + await expect(face.start(FIXTURE, 'connect')).rejects.toThrow('offline') face.follow(FIXTURE, OP) face.failed() expect(face.hooks.connectorAccounts.getSnapshot().notice).toEqual({ seq: 1, kind: 'action-failed' }) diff --git a/packages/client/ui-connector-account/tests/components.client.spec.tsx b/packages/client/ui-connector-account/tests/components.client.spec.tsx index 25978b5ac3..222db693f6 100644 --- a/packages/client/ui-connector-account/tests/components.client.spec.tsx +++ b/packages/client/ui-connector-account/tests/components.client.spec.tsx @@ -1,10 +1,9 @@ // @vitest-environment jsdom -/** The slot entries render each registrant's display from the Host with the shared copy, and buttons call the Remote directly. */ +/** The slot entries render each registrant's display from the Host with the shared copy, and buttons call the Host callbacks. */ import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' import type { PluginsSubject } from '@deepseek-ai/dsh-client-ui-plugin-manager/client' import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' -import { RemoteError, type RemoteResult } from '@deepseek-ai/dsh-typert-protocol' import { afterEach, expect, it, onTestFinished, vi } from 'vitest' import { ConnectorAccountActivationEntry, ConnectorAccountBadgeEntry, ConnectorAccountSectionEntry, ConnectorAccountToastEntry, @@ -36,19 +35,14 @@ function entry(display: ConnectorAccountDisplay = DISCONNECTED, extra: Partial(value: T): RemoteResult => ({ ok: true, value }) -const refused = (): RemoteResult => ({ ok: false, error: new RemoteError('gateway/internal', 'offline', {}) }) as never - function face(change: Partial = {}, accounts: readonly ConnectorAccountEntry[] = [entry()]) { const current: ConnectorAccountsState = { accounts: new Map(accounts.map(item => [item.key, item])), linked: true, notice: undefined, ...change, } return { useConnectorAccounts: (selector: (value: ConnectorAccountsState) => R): R => selector(current), - remote: { - start: vi.fn(async (_key: string, _operation: string) => ok(OP)), - cancel: vi.fn(async (_key: string, _id: ConnectorOperationId): Promise> => ok(undefined)), - }, + start: vi.fn(async (_key: string, _operation: string) => OP), + cancel: vi.fn(async (_key: string, _id: ConnectorOperationId) => {}), account: KEY, resolveText, follow: vi.fn(), failed: vi.fn(), dismissNotice: vi.fn(), t, } } @@ -57,7 +51,7 @@ const sectionOf = (display: ConnectorAccountDisplay, change: Partial, onDismiss = vi.fn(), onOpenDetails = vi.fn()) => -it('shows the registrant title, status, detail, notes, and hint, and starts each button\'s operation through the Remote', async () => { +it('shows the registrant title, status, detail, notes, and hint, and starts each button\'s operation on the Host', async () => { const props = sectionOf({ ...DISCONNECTED, detail: '先关联一个应用。', notes: [{ text: '应用:cli_a', button: { label: '更换', command: { kind: 'start', operation: 'link-app' }, variant: 'ghost' } }, { text: '普通说明' }], @@ -67,18 +61,18 @@ it('shows the registrant title, status, detail, notes, and hint, and starts each expect(container.querySelector('[data-connector-account="disconnected"][data-connector-account-key="@acme/fixture"]')).toBeTruthy() await click('连接演示') await click('更换') - expect(props.remote.start.mock.calls).toEqual([[KEY, 'connect'], [KEY, 'link-app']]) + expect(props.start.mock.calls).toEqual([[KEY, 'connect'], [KEY, 'link-app']]) expect(props.follow.mock.calls).toEqual([[KEY, OP], [KEY, OP]]) }) it('disables the buttons while a call is pending or the Host stream is down', async () => { const props = face() - const answer = Promise.withResolvers>() - props.remote.start.mockReturnValueOnce(answer.promise) + const answer = Promise.withResolvers() + props.start.mockReturnValueOnce(answer.promise) render() fireEvent.click(button('连接演示')) expect(disabled()).toEqual([true]) - await act(async () => { answer.resolve(ok(OP)) }) + await act(async () => { answer.resolve(OP) }) expect(disabled()).toEqual([false]) expect(props.failed).not.toHaveBeenCalled() cleanup() @@ -100,7 +94,28 @@ it('asks before a button that changes the account outside DSH and starts it only fireEvent.click(button('退出登录')) await click('确认退出') expect(screen.queryByRole('dialog')).toBeNull() - expect(props.remote.start.mock.calls).toEqual([[KEY, 'sign-out']]) + expect(props.start.mock.calls).toEqual([[KEY, 'sign-out']]) +}) + +it('disables an open confirmation and the activation prompt\'s Connect while the Host stream is down', () => { + const display: ConnectorAccountDisplay = { + phase: 'connected', status: '已连接', notes: [], + buttons: [{ label: '退出登录', command: { kind: 'start', operation: 'sign-out' }, confirm: { title: '退出演示?', body: '终端也会退出。', label: '确认退出' } }], + } + const { rerender } = render() + fireEvent.click(button('退出登录')) + // The stream drops while the confirmation is open. + const down = sectionOf(display, { linked: false }) + rerender() + fireEvent.click(button('确认退出')) + expect((button('确认退出') as HTMLButtonElement).disabled).toBe(true) + expect(down.start).not.toHaveBeenCalled() + cleanup() + const offline = sectionOf({ ...DISCONNECTED, connect: { kind: 'start', operation: 'connect' } }, { linked: false }) + render(prompt(offline)) + fireEvent.click(button('连接演示')) + expect((button('连接演示') as HTMLButtonElement).disabled).toBe(true) + expect(offline.start).not.toHaveBeenCalled() }) it.each<[string, ConnectorAccountDisplay['failure'], string]>([ @@ -112,9 +127,9 @@ it.each<[string, ConnectorAccountDisplay['failure'], string]>([ expect(screen.getByRole('alert').textContent).toBe(expected) }) -it('reports a start the Host refused or that never answered, without following it', async () => { +it('reports a start that the Host refused or that never answered, without following it', async () => { const props = face() - props.remote.start.mockResolvedValueOnce(refused()).mockRejectedValueOnce(new Error('carrier lost')) + props.start.mockRejectedValueOnce(new Error('offline')).mockRejectedValueOnce(new Error('carrier lost')) render() await click('连接演示') await click('连接演示') @@ -134,13 +149,13 @@ it('cancels the operation in progress and opens its authorization page again on fireEvent.click(button('打开授权页')) expect(windowOpen).toHaveBeenCalledWith('https://example.com/a', '_blank', 'noopener,noreferrer') await click('取消') - expect(props.remote.cancel).toHaveBeenCalledWith(KEY, OP) + expect(props.cancel).toHaveBeenCalledWith(KEY, OP) // A cancel button with no operation in progress calls nothing. cleanup() const idle = sectionOf(display) render() await click('取消') - expect(idle.remote.cancel).not.toHaveBeenCalled() + expect(idle.cancel).not.toHaveBeenCalled() }) it('renders nothing for a bundle whose account the Host has not listed', () => { @@ -191,23 +206,23 @@ it('connects from the prompt through the operation the display names, or only op const { rerender } = render(prompt(named, vi.fn(), onOpenDetails)) await click('连接演示') expect(onOpenDetails).toHaveBeenCalledOnce() - expect(named.remote.start).toHaveBeenCalledWith(KEY, 'link-app') + expect(named.start).toHaveBeenCalledWith(KEY, 'link-app') const bare = face() rerender(prompt(bare, vi.fn(), onOpenDetails)) fireEvent.click(button('连接演示')) expect(onOpenDetails).toHaveBeenCalledTimes(2) - expect(bare.remote.start).not.toHaveBeenCalled() + expect(bare.start).not.toHaveBeenCalled() }) it('starts once for a second click before the first call answers', async () => { const props = sectionOf({ ...DISCONNECTED, connect: { kind: 'start', operation: 'connect' } }) - const answer = Promise.withResolvers>() - props.remote.start.mockReturnValueOnce(answer.promise) + const answer = Promise.withResolvers() + props.start.mockReturnValueOnce(answer.promise) render(prompt(props)) fireEvent.click(button('连接演示')) fireEvent.click(button('连接演示')) - await act(async () => { answer.resolve(ok(OP)) }) - expect(props.remote.start).toHaveBeenCalledOnce() + await act(async () => { answer.resolve(OP) }) + expect(props.start).toHaveBeenCalledOnce() expect(props.follow).toHaveBeenCalledOnce() }) From 27a32189d3c70c21274dd21c39e7e592c9b70876 Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Tue, 10 Nov 2026 16:02:57 +0800 Subject: [PATCH 06/31] fix(checks): preserve cordis preset identifiers --- scripts/rescope-vendor.spec.ts | 14 ++++++++++++++ scripts/rescope-vendor.ts | 3 +++ 2 files changed, 17 insertions(+) diff --git a/scripts/rescope-vendor.spec.ts b/scripts/rescope-vendor.spec.ts index 4f43ef08fe..0eb3b530f8 100644 --- a/scripts/rescope-vendor.spec.ts +++ b/scripts/rescope-vendor.spec.ts @@ -87,6 +87,7 @@ describe('product identifiers', () => { it.each([ 'apps/cli/tests/optional-bundle-transitions.e2e.ts', 'apps/web/tests/agent-preset-selection.e2e.ts', + 'apps/web/tests/creator-persona.e2e.ts', 'apps/web/tests/developer-tools-settings.e2e.ts', 'docs/subsystems/extensions.md', 'docs/subsystems/extensions.zh.md', @@ -98,6 +99,8 @@ describe('product identifiers', () => { 'docs/upgrade-guide/v0.2.1-alpha.1/subagent-preset-composition/guide.zh.md', 'docs/upgrade-guide/v0.2.2-alpha.2/fs-observation-policy-default-off/guide.md', 'docs/upgrade-guide/v0.2.2-alpha.2/fs-observation-policy-default-off/guide.zh.md', + 'docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.md', + 'docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.zh.md', 'docs/user/guide/schedule.md', 'docs/user/guide/schedule.zh.md', 'packages/bundle/web-app/cordis.patch.yml', @@ -132,6 +135,17 @@ describe('product identifiers', () => { expect(rescopeText(scoped, file, true)).toEqual({ text, lines: 2 }) }) + it.each([ + 'apps/web/tests/creator-persona.e2e.ts', + 'docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.md', + 'docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.zh.md', + ])('still rewrites package imports in %s', (file) => { + const source = "const preset = 'cordis'\nimport { Context } from 'cordis'\n" + const text = file.endsWith('.md') ? `The \`cordis\` preset.\n\`\`\`ts\n${source}\`\`\`\n` : source + const scoped = text.replace("from 'cordis'", "from '@deepseek-ai/cordis'") + expectRoundTrip(file, text, scoped, 1) + }) + it('keeps unlisted package references subject to residue detection', () => { const file = 'packages/example/src/index.ts' const text = "import { Context } from 'cordis'\nimport type Schema from 'schemastery'\n" diff --git a/scripts/rescope-vendor.ts b/scripts/rescope-vendor.ts index 7a5dc46818..62259636b2 100644 --- a/scripts/rescope-vendor.ts +++ b/scripts/rescope-vendor.ts @@ -101,6 +101,7 @@ const GENERIC_SKIPS: readonly GenericSkip[] = [ { file: 'apps/cli/tests/web-agent-presets.e2e.ts', upstream: ['cordis'] }, { file: 'apps/cli/tests/profiles/web/tests/fixtures/creator-plugin-manager.mjs', upstream: ['cordis'] }, { file: 'apps/web/tests/agent-preset-authoring.e2e.ts', upstream: ['cordis'] }, + { file: 'apps/web/tests/creator-persona.e2e.ts', upstream: ['cordis'] }, { file: 'packages/preset/agent-preset-registry/tests/session.spec.ts', upstream: ['cordis'] }, { file: 'packages/experimental/creation-recommendations/src/index.ts', upstream: ['cordis'] }, { file: 'packages/experimental/creation-recommendations/tests/creation.spec.ts', upstream: ['cordis'] }, @@ -113,6 +114,8 @@ const GENERIC_SKIPS: readonly GenericSkip[] = [ { file: 'docs/tool-catalog.zh.md', upstream: ['cordis'] }, { file: 'docs/upgrade-guide/v0.2.2-alpha.2/fs-observation-policy-default-off/guide.md', upstream: ['cordis'] }, { file: 'docs/upgrade-guide/v0.2.2-alpha.2/fs-observation-policy-default-off/guide.zh.md', upstream: ['cordis'] }, + { file: 'docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.md', upstream: ['cordis'] }, + { file: 'docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.zh.md', upstream: ['cordis'] }, { file: 'scripts/gen-tool-catalog.ts', upstream: ['cordis'] }, { file: 'docs/upgrade-guide/v0.2.0-rc.2/schedule-bundle-retired/guide.md', upstream: ['cordis'] }, { file: 'docs/upgrade-guide/v0.2.0-rc.2/schedule-bundle-retired/guide.zh.md', upstream: ['cordis'] }, From c41f0d1d1086f8b067b34f84e4820ae177e58ee4 Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Tue, 10 Nov 2026 16:03:51 +0800 Subject: [PATCH 07/31] feat(session): add read-only workspace and session list tools --- docs/config-catalog.md | 17 + docs/config-catalog.zh.md | 17 + docs/event-producer-consumer.md | 10 +- docs/event-producer-consumer.zh.md | 10 +- docs/persistence-catalog.i18n.yaml | 12 +- docs/persistence-catalog.md | 6 +- docs/persistence-catalog.zh.md | 6 +- docs/persistence-schema.json | 6 +- docs/tool-catalog.i18n.yaml | 17 +- docs/tool-catalog.md | 63 ++ docs/tool-catalog.zh.md | 63 ++ package.json | 3 +- .../api/session-controller/README.i18n.yaml | 4 +- packages/api/session-controller/README.md | 2 +- packages/api/session-controller/README.zh.md | 2 +- packages/api/session-controller/src/list.ts | 47 +- packages/api/session-controller/src/types.ts | 12 +- .../session-controller/tsconfig.client.json | 1 + .../skills/dsh-doc/references/packages.md | 1 + packages/session-query/README.i18n.yaml | 4 +- packages/session-query/README.md | 1 + packages/session-query/README.zh.md | 1 + .../session-query/README.i18n.yaml | 15 +- .../session-query/session-query/README.md | 8 +- .../session-query/session-query/README.zh.md | 8 +- .../session-query/session-query/package.json | 8 +- .../session-query/session-query/src/index.ts | 1 + .../session-query/src/list-metadata.ts | 48 ++ .../session-query/session-query/src/types.ts | 19 +- .../session-query/tests/list-metadata.spec.ts | 84 +++ .../tool-session-list/README.i18n.yaml | 55 ++ .../session-query/tool-session-list/README.md | 128 ++++ .../tool-session-list/README.zh.md | 128 ++++ .../tool-session-list/locale/de.json | 6 + .../tool-session-list/locale/en.json | 6 + .../tool-session-list/locale/es.json | 6 + .../tool-session-list/locale/fr.json | 6 + .../tool-session-list/locale/ja.json | 6 + .../tool-session-list/locale/pt.json | 6 + .../tool-session-list/locale/ru.json | 6 + .../tool-session-list/locale/zh.json | 6 + .../tool-session-list/package.json | 74 ++ .../tool-session-list/src/index.ts | 99 +++ .../tool-session-list/src/list.ts | 182 +++++ .../tests/fixtures/session-list-seed.ts | 65 ++ .../tests/tool-session-list.spec.ts | 437 +++++++++++ .../tool-session-list/tsconfig.json | 39 + pnpm-lock.yaml | 64 ++ scripts/gen-tool-catalog.ts | 25 +- scripts/product-package-policy.ts | 1 + .../session-list-tools/cordis.snapshot.yml | 52 ++ .../session/session-list-tools/cordis.yml | 6 + .../session-list-tools/session.v4.jsonl | 57 ++ .../session/session-list-tools/snapshot.yml | 9 + .../tool-schemas.expected.json | 689 ++++++++++++++++++ tsconfig.base.json | 2 + tsconfig.host.json | 1 + 57 files changed, 2560 insertions(+), 97 deletions(-) create mode 100644 packages/session-query/session-query/src/list-metadata.ts create mode 100644 packages/session-query/session-query/tests/list-metadata.spec.ts create mode 100644 packages/session-query/tool-session-list/README.i18n.yaml create mode 100644 packages/session-query/tool-session-list/README.md create mode 100644 packages/session-query/tool-session-list/README.zh.md create mode 100644 packages/session-query/tool-session-list/locale/de.json create mode 100644 packages/session-query/tool-session-list/locale/en.json create mode 100644 packages/session-query/tool-session-list/locale/es.json create mode 100644 packages/session-query/tool-session-list/locale/fr.json create mode 100644 packages/session-query/tool-session-list/locale/ja.json create mode 100644 packages/session-query/tool-session-list/locale/pt.json create mode 100644 packages/session-query/tool-session-list/locale/ru.json create mode 100644 packages/session-query/tool-session-list/locale/zh.json create mode 100644 packages/session-query/tool-session-list/package.json create mode 100644 packages/session-query/tool-session-list/src/index.ts create mode 100644 packages/session-query/tool-session-list/src/list.ts create mode 100644 packages/session-query/tool-session-list/tests/fixtures/session-list-seed.ts create mode 100644 packages/session-query/tool-session-list/tests/tool-session-list.spec.ts create mode 100644 packages/session-query/tool-session-list/tsconfig.json create mode 100644 snapshots/session/session-list-tools/cordis.snapshot.yml create mode 100644 snapshots/session/session-list-tools/cordis.yml create mode 100644 snapshots/session/session-list-tools/session.v4.jsonl create mode 100644 snapshots/session/session-list-tools/snapshot.yml create mode 100644 snapshots/session/session-list-tools/tool-schemas.expected.json diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 41bd0207f3..48be42f926 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -4482,6 +4482,23 @@ export interface Config { ``` + + + +## `@deepseek-ai/dsh-tool-session-list` + +- `inject`: `tools` · `sessions` · `sessionQuery` · `workspaceRegistry` · `sessionProjections` +- `source`: [`packages/session-query/tool-session-list/src/index.ts:18`](../packages/session-query/tool-session-list/src/index.ts) + +```ts config-catalog +/** Deployment-owned responsiveness for large Session lists. */ +export interface Config { + /** Positive integral work slice in milliseconds; defaults to 16. Checked between complete rows. */ + readonly listWorkSliceMs?: number +} +``` + + diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index a3bb192363..77d249aa80 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -4484,6 +4484,23 @@ export interface Config { ``` + + + +## `@deepseek-ai/dsh-tool-session-list` + +- `inject`: `tools` · `sessions` · `sessionQuery` · `workspaceRegistry` · `sessionProjections` +- `source`: [`packages/session-query/tool-session-list/src/index.ts:18`](../packages/session-query/tool-session-list/src/index.ts) + +```ts config-catalog +/** Deployment-owned responsiveness for large Session lists. */ +export interface Config { + /** Positive integral work slice in milliseconds; defaults to 16. Checked between complete rows. */ + readonly listWorkSliceMs?: number +} +``` + + diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 1d80e1cfe7..fb5332b037 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -23,11 +23,11 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:390`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | | `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:310`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | | `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:418`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:705`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:685`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:712`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:691`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:698`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:697`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:677`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:704`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:683`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:690`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:55`](../packages/boot/app-boot/src/index.ts) | [`app-boot`](../packages/boot/app-boot) (`emit`) | [`settings`](../packages/settings/settings) | | `approval/request` | `waterfall` | [`packages/interaction/user-approval/src/types.ts:87`](../packages/interaction/user-approval/src/types.ts) | [`user-approval`](../packages/interaction/user-approval) (`waterfall`) | [`acp`](../packages/acp/acp), `remotes`, `server` | | `authorization/settled` | `emit` | [`packages/credentials/authorization/src/index.ts:57`](../packages/credentials/authorization/src/index.ts) | [`authorization`](../packages/credentials/authorization) (`events.dispatch`) | - | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index 9245fa8fab..18e0bd8f9b 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -25,11 +25,11 @@ | `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:390`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | | `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:310`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | | `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:418`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:705`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:685`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:712`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:691`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:698`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:697`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:677`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:704`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:683`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:690`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:55`](../packages/boot/app-boot/src/index.ts) | [`app-boot`](../packages/boot/app-boot) (`emit`) | [`settings`](../packages/settings/settings) | | `approval/request` | `waterfall` | [`packages/interaction/user-approval/src/types.ts:87`](../packages/interaction/user-approval/src/types.ts) | [`user-approval`](../packages/interaction/user-approval) (`waterfall`) | [`acp`](../packages/acp/acp), `remotes`, `server` | | `authorization/settled` | `emit` | [`packages/credentials/authorization/src/index.ts:57`](../packages/credentials/authorization/src/index.ts) | [`authorization`](../packages/credentials/authorization) (`events.dispatch`) | - | diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml index f2294edff6..731cdbf207 100644 --- a/docs/persistence-catalog.i18n.yaml +++ b/docs/persistence-catalog.i18n.yaml @@ -1368,8 +1368,8 @@ en: 4147b170f52814af zh: e78991ac1c41ebec /session-persistence-event-catalog/resolved-persistence-types/string: - en: ef89e74973f4a575 - zh: 0bb1564a0418501c + en: 3123f20799b77064 + zh: 34234db45f2769a1 /session-persistence-event-catalog/resolved-persistence-types/string~2: en: 0089620bf4638263 zh: 1922bef1713094bb @@ -1761,8 +1761,8 @@ en: f58bccca3df9c2ad zh: 5c92b6edeb7ce020 /session-persistence-event-catalog/resolved-persistence-types/kind-retry: - en: c628d0575f81407a - zh: d9a70ce1e05dcce8 + en: 898f27c058097895 + zh: bbbcf08ad8ba3a32 /session-persistence-event-catalog/resolved-persistence-types/kind-runtime-context: en: 68b5598e21cf8ba2 zh: 95ef1685af64a5f4 @@ -1899,8 +1899,8 @@ en: 4e102391d685eff5 zh: 9762243a13014f3d /session-persistence-event-catalog/resolved-persistence-types/kind-user: - en: 808d28208287e843 - zh: 18a8d63978c984a7 + en: 156e57c019aa1b28 + zh: a1629b267f7cc713 /session-persistence-event-catalog/resolved-persistence-types/kind-user-approval: en: a52d2dfbaf844127 zh: 4c5306ca40f20873 diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index 33d9aa4395..0789ca87af 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -5659,7 +5659,7 @@ Array of `number`. SHA-256: `4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b` -Sources: [`packages/api/session-controller/src/types.ts:391`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:21`](../packages/core/session/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/jobs/jobs/src/brand.ts:19`](../packages/jobs/jobs/src/brand.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:42`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/team/agent-team/src/types.ts:20`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:32`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:8`](../packages/team/agent-team/src/types.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts) +Sources: [`packages/api/session-controller/src/types.ts:383`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:21`](../packages/core/session/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/jobs/jobs/src/brand.ts:19`](../packages/jobs/jobs/src/brand.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:42`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/team/agent-team/src/types.ts:20`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:32`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:8`](../packages/team/agent-team/src/types.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts) `string` @@ -7305,7 +7305,7 @@ SHA-256: `db06ef35b27a38425046b2228fa6bce9582abe140d781d363137eb2f4d233a1c` SHA-256: `8f1062573ea9184129dfdec43df1e8136eb5808746fd809bf6b539f3fd11362e` -Sources: [`packages/api/session-controller/src/types.ts:402`](../packages/api/session-controller/src/types.ts) +Sources: [`packages/api/session-controller/src/types.ts:394`](../packages/api/session-controller/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -7824,7 +7824,7 @@ Sources: [`packages/core/tools/src/index.ts:28`](../packages/core/tools/src/inde SHA-256: `a4afec59b75aad5d13ef82d6931f35cc2d98918503916cf069355b77c5e42302` -Sources: [`packages/api/session-controller/src/types.ts:400`](../packages/api/session-controller/src/types.ts) +Sources: [`packages/api/session-controller/src/types.ts:392`](../packages/api/session-controller/src/types.ts) | Property | Presence | Type | |---|---|---| diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md index 5047ebc659..24e2e28177 100644 --- a/docs/persistence-catalog.zh.md +++ b/docs/persistence-catalog.zh.md @@ -5661,7 +5661,7 @@ SHA-256: `5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78` SHA-256: `4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b` -来源:[`packages/api/session-controller/src/types.ts:391`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:21`](../packages/core/session/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/jobs/jobs/src/brand.ts:19`](../packages/jobs/jobs/src/brand.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:42`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/team/agent-team/src/types.ts:20`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:32`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:8`](../packages/team/agent-team/src/types.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts) +来源:[`packages/api/session-controller/src/types.ts:383`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:21`](../packages/core/session/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/jobs/jobs/src/brand.ts:19`](../packages/jobs/jobs/src/brand.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:42`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/team/agent-team/src/types.ts:20`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:32`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:8`](../packages/team/agent-team/src/types.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts) `string` @@ -7307,7 +7307,7 @@ SHA-256: `db06ef35b27a38425046b2228fa6bce9582abe140d781d363137eb2f4d233a1c` SHA-256: `8f1062573ea9184129dfdec43df1e8136eb5808746fd809bf6b539f3fd11362e` -来源:[`packages/api/session-controller/src/types.ts:402`](../packages/api/session-controller/src/types.ts) +来源:[`packages/api/session-controller/src/types.ts:394`](../packages/api/session-controller/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -7826,7 +7826,7 @@ SHA-256: `8fcb0b44a575e998665c053643d1ab04c82f39253ebd190ac0c975b78e40b543` SHA-256: `a4afec59b75aad5d13ef82d6931f35cc2d98918503916cf069355b77c5e42302` -来源:[`packages/api/session-controller/src/types.ts:400`](../packages/api/session-controller/src/types.ts) +来源:[`packages/api/session-controller/src/types.ts:392`](../packages/api/session-controller/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| diff --git a/docs/persistence-schema.json b/docs/persistence-schema.json index a2832eb98c..c8effc7e32 100644 --- a/docs/persistence-schema.json +++ b/docs/persistence-schema.json @@ -259,7 +259,7 @@ {"digest":"4b259f7f8f0a44ad5e90b70a73553ced1df27012d126921d397ff403b6c86731","names":["packages/llm/llm/src/message.ts#ToolResultMessage"],"sources":["packages/llm/llm/src/message.ts:173"]}, {"digest":"4b7ddaf3710b88ff9b8df66304f5f97bf03688fd19730eedc2e9535203c820ea","names":[],"sources":[]}, {"digest":"4bb451330ff699f36b45539ceb0eb2606ead72084e2c5bb637c36cc80e2252db","names":[],"sources":["packages/core/session/src/types.ts:198"]}, - {"digest":"4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b","names":["packages/api/session-controller/src/types.ts#SessionRequestId","packages/attachment/attachment/src/brand.ts#AttachmentId","packages/compaction/compaction/src/brand.ts#CompactionId","packages/core/session/src/types.ts#SessionId","packages/experimental/webhook/src/brand.ts#WebhookDeliveryId","packages/experimental/webhook/src/brand.ts#WebhookRuleId","packages/experimental/webhook/src/brand.ts#WebhookSourceId","packages/feedback/message-feedback/src/types.ts#MessageFeedbackVersion","packages/goal/goal/src/types.ts#GoalId","packages/interaction/commands/src/brand.ts#CommandId","packages/interaction/user-approval/src/types.ts#ApprovalRequestId","packages/jobs/jobs/src/brand.ts#JobId","packages/llm/llm-retry/src/brand.ts#RetryId","packages/llm/llm/src/brand.ts#MessageId","packages/llm/llm/src/brand.ts#ProviderRequestId","packages/llm/llm/src/brand.ts#ReasoningEffortId","packages/llm/llm/src/brand.ts#ToolCallId","packages/schedule/schedule/src/types.ts#ScheduleId","packages/session/session-title/src/index.ts#SessionTitleProviderId","packages/session/session-title/src/types.ts#SessionTitleProviderId","packages/team/agent-team/src/types.ts#TeamId","packages/team/agent-team/src/types.ts#TeamMessageId","packages/team/agent-team/src/types.ts#TeamTaskId","packages/workflow/workflow/src/types.ts#WorkflowRunId"],"sources":["packages/api/session-controller/src/types.ts:391","packages/attachment/attachment/src/brand.ts:6","packages/compaction/compaction/src/brand.ts:4","packages/core/session/src/types.ts:21","packages/experimental/webhook/src/brand.ts:12","packages/experimental/webhook/src/brand.ts:6","packages/experimental/webhook/src/brand.ts:9","packages/feedback/message-feedback/src/types.ts:14","packages/goal/goal/src/types.ts:17","packages/interaction/commands/src/brand.ts:31","packages/interaction/user-approval/src/types.ts:17","packages/jobs/jobs/src/brand.ts:19","packages/llm/llm-retry/src/brand.ts:4","packages/llm/llm/src/brand.ts:16","packages/llm/llm/src/brand.ts:31","packages/llm/llm/src/brand.ts:43","packages/llm/llm/src/brand.ts:67","packages/schedule/schedule/src/types.ts:14","packages/session/session-title/src/index.ts:42","packages/session/session-title/src/types.ts:17","packages/team/agent-team/src/types.ts:20","packages/team/agent-team/src/types.ts:32","packages/team/agent-team/src/types.ts:8","packages/workflow/workflow/src/types.ts:13"]}, + {"digest":"4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b","names":["packages/api/session-controller/src/types.ts#SessionRequestId","packages/attachment/attachment/src/brand.ts#AttachmentId","packages/compaction/compaction/src/brand.ts#CompactionId","packages/core/session/src/types.ts#SessionId","packages/experimental/webhook/src/brand.ts#WebhookDeliveryId","packages/experimental/webhook/src/brand.ts#WebhookRuleId","packages/experimental/webhook/src/brand.ts#WebhookSourceId","packages/feedback/message-feedback/src/types.ts#MessageFeedbackVersion","packages/goal/goal/src/types.ts#GoalId","packages/interaction/commands/src/brand.ts#CommandId","packages/interaction/user-approval/src/types.ts#ApprovalRequestId","packages/jobs/jobs/src/brand.ts#JobId","packages/llm/llm-retry/src/brand.ts#RetryId","packages/llm/llm/src/brand.ts#MessageId","packages/llm/llm/src/brand.ts#ProviderRequestId","packages/llm/llm/src/brand.ts#ReasoningEffortId","packages/llm/llm/src/brand.ts#ToolCallId","packages/schedule/schedule/src/types.ts#ScheduleId","packages/session/session-title/src/index.ts#SessionTitleProviderId","packages/session/session-title/src/types.ts#SessionTitleProviderId","packages/team/agent-team/src/types.ts#TeamId","packages/team/agent-team/src/types.ts#TeamMessageId","packages/team/agent-team/src/types.ts#TeamTaskId","packages/workflow/workflow/src/types.ts#WorkflowRunId"],"sources":["packages/api/session-controller/src/types.ts:383","packages/attachment/attachment/src/brand.ts:6","packages/compaction/compaction/src/brand.ts:4","packages/core/session/src/types.ts:21","packages/experimental/webhook/src/brand.ts:12","packages/experimental/webhook/src/brand.ts:6","packages/experimental/webhook/src/brand.ts:9","packages/feedback/message-feedback/src/types.ts:14","packages/goal/goal/src/types.ts:17","packages/interaction/commands/src/brand.ts:31","packages/interaction/user-approval/src/types.ts:17","packages/jobs/jobs/src/brand.ts:19","packages/llm/llm-retry/src/brand.ts:4","packages/llm/llm/src/brand.ts:16","packages/llm/llm/src/brand.ts:31","packages/llm/llm/src/brand.ts:43","packages/llm/llm/src/brand.ts:67","packages/schedule/schedule/src/types.ts:14","packages/session/session-title/src/index.ts:42","packages/session/session-title/src/types.ts:17","packages/team/agent-team/src/types.ts:20","packages/team/agent-team/src/types.ts:32","packages/team/agent-team/src/types.ts:8","packages/workflow/workflow/src/types.ts:13"]}, {"digest":"4d60dddaa65d3da8d4cd014d85ce3d2c2875664dd0433e331d8e9d395289686b","names":["packages/experimental/liveshare/src/host/viewer-principal.ts#ShareViewerPrincipal"],"sources":["packages/experimental/liveshare/src/host/viewer-principal.ts:24"]}, {"digest":"4e011753f8263f436efaabfbb3b4db53a98fc55342c5ded2daf7208b217be159","names":[],"sources":[]}, {"digest":"4e44c9118152f6829634bfd508e47669ab0497caffa380c94b4be91f9390d35d","names":[],"sources":[]}, @@ -426,7 +426,7 @@ {"digest":"8e611bf46821e5003a1605a73560a6f56388295149d449dfe2142d5ec335f29c","names":["packages/llm/llm/src/types.ts#ToolAdditionBlock"],"sources":["packages/llm/llm/src/types.ts:122"]}, {"digest":"8e8155594e07812356b67d732196dda894b0f9c91a5969d51612cf490b0a016d","names":[],"sources":[]}, {"digest":"8e8e91646a5cae3fc78f7532a0013ff2088ae47077642c2edd507a508209b8af","names":["packages/schedule/schedule/src/types.ts#OneShotScheduleDispatchChange"],"sources":["packages/schedule/schedule/src/types.ts:213"]}, - {"digest":"8f1062573ea9184129dfdec43df1e8136eb5808746fd809bf6b539f3fd11362e","names":[],"sources":["packages/api/session-controller/src/types.ts:402"]}, + {"digest":"8f1062573ea9184129dfdec43df1e8136eb5808746fd809bf6b539f3fd11362e","names":[],"sources":["packages/api/session-controller/src/types.ts:394"]}, {"digest":"8f324cea3916c0517261e88167def8efb3a9994c1135e23d40ed9fd48f8c7bd4","names":[],"sources":[]}, {"digest":"8f6d609794bf5afc01d7ccf3e03811d32f4b8047f58a2c9a98db0154c2ad7cb9","names":[],"sources":[]}, {"digest":"8faed5b52ab2d2df40b94a926d0f0faa75280bddcc4b17b6bdd9c8bfed7c34b5","names":[],"sources":[]}, @@ -480,7 +480,7 @@ {"digest":"a3c6f1ea38e9a61d7a9706057ba65aabe02dfe6d9dd90d4736aa62325d874531","names":[],"sources":[]}, {"digest":"a3edd1efd1fef21b72c55e213c8a8b24196b091abde2b89db52be0b2aaae3cfa","names":[],"sources":[]}, {"digest":"a43327a1739c3fa477f32981071fef7d8ba6ae5f32a84fd70f547b2eee59e93e","names":[],"sources":[]}, - {"digest":"a4afec59b75aad5d13ef82d6931f35cc2d98918503916cf069355b77c5e42302","names":[],"sources":["packages/api/session-controller/src/types.ts:400"]}, + {"digest":"a4afec59b75aad5d13ef82d6931f35cc2d98918503916cf069355b77c5e42302","names":[],"sources":["packages/api/session-controller/src/types.ts:392"]}, {"digest":"a6567ccb2e530606b775371eb4fa31468d72084339968e8b0440a516a23b39dc","names":[],"sources":[]}, {"digest":"a6b41f5bede8094d7bf635be5d69b1bd7a25e006ca9cf9415bceb9322f1a7feb","names":["packages/experimental/hook-protocol/src/types.ts#HookDialect"],"sources":["packages/experimental/hook-protocol/src/types.ts:48"]}, {"digest":"a6da9ad5d42ae83a6833a8288b076688e8e0801633ea36cbdd8a30a6d9f3160c","names":["packages/workflow/tool-workflow/src/types.ts#ToolWorkflowRunStartData"],"sources":["packages/workflow/tool-workflow/src/types.ts:14"]}, diff --git a/docs/tool-catalog.i18n.yaml b/docs/tool-catalog.i18n.yaml index 54f6107f2b..a8129d0f23 100644 --- a/docs/tool-catalog.i18n.yaml +++ b/docs/tool-catalog.i18n.yaml @@ -9,8 +9,8 @@ en: 6cc2cd9ced70bb09 zh: 1c0e6cb4ba2ed637 /tool-schema-catalog/tool-package-map: - en: 1bec3e5c70eae394 - zh: 922d507fa65ae319 + en: f96964e4cb922482 + zh: e3fcc1daf935ca29 /tool-schema-catalog/deepseek-ai-dsh-plugin-manager: en: e0143916bb634762 zh: e0143916bb634762 @@ -237,8 +237,17 @@ en: 927a5ac0974b7642 zh: 927a5ac0974b7642 /tool-schema-catalog/deepseek-ai-dsh-tool-skill/skill: - en: 9b159d5831855afb - zh: 275ee82af0e0f59a + en: c1124b6642c57712 + zh: ede0a9f1479b4ecd +/tool-schema-catalog/deepseek-ai-dsh-tool-session-list: + en: 6d68942100dd76e7 + zh: 6d68942100dd76e7 +/tool-schema-catalog/deepseek-ai-dsh-tool-session-list/list-session: + en: fa3ac1878f21c149 + zh: dfd5759772f99d13 +/tool-schema-catalog/deepseek-ai-dsh-tool-session-list/list-workspace: + en: 7b1f0bed364dfcd2 + zh: c907d8ff78f54268 /tool-schema-catalog/deepseek-ai-dsh-tool-session-query: en: eac1dff4b6d9e195 zh: eac1dff4b6d9e195 diff --git a/docs/tool-catalog.md b/docs/tool-catalog.md index 16c42b6393..3d4070cdaf 100644 --- a/docs/tool-catalog.md +++ b/docs/tool-catalog.md @@ -40,6 +40,7 @@ This table connects model-visible tool names to the plugin package and service s | `@deepseek-ai/dsh-tool-lsp` | `lsp` | `ctx.workingDirectory`, `ctx.tools`, `ctx.lsp`, `ctx.systemPrompt` | `tool/call`, `tool/result` | - | The lsp tool keeps provider selection and language-server subprocesses behind ctx.lsp, so its model-visible schema stays stable across providers. Requires a registered provider (e.g. `@deepseek-ai/dsh-lsp-stdio`) at runtime; without one, a query returns the structured `LSP_UNAVAILABLE` error rather than changing the schema. | | `@deepseek-ai/dsh-tool-ralph` | `ralph` | `ctx.tools`, `ctx.workflowEngine`, `ctx.subagents`, `ctx.systemPrompt`, `a calling Agent (exec.agent parents every fresh round)` | `tool/call`, `tool/result`, `workflow and child session events during execution` | - | A fixed foreground workflow starts one fresh structured child per round; the model selects only the immutable objective and an optional round cap. | | `@deepseek-ai/dsh-tool-skill` | `skill` | `ctx.workingDirectory`, `ctx.tools`, `ctx.agents`, `ctx.skills` | `tool/call`, `tool/result`, `user/message replacement catalogs via agent.inject()` | - | - | +| `@deepseek-ai/dsh-tool-session-list` | `list_session`, `list_workspace` | `ctx.tools`, `ctx.sessions`, `ctx.sessionQuery`, `ctx.workspaceRegistry`, `ctx.sessionProjections` | `tool/call`, `tool/result` | - | Opt-in access to all Workspace and Session list metadata in the mounted runtime. Cold titles and activity use the optional projection cache; absent values become null titles and creation-time recency. No Agent is activated. | | `@deepseek-ai/dsh-tool-session-query` | `session_event_read`, `session_event_search`, `session_event_trace`, `session_search`, `session_trace` | `ctx.tools`, `ctx.systemPrompt`, `ctx.sessionQuery`, `ctx.agents`, `a calling Agent for workspace authority` | `tool/call`, `tool/result` | - | The five read-only tools hide provider cursors and authorize every result from the immutable calling agent session. The package is opt-in; compositions that need enforced deadlines or bounded inline output also mount the generic timeout or spill policies. | | `@deepseek-ai/dsh-experimental-tool-subagent-oar` | `subagent_oar` | `ctx.tools`, `ctx.subagents` | `tool/call`, `tool/result`, `parent subagent catalog and completion notices` | - | The subagent_oar tool selects among configured aliases for external providers. This catalog shows Codex and Claude Code aliases; each deployment chooses its providers. Native model and permission settings belong to the selected provider configuration. | | `@deepseek-ai/dsh-tool-subagent` | `list_subagent_models`, `subagent` | `ctx.tools`, `ctx.subagents`, `ctx.systemPrompt`, `ctx.sessionProjections`, `ctx.llm for model discovery and selected-route validation` | `tool/call`, `tool/result`, `child session events through the chosen provider` | `subagent`, `subagent_fork` | The load-time `toolName` selects the delegation name (default `subagent`); `modelSelection` adds optional route fields. `modelDiscovery` defaults off and registers shared discovery on one instance per scope. Web and Desktop presets enable spawn discovery and route fields and leave `subagent_fork` route fields disabled. The Host settings service records authorization for each new top-level Session; child Sessions inherit it. Without a recorded policy, discovery and explicit selection permit only the current parent route. Every delegation returns the child's name promptly; local children accept follow-ups, while external backends report their single execution automatically. | @@ -1916,6 +1917,68 @@ Load the full instructions for a skill. Call it before acting on a task that nam Source: [`packages/skill/tool-skill/src/index.ts`](../packages/skill/tool-skill/src/index.ts) + + +## `@deepseek-ai/dsh-tool-session-list` + +### `list_session` + +List sessions by latest human prompt time, newest first, then by ID. Returns IDs, available titles, and ISO creation and update times. Missing activity metadata uses creation time; unavailable titles are null. + +```json +{ + "type": "object", + "properties": { + "workspace_id": { + "type": "string", + "description": "Workspace ID from list_workspace. Includes its members and, when requested, subagents belonging through their nearest member ancestor. Omit to list all accessible sessions." + }, + "contain_subagent": { + "type": "boolean", + "description": "Include subagent sessions. Defaults to false." + }, + "archived": { + "type": "boolean", + "description": "Return only archived sessions when true, otherwise only unarchived sessions. Defaults to false." + }, + "limit": { + "type": "integer", + "description": "Maximum entries to return, from 1 to 100. Defaults to 20." + }, + "offset": { + "type": "integer", + "description": "Number of matching entries to skip. Defaults to 0." + } + } +} +``` + +Source: [`packages/session-query/tool-session-list/src/index.ts`](../packages/session-query/tool-session-list/src/index.ts) + +### `list_workspace` + +List workspaces in registry order, including empty workspaces. Returns IDs, titles, paths, and creation and update times. + +```json +{ + "type": "object", + "properties": { + "limit": { + "type": "integer", + "description": "Maximum entries to return, from 1 to 100. Defaults to 20." + }, + "offset": { + "type": "integer", + "description": "Number of matching entries to skip. Defaults to 0." + } + } +} +``` + +Source: [`packages/session-query/tool-session-list/src/index.ts`](../packages/session-query/tool-session-list/src/index.ts) + +Opt-in access to all Workspace and Session list metadata in the mounted runtime. Cold titles and activity use the optional projection cache; absent values become null titles and creation-time recency. No Agent is activated. + ## `@deepseek-ai/dsh-tool-session-query` diff --git a/docs/tool-catalog.zh.md b/docs/tool-catalog.zh.md index bf9a8255bb..4847ac26c1 100644 --- a/docs/tool-catalog.zh.md +++ b/docs/tool-catalog.zh.md @@ -44,6 +44,7 @@ | `@deepseek-ai/dsh-tool-lsp` | `lsp` | `ctx.workingDirectory`、`ctx.tools`、`ctx.lsp`、`ctx.systemPrompt` | `tool/call`、`tool/result` | - | lsp 工具将提供方选择和语言服务器子进程置于 ctx.lsp 之后,因此其模型可见 schema 在更换提供方时保持稳定。运行时要求已注册提供方,例如 `@deepseek-ai/dsh-lsp-stdio`;如果没有提供方,查询会返回结构化 `LSP_UNAVAILABLE` 错误,而不会改变 schema。 | | `@deepseek-ai/dsh-tool-ralph` | `ralph` | `ctx.tools`、`ctx.workflowEngine`、`ctx.subagents`、`ctx.systemPrompt`、`a calling Agent (exec.agent parents every fresh round)` | `tool/call`、`tool/result`、`workflow and child session events during execution` | - | 固定的前台工作流会在每个 Round 启动一个全新的结构化子级;模型只能选择不可变目标和可选的 Round 上限。 | | `@deepseek-ai/dsh-tool-skill` | `skill` | `ctx.workingDirectory`、`ctx.tools`、`ctx.agents`、`ctx.skills` | `tool/call`、`tool/result`、`user/message replacement catalogs via agent.inject()` | - | - | +| `@deepseek-ai/dsh-tool-session-list` | `list_session`、`list_workspace` | `ctx.tools`、`ctx.sessions`、`ctx.sessionQuery`、`ctx.workspaceRegistry`、`ctx.sessionProjections` | `tool/call`、`tool/result` | - | 选择启用后,可读取已挂载运行时中全部 Workspace 和 Session 的列表元数据。冷会话的标题和活动时间使用可选的投影缓存;值缺失时,标题为 null,最近活动时间取创建时间。不会激活 Agent。 | | `@deepseek-ai/dsh-tool-session-query` | `session_event_read`、`session_event_search`、`session_event_trace`、`session_search`、`session_trace` | `ctx.tools`、`ctx.systemPrompt`、`ctx.sessionQuery`、`a calling Agent for workspace authority` | `tool/call`、`tool/result` | - | 这 5 个只读工具会隐藏提供方游标,并根据不可变的调用 agent 会话为每个结果授权。该包需要选择启用;需要强制截止时间或限制行内输出的组合还会挂载通用超时或 spill 策略。 | | `@deepseek-ai/dsh-experimental-tool-subagent-oar` | `subagent_oar` | `ctx.tools`, `ctx.subagents` | `tool/call`, `tool/result`, `parent subagent catalog and completion notices` | - | subagent_oar 工具在为外部提供方配置的别名之间选择。本目录展示 Codex 和 Claude Code 别名;每个部署自行选择提供方。原生模型和权限设置由所选提供方的配置决定。 | | `@deepseek-ai/dsh-tool-subagent` | `list_subagent_models`、`subagent` | `ctx.tools`、`ctx.subagents`、`ctx.systemPrompt`、`ctx.sessionProjections`、`用于模型发现和所选路由校验的 ctx.llm` | `tool/call`、`tool/result`、`child session events through the chosen provider` | `subagent`、`subagent_fork` | 加载时的 `toolName` 选择委派名称(默认为 `subagent`);`modelSelection` 增加可选路由字段。`modelDiscovery` 默认关闭,每个作用域由一个实例注册共享发现工具。Web 与 Desktop preset 启用 spawn 发现和路由字段,并为 `subagent_fork` 保持路由字段关闭。Host 设置服务为每个新顶层 Session 记录授权;子 Session 继承该授权。没有已记录策略时,发现和显式选择只允许当前父级路由。每次委派都会立即返回子代理的名称;本地子代理接受后续消息,外部后端自动汇报单次执行结果。 | @@ -1922,6 +1923,68 @@ lsp 工具将提供方选择和语言服务器子进程置于 ctx.lsp 之后, 来源:[`packages/skill/tool-skill/src/index.ts`](../packages/skill/tool-skill/src/index.ts) + + +## `@deepseek-ai/dsh-tool-session-list` + +### `list_session` + +按最近人工提示词时间从新到旧列出会话,时间相同时按 ID 排列。返回 ID、可用标题以及 ISO 创建时间和更新时间。缺少活动元数据时使用创建时间;标题不可用时为 null。 + +```json +{ + "type": "object", + "properties": { + "workspace_id": { + "type": "string", + "description": "Workspace ID from list_workspace. Includes its members and, when requested, subagents belonging through their nearest member ancestor. Omit to list all accessible sessions." + }, + "contain_subagent": { + "type": "boolean", + "description": "Include subagent sessions. Defaults to false." + }, + "archived": { + "type": "boolean", + "description": "Return only archived sessions when true, otherwise only unarchived sessions. Defaults to false." + }, + "limit": { + "type": "integer", + "description": "Maximum entries to return, from 1 to 100. Defaults to 20." + }, + "offset": { + "type": "integer", + "description": "Number of matching entries to skip. Defaults to 0." + } + } +} +``` + +来源:[`packages/session-query/tool-session-list/src/index.ts`](../packages/session-query/tool-session-list/src/index.ts) + +### `list_workspace` + +按注册表顺序列出工作区,包括空工作区。返回 ID、标题、路径以及创建时间和更新时间。 + +```json +{ + "type": "object", + "properties": { + "limit": { + "type": "integer", + "description": "Maximum entries to return, from 1 to 100. Defaults to 20." + }, + "offset": { + "type": "integer", + "description": "Number of matching entries to skip. Defaults to 0." + } + } +} +``` + +来源:[`packages/session-query/tool-session-list/src/index.ts`](../packages/session-query/tool-session-list/src/index.ts) + +选择启用后,可读取已挂载运行时中全部 Workspace 和 Session 的列表元数据。冷会话的标题和活动时间使用可选的投影缓存;值缺失时,标题为 null,最近活动时间取创建时间。不会激活 Agent。 + ## `@deepseek-ai/dsh-tool-session-query` diff --git a/package.json b/package.json index 37b86b60d5..8a83bf1feb 100644 --- a/package.json +++ b/package.json @@ -307,6 +307,7 @@ "@deepseek-ai/dsh-experimental-forge": "workspace:*", "@deepseek-ai/dsh-experimental-forge-github": "workspace:*", "@deepseek-ai/dsh-experimental-forge-session": "workspace:*", - "@deepseek-ai/dsh-action-cards": "workspace:*" + "@deepseek-ai/dsh-action-cards": "workspace:*", + "@deepseek-ai/dsh-tool-session-list": "workspace:*" } } diff --git a/packages/api/session-controller/README.i18n.yaml b/packages/api/session-controller/README.i18n.yaml index 94482498be..d309647399 100644 --- a/packages/api/session-controller/README.i18n.yaml +++ b/packages/api/session-controller/README.i18n.yaml @@ -15,8 +15,8 @@ en: 1fdf707322fb6996 zh: 0204f7e9d4aa3cce /session-controller/use-this-package: - en: 50fa3dd0a2ce79c8 - zh: 88bd7ea6058d2122 + en: 179c281216ad0660 + zh: 81dbc1d8985ab21b /session-controller/client-references: en: e8979a803ec3e194 zh: c567efcd971728ba diff --git a/packages/api/session-controller/README.md b/packages/api/session-controller/README.md index f414ce78ef..12e9c840a0 100644 --- a/packages/api/session-controller/README.md +++ b/packages/api/session-controller/README.md @@ -43,7 +43,7 @@ Every Remote endpoint is access-controlled: a Peer whose principal is not the ow List rows carry `formatStatus` when available, so Clients can identify migration-required Sessions without requesting their projections. -Host list generation yields between complete rows only when its configured work slice is exhausted; cheap remaining work returns without a forced yield. Request cancellation is checked per row and after each yield and rejects without partial results. Each row is synchronous; the list does not promise one cross-Session snapshot. A Session already queued as cold remains a cached row if it attaches during a yield: Client in-flight mutation replay corrects its availability, and sequenced projections supersede cached hints. An attached Session's summary reads its blankness and last-prompt recency through the `sessionListMetadata` projection handle, and its projection hints carry every summary key computed through `snapshot`. The first summary of an attached Session computes these projections over its whole in-memory log, and later summaries advance them incrementally; this computation runs inside one synchronous row, so `listWorkSliceMs` cannot split it. +Host list generation yields between complete rows only when its configured work slice is exhausted; cheap remaining work returns without a forced yield. Request cancellation is checked per row and after each yield and rejects without partial results. Each row is synchronous; the list does not promise one cross-Session snapshot. A Session already queued as cold remains a cached row if it attaches during a yield: Client in-flight mutation replay corrects its availability, and sequenced projections supersede cached hints. An attached Session's summary reads its blankness and last-prompt recency through the [shared Session-list reader](../../session-query/session-query/README.md#shared-list-metadata), and its projection hints carry every summary key computed through `snapshot`. The first summary of an attached Session computes these projections over its whole in-memory log, and later summaries advance them incrementally; this computation runs inside one synchronous row, so `listWorkSliceMs` cannot split it. Client list rows and resident Sessions use the current `sessionListMetadata` projection to reject stale blank-session hints; recency is the later of the summary timestamp and the projected last user prompt. When SessionManager creates an instance before its list row arrives, it reconciles blankness with metadata already retained for that Session. An opened conversation is therefore not reused by New Session even when an older list response still marks it blank. diff --git a/packages/api/session-controller/README.zh.md b/packages/api/session-controller/README.zh.md index 2a83f4504d..1287e60744 100644 --- a/packages/api/session-controller/README.zh.md +++ b/packages/api/session-controller/README.zh.md @@ -43,7 +43,7 @@ Client journal 在发布 follow 快照、live entry 或历史页之前验证当 列表行在状态可用时携带 `formatStatus`,Client 无需请求其投影即可识别需要迁移的 Session。 -Host 仅在配置的工作时间片耗尽时,于完整条目之间让出事件循环;剩余工作较少时直接返回,不强制让出。每行及每次让出之后检查请求取消,取消时拒绝返回部分结果。每行同步计算;列表不承诺跨 Session 的统一快照。已经进入冷态队列的 Session 若在让出期间接入,仍返回缓存行:Client 对进行中请求的变更重放会纠正其可用性,带序号的投影会覆盖缓存提示。已接入 Session 的摘要通过 `sessionListMetadata` 投影句柄读取是否为空和最后一次提示词的最近活动时间,其投影提示携带通过 `snapshot` 计算的每个摘要 key。已接入 Session 的首次摘要在其完整内存日志上计算这些投影,之后的摘要增量推进;这次计算在单行的同步工作内进行,`listWorkSliceMs` 无法切分它。 +Host 仅在配置的工作时间片耗尽时,于完整条目之间让出事件循环;剩余工作较少时直接返回,不强制让出。每行及每次让出之后检查请求取消,取消时拒绝返回部分结果。每行同步计算;列表不承诺跨 Session 的统一快照。已经进入冷态队列的 Session 若在让出期间接入,仍返回缓存行:Client 对进行中请求的变更重放会纠正其可用性,带序号的投影会覆盖缓存提示。已接入 Session 的摘要通过[共享 Session 列表读取函数](../../session-query/session-query/README.zh.md#shared-list-metadata)读取是否为空和最后一次提示词的最近活动时间,其投影提示携带通过 `snapshot` 计算的每个摘要 key。已接入 Session 的首次摘要在其完整内存日志上计算这些投影,之后的摘要增量推进;这次计算在单行的同步工作内进行,`listWorkSliceMs` 无法切分它。 Client 列表行和驻留 Session 使用当前 `sessionListMetadata` 投影纠正过期的空白会话提示;最近活动时间取摘要时间戳与投影中最后一次用户提示词时间的较晚值。当 SessionManager 在列表行到达前创建实例时,会使用已保留的该 Session 元数据对账空白状态。因此,即使旧列表响应仍将已有对话标为空白,新会话操作也不会复用已经打开过的对话。 diff --git a/packages/api/session-controller/src/list.ts b/packages/api/session-controller/src/list.ts index 830ebe21a9..d2ff0d2a67 100644 --- a/packages/api/session-controller/src/list.ts +++ b/packages/api/session-controller/src/list.ts @@ -5,10 +5,10 @@ import { scheduler } from 'node:timers/promises' import type { Context } from '@deepseek-ai/cordis' import type {} from '@deepseek-ai/dsh-agent-preset-registry' import type { ImageAttachmentLimits } from '@deepseek-ai/dsh-attachment' -import type { Session, SessionEvent, SessionHeader, SessionId } from '@deepseek-ai/dsh-session' -import type { ProjectionHandle, ProjectionSnapshot } from '@deepseek-ai/dsh-session-projection' +import type { Session, SessionHeader, SessionId } from '@deepseek-ai/dsh-session' +import type { ProjectionSnapshot } from '@deepseek-ai/dsh-session-projection' import type {} from '@deepseek-ai/dsh-session-projection-cache' -import { SessionQueryError, type SessionRecord, type SessionSearchCursor } from '@deepseek-ai/dsh-session-query' +import { registerSessionListMetadata, SessionQueryError, type SessionRecord, type SessionSearchCursor } from '@deepseek-ai/dsh-session-query' import { RemoteError } from '@deepseek-ai/dsh-typert-protocol' import { z } from 'zod' import { @@ -24,11 +24,6 @@ const SEARCH_PROVIDER_CALL_LIMIT = 100 const SESSION_SEARCH_QUERY_MAX_CHARS = 500 const MESSAGE_TYPES = new Set(['user/message', 'assistant/message']) -const sessionListMetadataSchema: z.ZodType = z.object({ - blank: z.boolean(), - lastPromptAt: z.number().nullable(), -}) - const imageLimitsSchema = z.object({ maxImageBytes: z.number().int().positive(), maxImagesPerMessage: z.number().int().positive(), @@ -38,25 +33,6 @@ const imageLimitsSchema = z.object({ mediaTypes: z.array(z.string()), }) as unknown as z.ZodType -/** - * Advance the Session-list metadata projection by one committed event. - * @param state - metadata before the event. - * @param event - next committed Session event. - * @returns the original or advanced metadata value. - */ -export function applySessionListMetadata( - state: SessionListMetadata, - event: SessionEvent, -): SessionListMetadata { - const blank = state.blank && event.type !== 'turn/start' - const lastPromptAt = event.type === 'user/message' && event.data.source.kind === 'user' - ? event.time - : state.lastPromptAt - return blank === state.blank && lastPromptAt === state.lastPromptAt - ? state - : { blank, lastPromptAt } -} - /** * Return the longest prefix containing at most `maximum` Unicode code points. * @param value - source text. @@ -76,7 +52,7 @@ export function truncateUnicodeCodePoints(value: string, maximum: number): strin /** Owns list projection registration, bounded cold summaries, and authorized search. */ export class ApiSessionList { - private listMetadata!: ProjectionHandle + private listMetadata!: (session: Session) => SessionListMetadata /** * @param ctx - Host context carrying Session, query, persistence, and projection services. @@ -89,14 +65,7 @@ export class ApiSessionList { * @returns when all required registrations are ready. */ async initialize(): Promise { - this.listMetadata = await this.ctx.sessionProjections.register<'sessionListMetadata', SessionListMetadata>({ - key: 'sessionListMetadata', - stateSchema: sessionListMetadataSchema, - init: () => ({ blank: true, lastPromptAt: null }), - apply: applySessionListMetadata, - wire: { viewSchema: sessionListMetadataSchema, view: state => state }, - stateVersion: 1, - }) + this.listMetadata = await registerSessionListMetadata(this.ctx) await this.ctx.sessionProjections.register<'imageLimits', null>({ key: 'imageLimits', stateSchema: z.null(), @@ -113,17 +82,17 @@ export class ApiSessionList { /** * Build one current attached-Session summary. - * Blankness and recency come from the `sessionListMetadata` handle; projection + * Blankness and recency come from the shared `sessionListMetadata` reader; projection * hints carry every summary key computed through `snapshot`. The first call * for a Session computes these projections over its whole in-memory log, and * later calls advance them incrementally. The handle read and the hint with - * the same key come from one cell; the handle read does not depend on any + * the same key come from one cell; the metadata read does not depend on any * other unit's view. * @param session - attached Session to summarize. * @returns current list metadata and available projections. */ summaryFor(session: Session): SessionSummary { - const metadata = this.listMetadata.stateOf(session) + const metadata = this.listMetadata(session) const projections = this.projectionsFor(session.header, session) return { sessionId: session.id, diff --git a/packages/api/session-controller/src/types.ts b/packages/api/session-controller/src/types.ts index 49cd7c0f9d..d0bea27576 100644 --- a/packages/api/session-controller/src/types.ts +++ b/packages/api/session-controller/src/types.ts @@ -14,12 +14,12 @@ import type { Principal } from '@deepseek-ai/dsh-typert-protocol' import type { JsonValue } from '@deepseek-ai/dsh-util-values' import type { WorkspaceId } from '@deepseek-ai/dsh-workspace/types' +export type { SessionListMetadata } from '@deepseek-ai/dsh-session-query/types' + declare module '@deepseek-ai/dsh-session-projection/types' { interface SessionProjectionMap { /** Eligible latest failed turn/end for an empty prompt, or null. */ conversationContinuation: SessionSeq | null - /** Persisted facts used to summarize a Session without activating it. */ - sessionListMetadata: SessionListMetadata /** * Image-intake limits enforced by the Session prompt endpoint. Boot * constant, excluded from Session summary payloads: every Session shares @@ -29,14 +29,6 @@ declare module '@deepseek-ai/dsh-session-projection/types' { } } -/** Persisted hints used to summarize a cold Session. */ -export interface SessionListMetadata { - /** Whether the folded prefix contains no turn. */ - readonly blank: boolean - /** Latest human-authored prompt time in the folded prefix. */ - readonly lastPromptAt: number | null -} - /** * Summary wire values a Session-list row carries. A `sequenced` block carries * every summary key computed at its `asOfSeq`; a `cached` block carries the diff --git a/packages/api/session-controller/tsconfig.client.json b/packages/api/session-controller/tsconfig.client.json index a1375420ca..6b64356246 100644 --- a/packages/api/session-controller/tsconfig.client.json +++ b/packages/api/session-controller/tsconfig.client.json @@ -23,6 +23,7 @@ { "path": "../../llm/llm" }, { "path": "../../session/session-projection" }, { "path": "../../session/session-title" }, + { "path": "../../session-query/session-query" }, { "path": "../../subagent/subagent" }, { "path": "../../util/brand" }, { "path": "../../util/crypto" }, 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 489d3c98ce..9651f13643 100644 --- a/packages/preset/agent-preset/skills/dsh-doc/references/packages.md +++ b/packages/preset/agent-preset/skills/dsh-doc/references/packages.md @@ -403,6 +403,7 @@ Every package below exports a Cordis plugin that a bundle patch can name in a Lo |---|---|---| | `@deepseek-ai/dsh-session-log-export` | yes | Web Session-log ZIP export and Session Markdown copy | | `@deepseek-ai/dsh-session-query-sqlite` | yes | Concrete ctx.sessionQuery backend with SQLite FTS5 search | +| `@deepseek-ai/dsh-tool-session-list` | yes | Read-only paginated Workspace and Session metadata tools | ## settings diff --git a/packages/session-query/README.i18n.yaml b/packages/session-query/README.i18n.yaml index e391a1291c..6113794d2b 100644 --- a/packages/session-query/README.i18n.yaml +++ b/packages/session-query/README.i18n.yaml @@ -15,8 +15,8 @@ en: 1eb35b015a6c423f zh: a8a3dceee2c9e943 /session-query-session-retrieval-capability-family/packages: - en: 03f48fd85e12934a - zh: 4fb3f345f5d91572 + en: 474c97ed08ca68c8 + zh: af8114e7219d8938 /session-query-session-retrieval-capability-family/related-documentation: en: aa03439fc68a285d zh: eb074a3318b92024 diff --git a/packages/session-query/README.md b/packages/session-query/README.md index 240076d95b..4e0b88decc 100644 --- a/packages/session-query/README.md +++ b/packages/session-query/README.md @@ -28,6 +28,7 @@ Each package README describes what you can do with its part of the family. |---|---|---| | [`session-query/`](session-query/README.md) | Unified session-history query service: exact reads, relationship traces, and filters | `ctx.sessionQuery` | | [`session-query-sqlite/`](session-query-sqlite/README.md) | Full-text search across session history backed by a SQLite FTS5 index | registers on `ctx.sessionQuery` | +| [`tool-session-list/`](tool-session-list/README.md) | Optional read-only Workspace and Session metadata tools | — | | [`session-log-export/`](session-log-export/README.md) | Web `/export` command and browser download of a session ZIP | `ctx.sessionLogDownload` (browser) | ----- diff --git a/packages/session-query/README.zh.md b/packages/session-query/README.zh.md index f443ff7ee4..3367b6271a 100644 --- a/packages/session-query/README.zh.md +++ b/packages/session-query/README.zh.md @@ -28,6 +28,7 @@ kind: "package-group" |---|---|---| | [`session-query/`](session-query/README.zh.md) | 统一的会话历史查询服务:精确读取、关系追踪与过滤 | `ctx.sessionQuery` | | [`session-query-sqlite/`](session-query-sqlite/README.zh.md) | 基于 SQLite FTS5 索引的会话历史全文搜索 | 注册到 `ctx.sessionQuery` | +| [`tool-session-list/`](tool-session-list/README.zh.md) | 可选的只读 Workspace 和 Session 元数据工具 | — | | [`session-log-export/`](session-log-export/README.zh.md) | Web `/export` 命令与浏览器下载会话 ZIP | `ctx.sessionLogDownload`(浏览器) | ----- diff --git a/packages/session-query/session-query/README.i18n.yaml b/packages/session-query/session-query/README.i18n.yaml index 9928994e13..8e8ae5bcfd 100644 --- a/packages/session-query/session-query/README.i18n.yaml +++ b/packages/session-query/session-query/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-session-query/use-this-package: - en: cc9eb8f214c57137 - zh: 76723633d0faee5d + en: dfc90afac9ef47be + zh: 0a5aa60a34f24e61 /deepseek-ai-dsh-session-query/use-this-package/what-you-can-do: en: 608cd6d4c5cf2c35 zh: 23d3c5a7374b5283 @@ -36,11 +36,14 @@ en: b34fb0d209192ff4 zh: 455bdb024d04f16a /deepseek-ai-dsh-session-query/understand-the-implementation/source-map: - en: c58f4f086e3d0728 - zh: 7d66b688c7f54c87 + en: 58964ca2cde96c32 + zh: 9699c328cefc9f09 /deepseek-ai-dsh-session-query/understand-the-implementation/corpus-resolution: - en: efa560c55a869c71 - zh: 451eb107825856ac + en: 4dde9107d05de6ee + zh: 8c775eb7630e659a +/deepseek-ai-dsh-session-query/understand-the-implementation/shared-list-metadata: + en: 30d9af561283c382 + zh: bc8ceabe718239bf /deepseek-ai-dsh-session-query/understand-the-implementation/observation-cache: en: 16d4a29af5b2ac07 zh: 7ec4a91f97697d2e diff --git a/packages/session-query/session-query/README.md b/packages/session-query/session-query/README.md index 6110432284..af901c891d 100644 --- a/packages/session-query/session-query/README.md +++ b/packages/session-query/session-query/README.md @@ -25,7 +25,7 @@ English | [中文](README.zh.md) ## Use this package -Use `ctx.sessionQuery` from application code when you need to read or search session history without touching the session service or a storage backend directly. The service is provided by a concrete backend plugin — the shipped composition mounts `@deepseek-ai/dsh-session-query-sqlite` ([README](../session-query-sqlite/README.md)) — so this package is never mounted alone. Everything below is available on `ctx.sessionQuery` once a backend is composed. +Use `ctx.sessionQuery` from application code when you need to read or search session history without touching the session service or a storage backend directly. The service is provided by a concrete backend plugin — the shipped composition mounts `@deepseek-ai/dsh-session-query-sqlite` ([README](../session-query-sqlite/README.md)) — so this package is never mounted alone. The query operations below are available on `ctx.sessionQuery` once a backend is composed. ### What you can do @@ -92,6 +92,7 @@ The decision history lives in the [unified service decision](../../../.agents/no | [`src/index.ts`](src/index.ts) | Service definition: the abstract `SessionQueryEngine`, concrete reads, config validation | | [`src/corpus.ts`](src/corpus.ts) | Live-preferred corpus resolution, optional persistence binding, batch projections | | [`src/observation.ts`](src/observation.ts) | Live-preferred point observations with a bounded revision-keyed prepared-Session cache | +| [`src/list-metadata.ts`](src/list-metadata.ts) | Shared blankness and human-prompt recency projection registration | | [`src/cold-read.ts`](src/cold-read.ts) | Handle-based cold log read with in-memory interrupted-turn closers | | [`src/types.ts`](src/types.ts) | Public records, filters, requests, and page types | | [`src/config.ts`](src/config.ts) | Inherited config and the closed `SessionQueryError` taxonomy | @@ -105,6 +106,11 @@ The decision history lives in the [unified service decision](../../../.agents/no `SessionCorpus` binds optional `ctx.sessionPersistence` through a fiber and resolves each read live-first: a known live target is snapshotted without consulting persistence; otherwise the session is listed, read completely through a short-lived read handle, and re-checked for a live attachment before cloning. A cold log whose writer crashed mid-turn is balanced in memory with `interruptedTurnClosers` — persistence is never mutated by a read. Header compatibility is asserted between listed and loaded observations. Batch title reads run one metadata listing and bounded-concurrency reads, isolating per-session failures while cancellation rejects the whole batch. + +### Shared list metadata + +`registerSessionListMetadata(ctx)` acquires the shared projection for Session blankness and the latest human-authored prompt time, and returns a synchronous reader for prepared live Sessions. The Session API and optional [listing tools](../tool-session-list/README.md) share one projection unit; disposing a consumer releases only its own reference. Registration requires `sessionProjections`, independently of the query service's header-only `listSessions()` operation. + ### Observation cache `observeSession` builds point observations without a listing preflight. A live observation fixes its cut as the current log length and materializes `events` on first read, so header-, cursor-, or projection-only consumers never copy the log; the log only appends, so a late first read still yields exactly that prefix. The cold path stats the stored session first and consults its own bounded cache keyed by the persistence instance and the `stat` revision: an unchanged revision reuses the restored unpublished Session without re-reading the log; a changed revision, or a replaced persistence instance, reloads through the handle seam and replaces the entry. The cache holds `preparedSessionCacheSize` entries with least-recently-used eviction, entries pinned by active observation leases are never evicted, and a session that goes live mid-read retries the live path. diff --git a/packages/session-query/session-query/README.zh.md b/packages/session-query/session-query/README.zh.md index 3c9bfb329a..c65fc09154 100644 --- a/packages/session-query/session-query/README.zh.md +++ b/packages/session-query/session-query/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用本包 -当你需要读取或搜索会话历史、而不直接触碰会话服务或存储后端时,从应用代码使用 `ctx.sessionQuery`。该服务由具体后端插件提供——已发布组合挂载 `@deepseek-ai/dsh-session-query-sqlite`([README](../session-query-sqlite/README.zh.md))——因此本包从不单独挂载。一旦组合了后端,以下全部能力都可在 `ctx.sessionQuery` 上使用。 +当你需要读取或搜索会话历史、而不直接触碰会话服务或存储后端时,从应用代码使用 `ctx.sessionQuery`。该服务由具体后端插件提供——已发布组合挂载 `@deepseek-ai/dsh-session-query-sqlite`([README](../session-query-sqlite/README.zh.md))——因此本包从不单独挂载。一旦组合了后端,以下查询操作都可在 `ctx.sessionQuery` 上使用。 ### 你可以做什么 @@ -92,6 +92,7 @@ kind: "package-reference" | [`src/index.ts`](src/index.ts) | 服务定义:抽象 `SessionQueryEngine`、具体读取、配置校验 | | [`src/corpus.ts`](src/corpus.ts) | 实时优先的语料库解析、可选持久化绑定、批量投影 | | [`src/observation.ts`](src/observation.ts) | 实时优先的定点观察,带按修订键控的有界 prepared-Session 缓存 | +| [`src/list-metadata.ts`](src/list-metadata.ts) | 共享的空白状态与人工提示词活动时间投影注册 | | [`src/cold-read.ts`](src/cold-read.ts) | 基于句柄的冷日志读取,附内存中的中断轮次闭合事件 | | [`src/types.ts`](src/types.ts) | 公共记录、过滤器、请求与分页类型 | | [`src/config.ts`](src/config.ts) | 继承配置与封闭的 `SessionQueryError` 分类体系 | @@ -105,6 +106,11 @@ kind: "package-reference" `SessionCorpus` 通过 fiber 绑定可选的 `ctx.sessionPersistence`,并实时优先解析每次读取:已知实时目标直接快照,不查询持久化;否则先列出会话,再通过短生命周期的读取句柄完整读出日志,并在克隆前重新检查是否出现实时挂载。写入者在轮次中途崩溃的冷日志用 `interruptedTurnClosers` 在内存中补齐——读取从不修改持久化。列表与加载观察之间会断言 header 兼容性。批量标题读取执行一次元数据列表与有界并发读取,把逐会话失败隔离,而取消会拒绝整个批次。 + +### 共享列表元数据 + +`registerSessionListMetadata(ctx)` 获取 Session 空白状态与最近人工提示词时间的共享投影,并返回准备就绪的实时 Session 的同步读取函数。Session API 与可选的[列表工具](../tool-session-list/README.zh.md)共享同一个投影单元;释放消费方时只移除它自己的引用。注册需要 `sessionProjections`,独立于查询服务仅读取 header 的 `listSessions()` 操作。 + ### 观察缓存 `observeSession` 不经过列表预检直接构建定点观察。实时观察以当前日志长度固定 cut,并在首次读取时才物化 `events`,因此只需要 header、cursor 或 projection 的消费者永远不会复制日志;日志只会追加,所以延后的首次读取得到的仍然正好是该前缀。冷路径先对存储会话执行 `stat`,再查询自有的有界缓存,缓存键为持久化实例加 `stat` 修订:修订未变则复用已恢复的未发布 Session,不再重读日志;修订变化或持久化实例被替换则经句柄 seam 重新加载并替换条目。缓存保留 `preparedSessionCacheSize` 个条目并按最久未用淘汰,被活跃观察租约钉住的条目从不被淘汰;读取中途转为实时的会话会重试实时路径。 diff --git a/packages/session-query/session-query/package.json b/packages/session-query/session-query/package.json index 62e97be451..7ab415b45b 100644 --- a/packages/session-query/session-query/package.json +++ b/packages/session-query/session-query/package.json @@ -18,11 +18,16 @@ "types": "./lib/types/index.d.ts", "default": "./lib/index.js" }, + "./types": { + "types": "./lib/types/types.d.ts", + "default": "./lib/types/types.js" + }, "./src/*": "./src/*", "./package.json": "./package.json" }, "files": [ "lib/index.js", + "lib/types/**/*.js", "lib/types/**/*.d.ts", "lib/types/**/*.d.ts.map", "lib/**/*.js.map", @@ -63,6 +68,7 @@ "@deepseek-ai/cordis": "workspace:~" }, "dependencies": { - "@deepseek-ai/dsh-session-format-catalog": "workspace:*" + "@deepseek-ai/dsh-session-format-catalog": "workspace:*", + "zod": "4.6.6" } } diff --git a/packages/session-query/session-query/src/index.ts b/packages/session-query/session-query/src/index.ts index dfb11fec65..62dcbcc337 100644 --- a/packages/session-query/session-query/src/index.ts +++ b/packages/session-query/session-query/src/index.ts @@ -60,6 +60,7 @@ import { import * as tracing from './tracing.ts' export type * from './types.ts' +export { registerSessionListMetadata } from './list-metadata.ts' export { SessionSearchCursor } from './cursor.ts' export type { Config, SessionQueryErrorCode } from './config.ts' export { diff --git a/packages/session-query/session-query/src/list-metadata.ts b/packages/session-query/session-query/src/list-metadata.ts new file mode 100644 index 0000000000..46d77244fe --- /dev/null +++ b/packages/session-query/session-query/src/list-metadata.ts @@ -0,0 +1,48 @@ +/** Shared Session-list projection ownership for API and model-tool readers. */ + +import type { Context } from '@deepseek-ai/cordis' +import type { Session, SessionEvent } from '@deepseek-ai/dsh-session' +import type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection' +import { z } from 'zod' +import type { SessionListMetadata } from './types.ts' + +const sessionListMetadataSchema: z.ZodType = z.object({ + blank: z.boolean(), + lastPromptAt: z.number().nullable(), +}) + +/** Advance blankness and human-prompt recency without retaining history. */ +function applySessionListMetadata( + state: SessionListMetadata, + event: SessionEvent, +): SessionListMetadata { + const blank = state.blank && event.type !== 'turn/start' + const lastPromptAt = event.type === 'user/message' && event.data.source.kind === 'user' + ? event.time + : state.lastPromptAt + return blank === state.blank && lastPromptAt === state.lastPromptAt + ? state + : { blank, lastPromptAt } +} + +const sessionListMetadataDefinition = { + key: 'sessionListMetadata', + stateSchema: sessionListMetadataSchema, + init: () => ({ blank: true, lastPromptAt: null }), + apply: applySessionListMetadata, + wire: { viewSchema: sessionListMetadataSchema, view: state => state }, + stateVersion: 1, +} satisfies ProjectionDefinition<'sessionListMetadata', SessionListMetadata> + +/** + * Acquire the shared Session-list unit on the caller's fiber. + * Concurrent callers share one projection; disposal releases only the caller's reference. + * @param ctx - owner context with the required projection registry. + * @returns a synchronous domain reader ready for prepared live Sessions. + */ +export async function registerSessionListMetadata( + ctx: Context, +): Promise<(session: Session) => SessionListMetadata> { + const handle = await ctx.sessionProjections.register(sessionListMetadataDefinition) + return session => handle.stateOf(session) +} diff --git a/packages/session-query/session-query/src/types.ts b/packages/session-query/session-query/src/types.ts index cca5b2283e..8be1b4bfc6 100644 --- a/packages/session-query/session-query/src/types.ts +++ b/packages/session-query/session-query/src/types.ts @@ -14,12 +14,27 @@ import type { SessionSeq, OptionalSessionSeq, SurfaceEvent, -} from '@deepseek-ai/dsh-session' -import type { SessionTitleSnapshot } from '@deepseek-ai/dsh-session-title' +} from '@deepseek-ai/dsh-session/types' +import type { SessionTitleSnapshot } from '@deepseek-ai/dsh-session-title/types' import type { SessionSearchCursor } from './cursor.ts' export type { SessionSearchCursor } from './cursor.ts' +declare module '@deepseek-ai/dsh-session-projection/types' { + interface SessionProjectionMap { + /** Persisted facts used to summarize a Session without activating it. */ + sessionListMetadata: SessionListMetadata + } +} + +/** Persisted hints used to summarize a cold Session. */ +export interface SessionListMetadata { + /** Whether the folded prefix contains no turn. */ + readonly blank: boolean + /** Latest human-authored prompt time in the folded prefix. */ + readonly lastPromptAt: number | null +} + /** Whether an event is current model context, replaced context, or raw-log-only. */ export type SessionEventSurface = 'current' | 'shadowed' | 'log-only' diff --git a/packages/session-query/session-query/tests/list-metadata.spec.ts b/packages/session-query/session-query/tests/list-metadata.spec.ts new file mode 100644 index 0000000000..96fd8bf536 --- /dev/null +++ b/packages/session-query/session-query/tests/list-metadata.spec.ts @@ -0,0 +1,84 @@ +/** Shared list metadata keeps its values and lifetime across independent consumers. */ + +import { Context } from '@deepseek-ai/cordis' +import { createUserMessage } from '@deepseek-ai/dsh-llm' +import SessionStore from '@deepseek-ai/dsh-session' +import type { Session } from '@deepseek-ai/dsh-session' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' +import { describe, expect, it, onTestFinished, vi } from 'vitest' +import { registerSessionListMetadata } from '../src/list-metadata.ts' + +async function setup() { + const ctx = new Context() + onTestFinished(async () => { await ctx.fiber.dispose() }) + await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + return ctx +} + +function prompt(session: Session) { + return session.append('user/message', createUserMessage({ + content: [{ type: 'text', text: 'Continue the task.' }], + source: { kind: 'user' }, + }), { surfaceOp: 'append' }) +} + +describe('shared Session-list metadata', () => { + it('tracks human prompts and turns while preserving unchanged state references', async () => { + const ctx = await setup() + const read = await registerSessionListMetadata(ctx) + const session = ctx.sessions.create() + const initial = read(session) + expect(initial).toEqual({ blank: true, lastPromptAt: null }) + + session.append('session/title', { title: 'Task', messageSeqs: [], source: { kind: 'user' } }) + expect(read(session)).toBe(initial) + const first = prompt(session) + expect(read(session)).toEqual({ blank: true, lastPromptAt: first.time }) + session.append('turn/start', { turn: 1 }) + const active = read(session) + expect(active).toEqual({ blank: false, lastPromptAt: first.time }) + session.append('turn/start', { turn: 2 }) + expect(read(session)).toBe(active) + session.append('user/message', createUserMessage({ + content: [{ type: 'text', text: 'Context refresh.' }], + source: { kind: 'system-prompt' }, + }), { surfaceOp: 'append' }) + expect(read(session)).toBe(active) + const latest = prompt(session) + expect(read(session)).toEqual({ blank: false, lastPromptAt: latest.time }) + expect(ctx.sessionProjections.snapshot(session).values.sessionListMetadata).toEqual(read(session)) + expect(ctx.sessionProjections.checkpoint(session).sessionListMetadata?.ver).toBe(1) + }) + + it('shares one cell and notification across owners until the last owner unloads', async () => { + const ctx = await setup() + const first = await ctx.plugin(Object.assign(function firstOwner() {}, { inject: ['sessionProjections'] })) + const second = await ctx.plugin(Object.assign(function secondOwner() {}, { inject: ['sessionProjections'] })) + const firstRead = await registerSessionListMetadata(first.ctx) + const secondRead = await registerSessionListMetadata(second.ctx) + const session = ctx.sessions.create() + expect(firstRead(session)).toBe(secondRead(session)) + const changed = vi.fn() + ctx.sessionProjections.onChanged(changed) + session.append('turn/start', { turn: 1 }) + expect(changed).toHaveBeenCalledOnce() + expect(firstRead(session)).toBe(secondRead(session)) + + await first.dispose() + const event = prompt(session) + expect(secondRead(session)).toEqual({ blank: false, lastPromptAt: event.time }) + expect(ctx.sessionProjections.snapshot(session).values.sessionListMetadata).toEqual(secondRead(session)) + await second.dispose() + expect(ctx.sessionProjections.snapshot(session).values).not.toHaveProperty('sessionListMetadata') + }) + + it('folds existing live history when the first consumer registers', async () => { + const ctx = await setup() + const session = ctx.sessions.create() + session.append('turn/start', { turn: 1 }) + const event = prompt(session) + const read = await registerSessionListMetadata(ctx) + expect(read(session)).toEqual({ blank: false, lastPromptAt: event.time }) + }) +}) diff --git a/packages/session-query/tool-session-list/README.i18n.yaml b/packages/session-query/tool-session-list/README.i18n.yaml new file mode 100644 index 0000000000..a44227e3d0 --- /dev/null +++ b/packages/session-query/tool-session-list/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-query/tool-session-list/README.md +/: + en: 3475319e48226347 + zh: 68361c3ff00d966f +/deepseek-ai-dsh-tool-session-list: + en: 963f03d1ba483ea9 + zh: 4809b66477752fe9 +/deepseek-ai-dsh-tool-session-list/summary: + en: c643c299cff0602e + zh: a4e0d8d3cb039859 +/deepseek-ai-dsh-tool-session-list/table-of-contents: + en: d152484eb41ac6b4 + zh: 5acc0d3807846b6e +/deepseek-ai-dsh-tool-session-list/use-this-package: + en: 653ca12bb7c76f9d + zh: 4dc851c44aa30eb1 +/deepseek-ai-dsh-tool-session-list/use-this-package/access-and-composition: + en: efa812b2b38914ae + zh: 4d44617966d00378 +/deepseek-ai-dsh-tool-session-list/use-this-package/listing-behavior: + en: 9170312b97f617fb + zh: 0e7a397ea03d6695 +/deepseek-ai-dsh-tool-session-list/use-this-package/failures: + en: be4dd03d3877e2ed + zh: 27c38df3c449dde9 +/deepseek-ai-dsh-tool-session-list/understand-the-implementation: + en: a9a0e5d116579be4 + zh: 1b78e7f73b639f85 +/deepseek-ai-dsh-tool-session-list/further-exploration: + en: 2a147ada18753beb + zh: d9aa75491c8fc0b7 +/deepseek-ai-dsh-tool-session-list/model-experience: + en: 215e7ba838619b7b + zh: a311da3843709f90 +/deepseek-ai-dsh-tool-session-list/model-experience/tool-schemas-and-results: + en: cadc497841430a21 + zh: af4cc374d7d16917 +/deepseek-ai-dsh-tool-session-list/model-experience/tool-schemas-and-results/what-the-model-sees: + en: 6ffb21f59acadc4e + zh: 258cded3677be923 +/deepseek-ai-dsh-tool-session-list/model-experience/tool-schemas-and-results/token-effect: + en: e699317cafee83d9 + zh: 912c0ce1a9f3957f +/deepseek-ai-dsh-tool-session-list/model-experience/tool-schemas-and-results/kv-cache-effect: + en: 0e201fbbe37798d8 + zh: fd4bd41e7393c234 +/deepseek-ai-dsh-tool-session-list/known-limitations-and-deferred-work: + en: 103c746911f87efd + zh: 58f101c6b129c9e8 +/deepseek-ai-dsh-tool-session-list/known-limitations-and-deferred-work/dev-note: + en: e67f633dc6fe7773 + zh: e88aeb617ffb74ea diff --git a/packages/session-query/tool-session-list/README.md b/packages/session-query/tool-session-list/README.md new file mode 100644 index 0000000000..c45163b510 --- /dev/null +++ b/packages/session-query/tool-session-list/README.md @@ -0,0 +1,128 @@ +--- +description: "List Workspace and Session metadata through optional read-only tools, with pagination and cached titles and activity times." +kind: "package-reference" +--- + +# @deepseek-ai/dsh-tool-session-list + +English | [中文](README.zh.md) + +## Summary + +Discover workspaces and sessions without resuming an agent or reading cold conversation logs. List empty workspaces, find sessions in a workspace, or include subagents and archived sessions. Results contain identifiers and lightweight metadata, with bounded page sizes. Enable these tools when callers may inspect the metadata of the whole mounted runtime. + +## 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 optional plugin where the intended callers receive tools. It is absent from the default profiles. + +### Access and composition + +Granting these tools grants read access to every Workspace and Session in the mounted runtime. Tool availability is the access control; there is no per-agent Workspace ACL or implicit restriction to the caller's working directory. LiveShare's tool allowlist does not include these tools. + +The plugin requires `tools`, `sessions`, `sessionQuery`, `workspaceRegistry`, and `sessionProjections`. A projection cache supplies metadata for cold sessions; without it, cold rows use the documented missing-metadata values. In a headless profile, the base bundle supplies the other dependencies; add the Workspace registry and this plugin in a profile patch: + +```yaml +- insert: + - id: workspace-registry + name: '@deepseek-ai/dsh-workspace' + - id: tool-session-list + name: '@deepseek-ai/dsh-tool-session-list' +``` + +| Field | Default | Meaning | +|---|---|---| +| `listWorkSliceMs` | `16` | Positive safe integer work slice in milliseconds for Session metadata reads; checked between complete rows | + +When the composition already mounts `workspaceRegistry`, add only the tool row. Workspace initialization follows the [registry's existing history bootstrap](../../workspace/workspace/README.md); listing calls do not create or attach sessions or change registry records. + +### Listing behavior + +Both tools return an array directly. The [tool catalog](../../../docs/tool-catalog.md#deepseek-aidsh-tool-session-list) defines arguments. Pagination follows filtering and ordering; each call defaults to 20 entries, accepts at most 100, and starts at offset zero. Increase the offset by the number of returned entries to continue; an empty array ends the traversal. + +`list_workspace` preserves registry order and includes workspaces with no sessions. `list_session` includes unarchived ordinary sessions by default, including sessions outside every Workspace when no `workspace_id` is supplied. Explicit Workspace selection uses recorded membership, not a matching working directory. With subagents included, a directly assigned Workspace wins; otherwise the nearest recorded member ancestor determines membership. Ordinary forked sessions do not inherit membership through their parents. Archival matches each Session's own ID, independently of its ancestors. + +Session order is descending `updated_at`, then ascending Session ID for ties. Activity time is the later of creation and the latest human-authored prompt; assistant activity and title changes do not advance it. Titles come from live projections or persisted projection metadata. Unavailable titles are `null`, and unavailable activity metadata falls back to creation time. Timestamps are ISO 8601 strings. Pin order and manual sidebar order do not affect the results. + +Session metadata reads yield between complete rows when the configured work slice expires and check cancellation before continuing. The slice is not a hard latency bound: it cannot split one synchronous row, query enumeration, or final sorting. The list does not promise one snapshot across all Sessions. + +### Failures + +Invalid pagination and an unknown `workspace_id` fail with `ToolArgsError` (`INVALID_ARGS`); use `list_workspace` to find a registered ID. Query and storage failures fail the call, and cyclic subagent ancestry encountered during Workspace selection fails with `SESSION_QUERY_INVALID_LINEAGE`. Cancellation returns no partial result. These failures leave sessions and Workspace records untouched. + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +The tools combine the existing header-only query listing with Workspace membership and projected metadata. The shared `registerSessionListMetadata` helper acquires the same projection unit used by the Session API; each consumer releases its own registration when disposed. The title projection remains owned by `dsh-session-title`. Cold rows read the projection cache without opening the underlying log, including on a cache miss. No Session Controller or Agent activation is required. + +| File | Role | +|---|---| +| [`src/index.ts`](src/index.ts) | Tool schemas, registration, JSON result rendering, and generic tool cards | +| [`src/list.ts`](src/list.ts) | Pagination, membership selection, and live or cached metadata reads | + +
+ +----- + + +## Further Exploration + +- [Workspace registry](../../workspace/workspace/README.md) — recorded membership, registry order, and archival. +- [Session query](../session-query/README.md) — header enumeration and the shared list metadata reader. +- [Session projection cache](../../session/session-projection-cache/README.md) — persisted metadata and cache availability. +- [Session query package map](../README.md) — adjacent retrieval capabilities. + +----- + + +## Model Experience + +### Tool schemas and results + +#### What the model sees + +The [tool catalog](../../../docs/tool-catalog.md#deepseek-aidsh-tool-session-list) owns the `list_workspace` and `list_session` schemas. Each result renders as a JSON array. The plugin adds no separate system-prompt section. + +#### Token effect + +Available tool schemas contribute request tokens; each invocation adds its arguments and returned metadata. The page limit bounds the number of returned entries, while title and path lengths still affect result size. + +#### KV Cache effect + +The schemas remain stable while tool availability is unchanged. Calls append ordinary tool call and result history without replacing prior messages; enabling or disabling the tools changes the schema prefix. + +## Known Limitations and Deferred Work + + + +These constraints affect consumers of the lists. + +- **Cold metadata can be missing or stale** — listing never rebuilds it by reading the full log. A `null` title can mean either no title or unavailable title metadata. +- **Pagination is not a stable snapshot** — concurrent registry or Session changes can move entries between calls. Session listing enumerates candidates before selecting a page, so the page size does not bound total scan work. +- **Metadata access is runtime-wide** — callers needing per-agent Workspace authorization require a separately defined access policy before these tools are enabled for them. + + +### Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/session-query/tool-session-list/README.zh.md b/packages/session-query/tool-session-list/README.zh.md new file mode 100644 index 0000000000..54049b9d57 --- /dev/null +++ b/packages/session-query/tool-session-list/README.zh.md @@ -0,0 +1,128 @@ +--- +description: "通过可选的只读工具列出 Workspace 和 Session 元数据,支持分页以及缓存中的标题和活动时间。" +kind: "package-reference" +--- + +# @deepseek-ai/dsh-tool-session-list + +[English](README.md) | 中文 + +## 概述 + +无需恢复 agent(智能体)运行或读取冷会话的日志,即可发现工作区和会话。可以列出空工作区、查找某工作区中的会话,或包含 subagent 和已归档会话。结果包含标识符及轻量元数据,并限制每页条目数。当调用者可以查看整个已挂载运行时的元数据时,启用这些工具。 + +## 目录 + +- [使用本包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [进一步探索](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与待办工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用本包 + +在预期调用者获取工具的作用域中挂载此可选插件。默认配置方案不包含它。 + +### 访问范围与组合 + +授予这些工具即授予读取已挂载运行时中全部 Workspace 和 Session 的权限。工具可用性就是访问控制;没有逐 agent 的 Workspace ACL,也不会隐式限制到调用者的工作目录。LiveShare 的工具允许列表不包含这些工具。 + +插件需要 `tools`、`sessions`、`sessionQuery`、`workspaceRegistry` 和 `sessionProjections`。投影缓存为冷会话提供元数据;没有缓存时,冷条目使用下文规定的元数据缺失值。在 headless 配置方案中,基础 bundle 已提供其他依赖;在配置方案补丁中添加 Workspace 注册表和此插件: + +```yaml +- insert: + - id: workspace-registry + name: '@deepseek-ai/dsh-workspace' + - id: tool-session-list + name: '@deepseek-ai/dsh-tool-session-list' +``` + +| 字段 | 默认值 | 含义 | +|---|---|---| +| `listWorkSliceMs` | `16` | Session 元数据读取的工作时间片,单位为毫秒,必须是正安全整数;在完整条目之间检查 | + +如果组合已经挂载 `workspaceRegistry`,只添加工具条目。Workspace 初始化遵循[注册表现有的历史引导行为](../../workspace/workspace/README.zh.md);列表调用不会创建或接入会话,也不会修改注册表记录。 + +### 列表行为 + +两个工具都直接返回数组。[工具目录](../../../docs/tool-catalog.zh.md#deepseek-aidsh-tool-session-list)定义参数。先过滤和排序,再分页;每次调用默认返回 20 条,最多接受 100 条,起始偏移为零。继续遍历时,将偏移增加已返回的条目数;空数组表示遍历结束。 + +`list_workspace` 保留注册表顺序,并包含没有会话的工作区。`list_session` 默认包含未归档的普通会话;没有指定 `workspace_id` 时,也包含不属于任何 Workspace 的会话。显式选择 Workspace 时使用已记录的成员关系,而非相同的工作目录。包含 subagent 时,直接分配的 Workspace 优先;否则由最近的已记录成员祖先确定归属。普通 fork 会话不会通过父级继承成员关系。归档筛选匹配每个 Session 自身的 ID,与祖先无关。 + +会话按 `updated_at` 降序排列,时间相同则按 Session ID 升序排列。活动时间取创建时间与最近人工提示词时间的较晚值;助手活动和标题变化不会推进它。标题来自实时投影或持久化投影元数据。标题不可用时为 `null`,活动元数据不可用时回退到创建时间。时间戳使用 ISO 8601 字符串。置顶顺序和侧边栏手动顺序不影响结果。 + +Session 元数据读取在配置的工作时间片耗尽时,于完整条目之间让出执行,并在继续前检查取消。时间片不是严格的延迟上限:它无法切分单条同步读取、查询枚举或最终排序。列表不承诺所有 Session 共享同一个快照。 + +### 失败 + +无效分页参数或未知的 `workspace_id` 以 `ToolArgsError`(`INVALID_ARGS`)失败;使用 `list_workspace` 查找已注册的 ID。查询和存储故障使调用失败,按 Workspace 筛选时遇到循环的 subagent 祖先关系则以 `SESSION_QUERY_INVALID_LINEAGE` 失败。取消不返回部分结果。这些失败不会修改会话或 Workspace 记录。 + +----- + + +## 理解实现 + +
+实现细节——点击展开 + +工具将现有的仅 header 查询列表与 Workspace 成员关系及投影元数据结合。共享的 `registerSessionListMetadata` 辅助函数获取 Session API 使用的同一个投影单元;每个消费方在释放时只移除自己的注册。标题投影仍由 `dsh-session-title` 拥有。冷条目读取投影缓存,不打开底层日志,缓存未命中时也一样。不需要 Session 控制器,也不会激活 agent。 + +| 文件 | 职责 | +|---|---| +| [`src/index.ts`](src/index.ts) | 工具 schema、注册、JSON 结果渲染与通用工具卡片 | +| [`src/list.ts`](src/list.ts) | 分页、成员筛选以及实时或缓存元数据读取 | + +
+ +----- + + +## 进一步探索 + +- [Workspace 注册表](../../workspace/workspace/README.zh.md)——已记录的成员关系、注册表顺序与归档。 +- [Session 查询](../session-query/README.zh.md)——header 枚举与共享列表元数据读取函数。 +- [Session 投影缓存](../../session/session-projection-cache/README.zh.md)——持久化元数据与缓存可用性。 +- [Session 查询包映射](../README.zh.md)——相邻的检索能力。 + +----- + + +## 模型体验 + +### 工具 schema 与结果 + +#### 模型可见内容 + +[工具目录](../../../docs/tool-catalog.zh.md#deepseek-aidsh-tool-session-list)拥有 `list_workspace` 和 `list_session` 的 schema。每个结果渲染为 JSON 数组。插件不增加独立的系统提示词段落。 + +#### Token 影响 + +可用工具的 schema 占用请求 token;每次调用增加其参数和返回的元数据。每页上限限制返回的条目数,标题和路径长度仍会影响结果大小。 + +#### KV Cache 影响 + +工具可用性不变时,schema 保持稳定。调用追加普通工具调用与结果历史,不替换之前的消息;启用或禁用工具会改变 schema 前缀。 + +## 已知限制与待办工作 + + + +以下约束影响列表消费方。 + +- **冷元数据可能缺失或过期**——列表不会通过读取完整日志重建它。标题为 `null` 可能表示没有标题,也可能表示标题元数据不可用。 +- **分页不是稳定快照**——并发的注册表或 Session 变化可能让条目在多次调用间移动。会话列表先枚举候选项,再选取一页,因此每页大小不限制总扫描工作量。 +- **元数据访问覆盖整个运行时**——需要逐 agent Workspace 授权的调用者,必须先定义独立的访问策略,再为其启用这些工具。 + + +### 开发备注 + +
+维护者工作上下文——点击展开 + +无。 + +
diff --git a/packages/session-query/tool-session-list/locale/de.json b/packages/session-query/tool-session-list/locale/de.json new file mode 100644 index 0000000000..ef94863e4f --- /dev/null +++ b/packages/session-query/tool-session-list/locale/de.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Werkzeuge zur Sitzungsauflistung", + "description": "Listet Arbeitsbereiche und Sitzungen auf, ohne Agenten fortzusetzen." + } +} diff --git a/packages/session-query/tool-session-list/locale/en.json b/packages/session-query/tool-session-list/locale/en.json new file mode 100644 index 0000000000..8b3e1ef64a --- /dev/null +++ b/packages/session-query/tool-session-list/locale/en.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Session listing tools", + "description": "List workspaces and sessions without resuming agents." + } +} diff --git a/packages/session-query/tool-session-list/locale/es.json b/packages/session-query/tool-session-list/locale/es.json new file mode 100644 index 0000000000..985fd3aff1 --- /dev/null +++ b/packages/session-query/tool-session-list/locale/es.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Herramientas de listado de sesiones", + "description": "Lista espacios de trabajo y sesiones sin reanudar los agentes." + } +} diff --git a/packages/session-query/tool-session-list/locale/fr.json b/packages/session-query/tool-session-list/locale/fr.json new file mode 100644 index 0000000000..7e6ec40d8d --- /dev/null +++ b/packages/session-query/tool-session-list/locale/fr.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Outils de liste des sessions", + "description": "Liste les espaces de travail et les sessions sans relancer les agents." + } +} diff --git a/packages/session-query/tool-session-list/locale/ja.json b/packages/session-query/tool-session-list/locale/ja.json new file mode 100644 index 0000000000..43bcd18644 --- /dev/null +++ b/packages/session-query/tool-session-list/locale/ja.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "セッション一覧ツール", + "description": "エージェントを再開せずにワークスペースとセッションを一覧表示します。" + } +} diff --git a/packages/session-query/tool-session-list/locale/pt.json b/packages/session-query/tool-session-list/locale/pt.json new file mode 100644 index 0000000000..43bdfa3130 --- /dev/null +++ b/packages/session-query/tool-session-list/locale/pt.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Ferramentas de listagem de sessões", + "description": "Lista espaços de trabalho e sessões sem retomar os agentes." + } +} diff --git a/packages/session-query/tool-session-list/locale/ru.json b/packages/session-query/tool-session-list/locale/ru.json new file mode 100644 index 0000000000..7cbeb022f3 --- /dev/null +++ b/packages/session-query/tool-session-list/locale/ru.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Инструменты списка сеансов", + "description": "Показывает рабочие пространства и сеансы без возобновления работы агентов." + } +} diff --git a/packages/session-query/tool-session-list/locale/zh.json b/packages/session-query/tool-session-list/locale/zh.json new file mode 100644 index 0000000000..3588c3e15a --- /dev/null +++ b/packages/session-query/tool-session-list/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "会话列表工具", + "description": "列出工作区和会话,无需恢复智能体运行。" + } +} diff --git a/packages/session-query/tool-session-list/package.json b/packages/session-query/tool-session-list/package.json new file mode 100644 index 0000000000..897629f33e --- /dev/null +++ b/packages/session-query/tool-session-list/package.json @@ -0,0 +1,74 @@ +{ + "name": "@deepseek-ai/dsh-tool-session-list", + "description": "Read-only paginated Workspace and Session metadata tools", + "version": "0.2.2-rc.1", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/session-query/tool-session-list" + }, + "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/*", + "./locale/*.json": "./locale/*.json", + "./package.json": "./package.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-tools": "workspace:*", + "@deepseek-ai/dsh-session": "workspace:*", + "@deepseek-ai/dsh-session-query": "workspace:*", + "@deepseek-ai/dsh-session-projection": "workspace:*", + "@deepseek-ai/dsh-session-projection-cache": "workspace:*", + "@deepseek-ai/dsh-workspace": "workspace:*", + "@deepseek-ai/dsh-session-title": "workspace:*" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-tools": "workspace:*", + "@deepseek-ai/dsh-session": "workspace:*", + "@deepseek-ai/dsh-session-query": "workspace:*", + "@deepseek-ai/dsh-session-projection": "workspace:*", + "@deepseek-ai/dsh-session-projection-cache": "workspace:*", + "@deepseek-ai/dsh-workspace": "workspace:*", + "@deepseek-ai/dsh-agent": "workspace:*", + "@deepseek-ai/dsh-llm": "workspace:*", + "@deepseek-ai/dsh-session-title": "workspace:*", + "@deepseek-ai/dsh-session-persistence": "workspace:*", + "@deepseek-ai/dsh-storage": "workspace:*", + "@deepseek-ai/dsh-storage-domain": "workspace:*", + "@deepseek-ai/dsh-system-prompt": "workspace:*", + "@deepseek-ai/dsh-tool-executor-native": "workspace:*", + "@deepseek-ai/dsh-tool-testkit": "workspace:*", + "@deepseek-ai/dsh-storage-json": "workspace:*" + }, + "peerDependenciesMeta": { + "@deepseek-ai/dsh-session-projection-cache": { + "optional": true + }, + "@deepseek-ai/dsh-session-title": { + "optional": true + } + }, + "dependencies": { + "@deepseek-ai/schemastery": "workspace:~" + } +} diff --git a/packages/session-query/tool-session-list/src/index.ts b/packages/session-query/tool-session-list/src/index.ts new file mode 100644 index 0000000000..24fb9b3825 --- /dev/null +++ b/packages/session-query/tool-session-list/src/index.ts @@ -0,0 +1,99 @@ +/** + * Opt-in read-only Workspace and Session metadata tools for the mounted runtime. + * @module @deepseek-ai/dsh-tool-session-list + */ + +import type { Context } from '@deepseek-ai/cordis' +import z from '@deepseek-ai/schemastery' +import { registerSessionListMetadata } from '@deepseek-ai/dsh-session-query' +import { defineTool } from '@deepseek-ai/dsh-tools' +import { listSessions, listWorkspaces } from './list.ts' + +/** Cordis plugin identity. */ +export const name = 'tool-session-list' +/** Services needed for header-only listing and live metadata. */ +export const inject = ['tools', 'sessions', 'sessionQuery', 'workspaceRegistry', 'sessionProjections'] + +/** Deployment-owned responsiveness for large Session lists. */ +export interface Config { + /** Positive integral work slice in milliseconds; defaults to 16. Checked between complete rows. */ + readonly listWorkSliceMs?: number +} + +/** Loader configuration for cooperative list scheduling. */ +export const Config: z = z.object({ + listWorkSliceMs: z.number().step(1).min(1).default(16), +}) + +const pagination = { + limit: { type: 'integer', description: 'Maximum entries to return, from 1 to 100. Defaults to 20.' }, + offset: { type: 'integer', description: 'Number of matching entries to skip. Defaults to 0.' }, +} as const + +/** + * Grant tools access to all Workspace and Session metadata in this runtime. + * @param ctx - scoped context granting these tools to its callers. + * @param config - deployment work-slice choice; omitted uses 16 milliseconds. + * @returns when the shared list metadata projection and tools are registered. + */ +export async function apply(ctx: Context, config: Config = {}): Promise { + const workSliceMs = config.listWorkSliceMs ?? 16 + if (!Number.isSafeInteger(workSliceMs) || workSliceMs < 1) { + throw new TypeError('tool-session-list: listWorkSliceMs must be a positive safe integer') + } + const readMetadata = await registerSessionListMetadata(ctx) + ctx.tools.register(defineTool({ + name: 'list_workspace', + description: 'List workspaces in registry order, including empty workspaces. Returns IDs, titles, paths, and creation and update times.', + parameters: pagination, + output: { + schema: { + type: 'array', + items: { + type: 'object', + additionalProperties: false, + properties: { + workspace_id: { type: 'string', required: true }, + title: { type: 'string', required: true }, + path: { type: 'string', required: true }, + created_at: { type: 'string', required: true, description: 'ISO 8601 creation time.' }, + updated_at: { type: 'string', required: true, description: 'ISO 8601 update time.' }, + }, + }, + }, + render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }], + }, + isConcurrencySafe: () => true, + execute: (args, exec) => Promise.resolve(listWorkspaces(ctx, args, exec.signal)), + presentCall: () => ({ card: 'generic', title: 'List workspaces', kind: 'read' }), + })) + ctx.tools.register(defineTool({ + name: 'list_session', + description: 'List sessions by latest human prompt time, newest first, then by ID. Returns IDs, available titles, and ISO creation and update times. Missing activity metadata uses creation time; unavailable titles are null.', + parameters: { + workspace_id: { type: 'string', description: 'Workspace ID from list_workspace. Includes its members and, when requested, subagents belonging through their nearest member ancestor. Omit to list all accessible sessions.' }, + contain_subagent: { type: 'boolean', description: 'Include subagent sessions. Defaults to false.' }, + archived: { type: 'boolean', description: 'Return only archived sessions when true, otherwise only unarchived sessions. Defaults to false.' }, + ...pagination, + }, + output: { + schema: { + type: 'array', + items: { + type: 'object', + additionalProperties: false, + properties: { + session_id: { type: 'string', required: true }, + title: { oneOf: [{ type: 'string' }, { type: 'null' }], required: true }, + created_at: { type: 'string', required: true, description: 'ISO 8601 creation time.' }, + updated_at: { type: 'string', required: true, description: 'ISO 8601 latest human prompt time, or creation time when unavailable.' }, + }, + }, + }, + render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }], + }, + isConcurrencySafe: () => true, + execute: (args, exec) => listSessions(ctx, readMetadata, args, exec.signal, workSliceMs), + presentCall: args => ({ card: 'generic', title: 'List sessions', kind: 'read', rawInput: args.workspace_id }), + })) +} diff --git a/packages/session-query/tool-session-list/src/list.ts b/packages/session-query/tool-session-list/src/list.ts new file mode 100644 index 0000000000..1176e3db48 --- /dev/null +++ b/packages/session-query/tool-session-list/src/list.ts @@ -0,0 +1,182 @@ +/** Header-only selection and cached metadata for the read-only listing tools. */ + +import { performance } from 'node:perf_hooks' +import { scheduler } from 'node:timers/promises' +import type { Context } from '@deepseek-ai/cordis' +import type { Session, SessionHeader, SessionId } from '@deepseek-ai/dsh-session' +import { SessionQueryError, type SessionListMetadata } from '@deepseek-ai/dsh-session-query' +import type {} from '@deepseek-ai/dsh-session-projection-cache' +import type {} from '@deepseek-ai/dsh-session-title' +import { ToolArgsError } from '@deepseek-ai/dsh-tools' +import { WorkspaceId } from '@deepseek-ai/dsh-workspace' + +/** Optional model pagination arguments. */ +export interface PageInput { + readonly limit?: number + readonly offset?: number +} + +/** Optional Session selection arguments. */ +export interface SessionListInput extends PageInput { + readonly workspace_id?: string + readonly contain_subagent?: boolean + readonly archived?: boolean +} + +interface WorkspaceListItem { + workspace_id: WorkspaceId + title: string + path: string + created_at: string + updated_at: string +} + +interface SessionListItem { + session_id: SessionId + title: string | null + created_at: string + updated_at: string +} + +/** + * Resolve pagination before reading any registry or persistence data. + * @param input - model pagination arguments. + * @returns the validated count and starting index. + */ +export function resolvePage(input: PageInput): { limit: number; offset: number } { + const limit = input.limit ?? 20 + const offset = input.offset ?? 0 + if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100) { + throw new ToolArgsError(['limit must be an integer from 1 to 100']) + } + if (!Number.isSafeInteger(offset) || offset < 0) { + throw new ToolArgsError(['offset must be a non-negative safe integer']) + } + return { limit, offset } +} + +/** + * Read one page of the authoritative Workspace order, including empty records. + * @param ctx - context providing the Workspace registry. + * @param input - pagination arguments. + * @param signal - caller cancellation. + * @returns Workspace metadata with ISO timestamps. + */ +export function listWorkspaces(ctx: Context, input: PageInput, signal: AbortSignal): WorkspaceListItem[] { + const { limit, offset } = resolvePage(input) + signal.throwIfAborted() + return ctx.workspaceRegistry.list().slice(offset, offset + limit).map(workspace => ({ + workspace_id: workspace.id, + title: workspace.title, + path: workspace.path, + created_at: workspace.createdAt, + updated_at: workspace.updatedAt, + })) +} + +/** + * List live and persisted Session metadata without opening cold logs or activating Agents. + * @param ctx - context providing query, Workspace, and projection services. + * @param readLiveMetadata - ready reader owned by this plugin's registration. + * @param input - filters and pagination arguments. + * @param signal - caller cancellation, forwarded to the corpus listing. + * @param workSliceMs - resolved positive integral work slice between complete rows. + * @returns filtered Session metadata ordered by activity, then identity. + */ +export async function listSessions( + ctx: Context, + readLiveMetadata: (session: Session) => SessionListMetadata, + input: SessionListInput, + signal: AbortSignal, + workSliceMs: number, +): Promise { + const { limit, offset } = resolvePage(input) + signal.throwIfAborted() + const workspaceId = input.workspace_id === undefined ? undefined : WorkspaceId(input.workspace_id) + if (workspaceId !== undefined && ctx.workspaceRegistry.get(workspaceId) === undefined) { + throw new ToolArgsError([`workspace_id ${JSON.stringify(workspaceId)} is not registered; use list_workspace to find a workspace`]) + } + const records = await ctx.sessionQuery.listSessions(signal) + signal.throwIfAborted() + const archived = new Set(ctx.workspaceRegistry.archivedSessionIds) + const ownership = new Map() + if (workspaceId !== undefined) { + for (const workspace of ctx.workspaceRegistry.list()) { + for (const id of workspace.sessionIds) ownership.set(id, workspace.id) + } + } + const headers = new Map(records.map(record => [record.header.id, record.header])) + const nearestWorkspace = ancestorWorkspaceReader(headers, ownership) + const items = [] + let yieldDeadline = performance.now() + workSliceMs + for (const { header } of records) { + signal.throwIfAborted() + if (performance.now() >= yieldDeadline) { + await scheduler.yield() + signal.throwIfAborted() + yieldDeadline = performance.now() + workSliceMs + } + if (!input.contain_subagent && header.origin === 'subagent') continue + if (archived.has(header.id) !== (input.archived ?? false)) continue + if (workspaceId !== undefined) { + const owner = header.origin === 'subagent' ? nearestWorkspace(header) : ownership.get(header.id) + if (owner !== workspaceId) continue + } + const metadata = readListMetadata(ctx, header, readLiveMetadata) + items.push({ + session_id: header.id, + title: metadata.title, + created_at: new Date(header.createdAt).toISOString(), + updatedAt: Math.max(header.createdAt, metadata.lastPromptAt ?? 0), + }) + } + items.sort((left, right) => right.updatedAt - left.updatedAt + || (left.session_id < right.session_id ? -1 : 1)) + signal.throwIfAborted() + return items.slice(offset, offset + limit).map(({ updatedAt, ...item }) => ({ + ...item, + updated_at: new Date(updatedAt).toISOString(), + })) +} + +function readListMetadata( + ctx: Context, + header: SessionHeader, + readLiveMetadata: (session: Session) => SessionListMetadata, +): { title: string | null; lastPromptAt: number | null } { + const live = ctx.sessions.get(header.id) + if (live !== undefined) { + return { + title: ctx.sessionProjections.snapshot(live, ['title']).values.title ?? null, + lastPromptAt: readLiveMetadata(live).lastPromptAt, + } + } + const cache = ctx.get('sessionProjectionCache') + const snapshot = cache?.cachedSnapshot(header, ['title', 'sessionListMetadata']) + ?? cache?.cachedPredecessorTitle(header) + return { + title: snapshot?.values.title ?? null, + lastPromptAt: snapshot?.values.sessionListMetadata?.lastPromptAt ?? null, + } +} + +function ancestorWorkspaceReader( + headers: ReadonlyMap, + ownership: ReadonlyMap, +): (header: SessionHeader) => WorkspaceId | undefined { + const resolved = new Map(ownership) + return (header) => { + const visited = new Set() + let current: SessionHeader | undefined = header + while (current !== undefined && !resolved.has(current.id)) { + if (visited.has(current.id)) { + throw new SessionQueryError(`Session ${header.id} has cyclic parent ancestry`, 'SESSION_QUERY_INVALID_LINEAGE') + } + visited.add(current.id) + current = current.parentSession === undefined ? undefined : headers.get(current.parentSession) + } + const workspace = current === undefined ? undefined : resolved.get(current.id) + for (const id of visited) resolved.set(id, workspace) + return workspace + } +} diff --git a/packages/session-query/tool-session-list/tests/fixtures/session-list-seed.ts b/packages/session-query/tool-session-list/tests/fixtures/session-list-seed.ts new file mode 100644 index 0000000000..77e9986ed6 --- /dev/null +++ b/packages/session-query/tool-session-list/tests/fixtures/session-list-seed.ts @@ -0,0 +1,65 @@ +/** Deterministic Session and Workspace inputs for the shipped headless list tools. */ + +import { mkdir } from 'node:fs/promises' +import { join } from 'node:path' +import type { Context } from '@deepseek-ai/cordis' +import { SessionId } from '@deepseek-ai/dsh-session' +import type {} from '@deepseek-ai/dsh-session-title' +import type {} from '@deepseek-ai/dsh-storage-domain' +import WorkspaceRegistry, { WorkspaceId, workspaceDomainSpec } from '@deepseek-ai/dsh-workspace' + +/** Loader fixture identity. */ +export const name = 'session-list-seed' +/** Real services used to prepare the scenario's durable registry and attached Sessions. */ +export const inject = ['sessions', 'sessionPersistence', 'storageDomain'] + +/** + * Seed stable list inputs before the Workspace registry becomes available. + * These attached Sessions have no Agent, so the agent-loop persistence owner never publishes them. + * @param ctx - fixture lifetime and the shipped storage and Session services. + * @returns when the actual Workspace registry has opened the seeded domain. + */ +export async function apply(ctx: Context): Promise { + const cwd = process.cwd() + const emptyPath = join(cwd, '.dsh', 'empty-workspace') + await mkdir(emptyPath, { recursive: true }) + const alpha = ctx.sessions.create(SessionId('list-alpha'), { meta: { cwd, createdAt: 1_000 } }) + alpha.append('session/title', { title: 'Alpha', messageSeqs: [], source: { kind: 'user' } }) + ctx.sessions.create(SessionId('list-beta'), { meta: { cwd, createdAt: 2_000 } }) + ctx.sessions.create(SessionId('list-archived'), { meta: { cwd, createdAt: 3_000 } }) + ctx.sessions.create(SessionId('list-child'), { + meta: { cwd, createdAt: 4_000, parentSession: alpha.id, origin: 'subagent', delegationDepth: 1 }, + }) + // Matching cwd alone does not make this Session a member of the stored Workspace. + ctx.sessions.create(SessionId('list-unaffiliated'), { meta: { cwd, createdAt: 5_000 } }) + + const workspaceId = WorkspaceId('list-workspace') + const emptyId = WorkspaceId('list-empty') + const domain = await ctx.storageDomain.open(workspaceDomainSpec) + try { + const table = domain.table('workspaces') + await table.put(workspaceId, { + path: cwd, + title: 'List fixture', + sessionIds: [alpha.id, SessionId('list-beta'), SessionId('list-archived')], + createdAt: '2000-01-01T00:00:00.000Z', + updatedAt: '2000-01-02T00:00:00.000Z', + }) + await table.put(emptyId, { + path: emptyPath, + title: 'Empty workspace', + sessionIds: [], + createdAt: '2000-01-03T00:00:00.000Z', + updatedAt: '2000-01-04T00:00:00.000Z', + }) + await domain.global.set({ + initialized: true, + workspaceIds: [workspaceId, emptyId], + archivedSessionIds: [SessionId('list-archived')], + pinnedSessionIds: [], + }) + } finally { + await domain.close() + } + await ctx.plugin(WorkspaceRegistry) +} diff --git a/packages/session-query/tool-session-list/tests/tool-session-list.spec.ts b/packages/session-query/tool-session-list/tests/tool-session-list.spec.ts new file mode 100644 index 0000000000..a39534a926 --- /dev/null +++ b/packages/session-query/tool-session-list/tests/tool-session-list.spec.ts @@ -0,0 +1,437 @@ +import { mkdir, mkdtemp, realpath, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { performance } from 'node:perf_hooks' +import { scheduler } from 'node:timers/promises' +import { Context } from '@deepseek-ai/cordis' +import AgentRegistry from '@deepseek-ai/dsh-agent' +import { createUserMessage, ToolCallId } from '@deepseek-ai/dsh-llm' +import SessionStore, { SESSION_FORMAT_VERSION, SessionId, SessionLogOffset } from '@deepseek-ai/dsh-session' +import type { Session, SessionHeader } from '@deepseek-ai/dsh-session' +import SessionPersistence, { SessionPersistenceRevision } from '@deepseek-ai/dsh-session-persistence' +import type { SessionHandle, SessionPersistenceListOptions, SessionPersistenceSnapshot } from '@deepseek-ai/dsh-session-persistence' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' +import SessionProjectionCache, { projectionCacheDomainSpec } from '@deepseek-ai/dsh-session-projection-cache' +import type { CheckpointRecord } from '@deepseek-ai/dsh-session-projection-cache' +import SessionQueryEngine from '@deepseek-ai/dsh-session-query' +import type { SessionEventSearchPage, SessionSearchHit, SessionSearchPage } from '@deepseek-ai/dsh-session-query' +import { titleProjectionDefinition } from '@deepseek-ai/dsh-session-title' +import Storage from '@deepseek-ai/dsh-storage' +import * as StorageDomain from '@deepseek-ai/dsh-storage-domain' +import * as StorageJson from '@deepseek-ai/dsh-storage-json' +import SystemPrompt from '@deepseek-ai/dsh-system-prompt' +import { executeToolFixture } from '@deepseek-ai/dsh-tool-testkit' +import ToolRuntime from '@deepseek-ai/dsh-tools' +import type { ToolExecutionResult } from '@deepseek-ai/dsh-tools' +import WorkspaceRegistry, { WorkspaceId, workspaceDomainSpec } from '@deepseek-ai/dsh-workspace' +import type { WorkspaceRecord } from '@deepseek-ai/dsh-workspace' +import { afterEach, describe, expect, it, vi } from 'vitest' +import * as ToolSessionList from '../src/index.ts' + +const contexts: Context[] = [] +const roots: string[] = [] + +afterEach(async () => { + vi.restoreAllMocks() + for (const ctx of contexts.splice(0)) await ctx.fiber.dispose() + for (const root of roots.splice(0)) await rm(root, { recursive: true, force: true }) +}) + +class HeaderPersistence extends SessionPersistence { + readonly headers: SessionHeader[] + + constructor(ctx: Context, config: { headers: SessionHeader[] }) { + super(ctx) + this.headers = config.headers + } + + override create = vi.fn((): Promise => Promise.reject(new Error('listing must not create a stored Session'))) + override open = vi.fn((): Promise => Promise.reject(new Error('listing must not open an event log'))) + override flush = vi.fn((): Promise => Promise.resolve()) + override stat = vi.fn((): Promise => Promise.reject(new Error('listing must not stat each Session'))) + override list = vi.fn((options?: SessionPersistenceListOptions): Promise => { + options?.signal?.throwIfAborted() + return Promise.resolve(this.headers.map(header => ({ header, revision: SessionPersistenceRevision(`rev-${header.id}`) }))) + }) +} + +class ListingQuery extends SessionQueryEngine { + override searchSessions(): Promise> { + return Promise.reject(new Error('listing must not search Session contents')) + } + + override searchEvents(): Promise { + return Promise.reject(new Error('listing must not search event contents')) + } +} + +function header(id: string, createdAt: number, options: Partial> = {}): SessionHeader { + return { id: SessionId(id), version: SESSION_FORMAT_VERSION, createdAt, isSeeded: false, ...options } +} + +function workspace(path: string, sessionIds: string[] = [], title = 'Workspace'): WorkspaceRecord { + return { + path, + title, + sessionIds: sessionIds.map(SessionId), + createdAt: '2026-01-01T00:00:00.000Z', + updatedAt: '2026-01-02T00:00:00.000Z', + } +} + +function checkpoint(meta: SessionHeader, title: string | null, lastPromptAt: number | null): CheckpointRecord { + return { + identity: { + formatVersion: meta.version, + createdAt: meta.createdAt, + isSeeded: false, + inheritedEventCount: SessionLogOffset(0), + ...meta.cwd === undefined ? {} : { cwd: meta.cwd }, + }, + rows: { + title: { ver: 1, seq: -1, val: title }, + sessionListMetadata: { ver: 1, seq: -1, val: { blank: false, lastPromptAt } }, + }, + } +} + +async function directory(): Promise { + const root = await realpath(await mkdtemp(join(tmpdir(), 'dsh-session-list-'))) + roots.push(root) + return root +} + +async function mount(options: { + headers?: SessionHeader[] + workspaces?: Array<[string, WorkspaceRecord]> + archived?: string[] + cached?: Array<[string, CheckpointRecord]> + cache?: boolean + config?: ToolSessionList.Config +} = {}) { + const workspaces = options.workspaces ?? [] + const ctx = new Context() + contexts.push(ctx) + await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(AgentRegistry) + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRuntime) + await ctx.plugin(Storage) + await ctx.plugin(StorageJson, { root: await directory() }) + await ctx.plugin(StorageDomain, { backend: 'json' }) + const workspaceDomain = await ctx.storageDomain.open(workspaceDomainSpec) + for (const [id, record] of workspaces) await workspaceDomain.table('workspaces').put(WorkspaceId(id), record) + await workspaceDomain.global.set({ + initialized: true, + workspaceIds: workspaces.map(([id]) => WorkspaceId(id)), + archivedSessionIds: (options.archived ?? []).map(SessionId), + pinnedSessionIds: [], + }) + await workspaceDomain.close() + const cacheDomain = await ctx.storageDomain.open(projectionCacheDomainSpec) + for (const [id, record] of options.cached ?? []) await cacheDomain.table('sessions').put(SessionId(id), record) + await cacheDomain.close() + await ctx.plugin(HeaderPersistence, { headers: options.headers ?? [] }) + await ctx.plugin(WorkspaceRegistry) + if (options.cache !== false) { + await ctx.plugin(SessionProjectionCache, { writeEveryEvents: 1000, writeIntervalMs: 60_000 }) + } + await ctx.sessionProjections.register(titleProjectionDefinition) + await ctx.plugin(ListingQuery) + const fiber = await ctx.plugin(ToolSessionList, options.config) + const read = vi.spyOn(ctx.sessionQuery, 'readSession') + const titles = vi.spyOn(ctx.sessionQuery, 'readTitleSnapshots') + const open = vi.spyOn(ctx.sessionPersistence, 'open') + let callId = 0 + return { + ctx, + fiber, + read, + titles, + open, + call: (name: string, args: unknown = {}, signal = new AbortController().signal) => executeToolFixture(ctx, { + name, arguments: args, callId: ToolCallId(`list-${++callId}`), signal, + }), + } +} + +function value(result: ToolExecutionResult) { + if (result.isError) throw new Error(result.error.message) + return result.value +} + +function item(id: string, createdAt: number, updatedAt = createdAt, title: string | null = null) { + return { session_id: id, title, created_at: new Date(createdAt).toISOString(), updated_at: new Date(updatedAt).toISOString() } +} + +function prompt(session: Session) { + session.append('turn/start', { turn: 1 }) + return session.append('user/message', createUserMessage({ + content: [{ type: 'text', text: 'Human prompt' }], source: { kind: 'user' }, + }), { surfaceOp: 'append' }) +} + +function measureRows(ctx: Context, summaryMs: number) { + const clock = { now: 0 } + const trace: string[] = [] + const cachedSnapshot = ctx.sessionProjectionCache.cachedSnapshot.bind(ctx.sessionProjectionCache) + vi.spyOn(ctx.sessionProjectionCache, 'cachedSnapshot').mockImplementation((meta, keys) => { + clock.now += summaryMs + trace.push(meta.id) + return cachedSnapshot(meta, keys) + }) + vi.spyOn(performance, 'now').mockImplementation(() => clock.now) + return { clock, trace } +} + +describe('read-only Session list tools', () => { + it('lists empty Workspaces in registry order and applies offset after that order', async () => { + const path = await directory() + const secondPath = join(path, 'second') + await mkdir(secondPath) + const first = workspace(path, [], 'First') + const second = workspace(secondPath, [], 'Second') + const mounted = await mount({ workspaces: [['z-workspace', first], ['a-workspace', second]] }) + const rows = [first, second].map((record, index) => ({ + workspace_id: index === 0 ? 'z-workspace' : 'a-workspace', + title: record.title, path: record.path, created_at: record.createdAt, updated_at: record.updatedAt, + })) + expect(value(await mounted.call('list_workspace'))).toEqual(rows) + expect(value(await mounted.call('list_workspace', { limit: 1, offset: 1 }))).toEqual([rows[1]]) + expect(value(await mounted.call('list_workspace', { offset: 2 }))).toEqual([]) + expect(value(await mounted.call('list_session'))).toEqual([]) + }) + + it('uses current live metadata, cached cold metadata, and creation time for cache misses without opening logs', async () => { + const cold = header('cold', 10) + const live = header('live', 20) + const missing = header('missing', 30) + const mounted = await mount({ + headers: [cold, live, missing], + cached: [['cold', checkpoint(cold, 'Cold title', 100)], ['live', checkpoint(live, 'Old title', 90)]], + }) + const session = mounted.ctx.sessions.create(live.id, { meta: { createdAt: live.createdAt } }) + expect(value(await mounted.call('list_session'))).toEqual([ + item('cold', 10, 100, 'Cold title'), item('missing', 30), item('live', 20), + ]) + const human = prompt(session) + session.append('session/title', { title: 'Live title', messageSeqs: [], source: { kind: 'user' } }) + expect(value(await mounted.call('list_session'))).toEqual([ + item('live', 20, human.time, 'Live title'), item('cold', 10, 100, 'Cold title'), item('missing', 30), + ]) + expect(mounted.ctx.agents.list()).toEqual([]) + expect(mounted.ctx.sessions.list()).toEqual([session]) + expect(mounted.read).not.toHaveBeenCalled() + expect(mounted.titles).not.toHaveBeenCalled() + expect(mounted.open).not.toHaveBeenCalled() + }) + + it('uses creation time and null titles when the optional projection cache is not mounted', async () => { + const mounted = await mount({ headers: [header('cold', 10)], cache: false }) + expect(value(await mounted.call('list_session'))).toEqual([item('cold', 10)]) + expect(mounted.open).not.toHaveBeenCalled() + }) + + it('keeps the title hint of a predecessor cache without using its activity metadata', async () => { + const cold = header('predecessor', 10) + const old = checkpoint(cold, 'Prior title', 100) + old.identity.formatVersion = SESSION_FORMAT_VERSION - 1 + const mounted = await mount({ headers: [cold], cached: [[cold.id, old]] }) + expect(value(await mounted.call('list_session'))).toEqual([item('predecessor', 10, 10, 'Prior title')]) + expect(mounted.open).not.toHaveBeenCalled() + }) + + it('filters archive status and subagents before sorting and pagination; pins do not reorder results', async () => { + const mounted = await mount({ + headers: [header('z', 100), header('b', 100), header('a', 100), header('archived', 500), header('child', 200, { origin: 'subagent', parentSession: SessionId('z') })], + archived: ['archived'], + }) + await mounted.ctx.workspaceRegistry.pinSession(SessionId('z')) + expect(value(await mounted.call('list_session', { limit: 1, offset: 1 }))).toEqual([item('b', 100)]) + expect(value(await mounted.call('list_session', { contain_subagent: true }))).toEqual([ + item('child', 200), item('a', 100), item('b', 100), item('z', 100), + ]) + expect(value(await mounted.call('list_session', { archived: true }))).toEqual([item('archived', 500)]) + expect(value(await mounted.call('list_session', { archived: true, offset: 1 }))).toEqual([]) + }) + + it('breaks cached-activity ties by ID even when creation order differs', async () => { + const headers = [header('a', 10), header('b', 20), header('z', 30)] + const mounted = await mount({ headers, cached: headers.map(meta => [meta.id, checkpoint(meta, null, 100)]) }) + expect(value(await mounted.call('list_session'))).toEqual([ + item('a', 10, 100), item('b', 20, 100), item('z', 30, 100), + ]) + }) + + it('inherits explicit Workspace membership only for subagents and stops at the nearest assigned ancestor', async () => { + const path = await directory() + const otherPath = join(path, 'other') + await mkdir(otherPath) + const mounted = await mount({ + headers: [ + header('parent', 10, { cwd: path }), + header('same-cwd', 20, { cwd: path }), + header('child', 30, { cwd: path, origin: 'subagent', parentSession: SessionId('parent') }), + header('grandchild', 40, { origin: 'subagent', parentSession: SessionId('child') }), + header('fork', 50, { cwd: path, parentSession: SessionId('parent') }), + header('assigned-child', 60, { cwd: otherPath, origin: 'subagent', parentSession: SessionId('parent') }), + header('assigned-grandchild', 70, { origin: 'subagent', parentSession: SessionId('assigned-child') }), + header('orphan', 80, { origin: 'subagent', parentSession: SessionId('absent') }), + header('unassigned-child', 90, { origin: 'subagent', parentSession: SessionId('same-cwd') }), + ], + workspaces: [['primary', workspace(path, ['parent'])], ['other', workspace(otherPath, ['assigned-child'])]], + archived: ['parent'], + }) + expect(value(await mounted.call('list_session', { workspace_id: 'primary', contain_subagent: true }))).toEqual([ + item('grandchild', 40), item('child', 30), + ]) + expect(value(await mounted.call('list_session', { workspace_id: 'primary', archived: true }))).toEqual([item('parent', 10)]) + expect(value(await mounted.call('list_session', { workspace_id: 'other', contain_subagent: true }))).toEqual([ + item('assigned-grandchild', 70), item('assigned-child', 60), + ]) + expect(value(await mounted.call('list_session', { workspace_id: 'primary' }))).toEqual([]) + }) + + it('defaults to twenty rows and accepts the upper page limit', async () => { + const headers = Array.from({ length: 101 }, (_, index) => header(`session-${String(index).padStart(3, '0')}`, index)) + const mounted = await mount({ headers }) + expect(value(await mounted.call('list_session'))).toHaveLength(20) + expect(value(await mounted.call('list_session', { limit: 100 }))).toHaveLength(100) + expect(value(await mounted.call('list_session', { limit: 100, offset: 100 }))).toEqual([item('session-000', 0)]) + }) + + it.each(['list_workspace', 'list_session'])('rejects invalid pagination for %s with INVALID_ARGS', async (name) => { + const mounted = await mount() + const invalid = [{ limit: 0 }, { limit: 101 }, { limit: 1.5 }, { offset: -1 }, { offset: 1.5 }, { offset: Number.MAX_SAFE_INTEGER + 1 }] + for (const args of invalid) { + const result = await mounted.call(name, args) + expect(result.isError).toBe(true) + expect(result.error?.info).toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) + } + }) + + it('rejects an unknown Workspace and corrupt subagent ancestry with typed failures', async () => { + const path = await directory() + const mounted = await mount({ + headers: [header('cycle-a', 10, { origin: 'subagent', parentSession: SessionId('cycle-b') }), header('cycle-b', 20, { origin: 'subagent', parentSession: SessionId('cycle-a') })], + workspaces: [['known', workspace(path)]], + }) + expect((await mounted.call('list_session', { workspace_id: 'absent' })).error?.info) + .toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) + expect((await mounted.call('list_session', { workspace_id: 'known', contain_subagent: true })).error?.info) + .toMatchObject({ name: 'SessionQueryError', code: 'SESSION_QUERY_INVALID_LINEAGE' }) + expect(mounted.open).not.toHaveBeenCalled() + }) + + it('propagates cancellation during corpus discovery without reading metadata or activating Agents', async () => { + const mounted = await mount({ headers: [header('cold', 10)] }) + const controller = new AbortController() + const list = vi.spyOn(mounted.ctx.sessionQuery, 'listSessions').mockImplementation(async (signal) => { + expect(signal).toBe(controller.signal) + controller.abort(new Error('list cancelled')) + return [] + }) + const result = await mounted.call('list_session', {}, controller.signal) + expect(result.error?.info).toMatchObject({ name: 'AbortError', code: 'ABORTED' }) + expect(list).toHaveBeenCalledOnce() + expect(mounted.open).not.toHaveBeenCalled() + expect(mounted.ctx.agents.list()).toEqual([]) + }) + + it('registers concurrency-safe generic presentation and releases both tools on disposal', async () => { + const mounted = await mount() + for (const name of ['list_workspace', 'list_session']) { + const tool = mounted.ctx.tools.get(name) + expect(tool?.isConcurrencySafe?.({})).toBe(true) + expect(tool?.presentCall?.({})).toMatchObject({ card: 'generic', kind: 'read' }) + } + await mounted.fiber.dispose() + expect(mounted.ctx.tools.get('list_workspace')).toBeUndefined() + expect(mounted.ctx.tools.get('list_session')).toBeUndefined() + }) +}) + +describe('Session list work slices', () => { + const headers = [header('first', 30), header('middle', 20), header('last', 10)] + + it('resolves the default and explicit work slice through Loader configuration', () => { + expect(ToolSessionList.Config({})).toEqual({ listWorkSliceMs: 16 }) + expect(ToolSessionList.Config({ listWorkSliceMs: 8 })).toEqual({ listWorkSliceMs: 8 }) + }) + + it.each([0, -1, 0.5, Number.NaN, Number.POSITIVE_INFINITY, Number.MAX_SAFE_INTEGER + 1])( + 'rejects invalid work slice %s before registering a projection or tool', async (listWorkSliceMs) => { + const ctx = new Context() + contexts.push(ctx) + await expect(ToolSessionList.apply(ctx, { listWorkSliceMs })).rejects.toThrow( + 'tool-session-list: listWorkSliceMs must be a positive safe integer', + ) + }, + ) + + it('keeps cheap metadata reads in one synchronous slice', async () => { + const mounted = await mount({ headers }) + const { trace } = measureRows(mounted.ctx, 2) + const yieldWork = vi.spyOn(scheduler, 'yield') + expect(value(await mounted.call('list_session'))).toEqual([item('first', 30), item('middle', 20), item('last', 10)]) + expect(trace).toEqual(['first', 'middle', 'last']) + expect(yieldWork).not.toHaveBeenCalled() + }) + + it.each([ + { listWorkSliceMs: undefined, summaryMs: 8 }, + { listWorkSliceMs: 8, summaryMs: 4 }, + ])('resumes after an exhausted $listWorkSliceMs slice and resets the deadline after waiting', async ({ listWorkSliceMs, summaryMs }) => { + const mounted = await mount({ headers, config: listWorkSliceMs === undefined ? {} : { listWorkSliceMs } }) + if (listWorkSliceMs === undefined) { + await mounted.fiber.dispose() + await mounted.ctx.plugin({ inject: ToolSessionList.inject, apply: (ctx: Context) => ToolSessionList.apply(ctx) }) + } + const { clock, trace } = measureRows(mounted.ctx, summaryMs) + const yieldWork = vi.spyOn(scheduler, 'yield').mockImplementation(async () => { + trace.push('yield') + clock.now += 1_000 + }) + expect(value(await mounted.call('list_session'))).toEqual([item('first', 30), item('middle', 20), item('last', 10)]) + expect(trace).toEqual(['first', 'middle', 'yield', 'last']) + expect(yieldWork).toHaveBeenCalledOnce() + }) + + it('returns the final completed row without a trailing yield', async () => { + const mounted = await mount({ headers: [header('last', 10)] }) + measureRows(mounted.ctx, 16) + const yieldWork = vi.spyOn(scheduler, 'yield') + expect(value(await mounted.call('list_session'))).toEqual([item('last', 10)]) + expect(yieldWork).not.toHaveBeenCalled() + }) + + it('checks the work slice while classifying rows that the filters exclude', async () => { + const mounted = await mount({ + headers: headers.map(meta => ({ ...meta, origin: 'subagent', parentSession: SessionId('outside') })), + }) + const cached = vi.spyOn(mounted.ctx.sessionProjectionCache, 'cachedSnapshot') + // Classification consumes the first slice even though no metadata row is read. + vi.spyOn(performance, 'now').mockReturnValueOnce(0).mockReturnValueOnce(0).mockReturnValue(16) + const yieldWork = vi.spyOn(scheduler, 'yield').mockResolvedValue() + expect(value(await mounted.call('list_session'))).toEqual([]) + expect(yieldWork).toHaveBeenCalledOnce() + expect(cached).not.toHaveBeenCalled() + expect(mounted.open).not.toHaveBeenCalled() + }) + + it('cancels at a yielded row without reading later metadata or returning a partial list', async () => { + const mounted = await mount({ headers, config: { listWorkSliceMs: 4 } }) + const { trace } = measureRows(mounted.ctx, 4) + const controller = new AbortController() + const yieldWork = vi.spyOn(scheduler, 'yield').mockImplementation(async () => { + controller.abort(new Error('stop between rows')) + }) + const result = await mounted.call('list_session', {}, controller.signal) + expect(result.error?.info).toMatchObject({ name: 'AbortError', code: 'ABORTED' }) + expect(result.value).toBeUndefined() + expect(trace).toEqual(['first']) + expect(yieldWork).toHaveBeenCalledOnce() + expect(mounted.open).not.toHaveBeenCalled() + }) +}) diff --git a/packages/session-query/tool-session-list/tsconfig.json b/packages/session-query/tool-session-list/tsconfig.json new file mode 100644 index 0000000000..d2eabc4754 --- /dev/null +++ b/packages/session-query/tool-session-list/tsconfig.json @@ -0,0 +1,39 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../../core/tools" + }, + { + "path": "../../core/session" + }, + { + "path": "../session-query" + }, + { + "path": "../../session/session-projection" + }, + { + "path": "../../session/session-projection-cache" + }, + { + "path": "../../session/session-title" + }, + { + "path": "../../workspace/workspace" + } + ] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 65f0388b77..f27d93d4c7 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -123,6 +123,9 @@ importers: '@deepseek-ai/dsh-tool-ralph': specifier: workspace:* version: link:packages/experimental/tool-ralph + '@deepseek-ai/dsh-tool-session-list': + specifier: workspace:* + version: link:packages/session-query/tool-session-list '@deepseek-ai/dsh-tool-session-query': specifier: workspace:* version: link:packages/experimental/tool-session-query @@ -14673,6 +14676,9 @@ importers: '@deepseek-ai/dsh-session-format-catalog': specifier: workspace:* version: link:../../session/session-format-catalog + zod: + specifier: 4.6.6 + version: 4.6.6 devDependencies: '@deepseek-ai/cordis': specifier: workspace:~ @@ -14730,6 +14736,64 @@ importers: specifier: workspace:* version: link:../session-query + packages/session-query/tool-session-list: + dependencies: + '@deepseek-ai/schemastery': + specifier: link:../../../vendor/schemastery + version: link:../../../vendor/schemastery + devDependencies: + '@deepseek-ai/cordis': + specifier: workspace:~ + version: link:../../../vendor/cordis + '@deepseek-ai/dsh-agent': + specifier: workspace:* + version: link:../../core/agent + '@deepseek-ai/dsh-llm': + specifier: workspace:* + version: link:../../llm/llm + '@deepseek-ai/dsh-session': + specifier: workspace:* + version: link:../../core/session + '@deepseek-ai/dsh-session-persistence': + specifier: workspace:* + version: link:../../session/session-persistence + '@deepseek-ai/dsh-session-projection': + specifier: workspace:* + version: link:../../session/session-projection + '@deepseek-ai/dsh-session-projection-cache': + specifier: workspace:* + version: link:../../session/session-projection-cache + '@deepseek-ai/dsh-session-query': + specifier: workspace:* + version: link:../session-query + '@deepseek-ai/dsh-session-title': + specifier: workspace:* + version: link:../../session/session-title + '@deepseek-ai/dsh-storage': + specifier: workspace:* + version: link:../../storage/storage + '@deepseek-ai/dsh-storage-domain': + specifier: workspace:* + version: link:../../storage/storage-domain + '@deepseek-ai/dsh-storage-json': + specifier: workspace:* + version: link:../../storage/storage-json + '@deepseek-ai/dsh-system-prompt': + specifier: workspace:* + version: link:../../core/system-prompt + '@deepseek-ai/dsh-tool-executor-native': + specifier: workspace:* + version: link:../../core/tool-executor-native + '@deepseek-ai/dsh-tool-testkit': + specifier: workspace:* + version: link:../../test-support/tool-testkit + '@deepseek-ai/dsh-tools': + specifier: workspace:* + version: link:../../core/tools + '@deepseek-ai/dsh-workspace': + specifier: workspace:* + version: link:../../workspace/workspace + packages/session/message-quotes: devDependencies: '@deepseek-ai/cordis': diff --git a/scripts/gen-tool-catalog.ts b/scripts/gen-tool-catalog.ts index 7ca0a5d54f..871aa081e4 100644 --- a/scripts/gen-tool-catalog.ts +++ b/scripts/gen-tool-catalog.ts @@ -8,7 +8,7 @@ import { globSync, readFileSync, writeFileSync } from 'node:fs' import { basename, dirname, resolve } from 'node:path' -import { Context } from '@deepseek-ai/cordis' +import { Context, Service } from '@deepseek-ai/cordis' import LlmRuntime from '@deepseek-ai/dsh-llm' import type { ToolSchema } from '@deepseek-ai/dsh-llm' import AgentRegistry from '@deepseek-ai/dsh-agent' @@ -71,6 +71,8 @@ import Lsp from '@deepseek-ai/dsh-lsp' import * as ToolLsp from '@deepseek-ai/dsh-tool-lsp' import * as ToolSkill from '@deepseek-ai/dsh-tool-skill' import * as ToolSessionQuery from '@deepseek-ai/dsh-tool-session-query' +import * as ToolSessionList from '@deepseek-ai/dsh-tool-session-list' +import WorkspaceRegistry from '@deepseek-ai/dsh-workspace' import * as ToolJobs from '@deepseek-ai/dsh-tool-jobs' import BrowserUseRegistry from '@deepseek-ai/dsh-browser-use' import * as StagehandBrowserTools from '@deepseek-ai/dsh-experimental-browser-use-stagehand-native' @@ -136,6 +138,13 @@ class CatalogSessionPersistence extends SessionPersistence { list = unavailableCatalogPersistence } +/** Schema collection does not read Workspace records or open their durable domain. */ +class CatalogWorkspaceRegistry extends WorkspaceRegistry { + static override inject = [] + + protected override async [Service.init](): Promise {} +} + /** Storage operations are unreachable during schema collection. */ function unavailableCatalogPersistence(): never { throw new Error('gen-tool-catalog: persistence access is unavailable during schema harvest') @@ -570,6 +579,20 @@ const TOOL_PACKAGES: ToolPackage[] = [ await ctx.plugin(ToolSkill) }, }, + { + pkg: '@deepseek-ai/dsh-tool-session-list', + dir: 'tool-session-list', + source: 'packages/session-query/tool-session-list/src/index.ts', + requires: ['ctx.tools', 'ctx.sessions', 'ctx.sessionQuery', 'ctx.workspaceRegistry', 'ctx.sessionProjections'], + writes: ['tool/call', 'tool/result'], + async mount(ctx) { + await ctx.plugin(SessionStore) + await ctx.plugin(SqliteSessionQueryEngine, { path: ':memory:' }) + await ctx.plugin(CatalogWorkspaceRegistry) + await ctx.plugin(ToolSessionList) + }, + note: 'Opt-in access to all Workspace and Session list metadata in the mounted runtime. Cold titles and activity use the optional projection cache; absent values become null titles and creation-time recency. No Agent is activated.', + }, { pkg: '@deepseek-ai/dsh-tool-session-query', dir: 'tool-session-query', diff --git a/scripts/product-package-policy.ts b/scripts/product-package-policy.ts index d7ee247c03..0066304a50 100644 --- a/scripts/product-package-policy.ts +++ b/scripts/product-package-policy.ts @@ -16,6 +16,7 @@ export interface ProductPackagePolicy { * Optional integrations may be reached by an optional bundle without becoming default capabilities. */ export const PRODUCT_PACKAGE_POLICY: Readonly> = { + 'packages/session-query/tool-session-list': { category: 'optional', reason: 'Explicitly grants model callers read access to runtime Workspace and Session metadata.' }, 'packages/core/agent-tool-presentation': { category: 'optional', reason: 'Deprecated selector retained for existing executor configurations.' }, 'packages/browser-use/browser-use': { category: 'optional', reason: 'Service definition used by explicitly selected browser providers.' }, 'packages/computer-use/computer-use': { category: 'optional', reason: 'Service definition used by explicitly selected computer providers.' }, diff --git a/snapshots/session/session-list-tools/cordis.snapshot.yml b/snapshots/session/session-list-tools/cordis.snapshot.yml new file mode 100644 index 0000000000..d7b301ee86 --- /dev/null +++ b/snapshots/session/session-list-tools/cordis.snapshot.yml @@ -0,0 +1,52 @@ +# Replay patch shared by the ordinary headless snapshot composition. The model +# script comes from the scenario's committed session JSONL. + +- id: llm-deepseek + name: '@deepseek-ai/dsh-llm-deepseek-api-key' + disabled: true + +- id: plugin-package-inventory-deepseek + disabled: true + +- id: session-title-llm + disabled: true + +- id: session-persistence-jsonl + name: '@deepseek-ai/dsh-session-persistence-jsonl' + config: + root: !!js dshHomePath('sessions') + compression: none + +- id: sandbox + name: '@deepseek-ai/dsh-sandbox-local' + config: + runnerCommand: + - bash + - -c + - while [ "$1" != "--" ]; do shift; done; shift; exec "$@" + - passthrough-runner + runnerFailureSignatures: + - 'passthrough-runner: profile rejected' + +- insert: + - id: llm-replay + name: '@deepseek-ai/dsh-llm-replay' + config: + providers: + - id: deepseek-official + name: DeepSeek + models: + - id: deepseek-v4-flash + - id: deepseek-v4-pro + - id: deepseek-messages + name: DeepSeek Messages + models: + - id: deepseek-v4-flash + - id: deepseek-v4-pro + +- insert: + - id: session-list-seed + name: ../../../packages/session-query/tool-session-list/tests/fixtures/session-list-seed.ts + + - id: tool-session-list + name: '@deepseek-ai/dsh-tool-session-list' diff --git a/snapshots/session/session-list-tools/cordis.yml b/snapshots/session/session-list-tools/cordis.yml new file mode 100644 index 0000000000..35f941fe6d --- /dev/null +++ b/snapshots/session/session-list-tools/cordis.yml @@ -0,0 +1,6 @@ +- insert: + - id: session-list-seed + name: ../../../packages/session-query/tool-session-list/tests/fixtures/session-list-seed.ts + + - id: tool-session-list + name: '@deepseek-ai/dsh-tool-session-list' diff --git a/snapshots/session/session-list-tools/session.v4.jsonl b/snapshots/session/session-list-tools/session.v4.jsonl new file mode 100644 index 0000000000..18b6788ea5 --- /dev/null +++ b/snapshots/session/session-list-tools/session.v4.jsonl @@ -0,0 +1,57 @@ +{"type":"session","version":4,"id":"{{session:1}}","createdAt":0,"cwd":"{{cwd}}","isSeeded":false,"delegationDepth":0} +{"type":"permission/preset","data":{"preset":"danger-full-access"}} +{"type":"sandbox/mode","data":{"mode":"danger-full-access"}} +{"type":"approval/policy","data":{"policy":"never"}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"List the fixture workspaces and sessions."}],"source":{"kind":"user"},"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":"List the fixture workspaces and sessions."}],"source":{"kind":"user"},"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: 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 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"}],"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 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."}]},"role":"user","id":"{{message:3}}"},"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 fixture workspaces and","messageSeqs":[8],"source":{"kind":"fallback"}}} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"list-1","name":"list_workspace","arguments":"{}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"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":"list-1","name":"list_workspace","arguments":"{}"}}},{"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":"list-1","name":"list_workspace","arguments":"{}"}} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"list-1"},"toolCallId":"list-1","content":[{"type":"text","text":"[{\"workspace_id\":\"list-workspace\",\"title\":\"List fixture\",\"path\":\"{{cwd}}\",\"created_at\":\"2000-01-01T00:00:00.000Z\",\"updated_at\":\"2000-01-02T00:00:00.000Z\"},{\"workspace_id\":\"list-empty\",\"title\":\"Empty workspace\",\"path\":\"{{cwd}}/.dsh/empty-workspace\",\"created_at\":\"2000-01-03T00:00:00.000Z\",\"updated_at\":\"2000-01-04T00:00:00.000Z\"}]"}],"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":"list-2","name":"list_workspace","arguments":"{\"limit\":1,\"offset\":1}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"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":"list-2","name":"list_workspace","arguments":"{\"limit\":1,\"offset\":1}"}}},{"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":"list-2","name":"list_workspace","arguments":"{\"limit\":1,\"offset\":1}"}} +{"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"list-2"},"toolCallId":"list-2","content":[{"type":"text","text":"[{\"workspace_id\":\"list-empty\",\"title\":\"Empty workspace\",\"path\":\"{{cwd}}/.dsh/empty-workspace\",\"created_at\":\"2000-01-03T00:00:00.000Z\",\"updated_at\":\"2000-01-04T00:00:00.000Z\"}]"}],"isError":false,"id":"{{message:7}}"}},"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":"list-3","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:8}}"},"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":"list-3","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\"}"}}},{"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":3,"callId":"list-3","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\"}"}} +{"type":"tool/result","data":{"turn":1,"step":3,"message":{"role":"tool","source":{"kind":"tool","callId":"list-3"},"toolCallId":"list-3","content":[{"type":"text","text":"[{\"session_id\":\"list-beta\",\"title\":null,\"created_at\":\"1970-01-01T00:00:02.000Z\",\"updated_at\":\"1970-01-01T00:00:02.000Z\"},{\"session_id\":\"list-alpha\",\"title\":\"Alpha\",\"created_at\":\"1970-01-01T00:00:01.000Z\",\"updated_at\":\"1970-01-01T00:00:01.000Z\"}]"}],"isError":false,"id":"{{message:9}}"}},"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":"tool-call","id":"list-4","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"contain_subagent\":true,\"limit\":2}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:10}}"},"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":"list-4","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"contain_subagent\":true,\"limit\":2}"}}},{"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":4,"callId":"list-4","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"contain_subagent\":true,\"limit\":2}"}} +{"type":"tool/result","data":{"turn":1,"step":4,"message":{"role":"tool","source":{"kind":"tool","callId":"list-4"},"toolCallId":"list-4","content":[{"type":"text","text":"[{\"session_id\":\"list-child\",\"title\":null,\"created_at\":\"1970-01-01T00:00:04.000Z\",\"updated_at\":\"1970-01-01T00:00:04.000Z\"},{\"session_id\":\"list-beta\",\"title\":null,\"created_at\":\"1970-01-01T00:00:02.000Z\",\"updated_at\":\"1970-01-01T00:00:02.000Z\"}]"}],"isError":false,"id":"{{message:11}}"}},"sourceEventSeqs":[29],"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":"list-5","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"archived\":true}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:12}}"},"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":"list-5","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"archived\":true}"}}},{"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":5,"callId":"list-5","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"archived\":true}"}} +{"type":"tool/result","data":{"turn":1,"step":5,"message":{"role":"tool","source":{"kind":"tool","callId":"list-5"},"toolCallId":"list-5","content":[{"type":"text","text":"[{\"session_id\":\"list-archived\",\"title\":null,\"created_at\":\"1970-01-01T00:00:03.000Z\",\"updated_at\":\"1970-01-01T00:00:03.000Z\"}]"}],"isError":false,"id":"{{message:13}}"}},"sourceEventSeqs":[34],"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":"tool-call","id":"list-6","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"limit\":1,\"offset\":1}"}],"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":"list-6","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"limit\":1,\"offset\":1}"}}},{"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":6,"callId":"list-6","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"limit\":1,\"offset\":1}"}} +{"type":"tool/result","data":{"turn":1,"step":6,"message":{"role":"tool","source":{"kind":"tool","callId":"list-6"},"toolCallId":"list-6","content":[{"type":"text","text":"[{\"session_id\":\"list-alpha\",\"title\":\"Alpha\",\"created_at\":\"1970-01-01T00:00:01.000Z\",\"updated_at\":\"1970-01-01T00:00:01.000Z\"}]"}],"isError":false,"id":"{{message:15}}"}},"sourceEventSeqs":[39],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":6}} +{"type":"step/start","data":{"turn":1,"step":7}} +{"type":"assistant/message","data":{"turn":1,"step":7,"message":{"role":"assistant","content":[{"type":"tool-call","id":"list-7","name":"list_session","arguments":"{\"workspace_id\":\"list-empty\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:16}}"},"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":"list-7","name":"list_session","arguments":"{\"workspace_id\":\"list-empty\"}"}}},{"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":7,"callId":"list-7","name":"list_session","arguments":"{\"workspace_id\":\"list-empty\"}"}} +{"type":"tool/result","data":{"turn":1,"step":7,"message":{"role":"tool","source":{"kind":"tool","callId":"list-7"},"toolCallId":"list-7","content":[{"type":"text","text":"[]"}],"isError":false,"id":"{{message:17}}"}},"sourceEventSeqs":[44],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":7}} +{"type":"step/start","data":{"turn":1,"step":8}} +{"type":"assistant/message","data":{"turn":1,"step":8,"message":{"role":"assistant","content":[{"type":"tool-call","id":"list-8","name":"list_workspace","arguments":"{\"offset\":10}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:18}}"},"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":"list-8","name":"list_workspace","arguments":"{\"offset\":10}"}}},{"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":8,"callId":"list-8","name":"list_workspace","arguments":"{\"offset\":10}"}} +{"type":"tool/result","data":{"turn":1,"step":8,"message":{"role":"tool","source":{"kind":"tool","callId":"list-8"},"toolCallId":"list-8","content":[{"type":"text","text":"[]"}],"isError":false,"id":"{{message:19}}"}},"sourceEventSeqs":[49],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":8}} +{"type":"step/start","data":{"turn":1,"step":9}} +{"type":"assistant/message","data":{"turn":1,"step":9,"message":{"role":"assistant","content":[{"type":"text","text":"SESSION_LIST_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:20}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"SESSION_LIST_OK"}}},{"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":9}} +{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/snapshots/session/session-list-tools/snapshot.yml b/snapshots/session/session-list-tools/snapshot.yml new file mode 100644 index 0000000000..a1d5d12a41 --- /dev/null +++ b/snapshots/session/session-list-tools/snapshot.yml @@ -0,0 +1,9 @@ +version: 1 +scenario: session-list-tools +profile: headless +composition: session-list-tools +recording: authored +header: + class: session-list-tools + pin: true + systemPromptSource: text-turn diff --git a/snapshots/session/session-list-tools/tool-schemas.expected.json b/snapshots/session/session-list-tools/tool-schemas.expected.json new file mode 100644 index 0000000000..0cc0d307b3 --- /dev/null +++ b/snapshots/session/session-list-tools/tool-schemas.expected.json @@ -0,0 +1,689 @@ +{ + "initial": [ + { + "name": "apply_patch", + "description": "Create, update, delete, or move UTF-8 text files with one patch; prefer it over multiple edit calls when a change spans several files or separated regions.", + "parameters": { + "type": "object", + "properties": { + "input": { + "type": "string", + "description": "Patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory." + }, + "sandbox_permissions": { + "type": "string", + "description": "The narrowest wider sandbox mode for a one-shot retry of the exact operation the sandbox just denied; the retry asks the user for approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access. Use the language of the user’s current request." + } + }, + "required": [ + "input" + ] + } + }, + { + "name": "bash", + "description": "Execute a bash command (`bash -c`) and return its stdout/stderr. Each call runs in a fresh shell; pass `workdir` instead of using `cd`. Managed `$DSH_*` variables expose current harness environment facts. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. Provide `description` before `command` in the arguments. Before any delete or move, verify that the resolved absolute target path is the intended one; never run it against a computed path you have not checked. An unset variable expands to an empty string, so guard variables in such paths with `${VAR:?}`. Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under mode]`, a policy denial: do not retry another way.", + "parameters": { + "type": "object", + "properties": { + "description": { + "type": "string", + "description": "Clear, concise description of what this command does in active voice, 5-10 words (shown in the UI). Examples: \"ls\" → \"List files in current directory\"; \"git status\" → \"Show working tree status\"; \"npm install\" → \"Install package dependencies\"." + }, + "command": { + "type": "string", + "description": "The bash command to execute." + }, + "timeoutMs": { + "type": "number", + "description": "Timeout in milliseconds. The executor applies its configured default and cap; on expiry the command moves to the background as a job instead of being killed." + }, + "workdir": { + "type": "string", + "description": "Working directory for this command. Defaults to the session workspace; a relative path is resolved against it." + }, + "run_in_background": { + "type": "boolean", + "description": "Run in the background and return a job id immediately (collect with job_output, stop with job_kill). No timeout applies." + }, + "sandbox_permissions": { + "type": "string", + "description": "The narrowest wider sandbox mode for a one-shot retry of the exact command the sandbox just denied; the retry asks the user for approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact command needs the wider access. Use the language of the user’s current request." + } + }, + "required": [ + "description", + "command" + ] + } + }, + { + "name": "create_goal", + "description": "Create a persisted goal that keeps this session working across automatic continuation rounds. Use it when the direct human request is a long-running objective, even if the user did not say \"goal\"; not for single-turn work.", + "parameters": { + "type": "object", + "properties": { + "objective": { + "type": "string", + "description": "The concrete completion objective inferred from the direct human request." + }, + "max_goal_rounds": { + "type": "number", + "description": "Optional positive safe-integer limit on automatic continuation rounds." + } + }, + "required": [ + "objective" + ] + } + }, + { + "name": "edit", + "description": "Edit an existing UTF-8 text file by replacing literal text.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to edit, resolved by the filesystem backend. Provide `file_path` before `old_string` and `new_string` in the arguments." + }, + "old_string": { + "type": "string", + "description": "Literal text to replace." + }, + "new_string": { + "type": "string", + "description": "Literal replacement text. Use an empty string to delete the match." + }, + "replace_all": { + "type": "boolean", + "description": "Replace all matches. Defaults to false; when false, old_string must appear exactly once." + }, + "sandbox_permissions": { + "type": "string", + "description": "The narrowest wider sandbox mode for a one-shot retry of the exact operation the sandbox just denied; the retry asks the user for approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access. Use the language of the user’s current request." + } + }, + "required": [ + "file_path", + "old_string", + "new_string" + ] + } + }, + { + "name": "get_goal", + "description": "Read the current session goal, including the id and revision that update_goal requires.", + "parameters": { + "type": "object", + "properties": {} + } + }, + { + "name": "glob", + "description": "Find files, not directories, whose paths match a glob pattern, including hidden and ignored files. Returns up to 100 paths in modification-time order; a larger result keeps the first paths and reports where the complete list was saved.", + "parameters": { + "type": "object", + "properties": { + "pattern": { + "type": "string", + "description": "Glob pattern to match file paths against (e.g. \"**/*.ts\", \"src/**/*.test.js\"). A pattern with no \"/\" matches the basename at any depth, so \"*\" and \"*.ts\" both search the whole tree; include a separator to anchor the depth." + }, + "path": { + "type": "string", + "description": "Directory to search in. Defaults to the session workspace; a relative path resolves against it." + } + }, + "required": [ + "pattern" + ] + } + }, + { + "name": "grep", + "description": "Search file contents with a ripgrep regular expression. Returns matching lines with line numbers, grouped by file. Returns up to 250 matches; a larger result reports where the complete match list was saved.", + "parameters": { + "type": "object", + "properties": { + "pattern": { + "type": "string", + "description": "Regular expression to search for (ripgrep syntax)." + }, + "path": { + "type": "string", + "description": "File or directory to search. Defaults to the session workspace; a relative path resolves against it." + }, + "include": { + "type": "string", + "description": "One glob filter for which files to search (e.g. \"*.ts\", \"*.{js,jsx}\"). Not a list; negation is not supported." + } + }, + "required": [ + "pattern" + ] + } + }, + { + "name": "job_kill", + "description": "Request cancellation of a running background job.", + "parameters": { + "type": "object", + "properties": { + "job_id": { + "type": "string", + "description": "Job id returned by the tool that started the background work." + }, + "reason": { + "type": "string", + "description": "Optional short reason, recorded in the log and forwarded to the job." + } + }, + "required": [ + "job_id" + ] + } + }, + { + "name": "job_list", + "description": "List your background jobs (running and finished) with their ids, kinds, and statuses.", + "parameters": { + "type": "object", + "properties": {} + } + }, + { + "name": "job_output", + "description": "Read a background job: output since the previous read for stream jobs, or the result of a finished final-output job.", + "parameters": { + "type": "object", + "properties": { + "job_id": { + "type": "string", + "description": "Job id returned by the tool that started the background work." + }, + "wait": { + "type": "boolean", + "description": "Block until the job finishes or the timeout expires; a timed-out wait leaves the job running. Defaults to false." + }, + "timeout_ms": { + "type": "number", + "description": "Max wait in milliseconds with wait: true. Defaults to and is capped by configuration." + } + }, + "required": [ + "job_id" + ] + } + }, + { + "name": "list_agents", + "description": "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.", + "parameters": { + "type": "object", + "properties": {} + } + }, + { + "name": "list_session", + "description": "List sessions by latest human prompt time, newest first, then by ID. Returns IDs, available titles, and ISO creation and update times. Missing activity metadata uses creation time; unavailable titles are null.", + "parameters": { + "type": "object", + "properties": { + "workspace_id": { + "type": "string", + "description": "Workspace ID from list_workspace. Includes its members and, when requested, subagents belonging through their nearest member ancestor. Omit to list all accessible sessions." + }, + "contain_subagent": { + "type": "boolean", + "description": "Include subagent sessions. Defaults to false." + }, + "archived": { + "type": "boolean", + "description": "Return only archived sessions when true, otherwise only unarchived sessions. Defaults to false." + }, + "limit": { + "type": "integer", + "description": "Maximum entries to return, from 1 to 100. Defaults to 20." + }, + "offset": { + "type": "integer", + "description": "Number of matching entries to skip. Defaults to 0." + } + } + } + }, + { + "name": "list_workspace", + "description": "List workspaces in registry order, including empty workspaces. Returns IDs, titles, paths, and creation and update times.", + "parameters": { + "type": "object", + "properties": { + "limit": { + "type": "integer", + "description": "Maximum entries to return, from 1 to 100. Defaults to 20." + }, + "offset": { + "type": "integer", + "description": "Number of matching entries to skip. Defaults to 0." + } + } + } + }, + { + "name": "read", + "description": "Read a UTF-8 text file and return line-numbered content.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to read, resolved by the filesystem backend." + }, + "offset": { + "type": "number", + "description": "1-based first line to return. Defaults to 1." + }, + "limit": { + "type": "number", + "description": "Maximum number of lines to return. Defaults to 2000." + } + }, + "required": [ + "file_path" + ] + } + }, + { + "name": "read_image", + "description": "Read a PNG/JPEG/WebP/GIF file and return the image itself. Large images are downscaled automatically; do not install image libraries or create thumbnails to inspect an image.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to the image file, resolved by the filesystem backend." + } + }, + "required": [ + "file_path" + ] + } + }, + { + "name": "send_message", + "description": "Send a message to an agent. A working agent receives it at its next step; an idle agent starts a new turn with it. Returns delivery confirmation.", + "parameters": { + "type": "object", + "properties": { + "agent": { + "type": "string", + "description": "The name of another agent in your subagent tree, as shown by list_agents." + }, + "message": { + "type": "string", + "description": "The message to deliver to the agent." + } + }, + "required": [ + "agent", + "message" + ] + } + }, + { + "name": "skill", + "description": "Load the full instructions for a skill. Call it before acting on a task that names or clearly matches a skill in the session skill catalog.", + "parameters": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The exact skill name from the available skills list." + } + }, + "required": [ + "name" + ] + } + }, + { + "name": "subagent", + "description": "Delegate a self-contained task to a subagent (a separate agent that works in its own context) to offload focused, independent work — research, a scoped implementation, an analysis — so it does not consume this conversation's context. The subagent returns its result, not its intermediate steps. This tool starts an independently managed subagent and immediately returns its name. If you are still online when it finishes, the runtime automatically delivers its completion notice. The notice includes the final answer unless the child sent you a message just before finishing. Use `send_message` to steer it while running or continue its conversation after it finishes.", + "parameters": { + "type": "object", + "properties": { + "cwd": { + "type": "string", + "description": "Initial child working directory. Relative paths use your current directory; omitted inherits it. Later directory changes in either agent are independent." + }, + "description": { + "type": "string", + "description": "A short (3-5 word) description of the delegated task, for display. Use the language of the user's current request." + }, + "name": { + "type": "string", + "description": "Optional short name for the subagent, unique among the subagents you create: lower-case letters, digits, and hyphens, starting with a letter, at most 32 characters; lead is reserved for the root agent. Omitted names default to agent-1, agent-2, and so on." + }, + "prompt": { + "type": "string", + "description": "The complete, self-contained task for the subagent. It does not share this conversation's context, so include everything it needs." + } + }, + "required": [ + "description", + "prompt" + ] + } + }, + { + "name": "subagent_fork", + "description": "Delegate a task to a subagent that inherits this conversation: a child agent seeded with all completed turns so far (it does not see the current in-flight turn). Use this when the subtask builds on this conversation's context — a follow-up analysis, a review, a continuation — without consuming this conversation's context for the work itself. You receive its result, not its intermediate steps. This tool starts an independently managed subagent and immediately returns its name. If you are still online when it finishes, the runtime automatically delivers its completion notice. The notice includes the final answer unless the child sent you a message just before finishing. Use `send_message` to steer it while running or continue its conversation after it finishes.", + "parameters": { + "type": "object", + "properties": { + "cwd": { + "type": "string", + "description": "Initial child working directory. Relative paths use your current directory; omitted inherits it. Later directory changes in either agent are independent." + }, + "description": { + "type": "string", + "description": "A short (3-5 word) description of the delegated task, for display. Use the language of the user's current request." + }, + "name": { + "type": "string", + "description": "Optional short name for the subagent, unique among the subagents you create: lower-case letters, digits, and hyphens, starting with a letter, at most 32 characters; lead is reserved for the root agent. Omitted names default to agent-1, agent-2, and so on." + }, + "prompt": { + "type": "string", + "description": "The task for the subagent. It already sees this conversation's completed turns, so build on them freely and state only what is new." + } + }, + "required": [ + "description", + "prompt" + ] + } + }, + { + "name": "todo_write", + "description": "Record and update a task list to plan multi-step work and show progress; skip it for trivial single-step tasks. Add one todo per concrete step before you start. While work remains, keep the todos being worked on `in_progress`, several only when work runs in parallel. Mark each todo `completed` as soon as it is done.", + "parameters": { + "type": "object", + "properties": { + "todos": { + "type": "array", + "description": "The COMPLETE task list, replacing any previous list.", + "items": { + "type": "object", + "additionalProperties": false, + "properties": { + "content": { + "type": "string", + "description": "What the task is — a short imperative line." + }, + "status": { + "type": "string", + "description": "pending (not started) | in_progress (now) | completed (done).", + "enum": [ + "pending", + "in_progress", + "completed" + ] + } + }, + "required": [ + "content", + "status" + ] + } + } + }, + "required": [ + "todos" + ] + } + }, + { + "name": "update_goal", + "description": "Update the current goal.", + "parameters": { + "type": "object", + "properties": { + "goal_id": { + "type": "string", + "description": "Exact id returned by get_goal." + }, + "revision": { + "type": "number", + "description": "Exact positive revision returned by get_goal." + }, + "action": { + "type": "string", + "description": "edit, pause, and resume require a direct top-level human request. complete and blocked are also allowed during an automatic continuation of this goal; blocked is rejected before the configured minimum round count.", + "enum": [ + "edit", + "pause", + "resume", + "complete", + "blocked" + ] + }, + "objective": { + "type": "string", + "description": "Replacement objective; valid only with action edit." + }, + "max_goal_rounds": { + "type": "number", + "description": "Replacement cap; valid only with action edit." + }, + "blocked_reason": { + "type": "string", + "description": "Required only with action blocked: the concrete condition that persisted across rounds and blocks progress." + } + }, + "required": [ + "goal_id", + "revision", + "action" + ] + } + }, + { + "name": "wait_agent", + "description": "Wait for input at your next step, including agent messages, completion notifications, and user steering. Returns immediately if new input is pending. `timedOut: false` means new input is pending. Pending input is delivered to the model after code execution finishes.", + "parameters": { + "type": "object", + "properties": { + "timeout_ms": { + "type": "integer", + "description": "Wait duration in milliseconds, from 10000 through 3600000. Defaults to 30000." + } + } + } + }, + { + "name": "web_fetch", + "description": "Fetch the content of a specific HTTP(S) URL and return it decoded to text.", + "parameters": { + "type": "object", + "properties": { + "url": { + "type": "string", + "description": "The HTTP(S) URL to fetch." + } + }, + "required": [ + "url" + ] + } + }, + { + "name": "web_search", + "description": "Search the web for current information. Returns an optional summary answer and a list of source URLs.", + "parameters": { + "type": "object", + "properties": { + "queries": { + "type": "array", + "description": "1–10 search queries; their results are merged.", + "items": { + "type": "string" + } + } + }, + "required": [ + "queries" + ] + } + }, + { + "name": "workflow", + "description": "Run a JavaScript workflow script that orchestrates subagents at scale. Use this for work that fans out across many independent pieces — an audit over many files, a migration, multi-angle research, adversarial verification of findings — where you write the orchestration as a script instead of delegating turn by turn.\n\nScript-body hooks:\n- `agent(prompt, opts?): Promise` — run one subagent to completion. Without `opts.schema` it resolves to the child's final text; with `opts.schema` (an object-rooted JSON Schema using ONLY type/properties/required/additionalProperties/items/enum/const/oneOf) it resolves to the validated object. Resolves `null` when the child fails (filter with `.filter(Boolean)`). Other opts: `label` (display), `phase` (progress group), and independent `provider`/`model` LLM target overrides.\n- `pipeline(items, ...stages): Promise` — run each item through the stages independently with NO barrier between stages (prefer this for multi-stage work). Each stage receives `(prev, item, index)`. A stage throw drops that ITEM to `null` and skips its remaining stages.\n- `parallel(thunks): Promise` — run zero-argument functions concurrently and await ALL of them (a barrier; use only when a stage genuinely needs every prior result together). A throwing thunk resolves to `null`.\n- `phase(title)` — start a progress phase; `log(message)` — narrate progress; `args` — the tool call's `args` input, verbatim.\n\nMisused hooks (bad arguments, unknown options, unsupported schemas, tripped caps) end the whole script instead of producing `null`. The script has no filesystem, network, timer, or Node.js APIs; the agents do the work.", + "parameters": { + "type": "object", + "properties": { + "script": { + "type": "string", + "description": "The plain JavaScript body, not TypeScript and without an `export const meta` statement; top-level await is allowed. End with `return `; the JSON-serializable value is this tool's result." + }, + "meta": { + "type": "object", + "description": "The workflow identity as plain JSON, not code.", + "additionalProperties": true, + "properties": { + "name": { + "type": "string", + "description": "Short kebab-case workflow name." + }, + "description": { + "type": "string", + "description": "One-line description of what the workflow does." + }, + "whenToUse": { + "type": "string", + "description": "Optional guidance on when this workflow applies." + }, + "phases": { + "type": "array", + "description": "Optional phase declarations matched by phase() calls.", + "items": { + "type": "object", + "additionalProperties": true, + "properties": { + "title": { + "type": "string", + "description": "The phase title phase() calls match by exact string." + }, + "detail": { + "type": "string", + "description": "Optional one-line description of the phase." + }, + "provider": { + "type": "string", + "description": "Optional provider override this phase is expected to use." + }, + "model": { + "type": "string", + "description": "Optional model override this phase is expected to use." + } + }, + "required": [ + "title" + ] + } + } + }, + "required": [ + "name", + "description" + ] + }, + "args": { + "type": "object", + "description": "Optional JSON input exposed to the script as the `args` global (wrap a bare list as a field, e.g. {\"files\": [...]}).", + "additionalProperties": true + }, + "run_in_background": { + "type": "boolean", + "description": "Run as a background job: return a job id immediately instead of waiting; the return value arrives with the completion notice." + } + }, + "required": [ + "script", + "meta" + ] + } + }, + { + "name": "working_directory", + "description": "Read the current working directory, or change it with cd. Relative paths use the current directory. Existing shells and running processes keep their own directories.", + "parameters": { + "type": "object", + "properties": { + "cd": { + "type": "string", + "description": "Existing directory to enter. Omit to read the current directory." + } + } + } + }, + { + "name": "write", + "description": "Create or fully replace a UTF-8 text file.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to write, resolved by the filesystem backend. Provide `file_path` before `content` in the arguments." + }, + "content": { + "type": "string", + "description": "Full UTF-8 text content to write." + }, + "sandbox_permissions": { + "type": "string", + "description": "The narrowest wider sandbox mode for a one-shot retry of the exact operation the sandbox just denied; the retry asks the user for approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access. Use the language of the user’s current request." + } + }, + "required": [ + "file_path", + "content" + ] + } + } + ], + "changes": [] +} diff --git a/tsconfig.base.json b/tsconfig.base.json index e8ca4f8e44..946b230483 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -169,6 +169,7 @@ "@deepseek-ai/dsh-session/chunk-rows": ["./packages/core/session/src/chunk-rows.ts"], "@deepseek-ai/dsh-session/surface": ["./packages/core/session/src/surface.ts"], "@deepseek-ai/dsh-session/fork": ["./packages/core/session/src/fork.ts"], + "@deepseek-ai/dsh-session-query/types": ["./packages/session-query/session-query/src/types.ts"], "@deepseek-ai/dsh-session-projection/types": ["./packages/session/session-projection/src/types.ts"], "@deepseek-ai/dsh-tool-todo/types": ["./packages/todo/tool-todo/src/types.ts"], "@deepseek-ai/dsh-tool-todo/client": ["./packages/todo/tool-todo/src/client.ts"], @@ -597,6 +598,7 @@ "@deepseek-ai/dsh-tool-pwsh-persistent": ["./packages/shell/tool-pwsh-persistent/src"], "@deepseek-ai/dsh-tool-ralph": ["./packages/experimental/tool-ralph/src"], "@deepseek-ai/dsh-tool-schedule": ["./packages/schedule/tool-schedule/src"], + "@deepseek-ai/dsh-tool-session-list": ["./packages/session-query/tool-session-list/src"], "@deepseek-ai/dsh-tool-session-query": ["./packages/experimental/tool-session-query/src"], "@deepseek-ai/dsh-tool-skill": ["./packages/skill/tool-skill/src"], "@deepseek-ai/dsh-tool-str-replace-editor": ["./packages/fs/tool-str-replace-editor/src"], diff --git a/tsconfig.host.json b/tsconfig.host.json index 21ad8213c5..b8fa7559c2 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -424,6 +424,7 @@ { "path": "./packages/experimental/forge-bundle" }, { "path": "./packages/experimental/client-ui-forge/tsconfig.host.json" }, { "path": "./packages/session/tool-working-directory" }, + { "path": "./packages/session-query/tool-session-list" }, { "path": "./packages/session/session-title-llm" }, { "path": "./packages/session/session-title-first-prompt-llm" }, { "path": "./packages/experimental/session-title-all-prompts-llm" }, From 140547ca1f712a49d1dfd951c283891fbd37a0c7 Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Tue, 10 Nov 2026 16:15:56 +0800 Subject: [PATCH 08/31] docs: regenerate module graph for session list tools --- docs/module-graph.md | 9 +++++++++ docs/module-graph.zh.md | 9 +++++++++ 2 files changed, 18 insertions(+) diff --git a/docs/module-graph.md b/docs/module-graph.md index 7b28621265..fa4bd77035 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -111,6 +111,7 @@ flowchart TD pkg_session_log_export["session-log-export"] pkg_session_query["session-query"] pkg_session_query_sqlite["session-query-sqlite"] + pkg_tool_session_list["tool-session-list"] end subgraph group_acp["packages/acp"] pkg_acp["acp"] @@ -1247,6 +1248,13 @@ flowchart TD pkg_session_query_sqlite --> pkg_session pkg_session_query_sqlite --> pkg_session_persistence pkg_session_query_sqlite --> pkg_session_query + pkg_tool_session_list --> pkg_session + pkg_tool_session_list --> pkg_session_projection + pkg_tool_session_list --> pkg_session_projection_cache + pkg_tool_session_list --> pkg_session_query + pkg_tool_session_list --> pkg_session_title + pkg_tool_session_list --> pkg_tools + pkg_tool_session_list --> pkg_workspace pkg_acp --> pkg_agent pkg_acp --> pkg_attachment pkg_acp --> pkg_llm @@ -1882,6 +1890,7 @@ flowchart TD | [`subagent`](../packages/subagent/subagent) | `subagent` | [`agent`](../packages/core/agent), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`attachment`](../packages/attachment/attachment), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-query`](../packages/session-query/session-query), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval), [`util-time`](../packages/util/time), [`working-directory`](../packages/session/working-directory), [`workspace`](../packages/workspace/workspace) | | [`spill-policy`](../packages/spill/spill-policy) | `spill` | [`attachment`](../packages/attachment/attachment), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`session`](../packages/core/session), [`spill`](../packages/spill/spill), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools) | | [`session-query-sqlite`](../packages/session-query/session-query-sqlite) | `session-query` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-query`](../packages/session-query/session-query) | +| [`tool-session-list`](../packages/session-query/tool-session-list) | `session-query` | [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`session-title`](../packages/session/session-title), [`tools`](../packages/core/tools), [`workspace`](../packages/workspace/workspace) | | [`acp`](../packages/acp/acp) | `acp` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`llm`](../packages/llm/llm), [`mcp-client`](../packages/mcp/mcp-client), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`token-meter`](../packages/llm/token-meter), [`user-approval`](../packages/interaction/user-approval) | | [`plugin-manager`](../packages/boot/plugin-manager) | `boot` | [`brand`](../packages/util/brand), [`hmr`](../packages/boot/hmr), [`host-plugin-inventory`](../packages/host/plugin-inventory), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval) | | [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner) | `compaction` | [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`token-meter`](../packages/llm/token-meter) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index 4ddd93c256..99329ee2ab 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -113,6 +113,7 @@ flowchart TD pkg_session_log_export["session-log-export"] pkg_session_query["session-query"] pkg_session_query_sqlite["session-query-sqlite"] + pkg_tool_session_list["tool-session-list"] end subgraph group_acp["packages/acp"] pkg_acp["acp"] @@ -1249,6 +1250,13 @@ flowchart TD pkg_session_query_sqlite --> pkg_session pkg_session_query_sqlite --> pkg_session_persistence pkg_session_query_sqlite --> pkg_session_query + pkg_tool_session_list --> pkg_session + pkg_tool_session_list --> pkg_session_projection + pkg_tool_session_list --> pkg_session_projection_cache + pkg_tool_session_list --> pkg_session_query + pkg_tool_session_list --> pkg_session_title + pkg_tool_session_list --> pkg_tools + pkg_tool_session_list --> pkg_workspace pkg_acp --> pkg_agent pkg_acp --> pkg_attachment pkg_acp --> pkg_llm @@ -1884,6 +1892,7 @@ flowchart TD | [`subagent`](../packages/subagent/subagent) | `subagent` | [`agent`](../packages/core/agent), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`attachment`](../packages/attachment/attachment), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-query`](../packages/session-query/session-query), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval), [`util-time`](../packages/util/time), [`working-directory`](../packages/session/working-directory), [`workspace`](../packages/workspace/workspace) | | [`spill-policy`](../packages/spill/spill-policy) | `spill` | [`attachment`](../packages/attachment/attachment), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`session`](../packages/core/session), [`spill`](../packages/spill/spill), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools) | | [`session-query-sqlite`](../packages/session-query/session-query-sqlite) | `session-query` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-query`](../packages/session-query/session-query) | +| [`tool-session-list`](../packages/session-query/tool-session-list) | `session-query` | [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`session-title`](../packages/session/session-title), [`tools`](../packages/core/tools), [`workspace`](../packages/workspace/workspace) | | [`acp`](../packages/acp/acp) | `acp` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`llm`](../packages/llm/llm), [`mcp-client`](../packages/mcp/mcp-client), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`token-meter`](../packages/llm/token-meter), [`user-approval`](../packages/interaction/user-approval) | | [`plugin-manager`](../packages/boot/plugin-manager) | `boot` | [`brand`](../packages/util/brand), [`hmr`](../packages/boot/hmr), [`host-plugin-inventory`](../packages/host/plugin-inventory), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval) | | [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner) | `compaction` | [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`token-meter`](../packages/llm/token-meter) | From e8273f64667582a90fcfc5c29d4ac4e0cbcb2967 Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Tue, 10 Nov 2026 16:24:56 +0800 Subject: [PATCH 09/31] test(tools): include session list tools in catalog roster --- packages/core/tools/tests/gen-tool-catalog.spec.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/core/tools/tests/gen-tool-catalog.spec.ts b/packages/core/tools/tests/gen-tool-catalog.spec.ts index b9fe22584c..6df6ce6c3e 100644 --- a/packages/core/tools/tests/gen-tool-catalog.spec.ts +++ b/packages/core/tools/tests/gen-tool-catalog.spec.ts @@ -31,8 +31,8 @@ describe('gen-tool-catalog collectToolCatalog', () => { 'cordis_inspect_query', 'create_goal', 'create_worktree', 'edit', 'exit_plan_mode', 'get_goal', 'glob', 'grep', 'interrupt_agent', 'job_kill', 'job_list', 'job_output', - 'list_agents', 'list_mcp_resource_templates', 'list_mcp_resources', - 'list_subagent_models', 'load_workspace_dependencies', 'lsp', 'office_convert', 'office_recalculate', 'office_render', 'plugin_manager', 'plugin_market', 'present', 'propose_action', 'pwsh', 'pwsh', 'ralph', + 'list_agents', 'list_mcp_resource_templates', 'list_mcp_resources', 'list_session', + 'list_subagent_models', 'list_workspace', 'load_workspace_dependencies', 'lsp', 'office_convert', 'office_recalculate', 'office_render', 'plugin_manager', 'plugin_market', 'present', 'propose_action', 'pwsh', 'pwsh', 'ralph', 'read', 'read_image', 'read_mcp_resource', 'run_code', 'schedule_create', 'schedule_edit', 'schedule_list', 'schedule_view', 'send_message', 'session_event_read', 'session_event_search', 'session_event_trace', 'session_search', 'session_trace', 'skill', From c0037256e01e7b6608ac16a6c528c154daa0d46f Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Tue, 10 Nov 2026 17:09:37 +0800 Subject: [PATCH 10/31] refactor(session): remove list tool work slicing --- docs/config-catalog.md | 18 +--- docs/config-catalog.zh.md | 18 +--- .../skills/dsh-doc/references/packages.md | 2 +- .../tool-session-list/README.i18n.yaml | 12 +-- .../session-query/tool-session-list/README.md | 8 +- .../tool-session-list/README.zh.md | 8 +- .../tool-session-list/package.json | 3 - .../tool-session-list/src/index.ts | 21 +--- .../tool-session-list/src/list.ts | 10 -- .../tests/tool-session-list.spec.ts | 102 +----------------- pnpm-lock.yaml | 4 - 11 files changed, 16 insertions(+), 190 deletions(-) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 48be42f926..13a56ed8cc 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -4482,23 +4482,6 @@ export interface Config { ``` - - - -## `@deepseek-ai/dsh-tool-session-list` - -- `inject`: `tools` · `sessions` · `sessionQuery` · `workspaceRegistry` · `sessionProjections` -- `source`: [`packages/session-query/tool-session-list/src/index.ts:18`](../packages/session-query/tool-session-list/src/index.ts) - -```ts config-catalog -/** Deployment-owned responsiveness for large Session lists. */ -export interface Config { - /** Positive integral work slice in milliseconds; defaults to 16. Checked between complete rows. */ - readonly listWorkSliceMs?: number -} -``` - - @@ -5182,6 +5165,7 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co | `@deepseek-ai/dsh-tool-cordis` | `tools` · `cordisInspect` | [`packages/extensions/tool-cordis/src/index.ts`](../packages/extensions/tool-cordis/src/index.ts) | | `@deepseek-ai/dsh-tool-executor-native` | `tools` | [`packages/core/tool-executor-native/src/index.ts`](../packages/core/tool-executor-native/src/index.ts) | | `@deepseek-ai/dsh-tool-schedule` | `tools` · `systemPrompt` | [`packages/schedule/tool-schedule/src/index.ts`](../packages/schedule/tool-schedule/src/index.ts) | +| `@deepseek-ai/dsh-tool-session-list` | `tools` · `sessions` · `sessionQuery` · `workspaceRegistry` · `sessionProjections` | [`packages/session-query/tool-session-list/src/index.ts`](../packages/session-query/tool-session-list/src/index.ts) | | `@deepseek-ai/dsh-tool-working-directory` | `tools` · `workingDirectory` | [`packages/session/tool-working-directory/src/index.ts`](../packages/session/tool-working-directory/src/index.ts) | | `@deepseek-ai/dsh-tools` | `systemPrompt` | [`packages/core/tools/src/index.ts`](../packages/core/tools/src/index.ts) | | `@deepseek-ai/dsh-user-questions` | — | [`packages/interaction/user-questions/src/index.ts`](../packages/interaction/user-questions/src/index.ts) | diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 77d249aa80..11fc3b912d 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -4484,23 +4484,6 @@ export interface Config { ``` - - - -## `@deepseek-ai/dsh-tool-session-list` - -- `inject`: `tools` · `sessions` · `sessionQuery` · `workspaceRegistry` · `sessionProjections` -- `source`: [`packages/session-query/tool-session-list/src/index.ts:18`](../packages/session-query/tool-session-list/src/index.ts) - -```ts config-catalog -/** Deployment-owned responsiveness for large Session lists. */ -export interface Config { - /** Positive integral work slice in milliseconds; defaults to 16. Checked between complete rows. */ - readonly listWorkSliceMs?: number -} -``` - - @@ -5184,6 +5167,7 @@ export interface Config { | `@deepseek-ai/dsh-tool-cordis` | `tools` · `cordisInspect` | [`packages/extensions/tool-cordis/src/index.ts`](../packages/extensions/tool-cordis/src/index.ts) | | `@deepseek-ai/dsh-tool-executor-native` | `tools` | [`packages/core/tool-executor-native/src/index.ts`](../packages/core/tool-executor-native/src/index.ts) | | `@deepseek-ai/dsh-tool-schedule` | `tools` · `systemPrompt` | [`packages/schedule/tool-schedule/src/index.ts`](../packages/schedule/tool-schedule/src/index.ts) | +| `@deepseek-ai/dsh-tool-session-list` | `tools` · `sessions` · `sessionQuery` · `workspaceRegistry` · `sessionProjections` | [`packages/session-query/tool-session-list/src/index.ts`](../packages/session-query/tool-session-list/src/index.ts) | | `@deepseek-ai/dsh-tool-working-directory` | `tools` · `workingDirectory` | [`packages/session/tool-working-directory/src/index.ts`](../packages/session/tool-working-directory/src/index.ts) | | `@deepseek-ai/dsh-tools` | `systemPrompt` | [`packages/core/tools/src/index.ts`](../packages/core/tools/src/index.ts) | | `@deepseek-ai/dsh-user-questions` | — | [`packages/interaction/user-questions/src/index.ts`](../packages/interaction/user-questions/src/index.ts) | 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 9651f13643..54f7843405 100644 --- a/packages/preset/agent-preset/skills/dsh-doc/references/packages.md +++ b/packages/preset/agent-preset/skills/dsh-doc/references/packages.md @@ -403,7 +403,7 @@ Every package below exports a Cordis plugin that a bundle patch can name in a Lo |---|---|---| | `@deepseek-ai/dsh-session-log-export` | yes | Web Session-log ZIP export and Session Markdown copy | | `@deepseek-ai/dsh-session-query-sqlite` | yes | Concrete ctx.sessionQuery backend with SQLite FTS5 search | -| `@deepseek-ai/dsh-tool-session-list` | yes | Read-only paginated Workspace and Session metadata tools | +| `@deepseek-ai/dsh-tool-session-list` | no | Read-only paginated Workspace and Session metadata tools | ## settings diff --git a/packages/session-query/tool-session-list/README.i18n.yaml b/packages/session-query/tool-session-list/README.i18n.yaml index a44227e3d0..53c6e0e891 100644 --- a/packages/session-query/tool-session-list/README.i18n.yaml +++ b/packages/session-query/tool-session-list/README.i18n.yaml @@ -15,14 +15,14 @@ en: d152484eb41ac6b4 zh: 5acc0d3807846b6e /deepseek-ai-dsh-tool-session-list/use-this-package: - en: 653ca12bb7c76f9d - zh: 4dc851c44aa30eb1 + en: 388849d88b975263 + zh: df6db1e31c9bba7c /deepseek-ai-dsh-tool-session-list/use-this-package/access-and-composition: - en: efa812b2b38914ae - zh: 4d44617966d00378 + en: 0bf65fbc8660134a + zh: f4f7b3a0049d3196 /deepseek-ai-dsh-tool-session-list/use-this-package/listing-behavior: - en: 9170312b97f617fb - zh: 0e7a397ea03d6695 + en: 77a4b342a8be5311 + zh: eb166df6d600df90 /deepseek-ai-dsh-tool-session-list/use-this-package/failures: en: be4dd03d3877e2ed zh: 27c38df3c449dde9 diff --git a/packages/session-query/tool-session-list/README.md b/packages/session-query/tool-session-list/README.md index c45163b510..a8eda14d56 100644 --- a/packages/session-query/tool-session-list/README.md +++ b/packages/session-query/tool-session-list/README.md @@ -25,7 +25,7 @@ Discover workspaces and sessions without resuming an agent or reading cold conve ## Use this package -Mount this optional plugin where the intended callers receive tools. It is absent from the default profiles. +Mount this optional plugin where the intended callers receive tools. It has no configuration fields and is absent from the default profiles. ### Access and composition @@ -41,10 +41,6 @@ The plugin requires `tools`, `sessions`, `sessionQuery`, `workspaceRegistry`, an name: '@deepseek-ai/dsh-tool-session-list' ``` -| Field | Default | Meaning | -|---|---|---| -| `listWorkSliceMs` | `16` | Positive safe integer work slice in milliseconds for Session metadata reads; checked between complete rows | - When the composition already mounts `workspaceRegistry`, add only the tool row. Workspace initialization follows the [registry's existing history bootstrap](../../workspace/workspace/README.md); listing calls do not create or attach sessions or change registry records. ### Listing behavior @@ -55,7 +51,7 @@ Both tools return an array directly. The [tool catalog](../../../docs/tool-catal Session order is descending `updated_at`, then ascending Session ID for ties. Activity time is the later of creation and the latest human-authored prompt; assistant activity and title changes do not advance it. Titles come from live projections or persisted projection metadata. Unavailable titles are `null`, and unavailable activity metadata falls back to creation time. Timestamps are ISO 8601 strings. Pin order and manual sidebar order do not affect the results. -Session metadata reads yield between complete rows when the configured work slice expires and check cancellation before continuing. The slice is not a hard latency bound: it cannot split one synchronous row, query enumeration, or final sorting. The list does not promise one snapshot across all Sessions. +After header enumeration, filtering, metadata reads, and sorting run synchronously. The call does not promise prompt handling of new cancellation requests during this work or one snapshot across all Sessions. ### Failures diff --git a/packages/session-query/tool-session-list/README.zh.md b/packages/session-query/tool-session-list/README.zh.md index 54049b9d57..65492ef42b 100644 --- a/packages/session-query/tool-session-list/README.zh.md +++ b/packages/session-query/tool-session-list/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用本包 -在预期调用者获取工具的作用域中挂载此可选插件。默认配置方案不包含它。 +在预期调用者获取工具的作用域中挂载此可选插件。它没有配置字段,默认配置方案不包含它。 ### 访问范围与组合 @@ -41,10 +41,6 @@ kind: "package-reference" name: '@deepseek-ai/dsh-tool-session-list' ``` -| 字段 | 默认值 | 含义 | -|---|---|---| -| `listWorkSliceMs` | `16` | Session 元数据读取的工作时间片,单位为毫秒,必须是正安全整数;在完整条目之间检查 | - 如果组合已经挂载 `workspaceRegistry`,只添加工具条目。Workspace 初始化遵循[注册表现有的历史引导行为](../../workspace/workspace/README.zh.md);列表调用不会创建或接入会话,也不会修改注册表记录。 ### 列表行为 @@ -55,7 +51,7 @@ kind: "package-reference" 会话按 `updated_at` 降序排列,时间相同则按 Session ID 升序排列。活动时间取创建时间与最近人工提示词时间的较晚值;助手活动和标题变化不会推进它。标题来自实时投影或持久化投影元数据。标题不可用时为 `null`,活动元数据不可用时回退到创建时间。时间戳使用 ISO 8601 字符串。置顶顺序和侧边栏手动顺序不影响结果。 -Session 元数据读取在配置的工作时间片耗尽时,于完整条目之间让出执行,并在继续前检查取消。时间片不是严格的延迟上限:它无法切分单条同步读取、查询枚举或最终排序。列表不承诺所有 Session 共享同一个快照。 +header 枚举之后,筛选、元数据读取和排序同步执行。调用不承诺在这段工作中及时处理新收到的取消请求,也不承诺所有 Session 共享同一个快照。 ### 失败 diff --git a/packages/session-query/tool-session-list/package.json b/packages/session-query/tool-session-list/package.json index 897629f33e..26ac358141 100644 --- a/packages/session-query/tool-session-list/package.json +++ b/packages/session-query/tool-session-list/package.json @@ -67,8 +67,5 @@ "@deepseek-ai/dsh-session-title": { "optional": true } - }, - "dependencies": { - "@deepseek-ai/schemastery": "workspace:~" } } diff --git a/packages/session-query/tool-session-list/src/index.ts b/packages/session-query/tool-session-list/src/index.ts index 24fb9b3825..f3e2ed47c7 100644 --- a/packages/session-query/tool-session-list/src/index.ts +++ b/packages/session-query/tool-session-list/src/index.ts @@ -4,7 +4,6 @@ */ import type { Context } from '@deepseek-ai/cordis' -import z from '@deepseek-ai/schemastery' import { registerSessionListMetadata } from '@deepseek-ai/dsh-session-query' import { defineTool } from '@deepseek-ai/dsh-tools' import { listSessions, listWorkspaces } from './list.ts' @@ -14,17 +13,6 @@ export const name = 'tool-session-list' /** Services needed for header-only listing and live metadata. */ export const inject = ['tools', 'sessions', 'sessionQuery', 'workspaceRegistry', 'sessionProjections'] -/** Deployment-owned responsiveness for large Session lists. */ -export interface Config { - /** Positive integral work slice in milliseconds; defaults to 16. Checked between complete rows. */ - readonly listWorkSliceMs?: number -} - -/** Loader configuration for cooperative list scheduling. */ -export const Config: z = z.object({ - listWorkSliceMs: z.number().step(1).min(1).default(16), -}) - const pagination = { limit: { type: 'integer', description: 'Maximum entries to return, from 1 to 100. Defaults to 20.' }, offset: { type: 'integer', description: 'Number of matching entries to skip. Defaults to 0.' }, @@ -33,14 +21,9 @@ const pagination = { /** * Grant tools access to all Workspace and Session metadata in this runtime. * @param ctx - scoped context granting these tools to its callers. - * @param config - deployment work-slice choice; omitted uses 16 milliseconds. * @returns when the shared list metadata projection and tools are registered. */ -export async function apply(ctx: Context, config: Config = {}): Promise { - const workSliceMs = config.listWorkSliceMs ?? 16 - if (!Number.isSafeInteger(workSliceMs) || workSliceMs < 1) { - throw new TypeError('tool-session-list: listWorkSliceMs must be a positive safe integer') - } +export async function apply(ctx: Context): Promise { const readMetadata = await registerSessionListMetadata(ctx) ctx.tools.register(defineTool({ name: 'list_workspace', @@ -93,7 +76,7 @@ export async function apply(ctx: Context, config: Config = {}): Promise { render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }], }, isConcurrencySafe: () => true, - execute: (args, exec) => listSessions(ctx, readMetadata, args, exec.signal, workSliceMs), + execute: (args, exec) => listSessions(ctx, readMetadata, args, exec.signal), presentCall: args => ({ card: 'generic', title: 'List sessions', kind: 'read', rawInput: args.workspace_id }), })) } diff --git a/packages/session-query/tool-session-list/src/list.ts b/packages/session-query/tool-session-list/src/list.ts index 1176e3db48..68fed14528 100644 --- a/packages/session-query/tool-session-list/src/list.ts +++ b/packages/session-query/tool-session-list/src/list.ts @@ -1,7 +1,5 @@ /** Header-only selection and cached metadata for the read-only listing tools. */ -import { performance } from 'node:perf_hooks' -import { scheduler } from 'node:timers/promises' import type { Context } from '@deepseek-ai/cordis' import type { Session, SessionHeader, SessionId } from '@deepseek-ai/dsh-session' import { SessionQueryError, type SessionListMetadata } from '@deepseek-ai/dsh-session-query' @@ -80,7 +78,6 @@ export function listWorkspaces(ctx: Context, input: PageInput, signal: AbortSign * @param readLiveMetadata - ready reader owned by this plugin's registration. * @param input - filters and pagination arguments. * @param signal - caller cancellation, forwarded to the corpus listing. - * @param workSliceMs - resolved positive integral work slice between complete rows. * @returns filtered Session metadata ordered by activity, then identity. */ export async function listSessions( @@ -88,7 +85,6 @@ export async function listSessions( readLiveMetadata: (session: Session) => SessionListMetadata, input: SessionListInput, signal: AbortSignal, - workSliceMs: number, ): Promise { const { limit, offset } = resolvePage(input) signal.throwIfAborted() @@ -108,14 +104,8 @@ export async function listSessions( const headers = new Map(records.map(record => [record.header.id, record.header])) const nearestWorkspace = ancestorWorkspaceReader(headers, ownership) const items = [] - let yieldDeadline = performance.now() + workSliceMs for (const { header } of records) { signal.throwIfAborted() - if (performance.now() >= yieldDeadline) { - await scheduler.yield() - signal.throwIfAborted() - yieldDeadline = performance.now() + workSliceMs - } if (!input.contain_subagent && header.origin === 'subagent') continue if (archived.has(header.id) !== (input.archived ?? false)) continue if (workspaceId !== undefined) { diff --git a/packages/session-query/tool-session-list/tests/tool-session-list.spec.ts b/packages/session-query/tool-session-list/tests/tool-session-list.spec.ts index a39534a926..87dd7fcac7 100644 --- a/packages/session-query/tool-session-list/tests/tool-session-list.spec.ts +++ b/packages/session-query/tool-session-list/tests/tool-session-list.spec.ts @@ -1,8 +1,6 @@ import { mkdir, mkdtemp, realpath, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { performance } from 'node:perf_hooks' -import { scheduler } from 'node:timers/promises' import { Context } from '@deepseek-ai/cordis' import AgentRegistry from '@deepseek-ai/dsh-agent' import { createUserMessage, ToolCallId } from '@deepseek-ai/dsh-llm' @@ -107,7 +105,6 @@ async function mount(options: { archived?: string[] cached?: Array<[string, CheckpointRecord]> cache?: boolean - config?: ToolSessionList.Config } = {}) { const workspaces = options.workspaces ?? [] const ctx = new Context() @@ -139,7 +136,7 @@ async function mount(options: { } await ctx.sessionProjections.register(titleProjectionDefinition) await ctx.plugin(ListingQuery) - const fiber = await ctx.plugin(ToolSessionList, options.config) + const fiber = await ctx.plugin(ToolSessionList) const read = vi.spyOn(ctx.sessionQuery, 'readSession') const titles = vi.spyOn(ctx.sessionQuery, 'readTitleSnapshots') const open = vi.spyOn(ctx.sessionPersistence, 'open') @@ -172,19 +169,6 @@ function prompt(session: Session) { }), { surfaceOp: 'append' }) } -function measureRows(ctx: Context, summaryMs: number) { - const clock = { now: 0 } - const trace: string[] = [] - const cachedSnapshot = ctx.sessionProjectionCache.cachedSnapshot.bind(ctx.sessionProjectionCache) - vi.spyOn(ctx.sessionProjectionCache, 'cachedSnapshot').mockImplementation((meta, keys) => { - clock.now += summaryMs - trace.push(meta.id) - return cachedSnapshot(meta, keys) - }) - vi.spyOn(performance, 'now').mockImplementation(() => clock.now) - return { clock, trace } -} - describe('read-only Session list tools', () => { it('lists empty Workspaces in registry order and applies offset after that order', async () => { const path = await directory() @@ -351,87 +335,3 @@ describe('read-only Session list tools', () => { expect(mounted.ctx.tools.get('list_session')).toBeUndefined() }) }) - -describe('Session list work slices', () => { - const headers = [header('first', 30), header('middle', 20), header('last', 10)] - - it('resolves the default and explicit work slice through Loader configuration', () => { - expect(ToolSessionList.Config({})).toEqual({ listWorkSliceMs: 16 }) - expect(ToolSessionList.Config({ listWorkSliceMs: 8 })).toEqual({ listWorkSliceMs: 8 }) - }) - - it.each([0, -1, 0.5, Number.NaN, Number.POSITIVE_INFINITY, Number.MAX_SAFE_INTEGER + 1])( - 'rejects invalid work slice %s before registering a projection or tool', async (listWorkSliceMs) => { - const ctx = new Context() - contexts.push(ctx) - await expect(ToolSessionList.apply(ctx, { listWorkSliceMs })).rejects.toThrow( - 'tool-session-list: listWorkSliceMs must be a positive safe integer', - ) - }, - ) - - it('keeps cheap metadata reads in one synchronous slice', async () => { - const mounted = await mount({ headers }) - const { trace } = measureRows(mounted.ctx, 2) - const yieldWork = vi.spyOn(scheduler, 'yield') - expect(value(await mounted.call('list_session'))).toEqual([item('first', 30), item('middle', 20), item('last', 10)]) - expect(trace).toEqual(['first', 'middle', 'last']) - expect(yieldWork).not.toHaveBeenCalled() - }) - - it.each([ - { listWorkSliceMs: undefined, summaryMs: 8 }, - { listWorkSliceMs: 8, summaryMs: 4 }, - ])('resumes after an exhausted $listWorkSliceMs slice and resets the deadline after waiting', async ({ listWorkSliceMs, summaryMs }) => { - const mounted = await mount({ headers, config: listWorkSliceMs === undefined ? {} : { listWorkSliceMs } }) - if (listWorkSliceMs === undefined) { - await mounted.fiber.dispose() - await mounted.ctx.plugin({ inject: ToolSessionList.inject, apply: (ctx: Context) => ToolSessionList.apply(ctx) }) - } - const { clock, trace } = measureRows(mounted.ctx, summaryMs) - const yieldWork = vi.spyOn(scheduler, 'yield').mockImplementation(async () => { - trace.push('yield') - clock.now += 1_000 - }) - expect(value(await mounted.call('list_session'))).toEqual([item('first', 30), item('middle', 20), item('last', 10)]) - expect(trace).toEqual(['first', 'middle', 'yield', 'last']) - expect(yieldWork).toHaveBeenCalledOnce() - }) - - it('returns the final completed row without a trailing yield', async () => { - const mounted = await mount({ headers: [header('last', 10)] }) - measureRows(mounted.ctx, 16) - const yieldWork = vi.spyOn(scheduler, 'yield') - expect(value(await mounted.call('list_session'))).toEqual([item('last', 10)]) - expect(yieldWork).not.toHaveBeenCalled() - }) - - it('checks the work slice while classifying rows that the filters exclude', async () => { - const mounted = await mount({ - headers: headers.map(meta => ({ ...meta, origin: 'subagent', parentSession: SessionId('outside') })), - }) - const cached = vi.spyOn(mounted.ctx.sessionProjectionCache, 'cachedSnapshot') - // Classification consumes the first slice even though no metadata row is read. - vi.spyOn(performance, 'now').mockReturnValueOnce(0).mockReturnValueOnce(0).mockReturnValue(16) - const yieldWork = vi.spyOn(scheduler, 'yield').mockResolvedValue() - expect(value(await mounted.call('list_session'))).toEqual([]) - expect(yieldWork).toHaveBeenCalledOnce() - expect(cached).not.toHaveBeenCalled() - expect(mounted.open).not.toHaveBeenCalled() - }) - - it('cancels at a yielded row without reading later metadata or returning a partial list', async () => { - const mounted = await mount({ headers, config: { listWorkSliceMs: 4 } }) - const { trace } = measureRows(mounted.ctx, 4) - const controller = new AbortController() - const yieldWork = vi.spyOn(scheduler, 'yield').mockImplementation(async () => { - controller.abort(new Error('stop between rows')) - }) - const result = await mounted.call('list_session', {}, controller.signal) - expect(result.error?.info).toMatchObject({ name: 'AbortError', code: 'ABORTED' }) - expect(result.value).toBeUndefined() - expect(trace).toEqual(['first']) - expect(yieldWork).toHaveBeenCalledOnce() - expect(mounted.open).not.toHaveBeenCalled() - }) -}) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f27d93d4c7..248122fec9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -14737,10 +14737,6 @@ importers: version: link:../session-query packages/session-query/tool-session-list: - dependencies: - '@deepseek-ai/schemastery': - specifier: link:../../../vendor/schemastery - version: link:../../../vendor/schemastery devDependencies: '@deepseek-ai/cordis': specifier: workspace:~ From 3895609baad1dee2d92f50ef50d5e31ac6086195 Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Wed, 11 Nov 2026 13:38:59 +0800 Subject: [PATCH 11/31] refactor(session): list Workspace sessions from member headers Drop contain_subagent from list_session: discovering subagents of a Workspace needs either a corpus scan or the parent subagent catalog, so this version lists only non-subagent sessions. A workspace_id call now reads its members' headers from the Workspace registry index through the new Workspace.sessionHeaders, so its work grows with the member count instead of enumerating every stored Session. Unscoped calls still enumerate the corpus headers. --- docs/subsystems/workspace.md | 7 +++ docs/subsystems/workspace.zh.md | 7 +++ docs/tool-catalog.i18n.yaml | 4 +- docs/tool-catalog.md | 8 +-- docs/tool-catalog.zh.md | 8 +-- .../extensions/tool-cordis/src/api-catalog.ts | 2 +- .../tool-session-list/README.i18n.yaml | 24 +++---- .../session-query/tool-session-list/README.md | 14 ++--- .../tool-session-list/README.zh.md | 14 ++--- .../tool-session-list/src/index.ts | 5 +- .../tool-session-list/src/list.ts | 63 +++++-------------- .../tests/tool-session-list.spec.ts | 51 +++++++-------- packages/workspace/workspace/README.i18n.yaml | 4 +- packages/workspace/workspace/README.md | 2 +- packages/workspace/workspace/README.zh.md | 2 +- packages/workspace/workspace/src/entity.ts | 14 ++++- packages/workspace/workspace/src/index.ts | 8 +++ packages/workspace/workspace/src/types.ts | 9 ++- .../workspace/tests/workspace.spec.ts | 2 + .../session-list-tools/session.v4.jsonl | 6 +- .../tool-schemas.expected.json | 8 +-- 21 files changed, 129 insertions(+), 133 deletions(-) diff --git a/docs/subsystems/workspace.md b/docs/subsystems/workspace.md index 046f0b9924..ba01258c94 100644 --- a/docs/subsystems/workspace.md +++ b/docs/subsystems/workspace.md @@ -63,6 +63,13 @@ interface Workspace { */ readonly sessionIds: readonly SessionId[] + /** + * Stored headers of {@link sessionIds}, in the same order. Read from the + * registry's startup and attach-time header index without persistence I/O; + * headers are immutable, so an indexed header never goes stale. + */ + readonly sessionHeaders: readonly SessionHeader[] + /** * Replace the display title durably. * @param title - New title; any string, duplicates across workspaces allowed. diff --git a/docs/subsystems/workspace.zh.md b/docs/subsystems/workspace.zh.md index 95983eb846..55b4bd531d 100644 --- a/docs/subsystems/workspace.zh.md +++ b/docs/subsystems/workspace.zh.md @@ -63,6 +63,13 @@ interface Workspace { */ readonly sessionIds: readonly SessionId[] + /** + * Stored headers of {@link sessionIds}, in the same order. Read from the + * registry's startup and attach-time header index without persistence I/O; + * headers are immutable, so an indexed header never goes stale. + */ + readonly sessionHeaders: readonly SessionHeader[] + /** * Replace the display title durably. * @param title - New title; any string, duplicates across workspaces allowed. diff --git a/docs/tool-catalog.i18n.yaml b/docs/tool-catalog.i18n.yaml index a8129d0f23..e154e39f30 100644 --- a/docs/tool-catalog.i18n.yaml +++ b/docs/tool-catalog.i18n.yaml @@ -243,8 +243,8 @@ en: 6d68942100dd76e7 zh: 6d68942100dd76e7 /tool-schema-catalog/deepseek-ai-dsh-tool-session-list/list-session: - en: fa3ac1878f21c149 - zh: dfd5759772f99d13 + en: 8a04c79a2d8ef256 + zh: 06e93b69aa95c6e9 /tool-schema-catalog/deepseek-ai-dsh-tool-session-list/list-workspace: en: 7b1f0bed364dfcd2 zh: c907d8ff78f54268 diff --git a/docs/tool-catalog.md b/docs/tool-catalog.md index 3d4070cdaf..93f4b36c3e 100644 --- a/docs/tool-catalog.md +++ b/docs/tool-catalog.md @@ -1923,7 +1923,7 @@ Source: [`packages/skill/tool-skill/src/index.ts`](../packages/skill/tool-skill/ ### `list_session` -List sessions by latest human prompt time, newest first, then by ID. Returns IDs, available titles, and ISO creation and update times. Missing activity metadata uses creation time; unavailable titles are null. +List non-subagent sessions by latest human prompt time, newest first, then by ID. Returns IDs, available titles, and ISO creation and update times. Missing activity metadata uses creation time; unavailable titles are null. ```json { @@ -1931,11 +1931,7 @@ List sessions by latest human prompt time, newest first, then by ID. Returns IDs "properties": { "workspace_id": { "type": "string", - "description": "Workspace ID from list_workspace. Includes its members and, when requested, subagents belonging through their nearest member ancestor. Omit to list all accessible sessions." - }, - "contain_subagent": { - "type": "boolean", - "description": "Include subagent sessions. Defaults to false." + "description": "Workspace ID from list_workspace. Lists only its member sessions. Omit to list sessions in every workspace and outside all workspaces." }, "archived": { "type": "boolean", diff --git a/docs/tool-catalog.zh.md b/docs/tool-catalog.zh.md index 4847ac26c1..4b91662eb7 100644 --- a/docs/tool-catalog.zh.md +++ b/docs/tool-catalog.zh.md @@ -1929,7 +1929,7 @@ lsp 工具将提供方选择和语言服务器子进程置于 ctx.lsp 之后, ### `list_session` -按最近人工提示词时间从新到旧列出会话,时间相同时按 ID 排列。返回 ID、可用标题以及 ISO 创建时间和更新时间。缺少活动元数据时使用创建时间;标题不可用时为 null。 +按最近人工提示词时间从新到旧列出非 subagent 会话,时间相同时按 ID 排列。返回 ID、可用标题以及 ISO 创建时间和更新时间。缺少活动元数据时使用创建时间;标题不可用时为 null。 ```json { @@ -1937,11 +1937,7 @@ lsp 工具将提供方选择和语言服务器子进程置于 ctx.lsp 之后, "properties": { "workspace_id": { "type": "string", - "description": "Workspace ID from list_workspace. Includes its members and, when requested, subagents belonging through their nearest member ancestor. Omit to list all accessible sessions." - }, - "contain_subagent": { - "type": "boolean", - "description": "Include subagent sessions. Defaults to false." + "description": "Workspace ID from list_workspace. Lists only its member sessions. Omit to list sessions in every workspace and outside all workspaces." }, "archived": { "type": "boolean", diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 55c63b384c..d3a55d0b3a 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -10676,7 +10676,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'Workspace', - declaration: 'export interface Workspace {\n readonly id: WorkspaceId;\n readonly path: string;\n readonly title: string;\n readonly createdAt: string;\n readonly updatedAt: string;\n readonly sessionIds: readonly SessionId[];\n setTitle(title: string): Promise;\n attachSession(sessionId: SessionId): Promise;\n insertSessionBefore(sessionId: SessionId, beforeSessionId?: SessionId): Promise;\n detachSession(sessionId: SessionId): Promise;\n status(): Promise<\'ok\' | \'missing-dir\'>;\n}', + declaration: 'export interface Workspace {\n readonly id: WorkspaceId;\n readonly path: string;\n readonly title: string;\n readonly createdAt: string;\n readonly updatedAt: string;\n readonly sessionIds: readonly SessionId[];\n readonly sessionHeaders: readonly SessionHeader[];\n setTitle(title: string): Promise;\n attachSession(sessionId: SessionId): Promise;\n insertSessionBefore(sessionId: SessionId, beforeSessionId?: SessionId): Promise;\n detachSession(sessionId: SessionId): Promise;\n status(): Promise<\'ok\' | \'missing-dir\'>;\n}', }, { name: 'WorkspaceArchiveSessionRequest', diff --git a/packages/session-query/tool-session-list/README.i18n.yaml b/packages/session-query/tool-session-list/README.i18n.yaml index 53c6e0e891..362ea0c6c0 100644 --- a/packages/session-query/tool-session-list/README.i18n.yaml +++ b/packages/session-query/tool-session-list/README.i18n.yaml @@ -9,8 +9,8 @@ en: 963f03d1ba483ea9 zh: 4809b66477752fe9 /deepseek-ai-dsh-tool-session-list/summary: - en: c643c299cff0602e - zh: a4e0d8d3cb039859 + en: e4e61ecb4f56e250 + zh: 815fd87f03e766f1 /deepseek-ai-dsh-tool-session-list/table-of-contents: en: d152484eb41ac6b4 zh: 5acc0d3807846b6e @@ -21,17 +21,17 @@ en: 0bf65fbc8660134a zh: f4f7b3a0049d3196 /deepseek-ai-dsh-tool-session-list/use-this-package/listing-behavior: - en: 77a4b342a8be5311 - zh: eb166df6d600df90 + en: bd85d03043393832 + zh: 9c57bdd92461c1e1 /deepseek-ai-dsh-tool-session-list/use-this-package/failures: - en: be4dd03d3877e2ed - zh: 27c38df3c449dde9 + en: 95ee3e3c0ecedadd + zh: 933d267402ceec74 /deepseek-ai-dsh-tool-session-list/understand-the-implementation: - en: a9a0e5d116579be4 - zh: 1b78e7f73b639f85 + en: 730fef413ce5a404 + zh: 325a5700a9edbda1 /deepseek-ai-dsh-tool-session-list/further-exploration: - en: 2a147ada18753beb - zh: d9aa75491c8fc0b7 + en: 06d8fa5cb2d63b6b + zh: 2635b93fccf3dbc9 /deepseek-ai-dsh-tool-session-list/model-experience: en: 215e7ba838619b7b zh: a311da3843709f90 @@ -48,8 +48,8 @@ en: 0e201fbbe37798d8 zh: fd4bd41e7393c234 /deepseek-ai-dsh-tool-session-list/known-limitations-and-deferred-work: - en: 103c746911f87efd - zh: 58f101c6b129c9e8 + en: f0b57c2f2e7a0984 + zh: ed80800cb0d021c8 /deepseek-ai-dsh-tool-session-list/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: e88aeb617ffb74ea diff --git a/packages/session-query/tool-session-list/README.md b/packages/session-query/tool-session-list/README.md index a8eda14d56..3a17a6f125 100644 --- a/packages/session-query/tool-session-list/README.md +++ b/packages/session-query/tool-session-list/README.md @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -Discover workspaces and sessions without resuming an agent or reading cold conversation logs. List empty workspaces, find sessions in a workspace, or include subagents and archived sessions. Results contain identifiers and lightweight metadata, with bounded page sizes. Enable these tools when callers may inspect the metadata of the whole mounted runtime. +Discover workspaces and sessions without resuming an agent or reading cold conversation logs. List empty workspaces, find sessions in a workspace, or list archived sessions. Results contain identifiers and lightweight metadata, with bounded page sizes. Enable these tools when callers may inspect the metadata of the whole mounted runtime. ## Table of Contents @@ -47,15 +47,15 @@ When the composition already mounts `workspaceRegistry`, add only the tool row. Both tools return an array directly. The [tool catalog](../../../docs/tool-catalog.md#deepseek-aidsh-tool-session-list) defines arguments. Pagination follows filtering and ordering; each call defaults to 20 entries, accepts at most 100, and starts at offset zero. Increase the offset by the number of returned entries to continue; an empty array ends the traversal. -`list_workspace` preserves registry order and includes workspaces with no sessions. `list_session` includes unarchived ordinary sessions by default, including sessions outside every Workspace when no `workspace_id` is supplied. Explicit Workspace selection uses recorded membership, not a matching working directory. With subagents included, a directly assigned Workspace wins; otherwise the nearest recorded member ancestor determines membership. Ordinary forked sessions do not inherit membership through their parents. Archival matches each Session's own ID, independently of its ancestors. +`list_workspace` preserves registry order and includes workspaces with no sessions. `list_session` never returns subagent sessions. It includes unarchived sessions by default, including sessions outside every Workspace when no `workspace_id` is supplied. Explicit Workspace selection uses recorded membership, not a matching working directory. Archival matches each Session's own ID. Session order is descending `updated_at`, then ascending Session ID for ties. Activity time is the later of creation and the latest human-authored prompt; assistant activity and title changes do not advance it. Titles come from live projections or persisted projection metadata. Unavailable titles are `null`, and unavailable activity metadata falls back to creation time. Timestamps are ISO 8601 strings. Pin order and manual sidebar order do not affect the results. -After header enumeration, filtering, metadata reads, and sorting run synchronously. The call does not promise prompt handling of new cancellation requests during this work or one snapshot across all Sessions. +With `workspace_id`, the call reads its members' headers from the Workspace registry index without persistence I/O, so its work grows with the member count. Without `workspace_id`, it first enumerates every stored and live Session header. Filtering, metadata reads, and sorting then run synchronously. The call does not promise prompt handling of new cancellation requests during this work or one snapshot across all Sessions. ### Failures -Invalid pagination and an unknown `workspace_id` fail with `ToolArgsError` (`INVALID_ARGS`); use `list_workspace` to find a registered ID. Query and storage failures fail the call, and cyclic subagent ancestry encountered during Workspace selection fails with `SESSION_QUERY_INVALID_LINEAGE`. Cancellation returns no partial result. These failures leave sessions and Workspace records untouched. +Invalid pagination and an unknown `workspace_id` fail with `ToolArgsError` (`INVALID_ARGS`); use `list_workspace` to find a registered ID. Query and storage failures fail the call. Cancellation returns no partial result. These failures leave sessions and Workspace records untouched. ----- @@ -65,7 +65,7 @@ Invalid pagination and an unknown `workspace_id` fail with `ToolArgsError` (`INV
Implementation internals — click to expand -The tools combine the existing header-only query listing with Workspace membership and projected metadata. The shared `registerSessionListMetadata` helper acquires the same projection unit used by the Session API; each consumer releases its own registration when disposed. The title projection remains owned by `dsh-session-title`. Cold rows read the projection cache without opening the underlying log, including on a cache miss. No Session Controller or Agent activation is required. +A Workspace selection reads `Workspace.sessionHeaders`; an unscoped call uses the existing header-only query listing. Both combine headers with projected metadata. The shared `registerSessionListMetadata` helper acquires the same projection unit used by the Session API; each consumer releases its own registration when disposed. The title projection remains owned by `dsh-session-title`. Cold rows read the projection cache without opening the underlying log, including on a cache miss. No Session Controller or Agent activation is required. | File | Role | |---|---| @@ -80,7 +80,7 @@ The tools combine the existing header-only query listing with Workspace membersh ## Further Exploration - [Workspace registry](../../workspace/workspace/README.md) — recorded membership, registry order, and archival. -- [Session query](../session-query/README.md) — header enumeration and the shared list metadata reader. +- [Session query](../session-query/README.md) — corpus header enumeration and the shared list metadata reader. - [Session projection cache](../../session/session-projection-cache/README.md) — persisted metadata and cache availability. - [Session query package map](../README.md) — adjacent retrieval capabilities. @@ -110,7 +110,7 @@ The schemas remain stable while tool availability is unchanged. Calls append ord These constraints affect consumers of the lists. - **Cold metadata can be missing or stale** — listing never rebuilds it by reading the full log. A `null` title can mean either no title or unavailable title metadata. -- **Pagination is not a stable snapshot** — concurrent registry or Session changes can move entries between calls. Session listing enumerates candidates before selecting a page, so the page size does not bound total scan work. +- **Pagination is not a stable snapshot** — concurrent registry or Session changes can move entries between calls. Session listing reads every candidate before selecting a page, so the page size does not bound total work; an unscoped call scales with the Session count. - **Metadata access is runtime-wide** — callers needing per-agent Workspace authorization require a separately defined access policy before these tools are enabled for them. diff --git a/packages/session-query/tool-session-list/README.zh.md b/packages/session-query/tool-session-list/README.zh.md index 65492ef42b..a6dbcf8786 100644 --- a/packages/session-query/tool-session-list/README.zh.md +++ b/packages/session-query/tool-session-list/README.zh.md @@ -9,7 +9,7 @@ kind: "package-reference" ## 概述 -无需恢复 agent(智能体)运行或读取冷会话的日志,即可发现工作区和会话。可以列出空工作区、查找某工作区中的会话,或包含 subagent 和已归档会话。结果包含标识符及轻量元数据,并限制每页条目数。当调用者可以查看整个已挂载运行时的元数据时,启用这些工具。 +无需恢复 agent(智能体)运行或读取冷会话的日志,即可发现工作区和会话。可以列出空工作区、查找某工作区中的会话,或列出已归档会话。结果包含标识符及轻量元数据,并限制每页条目数。当调用者可以查看整个已挂载运行时的元数据时,启用这些工具。 ## 目录 @@ -47,15 +47,15 @@ kind: "package-reference" 两个工具都直接返回数组。[工具目录](../../../docs/tool-catalog.zh.md#deepseek-aidsh-tool-session-list)定义参数。先过滤和排序,再分页;每次调用默认返回 20 条,最多接受 100 条,起始偏移为零。继续遍历时,将偏移增加已返回的条目数;空数组表示遍历结束。 -`list_workspace` 保留注册表顺序,并包含没有会话的工作区。`list_session` 默认包含未归档的普通会话;没有指定 `workspace_id` 时,也包含不属于任何 Workspace 的会话。显式选择 Workspace 时使用已记录的成员关系,而非相同的工作目录。包含 subagent 时,直接分配的 Workspace 优先;否则由最近的已记录成员祖先确定归属。普通 fork 会话不会通过父级继承成员关系。归档筛选匹配每个 Session 自身的 ID,与祖先无关。 +`list_workspace` 保留注册表顺序,并包含没有会话的工作区。`list_session` 从不返回 subagent 会话。它默认包含未归档会话;没有指定 `workspace_id` 时,也包含不属于任何 Workspace 的会话。显式选择 Workspace 时使用已记录的成员关系,而非相同的工作目录。归档筛选匹配每个 Session 自身的 ID。 会话按 `updated_at` 降序排列,时间相同则按 Session ID 升序排列。活动时间取创建时间与最近人工提示词时间的较晚值;助手活动和标题变化不会推进它。标题来自实时投影或持久化投影元数据。标题不可用时为 `null`,活动元数据不可用时回退到创建时间。时间戳使用 ISO 8601 字符串。置顶顺序和侧边栏手动顺序不影响结果。 -header 枚举之后,筛选、元数据读取和排序同步执行。调用不承诺在这段工作中及时处理新收到的取消请求,也不承诺所有 Session 共享同一个快照。 +指定 `workspace_id` 时,调用从 Workspace 注册表索引读取成员 header,不做持久化 I/O,因此工作量随成员数增长。不指定 `workspace_id` 时,先枚举所有已存储和 live Session 的 header。随后的筛选、元数据读取和排序同步执行。调用不承诺在这段工作中及时处理新收到的取消请求,也不承诺所有 Session 共享同一个快照。 ### 失败 -无效分页参数或未知的 `workspace_id` 以 `ToolArgsError`(`INVALID_ARGS`)失败;使用 `list_workspace` 查找已注册的 ID。查询和存储故障使调用失败,按 Workspace 筛选时遇到循环的 subagent 祖先关系则以 `SESSION_QUERY_INVALID_LINEAGE` 失败。取消不返回部分结果。这些失败不会修改会话或 Workspace 记录。 +无效分页参数或未知的 `workspace_id` 以 `ToolArgsError`(`INVALID_ARGS`)失败;使用 `list_workspace` 查找已注册的 ID。查询和存储故障使调用失败。取消不返回部分结果。这些失败不会修改会话或 Workspace 记录。 ----- @@ -65,7 +65,7 @@ header 枚举之后,筛选、元数据读取和排序同步执行。调用不
实现细节——点击展开 -工具将现有的仅 header 查询列表与 Workspace 成员关系及投影元数据结合。共享的 `registerSessionListMetadata` 辅助函数获取 Session API 使用的同一个投影单元;每个消费方在释放时只移除自己的注册。标题投影仍由 `dsh-session-title` 拥有。冷条目读取投影缓存,不打开底层日志,缓存未命中时也一样。不需要 Session 控制器,也不会激活 agent。 +选定 Workspace 时读取 `Workspace.sessionHeaders`;不指定范围时使用现有的仅 header 查询列表。两者都把 header 与投影元数据结合。共享的 `registerSessionListMetadata` 辅助函数获取 Session API 使用的同一个投影单元;每个消费方在释放时只移除自己的注册。标题投影仍由 `dsh-session-title` 拥有。冷条目读取投影缓存,不打开底层日志,缓存未命中时也一样。不需要 Session 控制器,也不会激活 agent。 | 文件 | 职责 | |---|---| @@ -80,7 +80,7 @@ header 枚举之后,筛选、元数据读取和排序同步执行。调用不 ## 进一步探索 - [Workspace 注册表](../../workspace/workspace/README.zh.md)——已记录的成员关系、注册表顺序与归档。 -- [Session 查询](../session-query/README.zh.md)——header 枚举与共享列表元数据读取函数。 +- [Session 查询](../session-query/README.zh.md)——全量 header 枚举与共享列表元数据读取函数。 - [Session 投影缓存](../../session/session-projection-cache/README.zh.md)——持久化元数据与缓存可用性。 - [Session 查询包映射](../README.zh.md)——相邻的检索能力。 @@ -110,7 +110,7 @@ header 枚举之后,筛选、元数据读取和排序同步执行。调用不 以下约束影响列表消费方。 - **冷元数据可能缺失或过期**——列表不会通过读取完整日志重建它。标题为 `null` 可能表示没有标题,也可能表示标题元数据不可用。 -- **分页不是稳定快照**——并发的注册表或 Session 变化可能让条目在多次调用间移动。会话列表先枚举候选项,再选取一页,因此每页大小不限制总扫描工作量。 +- **分页不是稳定快照**——并发的注册表或 Session 变化可能让条目在多次调用间移动。会话列表先读取全部候选项,再选取一页,因此每页大小不限制总工作量;不指定范围的调用随 Session 总数增长。 - **元数据访问覆盖整个运行时**——需要逐 agent Workspace 授权的调用者,必须先定义独立的访问策略,再为其启用这些工具。 diff --git a/packages/session-query/tool-session-list/src/index.ts b/packages/session-query/tool-session-list/src/index.ts index f3e2ed47c7..a7d17b0bab 100644 --- a/packages/session-query/tool-session-list/src/index.ts +++ b/packages/session-query/tool-session-list/src/index.ts @@ -52,10 +52,9 @@ export async function apply(ctx: Context): Promise { })) ctx.tools.register(defineTool({ name: 'list_session', - description: 'List sessions by latest human prompt time, newest first, then by ID. Returns IDs, available titles, and ISO creation and update times. Missing activity metadata uses creation time; unavailable titles are null.', + description: 'List non-subagent sessions by latest human prompt time, newest first, then by ID. Returns IDs, available titles, and ISO creation and update times. Missing activity metadata uses creation time; unavailable titles are null.', parameters: { - workspace_id: { type: 'string', description: 'Workspace ID from list_workspace. Includes its members and, when requested, subagents belonging through their nearest member ancestor. Omit to list all accessible sessions.' }, - contain_subagent: { type: 'boolean', description: 'Include subagent sessions. Defaults to false.' }, + workspace_id: { type: 'string', description: 'Workspace ID from list_workspace. Lists only its member sessions. Omit to list sessions in every workspace and outside all workspaces.' }, archived: { type: 'boolean', description: 'Return only archived sessions when true, otherwise only unarchived sessions. Defaults to false.' }, ...pagination, }, diff --git a/packages/session-query/tool-session-list/src/list.ts b/packages/session-query/tool-session-list/src/list.ts index 68fed14528..2de007a6eb 100644 --- a/packages/session-query/tool-session-list/src/list.ts +++ b/packages/session-query/tool-session-list/src/list.ts @@ -2,7 +2,7 @@ import type { Context } from '@deepseek-ai/cordis' import type { Session, SessionHeader, SessionId } from '@deepseek-ai/dsh-session' -import { SessionQueryError, type SessionListMetadata } from '@deepseek-ai/dsh-session-query' +import type { SessionListMetadata } from '@deepseek-ai/dsh-session-query' import type {} from '@deepseek-ai/dsh-session-projection-cache' import type {} from '@deepseek-ai/dsh-session-title' import { ToolArgsError } from '@deepseek-ai/dsh-tools' @@ -17,7 +17,6 @@ export interface PageInput { /** Optional Session selection arguments. */ export interface SessionListInput extends PageInput { readonly workspace_id?: string - readonly contain_subagent?: boolean readonly archived?: boolean } @@ -74,6 +73,8 @@ export function listWorkspaces(ctx: Context, input: PageInput, signal: AbortSign /** * List live and persisted Session metadata without opening cold logs or activating Agents. + * A Workspace selection reads only its members' indexed headers; an unscoped call enumerates + * the corpus headers. Subagent Sessions are excluded. * @param ctx - context providing query, Workspace, and projection services. * @param readLiveMetadata - ready reader owned by this plugin's registration. * @param input - filters and pagination arguments. @@ -88,30 +89,22 @@ export async function listSessions( ): Promise { const { limit, offset } = resolvePage(input) signal.throwIfAborted() - const workspaceId = input.workspace_id === undefined ? undefined : WorkspaceId(input.workspace_id) - if (workspaceId !== undefined && ctx.workspaceRegistry.get(workspaceId) === undefined) { - throw new ToolArgsError([`workspace_id ${JSON.stringify(workspaceId)} is not registered; use list_workspace to find a workspace`]) - } - const records = await ctx.sessionQuery.listSessions(signal) - signal.throwIfAborted() - const archived = new Set(ctx.workspaceRegistry.archivedSessionIds) - const ownership = new Map() - if (workspaceId !== undefined) { - for (const workspace of ctx.workspaceRegistry.list()) { - for (const id of workspace.sessionIds) ownership.set(id, workspace.id) - } - } - const headers = new Map(records.map(record => [record.header.id, record.header])) - const nearestWorkspace = ancestorWorkspaceReader(headers, ownership) - const items = [] - for (const { header } of records) { + let headers: readonly SessionHeader[] + if (input.workspace_id === undefined) { + headers = (await ctx.sessionQuery.listSessions(signal)).map(record => record.header) signal.throwIfAborted() - if (!input.contain_subagent && header.origin === 'subagent') continue - if (archived.has(header.id) !== (input.archived ?? false)) continue - if (workspaceId !== undefined) { - const owner = header.origin === 'subagent' ? nearestWorkspace(header) : ownership.get(header.id) - if (owner !== workspaceId) continue + } else { + const workspace = ctx.workspaceRegistry.get(WorkspaceId(input.workspace_id)) + if (workspace === undefined) { + throw new ToolArgsError([`workspace_id ${JSON.stringify(input.workspace_id)} is not registered; use list_workspace to find a workspace`]) } + headers = workspace.sessionHeaders + } + const archived = new Set(ctx.workspaceRegistry.archivedSessionIds) + const items = [] + for (const header of headers) { + if (header.origin === 'subagent') continue + if (archived.has(header.id) !== (input.archived ?? false)) continue const metadata = readListMetadata(ctx, header, readLiveMetadata) items.push({ session_id: header.id, @@ -122,7 +115,6 @@ export async function listSessions( } items.sort((left, right) => right.updatedAt - left.updatedAt || (left.session_id < right.session_id ? -1 : 1)) - signal.throwIfAborted() return items.slice(offset, offset + limit).map(({ updatedAt, ...item }) => ({ ...item, updated_at: new Date(updatedAt).toISOString(), @@ -149,24 +141,3 @@ function readListMetadata( lastPromptAt: snapshot?.values.sessionListMetadata?.lastPromptAt ?? null, } } - -function ancestorWorkspaceReader( - headers: ReadonlyMap, - ownership: ReadonlyMap, -): (header: SessionHeader) => WorkspaceId | undefined { - const resolved = new Map(ownership) - return (header) => { - const visited = new Set() - let current: SessionHeader | undefined = header - while (current !== undefined && !resolved.has(current.id)) { - if (visited.has(current.id)) { - throw new SessionQueryError(`Session ${header.id} has cyclic parent ancestry`, 'SESSION_QUERY_INVALID_LINEAGE') - } - visited.add(current.id) - current = current.parentSession === undefined ? undefined : headers.get(current.parentSession) - } - const workspace = current === undefined ? undefined : resolved.get(current.id) - for (const id of visited) resolved.set(id, workspace) - return workspace - } -} diff --git a/packages/session-query/tool-session-list/tests/tool-session-list.spec.ts b/packages/session-query/tool-session-list/tests/tool-session-list.spec.ts index 87dd7fcac7..6777822aef 100644 --- a/packages/session-query/tool-session-list/tests/tool-session-list.spec.ts +++ b/packages/session-query/tool-session-list/tests/tool-session-list.spec.ts @@ -233,9 +233,7 @@ describe('read-only Session list tools', () => { }) await mounted.ctx.workspaceRegistry.pinSession(SessionId('z')) expect(value(await mounted.call('list_session', { limit: 1, offset: 1 }))).toEqual([item('b', 100)]) - expect(value(await mounted.call('list_session', { contain_subagent: true }))).toEqual([ - item('child', 200), item('a', 100), item('b', 100), item('z', 100), - ]) + expect(value(await mounted.call('list_session'))).toEqual([item('a', 100), item('b', 100), item('z', 100)]) expect(value(await mounted.call('list_session', { archived: true }))).toEqual([item('archived', 500)]) expect(value(await mounted.call('list_session', { archived: true, offset: 1 }))).toEqual([]) }) @@ -248,33 +246,36 @@ describe('read-only Session list tools', () => { ]) }) - it('inherits explicit Workspace membership only for subagents and stops at the nearest assigned ancestor', async () => { + it('lists recorded non-subagent Workspace members from indexed headers without enumerating the corpus', async () => { const path = await directory() const otherPath = join(path, 'other') await mkdir(otherPath) const mounted = await mount({ headers: [ header('parent', 10, { cwd: path }), - header('same-cwd', 20, { cwd: path }), - header('child', 30, { cwd: path, origin: 'subagent', parentSession: SessionId('parent') }), - header('grandchild', 40, { origin: 'subagent', parentSession: SessionId('child') }), - header('fork', 50, { cwd: path, parentSession: SessionId('parent') }), - header('assigned-child', 60, { cwd: otherPath, origin: 'subagent', parentSession: SessionId('parent') }), - header('assigned-grandchild', 70, { origin: 'subagent', parentSession: SessionId('assigned-child') }), - header('orphan', 80, { origin: 'subagent', parentSession: SessionId('absent') }), - header('unassigned-child', 90, { origin: 'subagent', parentSession: SessionId('same-cwd') }), + header('member', 20, { cwd: path }), + header('same-cwd', 30, { cwd: path }), + header('child', 40, { cwd: path, origin: 'subagent', parentSession: SessionId('parent') }), + header('assigned-child', 50, { cwd: path, origin: 'subagent', parentSession: SessionId('parent') }), + header('other-member', 60, { cwd: otherPath }), + ], + workspaces: [ + ['primary', workspace(path, ['parent', 'member', 'assigned-child'])], + ['other', workspace(otherPath, ['other-member'])], ], - workspaces: [['primary', workspace(path, ['parent'])], ['other', workspace(otherPath, ['assigned-child'])]], archived: ['parent'], }) - expect(value(await mounted.call('list_session', { workspace_id: 'primary', contain_subagent: true }))).toEqual([ - item('grandchild', 40), item('child', 30), - ]) + const corpus = vi.spyOn(mounted.ctx.sessionQuery, 'listSessions') + // Registry startup already listed the stored headers; only later listings matter. + const stored = vi.spyOn(mounted.ctx.sessionPersistence, 'list') + stored.mockClear() + expect(value(await mounted.call('list_session', { workspace_id: 'primary' }))).toEqual([item('member', 20)]) expect(value(await mounted.call('list_session', { workspace_id: 'primary', archived: true }))).toEqual([item('parent', 10)]) - expect(value(await mounted.call('list_session', { workspace_id: 'other', contain_subagent: true }))).toEqual([ - item('assigned-grandchild', 70), item('assigned-child', 60), - ]) - expect(value(await mounted.call('list_session', { workspace_id: 'primary' }))).toEqual([]) + expect(value(await mounted.call('list_session', { workspace_id: 'other' }))).toEqual([item('other-member', 60)]) + expect(corpus).not.toHaveBeenCalled() + expect(stored).not.toHaveBeenCalled() + expect(value(await mounted.call('list_session'))).toEqual([item('other-member', 60), item('same-cwd', 30), item('member', 20)]) + expect(corpus).toHaveBeenCalledOnce() }) it('defaults to twenty rows and accepts the upper page limit', async () => { @@ -295,16 +296,10 @@ describe('read-only Session list tools', () => { } }) - it('rejects an unknown Workspace and corrupt subagent ancestry with typed failures', async () => { - const path = await directory() - const mounted = await mount({ - headers: [header('cycle-a', 10, { origin: 'subagent', parentSession: SessionId('cycle-b') }), header('cycle-b', 20, { origin: 'subagent', parentSession: SessionId('cycle-a') })], - workspaces: [['known', workspace(path)]], - }) + it('rejects an unknown Workspace with a typed failure', async () => { + const mounted = await mount() expect((await mounted.call('list_session', { workspace_id: 'absent' })).error?.info) .toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) - expect((await mounted.call('list_session', { workspace_id: 'known', contain_subagent: true })).error?.info) - .toMatchObject({ name: 'SessionQueryError', code: 'SESSION_QUERY_INVALID_LINEAGE' }) expect(mounted.open).not.toHaveBeenCalled() }) diff --git a/packages/workspace/workspace/README.i18n.yaml b/packages/workspace/workspace/README.i18n.yaml index d90b57b56d..56af9d261a 100644 --- a/packages/workspace/workspace/README.i18n.yaml +++ b/packages/workspace/workspace/README.i18n.yaml @@ -39,8 +39,8 @@ en: 447ced401b3b14a8 zh: 3ce2105605223945 /deepseek-ai-dsh-workspace/understand-the-implementation/design-philosophy: - en: e969314497b99389 - zh: 82eafc832617a1eb + en: 512431b309ba0051 + zh: 206c77de2022a541 /deepseek-ai-dsh-workspace/understand-the-implementation/api-behavior: en: 8fcd81ee32f3c01e zh: 08ac92d085bb8147 diff --git a/packages/workspace/workspace/README.md b/packages/workspace/workspace/README.md index bafe861a81..23d8e88804 100644 --- a/packages/workspace/workspace/README.md +++ b/packages/workspace/workspace/README.md @@ -91,7 +91,7 @@ This section explains the design decisions behind the feature and points at the ### Design philosophy - **One record per canonical path.** `fs.realpath` is the single uniqueness canon: paths are stored canonicalized, so a symlink to an owned directory collides, and uniqueness is string equality of canonical paths. -- **Membership starts from the recorded account.** The header index validates ordered `sessionIds`; missing-directory candidates retain their account, while other invalid candidates are filtered on read and pruned by the next mutation. The strict canonical-path index used for history bootstrap includes existing directories only. +- **Membership starts from the recorded account.** The header index validates ordered `sessionIds`; missing-directory candidates retain their account, while other invalid candidates are filtered on read and pruned by the next mutation. `sessionHeaders` returns the indexed headers of `sessionIds` in the same order without persistence I/O. The strict canonical-path index used for history bootstrap includes existing directories only. - **Header-only reads.** Bootstrap and attach validation read `SessionHeader` fields only; event bodies are never loaded. - **Two-write mutations with an explicit marker.** Create and delete persist a `pendingMutation` marker before the record/order pair can diverge, so startup completes exactly the interrupted operation and unmarked divergence fails loud as corruption. - **Serialized writes.** Registry operations run on one operation chain; entity mutations go through `table.update` on the domain write chain, stamping `updatedAt` and deciding membership at their chain slot. diff --git a/packages/workspace/workspace/README.zh.md b/packages/workspace/workspace/README.zh.md index c894d3264a..02bf670648 100644 --- a/packages/workspace/workspace/README.zh.md +++ b/packages/workspace/workspace/README.zh.md @@ -91,7 +91,7 @@ Workspace 注册不意味着拥有其目录。未来的破坏性文件系统操 ### 设计理念 - **每个规范路径一条记录。** `fs.realpath` 是唯一的一套唯一性规范:路径以规范化形式存储,因此指向已有记录目录的符号链接会与之冲突,唯一性即规范路径的字符串相等。 -- **成员资格以已记录的归属为起点。** 头部索引校验有序的 `sessionIds`;目录缺失的候选保留归属,其他无效候选在读取时过滤,并在下一次变更时剪除。历史引导使用的严格规范路径索引只包含现存目录。 +- **成员资格以已记录的归属为起点。** 头部索引校验有序的 `sessionIds`;目录缺失的候选保留归属,其他无效候选在读取时过滤,并在下一次变更时剪除。`sessionHeaders` 按相同顺序返回 `sessionIds` 的已索引 header,不做持久化 I/O。历史引导使用的严格规范路径索引只包含现存目录。 - **仅读取头部。** 引导与 attach 校验只读取 `SessionHeader` 字段;事件正文绝不加载。 - **两次写入的变更带显式标记。** 创建与删除在记录/顺序对可能分叉之前先持久化 `pendingMutation` 标记,因此启动只补全被中断的操作,未标记的分叉作为损坏明确报错。 - **串行化写入。** 注册表操作跑在同一条操作链上;实体变更通过领域写链上的 `table.update` 执行,写入 `updatedAt`,并在其所在的链位置决定成员资格。 diff --git a/packages/workspace/workspace/src/entity.ts b/packages/workspace/workspace/src/entity.ts index 0d687e8c94..cecd435181 100644 --- a/packages/workspace/workspace/src/entity.ts +++ b/packages/workspace/workspace/src/entity.ts @@ -29,7 +29,8 @@ export class WorkspaceMoveInvalidError extends Error { /** * The registry-owned machinery an entity mutates through. Entities never see * the registry itself — only the open table, the canonical session-path - * index backing the `sessionIds` projection, and attach-time header reads. + * index backing the `sessionIds` projection, its header index, and + * attach-time header reads. */ export interface WorkspaceEntityHost { /** @@ -55,6 +56,13 @@ export interface WorkspaceEntityHost { */ readSessionHeader(id: SessionId): Promise + /** + * Read the indexed header of a session that {@link candidateMatches} accepted. + * @param id - Session currently returned by `sessionIds`. + * @returns the immutable indexed header. + */ + sessionHeader(id: SessionId): SessionHeader + /** * Publish a successfully validated canonical cwd to the projection index. * @param id - Validated session id. @@ -103,6 +111,10 @@ export class WorkspaceEntity implements Workspace { return this.record.sessionIds.filter(id => this.host.candidateMatches(id, this.record.path)) } + get sessionHeaders(): readonly SessionHeader[] { + return this.sessionIds.map(id => this.host.sessionHeader(id)) + } + async setTitle(title: string): Promise { await this.mutate(record => ({ ...record, title })) } diff --git a/packages/workspace/workspace/src/index.ts b/packages/workspace/workspace/src/index.ts index 825cb0491a..a8c0e498df 100644 --- a/packages/workspace/workspace/src/index.ts +++ b/packages/workspace/workspace/src/index.ts @@ -200,6 +200,14 @@ export class WorkspaceRegistry extends Service { table: () => this.requireTable(), candidateMatches: (id, path) => this.sessionPaths.get(id) === path || this.missingSessionPaths.has(id), readSessionHeader: id => this.readSessionHeader(id), + sessionHeader: (id) => { + const header = this.headers.get(id) + /* v8 ignore next 3 -- every path that admits a candidate indexes its header first. */ + if (header === undefined) { + throw new Error(`workspace member '${id}' has no indexed session header`) + } + return header + }, rememberSessionPath: (id, path) => { this.sessionPaths.set(id, path) this.missingSessionPaths.delete(id) diff --git a/packages/workspace/workspace/src/types.ts b/packages/workspace/workspace/src/types.ts index 1b09bef969..bd3ae0a3e4 100644 --- a/packages/workspace/workspace/src/types.ts +++ b/packages/workspace/workspace/src/types.ts @@ -6,7 +6,7 @@ */ import type { Branded } from '@deepseek-ai/dsh-brand' -import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type { SessionHeader, SessionId } from '@deepseek-ai/dsh-session/types' import type { TypertResource } from '@deepseek-ai/dsh-typert-protocol' /** @@ -99,6 +99,13 @@ export interface Workspace { */ readonly sessionIds: readonly SessionId[] + /** + * Stored headers of {@link sessionIds}, in the same order. Read from the + * registry's startup and attach-time header index without persistence I/O; + * headers are immutable, so an indexed header never goes stale. + */ + readonly sessionHeaders: readonly SessionHeader[] + /** * Replace the display title durably. * @param title - New title; any string, duplicates across workspaces allowed. diff --git a/packages/workspace/workspace/tests/workspace.spec.ts b/packages/workspace/workspace/tests/workspace.spec.ts index 7c0a9e99e7..ddba94bb49 100644 --- a/packages/workspace/workspace/tests/workspace.spec.ts +++ b/packages/workspace/workspace/tests/workspace.spec.ts @@ -667,6 +667,7 @@ describe('Workspace session ordering', () => { expect(workspace.sessionIds).toEqual(['s2', 's1']) await workspace.attachSession(SessionId('s1')) expect(workspace.sessionIds).toEqual(['s2', 's1']) + expect(workspace.sessionHeaders).toEqual([header('s2', dir, 2), header('s1', dir, 1)]) expect(storedRecord(result.pool, workspace.id).sessionIds).toEqual(['s2', 's1']) }) @@ -890,6 +891,7 @@ describe('header-validated membership projection', () => { onTestFinished(() => result.ctx.fiber.dispose()) const workspace = result.registry.get(id)! expect(workspace.sessionIds).toEqual(['missing-dir']) + expect(workspace.sessionHeaders).toEqual([header('missing-dir', missing)]) await workspace.setTitle('Validated') expect(storedRecord(pool, id).sessionIds).toEqual(['missing-dir']) }) diff --git a/snapshots/session/session-list-tools/session.v4.jsonl b/snapshots/session/session-list-tools/session.v4.jsonl index 18b6788ea5..bd34f510b8 100644 --- a/snapshots/session/session-list-tools/session.v4.jsonl +++ b/snapshots/session/session-list-tools/session.v4.jsonl @@ -27,9 +27,9 @@ {"type":"tool/result","data":{"turn":1,"step":3,"message":{"role":"tool","source":{"kind":"tool","callId":"list-3"},"toolCallId":"list-3","content":[{"type":"text","text":"[{\"session_id\":\"list-beta\",\"title\":null,\"created_at\":\"1970-01-01T00:00:02.000Z\",\"updated_at\":\"1970-01-01T00:00:02.000Z\"},{\"session_id\":\"list-alpha\",\"title\":\"Alpha\",\"created_at\":\"1970-01-01T00:00:01.000Z\",\"updated_at\":\"1970-01-01T00:00:01.000Z\"}]"}],"isError":false,"id":"{{message:9}}"}},"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":"tool-call","id":"list-4","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"contain_subagent\":true,\"limit\":2}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:10}}"},"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":"list-4","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"contain_subagent\":true,\"limit\":2}"}}},{"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":4,"callId":"list-4","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"contain_subagent\":true,\"limit\":2}"}} -{"type":"tool/result","data":{"turn":1,"step":4,"message":{"role":"tool","source":{"kind":"tool","callId":"list-4"},"toolCallId":"list-4","content":[{"type":"text","text":"[{\"session_id\":\"list-child\",\"title\":null,\"created_at\":\"1970-01-01T00:00:04.000Z\",\"updated_at\":\"1970-01-01T00:00:04.000Z\"},{\"session_id\":\"list-beta\",\"title\":null,\"created_at\":\"1970-01-01T00:00:02.000Z\",\"updated_at\":\"1970-01-01T00:00:02.000Z\"}]"}],"isError":false,"id":"{{message:11}}"}},"sourceEventSeqs":[29],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"tool-call","id":"list-4","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"limit\":1}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:10}}"},"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":"list-4","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"limit\":1}"}}},{"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":4,"callId":"list-4","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"limit\":1}"}} +{"type":"tool/result","data":{"turn":1,"step":4,"message":{"role":"tool","source":{"kind":"tool","callId":"list-4"},"toolCallId":"list-4","content":[{"type":"text","text":"[{\"session_id\":\"list-beta\",\"title\":null,\"created_at\":\"1970-01-01T00:00:02.000Z\",\"updated_at\":\"1970-01-01T00:00:02.000Z\"}]"}],"isError":false,"id":"{{message:11}}"}},"sourceEventSeqs":[29],"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":"list-5","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"archived\":true}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:12}}"},"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":"list-5","name":"list_session","arguments":"{\"workspace_id\":\"list-workspace\",\"archived\":true}"}}},{"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"} diff --git a/snapshots/session/session-list-tools/tool-schemas.expected.json b/snapshots/session/session-list-tools/tool-schemas.expected.json index 0cc0d307b3..a7f800a4ac 100644 --- a/snapshots/session/session-list-tools/tool-schemas.expected.json +++ b/snapshots/session/session-list-tools/tool-schemas.expected.json @@ -249,17 +249,13 @@ }, { "name": "list_session", - "description": "List sessions by latest human prompt time, newest first, then by ID. Returns IDs, available titles, and ISO creation and update times. Missing activity metadata uses creation time; unavailable titles are null.", + "description": "List non-subagent sessions by latest human prompt time, newest first, then by ID. Returns IDs, available titles, and ISO creation and update times. Missing activity metadata uses creation time; unavailable titles are null.", "parameters": { "type": "object", "properties": { "workspace_id": { "type": "string", - "description": "Workspace ID from list_workspace. Includes its members and, when requested, subagents belonging through their nearest member ancestor. Omit to list all accessible sessions." - }, - "contain_subagent": { - "type": "boolean", - "description": "Include subagent sessions. Defaults to false." + "description": "Workspace ID from list_workspace. Lists only its member sessions. Omit to list sessions in every workspace and outside all workspaces." }, "archived": { "type": "boolean", From cd329ad22a64040116e2404989a06283b556e54e Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Wed, 11 Nov 2026 14:31:42 +0800 Subject: [PATCH 12/31] fix(session): align list tool release version and rescope skip Match the new package to the merged 0.2.2-rc.2 release version, and add the cua agent-scopes test to the exact-path rescope exceptions for its cordis preset id. --- packages/session-query/tool-session-list/package.json | 2 +- scripts/rescope-vendor.ts | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/session-query/tool-session-list/package.json b/packages/session-query/tool-session-list/package.json index 26ac358141..0c24c7fcae 100644 --- a/packages/session-query/tool-session-list/package.json +++ b/packages/session-query/tool-session-list/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-tool-session-list", "description": "Read-only paginated Workspace and Session metadata tools", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/scripts/rescope-vendor.ts b/scripts/rescope-vendor.ts index 62259636b2..47cc146745 100644 --- a/scripts/rescope-vendor.ts +++ b/scripts/rescope-vendor.ts @@ -103,6 +103,7 @@ const GENERIC_SKIPS: readonly GenericSkip[] = [ { file: 'apps/web/tests/agent-preset-authoring.e2e.ts', upstream: ['cordis'] }, { file: 'apps/web/tests/creator-persona.e2e.ts', upstream: ['cordis'] }, { file: 'packages/preset/agent-preset-registry/tests/session.spec.ts', upstream: ['cordis'] }, + { file: 'packages/experimental/cua/tests/agent-scopes.spec.ts', upstream: ['cordis'] }, { file: 'packages/experimental/creation-recommendations/src/index.ts', upstream: ['cordis'] }, { file: 'packages/experimental/creation-recommendations/tests/creation.spec.ts', upstream: ['cordis'] }, { file: 'packages/experimental/creation-recommendations/tests/loader-composition.spec.ts', upstream: ['cordis'] }, From bb383263d8d244994cd709b42c61af49cf36f209 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Wed, 11 Nov 2026 14:17:28 +0800 Subject: [PATCH 13/31] refactor(llm): share extractTextContent across text consumers --- docs/config-catalog.md | 16 ++++---- docs/config-catalog.zh.md | 16 ++++---- docs/event-producer-consumer.md | 2 +- docs/event-producer-consumer.zh.md | 2 +- docs/module-graph.md | 3 +- docs/module-graph.zh.md | 3 +- docs/persistence-catalog.i18n.yaml | 8 ++-- docs/persistence-catalog.md | 4 +- docs/persistence-catalog.zh.md | 4 +- docs/persistence-schema.json | 2 +- packages/bundle/headless/src/index.ts | 6 +-- .../src/client/conversation-nodes/command.ts | 5 +-- .../src/client/contract/system-prompt.ts | 3 +- .../src/client/queue/QueueDock.tsx | 5 ++- .../src/client/tool/toolviews/office-row.tsx | 3 +- .../session-reference/src/projection.ts | 10 ++--- packages/core/tool-executor-ptc/src/ptc.ts | 3 +- .../claude-code-mods/src/host-ops.ts | 9 ++-- .../claude-code-mods/src/index.ts | 11 ++--- .../client-ui-stats/src/client/stats-fold.ts | 12 ++---- .../experimental/forge-session/package.json | 1 + .../forge-session/src/projection.ts | 4 +- .../forge-session/src/reference-lookup.ts | 4 +- .../hooks-claude-code/src/index.ts | 10 ++--- .../experimental/hooks-codex/src/index.ts | 12 ++---- .../src/index.ts | 8 ++-- packages/llm/llm-deepseek/src/serialize.ts | 6 +-- packages/llm/llm-pi-ai/src/context.ts | 20 +++------ packages/llm/llm/README.i18n.yaml | 8 ++-- packages/llm/llm/README.md | 3 +- packages/llm/llm/README.zh.md | 3 +- packages/llm/llm/src/index.ts | 6 ++- packages/llm/llm/src/message.ts | 15 ++++++- packages/llm/llm/tests/message.spec.ts | 41 +++++++++++++++++++ packages/sdk/server/src/query-activity.ts | 4 +- .../src/index.ts | 8 ++-- packages/session/session-title/src/index.ts | 6 +-- packages/web/web-deepseek-api/src/index.ts | 5 ++- .../workflow/workflow-ptc/src/guest-source.ts | 2 +- packages/workflow/workflow-ptc/src/runtime.ts | 12 +----- 40 files changed, 166 insertions(+), 139 deletions(-) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 778476c08b..66b4ce105e 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1046,7 +1046,7 @@ export interface StagehandModelConfig { ## `@deepseek-ai/dsh-experimental-claude-code-mods` - `inject`: `workingDirectory` · `agents` -- `source`: [`packages/experimental/claude-code-mods/src/index.ts:53`](../packages/experimental/claude-code-mods/src/index.ts) +- `source`: [`packages/experimental/claude-code-mods/src/index.ts:54`](../packages/experimental/claude-code-mods/src/index.ts) ```ts config-catalog /** Plugin config: the limits mod hooks run under. */ @@ -1714,7 +1714,7 @@ export interface Config { - `inject`: `agentDefaultModel` · `agents` · `sessions` - `refs`: [`ApprovalPolicy`](subsystems/approval.md) -- `source`: [`packages/bundle/headless/src/index.ts:48`](../packages/bundle/headless/src/index.ts) +- `source`: [`packages/bundle/headless/src/index.ts:49`](../packages/bundle/headless/src/index.ts) ```ts config-catalog /** Plugin config: the task and run options resolved from this app's injected provider service. */ @@ -1762,7 +1762,7 @@ export interface HmrConfig extends ChokidarOptions { ## `@deepseek-ai/dsh-hooks-claude-code` - `inject`: `shell` · `agents` · `workingDirectory` -- `source`: [`packages/experimental/hooks-claude-code/src/index.ts:50`](../packages/experimental/hooks-claude-code/src/index.ts) +- `source`: [`packages/experimental/hooks-claude-code/src/index.ts:51`](../packages/experimental/hooks-claude-code/src/index.ts) ```ts config-catalog /** Plugin config: where the CC hook config lives + substitution roots. */ @@ -1801,7 +1801,7 @@ export interface Config { ## `@deepseek-ai/dsh-hooks-codex` - `inject`: `shell` · `agents` · `workingDirectory` -- `source`: [`packages/experimental/hooks-codex/src/index.ts:49`](../packages/experimental/hooks-codex/src/index.ts) +- `source`: [`packages/experimental/hooks-codex/src/index.ts:50`](../packages/experimental/hooks-codex/src/index.ts) ```ts config-catalog /** Plugin config: where the Codex hooks.json lives + the model name for payloads. */ @@ -3399,7 +3399,7 @@ export enum SessionTelemetryMode { ## `@deepseek-ai/dsh-session-title` - `inject`: `sessions` · `sessionProjections` · `agents` -- `source`: [`packages/session/session-title/src/index.ts:56`](../packages/session/session-title/src/index.ts) +- `source`: [`packages/session/session-title/src/index.ts:57`](../packages/session/session-title/src/index.ts) ```ts config-catalog /** Required deterministic fallback and accepted-title limits. */ @@ -3421,7 +3421,7 @@ export interface Config { - `inject`: `sessionTitle` · `llm` · `sessions` - `refs`: [`SessionTitleLlmConfig`](../packages/session/session-title-llm/src/index.ts) -- `source`: [`packages/experimental/session-title-all-prompts-llm/src/index.ts:28`](../packages/experimental/session-title-all-prompts-llm/src/index.ts) +- `source`: [`packages/experimental/session-title-all-prompts-llm/src/index.ts:29`](../packages/experimental/session-title-all-prompts-llm/src/index.ts) ```ts config-catalog /** Required execution controls plus this provider's title-length targets; no defaults. */ @@ -3441,7 +3441,7 @@ export interface Config extends SessionTitleLlmConfig { - `inject`: `sessionTitle` · `llm` · `sessions` - `refs`: [`SessionTitleLlmConfig`](../packages/session/session-title-llm/src/index.ts) -- `source`: [`packages/session/session-title-first-prompt-llm/src/index.ts:28`](../packages/session/session-title-first-prompt-llm/src/index.ts) +- `source`: [`packages/session/session-title-first-prompt-llm/src/index.ts:29`](../packages/session/session-title-first-prompt-llm/src/index.ts) ```ts config-catalog /** Required execution controls plus this provider's title-length targets; no defaults. */ @@ -4884,7 +4884,7 @@ export interface Config { - `inject`: `web` - `refs`: `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/web/web-deepseek-api/src/index.ts:64`](../packages/web/web-deepseek-api/src/index.ts) +- `source`: [`packages/web/web-deepseek-api/src/index.ts:65`](../packages/web/web-deepseek-api/src/index.ts) ```ts config-catalog /** diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 29944e53bb..4df36f8825 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1048,7 +1048,7 @@ export interface StagehandModelConfig { ## `@deepseek-ai/dsh-experimental-claude-code-mods` - `inject`: `workingDirectory` · `agents` -- `source`: [`packages/experimental/claude-code-mods/src/index.ts:53`](../packages/experimental/claude-code-mods/src/index.ts) +- `source`: [`packages/experimental/claude-code-mods/src/index.ts:54`](../packages/experimental/claude-code-mods/src/index.ts) ```ts config-catalog /** Plugin config: the limits mod hooks run under. */ @@ -1716,7 +1716,7 @@ export interface Config { - `inject`: `agentDefaultModel` · `agents` · `sessions` - `refs`: [`ApprovalPolicy`](subsystems/approval.zh.md) -- `source`: [`packages/bundle/headless/src/index.ts:48`](../packages/bundle/headless/src/index.ts) +- `source`: [`packages/bundle/headless/src/index.ts:49`](../packages/bundle/headless/src/index.ts) ```ts config-catalog /** Plugin config: the task and run options resolved from this app's injected provider service. */ @@ -1764,7 +1764,7 @@ export interface HmrConfig extends ChokidarOptions { ## `@deepseek-ai/dsh-hooks-claude-code` - `inject`: `shell` · `agents` · `workingDirectory` -- `source`: [`packages/experimental/hooks-claude-code/src/index.ts:50`](../packages/experimental/hooks-claude-code/src/index.ts) +- `source`: [`packages/experimental/hooks-claude-code/src/index.ts:51`](../packages/experimental/hooks-claude-code/src/index.ts) ```ts config-catalog /** Plugin config: where the CC hook config lives + substitution roots. */ @@ -1803,7 +1803,7 @@ export interface Config { ## `@deepseek-ai/dsh-hooks-codex` - `inject`: `shell` · `agents` · `workingDirectory` -- `source`: [`packages/experimental/hooks-codex/src/index.ts:49`](../packages/experimental/hooks-codex/src/index.ts) +- `source`: [`packages/experimental/hooks-codex/src/index.ts:50`](../packages/experimental/hooks-codex/src/index.ts) ```ts config-catalog /** Plugin config: where the Codex hooks.json lives + the model name for payloads. */ @@ -3401,7 +3401,7 @@ export enum SessionTelemetryMode { ## `@deepseek-ai/dsh-session-title` - `inject`: `sessions` · `sessionProjections` · `agents` -- `source`: [`packages/session/session-title/src/index.ts:56`](../packages/session/session-title/src/index.ts) +- `source`: [`packages/session/session-title/src/index.ts:57`](../packages/session/session-title/src/index.ts) ```ts config-catalog /** Required deterministic fallback and accepted-title limits. */ @@ -3423,7 +3423,7 @@ export interface Config { - `inject`: `sessionTitle` · `llm` · `sessions` - `refs`: [`SessionTitleLlmConfig`](../packages/session/session-title-llm/src/index.ts) -- `source`: [`packages/experimental/session-title-all-prompts-llm/src/index.ts:28`](../packages/experimental/session-title-all-prompts-llm/src/index.ts) +- `source`: [`packages/experimental/session-title-all-prompts-llm/src/index.ts:29`](../packages/experimental/session-title-all-prompts-llm/src/index.ts) ```ts config-catalog /** Required execution controls plus this provider's title-length targets; no defaults. */ @@ -3443,7 +3443,7 @@ export interface Config extends SessionTitleLlmConfig { - `inject`: `sessionTitle` · `llm` · `sessions` - `refs`: [`SessionTitleLlmConfig`](../packages/session/session-title-llm/src/index.ts) -- `source`: [`packages/session/session-title-first-prompt-llm/src/index.ts:28`](../packages/session/session-title-first-prompt-llm/src/index.ts) +- `source`: [`packages/session/session-title-first-prompt-llm/src/index.ts:29`](../packages/session/session-title-first-prompt-llm/src/index.ts) ```ts config-catalog /** Required execution controls plus this provider's title-length targets; no defaults. */ @@ -4886,7 +4886,7 @@ export interface Config { - `inject`: `web` - `refs`: `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/web/web-deepseek-api/src/index.ts:64`](../packages/web/web-deepseek-api/src/index.ts) +- `source`: [`packages/web/web-deepseek-api/src/index.ts:65`](../packages/web/web-deepseek-api/src/index.ts) ```ts config-catalog /** diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index aa42c78c51..17f0edb61c 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -60,7 +60,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `llm-pi-ai/request-headers` | `waterfall` | [`packages/llm/llm-pi-ai/src/index.ts:113`](../packages/llm/llm-pi-ai/src/index.ts) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) (`waterfall`) | - | | `llm/adapters-updated` | `emit` | [`packages/llm/llm/src/types.ts:24`](../packages/llm/llm/src/types.ts) | [`llm`](../packages/llm/llm) (`events.dispatch`) | [`acp`](../packages/acp/acp), `remotes` | | `llm/models-updated` | `emit` | [`packages/llm/llm/src/types.ts:30`](../packages/llm/llm/src/types.ts) | [`llm-deepseek`](../packages/llm/llm-deepseek) (`emit`) | `remotes` | -| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:76`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) | +| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:80`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) | | `mcp-manager/status` | `parallel` | [`packages/mcp/mcp-manager/src/types.ts:46`](../packages/mcp/mcp-manager/src/types.ts) | [`mcp-manager`](../packages/mcp/mcp-manager) (`parallel`) | - | | `permission-presets/catalog-changed` | `emit` | [`packages/interaction/permission-presets/src/types.ts:48`](../packages/interaction/permission-presets/src/types.ts) | [`permission-presets`](../packages/interaction/permission-presets) (`events.dispatch`) | `remotes` | | `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:455`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index bdda966741..58d3f9819c 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -62,7 +62,7 @@ | `llm-pi-ai/request-headers` | `waterfall` | [`packages/llm/llm-pi-ai/src/index.ts:113`](../packages/llm/llm-pi-ai/src/index.ts) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) (`waterfall`) | - | | `llm/adapters-updated` | `emit` | [`packages/llm/llm/src/types.ts:24`](../packages/llm/llm/src/types.ts) | [`llm`](../packages/llm/llm) (`events.dispatch`) | [`acp`](../packages/acp/acp), `remotes` | | `llm/models-updated` | `emit` | [`packages/llm/llm/src/types.ts:30`](../packages/llm/llm/src/types.ts) | [`llm-deepseek`](../packages/llm/llm-deepseek) (`emit`) | `remotes` | -| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:76`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) | +| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:80`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) | | `mcp-manager/status` | `parallel` | [`packages/mcp/mcp-manager/src/types.ts:46`](../packages/mcp/mcp-manager/src/types.ts) | [`mcp-manager`](../packages/mcp/mcp-manager) (`parallel`) | - | | `permission-presets/catalog-changed` | `emit` | [`packages/interaction/permission-presets/src/types.ts:48`](../packages/interaction/permission-presets/src/types.ts) | [`permission-presets`](../packages/interaction/permission-presets) (`events.dispatch`) | `remotes` | | `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:455`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | diff --git a/docs/module-graph.md b/docs/module-graph.md index 623e1664ff..3e59e9c953 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -1147,6 +1147,7 @@ flowchart TD pkg_experimental_auto_review --> pkg_tools pkg_experimental_auto_review --> pkg_working_directory pkg_experimental_forge_session --> pkg_experimental_forge + pkg_experimental_forge_session --> pkg_llm pkg_experimental_forge_session --> pkg_sandbox_policy pkg_experimental_forge_session --> pkg_session pkg_experimental_forge_session --> pkg_session_projection @@ -1877,7 +1878,7 @@ flowchart TD | [`web-app`](../packages/bundle/web-app) | `bundle` | [`shell-env`](../packages/shell/shell-env) | | [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`user-questions`](../packages/interaction/user-questions) | | [`experimental-auto-review`](../packages/experimental/auto-review) | `experimental` | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | -| [`experimental-forge-session`](../packages/experimental/forge-session) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`tools`](../packages/core/tools) | +| [`experimental-forge-session`](../packages/experimental/forge-session) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`llm`](../packages/llm/llm), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`tools`](../packages/core/tools) | | [`webhook`](../packages/experimental/webhook) | `experimental` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`workspace`](../packages/workspace/workspace) | | [`tool-cordis`](../packages/extensions/tool-cordis) | `extensions` | [`agent`](../packages/core/agent), [`app-boot`](../packages/boot/app-boot), [`cordis-host-runner`](../packages/extensions/cordis-host-runner), [`tools`](../packages/core/tools) | | [`host-plugin-inventory`](../packages/host/plugin-inventory) | `host` | [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`brand`](../packages/util/brand), [`typert-protocol`](../packages/typert/protocol) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index fd754de0b4..311c6d06e6 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -1149,6 +1149,7 @@ flowchart TD pkg_experimental_auto_review --> pkg_tools pkg_experimental_auto_review --> pkg_working_directory pkg_experimental_forge_session --> pkg_experimental_forge + pkg_experimental_forge_session --> pkg_llm pkg_experimental_forge_session --> pkg_sandbox_policy pkg_experimental_forge_session --> pkg_session pkg_experimental_forge_session --> pkg_session_projection @@ -1879,7 +1880,7 @@ flowchart TD | [`web-app`](../packages/bundle/web-app) | `bundle` | [`shell-env`](../packages/shell/shell-env) | | [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`user-questions`](../packages/interaction/user-questions) | | [`experimental-auto-review`](../packages/experimental/auto-review) | `experimental` | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | -| [`experimental-forge-session`](../packages/experimental/forge-session) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`tools`](../packages/core/tools) | +| [`experimental-forge-session`](../packages/experimental/forge-session) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`llm`](../packages/llm/llm), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`tools`](../packages/core/tools) | | [`webhook`](../packages/experimental/webhook) | `experimental` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`workspace`](../packages/workspace/workspace) | | [`tool-cordis`](../packages/extensions/tool-cordis) | `extensions` | [`agent`](../packages/core/agent), [`app-boot`](../packages/boot/app-boot), [`cordis-host-runner`](../packages/extensions/cordis-host-runner), [`tools`](../packages/core/tools) | | [`host-plugin-inventory`](../packages/host/plugin-inventory) | `host` | [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`brand`](../packages/util/brand), [`typert-protocol`](../packages/typert/protocol) | diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml index f2294edff6..15315a1b41 100644 --- a/docs/persistence-catalog.i18n.yaml +++ b/docs/persistence-catalog.i18n.yaml @@ -183,8 +183,8 @@ en: 20645a60e921f012 zh: 7141cafe3a0e71d7 /session-persistence-event-catalog/events/session/session-title-log-only: - en: 6c6a27578dff5828 - zh: 9a5add2bc0df2d0a + en: 5775e52a72c0ce94 + zh: fa211a35b4660c10 /session-persistence-event-catalog/events/session/session-title-llm-request-log-only: en: 59b02baa2be32ca0 zh: 3637c99652ca89cf @@ -1368,8 +1368,8 @@ en: 4147b170f52814af zh: e78991ac1c41ebec /session-persistence-event-catalog/resolved-persistence-types/string: - en: ef89e74973f4a575 - zh: 0bb1564a0418501c + en: 396943de139bab31 + zh: 59c676f614b39c2a /session-persistence-event-catalog/resolved-persistence-types/string~2: en: 0089620bf4638263 zh: 1922bef1713094bb diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index 33d9aa4395..3713b7f10c 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -865,7 +865,7 @@ Source: [`packages/core/session/src/types.ts:435`](../packages/core/session/src/ Types: [SessionTitleEventData](subsystems/session-title.md) -Source: [`packages/session/session-title/src/index.ts:77`](../packages/session/session-title/src/index.ts) +Source: [`packages/session/session-title/src/index.ts:78`](../packages/session/session-title/src/index.ts) @@ -5659,7 +5659,7 @@ Array of `number`. SHA-256: `4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b` -Sources: [`packages/api/session-controller/src/types.ts:391`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:21`](../packages/core/session/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/jobs/jobs/src/brand.ts:19`](../packages/jobs/jobs/src/brand.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:42`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/team/agent-team/src/types.ts:20`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:32`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:8`](../packages/team/agent-team/src/types.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts) +Sources: [`packages/api/session-controller/src/types.ts:391`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:21`](../packages/core/session/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/jobs/jobs/src/brand.ts:19`](../packages/jobs/jobs/src/brand.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:43`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/team/agent-team/src/types.ts:20`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:32`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:8`](../packages/team/agent-team/src/types.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts) `string` diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md index 5047ebc659..8da066bf73 100644 --- a/docs/persistence-catalog.zh.md +++ b/docs/persistence-catalog.zh.md @@ -867,7 +867,7 @@ export type SessionEvent = { 类型:[SessionTitleEventData](subsystems/session-title.zh.md) -来源:[`packages/session/session-title/src/index.ts:77`](../packages/session/session-title/src/index.ts) +来源:[`packages/session/session-title/src/index.ts:78`](../packages/session/session-title/src/index.ts) @@ -5661,7 +5661,7 @@ SHA-256: `5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78` SHA-256: `4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b` -来源:[`packages/api/session-controller/src/types.ts:391`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:21`](../packages/core/session/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/jobs/jobs/src/brand.ts:19`](../packages/jobs/jobs/src/brand.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:42`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/team/agent-team/src/types.ts:20`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:32`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:8`](../packages/team/agent-team/src/types.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts) +来源:[`packages/api/session-controller/src/types.ts:391`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:21`](../packages/core/session/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/jobs/jobs/src/brand.ts:19`](../packages/jobs/jobs/src/brand.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:43`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/team/agent-team/src/types.ts:20`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:32`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:8`](../packages/team/agent-team/src/types.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts) `string` diff --git a/docs/persistence-schema.json b/docs/persistence-schema.json index a2832eb98c..b753ba4cb8 100644 --- a/docs/persistence-schema.json +++ b/docs/persistence-schema.json @@ -259,7 +259,7 @@ {"digest":"4b259f7f8f0a44ad5e90b70a73553ced1df27012d126921d397ff403b6c86731","names":["packages/llm/llm/src/message.ts#ToolResultMessage"],"sources":["packages/llm/llm/src/message.ts:173"]}, {"digest":"4b7ddaf3710b88ff9b8df66304f5f97bf03688fd19730eedc2e9535203c820ea","names":[],"sources":[]}, {"digest":"4bb451330ff699f36b45539ceb0eb2606ead72084e2c5bb637c36cc80e2252db","names":[],"sources":["packages/core/session/src/types.ts:198"]}, - {"digest":"4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b","names":["packages/api/session-controller/src/types.ts#SessionRequestId","packages/attachment/attachment/src/brand.ts#AttachmentId","packages/compaction/compaction/src/brand.ts#CompactionId","packages/core/session/src/types.ts#SessionId","packages/experimental/webhook/src/brand.ts#WebhookDeliveryId","packages/experimental/webhook/src/brand.ts#WebhookRuleId","packages/experimental/webhook/src/brand.ts#WebhookSourceId","packages/feedback/message-feedback/src/types.ts#MessageFeedbackVersion","packages/goal/goal/src/types.ts#GoalId","packages/interaction/commands/src/brand.ts#CommandId","packages/interaction/user-approval/src/types.ts#ApprovalRequestId","packages/jobs/jobs/src/brand.ts#JobId","packages/llm/llm-retry/src/brand.ts#RetryId","packages/llm/llm/src/brand.ts#MessageId","packages/llm/llm/src/brand.ts#ProviderRequestId","packages/llm/llm/src/brand.ts#ReasoningEffortId","packages/llm/llm/src/brand.ts#ToolCallId","packages/schedule/schedule/src/types.ts#ScheduleId","packages/session/session-title/src/index.ts#SessionTitleProviderId","packages/session/session-title/src/types.ts#SessionTitleProviderId","packages/team/agent-team/src/types.ts#TeamId","packages/team/agent-team/src/types.ts#TeamMessageId","packages/team/agent-team/src/types.ts#TeamTaskId","packages/workflow/workflow/src/types.ts#WorkflowRunId"],"sources":["packages/api/session-controller/src/types.ts:391","packages/attachment/attachment/src/brand.ts:6","packages/compaction/compaction/src/brand.ts:4","packages/core/session/src/types.ts:21","packages/experimental/webhook/src/brand.ts:12","packages/experimental/webhook/src/brand.ts:6","packages/experimental/webhook/src/brand.ts:9","packages/feedback/message-feedback/src/types.ts:14","packages/goal/goal/src/types.ts:17","packages/interaction/commands/src/brand.ts:31","packages/interaction/user-approval/src/types.ts:17","packages/jobs/jobs/src/brand.ts:19","packages/llm/llm-retry/src/brand.ts:4","packages/llm/llm/src/brand.ts:16","packages/llm/llm/src/brand.ts:31","packages/llm/llm/src/brand.ts:43","packages/llm/llm/src/brand.ts:67","packages/schedule/schedule/src/types.ts:14","packages/session/session-title/src/index.ts:42","packages/session/session-title/src/types.ts:17","packages/team/agent-team/src/types.ts:20","packages/team/agent-team/src/types.ts:32","packages/team/agent-team/src/types.ts:8","packages/workflow/workflow/src/types.ts:13"]}, + {"digest":"4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b","names":["packages/api/session-controller/src/types.ts#SessionRequestId","packages/attachment/attachment/src/brand.ts#AttachmentId","packages/compaction/compaction/src/brand.ts#CompactionId","packages/core/session/src/types.ts#SessionId","packages/experimental/webhook/src/brand.ts#WebhookDeliveryId","packages/experimental/webhook/src/brand.ts#WebhookRuleId","packages/experimental/webhook/src/brand.ts#WebhookSourceId","packages/feedback/message-feedback/src/types.ts#MessageFeedbackVersion","packages/goal/goal/src/types.ts#GoalId","packages/interaction/commands/src/brand.ts#CommandId","packages/interaction/user-approval/src/types.ts#ApprovalRequestId","packages/jobs/jobs/src/brand.ts#JobId","packages/llm/llm-retry/src/brand.ts#RetryId","packages/llm/llm/src/brand.ts#MessageId","packages/llm/llm/src/brand.ts#ProviderRequestId","packages/llm/llm/src/brand.ts#ReasoningEffortId","packages/llm/llm/src/brand.ts#ToolCallId","packages/schedule/schedule/src/types.ts#ScheduleId","packages/session/session-title/src/index.ts#SessionTitleProviderId","packages/session/session-title/src/types.ts#SessionTitleProviderId","packages/team/agent-team/src/types.ts#TeamId","packages/team/agent-team/src/types.ts#TeamMessageId","packages/team/agent-team/src/types.ts#TeamTaskId","packages/workflow/workflow/src/types.ts#WorkflowRunId"],"sources":["packages/api/session-controller/src/types.ts:391","packages/attachment/attachment/src/brand.ts:6","packages/compaction/compaction/src/brand.ts:4","packages/core/session/src/types.ts:21","packages/experimental/webhook/src/brand.ts:12","packages/experimental/webhook/src/brand.ts:6","packages/experimental/webhook/src/brand.ts:9","packages/feedback/message-feedback/src/types.ts:14","packages/goal/goal/src/types.ts:17","packages/interaction/commands/src/brand.ts:31","packages/interaction/user-approval/src/types.ts:17","packages/jobs/jobs/src/brand.ts:19","packages/llm/llm-retry/src/brand.ts:4","packages/llm/llm/src/brand.ts:16","packages/llm/llm/src/brand.ts:31","packages/llm/llm/src/brand.ts:43","packages/llm/llm/src/brand.ts:67","packages/schedule/schedule/src/types.ts:14","packages/session/session-title/src/index.ts:43","packages/session/session-title/src/types.ts:17","packages/team/agent-team/src/types.ts:20","packages/team/agent-team/src/types.ts:32","packages/team/agent-team/src/types.ts:8","packages/workflow/workflow/src/types.ts:13"]}, {"digest":"4d60dddaa65d3da8d4cd014d85ce3d2c2875664dd0433e331d8e9d395289686b","names":["packages/experimental/liveshare/src/host/viewer-principal.ts#ShareViewerPrincipal"],"sources":["packages/experimental/liveshare/src/host/viewer-principal.ts:24"]}, {"digest":"4e011753f8263f436efaabfbb3b4db53a98fc55342c5ded2daf7208b217be159","names":[],"sources":[]}, {"digest":"4e44c9118152f6829634bfd508e47669ab0497caffa380c94b4be91f9390d35d","names":[],"sources":[]}, diff --git a/packages/bundle/headless/src/index.ts b/packages/bundle/headless/src/index.ts index bc98d7ae6b..69b40ac06a 100644 --- a/packages/bundle/headless/src/index.ts +++ b/packages/bundle/headless/src/index.ts @@ -18,6 +18,7 @@ import type { Agent, AgentOptions } from '@deepseek-ai/dsh-agent' import type {} from '@deepseek-ai/dsh-agent-default-model' import { installModelSelection } from '@deepseek-ai/dsh-agent' import type {} from '@deepseek-ai/dsh-fs' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { createUserMessage } from '@deepseek-ai/dsh-llm' import { APPROVAL_POLICIES, setApprovalPolicy, type ApprovalPolicy } from '@deepseek-ai/dsh-user-approval' import { assertNever } from '@deepseek-ai/dsh-util-values' @@ -99,10 +100,7 @@ function summarize(session: Session, firstSeq: SessionLogOffset): RunOutcome { } if (!started) continue if (event.type === 'assistant/message') { - const joined = event.data.message.content - .filter(block => block.type === 'text') - .map(block => block.text) - .join('') + const joined = extractTextContent(event.data.message.content) if (joined !== '') text = joined } if (event.type === 'turn/end') reason = event.data.reason diff --git a/packages/client/ui-chat/src/client/conversation-nodes/command.ts b/packages/client/ui-chat/src/client/conversation-nodes/command.ts index a52b877552..de407aa354 100644 --- a/packages/client/ui-chat/src/client/conversation-nodes/command.ts +++ b/packages/client/ui-chat/src/client/conversation-nodes/command.ts @@ -1,3 +1,4 @@ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import type { Context } from '@deepseek-ai/cordis' import type { CommandNode, CompactionSummaryNode, ConversationMatch, ConversationNodeContext, ConversationNodeDefinition, @@ -105,9 +106,7 @@ function compactSummary(match: ConversationMatch | undefined, checkpoint: Conver if (match?.event.type === 'compaction/summary') { const data = match.event.data if (Array.isArray(data.summary)) { - const text = data.summary - .map(block => block.type === 'text' ? block.text : '') - .join('') + const text = extractTextContent(data.summary) summary = text.trim() === '' ? null : text } shadowedItemCount = Array.isArray(data.shadowedSeqs) diff --git a/packages/client/ui-conversation/src/client/contract/system-prompt.ts b/packages/client/ui-conversation/src/client/contract/system-prompt.ts index e61b35d81b..3ac1fadcc7 100644 --- a/packages/client/ui-conversation/src/client/contract/system-prompt.ts +++ b/packages/client/ui-conversation/src/client/contract/system-prompt.ts @@ -1,4 +1,5 @@ /** Immutable system-only interpretation of the loaded Session surface. */ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import type { SessionEvent } from '@deepseek-ai/dsh-session/types' import { isSurfaceEvent } from '@deepseek-ai/dsh-session/surface' import type { SystemPromptNode } from './request-inspection.ts' @@ -61,7 +62,7 @@ export function inspectSystemPrompt(previous: SystemPromptState | undefined, eve time: event.time, turn: event.data.turn, step: event.data.step, - text: event.data.message.content.flatMap(block => block.type === 'text' ? [block.text] : []).join(''), + text: extractTextContent(event.data.message.content), update: op === 'append' && previous?.nodes.some(item => item.node.text !== '') === true, } : undefined diff --git a/packages/client/ui-conversation/src/client/queue/QueueDock.tsx b/packages/client/ui-conversation/src/client/queue/QueueDock.tsx index 6396387a91..420dcff49f 100644 --- a/packages/client/ui-conversation/src/client/queue/QueueDock.tsx +++ b/packages/client/ui-conversation/src/client/queue/QueueDock.tsx @@ -1,3 +1,4 @@ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import type { Context } from '@deepseek-ai/cordis' import { useEffect, useId, useMemo, useState } from 'react' import type { FileAttachmentRef, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' @@ -23,7 +24,7 @@ const QUEUE_TEXT_FACTS: Readonly> = { function textOf(content: InboxState['next-turn'][number]['content']): string | null { if (!content.every(block => block.type === 'text')) return null - return content.map(block => block.text).join('') + return extractTextContent(content) } /** Queue operations injected by the session-scoped registration. */ @@ -228,7 +229,7 @@ export function QueueDock({ useSession, useProjection, updateQueue, notify, load )} {renderFactorySlot('conversation.user.text', { - text: row.content.filter(block => block.type === 'text').map(block => block.text).join(''), + text: extractTextContent(row.content), facts: QUEUE_TEXT_FACTS, interactive: false, ellipsis: true, })} diff --git a/packages/client/ui-tool/src/client/tool/toolviews/office-row.tsx b/packages/client/ui-tool/src/client/tool/toolviews/office-row.tsx index e52ff7d10f..c3e14750fe 100644 --- a/packages/client/ui-tool/src/client/tool/toolviews/office-row.tsx +++ b/packages/client/ui-tool/src/client/tool/toolviews/office-row.tsx @@ -1,6 +1,7 @@ // Office toolview links target the input, not the temporary output. Rows show the // result's text blocks; rendered page images reach the model but are not displayed. +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { IconBrowseOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' import type { Context } from '@deepseek-ai/cordis' import { toolFileInject } from '../file-menu.ts' @@ -26,7 +27,7 @@ export function OfficeRow({ const row = toolRowModel(toolName, block, cwd, home) // Image blocks flatten to JSON attachment references, so a settled result with only images shows no body. const output = 'kind' in block - ? block.content.flatMap(part => part.type === 'text' ? [part.text] : []).join('\n') || null + ? extractTextContent(block.content, { separator: '\n' }) || null : row.output const path = office.filePath return ( diff --git a/packages/context/session-reference/src/projection.ts b/packages/context/session-reference/src/projection.ts index 196c75b4e1..f747f242c3 100644 --- a/packages/context/session-reference/src/projection.ts +++ b/packages/context/session-reference/src/projection.ts @@ -1,5 +1,7 @@ /** Current-surface projection and byte-bounded rendering. */ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' + import { isCompactCheckpointSource } from '@deepseek-ai/dsh-compaction' import type { SessionSurfaceSnapshot } from '@deepseek-ai/dsh-session-query' import { TextRetainer } from '@deepseek-ai/dsh-output-retention' @@ -42,12 +44,12 @@ function projectSessionConversation(snapshot: SessionSurfaceSnapshot): Projected case 'user/message': { const checkpoint = isCompactCheckpointSource(event.data.source) if (!checkpoint && event.data.source.kind !== 'user') break - const text = textContent(event.data.content) + const text = extractTextContent(event.data.content, { separator: '\n' }) if (text !== '') conversation.push({ role: 'user', text, checkpoint, originalText: text, omittedBytes: 0 }) break } case 'assistant/message': { - const text = textContent(event.data.message.content) + const text = extractTextContent(event.data.message.content, { separator: '\n' }) if (text !== '') conversation.push({ role: 'assistant', text, checkpoint: false, originalText: text, omittedBytes: 0 }) break } @@ -145,10 +147,6 @@ export function retainReferencedSession( } } -function textContent(content: readonly { type: string; text?: string }[]): string { - return content.flatMap(block => block.type === 'text' && typeof block.text === 'string' ? [block.text] : []).join('\n') -} - function truncateWithNotice(text: string, maxOutputBytes: number): { text: string; omittedBytes: number } { /* v8 ignore next -- callers invoke this only with a target smaller than the selected original text. */ if (Buffer.byteLength(text, 'utf8') <= maxOutputBytes) return { text, omittedBytes: 0 } diff --git a/packages/core/tool-executor-ptc/src/ptc.ts b/packages/core/tool-executor-ptc/src/ptc.ts index 7fa2b79c78..ce3202e2b9 100644 --- a/packages/core/tool-executor-ptc/src/ptc.ts +++ b/packages/core/tool-executor-ptc/src/ptc.ts @@ -10,6 +10,7 @@ import { isDeepStrictEqual } from 'node:util' import type { PtcDispatchLog } from './runtime-types.ts' import { symbols, type Context } from '@deepseek-ai/cordis' import { brandString } from '@deepseek-ai/dsh-brand' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { createUserMessage, HarnessError, resolveImageAttachmentAccess } from '@deepseek-ai/dsh-llm' import type { ContentBlock, ToolCallId, ToolSchema } from '@deepseek-ai/dsh-llm' @@ -704,7 +705,7 @@ export function createRunCodeTransport( if (first !== undefined && images.length === 1) return programImage(first.attachment) if (outcome.imageRemoved) { throw new Error('Image output was removed by a tool output policy.\n' - + outcome.content.filter(block => block.type === 'text').map(block => block.text).join('\n')) + + extractTextContent(outcome.content, { separator: '\n' })) } if (name === 'read_image' || images.length > 1) throw new Error('Image-producing tools must return exactly one image') } diff --git a/packages/experimental/claude-code-mods/src/host-ops.ts b/packages/experimental/claude-code-mods/src/host-ops.ts index 47bf900671..0968717709 100644 --- a/packages/experimental/claude-code-mods/src/host-ops.ts +++ b/packages/experimental/claude-code-mods/src/host-ops.ts @@ -14,6 +14,7 @@ import type { Agent } from '@deepseek-ai/dsh-agent' import type {} from '@deepseek-ai/dsh-subprocess' import type { CommandDefinition } from '@deepseek-ai/dsh-commands' import type { FileSystem, FsTarget } from '@deepseek-ai/dsh-fs' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { createUserMessage, ToolCallId } from '@deepseek-ai/dsh-llm' import type { ContentBlock, Message } from '@deepseek-ai/dsh-llm' import { scopeOf } from '@deepseek-ai/dsh-scope' @@ -106,17 +107,13 @@ function requireAgent(context: OpContext, op: string): Agent { return agent } -function textOf(content: readonly ContentBlock[]): string { - return content.filter((block): block is Extract => block.type === 'text').map(block => block.text).join('') -} - /** * Project one tool outcome onto Claude Code's `tool.call` result. * @param result - the harness tool outcome. * @returns its text as `result`, with `isError` on a failure. */ export function toolCallResultOf(result: ToolExecutionResult): ToolCallResult { - return result.isError ? { result: textOf(result.content), isError: true } : { result: textOf(result.content) } + return result.isError ? { result: extractTextContent(result.content), isError: true } : { result: extractTextContent(result.content) } } /** The model's raw JSON arguments as an object; an unparsable string is an empty input. */ @@ -136,7 +133,7 @@ function sessionMessages(messages: readonly Message[], aliases: ToolNameAliases) const toolUses = message.content .filter((block): block is Extract => block.type === 'tool-call') .map(block => ({ tool_use_id: block.id, tool: aliases.toMod(block.name), input: argumentsOf(block.arguments) })) - out.push({ role: message.role, text: textOf(message.content), toolUses }) + out.push({ role: message.role, text: extractTextContent(message.content), toolUses }) } return out } diff --git a/packages/experimental/claude-code-mods/src/index.ts b/packages/experimental/claude-code-mods/src/index.ts index bcce9050c3..61a2f52435 100644 --- a/packages/experimental/claude-code-mods/src/index.ts +++ b/packages/experimental/claude-code-mods/src/index.ts @@ -15,7 +15,8 @@ import type {} from '@deepseek-ai/dsh-working-directory' import z from '@deepseek-ai/schemastery' import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent' import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' -import type { AssistantMessage, ContentBlock, TokenUsage } from '@deepseek-ai/dsh-llm' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' +import { type AssistantMessage, type ContentBlock, type TokenUsage } from '@deepseek-ai/dsh-llm' import { SessionId } from '@deepseek-ai/dsh-session' import type { UserMessage } from '@deepseek-ai/dsh-session' import { scopeOf } from '@deepseek-ai/dsh-scope' @@ -77,10 +78,6 @@ function assertPositive(field: string, value: number): void { if (!Number.isFinite(value) || value <= 0) throw new Error(`claude-code-mods: ${field} must be a positive number of milliseconds`) } -function textOf(blocks: readonly ContentBlock[]): string { - return blocks.filter((block): block is Extract => block.type === 'text').map(block => block.text).join('') -} - /** The human's own messages among a claim: the prompt a `prompt.submit` hook sees and may rewrite. */ function promptMessages(claimed: readonly UserMessage[]): UserMessage[] { return claimed.filter(message => message.source.kind === 'user') @@ -140,7 +137,7 @@ interface TurnRecord { /** Fold one committed assistant message into the turn's answer and usage. */ function foldAssistantMessage(turnRecord: TurnRecord, data: { message: AssistantMessage; usage?: TokenUsage }): void { - turnRecord.answer = textOf(data.message.content) + turnRecord.answer = extractTextContent(data.message.content) if (data.usage === undefined) return const { model } = data.message.source const usage = turnRecord.usage ?? { input_tokens: 0, output_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: 0, model } @@ -348,7 +345,7 @@ export class ClaudeCodeMods extends TypertRemoteService { const first = !started.has(turn) started.add(turn) const prompt = promptMessages(messages) - const text = textOf(prompt.flatMap(message => message.content)) + const text = extractTextContent(prompt.flatMap(message => message.content)) let submitted: PromptSubmitResult = { text } // A batch of injected context alone is not a prompt: Claude Code raises prompt.submit for typed prompts. if (prompt.length > 0) { diff --git a/packages/experimental/client-ui-stats/src/client/stats-fold.ts b/packages/experimental/client-ui-stats/src/client/stats-fold.ts index 365a7873f1..fd7c6d78e8 100644 --- a/packages/experimental/client-ui-stats/src/client/stats-fold.ts +++ b/packages/experimental/client-ui-stats/src/client/stats-fold.ts @@ -1,5 +1,6 @@ /** Event folding and per-step metric derivation for the Statistics table. */ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import type { SessionEventLike } from '@deepseek-ai/dsh-api-session-controller/client' import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' import type { AssistantMessage, ContentBlock, StreamChunk, UserMessage } from '@deepseek-ai/dsh-llm' @@ -267,10 +268,7 @@ const OPAQUE_SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9 export function triggerSenderOf(message: UserMessage): string | null { const kind: string = message.source.kind if (kind !== 'agent-message' && kind !== 'team-message') return null - let text = '' - for (const block of message.content) { - if (block.type === 'text') text += block.text - } + const text = extractTextContent(message.content) const team = TEAM_MESSAGE_PREFIX.exec(text) /* v8 ignore next -- a matched capture group is always present. */ if (team !== null) return team[1]?.trim() ?? null @@ -291,11 +289,7 @@ function answerOf(message: AssistantMessage): { body: string truncated: boolean } | null { - const parts: string[] = [] - for (const block of message.content) { - if (block.type === 'text') parts.push(block.text) - } - const text = parts.join('\n').trim() + const text = extractTextContent(message.content, { separator: '\n' }).trim() if (text === '') return null return { preview: text.length > ANSWER_LIMIT ? text.slice(0, ANSWER_LIMIT) : text, diff --git a/packages/experimental/forge-session/package.json b/packages/experimental/forge-session/package.json index 18d8274446..8819ada7bb 100644 --- a/packages/experimental/forge-session/package.json +++ b/packages/experimental/forge-session/package.json @@ -43,6 +43,7 @@ }, "peerDependencies": { "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-experimental-forge": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-session-projection": "workspace:*", diff --git a/packages/experimental/forge-session/src/projection.ts b/packages/experimental/forge-session/src/projection.ts index 1f1ab54a43..0a285de34d 100644 --- a/packages/experimental/forge-session/src/projection.ts +++ b/packages/experimental/forge-session/src/projection.ts @@ -1,5 +1,7 @@ /** Projection that folds shell results and binding records into one Session's change request bindings, and shows clients the bindings. */ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' + import { z } from 'zod' import { pluginRecordOf, SessionSeq } from '@deepseek-ai/dsh-session' import type { SessionEvent, SessionEventMap } from '@deepseek-ai/dsh-session' @@ -105,7 +107,7 @@ function applyResult(state: ForgeChangeRequestsState, result: SessionEventMap['t if (pending === undefined) return state const rest = state.pending.filter(entry => entry !== pending) if (result.message.isError === true) return { ...state, pending: rest } - const text = result.message.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('\n') + const text = extractTextContent(result.message.content, { separator: '\n' }) const printed = pending.urls === 'created' ? changeRequestUrls(text) : ownChangeRequestUrls(text) return { pending: rest, diff --git a/packages/experimental/forge-session/src/reference-lookup.ts b/packages/experimental/forge-session/src/reference-lookup.ts index 7cce3eb6dc..b648911c58 100644 --- a/packages/experimental/forge-session/src/reference-lookup.ts +++ b/packages/experimental/forge-session/src/reference-lookup.ts @@ -1,5 +1,7 @@ /** Resolve unqualified CLI references in the shell execution world and persist only confirmed URLs. */ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' + import type { Context } from '@deepseek-ai/cordis' import type { Session } from '@deepseek-ai/dsh-session' import type { ToolExecution, ToolExecutionResult } from '@deepseek-ai/dsh-tools' @@ -53,7 +55,7 @@ export function observeReferences(ctx: Context, timeoutMs: number, record: (sess const argumentsResult = shellArguments.safeParse(exec.arguments) const shell = completedShell.safeParse(result.value) if (!argumentsResult.success || !shell.success) return - const printed = result.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('\n') + const printed = extractTextContent(result.content, { separator: '\n' }) if (ownChangeRequestUrls(printed).length > 0) return const lookups = ghReferences(argumentsResult.data.command).flatMap(reference => reference.lookup === null ? [] : [reference.lookup]) const agent = exec.agent diff --git a/packages/experimental/hooks-claude-code/src/index.ts b/packages/experimental/hooks-claude-code/src/index.ts index 5e2b59d3d8..2541297e3d 100644 --- a/packages/experimental/hooks-claude-code/src/index.ts +++ b/packages/experimental/hooks-claude-code/src/index.ts @@ -13,6 +13,7 @@ import { readFileSync } from 'node:fs' import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { createUserMessage } from '@deepseek-ai/dsh-llm' import type { ContextFormed } from '@deepseek-ai/dsh-llm' declare module '@deepseek-ai/dsh-llm' { @@ -319,11 +320,6 @@ function lastTurn(ctx: Context, agent: Agent | undefined): number { return ctx.agents.turnBoundaryOf(agent.session).lastTurn } -/** Flatten content blocks to the text a hook payload carries (the common case). */ -function blocksToText(content: ContentBlock[]): string { - return content.filter((b): b is Extract => b.type === 'text').map(b => b.text).join('') -} - function base(agent: Agent | undefined, event: string): Record { return { session_id: agent?.session.header.id ?? '', @@ -338,13 +334,13 @@ function sessionStartPayload(agent: Agent, source: string): Record { - return { ...base(agent, 'UserPromptSubmit'), prompt: blocksToText(content) } + return { ...base(agent, 'UserPromptSubmit'), prompt: extractTextContent(content) } } function preToolPayload(exec: ToolExecution): Record { return { ...base(exec.agent, 'PreToolUse'), tool_name: exec.name, tool_input: exec.arguments, tool_use_id: exec.callId } } function postToolPayload(exec: ToolExecution, result: ToolExecutionResult): Record { - return { ...base(exec.agent, 'PostToolUse'), tool_name: exec.name, tool_input: exec.arguments, tool_use_id: exec.callId, tool_response: blocksToText(result.content) } + return { ...base(exec.agent, 'PostToolUse'), tool_name: exec.name, tool_input: exec.arguments, tool_use_id: exec.callId, tool_response: extractTextContent(result.content) } } function stopPayload(agent: Agent): Record { return { ...base(agent, 'Stop'), stop_hook_active: false } diff --git a/packages/experimental/hooks-codex/src/index.ts b/packages/experimental/hooks-codex/src/index.ts index 2d9b3c3daf..6d86ae79f3 100644 --- a/packages/experimental/hooks-codex/src/index.ts +++ b/packages/experimental/hooks-codex/src/index.ts @@ -16,6 +16,7 @@ import { readFileSync } from 'node:fs' import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { createUserMessage } from '@deepseek-ai/dsh-llm' import type { ContextFormed } from '@deepseek-ai/dsh-llm' declare module '@deepseek-ai/dsh-llm' { @@ -203,7 +204,7 @@ export function apply(ctx: Context, config: Config): void { const payload = { ...base(agent, 'UserPromptSubmit', model), turn_id: String(turn), - prompt: blocksToText(messages.flatMap(message => message.content)), + prompt: extractTextContent(messages.flatMap(message => message.content)), } const merged = await runPoint('UserPromptSubmit', '', payload, { agent, turn, plainStdoutAsContext: true, signal, @@ -275,17 +276,12 @@ export function apply(ctx: Context, config: Config): void { // --- Codex DIALECT payloads: snake_case, model on every event, turn_id on // turn-scoped events. --- -// These small payload helpers intentionally remain next to the dialect shape; -// sharing them would pull bridge-only agent/LLM dependencies into hook-protocol. +// Shared hook-protocol code has no Agent dependency, so turn lookup stays in the bridge. /* jscpd:ignore-start */ function lastTurn(ctx: Context, agent: Agent | undefined): number { if (!agent) return 0 return ctx.agents.turnBoundaryOf(agent.session).lastTurn } - -function blocksToText(content: ContentBlock[]): string { - return content.filter((b): b is Extract => b.type === 'text').map(b => b.text).join('') -} /* jscpd:ignore-end */ /** Base fields on every Codex payload (no turn_id). */ @@ -324,5 +320,5 @@ function preToolPayload(ctx: Context, exec: ToolExecution, model: string): Recor } function postToolPayload(ctx: Context, exec: ToolExecution, result: ToolExecutionResult, model: string): Record { - return { ...turnBase(ctx, exec.agent, 'PostToolUse', model), tool_name: exec.name, tool_input: { command: commandOf(exec.arguments) }, tool_use_id: exec.callId, tool_response: blocksToText(result.content) } + return { ...turnBase(ctx, exec.agent, 'PostToolUse', model), tool_name: exec.name, tool_input: { command: commandOf(exec.arguments) }, tool_use_id: exec.callId, tool_response: extractTextContent(result.content) } } diff --git a/packages/experimental/session-title-all-prompts-llm/src/index.ts b/packages/experimental/session-title-all-prompts-llm/src/index.ts index a88ba63695..5b48816e9c 100644 --- a/packages/experimental/session-title-all-prompts-llm/src/index.ts +++ b/packages/experimental/session-title-all-prompts-llm/src/index.ts @@ -3,7 +3,8 @@ /* jscpd:ignore-start -- both shipped providers import the same shared packages. */ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' -import type { LlmResolvedModelInfo, ReasoningEffortId } from '@deepseek-ai/dsh-llm' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' +import { type LlmResolvedModelInfo, type ReasoningEffortId } from '@deepseek-ai/dsh-llm' import { assertNever } from '@deepseek-ai/dsh-util-values' import { normalizeSessionTitle, @@ -136,10 +137,7 @@ function titleFromResponse(response: SessionTitleLlmResponse): string { if (response.blocks.some(block => block.type === 'tool-call')) { throw new Error('session-title-llm: title output must contain text only') } - const text = response.blocks - .filter((block): block is Extract<(typeof response.blocks)[number], { type: 'text' }> => block.type === 'text') - .map(block => block.text) - .join(' ') + const text = extractTextContent(response.blocks, { separator: ' ' }) const title = normalizeSessionTitle(titleFromOutput(text), Number.MAX_SAFE_INTEGER) if (title.length === 0) throw new Error('session-title-llm: title model produced no text') return title diff --git a/packages/llm/llm-deepseek/src/serialize.ts b/packages/llm/llm-deepseek/src/serialize.ts index f08412c0e9..ab5e0f75d7 100644 --- a/packages/llm/llm-deepseek/src/serialize.ts +++ b/packages/llm/llm-deepseek/src/serialize.ts @@ -1,5 +1,6 @@ /** Map system snapshots, tool changes, and conversation turns to Messages using the configured route capability. */ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { LlmError, requestImageHandleText } from '@deepseek-ai/dsh-llm' import type { ContentBlock, GenerateOptions, ImageAttachmentAccessResolver, Message, RequestMessage } from '@deepseek-ai/dsh-llm' import type { ImageAttachmentRef, RequestImageAttachment } from '@deepseek-ai/dsh-attachment' @@ -104,9 +105,8 @@ export function serialize( return unsupported('tool-change blocks outside developer messages') } if (message.role === 'system') { - const texts = message.content.filter(block => block.type === 'text') - if (texts.length !== message.content.length) return unsupported('non-text system message') - const text = texts.map(block => block.text).join('') + if (message.content.some(block => block.type !== 'text')) return unsupported('non-text system message') + const text = extractTextContent(message.content) if (inHistory && messages.length > 0) { if (text.length === 0) return unsupported('empty in-history system update') systemUpdates.push({ role: 'system', content: [{ type: 'text', text }] }) diff --git a/packages/llm/llm-pi-ai/src/context.ts b/packages/llm/llm-pi-ai/src/context.ts index b77fda933c..95179f5ab1 100644 --- a/packages/llm/llm-pi-ai/src/context.ts +++ b/packages/llm/llm-pi-ai/src/context.ts @@ -5,6 +5,7 @@ */ import { brandString } from '@deepseek-ai/dsh-brand' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { contentHasImage, IMAGE_OFFLOAD_REQUIRED_CODE, LlmError, offloadedImageText, projectOffloadedImages, requestImageHandleText, requiredImageOffload } from '@deepseek-ai/dsh-llm' import type { ContentBlock, GenerateOptions, ImageAttachmentAccessResolver, Message, RequestMessage, ToolCallId } from '@deepseek-ai/dsh-llm' import type { @@ -20,15 +21,6 @@ import type { PrefixDigests } from './prefix-binding.ts' import { requestImageDimensions } from '@deepseek-ai/dsh-attachment' import { DEFAULT_REQUEST_IMAGE_MAX_BYTES, DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET } from './config.ts' -/** Join the text blocks of a harness message. */ -function flattenText(message: RequestMessage): string { - return message.content - .filter(block => block.type === 'text') - .map(block => block.text) - .join('') -} - - /** Recover the pi-ai toolResult message for one harness tool-role message. */ function toolResultOf( message: Extract, @@ -94,7 +86,7 @@ function userContent( break } } - if (content.every(block => block.type === 'text')) return content.map(block => block.text).join('') + if (content.every(block => block.type === 'text')) return extractTextContent(content) return content } @@ -151,7 +143,7 @@ function splitSystemPrompt(options: GenerateOptions): SystemPromptSplit { let end = 0 for (const message of options.messages) { if (message.role !== 'system') break - text.push(flattenText(message)) + text.push(extractTextContent(message.content)) end++ } const systemPrompt = text.filter(Boolean).join('\n\n') @@ -230,7 +222,7 @@ function appendSharedHistory( return true } if (message.role === 'system') { - const content = flattenText(message) + const content = extractTextContent(message.content) if (content.length > 0) { if (supportsMidConvoSystemMessages) { messages.push({ role: 'system', content, timestamp: 0 }) @@ -264,10 +256,10 @@ function textOnlyContext( } if (appendSharedHistory(message, options, messages, toolNames, supportsMidConvoSystemMessages, onReplayDegrade, prefixDigests)) continue if (message.role === 'tool') { - messages.push(toolResultOf(message, toolNames, flattenText(message))) + messages.push(toolResultOf(message, toolNames, extractTextContent(message.content))) continue } - messages.push({ role: 'user', content: flattenText(message), timestamp: 0 }) + messages.push({ role: 'user', content: extractTextContent(message.content), timestamp: 0 }) } return piContext(split.systemPrompt, options, messages) } diff --git a/packages/llm/llm/README.i18n.yaml b/packages/llm/llm/README.i18n.yaml index d131c176a8..a740cc3d2e 100644 --- a/packages/llm/llm/README.i18n.yaml +++ b/packages/llm/llm/README.i18n.yaml @@ -24,8 +24,8 @@ en: cf221d60fb42a278 zh: 0ea17503495d386b /deepseek-ai-dsh-llm/use-this-package/what-you-can-do: - en: dc61eb86585f6e0d - zh: 9c0d6b240dfd2cda + en: cb9f0c6ee3203ab3 + zh: 8513340a40192513 /deepseek-ai-dsh-llm/use-this-package/failures-and-recovery: en: 47f4dab3c377a4cd zh: 49ac1c366de19136 @@ -36,8 +36,8 @@ en: 12d0444c18a397c7 zh: 9d4a5468b4bb7fcd /deepseek-ai-dsh-llm/understand-the-implementation/source-map: - en: ae1618577f4e8364 - zh: a6e8ab1563c08dfb + en: 8ec1ca8903e09bc0 + zh: 77c7bc3413cbab1c /deepseek-ai-dsh-llm/understand-the-implementation/main-flow: en: c95d4947745e39bb zh: ec37b969f27629e2 diff --git a/packages/llm/llm/README.md b/packages/llm/llm/README.md index 25718cdca3..ddba38e4da 100644 --- a/packages/llm/llm/README.md +++ b/packages/llm/llm/README.md @@ -83,6 +83,7 @@ const configure = (maxTokens: number): ConfigureCall => ### What you can do +- **Extract content text** — `extractTextContent(content, options?)` from `@deepseek-ai/dsh-llm/message` joins only `text` blocks in order, preserving whitespace and empty text blocks while omitting all other block types without placeholders. The optional `options.separator` defaults to `''`. It accepts read-only content and returns `''` when no text blocks exist. - **Stream one model call** — `ctx.llm.stream(options)` yields raw chunks (token-level deltas) for any registered provider and model; consumers assemble them with `BlockAssembler`. - **Register provider adapters** — an adapter owns one or more provider routes, and its registration captures that route's retry policy; registering the same route twice fails with `DUPLICATE_ADAPTER`. - **Expose and activate providers through configuration** — adapters declare configurable-provider routes plus a settings namespace, so configuration surfaces can activate dormant providers and edit connection facts without a restart. `LlmConfigurableProvider.error` reports a configuration diagnostic for repair; unaffected models can remain serviceable. An entry can also carry `defaultBaseURL`, the endpoint the adapter uses when the profile sets none, and `nativeAuth`, the environment variables and OAuth sign-in that the adapter's authentication reads when the profile names no credential reference; `baseURLEnv` lists environment variables used to configure the endpoint. Configuration UIs read these fields from the directory without calling the adapter. @@ -114,7 +115,7 @@ The service is built on one separation: **the logical contract is provider-neutr |---|---| | [`src/index.ts`](src/index.ts) | The `LlmRuntime` service: adapter registry, configurable-provider directory, model discovery, call preparation, and the streaming boundary | | [`src/types.ts`](src/types.ts) | The `StreamChunk` protocol, content-block map, finish reasons, and shared vocabulary | -| [`src/message.ts`](src/message.ts) | Immutable message constructors shared by delivery, history, and requests | +| [`src/message.ts`](src/message.ts) | Content text extraction and immutable message constructors shared by delivery, history, and requests | | [`src/assembler.ts`](src/assembler.ts) | `BlockAssembler`: incremental chunk-to-block assembly | | [`src/assistant-stream.ts`](src/assistant-stream.ts) | Compact timed Assistant stream accumulation, strict validation, exact expansion, and record-level readers | | [`src/call-config.ts`](src/call-config.ts) | Call-config validation, adapter-default materialization, and request freezing | diff --git a/packages/llm/llm/README.zh.md b/packages/llm/llm/README.zh.md index ee45bdbb9f..8373531ba5 100644 --- a/packages/llm/llm/README.zh.md +++ b/packages/llm/llm/README.zh.md @@ -83,6 +83,7 @@ const configure = (maxTokens: number): ConfigureCall => ### 你可以做什么 +- **提取内容文本**——从 `@deepseek-ai/dsh-llm/message` 导入的 `extractTextContent(content, options?)` 按顺序仅拼接 `text` 块,保留空白与空文本块,忽略所有其他块类型且不生成占位符。可选的 `options.separator` 默认为 `''`。它接受只读内容,没有文本块时返回 `''`。 - **流式发起一次模型调用**——`ctx.llm.stream(options)` 为任何已注册提供方与模型产出原始分片(token 级增量);消费方用 `BlockAssembler` 组装。 - **注册提供方适配器**——一个适配器拥有一个或多个提供方路由,其注册会捕获该路由的重试策略;重复注册同一路由会以 `DUPLICATE_ADAPTER` 失败。 - **通过配置暴露并激活提供方**——适配器声明可配置提供方路由与 settings namespace,配置界面因此可以激活休眠提供方并编辑连接信息,无需重启。`LlmConfigurableProvider.error` 报告供修复的配置诊断;未受影响的模型仍可提供服务。条目还可携带 `defaultBaseURL`,即配置未设置端点时适配器使用的端点;以及 `nativeAuth`,即配置未指定凭据引用时适配器认证读取的环境变量与 OAuth 登录;`baseURLEnv` 列出配置端点所用的环境变量。配置界面直接从目录读取这些字段,无需调用适配器。 @@ -114,7 +115,7 @@ const configure = (maxTokens: number): ConfigureCall => |---|---| | [`src/index.ts`](src/index.ts) | `LlmRuntime` 服务:适配器注册表、可配置提供方目录、模型发现、调用准备与流式边界 | | [`src/types.ts`](src/types.ts) | `StreamChunk` 协议、内容块映射、结束原因与共享词汇 | -| [`src/message.ts`](src/message.ts) | 投递、历史与请求共享的不可变消息构造函数 | +| [`src/message.ts`](src/message.ts) | 内容文本提取与投递、历史、请求共享的不可变消息构造函数 | | [`src/assembler.ts`](src/assembler.ts) | `BlockAssembler`:分片到块的增量组装 | | [`src/assistant-stream.ts`](src/assistant-stream.ts) | 带时间信息的紧凑 Assistant 流累积、严格校验、精确展开与记录级读取器 | | [`src/call-config.ts`](src/call-config.ts) | 调用配置校验、适配器默认值填入与请求冻结 | diff --git a/packages/llm/llm/src/index.ts b/packages/llm/llm/src/index.ts index 2f4299d8cd..5271c50291 100644 --- a/packages/llm/llm/src/index.ts +++ b/packages/llm/llm/src/index.ts @@ -49,7 +49,11 @@ export * from './api-key.ts' export * from './types.ts' export * from './content.ts' export * from './assistant-stream.ts' -export * from './message.ts' +export type * from './message.ts' +export { + CONTEXT_SUMMARY_MAX_CHARS, boundContextSummary, createAssistantMessage, createDeveloperMessage, createMessage, + createSystemMessage, createToolResultMessage, createUserMessage, freezeMessage, +} from './message.ts' export * from './retry-policy.ts' export { BlockAssembler } from './assembler.ts' export { callConfigEquals, isAgentLoopRequest, markAgentLoopRequest } from './call-config.ts' diff --git a/packages/llm/llm/src/message.ts b/packages/llm/llm/src/message.ts index d96a63edb6..175c1c5f7c 100644 --- a/packages/llm/llm/src/message.ts +++ b/packages/llm/llm/src/message.ts @@ -1,4 +1,4 @@ -/** Message value types, identity, and immutable construction helpers. */ +/** Message value types, content text extraction, identity, and immutable construction helpers. */ import { randomUUID } from '@deepseek-ai/dsh-util-crypto' import { brandString } from '@deepseek-ai/dsh-brand' @@ -305,3 +305,16 @@ export function createToolResultMessage(input: ToolResultMessageInput): ToolResu isError: input.isError, }) } + +/** + * Extract and join only text blocks in content order, preserving their whitespace. + * Non-text blocks contribute neither text nor separators; content is not modified. + * Import from `@deepseek-ai/dsh-llm/message` in Host and browser code. + * @param content - source blocks to read in their existing order. + * @param options - optional text extraction settings. + * @param options.separator - text inserted between text blocks; defaults to an empty string. + * @returns joined text, or an empty string when no text blocks are present. + */ +export function extractTextContent(content: readonly ContentBlock[], options?: { separator?: string }): string { + return content.filter(block => block.type === 'text').map(block => block.text).join(options?.separator ?? '') +} diff --git a/packages/llm/llm/tests/message.spec.ts b/packages/llm/llm/tests/message.spec.ts index 1f05272fba..5b43013c79 100644 --- a/packages/llm/llm/tests/message.spec.ts +++ b/packages/llm/llm/tests/message.spec.ts @@ -1,4 +1,5 @@ import { describe, expect, expectTypeOf, it } from 'vitest' +import { AttachmentId } from '@deepseek-ai/dsh-attachment' import { ToolCallId, boundContextSummary, @@ -11,6 +12,46 @@ import { freezeMessage, MessageId, } from '@deepseek-ai/dsh-llm' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' + +describe('extractTextContent', () => { + it('preserves whitespace and empty text blocks while omitting non-text blocks', () => { + const message = createUserMessage({ + source: { kind: 'test' }, + content: [ + { type: 'text', text: ' \talpha\n' }, + { type: 'reasoning', text: 'private reasoning' }, + { type: 'image', attachment: { + attachmentId: AttachmentId(`sha256:${'a'.repeat(64)}`), + mediaType: 'image/png', bytes: 1, width: 1, height: 1, + } }, + { type: 'tool-call', id: ToolCallId('call'), name: 'tool', arguments: '{}' }, + { type: 'text', text: '' }, + { type: 'tool-removal', toolName: 'removed' }, + { type: 'text', text: 'β \r\n' }, + ], + }) + expect(extractTextContent(message.content)).toBe(' \talpha\nβ \r\n') + expect(extractTextContent(message.content, undefined)).toBe(' \talpha\nβ \r\n') + expect(extractTextContent(message.content, {})).toBe(' \talpha\nβ \r\n') + expect(extractTextContent(message.content, { separator: '' })).toBe(' \talpha\nβ \r\n') + expect(extractTextContent(message.content, { separator: '\n' })).toBe(' \talpha\n\n\nβ \r\n') + expect(extractTextContent(message.content, { separator: ' ' })).toBe(' \talpha\n β \r\n') + expect(extractTextContent(message.content, { separator: '::' })).toBe(' \talpha\n::::β \r\n') + expect(Object.isFrozen(message.content)).toBe(true) + expect(message.content[0]).toEqual({ type: 'text', text: ' \talpha\n' }) + }) + + it('returns empty text when there are no text blocks and keeps separators between empty text blocks', () => { + expect(extractTextContent([])).toBe('') + expect(extractTextContent([{ type: 'reasoning', text: 'not plain text' }], { separator: '\n' })).toBe('') + expect(extractTextContent([ + { type: 'text', text: '' }, + { type: 'reasoning', text: 'ignored' }, + { type: 'text', text: '' }, + ], { separator: '\n' })).toBe('\n') + }) +}) describe('message construction', () => { it('detaches and freezes developer tool names without copying their definitions', () => { diff --git a/packages/sdk/server/src/query-activity.ts b/packages/sdk/server/src/query-activity.ts index 17a4fc9148..7bf4c8b7bf 100644 --- a/packages/sdk/server/src/query-activity.ts +++ b/packages/sdk/server/src/query-activity.ts @@ -1,5 +1,7 @@ /** Observe command-admitted activity through quiescence and preserve a goal's first terminal outcome. */ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' + import type { Context } from '@deepseek-ai/cordis' import type { Agent } from '@deepseek-ai/dsh-agent' import type { GoalView } from '@deepseek-ai/dsh-goal' @@ -63,7 +65,7 @@ export class QueryActivity { } if (this.input || this.goalId !== undefined) { if (event.type === 'assistant/message') { - this.response = event.data.message.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('') + this.response = extractTextContent(event.data.message.content) } if (event.type === 'turn/end') this.turnReason = event.data.reason.kind } diff --git a/packages/session/session-title-first-prompt-llm/src/index.ts b/packages/session/session-title-first-prompt-llm/src/index.ts index 1cd6aa26ea..046525130e 100644 --- a/packages/session/session-title-first-prompt-llm/src/index.ts +++ b/packages/session/session-title-first-prompt-llm/src/index.ts @@ -3,7 +3,8 @@ /* jscpd:ignore-start -- both shipped providers import the same shared packages. */ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' -import type { LlmResolvedModelInfo, ReasoningEffortId } from '@deepseek-ai/dsh-llm' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' +import { type LlmResolvedModelInfo, type ReasoningEffortId } from '@deepseek-ai/dsh-llm' import { assertNever } from '@deepseek-ai/dsh-util-values' import { normalizeSessionTitle, @@ -127,10 +128,7 @@ function titleFromResponse(response: SessionTitleLlmResponse): string { if (response.blocks.some(block => block.type === 'tool-call')) { throw new Error('session-title-llm: title output must contain text only') } - const text = response.blocks - .filter((block): block is Extract<(typeof response.blocks)[number], { type: 'text' }> => block.type === 'text') - .map(block => block.text) - .join(' ') + const text = extractTextContent(response.blocks, { separator: ' ' }) const title = normalizeSessionTitle(titleFromOutput(text), Number.MAX_SAFE_INTEGER) if (title.length === 0) throw new Error('session-title-llm: title model produced no text') return title diff --git a/packages/session/session-title/src/index.ts b/packages/session/session-title/src/index.ts index c80ae7e830..9917187dba 100644 --- a/packages/session/session-title/src/index.ts +++ b/packages/session/session-title/src/index.ts @@ -8,6 +8,7 @@ import z from '@deepseek-ai/schemastery' import { z as zod } from 'zod' import type { ZodType } from 'zod' import type { Branded } from '@deepseek-ai/dsh-brand' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { isAgentLoopRequest } from '@deepseek-ai/dsh-llm' import type { GenerateOptions } from '@deepseek-ai/dsh-llm' import { assertNever, deepFreeze } from '@deepseek-ai/dsh-util-values' @@ -137,10 +138,7 @@ export interface SessionTitleProvider { function sessionTitleUserMessageOf(event: SessionEvent): SessionTitleUserMessage | undefined { if (event.type !== 'user/message' || event.data.source.kind !== 'user') return undefined const content = event.data.content - const text = content - .filter((block): block is Extract<(typeof content)[number], { type: 'text' }> => block.type === 'text') - .map(block => block.text) - .join('\n') + const text = extractTextContent(content, { separator: '\n' }) if (normalizeSessionTitle(text, Number.MAX_SAFE_INTEGER).length === 0) return undefined return { seq: event.seq, text } } diff --git a/packages/web/web-deepseek-api/src/index.ts b/packages/web/web-deepseek-api/src/index.ts index 555bab178b..4da54814ea 100644 --- a/packages/web/web-deepseek-api/src/index.ts +++ b/packages/web/web-deepseek-api/src/index.ts @@ -21,7 +21,8 @@ import z from '@deepseek-ai/schemastery' import type {} from '@deepseek-ai/dsh-agent' import { credentialRef, type CredentialRef } from '@deepseek-ai/dsh-credentials' import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment' -import type {} from '@deepseek-ai/dsh-llm' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' + import { deepSeekApiKeyConfigured, rejectDeepSeekAccountToken, resolveDeepSeekAccountToken, resolveDeepSeekApiKey, } from '@deepseek-ai/dsh-llm-deepseek' @@ -156,7 +157,7 @@ const CAPABILITY = { function latestUserQuestion(session: Session | undefined): string | undefined { const prompt = session?.deriveMessages().findLast(message => message.role === 'user' && message.source.kind === 'user') if (prompt === undefined) return undefined - return prompt.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('\n') + return extractTextContent(prompt.content, { separator: '\n' }) } /** diff --git a/packages/workflow/workflow-ptc/src/guest-source.ts b/packages/workflow/workflow-ptc/src/guest-source.ts index 52313de66a..e35a126855 100644 --- a/packages/workflow/workflow-ptc/src/guest-source.ts +++ b/packages/workflow/workflow-ptc/src/guest-source.ts @@ -1,4 +1,4 @@ /** Generated by scripts/gen-workflow-guest.ts. Do not edit directly. */ /** Self-contained ESM guest transported into the mounted PTC runtime. */ -export const WORKFLOW_GUEST_SOURCE = "import * as vm from \"node:vm\";\n//#region packages/workflow/workflow-ptc/src/realm.ts\n/**\n* Materializes script VM values as plain JSON and renders thrown values.\n* Getters and proxy traps may execute inside the confined Node process;\n* process isolation and cancellation belong to PTC, not the VM.\n* @module @deepseek-ai/dsh-workflow-ptc/realm\n*/\n/** Thrown by {@link materializeFromRealm}; the caller wraps it into the right `WorkflowError` code. */\nvar MaterializeError = class extends Error {\n\tpath;\n\treason;\n\tconstructor(path, reason) {\n\t\tsuper(`${path}: ${reason}`);\n\t\tthis.path = path;\n\t\tthis.reason = reason;\n\t\tthis.name = \"MaterializeError\";\n\t}\n};\n/**\n* Render a thrown value to failure text without ever throwing: prefer the\n* `stack` (host or realm — a realm error's `stack` is a plain string read),\n* fall back to `message`, then `String()`. Reading those properties MAY run\n* script code; if that code itself throws, a fixed label is returned instead.\n* @param error - any value thrown in the host or guest realm.\n* @returns human-readable text for the failure report; prefers the stack.\n*/\nfunction renderThrown(error) {\n\ttry {\n\t\tconst stack = error?.stack;\n\t\tif (typeof stack === \"string\" && stack.length > 0) return stack;\n\t\tconst message = error?.message;\n\t\tif (typeof message === \"string\" && message.length > 0) return message;\n\t\treturn String(error);\n\t} catch {\n\t\treturn \"[unrenderable thrown value]\";\n\t}\n}\n/**\n* Whether an object's prototype chain represents a plain data object: `null`, or a prototype\n* whose own prototype is `null` (the realm's `Object.prototype` — which we\n* cannot compare by identity across realms). A `Date`/`Map`/class instance\n* has a longer chain and is rejected.\n*/\nfunction hasPlainPrototype(value) {\n\tconst proto = Object.getPrototypeOf(value);\n\tif (proto === null) return true;\n\treturn Object.getPrototypeOf(proto) === null;\n}\n/**\n* Copy `value` (typically from the vm realm) into plain host JSON data. Root `undefined` is\n* returned unchanged; nested `undefined` and values JSON cannot represent losslessly fail\n* with the offending path. Property accessors run normally, and a throwing read is wrapped\n* with its rendered failure.\n*\n* @param value - the realm value to materialize.\n* @param root - the path label for the root value (error messages).\n* @returns the host-realm copy (plain objects/arrays/scalars only).\n* @throws {@link MaterializeError} for unsupported values, cycles, sparse arrays, exotic\n* prototypes, or property reads that throw.\n*/\nfunction materializeFromRealm(value, root = \"value\") {\n\tif (value === void 0) return void 0;\n\ttry {\n\t\treturn materialize(value, root, /* @__PURE__ */ new Set());\n\t} catch (error) {\n\t\tif (error instanceof MaterializeError) throw error;\n\t\tthrow new MaterializeError(root, `reading the value threw: ${renderThrown(error)}`);\n\t}\n}\nfunction materialize(value, path, seen) {\n\tswitch (typeof value) {\n\t\tcase \"boolean\":\n\t\tcase \"string\": return value;\n\t\tcase \"number\":\n\t\t\tif (!Number.isFinite(value)) throw new MaterializeError(path, \"non-finite numbers are not JSON data\");\n\t\t\treturn value;\n\t\tcase \"bigint\": throw new MaterializeError(path, \"bigints are not JSON data\");\n\t\tcase \"function\": throw new MaterializeError(path, \"functions are not plain JSON data\");\n\t\tcase \"symbol\": throw new MaterializeError(path, \"symbols are not plain JSON data\");\n\t\tcase \"undefined\": throw new MaterializeError(path, \"undefined is not JSON data\");\n\t\tcase \"object\": break;\n\t}\n\tif (value === null) return null;\n\tconst objectValue = value;\n\tif (seen.has(objectValue)) throw new MaterializeError(path, \"circular references are not JSON data\");\n\tseen.add(objectValue);\n\ttry {\n\t\tif (Array.isArray(objectValue)) return materializeArray(objectValue, path, seen);\n\t\treturn materializeObject(objectValue, path, seen);\n\t} finally {\n\t\tseen.delete(objectValue);\n\t}\n}\nfunction materializeArray(value, path, seen) {\n\tconst out = [];\n\tfor (let index = 0; index < value.length; index++) {\n\t\tif (!(index in value)) throw new MaterializeError(`${path}[${index}]`, \"sparse arrays are not JSON data\");\n\t\tout.push(materialize(value[index], `${path}[${index}]`, seen));\n\t}\n\tfor (const key of Object.keys(value)) {\n\t\tconst index = Number(key);\n\t\tif (!Number.isInteger(index) || index < 0 || index >= value.length) throw new MaterializeError(`${path}.${key}`, \"arrays with non-index properties are not JSON data\");\n\t}\n\tif (Object.getOwnPropertySymbols(value).length > 0) throw new MaterializeError(path, \"symbol-keyed properties are not plain JSON data\");\n\treturn out;\n}\nfunction materializeObject(value, path, seen) {\n\tif (!hasPlainPrototype(value)) throw new MaterializeError(path, \"only plain objects and arrays are JSON data (exotic prototype)\");\n\tif (Object.getOwnPropertySymbols(value).length > 0) throw new MaterializeError(path, \"symbol-keyed properties are not plain JSON data\");\n\tconst out = {};\n\tfor (const key of Object.keys(value)) Object.defineProperty(out, key, {\n\t\tvalue: materialize(value[key], `${path}.${key}`, seen),\n\t\tenumerable: true,\n\t\twritable: true,\n\t\tconfigurable: true\n\t});\n\treturn out;\n}\n//#endregion\n//#region packages/util/brand/src/index.ts\n/**\n* Apply a compile-time string brand without changing the value.\n* @param value - string admitted by the domain that owns the target brand.\n* @returns the same string with the requested compile-time brand.\n*/\nfunction brandString(value) {\n\treturn value;\n}\n//#endregion\n//#region packages/util/error/src/index.ts\n/**\n* Harness error base with a stable machine-routable code and chained cause.\n* Package errors extend it so tool results and replay can retain failure class.\n* @module @deepseek-ai/dsh-error\n*/\n/**\n* Base class for all harness errors. Carries a `code` (stable, programmatic —\n* e.g. `NO_ADAPTER`, `INVALID_ARGS`) distinct from the\n* human-readable `message`, and supports `cause` chaining via the standard\n* `ErrorOptions`. `name` defaults to the subclass constructor name.\n*/\nvar HarnessError = class extends Error {\n\t/** Stable machine-routable failure class (e.g. `RATE_LIMIT`); route on this, never by parsing `message`. */\n\tcode;\n\tconstructor(message, code, options) {\n\t\tsuper(message, options);\n\t\tthis.code = code;\n\t\tthis.name = new.target.name;\n\t}\n};\n//#endregion\n//#region packages/util/values/src/index.ts\n/**\n* Mark an unreachable closed-union branch.\n* @param value - impossible value; an unhandled typed variant fails at the call site.\n* @param context - optional switch-site label included in the failure message.\n* @returns never; a runtime value that escaped its type always throws.\n*/\nfunction assertNever(value, context) {\n\tconst rendered = JSON.stringify(value) ?? String(value);\n\tthrow new Error(`unreachable variant${context ? ` in ${context}` : \"\"}: ${rendered}`);\n}\n/** Whether a realm-owned intrinsic prototype has a native constructor matching this engine's representation. */\nfunction hasIntrinsicConstructor$1(prototype, name) {\n\tconst constructor = Object.getOwnPropertyDescriptor(prototype, \"constructor\")?.value;\n\tif (typeof constructor !== \"function\") return false;\n\ttry {\n\t\treturn constructor.name === name && constructor.prototype === prototype && Function.prototype.toString.call(constructor) === Function.prototype.toString.call(name === \"Array\" ? Array : Object);\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Whether a candidate is one realm's intrinsic `Object.prototype`. */\nfunction isIntrinsicObjectPrototype$1(value) {\n\treturn Object.getPrototypeOf(value) === null && hasIntrinsicConstructor$1(value, \"Object\");\n}\n/** Whether an array uses one realm's intrinsic `Array.prototype`, not a subclass or forged prototype. */\nfunction hasPlainArrayPrototype$1(value) {\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (!Array.isArray(prototype) || !hasIntrinsicConstructor$1(prototype, \"Array\")) return false;\n\tconst objectPrototype = Object.getPrototypeOf(prototype);\n\treturn typeof objectPrototype === \"object\" && objectPrototype !== null && isIntrinsicObjectPrototype$1(objectPrototype);\n}\n/** Whether an object is a plain or null-prototype record from any JavaScript realm. */\nfunction hasPlainObjectPrototype(value) {\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === null || typeof prototype === \"object\" && isIntrinsicObjectPrototype$1(prototype);\n}\n/** Return every JSON-visible object key, or reject own data JSON would discard. */\nfunction enumerableStringKeys(value) {\n\tconst keys = Reflect.ownKeys(value);\n\tif (keys.some((key) => typeof key !== \"string\" || !Object.prototype.propertyIsEnumerable.call(value, key))) return void 0;\n\treturn keys;\n}\n/** Validate lossless JSON iteratively, optionally materializing a detached snapshot. */\nfunction walkJsonValue(value, detach) {\n\tconst ancestors = /* @__PURE__ */ new Set();\n\tlet root;\n\tlet parent;\n\tconst assign = (item) => {\n\t\tif (parent === void 0) {\n\t\t\tif (detach) root = item;\n\t\t} else if (parent.kind === \"array\") {\n\t\t\tif (parent.target !== void 0) parent.target[parent.key] = item;\n\t\t} else if (parent.target !== void 0) Object.defineProperty(parent.target, parent.key, {\n\t\t\tvalue: item,\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true\n\t\t});\n\t};\n\tconst frames = [];\n\tlet current = value;\n\tfor (;;) {\n\t\tif (current === null) assign(null);\n\t\telse if (typeof current === \"boolean\" || typeof current === \"string\") assign(current);\n\t\telse if (typeof current === \"number\") {\n\t\t\tif (!Number.isFinite(current) || Object.is(current, -0)) return void 0;\n\t\t\tassign(current);\n\t\t} else {\n\t\t\tif (typeof current !== \"object\") return void 0;\n\t\t\tif (ancestors.has(current)) return void 0;\n\t\t\tif (Array.isArray(current)) {\n\t\t\t\tif (!hasPlainArrayPrototype$1(current)) return void 0;\n\t\t\t\tconst length = current.length;\n\t\t\t\tif (Reflect.ownKeys(current).length !== length + 1) return void 0;\n\t\t\t\tconst target = detach ? [] : void 0;\n\t\t\t\tif (target !== void 0) assign(target);\n\t\t\t\tlet indices;\n\t\t\t\tif (!Number.isInteger(length)) {\n\t\t\t\t\tindices = [];\n\t\t\t\t\tfor (let index = length - 1; index >= 0; index--) indices.push(index);\n\t\t\t\t}\n\t\t\t\tframes.push({\n\t\t\t\t\tkind: \"array\",\n\t\t\t\t\tsource: current,\n\t\t\t\t\tlength: indices?.length ?? length,\n\t\t\t\t\tindex: 0,\n\t\t\t\t\tkey: 0,\n\t\t\t\t\tindices,\n\t\t\t\t\ttarget\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tif (!hasPlainObjectPrototype(current)) return void 0;\n\t\t\t\tconst keys = enumerableStringKeys(current);\n\t\t\t\tif (keys === void 0) return void 0;\n\t\t\t\tconst target = detach ? {} : void 0;\n\t\t\t\tif (target !== void 0) assign(target);\n\t\t\t\tframes.push({\n\t\t\t\t\tkind: \"object\",\n\t\t\t\t\tsource: current,\n\t\t\t\t\tkeys,\n\t\t\t\t\tindex: 0,\n\t\t\t\t\tkey: \"\",\n\t\t\t\t\ttarget\n\t\t\t\t});\n\t\t\t}\n\t\t\tancestors.add(current);\n\t\t}\n\t\tfor (;;) {\n\t\t\tconst frame = frames.at(-1);\n\t\t\tif (frame === void 0) return detach ? root : true;\n\t\t\tconst length = frame.kind === \"array\" ? frame.length : frame.keys.length;\n\t\t\tif (frame.index >= length) {\n\t\t\t\tancestors.delete(frame.source);\n\t\t\t\tframes.pop();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst index = frame.index++;\n\t\t\tparent = frame;\n\t\t\tif (frame.kind === \"array\") {\n\t\t\t\tconst key = frame.indices === void 0 ? index : frame.indices[frame.indices.length - index - 1];\n\t\t\t\t/* v8 ignore next -- the loop is bounded by the captured index count. */\n\t\t\t\tif (key === void 0) return void 0;\n\t\t\t\tif (!Object.prototype.hasOwnProperty.call(frame.source, key)) return void 0;\n\t\t\t\tframe.key = key;\n\t\t\t\tcurrent = frame.source[key];\n\t\t\t} else {\n\t\t\t\tconst key = frame.keys[index];\n\t\t\t\t/* v8 ignore next -- the loop is bounded by the captured key count. */\n\t\t\t\tif (key === void 0) return void 0;\n\t\t\t\tframe.key = key;\n\t\t\t\tcurrent = frame.source[key];\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n}\n/**\n* Test the same lossless JSON rules as {@link snapshotJsonValue} without detaching the value.\n* @param value - candidate value to test.\n* @returns whether the value survives a JSON round trip without loss.\n*/\nfunction isJsonValue(value) {\n\treturn walkJsonValue(value, false) === true;\n}\n//#endregion\n//#region packages/core/tools/src/json-schema.ts\n/**\n* Enforced JSON Schema subset shared by tool outputs, generated PTC mode\n* types, subagents, and workflows. The subset accepts any JSON root, an\n* annotation-only schema for unconstrained JSON, one scalar `type`, object\n* `properties`/`required`/boolean `additionalProperties`, array `items`,\n* type-correct scalar `enum`/`const`, and exact-one `oneOf`.\n*\n* Unsupported or misplaced keywords reject rather than being accepted without\n* enforcement. Consumers that require an object root apply\n* {@link assertObjectJsonSchema} before accepting input.\n* @module dsh-tools/json-schema\n*/\n/**\n* Thrown when a raw schema falls outside the enforced subset. `violations`\n* lists every offending path instead of stopping at the first author error.\n*/\nvar JsonSchemaError = class extends HarnessError {\n\t/** Individual schema violations in walk order. */\n\tviolations;\n\tconstructor(violations) {\n\t\tsuper(`unsupported JSON schema: ${violations.join(\"; \")}`, \"UNSUPPORTED_SCHEMA\");\n\t\tthis.name = \"JsonSchemaError\";\n\t\tthis.violations = violations;\n\t}\n};\nconst CONSTRAINT_KEYWORDS = new Set([\n\t\"type\",\n\t\"oneOf\",\n\t\"properties\",\n\t\"required\",\n\t\"additionalProperties\",\n\t\"items\",\n\t\"enum\",\n\t\"const\"\n]);\nconst ANNOTATION_KEYWORDS = new Set([\n\t\"description\",\n\t\"title\",\n\t\"default\",\n\t\"examples\"\n]);\nconst SCHEMA_TYPES = [\n\t\"object\",\n\t\"array\",\n\t\"string\",\n\t\"number\",\n\t\"integer\",\n\t\"boolean\",\n\t\"null\"\n];\n/** Whether a realm-owned intrinsic prototype is backed by its native constructor. */\nfunction hasIntrinsicConstructor(prototype, name) {\n\tconst constructor = Object.getOwnPropertyDescriptor(prototype, \"constructor\")?.value;\n\tif (typeof constructor !== \"function\") return false;\n\ttry {\n\t\treturn constructor.name === name && constructor.prototype === prototype && Function.prototype.toString.call(constructor) === `function ${name}() { [native code] }`;\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Whether a candidate is one realm's intrinsic `Object.prototype`. */\nfunction isIntrinsicObjectPrototype(value) {\n\treturn Object.getPrototypeOf(value) === null && hasIntrinsicConstructor(value, \"Object\");\n}\n/**\n* Test for a realm-agnostic plain JSON record without accepting arrays or\n* exotic objects.\n* @param value - candidate record from any JavaScript realm.\n* @returns Whether the value has a plain-object prototype chain.\n*/\nfunction isPlainJsonRecord(value) {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n\ttry {\n\t\tconst prototype = Object.getPrototypeOf(value);\n\t\treturn prototype === null || typeof prototype === \"object\" && isIntrinsicObjectPrototype(prototype);\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Whether an array uses one realm's intrinsic `Array.prototype`. */\nfunction hasPlainArrayPrototype(value) {\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (!Array.isArray(prototype) || !hasIntrinsicConstructor(prototype, \"Array\")) return false;\n\tconst objectPrototype = Object.getPrototypeOf(prototype);\n\treturn typeof objectPrototype === \"object\" && objectPrototype !== null && isIntrinsicObjectPrototype(objectPrototype);\n}\n/** Return whether a record contains only own enumerable string keys. */\nfunction hasOnlyEnumerableStringKeys(value) {\n\ttry {\n\t\treturn Reflect.ownKeys(value).every((key) => typeof key === \"string\" && Object.prototype.propertyIsEnumerable.call(value, key));\n\t} catch {\n\t\treturn false;\n\t}\n}\n/**\n* Test for an ordinary schema record whose keys survive JSON projection.\n* @param value - candidate record from any JavaScript realm.\n* @returns Whether the record has an intrinsic prototype and only own enumerable string keys.\n*/\nfunction isJsonSchemaRecord(value) {\n\treturn isPlainJsonRecord(value) && hasOnlyEnumerableStringKeys(value);\n}\n/**\n* Test for a dense ordinary array with no JSON-invisible decorations.\n* @param value - candidate array from any JavaScript realm.\n* @returns Whether the array is intrinsic, dense, and undecorated.\n*/\nfunction isPlainJsonArray(value) {\n\tif (!Array.isArray(value)) return false;\n\ttry {\n\t\tif (!hasPlainArrayPrototype(value) || Reflect.ownKeys(value).length !== value.length + 1) return false;\n\t\tfor (let index = 0; index < value.length; index++) if (!Object.hasOwn(value, index)) return false;\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Lossless finite JSON number, excluding negative zero. */\nfunction isJsonNumber(value) {\n\treturn typeof value === \"number\" && Number.isFinite(value) && !Object.is(value, -0);\n}\n/** Whether a scalar is valid for one declared schema type. */\nfunction scalarMatches(type, value) {\n\tswitch (type) {\n\t\tcase \"string\": return typeof value === \"string\";\n\t\tcase \"number\": return isJsonNumber(value);\n\t\tcase \"integer\": return isJsonNumber(value) && Number.isInteger(value);\n\t\tcase \"boolean\": return typeof value === \"boolean\";\n\t\tcase \"null\": return value === null;\n\t\t/* v8 ignore next -- JsonSchemaScalarType is closed; this retains compile-time exhaustiveness. */\n\t\tdefault: return assertNever(type, \"JsonSchemaType\");\n\t}\n}\n/** Keywords that are invalid beside `oneOf`. */\nconst ONE_OF_SIBLING_KEYWORDS = [\n\t\"properties\",\n\t\"required\",\n\t\"additionalProperties\",\n\t\"items\",\n\t\"enum\",\n\t\"const\"\n];\n/** Validate object-only fields after its property schemas have been visited. */\nfunction checkObjectSchemaTail(node, path, properties, violations) {\n\tconst hasRequired = Object.hasOwn(node, \"required\");\n\tconst required = hasRequired ? node.required : void 0;\n\tif (hasRequired) if (!isPlainJsonArray(required) || required.some((entry) => typeof entry !== \"string\")) violations.push(`${path}.required must be an array of strings`);\n\telse {\n\t\tconst declared = isJsonSchemaRecord(properties) ? properties : {};\n\t\tfor (const key of required) if (!Object.hasOwn(declared, key)) violations.push(`${path}.required names \"${key}\" which is not in properties`);\n\t}\n\tif (Object.hasOwn(node, \"additionalProperties\") && typeof node.additionalProperties !== \"boolean\") violations.push(`${path}.additionalProperties must be a boolean`);\n}\n/** Collect every violation for one raw schema tree without using the JavaScript call stack. */\nfunction checkSchemaNode(root, rootPath, violations, seen) {\n\tconst tasks = [{\n\t\tkind: \"enter\",\n\t\tnode: root,\n\t\tpath: rootPath\n\t}];\n\tfor (let task = tasks.pop(); task !== void 0; task = tasks.pop()) {\n\t\tif (task.kind === \"leave\") {\n\t\t\tseen.delete(task.node);\n\t\t\tcontinue;\n\t\t}\n\t\tif (task.kind === \"one-of-tail\") {\n\t\t\tfor (const key of ONE_OF_SIBLING_KEYWORDS) if (Object.hasOwn(task.node, key)) violations.push(`${task.path}.${key} is not supported beside oneOf`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (task.kind === \"object-tail\") {\n\t\t\tcheckObjectSchemaTail(task.node, task.path, task.properties, violations);\n\t\t\tcontinue;\n\t\t}\n\t\tconst { node, path } = task;\n\t\tif (!isJsonSchemaRecord(node)) {\n\t\t\tviolations.push(`${path} must be a schema object`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (seen.has(node)) {\n\t\t\tviolations.push(`${path} is circular`);\n\t\t\tcontinue;\n\t\t}\n\t\tseen.add(node);\n\t\ttasks.push({\n\t\t\tkind: \"leave\",\n\t\t\tnode\n\t\t});\n\t\tfor (const key of Object.keys(node)) {\n\t\t\tif (CONSTRAINT_KEYWORDS.has(key)) continue;\n\t\t\tif (ANNOTATION_KEYWORDS.has(key)) {\n\t\t\t\ttry {\n\t\t\t\t\tif (!isJsonValue(node[key])) violations.push(`${path}.${key} annotation must be lossless JSON data`);\n\t\t\t\t} catch {\n\t\t\t\t\tviolations.push(`${path}.${key} annotation must be lossless JSON data`);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tviolations.push(`${path}.${key} is not a supported keyword (subset: type/oneOf/properties/required/additionalProperties/items/enum/const + annotations)`);\n\t\t}\n\t\tif (Object.hasOwn(node, \"description\") && typeof node.description !== \"string\") violations.push(`${path}.description must be a string`);\n\t\tif (Object.hasOwn(node, \"title\") && typeof node.title !== \"string\") violations.push(`${path}.title must be a string`);\n\t\tconst hasType = Object.hasOwn(node, \"type\");\n\t\tconst hasOneOf = Object.hasOwn(node, \"oneOf\");\n\t\tif (hasType && hasOneOf) {\n\t\t\tviolations.push(`${path} cannot declare both type and oneOf`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!hasType && !hasOneOf) {\n\t\t\tfor (const key of ONE_OF_SIBLING_KEYWORDS) if (Object.hasOwn(node, key)) violations.push(`${path}.${key} requires type or oneOf`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (hasOneOf) {\n\t\t\tconst oneOf = node.oneOf;\n\t\t\ttasks.push({\n\t\t\t\tkind: \"one-of-tail\",\n\t\t\t\tnode,\n\t\t\t\tpath\n\t\t\t});\n\t\t\tif (!isPlainJsonArray(oneOf) || oneOf.length < 2) violations.push(`${path}.oneOf must be an array of at least two schemas`);\n\t\t\telse for (let index = oneOf.length - 1; index >= 0; index--) tasks.push({\n\t\t\t\tkind: \"enter\",\n\t\t\t\tnode: oneOf[index],\n\t\t\t\tpath: `${path}.oneOf[${index}]`\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst type = node.type;\n\t\tif (typeof type !== \"string\" || !SCHEMA_TYPES.includes(type)) {\n\t\t\tviolations.push(Array.isArray(type) ? `${path}.type must be a single type string (type arrays are not supported)` : `${path}.type must be one of ${SCHEMA_TYPES.join(\"/\")}`);\n\t\t\tcontinue;\n\t\t}\n\t\tconst schemaType = type;\n\t\tfor (const [key, types] of Object.entries({\n\t\t\tproperties: [\"object\"],\n\t\t\trequired: [\"object\"],\n\t\t\tadditionalProperties: [\"object\"],\n\t\t\titems: [\"array\"],\n\t\t\tenum: [\n\t\t\t\t\"string\",\n\t\t\t\t\"number\",\n\t\t\t\t\"integer\",\n\t\t\t\t\"boolean\",\n\t\t\t\t\"null\"\n\t\t\t],\n\t\t\tconst: [\n\t\t\t\t\"string\",\n\t\t\t\t\"number\",\n\t\t\t\t\"integer\",\n\t\t\t\t\"boolean\",\n\t\t\t\t\"null\"\n\t\t\t]\n\t\t})) if (Object.hasOwn(node, key) && !types.includes(schemaType)) violations.push(`${path}.${key} is not supported on type \"${schemaType}\"`);\n\t\tswitch (schemaType) {\n\t\t\tcase \"object\": {\n\t\t\t\tconst properties = Object.hasOwn(node, \"properties\") ? node.properties : void 0;\n\t\t\t\ttasks.push({\n\t\t\t\t\tkind: \"object-tail\",\n\t\t\t\t\tnode,\n\t\t\t\t\tpath,\n\t\t\t\t\tproperties\n\t\t\t\t});\n\t\t\t\tif (Object.hasOwn(node, \"properties\")) if (!isJsonSchemaRecord(properties)) violations.push(`${path}.properties must be an object of schemas`);\n\t\t\t\telse {\n\t\t\t\t\tconst entries = Object.entries(properties);\n\t\t\t\t\tfor (let index = entries.length - 1; index >= 0; index--) {\n\t\t\t\t\t\tconst entry = entries[index];\n\t\t\t\t\t\t/* v8 ignore next -- the loop is bounded by the captured entry count. */\n\t\t\t\t\t\tif (entry === void 0) continue;\n\t\t\t\t\t\ttasks.push({\n\t\t\t\t\t\t\tkind: \"enter\",\n\t\t\t\t\t\t\tnode: entry[1],\n\t\t\t\t\t\t\tpath: `${path}.properties.${entry[0]}`\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"array\":\n\t\t\t\tif (Object.hasOwn(node, \"items\")) tasks.push({\n\t\t\t\t\tkind: \"enter\",\n\t\t\t\t\tnode: node.items,\n\t\t\t\t\tpath: `${path}.items`\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"string\":\n\t\t\tcase \"number\":\n\t\t\tcase \"integer\":\n\t\t\tcase \"boolean\":\n\t\t\tcase \"null\": {\n\t\t\t\tconst hasEnum = Object.hasOwn(node, \"enum\");\n\t\t\t\tconst allowed = hasEnum ? node.enum : void 0;\n\t\t\t\tconst enumValid = isPlainJsonArray(allowed) && allowed.length > 0 && allowed.every((entry) => scalarMatches(schemaType, entry));\n\t\t\t\tif (hasEnum && !enumValid) violations.push(`${path}.enum must be a non-empty array of ${schemaType} values`);\n\t\t\t\tconst hasConst = Object.hasOwn(node, \"const\");\n\t\t\t\tconst declaredConst = hasConst ? node.const : void 0;\n\t\t\t\tconst constValid = scalarMatches(schemaType, declaredConst);\n\t\t\t\tif (hasConst) {\n\t\t\t\t\tif (!constValid) violations.push(`${path}.const must be a ${schemaType} value`);\n\t\t\t\t\telse if (enumValid && !allowed.includes(declaredConst)) violations.push(`${path}.const must be one of ${path}.enum when both are declared`);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t/* v8 ignore next -- schemaType was narrowed from the closed SCHEMA_TYPES table above. */\n\t\t\tdefault: assertNever(schemaType, \"JsonSchemaType\");\n\t\t}\n\t}\n}\n/**\n* Assert the enforced subset plus the object-root constraint retained by\n* subagent and workflow structured outputs.\n* @param schema - untrusted caller-supplied schema.\n* @returns Assertion that the schema belongs to the supported subset and has an object root.\n*/\nfunction assertObjectJsonSchema(schema) {\n\tconst violations = [];\n\tcheckSchemaNode(schema, \"schema\", violations, /* @__PURE__ */ new Set());\n\tif (violations.length === 0 && (!isJsonSchemaRecord(schema) || !Object.hasOwn(schema, \"type\") || schema.type !== \"object\")) violations.push(\"schema.type must be \\\"object\\\" (structured output is object-rooted)\");\n\tif (violations.length > 0) throw new JsonSchemaError(violations);\n}\n//#endregion\n//#region packages/workflow/workflow/src/index.ts\n/**\n* Typed error for workflow-seam failures. Extends {@link HarnessError}, so the\n* `code` is machine-routable taxonomy. `fatal` drives the combinator\n* discipline: `parallel()`/`pipeline()` re-throw a fatal error (a typo'd\n* option or a tripped cap must kill the script loudly), and reserve the\n* per-item `null` for child-run failures and ordinary in-stage script errors.\n* Every {@link WorkflowErrorCode} is fatal; the flag exists so the\n* distinction is explicit at every catch site rather than implied.\n*/\nvar WorkflowError = class extends HarnessError {\n\t/** Whether combinators must propagate this error instead of nulling the item. */\n\tfatal;\n\tconstructor(message, code, options) {\n\t\tsuper(message, code, options);\n\t\tthis.name = \"WorkflowError\";\n\t\tthis.fatal = options?.fatal ?? true;\n\t}\n};\n/**\n* Whether combinators must re-throw `error` instead of mapping the item to `null`.\n* @param error - any thrown value; fatality is host `instanceof` (unforgeable from a script realm).\n* @returns true iff `error` is a {@link WorkflowError} whose `fatal` flag is set.\n*/\nfunction isFatalWorkflowError(error) {\n\treturn error instanceof WorkflowError && error.fatal;\n}\n//#endregion\n//#region packages/workflow/workflow-ptc/src/runtime.ts\n/**\n* Workflow VM hooks, child callbacks, ordinary concurrency limits and result serialization.\n* PTC owns process confinement and cancellation. Fatal hook and provider failures propagate\n* through combinators; ordinary child failures and stage errors become per-item nulls.\n* @module @deepseek-ai/dsh-workflow-ptc/runtime\n*/\n/** The `agent()` options the script may pass; everything else rejects loud. */\nconst SUPPORTED_AGENT_OPTIONS = new Set([\n\t\"label\",\n\t\"phase\",\n\t\"schema\",\n\t\"provider\",\n\t\"model\"\n]);\n/** Deferred Claude Code options we name explicitly in the rejection message. */\nconst DEFERRED_AGENT_OPTIONS = new Set([\n\t\"effort\",\n\t\"isolation\",\n\t\"agentType\"\n]);\n/** Flatten a child's final output blocks to text (the non-schema `agent()` result). */\nfunction outputText(blocks) {\n\treturn blocks.filter((block) => block.type === \"text\").map((block) => block.text).join(\"\");\n}\n/** A short display label derived from the prompt when the script passes none. */\nfunction defaultLabel(prompt) {\n\tconst newline = prompt.indexOf(\"\\n\");\n\tconst line = newline === -1 ? prompt : prompt.slice(0, newline);\n\treturn line.length <= 48 ? line : `${line.slice(0, 47)}…`;\n}\n/**\n* One script execution inside the confined Node process. The host owns\n* cancellation and cleanup of any dropped child work.\n*/\nvar WorkflowExecution = class {\n\tlimits;\n\tobserver;\n\tchildren;\n\t/** 1-based count of `agent()` calls started (the `agentsStarted` result field). */\n\tstarted = 0;\n\tactiveSlots = 0;\n\tslotWaiters = [];\n\tcurrentPhase;\n\tcontext;\n\tcompiled;\n\tconstructor(meta, body, args, limits, observer, children) {\n\t\tthis.limits = limits;\n\t\tthis.observer = observer;\n\t\tthis.children = children;\n\t\ttry {\n\t\t\tthis.compiled = new vm.Script(`(async () => {\\n${body}\\n})()`, {\n\t\t\t\tfilename: `workflow:${meta.name}`,\n\t\t\t\tlineOffset: -1\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrow new WorkflowError(`workflow script does not parse: ${String(error)}`, \"SCRIPT_PARSE\", { cause: error });\n\t\t}\n\t\tthis.context = vm.createContext({}, { name: `workflow:${meta.name}` });\n\t\tconst globals = {\n\t\t\tagent: (prompt, opts) => this.contain(this.agent(prompt, opts)),\n\t\t\tparallel: (thunks) => this.contain(this.parallel(thunks)),\n\t\t\tpipeline: (items, ...stages) => this.contain(this.pipeline(items, stages)),\n\t\t\tphase: (title) => {\n\t\t\t\tthis.phase(title);\n\t\t\t},\n\t\t\tlog: (message) => {\n\t\t\t\tthis.log(message);\n\t\t\t},\n\t\t\targs\n\t\t};\n\t\tfor (const [key, value] of Object.entries(globals)) this.context[key] = typeof value === \"function\" ? Object.freeze(value) : value;\n\t}\n\t/**\n\t* Run the script and materialize its JSON return value.\n\t* @returns A completed or error result; script failures never reject.\n\t*/\n\tasync drive() {\n\t\ttry {\n\t\t\tconst scriptPromise = this.compiled.runInContext(this.context, { timeout: this.limits.syncTimeoutMs });\n\t\t\tconst raw = await this.contain(Promise.resolve(scriptPromise));\n\t\t\treturn {\n\t\t\t\tvalue: raw === void 0 ? null : this.materializeResult(raw),\n\t\t\t\tstopReason: \"completed\",\n\t\t\t\tagentsStarted: this.started\n\t\t\t};\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tvalue: null,\n\t\t\t\tstopReason: \"error\",\n\t\t\t\terror: renderThrown(error),\n\t\t\t\tagentsStarted: this.started\n\t\t\t};\n\t\t}\n\t}\n\t/**\n\t* Attach a no-op rejection consumer WITHOUT changing what the caller\n\t* receives: if the script drops the promise, a host rejection cannot become\n\t* an unhandled rejection that kills the process; if\n\t* the script does await it, it still observes the rejection.\n\t*/\n\tcontain(promise) {\n\t\tpromise.catch(() => {});\n\t\treturn promise;\n\t}\n\t/** Materialize the script's return value; violations become RESULT_UNSERIALIZABLE. */\n\tmaterializeResult(raw) {\n\t\ttry {\n\t\t\treturn materializeFromRealm(raw, \"workflow result\");\n\t\t} catch (error) {\n\t\t\t/* v8 ignore next -- defensive rethrow arm: materializeFromRealm only throws MaterializeError */\n\t\t\tif (!(error instanceof MaterializeError)) throw error;\n\t\t\tthrow new WorkflowError(`the workflow's return value is not plain JSON data — ${error.message}. Return only JSON-serializable objects/arrays/scalars.`, \"RESULT_UNSERIALIZABLE\", { cause: error });\n\t\t}\n\t}\n\t/** Acquire one concurrency slot in FIFO order. */\n\tacquireSlot() {\n\t\tif (this.activeSlots < this.limits.maxConcurrentAgents) {\n\t\t\tthis.activeSlots += 1;\n\t\t\treturn Promise.resolve();\n\t\t}\n\t\treturn new Promise((resolve) => {\n\t\t\tthis.slotWaiters.push(() => {\n\t\t\t\tthis.activeSlots += 1;\n\t\t\t\tresolve();\n\t\t\t});\n\t\t});\n\t}\n\treleaseSlot() {\n\t\tthis.activeSlots -= 1;\n\t\tconst next = this.slotWaiters.shift();\n\t\tif (next) next();\n\t}\n\t/** The `agent(prompt, opts)` hook. */\n\tasync agent(rawPrompt, rawOpts) {\n\t\tif (typeof rawPrompt !== \"string\" || rawPrompt.length === 0) throw new WorkflowError(\"agent() requires a non-empty prompt string\", \"INVALID_ARGUMENT\");\n\t\tconst opts = this.readAgentOptions(rawOpts);\n\t\tif (this.started >= this.limits.maxTotalAgents) throw new WorkflowError(`this run reached its total agent cap (${this.limits.maxTotalAgents}) — a runaway-loop backstop; raise the applicable maxTotalAgents limit if the scale is intentional`, \"AGENT_CAP\");\n\t\tthis.started += 1;\n\t\tconst seq = this.started;\n\t\tconst label = opts.label ?? defaultLabel(rawPrompt);\n\t\tconst phase = opts.phase ?? this.currentPhase;\n\t\tawait this.acquireSlot();\n\t\ttry {\n\t\t\tlet run;\n\t\t\ttry {\n\t\t\t\trun = await this.children.startAgent({\n\t\t\t\t\tprompt: rawPrompt,\n\t\t\t\t\t...opts.schema !== void 0 ? { schema: opts.schema } : {},\n\t\t\t\t\t...opts.provider !== void 0 ? { provider: opts.provider } : {},\n\t\t\t\t\t...opts.model !== void 0 ? { model: opts.model } : {}\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tthrow new WorkflowError(`agent() could not start a child: ${renderThrown(error)}`, \"AGENT_START\", { cause: error });\n\t\t\t}\n\t\t\tconst info = {\n\t\t\t\tseq,\n\t\t\t\tlabel,\n\t\t\t\t...phase !== void 0 ? { phase } : {},\n\t\t\t\tchildId: brandString(run.id)\n\t\t\t};\n\t\t\tthis.observer.agentStart(info);\n\t\t\ttry {\n\t\t\t\tlet result;\n\t\t\t\ttry {\n\t\t\t\t\tresult = await run.result;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t\t...info,\n\t\t\t\t\t\toutcome: \"failed\"\n\t\t\t\t\t});\n\t\t\t\t\tthrow new WorkflowError(`child agent run failed: ${renderThrown(error)}`, \"AGENT_RESULT\", { cause: error });\n\t\t\t\t}\n\t\t\t\tif (result.stopReason === \"completed\") {\n\t\t\t\t\tif (opts.schema !== void 0) {\n\t\t\t\t\t\tif (result.structured === void 0) {\n\t\t\t\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t\t\t\t...info,\n\t\t\t\t\t\t\t\toutcome: \"failed\"\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\treturn null;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t\t\t...info,\n\t\t\t\t\t\t\toutcome: \"completed\"\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn result.structured;\n\t\t\t\t\t}\n\t\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t\t...info,\n\t\t\t\t\t\toutcome: \"completed\"\n\t\t\t\t\t});\n\t\t\t\t\treturn outputText(result.output);\n\t\t\t\t}\n\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t...info,\n\t\t\t\t\toutcome: \"failed\"\n\t\t\t\t});\n\t\t\t\treturn null;\n\t\t\t} finally {\n\t\t\t\tawait run.dispose();\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.releaseSlot();\n\t\t}\n\t}\n\t/** Materialize + validate the `agent()` options bag from the realm. */\n\treadAgentOptions(rawOpts) {\n\t\tif (rawOpts === void 0) return {};\n\t\tlet opts;\n\t\ttry {\n\t\t\topts = materializeFromRealm(rawOpts, \"agent() options\");\n\t\t} catch (error) {\n\t\t\t/* v8 ignore next -- defensive rethrow arm: materializeFromRealm only throws MaterializeError */\n\t\t\tif (!(error instanceof MaterializeError)) throw error;\n\t\t\tthrow new WorkflowError(`agent() options must be plain JSON data — ${error.message}`, \"INVALID_ARGUMENT\", { cause: error });\n\t\t}\n\t\tif (typeof opts !== \"object\" || opts === null || Array.isArray(opts)) throw new WorkflowError(\"agent() options must be an object\", \"INVALID_ARGUMENT\");\n\t\tconst record = opts;\n\t\tfor (const key of Object.keys(record)) {\n\t\t\tif (SUPPORTED_AGENT_OPTIONS.has(key)) continue;\n\t\t\tif (DEFERRED_AGENT_OPTIONS.has(key)) throw new WorkflowError(`agent() option \"${key}\" is deferred and not supported by this engine (supported: label, phase, schema, provider, model)`, \"UNSUPPORTED_OPTION\");\n\t\t\tthrow new WorkflowError(`agent() option \"${key}\" is not recognized (supported: label, phase, schema, provider, model)`, \"UNSUPPORTED_OPTION\");\n\t\t}\n\t\tfor (const key of [\n\t\t\t\"label\",\n\t\t\t\"phase\",\n\t\t\t\"provider\",\n\t\t\t\"model\"\n\t\t]) if (record[key] !== void 0 && typeof record[key] !== \"string\") throw new WorkflowError(`agent() option \"${key}\" must be a string`, \"INVALID_ARGUMENT\");\n\t\tlet schema;\n\t\tif (record.schema !== void 0) try {\n\t\t\tassertObjectJsonSchema(record.schema);\n\t\t\tschema = record.schema;\n\t\t} catch (error) {\n\t\t\t/* v8 ignore next -- defensive rethrow arm: assertObjectJsonSchema only throws JsonSchemaError */\n\t\t\tif (!(error instanceof JsonSchemaError)) throw error;\n\t\t\tthrow new WorkflowError(`agent() schema is outside the supported subset — ${error.message}`, \"UNSUPPORTED_SCHEMA\", { cause: error });\n\t\t}\n\t\treturn {\n\t\t\t...record.label !== void 0 ? { label: record.label } : {},\n\t\t\t...record.phase !== void 0 ? { phase: record.phase } : {},\n\t\t\t...record.provider !== void 0 ? { provider: record.provider } : {},\n\t\t\t...record.model !== void 0 ? { model: record.model } : {},\n\t\t\t...schema !== void 0 ? { schema } : {}\n\t\t};\n\t}\n\t/** The `parallel(thunks)` hook: each thunk caught → `null`; fatal errors propagate. */\n\tasync parallel(rawThunks) {\n\t\tif (!Array.isArray(rawThunks)) throw new WorkflowError(\"parallel() requires an array of zero-argument functions\", \"INVALID_ARGUMENT\");\n\t\tthis.assertItemCap(rawThunks.length, \"parallel()\");\n\t\tconst thunks = rawThunks.map((thunk, index) => {\n\t\t\tif (typeof thunk !== \"function\") throw new WorkflowError(`parallel() item ${index} is not a function`, \"INVALID_ARGUMENT\");\n\t\t\treturn thunk;\n\t\t});\n\t\treturn Promise.all(thunks.map(async (thunk) => {\n\t\t\ttry {\n\t\t\t\treturn await thunk();\n\t\t\t} catch (error) {\n\t\t\t\tif (isFatalWorkflowError(error)) throw error;\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}));\n\t}\n\t/** The `pipeline(items, ...stages)` hook: per-item stage chains, NO cross-stage barrier. */\n\tasync pipeline(rawItems, rawStages) {\n\t\tif (!Array.isArray(rawItems)) throw new WorkflowError(\"pipeline() requires an items array\", \"INVALID_ARGUMENT\");\n\t\tthis.assertItemCap(rawItems.length, \"pipeline()\");\n\t\tif (rawStages.length === 0) throw new WorkflowError(\"pipeline() requires at least one stage function\", \"INVALID_ARGUMENT\");\n\t\tconst stages = rawStages.map((stage, index) => {\n\t\t\tif (typeof stage !== \"function\") throw new WorkflowError(`pipeline() stage ${index} is not a function`, \"INVALID_ARGUMENT\");\n\t\t\treturn stage;\n\t\t});\n\t\treturn Promise.all(rawItems.map(async (item, index) => {\n\t\t\tlet value = item;\n\t\t\ttry {\n\t\t\t\tfor (const stage of stages) value = await stage(value, item, index);\n\t\t\t\treturn value;\n\t\t\t} catch (error) {\n\t\t\t\tif (isFatalWorkflowError(error)) throw error;\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}));\n\t}\n\tassertItemCap(length, hook) {\n\t\tif (length > this.limits.maxItemsPerCall) throw new WorkflowError(`${hook} received ${length} items — over the per-call cap (${this.limits.maxItemsPerCall}); split the work or raise maxItemsPerCall in the engine config`, \"ITEM_CAP\");\n\t}\n\t/** The `phase(title)` hook: sets the current label for subsequent `agent()` calls and notifies observers. */\n\tphase(title) {\n\t\tif (typeof title !== \"string\" || title.length === 0) throw new WorkflowError(\"phase() requires a non-empty title string\", \"INVALID_ARGUMENT\");\n\t\tthis.currentPhase = title;\n\t\tthis.observer.phase(title);\n\t}\n\t/** The `log(message)` hook: narration to observers. */\n\tlog(message) {\n\t\tif (typeof message !== \"string\") throw new WorkflowError(\"log() requires a message string\", \"INVALID_ARGUMENT\");\n\t\tthis.observer.log(message);\n\t}\n};\n//#endregion\n//#region packages/workflow/workflow-ptc/src/guest.ts\n/**\n* Run a workflow with one progress batch in flight. Drain progress before child\n* disposal and the terminal result; PTC and the host own cancellation and cleanup.\n* @param host - JSON callbacks owned by this workflow run.\n* @returns The script result after progress delivery; initialization failures reject.\n*/\nasync function runWorkflowGuest(host) {\n\tconst init = await host.begin({});\n\tlet queued = [];\n\tlet inFlight;\n\tlet progressError;\n\tconst flush = () => {\n\t\tif (inFlight !== void 0 || queued.length === 0) return;\n\t\tconst batch = queued;\n\t\tqueued = [];\n\t\tinFlight = host.progress(batch).then(() => {\n\t\t\tinFlight = void 0;\n\t\t\tflush();\n\t\t}, (error) => {\n\t\t\tprogressError = renderThrown(error);\n\t\t\tqueued = [];\n\t\t\tinFlight = void 0;\n\t\t});\n\t};\n\tconst send = (event) => {\n\t\tif (progressError !== void 0) return;\n\t\tqueued.push(event);\n\t\tflush();\n\t};\n\tconst drain = async () => {\n\t\twhile (inFlight !== void 0) await inFlight;\n\t};\n\tconst result = await new WorkflowExecution(init.meta, init.body, init.args, init.limits, {\n\t\tphase: (title) => {\n\t\t\tsend({\n\t\t\t\ttype: \"phase\",\n\t\t\t\ttitle\n\t\t\t});\n\t\t},\n\t\tlog: (message) => {\n\t\t\tsend({\n\t\t\t\ttype: \"log\",\n\t\t\t\tmessage\n\t\t\t});\n\t\t},\n\t\tagentStart: (info) => {\n\t\t\tsend({\n\t\t\t\ttype: \"agent-start\",\n\t\t\t\tinfo\n\t\t\t});\n\t\t},\n\t\tagentEnd: (info) => {\n\t\t\tsend({\n\t\t\t\ttype: \"agent-end\",\n\t\t\t\tinfo\n\t\t\t});\n\t\t}\n\t}, { async startAgent(request) {\n\t\tconst { callId, childId } = await host.startChild(request);\n\t\tconst result = host.childResult({ callId });\n\t\tresult.catch(() => {});\n\t\treturn {\n\t\t\tid: childId,\n\t\t\tresult,\n\t\t\tasync dispose() {\n\t\t\t\tawait drain();\n\t\t\t\tawait host.disposeChild({ callId });\n\t\t\t}\n\t\t};\n\t} }).drive();\n\tawait drain();\n\treturn progressError === void 0 ? result : {\n\t\tvalue: null,\n\t\tstopReason: \"error\",\n\t\terror: progressError,\n\t\tagentsStarted: result.agentsStarted\n\t};\n}\n//#endregion\nexport { runWorkflowGuest };\n//# sourceURL=dsh-workflow-guest.js\n" +export const WORKFLOW_GUEST_SOURCE = "import * as vm from \"node:vm\";\n//#region packages/workflow/workflow-ptc/src/realm.ts\n/**\n* Materializes script VM values as plain JSON and renders thrown values.\n* Getters and proxy traps may execute inside the confined Node process;\n* process isolation and cancellation belong to PTC, not the VM.\n* @module @deepseek-ai/dsh-workflow-ptc/realm\n*/\n/** Thrown by {@link materializeFromRealm}; the caller wraps it into the right `WorkflowError` code. */\nvar MaterializeError = class extends Error {\n\tpath;\n\treason;\n\tconstructor(path, reason) {\n\t\tsuper(`${path}: ${reason}`);\n\t\tthis.path = path;\n\t\tthis.reason = reason;\n\t\tthis.name = \"MaterializeError\";\n\t}\n};\n/**\n* Render a thrown value to failure text without ever throwing: prefer the\n* `stack` (host or realm — a realm error's `stack` is a plain string read),\n* fall back to `message`, then `String()`. Reading those properties MAY run\n* script code; if that code itself throws, a fixed label is returned instead.\n* @param error - any value thrown in the host or guest realm.\n* @returns human-readable text for the failure report; prefers the stack.\n*/\nfunction renderThrown(error) {\n\ttry {\n\t\tconst stack = error?.stack;\n\t\tif (typeof stack === \"string\" && stack.length > 0) return stack;\n\t\tconst message = error?.message;\n\t\tif (typeof message === \"string\" && message.length > 0) return message;\n\t\treturn String(error);\n\t} catch {\n\t\treturn \"[unrenderable thrown value]\";\n\t}\n}\n/**\n* Whether an object's prototype chain represents a plain data object: `null`, or a prototype\n* whose own prototype is `null` (the realm's `Object.prototype` — which we\n* cannot compare by identity across realms). A `Date`/`Map`/class instance\n* has a longer chain and is rejected.\n*/\nfunction hasPlainPrototype(value) {\n\tconst proto = Object.getPrototypeOf(value);\n\tif (proto === null) return true;\n\treturn Object.getPrototypeOf(proto) === null;\n}\n/**\n* Copy `value` (typically from the vm realm) into plain host JSON data. Root `undefined` is\n* returned unchanged; nested `undefined` and values JSON cannot represent losslessly fail\n* with the offending path. Property accessors run normally, and a throwing read is wrapped\n* with its rendered failure.\n*\n* @param value - the realm value to materialize.\n* @param root - the path label for the root value (error messages).\n* @returns the host-realm copy (plain objects/arrays/scalars only).\n* @throws {@link MaterializeError} for unsupported values, cycles, sparse arrays, exotic\n* prototypes, or property reads that throw.\n*/\nfunction materializeFromRealm(value, root = \"value\") {\n\tif (value === void 0) return void 0;\n\ttry {\n\t\treturn materialize(value, root, /* @__PURE__ */ new Set());\n\t} catch (error) {\n\t\tif (error instanceof MaterializeError) throw error;\n\t\tthrow new MaterializeError(root, `reading the value threw: ${renderThrown(error)}`);\n\t}\n}\nfunction materialize(value, path, seen) {\n\tswitch (typeof value) {\n\t\tcase \"boolean\":\n\t\tcase \"string\": return value;\n\t\tcase \"number\":\n\t\t\tif (!Number.isFinite(value)) throw new MaterializeError(path, \"non-finite numbers are not JSON data\");\n\t\t\treturn value;\n\t\tcase \"bigint\": throw new MaterializeError(path, \"bigints are not JSON data\");\n\t\tcase \"function\": throw new MaterializeError(path, \"functions are not plain JSON data\");\n\t\tcase \"symbol\": throw new MaterializeError(path, \"symbols are not plain JSON data\");\n\t\tcase \"undefined\": throw new MaterializeError(path, \"undefined is not JSON data\");\n\t\tcase \"object\": break;\n\t}\n\tif (value === null) return null;\n\tconst objectValue = value;\n\tif (seen.has(objectValue)) throw new MaterializeError(path, \"circular references are not JSON data\");\n\tseen.add(objectValue);\n\ttry {\n\t\tif (Array.isArray(objectValue)) return materializeArray(objectValue, path, seen);\n\t\treturn materializeObject(objectValue, path, seen);\n\t} finally {\n\t\tseen.delete(objectValue);\n\t}\n}\nfunction materializeArray(value, path, seen) {\n\tconst out = [];\n\tfor (let index = 0; index < value.length; index++) {\n\t\tif (!(index in value)) throw new MaterializeError(`${path}[${index}]`, \"sparse arrays are not JSON data\");\n\t\tout.push(materialize(value[index], `${path}[${index}]`, seen));\n\t}\n\tfor (const key of Object.keys(value)) {\n\t\tconst index = Number(key);\n\t\tif (!Number.isInteger(index) || index < 0 || index >= value.length) throw new MaterializeError(`${path}.${key}`, \"arrays with non-index properties are not JSON data\");\n\t}\n\tif (Object.getOwnPropertySymbols(value).length > 0) throw new MaterializeError(path, \"symbol-keyed properties are not plain JSON data\");\n\treturn out;\n}\nfunction materializeObject(value, path, seen) {\n\tif (!hasPlainPrototype(value)) throw new MaterializeError(path, \"only plain objects and arrays are JSON data (exotic prototype)\");\n\tif (Object.getOwnPropertySymbols(value).length > 0) throw new MaterializeError(path, \"symbol-keyed properties are not plain JSON data\");\n\tconst out = {};\n\tfor (const key of Object.keys(value)) Object.defineProperty(out, key, {\n\t\tvalue: materialize(value[key], `${path}.${key}`, seen),\n\t\tenumerable: true,\n\t\twritable: true,\n\t\tconfigurable: true\n\t});\n\treturn out;\n}\n//#endregion\n//#region packages/util/brand/src/index.ts\n/**\n* Apply a compile-time string brand without changing the value.\n* @param value - string admitted by the domain that owns the target brand.\n* @returns the same string with the requested compile-time brand.\n*/\nfunction brandString(value) {\n\treturn value;\n}\n//#endregion\n//#region packages/util/values/src/index.ts\n/**\n* Mark an unreachable closed-union branch.\n* @param value - impossible value; an unhandled typed variant fails at the call site.\n* @param context - optional switch-site label included in the failure message.\n* @returns never; a runtime value that escaped its type always throws.\n*/\nfunction assertNever(value, context) {\n\tconst rendered = JSON.stringify(value) ?? String(value);\n\tthrow new Error(`unreachable variant${context ? ` in ${context}` : \"\"}: ${rendered}`);\n}\n/** Whether a realm-owned intrinsic prototype has a native constructor matching this engine's representation. */\nfunction hasIntrinsicConstructor$1(prototype, name) {\n\tconst constructor = Object.getOwnPropertyDescriptor(prototype, \"constructor\")?.value;\n\tif (typeof constructor !== \"function\") return false;\n\ttry {\n\t\treturn constructor.name === name && constructor.prototype === prototype && Function.prototype.toString.call(constructor) === Function.prototype.toString.call(name === \"Array\" ? Array : Object);\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Whether a candidate is one realm's intrinsic `Object.prototype`. */\nfunction isIntrinsicObjectPrototype$1(value) {\n\treturn Object.getPrototypeOf(value) === null && hasIntrinsicConstructor$1(value, \"Object\");\n}\n/** Whether an array uses one realm's intrinsic `Array.prototype`, not a subclass or forged prototype. */\nfunction hasPlainArrayPrototype$1(value) {\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (!Array.isArray(prototype) || !hasIntrinsicConstructor$1(prototype, \"Array\")) return false;\n\tconst objectPrototype = Object.getPrototypeOf(prototype);\n\treturn typeof objectPrototype === \"object\" && objectPrototype !== null && isIntrinsicObjectPrototype$1(objectPrototype);\n}\n/** Whether an object is a plain or null-prototype record from any JavaScript realm. */\nfunction hasPlainObjectPrototype(value) {\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === null || typeof prototype === \"object\" && isIntrinsicObjectPrototype$1(prototype);\n}\n/** Return every JSON-visible object key, or reject own data JSON would discard. */\nfunction enumerableStringKeys(value) {\n\tconst keys = Reflect.ownKeys(value);\n\tif (keys.some((key) => typeof key !== \"string\" || !Object.prototype.propertyIsEnumerable.call(value, key))) return void 0;\n\treturn keys;\n}\n/** Validate lossless JSON iteratively, optionally materializing a detached snapshot. */\nfunction walkJsonValue(value, detach) {\n\tconst ancestors = /* @__PURE__ */ new Set();\n\tlet root;\n\tlet parent;\n\tconst assign = (item) => {\n\t\tif (parent === void 0) {\n\t\t\tif (detach) root = item;\n\t\t} else if (parent.kind === \"array\") {\n\t\t\tif (parent.target !== void 0) parent.target[parent.key] = item;\n\t\t} else if (parent.target !== void 0) Object.defineProperty(parent.target, parent.key, {\n\t\t\tvalue: item,\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true\n\t\t});\n\t};\n\tconst frames = [];\n\tlet current = value;\n\tfor (;;) {\n\t\tif (current === null) assign(null);\n\t\telse if (typeof current === \"boolean\" || typeof current === \"string\") assign(current);\n\t\telse if (typeof current === \"number\") {\n\t\t\tif (!Number.isFinite(current) || Object.is(current, -0)) return void 0;\n\t\t\tassign(current);\n\t\t} else {\n\t\t\tif (typeof current !== \"object\") return void 0;\n\t\t\tif (ancestors.has(current)) return void 0;\n\t\t\tif (Array.isArray(current)) {\n\t\t\t\tif (!hasPlainArrayPrototype$1(current)) return void 0;\n\t\t\t\tconst length = current.length;\n\t\t\t\tif (Reflect.ownKeys(current).length !== length + 1) return void 0;\n\t\t\t\tconst target = detach ? [] : void 0;\n\t\t\t\tif (target !== void 0) assign(target);\n\t\t\t\tlet indices;\n\t\t\t\tif (!Number.isInteger(length)) {\n\t\t\t\t\tindices = [];\n\t\t\t\t\tfor (let index = length - 1; index >= 0; index--) indices.push(index);\n\t\t\t\t}\n\t\t\t\tframes.push({\n\t\t\t\t\tkind: \"array\",\n\t\t\t\t\tsource: current,\n\t\t\t\t\tlength: indices?.length ?? length,\n\t\t\t\t\tindex: 0,\n\t\t\t\t\tkey: 0,\n\t\t\t\t\tindices,\n\t\t\t\t\ttarget\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tif (!hasPlainObjectPrototype(current)) return void 0;\n\t\t\t\tconst keys = enumerableStringKeys(current);\n\t\t\t\tif (keys === void 0) return void 0;\n\t\t\t\tconst target = detach ? {} : void 0;\n\t\t\t\tif (target !== void 0) assign(target);\n\t\t\t\tframes.push({\n\t\t\t\t\tkind: \"object\",\n\t\t\t\t\tsource: current,\n\t\t\t\t\tkeys,\n\t\t\t\t\tindex: 0,\n\t\t\t\t\tkey: \"\",\n\t\t\t\t\ttarget\n\t\t\t\t});\n\t\t\t}\n\t\t\tancestors.add(current);\n\t\t}\n\t\tfor (;;) {\n\t\t\tconst frame = frames.at(-1);\n\t\t\tif (frame === void 0) return detach ? root : true;\n\t\t\tconst length = frame.kind === \"array\" ? frame.length : frame.keys.length;\n\t\t\tif (frame.index >= length) {\n\t\t\t\tancestors.delete(frame.source);\n\t\t\t\tframes.pop();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst index = frame.index++;\n\t\t\tparent = frame;\n\t\t\tif (frame.kind === \"array\") {\n\t\t\t\tconst key = frame.indices === void 0 ? index : frame.indices[frame.indices.length - index - 1];\n\t\t\t\t/* v8 ignore next -- the loop is bounded by the captured index count. */\n\t\t\t\tif (key === void 0) return void 0;\n\t\t\t\tif (!Object.prototype.hasOwnProperty.call(frame.source, key)) return void 0;\n\t\t\t\tframe.key = key;\n\t\t\t\tcurrent = frame.source[key];\n\t\t\t} else {\n\t\t\t\tconst key = frame.keys[index];\n\t\t\t\t/* v8 ignore next -- the loop is bounded by the captured key count. */\n\t\t\t\tif (key === void 0) return void 0;\n\t\t\t\tframe.key = key;\n\t\t\t\tcurrent = frame.source[key];\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n}\n/**\n* Test the same lossless JSON rules as {@link snapshotJsonValue} without detaching the value.\n* @param value - candidate value to test.\n* @returns whether the value survives a JSON round trip without loss.\n*/\nfunction isJsonValue(value) {\n\treturn walkJsonValue(value, false) === true;\n}\n//#endregion\n//#region packages/llm/llm/src/message.ts\n/**\n* Extract and join only text blocks in content order, preserving their whitespace.\n* Non-text blocks contribute neither text nor separators; content is not modified.\n* Import from `@deepseek-ai/dsh-llm/message` in Host and browser code.\n* @param content - source blocks to read in their existing order.\n* @param options - optional text extraction settings.\n* @param options.separator - text inserted between text blocks; defaults to an empty string.\n* @returns joined text, or an empty string when no text blocks are present.\n*/\nfunction extractTextContent(content, options) {\n\treturn content.filter((block) => block.type === \"text\").map((block) => block.text).join(options?.separator ?? \"\");\n}\n//#endregion\n//#region packages/util/error/src/index.ts\n/**\n* Harness error base with a stable machine-routable code and chained cause.\n* Package errors extend it so tool results and replay can retain failure class.\n* @module @deepseek-ai/dsh-error\n*/\n/**\n* Base class for all harness errors. Carries a `code` (stable, programmatic —\n* e.g. `NO_ADAPTER`, `INVALID_ARGS`) distinct from the\n* human-readable `message`, and supports `cause` chaining via the standard\n* `ErrorOptions`. `name` defaults to the subclass constructor name.\n*/\nvar HarnessError = class extends Error {\n\t/** Stable machine-routable failure class (e.g. `RATE_LIMIT`); route on this, never by parsing `message`. */\n\tcode;\n\tconstructor(message, code, options) {\n\t\tsuper(message, options);\n\t\tthis.code = code;\n\t\tthis.name = new.target.name;\n\t}\n};\n//#endregion\n//#region packages/core/tools/src/json-schema.ts\n/**\n* Enforced JSON Schema subset shared by tool outputs, generated PTC mode\n* types, subagents, and workflows. The subset accepts any JSON root, an\n* annotation-only schema for unconstrained JSON, one scalar `type`, object\n* `properties`/`required`/boolean `additionalProperties`, array `items`,\n* type-correct scalar `enum`/`const`, and exact-one `oneOf`.\n*\n* Unsupported or misplaced keywords reject rather than being accepted without\n* enforcement. Consumers that require an object root apply\n* {@link assertObjectJsonSchema} before accepting input.\n* @module dsh-tools/json-schema\n*/\n/**\n* Thrown when a raw schema falls outside the enforced subset. `violations`\n* lists every offending path instead of stopping at the first author error.\n*/\nvar JsonSchemaError = class extends HarnessError {\n\t/** Individual schema violations in walk order. */\n\tviolations;\n\tconstructor(violations) {\n\t\tsuper(`unsupported JSON schema: ${violations.join(\"; \")}`, \"UNSUPPORTED_SCHEMA\");\n\t\tthis.name = \"JsonSchemaError\";\n\t\tthis.violations = violations;\n\t}\n};\nconst CONSTRAINT_KEYWORDS = new Set([\n\t\"type\",\n\t\"oneOf\",\n\t\"properties\",\n\t\"required\",\n\t\"additionalProperties\",\n\t\"items\",\n\t\"enum\",\n\t\"const\"\n]);\nconst ANNOTATION_KEYWORDS = new Set([\n\t\"description\",\n\t\"title\",\n\t\"default\",\n\t\"examples\"\n]);\nconst SCHEMA_TYPES = [\n\t\"object\",\n\t\"array\",\n\t\"string\",\n\t\"number\",\n\t\"integer\",\n\t\"boolean\",\n\t\"null\"\n];\n/** Whether a realm-owned intrinsic prototype is backed by its native constructor. */\nfunction hasIntrinsicConstructor(prototype, name) {\n\tconst constructor = Object.getOwnPropertyDescriptor(prototype, \"constructor\")?.value;\n\tif (typeof constructor !== \"function\") return false;\n\ttry {\n\t\treturn constructor.name === name && constructor.prototype === prototype && Function.prototype.toString.call(constructor) === `function ${name}() { [native code] }`;\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Whether a candidate is one realm's intrinsic `Object.prototype`. */\nfunction isIntrinsicObjectPrototype(value) {\n\treturn Object.getPrototypeOf(value) === null && hasIntrinsicConstructor(value, \"Object\");\n}\n/**\n* Test for a realm-agnostic plain JSON record without accepting arrays or\n* exotic objects.\n* @param value - candidate record from any JavaScript realm.\n* @returns Whether the value has a plain-object prototype chain.\n*/\nfunction isPlainJsonRecord(value) {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n\ttry {\n\t\tconst prototype = Object.getPrototypeOf(value);\n\t\treturn prototype === null || typeof prototype === \"object\" && isIntrinsicObjectPrototype(prototype);\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Whether an array uses one realm's intrinsic `Array.prototype`. */\nfunction hasPlainArrayPrototype(value) {\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (!Array.isArray(prototype) || !hasIntrinsicConstructor(prototype, \"Array\")) return false;\n\tconst objectPrototype = Object.getPrototypeOf(prototype);\n\treturn typeof objectPrototype === \"object\" && objectPrototype !== null && isIntrinsicObjectPrototype(objectPrototype);\n}\n/** Return whether a record contains only own enumerable string keys. */\nfunction hasOnlyEnumerableStringKeys(value) {\n\ttry {\n\t\treturn Reflect.ownKeys(value).every((key) => typeof key === \"string\" && Object.prototype.propertyIsEnumerable.call(value, key));\n\t} catch {\n\t\treturn false;\n\t}\n}\n/**\n* Test for an ordinary schema record whose keys survive JSON projection.\n* @param value - candidate record from any JavaScript realm.\n* @returns Whether the record has an intrinsic prototype and only own enumerable string keys.\n*/\nfunction isJsonSchemaRecord(value) {\n\treturn isPlainJsonRecord(value) && hasOnlyEnumerableStringKeys(value);\n}\n/**\n* Test for a dense ordinary array with no JSON-invisible decorations.\n* @param value - candidate array from any JavaScript realm.\n* @returns Whether the array is intrinsic, dense, and undecorated.\n*/\nfunction isPlainJsonArray(value) {\n\tif (!Array.isArray(value)) return false;\n\ttry {\n\t\tif (!hasPlainArrayPrototype(value) || Reflect.ownKeys(value).length !== value.length + 1) return false;\n\t\tfor (let index = 0; index < value.length; index++) if (!Object.hasOwn(value, index)) return false;\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Lossless finite JSON number, excluding negative zero. */\nfunction isJsonNumber(value) {\n\treturn typeof value === \"number\" && Number.isFinite(value) && !Object.is(value, -0);\n}\n/** Whether a scalar is valid for one declared schema type. */\nfunction scalarMatches(type, value) {\n\tswitch (type) {\n\t\tcase \"string\": return typeof value === \"string\";\n\t\tcase \"number\": return isJsonNumber(value);\n\t\tcase \"integer\": return isJsonNumber(value) && Number.isInteger(value);\n\t\tcase \"boolean\": return typeof value === \"boolean\";\n\t\tcase \"null\": return value === null;\n\t\t/* v8 ignore next -- JsonSchemaScalarType is closed; this retains compile-time exhaustiveness. */\n\t\tdefault: return assertNever(type, \"JsonSchemaType\");\n\t}\n}\n/** Keywords that are invalid beside `oneOf`. */\nconst ONE_OF_SIBLING_KEYWORDS = [\n\t\"properties\",\n\t\"required\",\n\t\"additionalProperties\",\n\t\"items\",\n\t\"enum\",\n\t\"const\"\n];\n/** Validate object-only fields after its property schemas have been visited. */\nfunction checkObjectSchemaTail(node, path, properties, violations) {\n\tconst hasRequired = Object.hasOwn(node, \"required\");\n\tconst required = hasRequired ? node.required : void 0;\n\tif (hasRequired) if (!isPlainJsonArray(required) || required.some((entry) => typeof entry !== \"string\")) violations.push(`${path}.required must be an array of strings`);\n\telse {\n\t\tconst declared = isJsonSchemaRecord(properties) ? properties : {};\n\t\tfor (const key of required) if (!Object.hasOwn(declared, key)) violations.push(`${path}.required names \"${key}\" which is not in properties`);\n\t}\n\tif (Object.hasOwn(node, \"additionalProperties\") && typeof node.additionalProperties !== \"boolean\") violations.push(`${path}.additionalProperties must be a boolean`);\n}\n/** Collect every violation for one raw schema tree without using the JavaScript call stack. */\nfunction checkSchemaNode(root, rootPath, violations, seen) {\n\tconst tasks = [{\n\t\tkind: \"enter\",\n\t\tnode: root,\n\t\tpath: rootPath\n\t}];\n\tfor (let task = tasks.pop(); task !== void 0; task = tasks.pop()) {\n\t\tif (task.kind === \"leave\") {\n\t\t\tseen.delete(task.node);\n\t\t\tcontinue;\n\t\t}\n\t\tif (task.kind === \"one-of-tail\") {\n\t\t\tfor (const key of ONE_OF_SIBLING_KEYWORDS) if (Object.hasOwn(task.node, key)) violations.push(`${task.path}.${key} is not supported beside oneOf`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (task.kind === \"object-tail\") {\n\t\t\tcheckObjectSchemaTail(task.node, task.path, task.properties, violations);\n\t\t\tcontinue;\n\t\t}\n\t\tconst { node, path } = task;\n\t\tif (!isJsonSchemaRecord(node)) {\n\t\t\tviolations.push(`${path} must be a schema object`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (seen.has(node)) {\n\t\t\tviolations.push(`${path} is circular`);\n\t\t\tcontinue;\n\t\t}\n\t\tseen.add(node);\n\t\ttasks.push({\n\t\t\tkind: \"leave\",\n\t\t\tnode\n\t\t});\n\t\tfor (const key of Object.keys(node)) {\n\t\t\tif (CONSTRAINT_KEYWORDS.has(key)) continue;\n\t\t\tif (ANNOTATION_KEYWORDS.has(key)) {\n\t\t\t\ttry {\n\t\t\t\t\tif (!isJsonValue(node[key])) violations.push(`${path}.${key} annotation must be lossless JSON data`);\n\t\t\t\t} catch {\n\t\t\t\t\tviolations.push(`${path}.${key} annotation must be lossless JSON data`);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tviolations.push(`${path}.${key} is not a supported keyword (subset: type/oneOf/properties/required/additionalProperties/items/enum/const + annotations)`);\n\t\t}\n\t\tif (Object.hasOwn(node, \"description\") && typeof node.description !== \"string\") violations.push(`${path}.description must be a string`);\n\t\tif (Object.hasOwn(node, \"title\") && typeof node.title !== \"string\") violations.push(`${path}.title must be a string`);\n\t\tconst hasType = Object.hasOwn(node, \"type\");\n\t\tconst hasOneOf = Object.hasOwn(node, \"oneOf\");\n\t\tif (hasType && hasOneOf) {\n\t\t\tviolations.push(`${path} cannot declare both type and oneOf`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!hasType && !hasOneOf) {\n\t\t\tfor (const key of ONE_OF_SIBLING_KEYWORDS) if (Object.hasOwn(node, key)) violations.push(`${path}.${key} requires type or oneOf`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (hasOneOf) {\n\t\t\tconst oneOf = node.oneOf;\n\t\t\ttasks.push({\n\t\t\t\tkind: \"one-of-tail\",\n\t\t\t\tnode,\n\t\t\t\tpath\n\t\t\t});\n\t\t\tif (!isPlainJsonArray(oneOf) || oneOf.length < 2) violations.push(`${path}.oneOf must be an array of at least two schemas`);\n\t\t\telse for (let index = oneOf.length - 1; index >= 0; index--) tasks.push({\n\t\t\t\tkind: \"enter\",\n\t\t\t\tnode: oneOf[index],\n\t\t\t\tpath: `${path}.oneOf[${index}]`\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst type = node.type;\n\t\tif (typeof type !== \"string\" || !SCHEMA_TYPES.includes(type)) {\n\t\t\tviolations.push(Array.isArray(type) ? `${path}.type must be a single type string (type arrays are not supported)` : `${path}.type must be one of ${SCHEMA_TYPES.join(\"/\")}`);\n\t\t\tcontinue;\n\t\t}\n\t\tconst schemaType = type;\n\t\tfor (const [key, types] of Object.entries({\n\t\t\tproperties: [\"object\"],\n\t\t\trequired: [\"object\"],\n\t\t\tadditionalProperties: [\"object\"],\n\t\t\titems: [\"array\"],\n\t\t\tenum: [\n\t\t\t\t\"string\",\n\t\t\t\t\"number\",\n\t\t\t\t\"integer\",\n\t\t\t\t\"boolean\",\n\t\t\t\t\"null\"\n\t\t\t],\n\t\t\tconst: [\n\t\t\t\t\"string\",\n\t\t\t\t\"number\",\n\t\t\t\t\"integer\",\n\t\t\t\t\"boolean\",\n\t\t\t\t\"null\"\n\t\t\t]\n\t\t})) if (Object.hasOwn(node, key) && !types.includes(schemaType)) violations.push(`${path}.${key} is not supported on type \"${schemaType}\"`);\n\t\tswitch (schemaType) {\n\t\t\tcase \"object\": {\n\t\t\t\tconst properties = Object.hasOwn(node, \"properties\") ? node.properties : void 0;\n\t\t\t\ttasks.push({\n\t\t\t\t\tkind: \"object-tail\",\n\t\t\t\t\tnode,\n\t\t\t\t\tpath,\n\t\t\t\t\tproperties\n\t\t\t\t});\n\t\t\t\tif (Object.hasOwn(node, \"properties\")) if (!isJsonSchemaRecord(properties)) violations.push(`${path}.properties must be an object of schemas`);\n\t\t\t\telse {\n\t\t\t\t\tconst entries = Object.entries(properties);\n\t\t\t\t\tfor (let index = entries.length - 1; index >= 0; index--) {\n\t\t\t\t\t\tconst entry = entries[index];\n\t\t\t\t\t\t/* v8 ignore next -- the loop is bounded by the captured entry count. */\n\t\t\t\t\t\tif (entry === void 0) continue;\n\t\t\t\t\t\ttasks.push({\n\t\t\t\t\t\t\tkind: \"enter\",\n\t\t\t\t\t\t\tnode: entry[1],\n\t\t\t\t\t\t\tpath: `${path}.properties.${entry[0]}`\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"array\":\n\t\t\t\tif (Object.hasOwn(node, \"items\")) tasks.push({\n\t\t\t\t\tkind: \"enter\",\n\t\t\t\t\tnode: node.items,\n\t\t\t\t\tpath: `${path}.items`\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"string\":\n\t\t\tcase \"number\":\n\t\t\tcase \"integer\":\n\t\t\tcase \"boolean\":\n\t\t\tcase \"null\": {\n\t\t\t\tconst hasEnum = Object.hasOwn(node, \"enum\");\n\t\t\t\tconst allowed = hasEnum ? node.enum : void 0;\n\t\t\t\tconst enumValid = isPlainJsonArray(allowed) && allowed.length > 0 && allowed.every((entry) => scalarMatches(schemaType, entry));\n\t\t\t\tif (hasEnum && !enumValid) violations.push(`${path}.enum must be a non-empty array of ${schemaType} values`);\n\t\t\t\tconst hasConst = Object.hasOwn(node, \"const\");\n\t\t\t\tconst declaredConst = hasConst ? node.const : void 0;\n\t\t\t\tconst constValid = scalarMatches(schemaType, declaredConst);\n\t\t\t\tif (hasConst) {\n\t\t\t\t\tif (!constValid) violations.push(`${path}.const must be a ${schemaType} value`);\n\t\t\t\t\telse if (enumValid && !allowed.includes(declaredConst)) violations.push(`${path}.const must be one of ${path}.enum when both are declared`);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t/* v8 ignore next -- schemaType was narrowed from the closed SCHEMA_TYPES table above. */\n\t\t\tdefault: assertNever(schemaType, \"JsonSchemaType\");\n\t\t}\n\t}\n}\n/**\n* Assert the enforced subset plus the object-root constraint retained by\n* subagent and workflow structured outputs.\n* @param schema - untrusted caller-supplied schema.\n* @returns Assertion that the schema belongs to the supported subset and has an object root.\n*/\nfunction assertObjectJsonSchema(schema) {\n\tconst violations = [];\n\tcheckSchemaNode(schema, \"schema\", violations, /* @__PURE__ */ new Set());\n\tif (violations.length === 0 && (!isJsonSchemaRecord(schema) || !Object.hasOwn(schema, \"type\") || schema.type !== \"object\")) violations.push(\"schema.type must be \\\"object\\\" (structured output is object-rooted)\");\n\tif (violations.length > 0) throw new JsonSchemaError(violations);\n}\n//#endregion\n//#region packages/workflow/workflow/src/index.ts\n/**\n* Typed error for workflow-seam failures. Extends {@link HarnessError}, so the\n* `code` is machine-routable taxonomy. `fatal` drives the combinator\n* discipline: `parallel()`/`pipeline()` re-throw a fatal error (a typo'd\n* option or a tripped cap must kill the script loudly), and reserve the\n* per-item `null` for child-run failures and ordinary in-stage script errors.\n* Every {@link WorkflowErrorCode} is fatal; the flag exists so the\n* distinction is explicit at every catch site rather than implied.\n*/\nvar WorkflowError = class extends HarnessError {\n\t/** Whether combinators must propagate this error instead of nulling the item. */\n\tfatal;\n\tconstructor(message, code, options) {\n\t\tsuper(message, code, options);\n\t\tthis.name = \"WorkflowError\";\n\t\tthis.fatal = options?.fatal ?? true;\n\t}\n};\n/**\n* Whether combinators must re-throw `error` instead of mapping the item to `null`.\n* @param error - any thrown value; fatality is host `instanceof` (unforgeable from a script realm).\n* @returns true iff `error` is a {@link WorkflowError} whose `fatal` flag is set.\n*/\nfunction isFatalWorkflowError(error) {\n\treturn error instanceof WorkflowError && error.fatal;\n}\n//#endregion\n//#region packages/workflow/workflow-ptc/src/runtime.ts\n/**\n* Workflow VM hooks, child callbacks, ordinary concurrency limits and result serialization.\n* PTC owns process confinement and cancellation. Fatal hook and provider failures propagate\n* through combinators; ordinary child failures and stage errors become per-item nulls.\n* @module @deepseek-ai/dsh-workflow-ptc/runtime\n*/\n/** The `agent()` options the script may pass; everything else rejects loud. */\nconst SUPPORTED_AGENT_OPTIONS = new Set([\n\t\"label\",\n\t\"phase\",\n\t\"schema\",\n\t\"provider\",\n\t\"model\"\n]);\n/** Deferred Claude Code options we name explicitly in the rejection message. */\nconst DEFERRED_AGENT_OPTIONS = new Set([\n\t\"effort\",\n\t\"isolation\",\n\t\"agentType\"\n]);\n/** A short display label derived from the prompt when the script passes none. */\nfunction defaultLabel(prompt) {\n\tconst newline = prompt.indexOf(\"\\n\");\n\tconst line = newline === -1 ? prompt : prompt.slice(0, newline);\n\treturn line.length <= 48 ? line : `${line.slice(0, 47)}…`;\n}\n/**\n* One script execution inside the confined Node process. The host owns\n* cancellation and cleanup of any dropped child work.\n*/\nvar WorkflowExecution = class {\n\tlimits;\n\tobserver;\n\tchildren;\n\t/** 1-based count of `agent()` calls started (the `agentsStarted` result field). */\n\tstarted = 0;\n\tactiveSlots = 0;\n\tslotWaiters = [];\n\tcurrentPhase;\n\tcontext;\n\tcompiled;\n\tconstructor(meta, body, args, limits, observer, children) {\n\t\tthis.limits = limits;\n\t\tthis.observer = observer;\n\t\tthis.children = children;\n\t\ttry {\n\t\t\tthis.compiled = new vm.Script(`(async () => {\\n${body}\\n})()`, {\n\t\t\t\tfilename: `workflow:${meta.name}`,\n\t\t\t\tlineOffset: -1\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrow new WorkflowError(`workflow script does not parse: ${String(error)}`, \"SCRIPT_PARSE\", { cause: error });\n\t\t}\n\t\tthis.context = vm.createContext({}, { name: `workflow:${meta.name}` });\n\t\tconst globals = {\n\t\t\tagent: (prompt, opts) => this.contain(this.agent(prompt, opts)),\n\t\t\tparallel: (thunks) => this.contain(this.parallel(thunks)),\n\t\t\tpipeline: (items, ...stages) => this.contain(this.pipeline(items, stages)),\n\t\t\tphase: (title) => {\n\t\t\t\tthis.phase(title);\n\t\t\t},\n\t\t\tlog: (message) => {\n\t\t\t\tthis.log(message);\n\t\t\t},\n\t\t\targs\n\t\t};\n\t\tfor (const [key, value] of Object.entries(globals)) this.context[key] = typeof value === \"function\" ? Object.freeze(value) : value;\n\t}\n\t/**\n\t* Run the script and materialize its JSON return value.\n\t* @returns A completed or error result; script failures never reject.\n\t*/\n\tasync drive() {\n\t\ttry {\n\t\t\tconst scriptPromise = this.compiled.runInContext(this.context, { timeout: this.limits.syncTimeoutMs });\n\t\t\tconst raw = await this.contain(Promise.resolve(scriptPromise));\n\t\t\treturn {\n\t\t\t\tvalue: raw === void 0 ? null : this.materializeResult(raw),\n\t\t\t\tstopReason: \"completed\",\n\t\t\t\tagentsStarted: this.started\n\t\t\t};\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tvalue: null,\n\t\t\t\tstopReason: \"error\",\n\t\t\t\terror: renderThrown(error),\n\t\t\t\tagentsStarted: this.started\n\t\t\t};\n\t\t}\n\t}\n\t/**\n\t* Attach a no-op rejection consumer WITHOUT changing what the caller\n\t* receives: if the script drops the promise, a host rejection cannot become\n\t* an unhandled rejection that kills the process; if\n\t* the script does await it, it still observes the rejection.\n\t*/\n\tcontain(promise) {\n\t\tpromise.catch(() => {});\n\t\treturn promise;\n\t}\n\t/** Materialize the script's return value; violations become RESULT_UNSERIALIZABLE. */\n\tmaterializeResult(raw) {\n\t\ttry {\n\t\t\treturn materializeFromRealm(raw, \"workflow result\");\n\t\t} catch (error) {\n\t\t\t/* v8 ignore next -- defensive rethrow arm: materializeFromRealm only throws MaterializeError */\n\t\t\tif (!(error instanceof MaterializeError)) throw error;\n\t\t\tthrow new WorkflowError(`the workflow's return value is not plain JSON data — ${error.message}. Return only JSON-serializable objects/arrays/scalars.`, \"RESULT_UNSERIALIZABLE\", { cause: error });\n\t\t}\n\t}\n\t/** Acquire one concurrency slot in FIFO order. */\n\tacquireSlot() {\n\t\tif (this.activeSlots < this.limits.maxConcurrentAgents) {\n\t\t\tthis.activeSlots += 1;\n\t\t\treturn Promise.resolve();\n\t\t}\n\t\treturn new Promise((resolve) => {\n\t\t\tthis.slotWaiters.push(() => {\n\t\t\t\tthis.activeSlots += 1;\n\t\t\t\tresolve();\n\t\t\t});\n\t\t});\n\t}\n\treleaseSlot() {\n\t\tthis.activeSlots -= 1;\n\t\tconst next = this.slotWaiters.shift();\n\t\tif (next) next();\n\t}\n\t/** The `agent(prompt, opts)` hook. */\n\tasync agent(rawPrompt, rawOpts) {\n\t\tif (typeof rawPrompt !== \"string\" || rawPrompt.length === 0) throw new WorkflowError(\"agent() requires a non-empty prompt string\", \"INVALID_ARGUMENT\");\n\t\tconst opts = this.readAgentOptions(rawOpts);\n\t\tif (this.started >= this.limits.maxTotalAgents) throw new WorkflowError(`this run reached its total agent cap (${this.limits.maxTotalAgents}) — a runaway-loop backstop; raise the applicable maxTotalAgents limit if the scale is intentional`, \"AGENT_CAP\");\n\t\tthis.started += 1;\n\t\tconst seq = this.started;\n\t\tconst label = opts.label ?? defaultLabel(rawPrompt);\n\t\tconst phase = opts.phase ?? this.currentPhase;\n\t\tawait this.acquireSlot();\n\t\ttry {\n\t\t\tlet run;\n\t\t\ttry {\n\t\t\t\trun = await this.children.startAgent({\n\t\t\t\t\tprompt: rawPrompt,\n\t\t\t\t\t...opts.schema !== void 0 ? { schema: opts.schema } : {},\n\t\t\t\t\t...opts.provider !== void 0 ? { provider: opts.provider } : {},\n\t\t\t\t\t...opts.model !== void 0 ? { model: opts.model } : {}\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tthrow new WorkflowError(`agent() could not start a child: ${renderThrown(error)}`, \"AGENT_START\", { cause: error });\n\t\t\t}\n\t\t\tconst info = {\n\t\t\t\tseq,\n\t\t\t\tlabel,\n\t\t\t\t...phase !== void 0 ? { phase } : {},\n\t\t\t\tchildId: brandString(run.id)\n\t\t\t};\n\t\t\tthis.observer.agentStart(info);\n\t\t\ttry {\n\t\t\t\tlet result;\n\t\t\t\ttry {\n\t\t\t\t\tresult = await run.result;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t\t...info,\n\t\t\t\t\t\toutcome: \"failed\"\n\t\t\t\t\t});\n\t\t\t\t\tthrow new WorkflowError(`child agent run failed: ${renderThrown(error)}`, \"AGENT_RESULT\", { cause: error });\n\t\t\t\t}\n\t\t\t\tif (result.stopReason === \"completed\") {\n\t\t\t\t\tif (opts.schema !== void 0) {\n\t\t\t\t\t\tif (result.structured === void 0) {\n\t\t\t\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t\t\t\t...info,\n\t\t\t\t\t\t\t\toutcome: \"failed\"\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\treturn null;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t\t\t...info,\n\t\t\t\t\t\t\toutcome: \"completed\"\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn result.structured;\n\t\t\t\t\t}\n\t\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t\t...info,\n\t\t\t\t\t\toutcome: \"completed\"\n\t\t\t\t\t});\n\t\t\t\t\treturn extractTextContent(result.output);\n\t\t\t\t}\n\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t...info,\n\t\t\t\t\toutcome: \"failed\"\n\t\t\t\t});\n\t\t\t\treturn null;\n\t\t\t} finally {\n\t\t\t\tawait run.dispose();\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.releaseSlot();\n\t\t}\n\t}\n\t/** Materialize + validate the `agent()` options bag from the realm. */\n\treadAgentOptions(rawOpts) {\n\t\tif (rawOpts === void 0) return {};\n\t\tlet opts;\n\t\ttry {\n\t\t\topts = materializeFromRealm(rawOpts, \"agent() options\");\n\t\t} catch (error) {\n\t\t\t/* v8 ignore next -- defensive rethrow arm: materializeFromRealm only throws MaterializeError */\n\t\t\tif (!(error instanceof MaterializeError)) throw error;\n\t\t\tthrow new WorkflowError(`agent() options must be plain JSON data — ${error.message}`, \"INVALID_ARGUMENT\", { cause: error });\n\t\t}\n\t\tif (typeof opts !== \"object\" || opts === null || Array.isArray(opts)) throw new WorkflowError(\"agent() options must be an object\", \"INVALID_ARGUMENT\");\n\t\tconst record = opts;\n\t\tfor (const key of Object.keys(record)) {\n\t\t\tif (SUPPORTED_AGENT_OPTIONS.has(key)) continue;\n\t\t\tif (DEFERRED_AGENT_OPTIONS.has(key)) throw new WorkflowError(`agent() option \"${key}\" is deferred and not supported by this engine (supported: label, phase, schema, provider, model)`, \"UNSUPPORTED_OPTION\");\n\t\t\tthrow new WorkflowError(`agent() option \"${key}\" is not recognized (supported: label, phase, schema, provider, model)`, \"UNSUPPORTED_OPTION\");\n\t\t}\n\t\tfor (const key of [\n\t\t\t\"label\",\n\t\t\t\"phase\",\n\t\t\t\"provider\",\n\t\t\t\"model\"\n\t\t]) if (record[key] !== void 0 && typeof record[key] !== \"string\") throw new WorkflowError(`agent() option \"${key}\" must be a string`, \"INVALID_ARGUMENT\");\n\t\tlet schema;\n\t\tif (record.schema !== void 0) try {\n\t\t\tassertObjectJsonSchema(record.schema);\n\t\t\tschema = record.schema;\n\t\t} catch (error) {\n\t\t\t/* v8 ignore next -- defensive rethrow arm: assertObjectJsonSchema only throws JsonSchemaError */\n\t\t\tif (!(error instanceof JsonSchemaError)) throw error;\n\t\t\tthrow new WorkflowError(`agent() schema is outside the supported subset — ${error.message}`, \"UNSUPPORTED_SCHEMA\", { cause: error });\n\t\t}\n\t\treturn {\n\t\t\t...record.label !== void 0 ? { label: record.label } : {},\n\t\t\t...record.phase !== void 0 ? { phase: record.phase } : {},\n\t\t\t...record.provider !== void 0 ? { provider: record.provider } : {},\n\t\t\t...record.model !== void 0 ? { model: record.model } : {},\n\t\t\t...schema !== void 0 ? { schema } : {}\n\t\t};\n\t}\n\t/** The `parallel(thunks)` hook: each thunk caught → `null`; fatal errors propagate. */\n\tasync parallel(rawThunks) {\n\t\tif (!Array.isArray(rawThunks)) throw new WorkflowError(\"parallel() requires an array of zero-argument functions\", \"INVALID_ARGUMENT\");\n\t\tthis.assertItemCap(rawThunks.length, \"parallel()\");\n\t\tconst thunks = rawThunks.map((thunk, index) => {\n\t\t\tif (typeof thunk !== \"function\") throw new WorkflowError(`parallel() item ${index} is not a function`, \"INVALID_ARGUMENT\");\n\t\t\treturn thunk;\n\t\t});\n\t\treturn Promise.all(thunks.map(async (thunk) => {\n\t\t\ttry {\n\t\t\t\treturn await thunk();\n\t\t\t} catch (error) {\n\t\t\t\tif (isFatalWorkflowError(error)) throw error;\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}));\n\t}\n\t/** The `pipeline(items, ...stages)` hook: per-item stage chains, NO cross-stage barrier. */\n\tasync pipeline(rawItems, rawStages) {\n\t\tif (!Array.isArray(rawItems)) throw new WorkflowError(\"pipeline() requires an items array\", \"INVALID_ARGUMENT\");\n\t\tthis.assertItemCap(rawItems.length, \"pipeline()\");\n\t\tif (rawStages.length === 0) throw new WorkflowError(\"pipeline() requires at least one stage function\", \"INVALID_ARGUMENT\");\n\t\tconst stages = rawStages.map((stage, index) => {\n\t\t\tif (typeof stage !== \"function\") throw new WorkflowError(`pipeline() stage ${index} is not a function`, \"INVALID_ARGUMENT\");\n\t\t\treturn stage;\n\t\t});\n\t\treturn Promise.all(rawItems.map(async (item, index) => {\n\t\t\tlet value = item;\n\t\t\ttry {\n\t\t\t\tfor (const stage of stages) value = await stage(value, item, index);\n\t\t\t\treturn value;\n\t\t\t} catch (error) {\n\t\t\t\tif (isFatalWorkflowError(error)) throw error;\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}));\n\t}\n\tassertItemCap(length, hook) {\n\t\tif (length > this.limits.maxItemsPerCall) throw new WorkflowError(`${hook} received ${length} items — over the per-call cap (${this.limits.maxItemsPerCall}); split the work or raise maxItemsPerCall in the engine config`, \"ITEM_CAP\");\n\t}\n\t/** The `phase(title)` hook: sets the current label for subsequent `agent()` calls and notifies observers. */\n\tphase(title) {\n\t\tif (typeof title !== \"string\" || title.length === 0) throw new WorkflowError(\"phase() requires a non-empty title string\", \"INVALID_ARGUMENT\");\n\t\tthis.currentPhase = title;\n\t\tthis.observer.phase(title);\n\t}\n\t/** The `log(message)` hook: narration to observers. */\n\tlog(message) {\n\t\tif (typeof message !== \"string\") throw new WorkflowError(\"log() requires a message string\", \"INVALID_ARGUMENT\");\n\t\tthis.observer.log(message);\n\t}\n};\n//#endregion\n//#region packages/workflow/workflow-ptc/src/guest.ts\n/**\n* Run a workflow with one progress batch in flight. Drain progress before child\n* disposal and the terminal result; PTC and the host own cancellation and cleanup.\n* @param host - JSON callbacks owned by this workflow run.\n* @returns The script result after progress delivery; initialization failures reject.\n*/\nasync function runWorkflowGuest(host) {\n\tconst init = await host.begin({});\n\tlet queued = [];\n\tlet inFlight;\n\tlet progressError;\n\tconst flush = () => {\n\t\tif (inFlight !== void 0 || queued.length === 0) return;\n\t\tconst batch = queued;\n\t\tqueued = [];\n\t\tinFlight = host.progress(batch).then(() => {\n\t\t\tinFlight = void 0;\n\t\t\tflush();\n\t\t}, (error) => {\n\t\t\tprogressError = renderThrown(error);\n\t\t\tqueued = [];\n\t\t\tinFlight = void 0;\n\t\t});\n\t};\n\tconst send = (event) => {\n\t\tif (progressError !== void 0) return;\n\t\tqueued.push(event);\n\t\tflush();\n\t};\n\tconst drain = async () => {\n\t\twhile (inFlight !== void 0) await inFlight;\n\t};\n\tconst result = await new WorkflowExecution(init.meta, init.body, init.args, init.limits, {\n\t\tphase: (title) => {\n\t\t\tsend({\n\t\t\t\ttype: \"phase\",\n\t\t\t\ttitle\n\t\t\t});\n\t\t},\n\t\tlog: (message) => {\n\t\t\tsend({\n\t\t\t\ttype: \"log\",\n\t\t\t\tmessage\n\t\t\t});\n\t\t},\n\t\tagentStart: (info) => {\n\t\t\tsend({\n\t\t\t\ttype: \"agent-start\",\n\t\t\t\tinfo\n\t\t\t});\n\t\t},\n\t\tagentEnd: (info) => {\n\t\t\tsend({\n\t\t\t\ttype: \"agent-end\",\n\t\t\t\tinfo\n\t\t\t});\n\t\t}\n\t}, { async startAgent(request) {\n\t\tconst { callId, childId } = await host.startChild(request);\n\t\tconst result = host.childResult({ callId });\n\t\tresult.catch(() => {});\n\t\treturn {\n\t\t\tid: childId,\n\t\t\tresult,\n\t\t\tasync dispose() {\n\t\t\t\tawait drain();\n\t\t\t\tawait host.disposeChild({ callId });\n\t\t\t}\n\t\t};\n\t} }).drive();\n\tawait drain();\n\treturn progressError === void 0 ? result : {\n\t\tvalue: null,\n\t\tstopReason: \"error\",\n\t\terror: progressError,\n\t\tagentsStarted: result.agentsStarted\n\t};\n}\n//#endregion\nexport { runWorkflowGuest };\n//# sourceURL=dsh-workflow-guest.js\n" diff --git a/packages/workflow/workflow-ptc/src/runtime.ts b/packages/workflow/workflow-ptc/src/runtime.ts index 71c153e586..373bd1bf87 100644 --- a/packages/workflow/workflow-ptc/src/runtime.ts +++ b/packages/workflow/workflow-ptc/src/runtime.ts @@ -7,7 +7,7 @@ import * as vm from 'node:vm' import { brandString } from '@deepseek-ai/dsh-brand' -import type { ContentBlock } from '@deepseek-ai/dsh-llm' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import type { SessionId } from '@deepseek-ai/dsh-session' import { assertObjectJsonSchema, JsonSchemaError } from '@deepseek-ai/dsh-tools' import type { ObjectJsonSchema } from '@deepseek-ai/dsh-tools' @@ -34,14 +34,6 @@ const SUPPORTED_AGENT_OPTIONS = new Set(['label', 'phase', 'schema', 'provider', /** Deferred Claude Code options we name explicitly in the rejection message. */ const DEFERRED_AGENT_OPTIONS = new Set(['effort', 'isolation', 'agentType']) -/** Flatten a child's final output blocks to text (the non-schema `agent()` result). */ -function outputText(blocks: ContentBlock[]): string { - return blocks - .filter((block): block is Extract => block.type === 'text') - .map(block => block.text) - .join('') -} - /** A short display label derived from the prompt when the script passes none. */ function defaultLabel(prompt: string): string { const newline = prompt.indexOf('\n') @@ -216,7 +208,7 @@ export class WorkflowExecution { return result.structured } this.observer.agentEnd({ ...info, outcome: 'completed' }) - return outputText(result.output) + return extractTextContent(result.output) } this.observer.agentEnd({ ...info, outcome: 'failed' }) return null From 3268ba0ccd11717fefed03978ea0e74dbf3ad434 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Wed, 11 Nov 2026 14:17:28 +0800 Subject: [PATCH 14/31] refactor(llm): share extractTextContent across text consumers --- docs/config-catalog.md | 10 ++--- docs/config-catalog.zh.md | 10 ++--- docs/event-producer-consumer.md | 2 +- docs/event-producer-consumer.zh.md | 2 +- docs/module-graph.md | 3 +- docs/module-graph.zh.md | 3 +- docs/persistence-catalog.i18n.yaml | 4 +- docs/persistence-catalog.md | 2 +- docs/persistence-catalog.zh.md | 2 +- packages/bundle/headless/src/index.ts | 6 +-- .../src/client/conversation-nodes/command.ts | 5 +-- .../src/client/contract/system-prompt.ts | 3 +- .../src/client/queue/QueueDock.tsx | 5 ++- .../src/client/tool/toolviews/office-row.tsx | 3 +- .../session-reference/src/projection.ts | 10 ++--- packages/core/tool-executor-ptc/src/ptc.ts | 3 +- .../claude-code-mods/src/host-ops.ts | 9 ++-- .../claude-code-mods/src/index.ts | 9 ++-- .../client-ui-stats/src/client/stats-fold.ts | 12 ++---- .../experimental/forge-session/package.json | 1 + .../forge-session/src/projection.ts | 4 +- .../forge-session/src/reference-lookup.ts | 4 +- .../hooks-claude-code/src/index.ts | 10 ++--- .../experimental/hooks-codex/src/index.ts | 12 ++---- .../src/index.ts | 8 ++-- packages/llm/llm-deepseek/src/serialize.ts | 6 +-- packages/llm/llm-pi-ai/src/context.ts | 20 +++------ packages/llm/llm/README.i18n.yaml | 8 ++-- packages/llm/llm/README.md | 3 +- packages/llm/llm/README.zh.md | 3 +- packages/llm/llm/src/index.ts | 6 ++- packages/llm/llm/src/message.ts | 15 ++++++- packages/llm/llm/tests/message.spec.ts | 41 +++++++++++++++++++ packages/sdk/server/src/query-activity.ts | 4 +- .../src/index.ts | 8 ++-- packages/session/session-title/src/index.ts | 6 +-- packages/web/web-deepseek-api/src/index.ts | 5 ++- .../workflow/workflow-ptc/src/guest-source.ts | 2 +- packages/workflow/workflow-ptc/src/runtime.ts | 12 +----- 39 files changed, 154 insertions(+), 127 deletions(-) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 825cea47b9..605f3537d8 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1645,7 +1645,7 @@ export interface Config { - `inject`: `agentDefaultModel` · `agents` · `sessions` - `refs`: [`ApprovalPolicy`](subsystems/approval.md) -- `source`: [`packages/bundle/headless/src/index.ts:48`](../packages/bundle/headless/src/index.ts) +- `source`: [`packages/bundle/headless/src/index.ts:49`](../packages/bundle/headless/src/index.ts) ```ts config-catalog /** Plugin config: the task and run options resolved from this app's injected provider service. */ @@ -1693,7 +1693,7 @@ export interface HmrConfig extends ChokidarOptions { ## `@deepseek-ai/dsh-hooks-claude-code` - `inject`: `shell` · `agents` · `workingDirectory` -- `source`: [`packages/experimental/hooks-claude-code/src/index.ts:50`](../packages/experimental/hooks-claude-code/src/index.ts) +- `source`: [`packages/experimental/hooks-claude-code/src/index.ts:51`](../packages/experimental/hooks-claude-code/src/index.ts) ```ts config-catalog /** Plugin config: where the CC hook config lives + substitution roots. */ @@ -1732,7 +1732,7 @@ export interface Config { ## `@deepseek-ai/dsh-hooks-codex` - `inject`: `shell` · `agents` · `workingDirectory` -- `source`: [`packages/experimental/hooks-codex/src/index.ts:49`](../packages/experimental/hooks-codex/src/index.ts) +- `source`: [`packages/experimental/hooks-codex/src/index.ts:50`](../packages/experimental/hooks-codex/src/index.ts) ```ts config-catalog /** Plugin config: where the Codex hooks.json lives + the model name for payloads. */ @@ -3330,7 +3330,7 @@ export enum SessionTelemetryMode { ## `@deepseek-ai/dsh-session-title` - `inject`: `sessions` · `sessionProjections` · `agents` -- `source`: [`packages/session/session-title/src/index.ts:56`](../packages/session/session-title/src/index.ts) +- `source`: [`packages/session/session-title/src/index.ts:57`](../packages/session/session-title/src/index.ts) ```ts config-catalog /** Required deterministic fallback and accepted-title limits. */ @@ -4815,7 +4815,7 @@ export interface Config { - `inject`: `web` - `refs`: `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/web/web-deepseek-api/src/index.ts:64`](../packages/web/web-deepseek-api/src/index.ts) +- `source`: [`packages/web/web-deepseek-api/src/index.ts:65`](../packages/web/web-deepseek-api/src/index.ts) ```ts config-catalog /** diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 09c61e5660..e36e5652ba 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1647,7 +1647,7 @@ export interface Config { - `inject`: `agentDefaultModel` · `agents` · `sessions` - `refs`: [`ApprovalPolicy`](subsystems/approval.zh.md) -- `source`: [`packages/bundle/headless/src/index.ts:48`](../packages/bundle/headless/src/index.ts) +- `source`: [`packages/bundle/headless/src/index.ts:49`](../packages/bundle/headless/src/index.ts) ```ts config-catalog /** Plugin config: the task and run options resolved from this app's injected provider service. */ @@ -1695,7 +1695,7 @@ export interface HmrConfig extends ChokidarOptions { ## `@deepseek-ai/dsh-hooks-claude-code` - `inject`: `shell` · `agents` · `workingDirectory` -- `source`: [`packages/experimental/hooks-claude-code/src/index.ts:50`](../packages/experimental/hooks-claude-code/src/index.ts) +- `source`: [`packages/experimental/hooks-claude-code/src/index.ts:51`](../packages/experimental/hooks-claude-code/src/index.ts) ```ts config-catalog /** Plugin config: where the CC hook config lives + substitution roots. */ @@ -1734,7 +1734,7 @@ export interface Config { ## `@deepseek-ai/dsh-hooks-codex` - `inject`: `shell` · `agents` · `workingDirectory` -- `source`: [`packages/experimental/hooks-codex/src/index.ts:49`](../packages/experimental/hooks-codex/src/index.ts) +- `source`: [`packages/experimental/hooks-codex/src/index.ts:50`](../packages/experimental/hooks-codex/src/index.ts) ```ts config-catalog /** Plugin config: where the Codex hooks.json lives + the model name for payloads. */ @@ -3332,7 +3332,7 @@ export enum SessionTelemetryMode { ## `@deepseek-ai/dsh-session-title` - `inject`: `sessions` · `sessionProjections` · `agents` -- `source`: [`packages/session/session-title/src/index.ts:56`](../packages/session/session-title/src/index.ts) +- `source`: [`packages/session/session-title/src/index.ts:57`](../packages/session/session-title/src/index.ts) ```ts config-catalog /** Required deterministic fallback and accepted-title limits. */ @@ -4817,7 +4817,7 @@ export interface Config { - `inject`: `web` - `refs`: `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/web/web-deepseek-api/src/index.ts:64`](../packages/web/web-deepseek-api/src/index.ts) +- `source`: [`packages/web/web-deepseek-api/src/index.ts:65`](../packages/web/web-deepseek-api/src/index.ts) ```ts config-catalog /** diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 3a8967f3a0..7bf87ba05c 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -60,7 +60,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `llm-pi-ai/request-headers` | `waterfall` | [`packages/llm/llm-pi-ai/src/index.ts:113`](../packages/llm/llm-pi-ai/src/index.ts) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) (`waterfall`) | - | | `llm/adapters-updated` | `emit` | [`packages/llm/llm/src/types.ts:24`](../packages/llm/llm/src/types.ts) | [`llm`](../packages/llm/llm) (`events.dispatch`) | [`acp`](../packages/acp/acp), `remotes` | | `llm/models-updated` | `emit` | [`packages/llm/llm/src/types.ts:30`](../packages/llm/llm/src/types.ts) | [`llm-deepseek`](../packages/llm/llm-deepseek) (`emit`) | `remotes` | -| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:76`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) | +| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:80`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) | | `mcp-manager/status` | `parallel` | [`packages/mcp/mcp-manager/src/types.ts:46`](../packages/mcp/mcp-manager/src/types.ts) | [`mcp-manager`](../packages/mcp/mcp-manager) (`parallel`) | - | | `permission-presets/catalog-changed` | `emit` | [`packages/interaction/permission-presets/src/types.ts:48`](../packages/interaction/permission-presets/src/types.ts) | [`permission-presets`](../packages/interaction/permission-presets) (`events.dispatch`) | `remotes` | | `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:455`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index 605c83f4f3..4e69269e5c 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -62,7 +62,7 @@ | `llm-pi-ai/request-headers` | `waterfall` | [`packages/llm/llm-pi-ai/src/index.ts:113`](../packages/llm/llm-pi-ai/src/index.ts) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) (`waterfall`) | - | | `llm/adapters-updated` | `emit` | [`packages/llm/llm/src/types.ts:24`](../packages/llm/llm/src/types.ts) | [`llm`](../packages/llm/llm) (`events.dispatch`) | [`acp`](../packages/acp/acp), `remotes` | | `llm/models-updated` | `emit` | [`packages/llm/llm/src/types.ts:30`](../packages/llm/llm/src/types.ts) | [`llm-deepseek`](../packages/llm/llm-deepseek) (`emit`) | `remotes` | -| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:76`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) | +| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:80`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) | | `mcp-manager/status` | `parallel` | [`packages/mcp/mcp-manager/src/types.ts:46`](../packages/mcp/mcp-manager/src/types.ts) | [`mcp-manager`](../packages/mcp/mcp-manager) (`parallel`) | - | | `permission-presets/catalog-changed` | `emit` | [`packages/interaction/permission-presets/src/types.ts:48`](../packages/interaction/permission-presets/src/types.ts) | [`permission-presets`](../packages/interaction/permission-presets) (`events.dispatch`) | `remotes` | | `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:455`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | diff --git a/docs/module-graph.md b/docs/module-graph.md index 717151dcef..33d3de5dd9 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -1124,6 +1124,7 @@ flowchart TD pkg_experimental_auto_review --> pkg_tools pkg_experimental_auto_review --> pkg_working_directory pkg_experimental_forge_session --> pkg_experimental_forge + pkg_experimental_forge_session --> pkg_llm pkg_experimental_forge_session --> pkg_sandbox_policy pkg_experimental_forge_session --> pkg_session pkg_experimental_forge_session --> pkg_session_projection @@ -1853,7 +1854,7 @@ flowchart TD | [`web-app`](../packages/bundle/web-app) | `bundle` | [`shell-env`](../packages/shell/shell-env) | | [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`user-questions`](../packages/interaction/user-questions) | | [`experimental-auto-review`](../packages/experimental/auto-review) | `experimental` | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | -| [`experimental-forge-session`](../packages/experimental/forge-session) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`tools`](../packages/core/tools) | +| [`experimental-forge-session`](../packages/experimental/forge-session) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`llm`](../packages/llm/llm), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`tools`](../packages/core/tools) | | [`webhook`](../packages/experimental/webhook) | `experimental` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`workspace`](../packages/workspace/workspace) | | [`tool-cordis`](../packages/extensions/tool-cordis) | `extensions` | [`agent`](../packages/core/agent), [`app-boot`](../packages/boot/app-boot), [`cordis-host-runner`](../packages/extensions/cordis-host-runner), [`tools`](../packages/core/tools) | | [`host-plugin-inventory`](../packages/host/plugin-inventory) | `host` | [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`brand`](../packages/util/brand), [`typert-protocol`](../packages/typert/protocol) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index 42507cab06..e0e4a65102 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -1126,6 +1126,7 @@ flowchart TD pkg_experimental_auto_review --> pkg_tools pkg_experimental_auto_review --> pkg_working_directory pkg_experimental_forge_session --> pkg_experimental_forge + pkg_experimental_forge_session --> pkg_llm pkg_experimental_forge_session --> pkg_sandbox_policy pkg_experimental_forge_session --> pkg_session pkg_experimental_forge_session --> pkg_session_projection @@ -1855,7 +1856,7 @@ flowchart TD | [`web-app`](../packages/bundle/web-app) | `bundle` | [`shell-env`](../packages/shell/shell-env) | | [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`user-questions`](../packages/interaction/user-questions) | | [`experimental-auto-review`](../packages/experimental/auto-review) | `experimental` | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | -| [`experimental-forge-session`](../packages/experimental/forge-session) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`tools`](../packages/core/tools) | +| [`experimental-forge-session`](../packages/experimental/forge-session) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`llm`](../packages/llm/llm), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`tools`](../packages/core/tools) | | [`webhook`](../packages/experimental/webhook) | `experimental` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`workspace`](../packages/workspace/workspace) | | [`tool-cordis`](../packages/extensions/tool-cordis) | `extensions` | [`agent`](../packages/core/agent), [`app-boot`](../packages/boot/app-boot), [`cordis-host-runner`](../packages/extensions/cordis-host-runner), [`tools`](../packages/core/tools) | | [`host-plugin-inventory`](../packages/host/plugin-inventory) | `host` | [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`brand`](../packages/util/brand), [`typert-protocol`](../packages/typert/protocol) | diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml index 4e1e235fcb..20fbd2e33b 100644 --- a/docs/persistence-catalog.i18n.yaml +++ b/docs/persistence-catalog.i18n.yaml @@ -183,8 +183,8 @@ en: 20645a60e921f012 zh: 7141cafe3a0e71d7 /session-persistence-event-catalog/events/session/session-title-log-only: - en: 6c6a27578dff5828 - zh: 9a5add2bc0df2d0a + en: 5775e52a72c0ce94 + zh: fa211a35b4660c10 /session-persistence-event-catalog/events/session/session-title-llm-request-log-only: en: 59b02baa2be32ca0 zh: 3637c99652ca89cf diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index 8392c8b354..fd81a9a562 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -865,7 +865,7 @@ Source: [`packages/core/session/src/types.ts:435`](../packages/core/session/src/ Types: [SessionTitleEventData](subsystems/session-title.md) -Source: [`packages/session/session-title/src/index.ts:77`](../packages/session/session-title/src/index.ts) +Source: [`packages/session/session-title/src/index.ts:78`](../packages/session/session-title/src/index.ts) diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md index acbfefaf7d..c7fa4a6edb 100644 --- a/docs/persistence-catalog.zh.md +++ b/docs/persistence-catalog.zh.md @@ -867,7 +867,7 @@ export type SessionEvent = { 类型:[SessionTitleEventData](subsystems/session-title.zh.md) -来源:[`packages/session/session-title/src/index.ts:77`](../packages/session/session-title/src/index.ts) +来源:[`packages/session/session-title/src/index.ts:78`](../packages/session/session-title/src/index.ts) diff --git a/packages/bundle/headless/src/index.ts b/packages/bundle/headless/src/index.ts index bc98d7ae6b..69b40ac06a 100644 --- a/packages/bundle/headless/src/index.ts +++ b/packages/bundle/headless/src/index.ts @@ -18,6 +18,7 @@ import type { Agent, AgentOptions } from '@deepseek-ai/dsh-agent' import type {} from '@deepseek-ai/dsh-agent-default-model' import { installModelSelection } from '@deepseek-ai/dsh-agent' import type {} from '@deepseek-ai/dsh-fs' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { createUserMessage } from '@deepseek-ai/dsh-llm' import { APPROVAL_POLICIES, setApprovalPolicy, type ApprovalPolicy } from '@deepseek-ai/dsh-user-approval' import { assertNever } from '@deepseek-ai/dsh-util-values' @@ -99,10 +100,7 @@ function summarize(session: Session, firstSeq: SessionLogOffset): RunOutcome { } if (!started) continue if (event.type === 'assistant/message') { - const joined = event.data.message.content - .filter(block => block.type === 'text') - .map(block => block.text) - .join('') + const joined = extractTextContent(event.data.message.content) if (joined !== '') text = joined } if (event.type === 'turn/end') reason = event.data.reason diff --git a/packages/client/ui-chat/src/client/conversation-nodes/command.ts b/packages/client/ui-chat/src/client/conversation-nodes/command.ts index a52b877552..de407aa354 100644 --- a/packages/client/ui-chat/src/client/conversation-nodes/command.ts +++ b/packages/client/ui-chat/src/client/conversation-nodes/command.ts @@ -1,3 +1,4 @@ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import type { Context } from '@deepseek-ai/cordis' import type { CommandNode, CompactionSummaryNode, ConversationMatch, ConversationNodeContext, ConversationNodeDefinition, @@ -105,9 +106,7 @@ function compactSummary(match: ConversationMatch | undefined, checkpoint: Conver if (match?.event.type === 'compaction/summary') { const data = match.event.data if (Array.isArray(data.summary)) { - const text = data.summary - .map(block => block.type === 'text' ? block.text : '') - .join('') + const text = extractTextContent(data.summary) summary = text.trim() === '' ? null : text } shadowedItemCount = Array.isArray(data.shadowedSeqs) diff --git a/packages/client/ui-conversation/src/client/contract/system-prompt.ts b/packages/client/ui-conversation/src/client/contract/system-prompt.ts index e61b35d81b..3ac1fadcc7 100644 --- a/packages/client/ui-conversation/src/client/contract/system-prompt.ts +++ b/packages/client/ui-conversation/src/client/contract/system-prompt.ts @@ -1,4 +1,5 @@ /** Immutable system-only interpretation of the loaded Session surface. */ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import type { SessionEvent } from '@deepseek-ai/dsh-session/types' import { isSurfaceEvent } from '@deepseek-ai/dsh-session/surface' import type { SystemPromptNode } from './request-inspection.ts' @@ -61,7 +62,7 @@ export function inspectSystemPrompt(previous: SystemPromptState | undefined, eve time: event.time, turn: event.data.turn, step: event.data.step, - text: event.data.message.content.flatMap(block => block.type === 'text' ? [block.text] : []).join(''), + text: extractTextContent(event.data.message.content), update: op === 'append' && previous?.nodes.some(item => item.node.text !== '') === true, } : undefined diff --git a/packages/client/ui-conversation/src/client/queue/QueueDock.tsx b/packages/client/ui-conversation/src/client/queue/QueueDock.tsx index b0907447c6..efbf311ef6 100644 --- a/packages/client/ui-conversation/src/client/queue/QueueDock.tsx +++ b/packages/client/ui-conversation/src/client/queue/QueueDock.tsx @@ -1,3 +1,4 @@ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import type { Context } from '@deepseek-ai/cordis' import { useEffect, useId, useMemo, useState } from 'react' import type { FileAttachmentRef, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' @@ -23,7 +24,7 @@ const QUEUE_TEXT_FACTS: Readonly> = { function textOf(content: InboxState['next-turn'][number]['content']): string | null { if (!content.every(block => block.type === 'text')) return null - return content.map(block => block.text).join('') + return extractTextContent(content) } /** Queue operations injected by the session-scoped registration. */ @@ -228,7 +229,7 @@ export function QueueDock({ useSession, useProjection, updateQueue, notify, load )} {renderFactorySlot('conversation.user.text', { - text: row.content.filter(block => block.type === 'text').map(block => block.text).join(''), + text: extractTextContent(row.content), facts: QUEUE_TEXT_FACTS, interactive: false, ellipsis: true, })} diff --git a/packages/client/ui-tool/src/client/tool/toolviews/office-row.tsx b/packages/client/ui-tool/src/client/tool/toolviews/office-row.tsx index e52ff7d10f..c3e14750fe 100644 --- a/packages/client/ui-tool/src/client/tool/toolviews/office-row.tsx +++ b/packages/client/ui-tool/src/client/tool/toolviews/office-row.tsx @@ -1,6 +1,7 @@ // Office toolview links target the input, not the temporary output. Rows show the // result's text blocks; rendered page images reach the model but are not displayed. +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { IconBrowseOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' import type { Context } from '@deepseek-ai/cordis' import { toolFileInject } from '../file-menu.ts' @@ -26,7 +27,7 @@ export function OfficeRow({ const row = toolRowModel(toolName, block, cwd, home) // Image blocks flatten to JSON attachment references, so a settled result with only images shows no body. const output = 'kind' in block - ? block.content.flatMap(part => part.type === 'text' ? [part.text] : []).join('\n') || null + ? extractTextContent(block.content, { separator: '\n' }) || null : row.output const path = office.filePath return ( diff --git a/packages/context/session-reference/src/projection.ts b/packages/context/session-reference/src/projection.ts index 196c75b4e1..f747f242c3 100644 --- a/packages/context/session-reference/src/projection.ts +++ b/packages/context/session-reference/src/projection.ts @@ -1,5 +1,7 @@ /** Current-surface projection and byte-bounded rendering. */ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' + import { isCompactCheckpointSource } from '@deepseek-ai/dsh-compaction' import type { SessionSurfaceSnapshot } from '@deepseek-ai/dsh-session-query' import { TextRetainer } from '@deepseek-ai/dsh-output-retention' @@ -42,12 +44,12 @@ function projectSessionConversation(snapshot: SessionSurfaceSnapshot): Projected case 'user/message': { const checkpoint = isCompactCheckpointSource(event.data.source) if (!checkpoint && event.data.source.kind !== 'user') break - const text = textContent(event.data.content) + const text = extractTextContent(event.data.content, { separator: '\n' }) if (text !== '') conversation.push({ role: 'user', text, checkpoint, originalText: text, omittedBytes: 0 }) break } case 'assistant/message': { - const text = textContent(event.data.message.content) + const text = extractTextContent(event.data.message.content, { separator: '\n' }) if (text !== '') conversation.push({ role: 'assistant', text, checkpoint: false, originalText: text, omittedBytes: 0 }) break } @@ -145,10 +147,6 @@ export function retainReferencedSession( } } -function textContent(content: readonly { type: string; text?: string }[]): string { - return content.flatMap(block => block.type === 'text' && typeof block.text === 'string' ? [block.text] : []).join('\n') -} - function truncateWithNotice(text: string, maxOutputBytes: number): { text: string; omittedBytes: number } { /* v8 ignore next -- callers invoke this only with a target smaller than the selected original text. */ if (Buffer.byteLength(text, 'utf8') <= maxOutputBytes) return { text, omittedBytes: 0 } diff --git a/packages/core/tool-executor-ptc/src/ptc.ts b/packages/core/tool-executor-ptc/src/ptc.ts index 7fa2b79c78..ce3202e2b9 100644 --- a/packages/core/tool-executor-ptc/src/ptc.ts +++ b/packages/core/tool-executor-ptc/src/ptc.ts @@ -10,6 +10,7 @@ import { isDeepStrictEqual } from 'node:util' import type { PtcDispatchLog } from './runtime-types.ts' import { symbols, type Context } from '@deepseek-ai/cordis' import { brandString } from '@deepseek-ai/dsh-brand' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { createUserMessage, HarnessError, resolveImageAttachmentAccess } from '@deepseek-ai/dsh-llm' import type { ContentBlock, ToolCallId, ToolSchema } from '@deepseek-ai/dsh-llm' @@ -704,7 +705,7 @@ export function createRunCodeTransport( if (first !== undefined && images.length === 1) return programImage(first.attachment) if (outcome.imageRemoved) { throw new Error('Image output was removed by a tool output policy.\n' - + outcome.content.filter(block => block.type === 'text').map(block => block.text).join('\n')) + + extractTextContent(outcome.content, { separator: '\n' })) } if (name === 'read_image' || images.length > 1) throw new Error('Image-producing tools must return exactly one image') } diff --git a/packages/experimental/claude-code-mods/src/host-ops.ts b/packages/experimental/claude-code-mods/src/host-ops.ts index 1ad62ef0c7..9908a22ff1 100644 --- a/packages/experimental/claude-code-mods/src/host-ops.ts +++ b/packages/experimental/claude-code-mods/src/host-ops.ts @@ -16,6 +16,7 @@ import type { CommandDefinition } from '@deepseek-ai/dsh-commands' import type { FileSystem, FsTarget } from '@deepseek-ai/dsh-fs' import { brandString } from '@deepseek-ai/dsh-brand' import { createUserMessage, type ToolCallId } from '@deepseek-ai/dsh-llm' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import type { ContentBlock, Message } from '@deepseek-ai/dsh-llm' import { scopeOf } from '@deepseek-ai/dsh-scope' import type { WorkingDirectoryService } from '@deepseek-ai/dsh-working-directory' @@ -107,17 +108,13 @@ function requireAgent(context: OpContext, op: string): Agent { return agent } -function textOf(content: readonly ContentBlock[]): string { - return content.filter((block): block is Extract => block.type === 'text').map(block => block.text).join('') -} - /** * Project one tool outcome onto Claude Code's `tool.call` result. * @param result - the harness tool outcome. * @returns its text as `result`, with `isError` on a failure. */ export function toolCallResultOf(result: ToolExecutionResult): ToolCallResult { - return result.isError ? { result: textOf(result.content), isError: true } : { result: textOf(result.content) } + return result.isError ? { result: extractTextContent(result.content), isError: true } : { result: extractTextContent(result.content) } } /** The model's raw JSON arguments as an object; an unparsable string is an empty input. */ @@ -137,7 +134,7 @@ function sessionMessages(messages: readonly Message[], aliases: ToolNameAliases) const toolUses = message.content .filter((block): block is Extract => block.type === 'tool-call') .map(block => ({ tool_use_id: block.id, tool: aliases.toMod(block.name), input: argumentsOf(block.arguments) })) - out.push({ role: message.role, text: textOf(message.content), toolUses }) + out.push({ role: message.role, text: extractTextContent(message.content), toolUses }) } return out } diff --git a/packages/experimental/claude-code-mods/src/index.ts b/packages/experimental/claude-code-mods/src/index.ts index 5a725ae533..bed288d211 100644 --- a/packages/experimental/claude-code-mods/src/index.ts +++ b/packages/experimental/claude-code-mods/src/index.ts @@ -18,6 +18,7 @@ import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' import type { AssistantMessage, ContentBlock, TokenUsage } from '@deepseek-ai/dsh-llm' import { brandString } from '@deepseek-ai/dsh-brand' import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import type { UserMessage } from '@deepseek-ai/dsh-session' import { scopeOf } from '@deepseek-ai/dsh-scope' import { validateJsonSchemaValue } from '@deepseek-ai/dsh-tools' @@ -78,10 +79,6 @@ function assertPositive(field: string, value: number): void { if (!Number.isFinite(value) || value <= 0) throw new Error(`claude-code-mods: ${field} must be a positive number of milliseconds`) } -function textOf(blocks: readonly ContentBlock[]): string { - return blocks.filter((block): block is Extract => block.type === 'text').map(block => block.text).join('') -} - /** The human's own messages among a claim: the prompt a `prompt.submit` hook sees and may rewrite. */ function promptMessages(claimed: readonly UserMessage[]): UserMessage[] { return claimed.filter(message => message.source.kind === 'user') @@ -141,7 +138,7 @@ interface TurnRecord { /** Fold one committed assistant message into the turn's answer and usage. */ function foldAssistantMessage(turnRecord: TurnRecord, data: { message: AssistantMessage; usage?: TokenUsage }): void { - turnRecord.answer = textOf(data.message.content) + turnRecord.answer = extractTextContent(data.message.content) if (data.usage === undefined) return const { model } = data.message.source const usage = turnRecord.usage ?? { input_tokens: 0, output_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: 0, model } @@ -349,7 +346,7 @@ export class ClaudeCodeMods extends TypertRemoteService { const first = !started.has(turn) started.add(turn) const prompt = promptMessages(messages) - const text = textOf(prompt.flatMap(message => message.content)) + const text = extractTextContent(prompt.flatMap(message => message.content)) let submitted: PromptSubmitResult = { text } // A batch of injected context alone is not a prompt: Claude Code raises prompt.submit for typed prompts. if (prompt.length > 0) { diff --git a/packages/experimental/client-ui-stats/src/client/stats-fold.ts b/packages/experimental/client-ui-stats/src/client/stats-fold.ts index 365a7873f1..fd7c6d78e8 100644 --- a/packages/experimental/client-ui-stats/src/client/stats-fold.ts +++ b/packages/experimental/client-ui-stats/src/client/stats-fold.ts @@ -1,5 +1,6 @@ /** Event folding and per-step metric derivation for the Statistics table. */ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import type { SessionEventLike } from '@deepseek-ai/dsh-api-session-controller/client' import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' import type { AssistantMessage, ContentBlock, StreamChunk, UserMessage } from '@deepseek-ai/dsh-llm' @@ -267,10 +268,7 @@ const OPAQUE_SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9 export function triggerSenderOf(message: UserMessage): string | null { const kind: string = message.source.kind if (kind !== 'agent-message' && kind !== 'team-message') return null - let text = '' - for (const block of message.content) { - if (block.type === 'text') text += block.text - } + const text = extractTextContent(message.content) const team = TEAM_MESSAGE_PREFIX.exec(text) /* v8 ignore next -- a matched capture group is always present. */ if (team !== null) return team[1]?.trim() ?? null @@ -291,11 +289,7 @@ function answerOf(message: AssistantMessage): { body: string truncated: boolean } | null { - const parts: string[] = [] - for (const block of message.content) { - if (block.type === 'text') parts.push(block.text) - } - const text = parts.join('\n').trim() + const text = extractTextContent(message.content, { separator: '\n' }).trim() if (text === '') return null return { preview: text.length > ANSWER_LIMIT ? text.slice(0, ANSWER_LIMIT) : text, diff --git a/packages/experimental/forge-session/package.json b/packages/experimental/forge-session/package.json index 90c20a4398..227cf26989 100644 --- a/packages/experimental/forge-session/package.json +++ b/packages/experimental/forge-session/package.json @@ -43,6 +43,7 @@ }, "peerDependencies": { "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-experimental-forge": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-session-projection": "workspace:*", diff --git a/packages/experimental/forge-session/src/projection.ts b/packages/experimental/forge-session/src/projection.ts index 1f1ab54a43..0a285de34d 100644 --- a/packages/experimental/forge-session/src/projection.ts +++ b/packages/experimental/forge-session/src/projection.ts @@ -1,5 +1,7 @@ /** Projection that folds shell results and binding records into one Session's change request bindings, and shows clients the bindings. */ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' + import { z } from 'zod' import { pluginRecordOf, SessionSeq } from '@deepseek-ai/dsh-session' import type { SessionEvent, SessionEventMap } from '@deepseek-ai/dsh-session' @@ -105,7 +107,7 @@ function applyResult(state: ForgeChangeRequestsState, result: SessionEventMap['t if (pending === undefined) return state const rest = state.pending.filter(entry => entry !== pending) if (result.message.isError === true) return { ...state, pending: rest } - const text = result.message.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('\n') + const text = extractTextContent(result.message.content, { separator: '\n' }) const printed = pending.urls === 'created' ? changeRequestUrls(text) : ownChangeRequestUrls(text) return { pending: rest, diff --git a/packages/experimental/forge-session/src/reference-lookup.ts b/packages/experimental/forge-session/src/reference-lookup.ts index 7cce3eb6dc..b648911c58 100644 --- a/packages/experimental/forge-session/src/reference-lookup.ts +++ b/packages/experimental/forge-session/src/reference-lookup.ts @@ -1,5 +1,7 @@ /** Resolve unqualified CLI references in the shell execution world and persist only confirmed URLs. */ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' + import type { Context } from '@deepseek-ai/cordis' import type { Session } from '@deepseek-ai/dsh-session' import type { ToolExecution, ToolExecutionResult } from '@deepseek-ai/dsh-tools' @@ -53,7 +55,7 @@ export function observeReferences(ctx: Context, timeoutMs: number, record: (sess const argumentsResult = shellArguments.safeParse(exec.arguments) const shell = completedShell.safeParse(result.value) if (!argumentsResult.success || !shell.success) return - const printed = result.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('\n') + const printed = extractTextContent(result.content, { separator: '\n' }) if (ownChangeRequestUrls(printed).length > 0) return const lookups = ghReferences(argumentsResult.data.command).flatMap(reference => reference.lookup === null ? [] : [reference.lookup]) const agent = exec.agent diff --git a/packages/experimental/hooks-claude-code/src/index.ts b/packages/experimental/hooks-claude-code/src/index.ts index 5e2b59d3d8..2541297e3d 100644 --- a/packages/experimental/hooks-claude-code/src/index.ts +++ b/packages/experimental/hooks-claude-code/src/index.ts @@ -13,6 +13,7 @@ import { readFileSync } from 'node:fs' import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { createUserMessage } from '@deepseek-ai/dsh-llm' import type { ContextFormed } from '@deepseek-ai/dsh-llm' declare module '@deepseek-ai/dsh-llm' { @@ -319,11 +320,6 @@ function lastTurn(ctx: Context, agent: Agent | undefined): number { return ctx.agents.turnBoundaryOf(agent.session).lastTurn } -/** Flatten content blocks to the text a hook payload carries (the common case). */ -function blocksToText(content: ContentBlock[]): string { - return content.filter((b): b is Extract => b.type === 'text').map(b => b.text).join('') -} - function base(agent: Agent | undefined, event: string): Record { return { session_id: agent?.session.header.id ?? '', @@ -338,13 +334,13 @@ function sessionStartPayload(agent: Agent, source: string): Record { - return { ...base(agent, 'UserPromptSubmit'), prompt: blocksToText(content) } + return { ...base(agent, 'UserPromptSubmit'), prompt: extractTextContent(content) } } function preToolPayload(exec: ToolExecution): Record { return { ...base(exec.agent, 'PreToolUse'), tool_name: exec.name, tool_input: exec.arguments, tool_use_id: exec.callId } } function postToolPayload(exec: ToolExecution, result: ToolExecutionResult): Record { - return { ...base(exec.agent, 'PostToolUse'), tool_name: exec.name, tool_input: exec.arguments, tool_use_id: exec.callId, tool_response: blocksToText(result.content) } + return { ...base(exec.agent, 'PostToolUse'), tool_name: exec.name, tool_input: exec.arguments, tool_use_id: exec.callId, tool_response: extractTextContent(result.content) } } function stopPayload(agent: Agent): Record { return { ...base(agent, 'Stop'), stop_hook_active: false } diff --git a/packages/experimental/hooks-codex/src/index.ts b/packages/experimental/hooks-codex/src/index.ts index 2d9b3c3daf..6d86ae79f3 100644 --- a/packages/experimental/hooks-codex/src/index.ts +++ b/packages/experimental/hooks-codex/src/index.ts @@ -16,6 +16,7 @@ import { readFileSync } from 'node:fs' import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { createUserMessage } from '@deepseek-ai/dsh-llm' import type { ContextFormed } from '@deepseek-ai/dsh-llm' declare module '@deepseek-ai/dsh-llm' { @@ -203,7 +204,7 @@ export function apply(ctx: Context, config: Config): void { const payload = { ...base(agent, 'UserPromptSubmit', model), turn_id: String(turn), - prompt: blocksToText(messages.flatMap(message => message.content)), + prompt: extractTextContent(messages.flatMap(message => message.content)), } const merged = await runPoint('UserPromptSubmit', '', payload, { agent, turn, plainStdoutAsContext: true, signal, @@ -275,17 +276,12 @@ export function apply(ctx: Context, config: Config): void { // --- Codex DIALECT payloads: snake_case, model on every event, turn_id on // turn-scoped events. --- -// These small payload helpers intentionally remain next to the dialect shape; -// sharing them would pull bridge-only agent/LLM dependencies into hook-protocol. +// Shared hook-protocol code has no Agent dependency, so turn lookup stays in the bridge. /* jscpd:ignore-start */ function lastTurn(ctx: Context, agent: Agent | undefined): number { if (!agent) return 0 return ctx.agents.turnBoundaryOf(agent.session).lastTurn } - -function blocksToText(content: ContentBlock[]): string { - return content.filter((b): b is Extract => b.type === 'text').map(b => b.text).join('') -} /* jscpd:ignore-end */ /** Base fields on every Codex payload (no turn_id). */ @@ -324,5 +320,5 @@ function preToolPayload(ctx: Context, exec: ToolExecution, model: string): Recor } function postToolPayload(ctx: Context, exec: ToolExecution, result: ToolExecutionResult, model: string): Record { - return { ...turnBase(ctx, exec.agent, 'PostToolUse', model), tool_name: exec.name, tool_input: { command: commandOf(exec.arguments) }, tool_use_id: exec.callId, tool_response: blocksToText(result.content) } + return { ...turnBase(ctx, exec.agent, 'PostToolUse', model), tool_name: exec.name, tool_input: { command: commandOf(exec.arguments) }, tool_use_id: exec.callId, tool_response: extractTextContent(result.content) } } diff --git a/packages/experimental/session-title-all-prompts-llm/src/index.ts b/packages/experimental/session-title-all-prompts-llm/src/index.ts index 042267bc49..f2623be0c4 100644 --- a/packages/experimental/session-title-all-prompts-llm/src/index.ts +++ b/packages/experimental/session-title-all-prompts-llm/src/index.ts @@ -3,7 +3,8 @@ /* jscpd:ignore-start -- both shipped providers import the same shared packages. */ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' -import type { LlmResolvedModelInfo, ReasoningEffortId } from '@deepseek-ai/dsh-llm' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' +import { type LlmResolvedModelInfo, type ReasoningEffortId } from '@deepseek-ai/dsh-llm' import { assertNever } from '@deepseek-ai/dsh-util-values' import { brandString } from '@deepseek-ai/dsh-brand' import type { SessionTitleProviderId } from '@deepseek-ai/dsh-session-title/types' @@ -137,10 +138,7 @@ function titleFromResponse(response: SessionTitleLlmResponse): string { if (response.blocks.some(block => block.type === 'tool-call')) { throw new Error('session-title-llm: title output must contain text only') } - const text = response.blocks - .filter((block): block is Extract<(typeof response.blocks)[number], { type: 'text' }> => block.type === 'text') - .map(block => block.text) - .join(' ') + const text = extractTextContent(response.blocks, { separator: ' ' }) const title = normalizeSessionTitle(titleFromOutput(text), Number.MAX_SAFE_INTEGER) if (title.length === 0) throw new Error('session-title-llm: title model produced no text') return title diff --git a/packages/llm/llm-deepseek/src/serialize.ts b/packages/llm/llm-deepseek/src/serialize.ts index f08412c0e9..ab5e0f75d7 100644 --- a/packages/llm/llm-deepseek/src/serialize.ts +++ b/packages/llm/llm-deepseek/src/serialize.ts @@ -1,5 +1,6 @@ /** Map system snapshots, tool changes, and conversation turns to Messages using the configured route capability. */ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { LlmError, requestImageHandleText } from '@deepseek-ai/dsh-llm' import type { ContentBlock, GenerateOptions, ImageAttachmentAccessResolver, Message, RequestMessage } from '@deepseek-ai/dsh-llm' import type { ImageAttachmentRef, RequestImageAttachment } from '@deepseek-ai/dsh-attachment' @@ -104,9 +105,8 @@ export function serialize( return unsupported('tool-change blocks outside developer messages') } if (message.role === 'system') { - const texts = message.content.filter(block => block.type === 'text') - if (texts.length !== message.content.length) return unsupported('non-text system message') - const text = texts.map(block => block.text).join('') + if (message.content.some(block => block.type !== 'text')) return unsupported('non-text system message') + const text = extractTextContent(message.content) if (inHistory && messages.length > 0) { if (text.length === 0) return unsupported('empty in-history system update') systemUpdates.push({ role: 'system', content: [{ type: 'text', text }] }) diff --git a/packages/llm/llm-pi-ai/src/context.ts b/packages/llm/llm-pi-ai/src/context.ts index d8a657d4e6..fa8b833d43 100644 --- a/packages/llm/llm-pi-ai/src/context.ts +++ b/packages/llm/llm-pi-ai/src/context.ts @@ -5,6 +5,7 @@ */ import { brandString } from '@deepseek-ai/dsh-brand' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { contentHasImage, IMAGE_OFFLOAD_REQUIRED_CODE, LlmError, offloadedImageText, projectOffloadedImages, requestImageHandleText, requiredImageOffload } from '@deepseek-ai/dsh-llm' import type { ContentBlock, GenerateOptions, ImageAttachmentAccessResolver, Message, RequestMessage, ToolCallId } from '@deepseek-ai/dsh-llm' import type { AttachmentId } from '@deepseek-ai/dsh-attachment/types' @@ -20,15 +21,6 @@ import type { PrefixDigests } from './prefix-binding.ts' import { requestImageDimensions } from '@deepseek-ai/dsh-attachment' import { DEFAULT_REQUEST_IMAGE_MAX_BYTES, DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET } from './config.ts' -/** Join the text blocks of a harness message. */ -function flattenText(message: RequestMessage): string { - return message.content - .filter(block => block.type === 'text') - .map(block => block.text) - .join('') -} - - /** Recover the pi-ai toolResult message for one harness tool-role message. */ function toolResultOf( message: Extract, @@ -94,7 +86,7 @@ function userContent( break } } - if (content.every(block => block.type === 'text')) return content.map(block => block.text).join('') + if (content.every(block => block.type === 'text')) return extractTextContent(content) return content } @@ -151,7 +143,7 @@ function splitSystemPrompt(options: GenerateOptions): SystemPromptSplit { let end = 0 for (const message of options.messages) { if (message.role !== 'system') break - text.push(flattenText(message)) + text.push(extractTextContent(message.content)) end++ } const systemPrompt = text.filter(Boolean).join('\n\n') @@ -230,7 +222,7 @@ function appendSharedHistory( return true } if (message.role === 'system') { - const content = flattenText(message) + const content = extractTextContent(message.content) if (content.length > 0) { if (supportsMidConvoSystemMessages) { messages.push({ role: 'system', content, timestamp: 0 }) @@ -264,10 +256,10 @@ function textOnlyContext( } if (appendSharedHistory(message, options, messages, toolNames, supportsMidConvoSystemMessages, onReplayDegrade, prefixDigests)) continue if (message.role === 'tool') { - messages.push(toolResultOf(message, toolNames, flattenText(message))) + messages.push(toolResultOf(message, toolNames, extractTextContent(message.content))) continue } - messages.push({ role: 'user', content: flattenText(message), timestamp: 0 }) + messages.push({ role: 'user', content: extractTextContent(message.content), timestamp: 0 }) } return piContext(split.systemPrompt, options, messages) } diff --git a/packages/llm/llm/README.i18n.yaml b/packages/llm/llm/README.i18n.yaml index 1bc7dd7016..ee9b1d0bd5 100644 --- a/packages/llm/llm/README.i18n.yaml +++ b/packages/llm/llm/README.i18n.yaml @@ -24,8 +24,8 @@ en: cf221d60fb42a278 zh: 0ea17503495d386b /deepseek-ai-dsh-llm/use-this-package/what-you-can-do: - en: dc61eb86585f6e0d - zh: 9c0d6b240dfd2cda + en: cb9f0c6ee3203ab3 + zh: 8513340a40192513 /deepseek-ai-dsh-llm/use-this-package/failures-and-recovery: en: 47f4dab3c377a4cd zh: 49ac1c366de19136 @@ -36,8 +36,8 @@ en: 12d0444c18a397c7 zh: 9d4a5468b4bb7fcd /deepseek-ai-dsh-llm/understand-the-implementation/source-map: - en: ae1618577f4e8364 - zh: a6e8ab1563c08dfb + en: 8ec1ca8903e09bc0 + zh: 77c7bc3413cbab1c /deepseek-ai-dsh-llm/understand-the-implementation/main-flow: en: c95d4947745e39bb zh: ec37b969f27629e2 diff --git a/packages/llm/llm/README.md b/packages/llm/llm/README.md index e5d2838586..1419acbe3b 100644 --- a/packages/llm/llm/README.md +++ b/packages/llm/llm/README.md @@ -85,6 +85,7 @@ const configure = (maxTokens: number): ConfigureCall => ### What you can do +- **Extract content text** — `extractTextContent(content, options?)` from `@deepseek-ai/dsh-llm/message` joins only `text` blocks in order, preserving whitespace and empty text blocks while omitting all other block types without placeholders. The optional `options.separator` defaults to `''`. It accepts read-only content and returns `''` when no text blocks exist. - **Stream one model call** — `ctx.llm.stream(options)` yields raw chunks (token-level deltas) for any registered provider and model; consumers assemble them with `BlockAssembler`. - **Register provider adapters** — an adapter owns one or more provider routes, and its registration captures that route's retry policy; registering the same route twice fails with `DUPLICATE_ADAPTER`. - **Expose and activate providers through configuration** — adapters declare configurable-provider routes plus a settings namespace, so configuration surfaces can activate dormant providers and edit connection facts without a restart. `LlmConfigurableProvider.error` reports a configuration diagnostic for repair; unaffected models can remain serviceable. An entry can also carry `defaultBaseURL`, the endpoint the adapter uses when the profile sets none, and `nativeAuth`, the environment variables and OAuth sign-in that the adapter's authentication reads when the profile names no credential reference; `baseURLEnv` lists environment variables used to configure the endpoint. Configuration UIs read these fields from the directory without calling the adapter. @@ -116,7 +117,7 @@ The service is built on one separation: **the logical contract is provider-neutr |---|---| | [`src/index.ts`](src/index.ts) | The `LlmRuntime` service: adapter registry, configurable-provider directory, model discovery, call preparation, and the streaming boundary | | [`src/types.ts`](src/types.ts) | The `StreamChunk` protocol, content-block map, finish reasons, and shared vocabulary | -| [`src/message.ts`](src/message.ts) | Immutable message constructors shared by delivery, history, and requests | +| [`src/message.ts`](src/message.ts) | Content text extraction and immutable message constructors shared by delivery, history, and requests | | [`src/assembler.ts`](src/assembler.ts) | `BlockAssembler`: incremental chunk-to-block assembly | | [`src/assistant-stream.ts`](src/assistant-stream.ts) | Compact timed Assistant stream accumulation, strict validation, exact expansion, and record-level readers | | [`src/call-config.ts`](src/call-config.ts) | Call-config validation, adapter-default materialization, and request freezing | diff --git a/packages/llm/llm/README.zh.md b/packages/llm/llm/README.zh.md index 21e2b778ba..777d877ff0 100644 --- a/packages/llm/llm/README.zh.md +++ b/packages/llm/llm/README.zh.md @@ -85,6 +85,7 @@ const configure = (maxTokens: number): ConfigureCall => ### 你可以做什么 +- **提取内容文本**——从 `@deepseek-ai/dsh-llm/message` 导入的 `extractTextContent(content, options?)` 按顺序仅拼接 `text` 块,保留空白与空文本块,忽略所有其他块类型且不生成占位符。可选的 `options.separator` 默认为 `''`。它接受只读内容,没有文本块时返回 `''`。 - **流式发起一次模型调用**——`ctx.llm.stream(options)` 为任何已注册提供方与模型产出原始分片(token 级增量);消费方用 `BlockAssembler` 组装。 - **注册提供方适配器**——一个适配器拥有一个或多个提供方路由,其注册会捕获该路由的重试策略;重复注册同一路由会以 `DUPLICATE_ADAPTER` 失败。 - **通过配置暴露并激活提供方**——适配器声明可配置提供方路由与 settings namespace,配置界面因此可以激活休眠提供方并编辑连接信息,无需重启。`LlmConfigurableProvider.error` 报告供修复的配置诊断;未受影响的模型仍可提供服务。条目还可携带 `defaultBaseURL`,即配置未设置端点时适配器使用的端点;以及 `nativeAuth`,即配置未指定凭据引用时适配器认证读取的环境变量与 OAuth 登录;`baseURLEnv` 列出配置端点所用的环境变量。配置界面直接从目录读取这些字段,无需调用适配器。 @@ -116,7 +117,7 @@ const configure = (maxTokens: number): ConfigureCall => |---|---| | [`src/index.ts`](src/index.ts) | `LlmRuntime` 服务:适配器注册表、可配置提供方目录、模型发现、调用准备与流式边界 | | [`src/types.ts`](src/types.ts) | `StreamChunk` 协议、内容块映射、结束原因与共享词汇 | -| [`src/message.ts`](src/message.ts) | 投递、历史与请求共享的不可变消息构造函数 | +| [`src/message.ts`](src/message.ts) | 内容文本提取与投递、历史、请求共享的不可变消息构造函数 | | [`src/assembler.ts`](src/assembler.ts) | `BlockAssembler`:分片到块的增量组装 | | [`src/assistant-stream.ts`](src/assistant-stream.ts) | 带时间信息的紧凑 Assistant 流累积、严格校验、精确展开与记录级读取器 | | [`src/call-config.ts`](src/call-config.ts) | 调用配置校验、适配器默认值填入与请求冻结 | diff --git a/packages/llm/llm/src/index.ts b/packages/llm/llm/src/index.ts index cd1aa71ca8..7475ad9a18 100644 --- a/packages/llm/llm/src/index.ts +++ b/packages/llm/llm/src/index.ts @@ -49,7 +49,11 @@ export * from './api-key.ts' export type * from './types.ts' export * from './content.ts' export * from './assistant-stream.ts' -export * from './message.ts' +export type * from './message.ts' +export { + CONTEXT_SUMMARY_MAX_CHARS, boundContextSummary, createAssistantMessage, createDeveloperMessage, createMessage, + createSystemMessage, createToolResultMessage, createUserMessage, freezeMessage, +} from './message.ts' export * from './retry-policy.ts' export { BlockAssembler } from './assembler.ts' export { callConfigEquals, isAgentLoopRequest, markAgentLoopRequest } from './call-config.ts' diff --git a/packages/llm/llm/src/message.ts b/packages/llm/llm/src/message.ts index 0138452426..fc43cbadbc 100644 --- a/packages/llm/llm/src/message.ts +++ b/packages/llm/llm/src/message.ts @@ -1,4 +1,4 @@ -/** Message value types, identity, and immutable construction helpers. */ +/** Message value types, content text extraction, identity, and immutable construction helpers. */ import { randomUUID } from '@deepseek-ai/dsh-util-crypto' import { brandString } from '@deepseek-ai/dsh-brand' @@ -304,3 +304,16 @@ export function createToolResultMessage(input: ToolResultMessageInput): ToolResu isError: input.isError, }) } + +/** + * Extract and join only text blocks in content order, preserving their whitespace. + * Non-text blocks contribute neither text nor separators; content is not modified. + * Import from `@deepseek-ai/dsh-llm/message` in Host and browser code. + * @param content - source blocks to read in their existing order. + * @param options - optional text extraction settings. + * @param options.separator - text inserted between text blocks; defaults to an empty string. + * @returns joined text, or an empty string when no text blocks are present. + */ +export function extractTextContent(content: readonly ContentBlock[], options?: { separator?: string }): string { + return content.filter(block => block.type === 'text').map(block => block.text).join(options?.separator ?? '') +} diff --git a/packages/llm/llm/tests/message.spec.ts b/packages/llm/llm/tests/message.spec.ts index d3e3ba995e..f70710672e 100644 --- a/packages/llm/llm/tests/message.spec.ts +++ b/packages/llm/llm/tests/message.spec.ts @@ -1,5 +1,6 @@ import { describe, expect, expectTypeOf, it } from 'vitest' import { brandString } from '@deepseek-ai/dsh-brand' +import type { AttachmentId } from '@deepseek-ai/dsh-attachment' import { type ToolCallId, boundContextSummary, @@ -12,6 +13,46 @@ import { freezeMessage, type MessageId, } from '@deepseek-ai/dsh-llm' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' + +describe('extractTextContent', () => { + it('preserves whitespace and empty text blocks while omitting non-text blocks', () => { + const message = createUserMessage({ + source: { kind: 'test' }, + content: [ + { type: 'text', text: ' \talpha\n' }, + { type: 'reasoning', text: 'private reasoning' }, + { type: 'image', attachment: { + attachmentId: brandString(`sha256:${'a'.repeat(64)}`), + mediaType: 'image/png', bytes: 1, width: 1, height: 1, + } }, + { type: 'tool-call', id: brandString('call'), name: 'tool', arguments: '{}' }, + { type: 'text', text: '' }, + { type: 'tool-removal', toolName: 'removed' }, + { type: 'text', text: 'β \r\n' }, + ], + }) + expect(extractTextContent(message.content)).toBe(' \talpha\nβ \r\n') + expect(extractTextContent(message.content, undefined)).toBe(' \talpha\nβ \r\n') + expect(extractTextContent(message.content, {})).toBe(' \talpha\nβ \r\n') + expect(extractTextContent(message.content, { separator: '' })).toBe(' \talpha\nβ \r\n') + expect(extractTextContent(message.content, { separator: '\n' })).toBe(' \talpha\n\n\nβ \r\n') + expect(extractTextContent(message.content, { separator: ' ' })).toBe(' \talpha\n β \r\n') + expect(extractTextContent(message.content, { separator: '::' })).toBe(' \talpha\n::::β \r\n') + expect(Object.isFrozen(message.content)).toBe(true) + expect(message.content[0]).toEqual({ type: 'text', text: ' \talpha\n' }) + }) + + it('returns empty text when there are no text blocks and keeps separators between empty text blocks', () => { + expect(extractTextContent([])).toBe('') + expect(extractTextContent([{ type: 'reasoning', text: 'not plain text' }], { separator: '\n' })).toBe('') + expect(extractTextContent([ + { type: 'text', text: '' }, + { type: 'reasoning', text: 'ignored' }, + { type: 'text', text: '' }, + ], { separator: '\n' })).toBe('\n') + }) +}) describe('message construction', () => { it('detaches and freezes developer tool names without copying their definitions', () => { diff --git a/packages/sdk/server/src/query-activity.ts b/packages/sdk/server/src/query-activity.ts index 17a4fc9148..7bf4c8b7bf 100644 --- a/packages/sdk/server/src/query-activity.ts +++ b/packages/sdk/server/src/query-activity.ts @@ -1,5 +1,7 @@ /** Observe command-admitted activity through quiescence and preserve a goal's first terminal outcome. */ +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' + import type { Context } from '@deepseek-ai/cordis' import type { Agent } from '@deepseek-ai/dsh-agent' import type { GoalView } from '@deepseek-ai/dsh-goal' @@ -63,7 +65,7 @@ export class QueryActivity { } if (this.input || this.goalId !== undefined) { if (event.type === 'assistant/message') { - this.response = event.data.message.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('') + this.response = extractTextContent(event.data.message.content) } if (event.type === 'turn/end') this.turnReason = event.data.reason.kind } diff --git a/packages/session/session-title-first-prompt-llm/src/index.ts b/packages/session/session-title-first-prompt-llm/src/index.ts index 7515630a88..099cf3c830 100644 --- a/packages/session/session-title-first-prompt-llm/src/index.ts +++ b/packages/session/session-title-first-prompt-llm/src/index.ts @@ -3,7 +3,8 @@ /* jscpd:ignore-start -- both shipped providers import the same shared packages. */ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' -import type { LlmResolvedModelInfo, ReasoningEffortId } from '@deepseek-ai/dsh-llm' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' +import { type LlmResolvedModelInfo, type ReasoningEffortId } from '@deepseek-ai/dsh-llm' import { assertNever } from '@deepseek-ai/dsh-util-values' import { brandString } from '@deepseek-ai/dsh-brand' import type { SessionTitleProviderId } from '@deepseek-ai/dsh-session-title/types' @@ -128,10 +129,7 @@ function titleFromResponse(response: SessionTitleLlmResponse): string { if (response.blocks.some(block => block.type === 'tool-call')) { throw new Error('session-title-llm: title output must contain text only') } - const text = response.blocks - .filter((block): block is Extract<(typeof response.blocks)[number], { type: 'text' }> => block.type === 'text') - .map(block => block.text) - .join(' ') + const text = extractTextContent(response.blocks, { separator: ' ' }) const title = normalizeSessionTitle(titleFromOutput(text), Number.MAX_SAFE_INTEGER) if (title.length === 0) throw new Error('session-title-llm: title model produced no text') return title diff --git a/packages/session/session-title/src/index.ts b/packages/session/session-title/src/index.ts index c80ae7e830..9917187dba 100644 --- a/packages/session/session-title/src/index.ts +++ b/packages/session/session-title/src/index.ts @@ -8,6 +8,7 @@ import z from '@deepseek-ai/schemastery' import { z as zod } from 'zod' import type { ZodType } from 'zod' import type { Branded } from '@deepseek-ai/dsh-brand' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import { isAgentLoopRequest } from '@deepseek-ai/dsh-llm' import type { GenerateOptions } from '@deepseek-ai/dsh-llm' import { assertNever, deepFreeze } from '@deepseek-ai/dsh-util-values' @@ -137,10 +138,7 @@ export interface SessionTitleProvider { function sessionTitleUserMessageOf(event: SessionEvent): SessionTitleUserMessage | undefined { if (event.type !== 'user/message' || event.data.source.kind !== 'user') return undefined const content = event.data.content - const text = content - .filter((block): block is Extract<(typeof content)[number], { type: 'text' }> => block.type === 'text') - .map(block => block.text) - .join('\n') + const text = extractTextContent(content, { separator: '\n' }) if (normalizeSessionTitle(text, Number.MAX_SAFE_INTEGER).length === 0) return undefined return { seq: event.seq, text } } diff --git a/packages/web/web-deepseek-api/src/index.ts b/packages/web/web-deepseek-api/src/index.ts index 555bab178b..4da54814ea 100644 --- a/packages/web/web-deepseek-api/src/index.ts +++ b/packages/web/web-deepseek-api/src/index.ts @@ -21,7 +21,8 @@ import z from '@deepseek-ai/schemastery' import type {} from '@deepseek-ai/dsh-agent' import { credentialRef, type CredentialRef } from '@deepseek-ai/dsh-credentials' import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment' -import type {} from '@deepseek-ai/dsh-llm' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' + import { deepSeekApiKeyConfigured, rejectDeepSeekAccountToken, resolveDeepSeekAccountToken, resolveDeepSeekApiKey, } from '@deepseek-ai/dsh-llm-deepseek' @@ -156,7 +157,7 @@ const CAPABILITY = { function latestUserQuestion(session: Session | undefined): string | undefined { const prompt = session?.deriveMessages().findLast(message => message.role === 'user' && message.source.kind === 'user') if (prompt === undefined) return undefined - return prompt.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('\n') + return extractTextContent(prompt.content, { separator: '\n' }) } /** diff --git a/packages/workflow/workflow-ptc/src/guest-source.ts b/packages/workflow/workflow-ptc/src/guest-source.ts index ff57ab8e8f..86ae9078ed 100644 --- a/packages/workflow/workflow-ptc/src/guest-source.ts +++ b/packages/workflow/workflow-ptc/src/guest-source.ts @@ -1,4 +1,4 @@ /** Generated by scripts/gen-workflow-guest.ts. Do not edit directly. */ /** Self-contained ESM guest transported into the mounted PTC runtime. */ -export const WORKFLOW_GUEST_SOURCE = "import * as vm from \"node:vm\";\n//#region packages/workflow/workflow-ptc/src/realm.ts\n/**\n* Materializes script VM values as plain JSON and renders thrown values.\n* Getters and proxy traps may execute inside the confined Node process;\n* process isolation and cancellation belong to PTC, not the VM.\n* @module @deepseek-ai/dsh-workflow-ptc/realm\n*/\n/** Thrown by {@link materializeFromRealm}; the caller wraps it into the right `WorkflowError` code. */\nvar MaterializeError = class extends Error {\n\tpath;\n\treason;\n\tconstructor(path, reason) {\n\t\tsuper(`${path}: ${reason}`);\n\t\tthis.path = path;\n\t\tthis.reason = reason;\n\t\tthis.name = \"MaterializeError\";\n\t}\n};\n/**\n* Render a thrown value to failure text without ever throwing: prefer the\n* `stack` (host or realm — a realm error's `stack` is a plain string read),\n* fall back to `message`, then `String()`. Reading those properties MAY run\n* script code; if that code itself throws, a fixed label is returned instead.\n* @param error - any value thrown in the host or guest realm.\n* @returns human-readable text for the failure report; prefers the stack.\n*/\nfunction renderThrown(error) {\n\ttry {\n\t\tconst stack = error?.stack;\n\t\tif (typeof stack === \"string\" && stack.length > 0) return stack;\n\t\tconst message = error?.message;\n\t\tif (typeof message === \"string\" && message.length > 0) return message;\n\t\treturn String(error);\n\t} catch {\n\t\treturn \"[unrenderable thrown value]\";\n\t}\n}\n/**\n* Whether an object's prototype chain represents a plain data object: `null`, or a prototype\n* whose own prototype is `null` (the realm's `Object.prototype` — which we\n* cannot compare by identity across realms). A `Date`/`Map`/class instance\n* has a longer chain and is rejected.\n*/\nfunction hasPlainPrototype(value) {\n\tconst proto = Object.getPrototypeOf(value);\n\tif (proto === null) return true;\n\treturn Object.getPrototypeOf(proto) === null;\n}\n/**\n* Copy `value` (typically from the vm realm) into plain host JSON data. Root `undefined` is\n* returned unchanged; nested `undefined` and values JSON cannot represent losslessly fail\n* with the offending path. Property accessors run normally, and a throwing read is wrapped\n* with its rendered failure.\n*\n* @param value - the realm value to materialize.\n* @param root - the path label for the root value (error messages).\n* @returns the host-realm copy (plain objects/arrays/scalars only).\n* @throws {@link MaterializeError} for unsupported values, cycles, sparse arrays, exotic\n* prototypes, or property reads that throw.\n*/\nfunction materializeFromRealm(value, root = \"value\") {\n\tif (value === void 0) return void 0;\n\ttry {\n\t\treturn materialize(value, root, /* @__PURE__ */ new Set());\n\t} catch (error) {\n\t\tif (error instanceof MaterializeError) throw error;\n\t\tthrow new MaterializeError(root, `reading the value threw: ${renderThrown(error)}`);\n\t}\n}\nfunction materialize(value, path, seen) {\n\tswitch (typeof value) {\n\t\tcase \"boolean\":\n\t\tcase \"string\": return value;\n\t\tcase \"number\":\n\t\t\tif (!Number.isFinite(value)) throw new MaterializeError(path, \"non-finite numbers are not JSON data\");\n\t\t\treturn value;\n\t\tcase \"bigint\": throw new MaterializeError(path, \"bigints are not JSON data\");\n\t\tcase \"function\": throw new MaterializeError(path, \"functions are not plain JSON data\");\n\t\tcase \"symbol\": throw new MaterializeError(path, \"symbols are not plain JSON data\");\n\t\tcase \"undefined\": throw new MaterializeError(path, \"undefined is not JSON data\");\n\t\tcase \"object\": break;\n\t}\n\tif (value === null) return null;\n\tconst objectValue = value;\n\tif (seen.has(objectValue)) throw new MaterializeError(path, \"circular references are not JSON data\");\n\tseen.add(objectValue);\n\ttry {\n\t\tif (Array.isArray(objectValue)) return materializeArray(objectValue, path, seen);\n\t\treturn materializeObject(objectValue, path, seen);\n\t} finally {\n\t\tseen.delete(objectValue);\n\t}\n}\nfunction materializeArray(value, path, seen) {\n\tconst out = [];\n\tfor (let index = 0; index < value.length; index++) {\n\t\tif (!(index in value)) throw new MaterializeError(`${path}[${index}]`, \"sparse arrays are not JSON data\");\n\t\tout.push(materialize(value[index], `${path}[${index}]`, seen));\n\t}\n\tfor (const key of Object.keys(value)) {\n\t\tconst index = Number(key);\n\t\tif (!Number.isInteger(index) || index < 0 || index >= value.length) throw new MaterializeError(`${path}.${key}`, \"arrays with non-index properties are not JSON data\");\n\t}\n\tif (Object.getOwnPropertySymbols(value).length > 0) throw new MaterializeError(path, \"symbol-keyed properties are not plain JSON data\");\n\treturn out;\n}\nfunction materializeObject(value, path, seen) {\n\tif (!hasPlainPrototype(value)) throw new MaterializeError(path, \"only plain objects and arrays are JSON data (exotic prototype)\");\n\tif (Object.getOwnPropertySymbols(value).length > 0) throw new MaterializeError(path, \"symbol-keyed properties are not plain JSON data\");\n\tconst out = {};\n\tfor (const key of Object.keys(value)) Object.defineProperty(out, key, {\n\t\tvalue: materialize(value[key], `${path}.${key}`, seen),\n\t\tenumerable: true,\n\t\twritable: true,\n\t\tconfigurable: true\n\t});\n\treturn out;\n}\n//#endregion\n//#region packages/util/brand/src/index.ts\n/**\n* Apply a compile-time string brand without changing the value.\n* @param value - string admitted by the domain that owns the target brand.\n* @returns the same string with the requested compile-time brand.\n*/\nfunction brandString(value) {\n\treturn value;\n}\n//#endregion\n//#region packages/util/error/src/index.ts\n/**\n* Harness error base with a stable machine-routable code and chained cause.\n* Package errors extend it so tool results and replay can retain failure class.\n* @module @deepseek-ai/dsh-error\n*/\n/**\n* Base class for all harness errors. Carries a `code` (stable, programmatic —\n* e.g. `NO_ADAPTER`, `INVALID_ARGS`) distinct from the\n* human-readable `message`, and supports `cause` chaining via the standard\n* `ErrorOptions`. `name` defaults to the subclass constructor name.\n*/\nvar HarnessError = class extends Error {\n\t/** Stable machine-routable failure class (e.g. `RATE_LIMIT`); route on this, never by parsing `message`. */\n\tcode;\n\tconstructor(message, code, options) {\n\t\tsuper(message, options);\n\t\tthis.code = code;\n\t\tthis.name = new.target.name;\n\t}\n};\n//#endregion\n//#region packages/util/values/src/index.ts\n/**\n* Mark an unreachable closed-union branch.\n* @param value - impossible value; an unhandled typed variant fails at the call site.\n* @param context - optional switch-site label included in the failure message.\n* @returns never; a runtime value that escaped its type always throws.\n*/\nfunction assertNever(value, context) {\n\tconst rendered = JSON.stringify(value) ?? String(value);\n\tthrow new Error(`unreachable variant${context ? ` in ${context}` : \"\"}: ${rendered}`);\n}\n/** Whether a realm-owned intrinsic prototype has a native constructor matching this engine's representation. */\nfunction hasIntrinsicConstructor$1(prototype, name) {\n\tconst constructor = Object.getOwnPropertyDescriptor(prototype, \"constructor\")?.value;\n\tif (typeof constructor !== \"function\") return false;\n\ttry {\n\t\treturn constructor.name === name && constructor.prototype === prototype && Function.prototype.toString.call(constructor) === Function.prototype.toString.call(name === \"Array\" ? Array : Object);\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Whether a candidate is one realm's intrinsic `Object.prototype`. */\nfunction isIntrinsicObjectPrototype$1(value) {\n\treturn Object.getPrototypeOf(value) === null && hasIntrinsicConstructor$1(value, \"Object\");\n}\n/** Whether an array uses one realm's intrinsic `Array.prototype`, not a subclass or forged prototype. */\nfunction hasPlainArrayPrototype$1(value) {\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (!Array.isArray(prototype) || !hasIntrinsicConstructor$1(prototype, \"Array\")) return false;\n\tconst objectPrototype = Object.getPrototypeOf(prototype);\n\treturn typeof objectPrototype === \"object\" && objectPrototype !== null && isIntrinsicObjectPrototype$1(objectPrototype);\n}\n/** Whether an object is a plain or null-prototype record from any JavaScript realm. */\nfunction hasPlainObjectPrototype(value) {\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === null || typeof prototype === \"object\" && isIntrinsicObjectPrototype$1(prototype);\n}\n/** Return every JSON-visible object key, or reject own data JSON would discard. */\nfunction enumerableStringKeys(value) {\n\tconst keys = Reflect.ownKeys(value);\n\tif (keys.some((key) => typeof key !== \"string\" || !Object.prototype.propertyIsEnumerable.call(value, key))) return void 0;\n\treturn keys;\n}\n/** Validate lossless JSON iteratively, optionally materializing a detached snapshot. */\nfunction walkJsonValue(value, detach) {\n\tconst ancestors = /* @__PURE__ */ new Set();\n\tlet root;\n\tlet parent;\n\tconst assign = (item) => {\n\t\tif (parent === void 0) {\n\t\t\tif (detach) root = item;\n\t\t} else if (parent.kind === \"array\") {\n\t\t\tif (parent.target !== void 0) parent.target[parent.key] = item;\n\t\t} else if (parent.target !== void 0) Object.defineProperty(parent.target, parent.key, {\n\t\t\tvalue: item,\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true\n\t\t});\n\t};\n\tconst frames = [];\n\tlet current = value;\n\tfor (;;) {\n\t\tif (current === null) assign(null);\n\t\telse if (typeof current === \"boolean\" || typeof current === \"string\") assign(current);\n\t\telse if (typeof current === \"number\") {\n\t\t\tif (!Number.isFinite(current) || Object.is(current, -0)) return void 0;\n\t\t\tassign(current);\n\t\t} else {\n\t\t\tif (typeof current !== \"object\") return void 0;\n\t\t\tif (ancestors.has(current)) return void 0;\n\t\t\tif (Array.isArray(current)) {\n\t\t\t\tif (!hasPlainArrayPrototype$1(current)) return void 0;\n\t\t\t\tconst length = current.length;\n\t\t\t\tif (Reflect.ownKeys(current).length !== length + 1) return void 0;\n\t\t\t\tconst target = detach ? [] : void 0;\n\t\t\t\tif (target !== void 0) assign(target);\n\t\t\t\tlet indices;\n\t\t\t\tif (!Number.isInteger(length)) {\n\t\t\t\t\tindices = [];\n\t\t\t\t\tfor (let index = length - 1; index >= 0; index--) indices.push(index);\n\t\t\t\t}\n\t\t\t\tframes.push({\n\t\t\t\t\tkind: \"array\",\n\t\t\t\t\tsource: current,\n\t\t\t\t\tlength: indices?.length ?? length,\n\t\t\t\t\tindex: 0,\n\t\t\t\t\tkey: 0,\n\t\t\t\t\tindices,\n\t\t\t\t\ttarget\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tif (!hasPlainObjectPrototype(current)) return void 0;\n\t\t\t\tconst keys = enumerableStringKeys(current);\n\t\t\t\tif (keys === void 0) return void 0;\n\t\t\t\tconst target = detach ? {} : void 0;\n\t\t\t\tif (target !== void 0) assign(target);\n\t\t\t\tframes.push({\n\t\t\t\t\tkind: \"object\",\n\t\t\t\t\tsource: current,\n\t\t\t\t\tkeys,\n\t\t\t\t\tindex: 0,\n\t\t\t\t\tkey: \"\",\n\t\t\t\t\ttarget\n\t\t\t\t});\n\t\t\t}\n\t\t\tancestors.add(current);\n\t\t}\n\t\tfor (;;) {\n\t\t\tconst frame = frames.at(-1);\n\t\t\tif (frame === void 0) return detach ? root : true;\n\t\t\tconst length = frame.kind === \"array\" ? frame.length : frame.keys.length;\n\t\t\tif (frame.index >= length) {\n\t\t\t\tancestors.delete(frame.source);\n\t\t\t\tframes.pop();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst index = frame.index++;\n\t\t\tparent = frame;\n\t\t\tif (frame.kind === \"array\") {\n\t\t\t\tconst key = frame.indices === void 0 ? index : frame.indices[frame.indices.length - index - 1];\n\t\t\t\t/* v8 ignore next -- the loop is bounded by the captured index count. */\n\t\t\t\tif (key === void 0) return void 0;\n\t\t\t\tif (!Object.prototype.hasOwnProperty.call(frame.source, key)) return void 0;\n\t\t\t\tframe.key = key;\n\t\t\t\tcurrent = frame.source[key];\n\t\t\t} else {\n\t\t\t\tconst key = frame.keys[index];\n\t\t\t\t/* v8 ignore next -- the loop is bounded by the captured key count. */\n\t\t\t\tif (key === void 0) return void 0;\n\t\t\t\tframe.key = key;\n\t\t\t\tcurrent = frame.source[key];\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n}\n/**\n* Test the same lossless JSON rules as {@link snapshotJsonValue} without detaching the value.\n* @param value - candidate value to test.\n* @returns whether the value survives a JSON round trip without loss.\n*/\nfunction isJsonValue(value) {\n\treturn walkJsonValue(value, false) === true;\n}\n//#endregion\n//#region packages/core/tools/src/json-schema.ts\n/**\n* Enforced JSON Schema subset shared by tool outputs, generated PTC mode\n* types, subagents, and workflows. The subset accepts any JSON root, an\n* annotation-only schema for unconstrained JSON, one scalar `type`, object\n* `properties`/`required`/boolean `additionalProperties`, array `items`,\n* type-correct scalar `enum`/`const`, and exact-one `oneOf`.\n*\n* Unsupported or misplaced keywords reject rather than being accepted without\n* enforcement. Consumers that require an object root apply\n* {@link assertObjectJsonSchema} before accepting input.\n* @module dsh-tools/json-schema\n*/\n/**\n* Thrown when a raw schema falls outside the enforced subset. `violations`\n* lists every offending path instead of stopping at the first author error.\n*/\nvar JsonSchemaError = class extends HarnessError {\n\t/** Individual schema violations in walk order. */\n\tviolations;\n\tconstructor(violations) {\n\t\tsuper(`unsupported JSON schema: ${violations.join(\"; \")}`, \"UNSUPPORTED_SCHEMA\");\n\t\tthis.name = \"JsonSchemaError\";\n\t\tthis.violations = violations;\n\t}\n};\nconst CONSTRAINT_KEYWORDS = new Set([\n\t\"type\",\n\t\"oneOf\",\n\t\"properties\",\n\t\"required\",\n\t\"additionalProperties\",\n\t\"items\",\n\t\"enum\",\n\t\"const\"\n]);\nconst ANNOTATION_KEYWORDS = new Set([\n\t\"description\",\n\t\"title\",\n\t\"default\",\n\t\"examples\"\n]);\nconst SCHEMA_TYPES = [\n\t\"object\",\n\t\"array\",\n\t\"string\",\n\t\"number\",\n\t\"integer\",\n\t\"boolean\",\n\t\"null\"\n];\n/** Whether a realm-owned intrinsic prototype is backed by its native constructor. */\nfunction hasIntrinsicConstructor(prototype, name) {\n\tconst constructor = Object.getOwnPropertyDescriptor(prototype, \"constructor\")?.value;\n\tif (typeof constructor !== \"function\") return false;\n\ttry {\n\t\treturn constructor.name === name && constructor.prototype === prototype && Function.prototype.toString.call(constructor) === `function ${name}() { [native code] }`;\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Whether a candidate is one realm's intrinsic `Object.prototype`. */\nfunction isIntrinsicObjectPrototype(value) {\n\treturn Object.getPrototypeOf(value) === null && hasIntrinsicConstructor(value, \"Object\");\n}\n/**\n* Test for a realm-agnostic plain JSON record without accepting arrays or\n* exotic objects.\n* @param value - candidate record from any JavaScript realm.\n* @returns Whether the value has a plain-object prototype chain.\n*/\nfunction isPlainJsonRecord(value) {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n\ttry {\n\t\tconst prototype = Object.getPrototypeOf(value);\n\t\treturn prototype === null || typeof prototype === \"object\" && isIntrinsicObjectPrototype(prototype);\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Whether an array uses one realm's intrinsic `Array.prototype`. */\nfunction hasPlainArrayPrototype(value) {\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (!Array.isArray(prototype) || !hasIntrinsicConstructor(prototype, \"Array\")) return false;\n\tconst objectPrototype = Object.getPrototypeOf(prototype);\n\treturn typeof objectPrototype === \"object\" && objectPrototype !== null && isIntrinsicObjectPrototype(objectPrototype);\n}\n/** Return whether a record contains only own enumerable string keys. */\nfunction hasOnlyEnumerableStringKeys(value) {\n\ttry {\n\t\treturn Reflect.ownKeys(value).every((key) => typeof key === \"string\" && Object.prototype.propertyIsEnumerable.call(value, key));\n\t} catch {\n\t\treturn false;\n\t}\n}\n/**\n* Test for an ordinary schema record whose keys survive JSON projection.\n* @param value - candidate record from any JavaScript realm.\n* @returns Whether the record has an intrinsic prototype and only own enumerable string keys.\n*/\nfunction isJsonSchemaRecord(value) {\n\treturn isPlainJsonRecord(value) && hasOnlyEnumerableStringKeys(value);\n}\n/**\n* Test for a dense ordinary array with no JSON-invisible decorations.\n* @param value - candidate array from any JavaScript realm.\n* @returns Whether the array is intrinsic, dense, and undecorated.\n*/\nfunction isPlainJsonArray(value) {\n\tif (!Array.isArray(value)) return false;\n\ttry {\n\t\tif (!hasPlainArrayPrototype(value) || Reflect.ownKeys(value).length !== value.length + 1) return false;\n\t\tfor (let index = 0; index < value.length; index++) if (!Object.hasOwn(value, index)) return false;\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Lossless finite JSON number, excluding negative zero. */\nfunction isJsonNumber(value) {\n\treturn typeof value === \"number\" && Number.isFinite(value) && !Object.is(value, -0);\n}\n/** Whether a scalar is valid for one declared schema type. */\nfunction scalarMatches(type, value) {\n\tswitch (type) {\n\t\tcase \"string\": return typeof value === \"string\";\n\t\tcase \"number\": return isJsonNumber(value);\n\t\tcase \"integer\": return isJsonNumber(value) && Number.isInteger(value);\n\t\tcase \"boolean\": return typeof value === \"boolean\";\n\t\tcase \"null\": return value === null;\n\t\t/* v8 ignore next -- JsonSchemaScalarType is closed; this retains compile-time exhaustiveness. */\n\t\tdefault: return assertNever(type, \"JsonSchemaType\");\n\t}\n}\n/** Keywords that are invalid beside `oneOf`. */\nconst ONE_OF_SIBLING_KEYWORDS = [\n\t\"properties\",\n\t\"required\",\n\t\"additionalProperties\",\n\t\"items\",\n\t\"enum\",\n\t\"const\"\n];\n/** Validate object-only fields after its property schemas have been visited. */\nfunction checkObjectSchemaTail(node, path, properties, violations) {\n\tconst hasRequired = Object.hasOwn(node, \"required\");\n\tconst required = hasRequired ? node.required : void 0;\n\tif (hasRequired) if (!isPlainJsonArray(required) || required.some((entry) => typeof entry !== \"string\")) violations.push(`${path}.required must be an array of strings`);\n\telse {\n\t\tconst declared = isJsonSchemaRecord(properties) ? properties : {};\n\t\tfor (const key of required) if (!Object.hasOwn(declared, key)) violations.push(`${path}.required names \"${key}\" which is not in properties`);\n\t}\n\tif (Object.hasOwn(node, \"additionalProperties\") && typeof node.additionalProperties !== \"boolean\") violations.push(`${path}.additionalProperties must be a boolean`);\n}\n/** Collect every violation for one raw schema tree without using the JavaScript call stack. */\nfunction checkSchemaNode(root, rootPath, violations, seen) {\n\tconst tasks = [{\n\t\tkind: \"enter\",\n\t\tnode: root,\n\t\tpath: rootPath\n\t}];\n\tfor (let task = tasks.pop(); task !== void 0; task = tasks.pop()) {\n\t\tif (task.kind === \"leave\") {\n\t\t\tseen.delete(task.node);\n\t\t\tcontinue;\n\t\t}\n\t\tif (task.kind === \"one-of-tail\") {\n\t\t\tfor (const key of ONE_OF_SIBLING_KEYWORDS) if (Object.hasOwn(task.node, key)) violations.push(`${task.path}.${key} is not supported beside oneOf`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (task.kind === \"object-tail\") {\n\t\t\tcheckObjectSchemaTail(task.node, task.path, task.properties, violations);\n\t\t\tcontinue;\n\t\t}\n\t\tconst { node, path } = task;\n\t\tif (!isJsonSchemaRecord(node)) {\n\t\t\tviolations.push(`${path} must be a schema object`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (seen.has(node)) {\n\t\t\tviolations.push(`${path} is circular`);\n\t\t\tcontinue;\n\t\t}\n\t\tseen.add(node);\n\t\ttasks.push({\n\t\t\tkind: \"leave\",\n\t\t\tnode\n\t\t});\n\t\tfor (const key of Object.keys(node)) {\n\t\t\tif (CONSTRAINT_KEYWORDS.has(key)) continue;\n\t\t\tif (ANNOTATION_KEYWORDS.has(key)) {\n\t\t\t\ttry {\n\t\t\t\t\tif (!isJsonValue(node[key])) violations.push(`${path}.${key} annotation must be lossless JSON data`);\n\t\t\t\t} catch {\n\t\t\t\t\tviolations.push(`${path}.${key} annotation must be lossless JSON data`);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tviolations.push(`${path}.${key} is not a supported keyword (subset: type/oneOf/properties/required/additionalProperties/items/enum/const + annotations)`);\n\t\t}\n\t\tif (Object.hasOwn(node, \"description\") && typeof node.description !== \"string\") violations.push(`${path}.description must be a string`);\n\t\tif (Object.hasOwn(node, \"title\") && typeof node.title !== \"string\") violations.push(`${path}.title must be a string`);\n\t\tconst hasType = Object.hasOwn(node, \"type\");\n\t\tconst hasOneOf = Object.hasOwn(node, \"oneOf\");\n\t\tif (hasType && hasOneOf) {\n\t\t\tviolations.push(`${path} cannot declare both type and oneOf`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!hasType && !hasOneOf) {\n\t\t\tfor (const key of ONE_OF_SIBLING_KEYWORDS) if (Object.hasOwn(node, key)) violations.push(`${path}.${key} requires type or oneOf`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (hasOneOf) {\n\t\t\tconst oneOf = node.oneOf;\n\t\t\ttasks.push({\n\t\t\t\tkind: \"one-of-tail\",\n\t\t\t\tnode,\n\t\t\t\tpath\n\t\t\t});\n\t\t\tif (!isPlainJsonArray(oneOf) || oneOf.length < 2) violations.push(`${path}.oneOf must be an array of at least two schemas`);\n\t\t\telse for (let index = oneOf.length - 1; index >= 0; index--) tasks.push({\n\t\t\t\tkind: \"enter\",\n\t\t\t\tnode: oneOf[index],\n\t\t\t\tpath: `${path}.oneOf[${index}]`\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst type = node.type;\n\t\tif (typeof type !== \"string\" || !SCHEMA_TYPES.includes(type)) {\n\t\t\tviolations.push(Array.isArray(type) ? `${path}.type must be a single type string (type arrays are not supported)` : `${path}.type must be one of ${SCHEMA_TYPES.join(\"/\")}`);\n\t\t\tcontinue;\n\t\t}\n\t\tconst schemaType = type;\n\t\tfor (const [key, types] of Object.entries({\n\t\t\tproperties: [\"object\"],\n\t\t\trequired: [\"object\"],\n\t\t\tadditionalProperties: [\"object\"],\n\t\t\titems: [\"array\"],\n\t\t\tenum: [\n\t\t\t\t\"string\",\n\t\t\t\t\"number\",\n\t\t\t\t\"integer\",\n\t\t\t\t\"boolean\",\n\t\t\t\t\"null\"\n\t\t\t],\n\t\t\tconst: [\n\t\t\t\t\"string\",\n\t\t\t\t\"number\",\n\t\t\t\t\"integer\",\n\t\t\t\t\"boolean\",\n\t\t\t\t\"null\"\n\t\t\t]\n\t\t})) if (Object.hasOwn(node, key) && !types.includes(schemaType)) violations.push(`${path}.${key} is not supported on type \"${schemaType}\"`);\n\t\tswitch (schemaType) {\n\t\t\tcase \"object\": {\n\t\t\t\tconst properties = Object.hasOwn(node, \"properties\") ? node.properties : void 0;\n\t\t\t\ttasks.push({\n\t\t\t\t\tkind: \"object-tail\",\n\t\t\t\t\tnode,\n\t\t\t\t\tpath,\n\t\t\t\t\tproperties\n\t\t\t\t});\n\t\t\t\tif (Object.hasOwn(node, \"properties\")) if (!isJsonSchemaRecord(properties)) violations.push(`${path}.properties must be an object of schemas`);\n\t\t\t\telse {\n\t\t\t\t\tconst entries = Object.entries(properties);\n\t\t\t\t\tfor (let index = entries.length - 1; index >= 0; index--) {\n\t\t\t\t\t\tconst entry = entries[index];\n\t\t\t\t\t\t/* v8 ignore next -- the loop is bounded by the captured entry count. */\n\t\t\t\t\t\tif (entry === void 0) continue;\n\t\t\t\t\t\ttasks.push({\n\t\t\t\t\t\t\tkind: \"enter\",\n\t\t\t\t\t\t\tnode: entry[1],\n\t\t\t\t\t\t\tpath: `${path}.properties.${entry[0]}`\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"array\":\n\t\t\t\tif (Object.hasOwn(node, \"items\")) tasks.push({\n\t\t\t\t\tkind: \"enter\",\n\t\t\t\t\tnode: node.items,\n\t\t\t\t\tpath: `${path}.items`\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"string\":\n\t\t\tcase \"number\":\n\t\t\tcase \"integer\":\n\t\t\tcase \"boolean\":\n\t\t\tcase \"null\": {\n\t\t\t\tconst hasEnum = Object.hasOwn(node, \"enum\");\n\t\t\t\tconst allowed = hasEnum ? node.enum : void 0;\n\t\t\t\tconst enumValid = isPlainJsonArray(allowed) && allowed.length > 0 && allowed.every((entry) => scalarMatches(schemaType, entry));\n\t\t\t\tif (hasEnum && !enumValid) violations.push(`${path}.enum must be a non-empty array of ${schemaType} values`);\n\t\t\t\tconst hasConst = Object.hasOwn(node, \"const\");\n\t\t\t\tconst declaredConst = hasConst ? node.const : void 0;\n\t\t\t\tconst constValid = scalarMatches(schemaType, declaredConst);\n\t\t\t\tif (hasConst) {\n\t\t\t\t\tif (!constValid) violations.push(`${path}.const must be a ${schemaType} value`);\n\t\t\t\t\telse if (enumValid && !allowed.includes(declaredConst)) violations.push(`${path}.const must be one of ${path}.enum when both are declared`);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t/* v8 ignore next -- schemaType was narrowed from the closed SCHEMA_TYPES table above. */\n\t\t\tdefault: assertNever(schemaType, \"JsonSchemaType\");\n\t\t}\n\t}\n}\n/**\n* Assert the enforced subset plus the object-root constraint retained by\n* subagent and workflow structured outputs.\n* @param schema - untrusted caller-supplied schema.\n* @returns Assertion that the schema belongs to the supported subset and has an object root.\n*/\nfunction assertObjectJsonSchema(schema) {\n\tconst violations = [];\n\tcheckSchemaNode(schema, \"schema\", violations, /* @__PURE__ */ new Set());\n\tif (violations.length === 0 && (!isJsonSchemaRecord(schema) || !Object.hasOwn(schema, \"type\") || schema.type !== \"object\")) violations.push(\"schema.type must be \\\"object\\\" (structured output is object-rooted)\");\n\tif (violations.length > 0) throw new JsonSchemaError(violations);\n}\n//#endregion\n//#region packages/workflow/workflow/src/index.ts\n/**\n* Typed error for workflow-seam failures. Extends {@link HarnessError}, so the\n* `code` is machine-routable taxonomy. `fatal` drives the combinator\n* discipline: `parallel()`/`pipeline()` re-throw a fatal error (a typo'd\n* option or a tripped cap must kill the script loudly), and reserve the\n* per-item `null` for child-run failures and ordinary in-stage script errors.\n* Every {@link WorkflowErrorCode} is fatal; the flag exists so the\n* distinction is explicit at every catch site rather than implied.\n*/\nvar WorkflowError = class extends HarnessError {\n\tcode;\n\t/** Whether combinators must propagate this error instead of nulling the item. */\n\tfatal;\n\tconstructor(message, code, options) {\n\t\tsuper(message, code, options);\n\t\tthis.name = \"WorkflowError\";\n\t\tthis.code = code;\n\t\tthis.fatal = options?.fatal ?? true;\n\t}\n};\n/**\n* Whether combinators must re-throw `error` instead of mapping the item to `null`.\n* @param error - any thrown value; fatality is host `instanceof` (unforgeable from a script realm).\n* @returns true iff `error` is a {@link WorkflowError} whose `fatal` flag is set.\n*/\nfunction isFatalWorkflowError(error) {\n\treturn error instanceof WorkflowError && error.fatal;\n}\n//#endregion\n//#region packages/workflow/workflow-ptc/src/runtime.ts\n/**\n* Workflow VM hooks, child callbacks, ordinary concurrency limits and result serialization.\n* PTC owns process confinement and cancellation. Fatal hook and provider failures propagate\n* through combinators; ordinary child failures and stage errors become per-item nulls.\n* @module @deepseek-ai/dsh-workflow-ptc/runtime\n*/\n/** The `agent()` options the script may pass; everything else rejects loud. */\nconst SUPPORTED_AGENT_OPTIONS = new Set([\n\t\"label\",\n\t\"phase\",\n\t\"schema\",\n\t\"provider\",\n\t\"model\"\n]);\n/** Deferred Claude Code options we name explicitly in the rejection message. */\nconst DEFERRED_AGENT_OPTIONS = new Set([\n\t\"effort\",\n\t\"isolation\",\n\t\"agentType\"\n]);\n/** Flatten a child's final output blocks to text (the non-schema `agent()` result). */\nfunction outputText(blocks) {\n\treturn blocks.filter((block) => block.type === \"text\").map((block) => block.text).join(\"\");\n}\n/** A short display label derived from the prompt when the script passes none. */\nfunction defaultLabel(prompt) {\n\tconst newline = prompt.indexOf(\"\\n\");\n\tconst line = newline === -1 ? prompt : prompt.slice(0, newline);\n\treturn line.length <= 48 ? line : `${line.slice(0, 47)}…`;\n}\n/**\n* One script execution inside the confined Node process. The host owns\n* cancellation and cleanup of any dropped child work.\n*/\nvar WorkflowExecution = class {\n\tlimits;\n\tobserver;\n\tchildren;\n\t/** 1-based count of `agent()` calls started (the `agentsStarted` result field). */\n\tstarted = 0;\n\tactiveSlots = 0;\n\tslotWaiters = [];\n\tcurrentPhase;\n\tcontext;\n\tcompiled;\n\tconstructor(meta, body, args, limits, observer, children) {\n\t\tthis.limits = limits;\n\t\tthis.observer = observer;\n\t\tthis.children = children;\n\t\ttry {\n\t\t\tthis.compiled = new vm.Script(`(async () => {\\n${body}\\n})()`, {\n\t\t\t\tfilename: `workflow:${meta.name}`,\n\t\t\t\tlineOffset: -1\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrow new WorkflowError(`workflow script does not parse: ${String(error)}`, \"SCRIPT_PARSE\", { cause: error });\n\t\t}\n\t\tthis.context = vm.createContext({}, { name: `workflow:${meta.name}` });\n\t\tconst globals = {\n\t\t\tagent: (prompt, opts) => this.contain(this.agent(prompt, opts)),\n\t\t\tparallel: (thunks) => this.contain(this.parallel(thunks)),\n\t\t\tpipeline: (items, ...stages) => this.contain(this.pipeline(items, stages)),\n\t\t\tphase: (title) => {\n\t\t\t\tthis.phase(title);\n\t\t\t},\n\t\t\tlog: (message) => {\n\t\t\t\tthis.log(message);\n\t\t\t},\n\t\t\targs\n\t\t};\n\t\tfor (const [key, value] of Object.entries(globals)) this.context[key] = typeof value === \"function\" ? Object.freeze(value) : value;\n\t}\n\t/**\n\t* Run the script and materialize its JSON return value.\n\t* @returns A completed or error result; script failures never reject.\n\t*/\n\tasync drive() {\n\t\ttry {\n\t\t\tconst scriptPromise = this.compiled.runInContext(this.context, { timeout: this.limits.syncTimeoutMs });\n\t\t\tconst raw = await this.contain(Promise.resolve(scriptPromise));\n\t\t\treturn {\n\t\t\t\tvalue: raw === void 0 ? null : this.materializeResult(raw),\n\t\t\t\tstopReason: \"completed\",\n\t\t\t\tagentsStarted: this.started\n\t\t\t};\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tvalue: null,\n\t\t\t\tstopReason: \"error\",\n\t\t\t\terror: renderThrown(error),\n\t\t\t\t...error instanceof WorkflowError ? { errorCode: error.code } : {},\n\t\t\t\tagentsStarted: this.started\n\t\t\t};\n\t\t}\n\t}\n\t/**\n\t* Attach a no-op rejection consumer WITHOUT changing what the caller\n\t* receives: if the script drops the promise, a host rejection cannot become\n\t* an unhandled rejection that kills the process; if\n\t* the script does await it, it still observes the rejection.\n\t*/\n\tcontain(promise) {\n\t\tpromise.catch(() => {});\n\t\treturn promise;\n\t}\n\t/** Materialize the script's return value; violations become RESULT_UNSERIALIZABLE. */\n\tmaterializeResult(raw) {\n\t\ttry {\n\t\t\treturn materializeFromRealm(raw, \"workflow result\");\n\t\t} catch (error) {\n\t\t\t/* v8 ignore next -- defensive rethrow arm: materializeFromRealm only throws MaterializeError */\n\t\t\tif (!(error instanceof MaterializeError)) throw error;\n\t\t\tthrow new WorkflowError(`the workflow's return value is not plain JSON data — ${error.message}. Return only JSON-serializable objects/arrays/scalars.`, \"RESULT_UNSERIALIZABLE\", { cause: error });\n\t\t}\n\t}\n\t/** Acquire one concurrency slot in FIFO order. */\n\tacquireSlot() {\n\t\tif (this.activeSlots < this.limits.maxConcurrentAgents) {\n\t\t\tthis.activeSlots += 1;\n\t\t\treturn Promise.resolve();\n\t\t}\n\t\treturn new Promise((resolve) => {\n\t\t\tthis.slotWaiters.push(() => {\n\t\t\t\tthis.activeSlots += 1;\n\t\t\t\tresolve();\n\t\t\t});\n\t\t});\n\t}\n\treleaseSlot() {\n\t\tthis.activeSlots -= 1;\n\t\tconst next = this.slotWaiters.shift();\n\t\tif (next) next();\n\t}\n\t/** The `agent(prompt, opts)` hook. */\n\tasync agent(rawPrompt, rawOpts) {\n\t\tif (typeof rawPrompt !== \"string\" || rawPrompt.length === 0) throw new WorkflowError(\"agent() requires a non-empty prompt string\", \"INVALID_ARGUMENT\");\n\t\tconst opts = this.readAgentOptions(rawOpts);\n\t\tif (this.started >= this.limits.maxTotalAgents) throw new WorkflowError(`this run reached its total agent cap (${this.limits.maxTotalAgents}) — a runaway-loop backstop; raise the applicable maxTotalAgents limit if the scale is intentional`, \"AGENT_CAP\");\n\t\tthis.started += 1;\n\t\tconst seq = this.started;\n\t\tconst label = opts.label ?? defaultLabel(rawPrompt);\n\t\tconst phase = opts.phase ?? this.currentPhase;\n\t\tawait this.acquireSlot();\n\t\ttry {\n\t\t\tlet run;\n\t\t\ttry {\n\t\t\t\trun = await this.children.startAgent({\n\t\t\t\t\tprompt: rawPrompt,\n\t\t\t\t\t...opts.schema !== void 0 ? { schema: opts.schema } : {},\n\t\t\t\t\t...opts.provider !== void 0 ? { provider: opts.provider } : {},\n\t\t\t\t\t...opts.model !== void 0 ? { model: opts.model } : {}\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tthrow new WorkflowError(`agent() could not start a child: ${renderThrown(error)}`, \"AGENT_START\", { cause: error });\n\t\t\t}\n\t\t\tconst info = {\n\t\t\t\tseq,\n\t\t\t\tlabel,\n\t\t\t\t...phase !== void 0 ? { phase } : {},\n\t\t\t\tchildId: brandString(run.id)\n\t\t\t};\n\t\t\tthis.observer.agentStart(info);\n\t\t\ttry {\n\t\t\t\tlet result;\n\t\t\t\ttry {\n\t\t\t\t\tresult = await run.result;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t\t...info,\n\t\t\t\t\t\toutcome: \"failed\"\n\t\t\t\t\t});\n\t\t\t\t\tthrow new WorkflowError(`child agent run failed: ${renderThrown(error)}`, \"AGENT_RESULT\", { cause: error });\n\t\t\t\t}\n\t\t\t\tif (result.stopReason === \"completed\") {\n\t\t\t\t\tif (opts.schema !== void 0) {\n\t\t\t\t\t\tif (result.structured === void 0) {\n\t\t\t\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t\t\t\t...info,\n\t\t\t\t\t\t\t\toutcome: \"failed\"\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\treturn null;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t\t\t...info,\n\t\t\t\t\t\t\toutcome: \"completed\"\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn result.structured;\n\t\t\t\t\t}\n\t\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t\t...info,\n\t\t\t\t\t\toutcome: \"completed\"\n\t\t\t\t\t});\n\t\t\t\t\treturn outputText(result.output);\n\t\t\t\t}\n\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t...info,\n\t\t\t\t\toutcome: \"failed\"\n\t\t\t\t});\n\t\t\t\treturn null;\n\t\t\t} finally {\n\t\t\t\tawait run.dispose();\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.releaseSlot();\n\t\t}\n\t}\n\t/** Materialize + validate the `agent()` options bag from the realm. */\n\treadAgentOptions(rawOpts) {\n\t\tif (rawOpts === void 0) return {};\n\t\tlet opts;\n\t\ttry {\n\t\t\topts = materializeFromRealm(rawOpts, \"agent() options\");\n\t\t} catch (error) {\n\t\t\t/* v8 ignore next -- defensive rethrow arm: materializeFromRealm only throws MaterializeError */\n\t\t\tif (!(error instanceof MaterializeError)) throw error;\n\t\t\tthrow new WorkflowError(`agent() options must be plain JSON data — ${error.message}`, \"INVALID_ARGUMENT\", { cause: error });\n\t\t}\n\t\tif (typeof opts !== \"object\" || opts === null || Array.isArray(opts)) throw new WorkflowError(\"agent() options must be an object\", \"INVALID_ARGUMENT\");\n\t\tconst record = opts;\n\t\tfor (const key of Object.keys(record)) {\n\t\t\tif (SUPPORTED_AGENT_OPTIONS.has(key)) continue;\n\t\t\tif (DEFERRED_AGENT_OPTIONS.has(key)) throw new WorkflowError(`agent() option \"${key}\" is deferred and not supported by this engine (supported: label, phase, schema, provider, model)`, \"UNSUPPORTED_OPTION\");\n\t\t\tthrow new WorkflowError(`agent() option \"${key}\" is not recognized (supported: label, phase, schema, provider, model)`, \"UNSUPPORTED_OPTION\");\n\t\t}\n\t\tfor (const key of [\n\t\t\t\"label\",\n\t\t\t\"phase\",\n\t\t\t\"provider\",\n\t\t\t\"model\"\n\t\t]) if (record[key] !== void 0 && typeof record[key] !== \"string\") throw new WorkflowError(`agent() option \"${key}\" must be a string`, \"INVALID_ARGUMENT\");\n\t\tlet schema;\n\t\tif (record.schema !== void 0) try {\n\t\t\tassertObjectJsonSchema(record.schema);\n\t\t\tschema = record.schema;\n\t\t} catch (error) {\n\t\t\t/* v8 ignore next -- defensive rethrow arm: assertObjectJsonSchema only throws JsonSchemaError */\n\t\t\tif (!(error instanceof JsonSchemaError)) throw error;\n\t\t\tthrow new WorkflowError(`agent() schema is outside the supported subset — ${error.message}`, \"UNSUPPORTED_SCHEMA\", { cause: error });\n\t\t}\n\t\treturn {\n\t\t\t...record.label !== void 0 ? { label: record.label } : {},\n\t\t\t...record.phase !== void 0 ? { phase: record.phase } : {},\n\t\t\t...record.provider !== void 0 ? { provider: record.provider } : {},\n\t\t\t...record.model !== void 0 ? { model: record.model } : {},\n\t\t\t...schema !== void 0 ? { schema } : {}\n\t\t};\n\t}\n\t/** The `parallel(thunks)` hook: each thunk caught → `null`; fatal errors propagate. */\n\tasync parallel(rawThunks) {\n\t\tif (!Array.isArray(rawThunks)) throw new WorkflowError(\"parallel() requires an array of zero-argument functions\", \"INVALID_ARGUMENT\");\n\t\tthis.assertItemCap(rawThunks.length, \"parallel()\");\n\t\tconst thunks = rawThunks.map((thunk, index) => {\n\t\t\tif (typeof thunk !== \"function\") throw new WorkflowError(`parallel() item ${index} is not a function`, \"INVALID_ARGUMENT\");\n\t\t\treturn thunk;\n\t\t});\n\t\treturn Promise.all(thunks.map(async (thunk) => {\n\t\t\ttry {\n\t\t\t\treturn await thunk();\n\t\t\t} catch (error) {\n\t\t\t\tif (isFatalWorkflowError(error)) throw error;\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}));\n\t}\n\t/** The `pipeline(items, ...stages)` hook: per-item stage chains, NO cross-stage barrier. */\n\tasync pipeline(rawItems, rawStages) {\n\t\tif (!Array.isArray(rawItems)) throw new WorkflowError(\"pipeline() requires an items array\", \"INVALID_ARGUMENT\");\n\t\tthis.assertItemCap(rawItems.length, \"pipeline()\");\n\t\tif (rawStages.length === 0) throw new WorkflowError(\"pipeline() requires at least one stage function\", \"INVALID_ARGUMENT\");\n\t\tconst stages = rawStages.map((stage, index) => {\n\t\t\tif (typeof stage !== \"function\") throw new WorkflowError(`pipeline() stage ${index} is not a function`, \"INVALID_ARGUMENT\");\n\t\t\treturn stage;\n\t\t});\n\t\treturn Promise.all(rawItems.map(async (item, index) => {\n\t\t\tlet value = item;\n\t\t\ttry {\n\t\t\t\tfor (const stage of stages) value = await stage(value, item, index);\n\t\t\t\treturn value;\n\t\t\t} catch (error) {\n\t\t\t\tif (isFatalWorkflowError(error)) throw error;\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}));\n\t}\n\tassertItemCap(length, hook) {\n\t\tif (length > this.limits.maxItemsPerCall) throw new WorkflowError(`${hook} received ${length} items — over the per-call cap (${this.limits.maxItemsPerCall}); split the work or raise maxItemsPerCall in the engine config`, \"ITEM_CAP\");\n\t}\n\t/** The `phase(title)` hook: sets the current label for subsequent `agent()` calls and notifies observers. */\n\tphase(title) {\n\t\tif (typeof title !== \"string\" || title.length === 0) throw new WorkflowError(\"phase() requires a non-empty title string\", \"INVALID_ARGUMENT\");\n\t\tthis.currentPhase = title;\n\t\tthis.observer.phase(title);\n\t}\n\t/** The `log(message)` hook: narration to observers. */\n\tlog(message) {\n\t\tif (typeof message !== \"string\") throw new WorkflowError(\"log() requires a message string\", \"INVALID_ARGUMENT\");\n\t\tthis.observer.log(message);\n\t}\n};\n//#endregion\n//#region packages/workflow/workflow-ptc/src/guest.ts\n/**\n* Run a workflow with one progress batch in flight. Drain progress before child\n* disposal and the terminal result; PTC and the host own cancellation and cleanup.\n* @param host - JSON callbacks owned by this workflow run.\n* @returns The script result after progress delivery; initialization failures reject.\n*/\nasync function runWorkflowGuest(host) {\n\tconst init = await host.begin({});\n\tlet queued = [];\n\tlet inFlight;\n\tlet progressError;\n\tconst flush = () => {\n\t\tif (inFlight !== void 0 || queued.length === 0) return;\n\t\tconst batch = queued;\n\t\tqueued = [];\n\t\tinFlight = host.progress(batch).then(() => {\n\t\t\tinFlight = void 0;\n\t\t\tflush();\n\t\t}, (error) => {\n\t\t\tprogressError = renderThrown(error);\n\t\t\tqueued = [];\n\t\t\tinFlight = void 0;\n\t\t});\n\t};\n\tconst send = (event) => {\n\t\tif (progressError !== void 0) return;\n\t\tqueued.push(event);\n\t\tflush();\n\t};\n\tconst drain = async () => {\n\t\twhile (inFlight !== void 0) await inFlight;\n\t};\n\tconst result = await new WorkflowExecution(init.meta, init.body, init.args, init.limits, {\n\t\tphase: (title) => {\n\t\t\tsend({\n\t\t\t\ttype: \"phase\",\n\t\t\t\ttitle\n\t\t\t});\n\t\t},\n\t\tlog: (message) => {\n\t\t\tsend({\n\t\t\t\ttype: \"log\",\n\t\t\t\tmessage\n\t\t\t});\n\t\t},\n\t\tagentStart: (info) => {\n\t\t\tsend({\n\t\t\t\ttype: \"agent-start\",\n\t\t\t\tinfo\n\t\t\t});\n\t\t},\n\t\tagentEnd: (info) => {\n\t\t\tsend({\n\t\t\t\ttype: \"agent-end\",\n\t\t\t\tinfo\n\t\t\t});\n\t\t}\n\t}, { async startAgent(request) {\n\t\tconst { callId, childId } = await host.startChild(request);\n\t\tconst result = host.childResult({ callId });\n\t\tresult.catch(() => {});\n\t\treturn {\n\t\t\tid: childId,\n\t\t\tresult,\n\t\t\tasync dispose() {\n\t\t\t\tawait drain();\n\t\t\t\tawait host.disposeChild({ callId });\n\t\t\t}\n\t\t};\n\t} }).drive();\n\tawait drain();\n\treturn progressError === void 0 ? result : {\n\t\tvalue: null,\n\t\tstopReason: \"error\",\n\t\terror: progressError,\n\t\tagentsStarted: result.agentsStarted\n\t};\n}\n//#endregion\nexport { runWorkflowGuest };\n//# sourceURL=dsh-workflow-guest.js\n" +export const WORKFLOW_GUEST_SOURCE = "import * as vm from \"node:vm\";\n//#region packages/workflow/workflow-ptc/src/realm.ts\n/**\n* Materializes script VM values as plain JSON and renders thrown values.\n* Getters and proxy traps may execute inside the confined Node process;\n* process isolation and cancellation belong to PTC, not the VM.\n* @module @deepseek-ai/dsh-workflow-ptc/realm\n*/\n/** Thrown by {@link materializeFromRealm}; the caller wraps it into the right `WorkflowError` code. */\nvar MaterializeError = class extends Error {\n\tpath;\n\treason;\n\tconstructor(path, reason) {\n\t\tsuper(`${path}: ${reason}`);\n\t\tthis.path = path;\n\t\tthis.reason = reason;\n\t\tthis.name = \"MaterializeError\";\n\t}\n};\n/**\n* Render a thrown value to failure text without ever throwing: prefer the\n* `stack` (host or realm — a realm error's `stack` is a plain string read),\n* fall back to `message`, then `String()`. Reading those properties MAY run\n* script code; if that code itself throws, a fixed label is returned instead.\n* @param error - any value thrown in the host or guest realm.\n* @returns human-readable text for the failure report; prefers the stack.\n*/\nfunction renderThrown(error) {\n\ttry {\n\t\tconst stack = error?.stack;\n\t\tif (typeof stack === \"string\" && stack.length > 0) return stack;\n\t\tconst message = error?.message;\n\t\tif (typeof message === \"string\" && message.length > 0) return message;\n\t\treturn String(error);\n\t} catch {\n\t\treturn \"[unrenderable thrown value]\";\n\t}\n}\n/**\n* Whether an object's prototype chain represents a plain data object: `null`, or a prototype\n* whose own prototype is `null` (the realm's `Object.prototype` — which we\n* cannot compare by identity across realms). A `Date`/`Map`/class instance\n* has a longer chain and is rejected.\n*/\nfunction hasPlainPrototype(value) {\n\tconst proto = Object.getPrototypeOf(value);\n\tif (proto === null) return true;\n\treturn Object.getPrototypeOf(proto) === null;\n}\n/**\n* Copy `value` (typically from the vm realm) into plain host JSON data. Root `undefined` is\n* returned unchanged; nested `undefined` and values JSON cannot represent losslessly fail\n* with the offending path. Property accessors run normally, and a throwing read is wrapped\n* with its rendered failure.\n*\n* @param value - the realm value to materialize.\n* @param root - the path label for the root value (error messages).\n* @returns the host-realm copy (plain objects/arrays/scalars only).\n* @throws {@link MaterializeError} for unsupported values, cycles, sparse arrays, exotic\n* prototypes, or property reads that throw.\n*/\nfunction materializeFromRealm(value, root = \"value\") {\n\tif (value === void 0) return void 0;\n\ttry {\n\t\treturn materialize(value, root, /* @__PURE__ */ new Set());\n\t} catch (error) {\n\t\tif (error instanceof MaterializeError) throw error;\n\t\tthrow new MaterializeError(root, `reading the value threw: ${renderThrown(error)}`);\n\t}\n}\nfunction materialize(value, path, seen) {\n\tswitch (typeof value) {\n\t\tcase \"boolean\":\n\t\tcase \"string\": return value;\n\t\tcase \"number\":\n\t\t\tif (!Number.isFinite(value)) throw new MaterializeError(path, \"non-finite numbers are not JSON data\");\n\t\t\treturn value;\n\t\tcase \"bigint\": throw new MaterializeError(path, \"bigints are not JSON data\");\n\t\tcase \"function\": throw new MaterializeError(path, \"functions are not plain JSON data\");\n\t\tcase \"symbol\": throw new MaterializeError(path, \"symbols are not plain JSON data\");\n\t\tcase \"undefined\": throw new MaterializeError(path, \"undefined is not JSON data\");\n\t\tcase \"object\": break;\n\t}\n\tif (value === null) return null;\n\tconst objectValue = value;\n\tif (seen.has(objectValue)) throw new MaterializeError(path, \"circular references are not JSON data\");\n\tseen.add(objectValue);\n\ttry {\n\t\tif (Array.isArray(objectValue)) return materializeArray(objectValue, path, seen);\n\t\treturn materializeObject(objectValue, path, seen);\n\t} finally {\n\t\tseen.delete(objectValue);\n\t}\n}\nfunction materializeArray(value, path, seen) {\n\tconst out = [];\n\tfor (let index = 0; index < value.length; index++) {\n\t\tif (!(index in value)) throw new MaterializeError(`${path}[${index}]`, \"sparse arrays are not JSON data\");\n\t\tout.push(materialize(value[index], `${path}[${index}]`, seen));\n\t}\n\tfor (const key of Object.keys(value)) {\n\t\tconst index = Number(key);\n\t\tif (!Number.isInteger(index) || index < 0 || index >= value.length) throw new MaterializeError(`${path}.${key}`, \"arrays with non-index properties are not JSON data\");\n\t}\n\tif (Object.getOwnPropertySymbols(value).length > 0) throw new MaterializeError(path, \"symbol-keyed properties are not plain JSON data\");\n\treturn out;\n}\nfunction materializeObject(value, path, seen) {\n\tif (!hasPlainPrototype(value)) throw new MaterializeError(path, \"only plain objects and arrays are JSON data (exotic prototype)\");\n\tif (Object.getOwnPropertySymbols(value).length > 0) throw new MaterializeError(path, \"symbol-keyed properties are not plain JSON data\");\n\tconst out = {};\n\tfor (const key of Object.keys(value)) Object.defineProperty(out, key, {\n\t\tvalue: materialize(value[key], `${path}.${key}`, seen),\n\t\tenumerable: true,\n\t\twritable: true,\n\t\tconfigurable: true\n\t});\n\treturn out;\n}\n//#endregion\n//#region packages/util/brand/src/index.ts\n/**\n* Apply a compile-time string brand without changing the value.\n* @param value - string admitted by the domain that owns the target brand.\n* @returns the same string with the requested compile-time brand.\n*/\nfunction brandString(value) {\n\treturn value;\n}\n//#endregion\n//#region packages/util/values/src/index.ts\n/**\n* Mark an unreachable closed-union branch.\n* @param value - impossible value; an unhandled typed variant fails at the call site.\n* @param context - optional switch-site label included in the failure message.\n* @returns never; a runtime value that escaped its type always throws.\n*/\nfunction assertNever(value, context) {\n\tconst rendered = JSON.stringify(value) ?? String(value);\n\tthrow new Error(`unreachable variant${context ? ` in ${context}` : \"\"}: ${rendered}`);\n}\n/** Whether a realm-owned intrinsic prototype has a native constructor matching this engine's representation. */\nfunction hasIntrinsicConstructor$1(prototype, name) {\n\tconst constructor = Object.getOwnPropertyDescriptor(prototype, \"constructor\")?.value;\n\tif (typeof constructor !== \"function\") return false;\n\ttry {\n\t\treturn constructor.name === name && constructor.prototype === prototype && Function.prototype.toString.call(constructor) === Function.prototype.toString.call(name === \"Array\" ? Array : Object);\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Whether a candidate is one realm's intrinsic `Object.prototype`. */\nfunction isIntrinsicObjectPrototype$1(value) {\n\treturn Object.getPrototypeOf(value) === null && hasIntrinsicConstructor$1(value, \"Object\");\n}\n/** Whether an array uses one realm's intrinsic `Array.prototype`, not a subclass or forged prototype. */\nfunction hasPlainArrayPrototype$1(value) {\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (!Array.isArray(prototype) || !hasIntrinsicConstructor$1(prototype, \"Array\")) return false;\n\tconst objectPrototype = Object.getPrototypeOf(prototype);\n\treturn typeof objectPrototype === \"object\" && objectPrototype !== null && isIntrinsicObjectPrototype$1(objectPrototype);\n}\n/** Whether an object is a plain or null-prototype record from any JavaScript realm. */\nfunction hasPlainObjectPrototype(value) {\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === null || typeof prototype === \"object\" && isIntrinsicObjectPrototype$1(prototype);\n}\n/** Return every JSON-visible object key, or reject own data JSON would discard. */\nfunction enumerableStringKeys(value) {\n\tconst keys = Reflect.ownKeys(value);\n\tif (keys.some((key) => typeof key !== \"string\" || !Object.prototype.propertyIsEnumerable.call(value, key))) return void 0;\n\treturn keys;\n}\n/** Validate lossless JSON iteratively, optionally materializing a detached snapshot. */\nfunction walkJsonValue(value, detach) {\n\tconst ancestors = /* @__PURE__ */ new Set();\n\tlet root;\n\tlet parent;\n\tconst assign = (item) => {\n\t\tif (parent === void 0) {\n\t\t\tif (detach) root = item;\n\t\t} else if (parent.kind === \"array\") {\n\t\t\tif (parent.target !== void 0) parent.target[parent.key] = item;\n\t\t} else if (parent.target !== void 0) Object.defineProperty(parent.target, parent.key, {\n\t\t\tvalue: item,\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true\n\t\t});\n\t};\n\tconst frames = [];\n\tlet current = value;\n\tfor (;;) {\n\t\tif (current === null) assign(null);\n\t\telse if (typeof current === \"boolean\" || typeof current === \"string\") assign(current);\n\t\telse if (typeof current === \"number\") {\n\t\t\tif (!Number.isFinite(current) || Object.is(current, -0)) return void 0;\n\t\t\tassign(current);\n\t\t} else {\n\t\t\tif (typeof current !== \"object\") return void 0;\n\t\t\tif (ancestors.has(current)) return void 0;\n\t\t\tif (Array.isArray(current)) {\n\t\t\t\tif (!hasPlainArrayPrototype$1(current)) return void 0;\n\t\t\t\tconst length = current.length;\n\t\t\t\tif (Reflect.ownKeys(current).length !== length + 1) return void 0;\n\t\t\t\tconst target = detach ? [] : void 0;\n\t\t\t\tif (target !== void 0) assign(target);\n\t\t\t\tlet indices;\n\t\t\t\tif (!Number.isInteger(length)) {\n\t\t\t\t\tindices = [];\n\t\t\t\t\tfor (let index = length - 1; index >= 0; index--) indices.push(index);\n\t\t\t\t}\n\t\t\t\tframes.push({\n\t\t\t\t\tkind: \"array\",\n\t\t\t\t\tsource: current,\n\t\t\t\t\tlength: indices?.length ?? length,\n\t\t\t\t\tindex: 0,\n\t\t\t\t\tkey: 0,\n\t\t\t\t\tindices,\n\t\t\t\t\ttarget\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tif (!hasPlainObjectPrototype(current)) return void 0;\n\t\t\t\tconst keys = enumerableStringKeys(current);\n\t\t\t\tif (keys === void 0) return void 0;\n\t\t\t\tconst target = detach ? {} : void 0;\n\t\t\t\tif (target !== void 0) assign(target);\n\t\t\t\tframes.push({\n\t\t\t\t\tkind: \"object\",\n\t\t\t\t\tsource: current,\n\t\t\t\t\tkeys,\n\t\t\t\t\tindex: 0,\n\t\t\t\t\tkey: \"\",\n\t\t\t\t\ttarget\n\t\t\t\t});\n\t\t\t}\n\t\t\tancestors.add(current);\n\t\t}\n\t\tfor (;;) {\n\t\t\tconst frame = frames.at(-1);\n\t\t\tif (frame === void 0) return detach ? root : true;\n\t\t\tconst length = frame.kind === \"array\" ? frame.length : frame.keys.length;\n\t\t\tif (frame.index >= length) {\n\t\t\t\tancestors.delete(frame.source);\n\t\t\t\tframes.pop();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst index = frame.index++;\n\t\t\tparent = frame;\n\t\t\tif (frame.kind === \"array\") {\n\t\t\t\tconst key = frame.indices === void 0 ? index : frame.indices[frame.indices.length - index - 1];\n\t\t\t\t/* v8 ignore next -- the loop is bounded by the captured index count. */\n\t\t\t\tif (key === void 0) return void 0;\n\t\t\t\tif (!Object.prototype.hasOwnProperty.call(frame.source, key)) return void 0;\n\t\t\t\tframe.key = key;\n\t\t\t\tcurrent = frame.source[key];\n\t\t\t} else {\n\t\t\t\tconst key = frame.keys[index];\n\t\t\t\t/* v8 ignore next -- the loop is bounded by the captured key count. */\n\t\t\t\tif (key === void 0) return void 0;\n\t\t\t\tframe.key = key;\n\t\t\t\tcurrent = frame.source[key];\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n}\n/**\n* Test the same lossless JSON rules as {@link snapshotJsonValue} without detaching the value.\n* @param value - candidate value to test.\n* @returns whether the value survives a JSON round trip without loss.\n*/\nfunction isJsonValue(value) {\n\treturn walkJsonValue(value, false) === true;\n}\n//#endregion\n//#region packages/llm/llm/src/message.ts\n/**\n* Extract and join only text blocks in content order, preserving their whitespace.\n* Non-text blocks contribute neither text nor separators; content is not modified.\n* Import from `@deepseek-ai/dsh-llm/message` in Host and browser code.\n* @param content - source blocks to read in their existing order.\n* @param options - optional text extraction settings.\n* @param options.separator - text inserted between text blocks; defaults to an empty string.\n* @returns joined text, or an empty string when no text blocks are present.\n*/\nfunction extractTextContent(content, options) {\n\treturn content.filter((block) => block.type === \"text\").map((block) => block.text).join(options?.separator ?? \"\");\n}\n//#endregion\n//#region packages/util/error/src/index.ts\n/**\n* Harness error base with a stable machine-routable code and chained cause.\n* Package errors extend it so tool results and replay can retain failure class.\n* @module @deepseek-ai/dsh-error\n*/\n/**\n* Base class for all harness errors. Carries a `code` (stable, programmatic —\n* e.g. `NO_ADAPTER`, `INVALID_ARGS`) distinct from the\n* human-readable `message`, and supports `cause` chaining via the standard\n* `ErrorOptions`. `name` defaults to the subclass constructor name.\n*/\nvar HarnessError = class extends Error {\n\t/** Stable machine-routable failure class (e.g. `RATE_LIMIT`); route on this, never by parsing `message`. */\n\tcode;\n\tconstructor(message, code, options) {\n\t\tsuper(message, options);\n\t\tthis.code = code;\n\t\tthis.name = new.target.name;\n\t}\n};\n//#endregion\n//#region packages/core/tools/src/json-schema.ts\n/**\n* Enforced JSON Schema subset shared by tool outputs, generated PTC mode\n* types, subagents, and workflows. The subset accepts any JSON root, an\n* annotation-only schema for unconstrained JSON, one scalar `type`, object\n* `properties`/`required`/boolean `additionalProperties`, array `items`,\n* type-correct scalar `enum`/`const`, and exact-one `oneOf`.\n*\n* Unsupported or misplaced keywords reject rather than being accepted without\n* enforcement. Consumers that require an object root apply\n* {@link assertObjectJsonSchema} before accepting input.\n* @module dsh-tools/json-schema\n*/\n/**\n* Thrown when a raw schema falls outside the enforced subset. `violations`\n* lists every offending path instead of stopping at the first author error.\n*/\nvar JsonSchemaError = class extends HarnessError {\n\t/** Individual schema violations in walk order. */\n\tviolations;\n\tconstructor(violations) {\n\t\tsuper(`unsupported JSON schema: ${violations.join(\"; \")}`, \"UNSUPPORTED_SCHEMA\");\n\t\tthis.name = \"JsonSchemaError\";\n\t\tthis.violations = violations;\n\t}\n};\nconst CONSTRAINT_KEYWORDS = new Set([\n\t\"type\",\n\t\"oneOf\",\n\t\"properties\",\n\t\"required\",\n\t\"additionalProperties\",\n\t\"items\",\n\t\"enum\",\n\t\"const\"\n]);\nconst ANNOTATION_KEYWORDS = new Set([\n\t\"description\",\n\t\"title\",\n\t\"default\",\n\t\"examples\"\n]);\nconst SCHEMA_TYPES = [\n\t\"object\",\n\t\"array\",\n\t\"string\",\n\t\"number\",\n\t\"integer\",\n\t\"boolean\",\n\t\"null\"\n];\n/** Whether a realm-owned intrinsic prototype is backed by its native constructor. */\nfunction hasIntrinsicConstructor(prototype, name) {\n\tconst constructor = Object.getOwnPropertyDescriptor(prototype, \"constructor\")?.value;\n\tif (typeof constructor !== \"function\") return false;\n\ttry {\n\t\treturn constructor.name === name && constructor.prototype === prototype && Function.prototype.toString.call(constructor) === `function ${name}() { [native code] }`;\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Whether a candidate is one realm's intrinsic `Object.prototype`. */\nfunction isIntrinsicObjectPrototype(value) {\n\treturn Object.getPrototypeOf(value) === null && hasIntrinsicConstructor(value, \"Object\");\n}\n/**\n* Test for a realm-agnostic plain JSON record without accepting arrays or\n* exotic objects.\n* @param value - candidate record from any JavaScript realm.\n* @returns Whether the value has a plain-object prototype chain.\n*/\nfunction isPlainJsonRecord(value) {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n\ttry {\n\t\tconst prototype = Object.getPrototypeOf(value);\n\t\treturn prototype === null || typeof prototype === \"object\" && isIntrinsicObjectPrototype(prototype);\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Whether an array uses one realm's intrinsic `Array.prototype`. */\nfunction hasPlainArrayPrototype(value) {\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (!Array.isArray(prototype) || !hasIntrinsicConstructor(prototype, \"Array\")) return false;\n\tconst objectPrototype = Object.getPrototypeOf(prototype);\n\treturn typeof objectPrototype === \"object\" && objectPrototype !== null && isIntrinsicObjectPrototype(objectPrototype);\n}\n/** Return whether a record contains only own enumerable string keys. */\nfunction hasOnlyEnumerableStringKeys(value) {\n\ttry {\n\t\treturn Reflect.ownKeys(value).every((key) => typeof key === \"string\" && Object.prototype.propertyIsEnumerable.call(value, key));\n\t} catch {\n\t\treturn false;\n\t}\n}\n/**\n* Test for an ordinary schema record whose keys survive JSON projection.\n* @param value - candidate record from any JavaScript realm.\n* @returns Whether the record has an intrinsic prototype and only own enumerable string keys.\n*/\nfunction isJsonSchemaRecord(value) {\n\treturn isPlainJsonRecord(value) && hasOnlyEnumerableStringKeys(value);\n}\n/**\n* Test for a dense ordinary array with no JSON-invisible decorations.\n* @param value - candidate array from any JavaScript realm.\n* @returns Whether the array is intrinsic, dense, and undecorated.\n*/\nfunction isPlainJsonArray(value) {\n\tif (!Array.isArray(value)) return false;\n\ttry {\n\t\tif (!hasPlainArrayPrototype(value) || Reflect.ownKeys(value).length !== value.length + 1) return false;\n\t\tfor (let index = 0; index < value.length; index++) if (!Object.hasOwn(value, index)) return false;\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Lossless finite JSON number, excluding negative zero. */\nfunction isJsonNumber(value) {\n\treturn typeof value === \"number\" && Number.isFinite(value) && !Object.is(value, -0);\n}\n/** Whether a scalar is valid for one declared schema type. */\nfunction scalarMatches(type, value) {\n\tswitch (type) {\n\t\tcase \"string\": return typeof value === \"string\";\n\t\tcase \"number\": return isJsonNumber(value);\n\t\tcase \"integer\": return isJsonNumber(value) && Number.isInteger(value);\n\t\tcase \"boolean\": return typeof value === \"boolean\";\n\t\tcase \"null\": return value === null;\n\t\t/* v8 ignore next -- JsonSchemaScalarType is closed; this retains compile-time exhaustiveness. */\n\t\tdefault: return assertNever(type, \"JsonSchemaType\");\n\t}\n}\n/** Keywords that are invalid beside `oneOf`. */\nconst ONE_OF_SIBLING_KEYWORDS = [\n\t\"properties\",\n\t\"required\",\n\t\"additionalProperties\",\n\t\"items\",\n\t\"enum\",\n\t\"const\"\n];\n/** Validate object-only fields after its property schemas have been visited. */\nfunction checkObjectSchemaTail(node, path, properties, violations) {\n\tconst hasRequired = Object.hasOwn(node, \"required\");\n\tconst required = hasRequired ? node.required : void 0;\n\tif (hasRequired) if (!isPlainJsonArray(required) || required.some((entry) => typeof entry !== \"string\")) violations.push(`${path}.required must be an array of strings`);\n\telse {\n\t\tconst declared = isJsonSchemaRecord(properties) ? properties : {};\n\t\tfor (const key of required) if (!Object.hasOwn(declared, key)) violations.push(`${path}.required names \"${key}\" which is not in properties`);\n\t}\n\tif (Object.hasOwn(node, \"additionalProperties\") && typeof node.additionalProperties !== \"boolean\") violations.push(`${path}.additionalProperties must be a boolean`);\n}\n/** Collect every violation for one raw schema tree without using the JavaScript call stack. */\nfunction checkSchemaNode(root, rootPath, violations, seen) {\n\tconst tasks = [{\n\t\tkind: \"enter\",\n\t\tnode: root,\n\t\tpath: rootPath\n\t}];\n\tfor (let task = tasks.pop(); task !== void 0; task = tasks.pop()) {\n\t\tif (task.kind === \"leave\") {\n\t\t\tseen.delete(task.node);\n\t\t\tcontinue;\n\t\t}\n\t\tif (task.kind === \"one-of-tail\") {\n\t\t\tfor (const key of ONE_OF_SIBLING_KEYWORDS) if (Object.hasOwn(task.node, key)) violations.push(`${task.path}.${key} is not supported beside oneOf`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (task.kind === \"object-tail\") {\n\t\t\tcheckObjectSchemaTail(task.node, task.path, task.properties, violations);\n\t\t\tcontinue;\n\t\t}\n\t\tconst { node, path } = task;\n\t\tif (!isJsonSchemaRecord(node)) {\n\t\t\tviolations.push(`${path} must be a schema object`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (seen.has(node)) {\n\t\t\tviolations.push(`${path} is circular`);\n\t\t\tcontinue;\n\t\t}\n\t\tseen.add(node);\n\t\ttasks.push({\n\t\t\tkind: \"leave\",\n\t\t\tnode\n\t\t});\n\t\tfor (const key of Object.keys(node)) {\n\t\t\tif (CONSTRAINT_KEYWORDS.has(key)) continue;\n\t\t\tif (ANNOTATION_KEYWORDS.has(key)) {\n\t\t\t\ttry {\n\t\t\t\t\tif (!isJsonValue(node[key])) violations.push(`${path}.${key} annotation must be lossless JSON data`);\n\t\t\t\t} catch {\n\t\t\t\t\tviolations.push(`${path}.${key} annotation must be lossless JSON data`);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tviolations.push(`${path}.${key} is not a supported keyword (subset: type/oneOf/properties/required/additionalProperties/items/enum/const + annotations)`);\n\t\t}\n\t\tif (Object.hasOwn(node, \"description\") && typeof node.description !== \"string\") violations.push(`${path}.description must be a string`);\n\t\tif (Object.hasOwn(node, \"title\") && typeof node.title !== \"string\") violations.push(`${path}.title must be a string`);\n\t\tconst hasType = Object.hasOwn(node, \"type\");\n\t\tconst hasOneOf = Object.hasOwn(node, \"oneOf\");\n\t\tif (hasType && hasOneOf) {\n\t\t\tviolations.push(`${path} cannot declare both type and oneOf`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!hasType && !hasOneOf) {\n\t\t\tfor (const key of ONE_OF_SIBLING_KEYWORDS) if (Object.hasOwn(node, key)) violations.push(`${path}.${key} requires type or oneOf`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (hasOneOf) {\n\t\t\tconst oneOf = node.oneOf;\n\t\t\ttasks.push({\n\t\t\t\tkind: \"one-of-tail\",\n\t\t\t\tnode,\n\t\t\t\tpath\n\t\t\t});\n\t\t\tif (!isPlainJsonArray(oneOf) || oneOf.length < 2) violations.push(`${path}.oneOf must be an array of at least two schemas`);\n\t\t\telse for (let index = oneOf.length - 1; index >= 0; index--) tasks.push({\n\t\t\t\tkind: \"enter\",\n\t\t\t\tnode: oneOf[index],\n\t\t\t\tpath: `${path}.oneOf[${index}]`\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst type = node.type;\n\t\tif (typeof type !== \"string\" || !SCHEMA_TYPES.includes(type)) {\n\t\t\tviolations.push(Array.isArray(type) ? `${path}.type must be a single type string (type arrays are not supported)` : `${path}.type must be one of ${SCHEMA_TYPES.join(\"/\")}`);\n\t\t\tcontinue;\n\t\t}\n\t\tconst schemaType = type;\n\t\tfor (const [key, types] of Object.entries({\n\t\t\tproperties: [\"object\"],\n\t\t\trequired: [\"object\"],\n\t\t\tadditionalProperties: [\"object\"],\n\t\t\titems: [\"array\"],\n\t\t\tenum: [\n\t\t\t\t\"string\",\n\t\t\t\t\"number\",\n\t\t\t\t\"integer\",\n\t\t\t\t\"boolean\",\n\t\t\t\t\"null\"\n\t\t\t],\n\t\t\tconst: [\n\t\t\t\t\"string\",\n\t\t\t\t\"number\",\n\t\t\t\t\"integer\",\n\t\t\t\t\"boolean\",\n\t\t\t\t\"null\"\n\t\t\t]\n\t\t})) if (Object.hasOwn(node, key) && !types.includes(schemaType)) violations.push(`${path}.${key} is not supported on type \"${schemaType}\"`);\n\t\tswitch (schemaType) {\n\t\t\tcase \"object\": {\n\t\t\t\tconst properties = Object.hasOwn(node, \"properties\") ? node.properties : void 0;\n\t\t\t\ttasks.push({\n\t\t\t\t\tkind: \"object-tail\",\n\t\t\t\t\tnode,\n\t\t\t\t\tpath,\n\t\t\t\t\tproperties\n\t\t\t\t});\n\t\t\t\tif (Object.hasOwn(node, \"properties\")) if (!isJsonSchemaRecord(properties)) violations.push(`${path}.properties must be an object of schemas`);\n\t\t\t\telse {\n\t\t\t\t\tconst entries = Object.entries(properties);\n\t\t\t\t\tfor (let index = entries.length - 1; index >= 0; index--) {\n\t\t\t\t\t\tconst entry = entries[index];\n\t\t\t\t\t\t/* v8 ignore next -- the loop is bounded by the captured entry count. */\n\t\t\t\t\t\tif (entry === void 0) continue;\n\t\t\t\t\t\ttasks.push({\n\t\t\t\t\t\t\tkind: \"enter\",\n\t\t\t\t\t\t\tnode: entry[1],\n\t\t\t\t\t\t\tpath: `${path}.properties.${entry[0]}`\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"array\":\n\t\t\t\tif (Object.hasOwn(node, \"items\")) tasks.push({\n\t\t\t\t\tkind: \"enter\",\n\t\t\t\t\tnode: node.items,\n\t\t\t\t\tpath: `${path}.items`\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"string\":\n\t\t\tcase \"number\":\n\t\t\tcase \"integer\":\n\t\t\tcase \"boolean\":\n\t\t\tcase \"null\": {\n\t\t\t\tconst hasEnum = Object.hasOwn(node, \"enum\");\n\t\t\t\tconst allowed = hasEnum ? node.enum : void 0;\n\t\t\t\tconst enumValid = isPlainJsonArray(allowed) && allowed.length > 0 && allowed.every((entry) => scalarMatches(schemaType, entry));\n\t\t\t\tif (hasEnum && !enumValid) violations.push(`${path}.enum must be a non-empty array of ${schemaType} values`);\n\t\t\t\tconst hasConst = Object.hasOwn(node, \"const\");\n\t\t\t\tconst declaredConst = hasConst ? node.const : void 0;\n\t\t\t\tconst constValid = scalarMatches(schemaType, declaredConst);\n\t\t\t\tif (hasConst) {\n\t\t\t\t\tif (!constValid) violations.push(`${path}.const must be a ${schemaType} value`);\n\t\t\t\t\telse if (enumValid && !allowed.includes(declaredConst)) violations.push(`${path}.const must be one of ${path}.enum when both are declared`);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t/* v8 ignore next -- schemaType was narrowed from the closed SCHEMA_TYPES table above. */\n\t\t\tdefault: assertNever(schemaType, \"JsonSchemaType\");\n\t\t}\n\t}\n}\n/**\n* Assert the enforced subset plus the object-root constraint retained by\n* subagent and workflow structured outputs.\n* @param schema - untrusted caller-supplied schema.\n* @returns Assertion that the schema belongs to the supported subset and has an object root.\n*/\nfunction assertObjectJsonSchema(schema) {\n\tconst violations = [];\n\tcheckSchemaNode(schema, \"schema\", violations, /* @__PURE__ */ new Set());\n\tif (violations.length === 0 && (!isJsonSchemaRecord(schema) || !Object.hasOwn(schema, \"type\") || schema.type !== \"object\")) violations.push(\"schema.type must be \\\"object\\\" (structured output is object-rooted)\");\n\tif (violations.length > 0) throw new JsonSchemaError(violations);\n}\n//#endregion\n//#region packages/workflow/workflow/src/index.ts\n/**\n* Typed error for workflow-seam failures. Extends {@link HarnessError}, so the\n* `code` is machine-routable taxonomy. `fatal` drives the combinator\n* discipline: `parallel()`/`pipeline()` re-throw a fatal error (a typo'd\n* option or a tripped cap must kill the script loudly), and reserve the\n* per-item `null` for child-run failures and ordinary in-stage script errors.\n* Every {@link WorkflowErrorCode} is fatal; the flag exists so the\n* distinction is explicit at every catch site rather than implied.\n*/\nvar WorkflowError = class extends HarnessError {\n\tcode;\n\t/** Whether combinators must propagate this error instead of nulling the item. */\n\tfatal;\n\tconstructor(message, code, options) {\n\t\tsuper(message, code, options);\n\t\tthis.name = \"WorkflowError\";\n\t\tthis.code = code;\n\t\tthis.fatal = options?.fatal ?? true;\n\t}\n};\n/**\n* Whether combinators must re-throw `error` instead of mapping the item to `null`.\n* @param error - any thrown value; fatality is host `instanceof` (unforgeable from a script realm).\n* @returns true iff `error` is a {@link WorkflowError} whose `fatal` flag is set.\n*/\nfunction isFatalWorkflowError(error) {\n\treturn error instanceof WorkflowError && error.fatal;\n}\n//#endregion\n//#region packages/workflow/workflow-ptc/src/runtime.ts\n/**\n* Workflow VM hooks, child callbacks, ordinary concurrency limits and result serialization.\n* PTC owns process confinement and cancellation. Fatal hook and provider failures propagate\n* through combinators; ordinary child failures and stage errors become per-item nulls.\n* @module @deepseek-ai/dsh-workflow-ptc/runtime\n*/\n/** The `agent()` options the script may pass; everything else rejects loud. */\nconst SUPPORTED_AGENT_OPTIONS = new Set([\n\t\"label\",\n\t\"phase\",\n\t\"schema\",\n\t\"provider\",\n\t\"model\"\n]);\n/** Deferred Claude Code options we name explicitly in the rejection message. */\nconst DEFERRED_AGENT_OPTIONS = new Set([\n\t\"effort\",\n\t\"isolation\",\n\t\"agentType\"\n]);\n/** A short display label derived from the prompt when the script passes none. */\nfunction defaultLabel(prompt) {\n\tconst newline = prompt.indexOf(\"\\n\");\n\tconst line = newline === -1 ? prompt : prompt.slice(0, newline);\n\treturn line.length <= 48 ? line : `${line.slice(0, 47)}…`;\n}\n/**\n* One script execution inside the confined Node process. The host owns\n* cancellation and cleanup of any dropped child work.\n*/\nvar WorkflowExecution = class {\n\tlimits;\n\tobserver;\n\tchildren;\n\t/** 1-based count of `agent()` calls started (the `agentsStarted` result field). */\n\tstarted = 0;\n\tactiveSlots = 0;\n\tslotWaiters = [];\n\tcurrentPhase;\n\tcontext;\n\tcompiled;\n\tconstructor(meta, body, args, limits, observer, children) {\n\t\tthis.limits = limits;\n\t\tthis.observer = observer;\n\t\tthis.children = children;\n\t\ttry {\n\t\t\tthis.compiled = new vm.Script(`(async () => {\\n${body}\\n})()`, {\n\t\t\t\tfilename: `workflow:${meta.name}`,\n\t\t\t\tlineOffset: -1\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrow new WorkflowError(`workflow script does not parse: ${String(error)}`, \"SCRIPT_PARSE\", { cause: error });\n\t\t}\n\t\tthis.context = vm.createContext({}, { name: `workflow:${meta.name}` });\n\t\tconst globals = {\n\t\t\tagent: (prompt, opts) => this.contain(this.agent(prompt, opts)),\n\t\t\tparallel: (thunks) => this.contain(this.parallel(thunks)),\n\t\t\tpipeline: (items, ...stages) => this.contain(this.pipeline(items, stages)),\n\t\t\tphase: (title) => {\n\t\t\t\tthis.phase(title);\n\t\t\t},\n\t\t\tlog: (message) => {\n\t\t\t\tthis.log(message);\n\t\t\t},\n\t\t\targs\n\t\t};\n\t\tfor (const [key, value] of Object.entries(globals)) this.context[key] = typeof value === \"function\" ? Object.freeze(value) : value;\n\t}\n\t/**\n\t* Run the script and materialize its JSON return value.\n\t* @returns A completed or error result; script failures never reject.\n\t*/\n\tasync drive() {\n\t\ttry {\n\t\t\tconst scriptPromise = this.compiled.runInContext(this.context, { timeout: this.limits.syncTimeoutMs });\n\t\t\tconst raw = await this.contain(Promise.resolve(scriptPromise));\n\t\t\treturn {\n\t\t\t\tvalue: raw === void 0 ? null : this.materializeResult(raw),\n\t\t\t\tstopReason: \"completed\",\n\t\t\t\tagentsStarted: this.started\n\t\t\t};\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tvalue: null,\n\t\t\t\tstopReason: \"error\",\n\t\t\t\terror: renderThrown(error),\n\t\t\t\t...error instanceof WorkflowError ? { errorCode: error.code } : {},\n\t\t\t\tagentsStarted: this.started\n\t\t\t};\n\t\t}\n\t}\n\t/**\n\t* Attach a no-op rejection consumer WITHOUT changing what the caller\n\t* receives: if the script drops the promise, a host rejection cannot become\n\t* an unhandled rejection that kills the process; if\n\t* the script does await it, it still observes the rejection.\n\t*/\n\tcontain(promise) {\n\t\tpromise.catch(() => {});\n\t\treturn promise;\n\t}\n\t/** Materialize the script's return value; violations become RESULT_UNSERIALIZABLE. */\n\tmaterializeResult(raw) {\n\t\ttry {\n\t\t\treturn materializeFromRealm(raw, \"workflow result\");\n\t\t} catch (error) {\n\t\t\t/* v8 ignore next -- defensive rethrow arm: materializeFromRealm only throws MaterializeError */\n\t\t\tif (!(error instanceof MaterializeError)) throw error;\n\t\t\tthrow new WorkflowError(`the workflow's return value is not plain JSON data — ${error.message}. Return only JSON-serializable objects/arrays/scalars.`, \"RESULT_UNSERIALIZABLE\", { cause: error });\n\t\t}\n\t}\n\t/** Acquire one concurrency slot in FIFO order. */\n\tacquireSlot() {\n\t\tif (this.activeSlots < this.limits.maxConcurrentAgents) {\n\t\t\tthis.activeSlots += 1;\n\t\t\treturn Promise.resolve();\n\t\t}\n\t\treturn new Promise((resolve) => {\n\t\t\tthis.slotWaiters.push(() => {\n\t\t\t\tthis.activeSlots += 1;\n\t\t\t\tresolve();\n\t\t\t});\n\t\t});\n\t}\n\treleaseSlot() {\n\t\tthis.activeSlots -= 1;\n\t\tconst next = this.slotWaiters.shift();\n\t\tif (next) next();\n\t}\n\t/** The `agent(prompt, opts)` hook. */\n\tasync agent(rawPrompt, rawOpts) {\n\t\tif (typeof rawPrompt !== \"string\" || rawPrompt.length === 0) throw new WorkflowError(\"agent() requires a non-empty prompt string\", \"INVALID_ARGUMENT\");\n\t\tconst opts = this.readAgentOptions(rawOpts);\n\t\tif (this.started >= this.limits.maxTotalAgents) throw new WorkflowError(`this run reached its total agent cap (${this.limits.maxTotalAgents}) — a runaway-loop backstop; raise the applicable maxTotalAgents limit if the scale is intentional`, \"AGENT_CAP\");\n\t\tthis.started += 1;\n\t\tconst seq = this.started;\n\t\tconst label = opts.label ?? defaultLabel(rawPrompt);\n\t\tconst phase = opts.phase ?? this.currentPhase;\n\t\tawait this.acquireSlot();\n\t\ttry {\n\t\t\tlet run;\n\t\t\ttry {\n\t\t\t\trun = await this.children.startAgent({\n\t\t\t\t\tprompt: rawPrompt,\n\t\t\t\t\t...opts.schema !== void 0 ? { schema: opts.schema } : {},\n\t\t\t\t\t...opts.provider !== void 0 ? { provider: opts.provider } : {},\n\t\t\t\t\t...opts.model !== void 0 ? { model: opts.model } : {}\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tthrow new WorkflowError(`agent() could not start a child: ${renderThrown(error)}`, \"AGENT_START\", { cause: error });\n\t\t\t}\n\t\t\tconst info = {\n\t\t\t\tseq,\n\t\t\t\tlabel,\n\t\t\t\t...phase !== void 0 ? { phase } : {},\n\t\t\t\tchildId: brandString(run.id)\n\t\t\t};\n\t\t\tthis.observer.agentStart(info);\n\t\t\ttry {\n\t\t\t\tlet result;\n\t\t\t\ttry {\n\t\t\t\t\tresult = await run.result;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t\t...info,\n\t\t\t\t\t\toutcome: \"failed\"\n\t\t\t\t\t});\n\t\t\t\t\tthrow new WorkflowError(`child agent run failed: ${renderThrown(error)}`, \"AGENT_RESULT\", { cause: error });\n\t\t\t\t}\n\t\t\t\tif (result.stopReason === \"completed\") {\n\t\t\t\t\tif (opts.schema !== void 0) {\n\t\t\t\t\t\tif (result.structured === void 0) {\n\t\t\t\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t\t\t\t...info,\n\t\t\t\t\t\t\t\toutcome: \"failed\"\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\treturn null;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t\t\t...info,\n\t\t\t\t\t\t\toutcome: \"completed\"\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn result.structured;\n\t\t\t\t\t}\n\t\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t\t...info,\n\t\t\t\t\t\toutcome: \"completed\"\n\t\t\t\t\t});\n\t\t\t\t\treturn extractTextContent(result.output);\n\t\t\t\t}\n\t\t\t\tthis.observer.agentEnd({\n\t\t\t\t\t...info,\n\t\t\t\t\toutcome: \"failed\"\n\t\t\t\t});\n\t\t\t\treturn null;\n\t\t\t} finally {\n\t\t\t\tawait run.dispose();\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.releaseSlot();\n\t\t}\n\t}\n\t/** Materialize + validate the `agent()` options bag from the realm. */\n\treadAgentOptions(rawOpts) {\n\t\tif (rawOpts === void 0) return {};\n\t\tlet opts;\n\t\ttry {\n\t\t\topts = materializeFromRealm(rawOpts, \"agent() options\");\n\t\t} catch (error) {\n\t\t\t/* v8 ignore next -- defensive rethrow arm: materializeFromRealm only throws MaterializeError */\n\t\t\tif (!(error instanceof MaterializeError)) throw error;\n\t\t\tthrow new WorkflowError(`agent() options must be plain JSON data — ${error.message}`, \"INVALID_ARGUMENT\", { cause: error });\n\t\t}\n\t\tif (typeof opts !== \"object\" || opts === null || Array.isArray(opts)) throw new WorkflowError(\"agent() options must be an object\", \"INVALID_ARGUMENT\");\n\t\tconst record = opts;\n\t\tfor (const key of Object.keys(record)) {\n\t\t\tif (SUPPORTED_AGENT_OPTIONS.has(key)) continue;\n\t\t\tif (DEFERRED_AGENT_OPTIONS.has(key)) throw new WorkflowError(`agent() option \"${key}\" is deferred and not supported by this engine (supported: label, phase, schema, provider, model)`, \"UNSUPPORTED_OPTION\");\n\t\t\tthrow new WorkflowError(`agent() option \"${key}\" is not recognized (supported: label, phase, schema, provider, model)`, \"UNSUPPORTED_OPTION\");\n\t\t}\n\t\tfor (const key of [\n\t\t\t\"label\",\n\t\t\t\"phase\",\n\t\t\t\"provider\",\n\t\t\t\"model\"\n\t\t]) if (record[key] !== void 0 && typeof record[key] !== \"string\") throw new WorkflowError(`agent() option \"${key}\" must be a string`, \"INVALID_ARGUMENT\");\n\t\tlet schema;\n\t\tif (record.schema !== void 0) try {\n\t\t\tassertObjectJsonSchema(record.schema);\n\t\t\tschema = record.schema;\n\t\t} catch (error) {\n\t\t\t/* v8 ignore next -- defensive rethrow arm: assertObjectJsonSchema only throws JsonSchemaError */\n\t\t\tif (!(error instanceof JsonSchemaError)) throw error;\n\t\t\tthrow new WorkflowError(`agent() schema is outside the supported subset — ${error.message}`, \"UNSUPPORTED_SCHEMA\", { cause: error });\n\t\t}\n\t\treturn {\n\t\t\t...record.label !== void 0 ? { label: record.label } : {},\n\t\t\t...record.phase !== void 0 ? { phase: record.phase } : {},\n\t\t\t...record.provider !== void 0 ? { provider: record.provider } : {},\n\t\t\t...record.model !== void 0 ? { model: record.model } : {},\n\t\t\t...schema !== void 0 ? { schema } : {}\n\t\t};\n\t}\n\t/** The `parallel(thunks)` hook: each thunk caught → `null`; fatal errors propagate. */\n\tasync parallel(rawThunks) {\n\t\tif (!Array.isArray(rawThunks)) throw new WorkflowError(\"parallel() requires an array of zero-argument functions\", \"INVALID_ARGUMENT\");\n\t\tthis.assertItemCap(rawThunks.length, \"parallel()\");\n\t\tconst thunks = rawThunks.map((thunk, index) => {\n\t\t\tif (typeof thunk !== \"function\") throw new WorkflowError(`parallel() item ${index} is not a function`, \"INVALID_ARGUMENT\");\n\t\t\treturn thunk;\n\t\t});\n\t\treturn Promise.all(thunks.map(async (thunk) => {\n\t\t\ttry {\n\t\t\t\treturn await thunk();\n\t\t\t} catch (error) {\n\t\t\t\tif (isFatalWorkflowError(error)) throw error;\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}));\n\t}\n\t/** The `pipeline(items, ...stages)` hook: per-item stage chains, NO cross-stage barrier. */\n\tasync pipeline(rawItems, rawStages) {\n\t\tif (!Array.isArray(rawItems)) throw new WorkflowError(\"pipeline() requires an items array\", \"INVALID_ARGUMENT\");\n\t\tthis.assertItemCap(rawItems.length, \"pipeline()\");\n\t\tif (rawStages.length === 0) throw new WorkflowError(\"pipeline() requires at least one stage function\", \"INVALID_ARGUMENT\");\n\t\tconst stages = rawStages.map((stage, index) => {\n\t\t\tif (typeof stage !== \"function\") throw new WorkflowError(`pipeline() stage ${index} is not a function`, \"INVALID_ARGUMENT\");\n\t\t\treturn stage;\n\t\t});\n\t\treturn Promise.all(rawItems.map(async (item, index) => {\n\t\t\tlet value = item;\n\t\t\ttry {\n\t\t\t\tfor (const stage of stages) value = await stage(value, item, index);\n\t\t\t\treturn value;\n\t\t\t} catch (error) {\n\t\t\t\tif (isFatalWorkflowError(error)) throw error;\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}));\n\t}\n\tassertItemCap(length, hook) {\n\t\tif (length > this.limits.maxItemsPerCall) throw new WorkflowError(`${hook} received ${length} items — over the per-call cap (${this.limits.maxItemsPerCall}); split the work or raise maxItemsPerCall in the engine config`, \"ITEM_CAP\");\n\t}\n\t/** The `phase(title)` hook: sets the current label for subsequent `agent()` calls and notifies observers. */\n\tphase(title) {\n\t\tif (typeof title !== \"string\" || title.length === 0) throw new WorkflowError(\"phase() requires a non-empty title string\", \"INVALID_ARGUMENT\");\n\t\tthis.currentPhase = title;\n\t\tthis.observer.phase(title);\n\t}\n\t/** The `log(message)` hook: narration to observers. */\n\tlog(message) {\n\t\tif (typeof message !== \"string\") throw new WorkflowError(\"log() requires a message string\", \"INVALID_ARGUMENT\");\n\t\tthis.observer.log(message);\n\t}\n};\n//#endregion\n//#region packages/workflow/workflow-ptc/src/guest.ts\n/**\n* Run a workflow with one progress batch in flight. Drain progress before child\n* disposal and the terminal result; PTC and the host own cancellation and cleanup.\n* @param host - JSON callbacks owned by this workflow run.\n* @returns The script result after progress delivery; initialization failures reject.\n*/\nasync function runWorkflowGuest(host) {\n\tconst init = await host.begin({});\n\tlet queued = [];\n\tlet inFlight;\n\tlet progressError;\n\tconst flush = () => {\n\t\tif (inFlight !== void 0 || queued.length === 0) return;\n\t\tconst batch = queued;\n\t\tqueued = [];\n\t\tinFlight = host.progress(batch).then(() => {\n\t\t\tinFlight = void 0;\n\t\t\tflush();\n\t\t}, (error) => {\n\t\t\tprogressError = renderThrown(error);\n\t\t\tqueued = [];\n\t\t\tinFlight = void 0;\n\t\t});\n\t};\n\tconst send = (event) => {\n\t\tif (progressError !== void 0) return;\n\t\tqueued.push(event);\n\t\tflush();\n\t};\n\tconst drain = async () => {\n\t\twhile (inFlight !== void 0) await inFlight;\n\t};\n\tconst result = await new WorkflowExecution(init.meta, init.body, init.args, init.limits, {\n\t\tphase: (title) => {\n\t\t\tsend({\n\t\t\t\ttype: \"phase\",\n\t\t\t\ttitle\n\t\t\t});\n\t\t},\n\t\tlog: (message) => {\n\t\t\tsend({\n\t\t\t\ttype: \"log\",\n\t\t\t\tmessage\n\t\t\t});\n\t\t},\n\t\tagentStart: (info) => {\n\t\t\tsend({\n\t\t\t\ttype: \"agent-start\",\n\t\t\t\tinfo\n\t\t\t});\n\t\t},\n\t\tagentEnd: (info) => {\n\t\t\tsend({\n\t\t\t\ttype: \"agent-end\",\n\t\t\t\tinfo\n\t\t\t});\n\t\t}\n\t}, { async startAgent(request) {\n\t\tconst { callId, childId } = await host.startChild(request);\n\t\tconst result = host.childResult({ callId });\n\t\tresult.catch(() => {});\n\t\treturn {\n\t\t\tid: childId,\n\t\t\tresult,\n\t\t\tasync dispose() {\n\t\t\t\tawait drain();\n\t\t\t\tawait host.disposeChild({ callId });\n\t\t\t}\n\t\t};\n\t} }).drive();\n\tawait drain();\n\treturn progressError === void 0 ? result : {\n\t\tvalue: null,\n\t\tstopReason: \"error\",\n\t\terror: progressError,\n\t\tagentsStarted: result.agentsStarted\n\t};\n}\n//#endregion\nexport { runWorkflowGuest };\n//# sourceURL=dsh-workflow-guest.js\n" diff --git a/packages/workflow/workflow-ptc/src/runtime.ts b/packages/workflow/workflow-ptc/src/runtime.ts index b99424420b..ca79b2f3fb 100644 --- a/packages/workflow/workflow-ptc/src/runtime.ts +++ b/packages/workflow/workflow-ptc/src/runtime.ts @@ -7,7 +7,7 @@ import * as vm from 'node:vm' import { brandString } from '@deepseek-ai/dsh-brand' -import type { ContentBlock } from '@deepseek-ai/dsh-llm' +import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import type { SessionId } from '@deepseek-ai/dsh-session' import { assertObjectJsonSchema, JsonSchemaError } from '@deepseek-ai/dsh-tools' import type { ObjectJsonSchema } from '@deepseek-ai/dsh-tools' @@ -34,14 +34,6 @@ const SUPPORTED_AGENT_OPTIONS = new Set(['label', 'phase', 'schema', 'provider', /** Deferred Claude Code options we name explicitly in the rejection message. */ const DEFERRED_AGENT_OPTIONS = new Set(['effort', 'isolation', 'agentType']) -/** Flatten a child's final output blocks to text (the non-schema `agent()` result). */ -function outputText(blocks: ContentBlock[]): string { - return blocks - .filter((block): block is Extract => block.type === 'text') - .map(block => block.text) - .join('') -} - /** A short display label derived from the prompt when the script passes none. */ function defaultLabel(prompt: string): string { const newline = prompt.indexOf('\n') @@ -222,7 +214,7 @@ export class WorkflowExecution { return result.structured } this.observer.agentEnd({ ...info, outcome: 'completed' }) - return outputText(result.output) + return extractTextContent(result.output) } this.observer.agentEnd({ ...info, outcome: 'failed' }) return null From 10aed76233436b20f2d95af25d351ad30c615f9f Mon Sep 17 00:00:00 2001 From: _Kerman Date: Fri, 13 Nov 2026 12:58:10 +0800 Subject: [PATCH 15/31] docs: refresh generated dependency graphs after master merge --- docs/event-producer-consumer.md | 6 +----- docs/event-producer-consumer.zh.md | 6 +----- 2 files changed, 2 insertions(+), 10 deletions(-) diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 1fd7441387..ac2d8cd5f5 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -60,11 +60,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `llm-pi-ai/request-headers` | `waterfall` | [`packages/llm/llm-pi-ai/src/index.ts:113`](../packages/llm/llm-pi-ai/src/index.ts) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) (`waterfall`) | - | | `llm/adapters-updated` | `emit` | [`packages/llm/llm/src/types.ts:24`](../packages/llm/llm/src/types.ts) | [`llm`](../packages/llm/llm) (`events.dispatch`) | [`acp`](../packages/acp/acp), `remotes` | | `llm/models-updated` | `emit` | [`packages/llm/llm/src/types.ts:30`](../packages/llm/llm/src/types.ts) | [`llm-deepseek`](../packages/llm/llm-deepseek) (`emit`) | `remotes` | -<<<<<<< HEAD -| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:80`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) | -======= -| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:76`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title), [`timeline`](../packages/experimental/timeline) | ->>>>>>> origin/master +| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:80`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title), [`timeline`](../packages/experimental/timeline) | | `mcp-manager/status` | `parallel` | [`packages/mcp/mcp-manager/src/types.ts:46`](../packages/mcp/mcp-manager/src/types.ts) | [`mcp-manager`](../packages/mcp/mcp-manager) (`parallel`) | - | | `permission-presets/catalog-changed` | `emit` | [`packages/interaction/permission-presets/src/types.ts:48`](../packages/interaction/permission-presets/src/types.ts) | [`permission-presets`](../packages/interaction/permission-presets) (`events.dispatch`) | `remotes` | | `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:455`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index f569d59b0b..82c9d95cd4 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -62,11 +62,7 @@ | `llm-pi-ai/request-headers` | `waterfall` | [`packages/llm/llm-pi-ai/src/index.ts:113`](../packages/llm/llm-pi-ai/src/index.ts) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) (`waterfall`) | - | | `llm/adapters-updated` | `emit` | [`packages/llm/llm/src/types.ts:24`](../packages/llm/llm/src/types.ts) | [`llm`](../packages/llm/llm) (`events.dispatch`) | [`acp`](../packages/acp/acp), `remotes` | | `llm/models-updated` | `emit` | [`packages/llm/llm/src/types.ts:30`](../packages/llm/llm/src/types.ts) | [`llm-deepseek`](../packages/llm/llm-deepseek) (`emit`) | `remotes` | -<<<<<<< HEAD -| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:80`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) | -======= -| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:76`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title), [`timeline`](../packages/experimental/timeline) | ->>>>>>> origin/master +| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:80`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title), [`timeline`](../packages/experimental/timeline) | | `mcp-manager/status` | `parallel` | [`packages/mcp/mcp-manager/src/types.ts:46`](../packages/mcp/mcp-manager/src/types.ts) | [`mcp-manager`](../packages/mcp/mcp-manager) (`parallel`) | - | | `permission-presets/catalog-changed` | `emit` | [`packages/interaction/permission-presets/src/types.ts:48`](../packages/interaction/permission-presets/src/types.ts) | [`permission-presets`](../packages/interaction/permission-presets) (`events.dispatch`) | `remotes` | | `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:455`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | From 7dc068057047e23565e0825824f7467d9dec11f3 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Fri, 13 Nov 2026 13:03:46 +0800 Subject: [PATCH 16/31] fix: keep text extraction imports unique after master merge --- docs/config-catalog.md | 2 +- docs/config-catalog.zh.md | 2 +- packages/experimental/claude-code-mods/src/index.ts | 1 - packages/llm/llm/tests/message.spec.ts | 1 - 4 files changed, 2 insertions(+), 4 deletions(-) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 6304197d85..de1f837b3c 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1104,7 +1104,7 @@ export interface StagehandModelConfig { ## `@deepseek-ai/dsh-experimental-claude-code-mods` - `inject`: `workingDirectory` · `agents` -- `source`: [`packages/experimental/claude-code-mods/src/index.ts:56`](../packages/experimental/claude-code-mods/src/index.ts) +- `source`: [`packages/experimental/claude-code-mods/src/index.ts:55`](../packages/experimental/claude-code-mods/src/index.ts) ```ts config-catalog /** Plugin config: the limits mod hooks run under. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index e05501d811..503bb33fbd 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1106,7 +1106,7 @@ export interface StagehandModelConfig { ## `@deepseek-ai/dsh-experimental-claude-code-mods` - `inject`: `workingDirectory` · `agents` -- `source`: [`packages/experimental/claude-code-mods/src/index.ts:56`](../packages/experimental/claude-code-mods/src/index.ts) +- `source`: [`packages/experimental/claude-code-mods/src/index.ts:55`](../packages/experimental/claude-code-mods/src/index.ts) ```ts config-catalog /** Plugin config: the limits mod hooks run under. */ diff --git a/packages/experimental/claude-code-mods/src/index.ts b/packages/experimental/claude-code-mods/src/index.ts index ee995871b1..08398f4b0b 100644 --- a/packages/experimental/claude-code-mods/src/index.ts +++ b/packages/experimental/claude-code-mods/src/index.ts @@ -19,7 +19,6 @@ import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import type { AssistantMessage, ContentBlock, TokenUsage } from '@deepseek-ai/dsh-llm' import { brandString } from '@deepseek-ai/dsh-brand' import type { SessionId } from '@deepseek-ai/dsh-session/types' -import { extractTextContent } from '@deepseek-ai/dsh-llm/message' import type { UserMessage } from '@deepseek-ai/dsh-session' import { scopeOf } from '@deepseek-ai/dsh-scope' import { validateJsonSchemaValue } from '@deepseek-ai/dsh-tools' diff --git a/packages/llm/llm/tests/message.spec.ts b/packages/llm/llm/tests/message.spec.ts index 8158bb047d..f70710672e 100644 --- a/packages/llm/llm/tests/message.spec.ts +++ b/packages/llm/llm/tests/message.spec.ts @@ -1,5 +1,4 @@ import { describe, expect, expectTypeOf, it } from 'vitest' -import type { AttachmentId } from '@deepseek-ai/dsh-attachment/types' import { brandString } from '@deepseek-ai/dsh-brand' import type { AttachmentId } from '@deepseek-ai/dsh-attachment' import { From 79015b174c1413d755470a076c6861322eb07e08 Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Mon, 16 Nov 2026 11:59:34 +0800 Subject: [PATCH 17/31] refactor(session): move list metadata to sessionQuery and query Workspace headers Address review on #8238: - Replace the Workspace.sessionHeaders property with getSessionHeaders(). The public contract states only membership and order; the in-memory header index is documented on the implementation. - SessionQueryEngine now injects sessionProjections, registers the sessionListMetadata projection in Service.init, and exposes getListMetadata(session). Disposing the service releases the registration. The Session API and list_session read metadata through ctx.sessionQuery; registerSessionListMetadata and the passed reader closure are removed. - SqliteSessionQueryEngine injects sessionProjections and chains Service.init. - Tests: a newly attached Session appears in a later getSessionHeaders() result; query-service disposal removes the projection; test query services run Service.init; projection-order expectations follow the new registration order. --- docs/config-catalog.md | 2 +- docs/config-catalog.zh.md | 2 +- docs/subsystems/session-query.md | 7 +++ docs/subsystems/session-query.zh.md | 7 +++ docs/subsystems/workspace.md | 7 +-- docs/subsystems/workspace.zh.md | 7 +-- .../api/session-controller/README.i18n.yaml | 4 +- packages/api/session-controller/README.md | 2 +- packages/api/session-controller/README.zh.md | 2 +- packages/api/session-controller/src/list.ts | 11 ++-- .../tests/agent.host.spec.ts | 2 +- .../tests/commands-create-fork.host.spec.ts | 2 +- .../commands-queue-attachment.host.spec.ts | 2 +- .../tests/controller.host.spec.ts | 2 +- .../tests/history-controller.host.spec.ts | 2 +- .../tests/list-scheduling.host.spec.ts | 3 +- .../tests/listeners.host.spec.ts | 2 +- .../tests/session-fork.host.spec.ts | 2 +- .../session-history-journal.host.spec.ts | 2 +- .../tests/session-projections.host.spec.ts | 6 +- .../tests/session-search.host.spec.ts | 60 ++++++++++--------- .../tests/state-controller.host.spec.ts | 2 +- .../tests/subagent-catalog.host.spec.ts | 4 +- .../session-controller/tests/test-remote.ts | 16 +++-- .../tests/transport.host.spec.ts | 7 +-- .../tests/session-reference.spec.ts | 5 ++ .../extensions/tool-cordis/src/api-catalog.ts | 12 +++- .../session-query-sqlite/src/index.ts | 5 +- .../session-query/README.i18n.yaml | 18 +++--- .../session-query/session-query/README.md | 9 +-- .../session-query/session-query/README.zh.md | 9 +-- .../session-query/session-query/package.json | 3 - .../session-query/session-query/src/index.ts | 21 ++++++- .../session-query/src/list-metadata.ts | 21 ++----- .../session-query/tests/list-metadata.spec.ts | 37 +++++------- .../tool-session-list/README.i18n.yaml | 4 +- .../session-query/tool-session-list/README.md | 2 +- .../tool-session-list/README.zh.md | 2 +- .../tool-session-list/src/index.ts | 7 +-- .../tool-session-list/src/list.ts | 13 ++-- packages/workspace/workspace/README.i18n.yaml | 4 +- packages/workspace/workspace/README.md | 2 +- packages/workspace/workspace/README.zh.md | 2 +- packages/workspace/workspace/src/entity.ts | 3 +- packages/workspace/workspace/src/types.ts | 7 +-- .../workspace/tests/workspace.spec.ts | 19 +++++- scripts/gen-cordis-catalog.ts | 1 + 47 files changed, 206 insertions(+), 165 deletions(-) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index b35e5aa168..3d1cf5eeab 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -3280,7 +3280,7 @@ export interface Config { ## `@deepseek-ai/dsh-session-query-sqlite` -- `inject`: `sessions` +- `inject`: `sessions` · `sessionProjections` - `refs`: [`SessionQueryConfig`](../packages/session-query/session-query/src/index.ts) - `source`: [`packages/session-query/session-query-sqlite/src/index.ts:92`](../packages/session-query/session-query-sqlite/src/index.ts) diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 908b3c708d..44a2550947 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -3282,7 +3282,7 @@ export interface Config { ## `@deepseek-ai/dsh-session-query-sqlite` -- `inject`: `sessions` +- `inject`: `sessions` · `sessionProjections` - `refs`: [`SessionQueryConfig`](../packages/session-query/session-query/src/index.ts) - `source`: [`packages/session-query/session-query-sqlite/src/index.ts:92`](../packages/session-query/session-query-sqlite/src/index.ts) diff --git a/docs/subsystems/session-query.md b/docs/subsystems/session-query.md index 94e7eae55b..5dca82b24c 100644 --- a/docs/subsystems/session-query.md +++ b/docs/subsystems/session-query.md @@ -381,6 +381,13 @@ Unified live-preferred session query service. Exact reads, filters, and traces are backend-independent concrete behavior. A backend implements full-text observation, reconciliation, ranking, cursor generations, and query execution on the same `ctx.sessionQuery` service. ```ts cordis-catalog +/** + * Read the metadata that summarizes one live or prepared Session in a Session list. + * @param session - live or prepared Session to summarize. + * @returns whether the Session has no turn, and its latest human-authored prompt time. + */ +getListMetadata(session: Session): SessionListMetadata + /** * Observe one exact live or prepared Session without a persistence listing preflight. * @param sessionId - logical Session identity. diff --git a/docs/subsystems/session-query.zh.md b/docs/subsystems/session-query.zh.md index 7d33c1946c..40605385c1 100644 --- a/docs/subsystems/session-query.zh.md +++ b/docs/subsystems/session-query.zh.md @@ -381,6 +381,13 @@ Unified live-preferred session query service. Exact reads, filters, and traces are backend-independent concrete behavior. A backend implements full-text observation, reconciliation, ranking, cursor generations, and query execution on the same `ctx.sessionQuery` service. ```ts cordis-catalog +/** + * Read the metadata that summarizes one live or prepared Session in a Session list. + * @param session - live or prepared Session to summarize. + * @returns whether the Session has no turn, and its latest human-authored prompt time. + */ +getListMetadata(session: Session): SessionListMetadata + /** * Observe one exact live or prepared Session without a persistence listing preflight. * @param sessionId - logical Session identity. diff --git a/docs/subsystems/workspace.md b/docs/subsystems/workspace.md index ba01258c94..c82ba0dbc9 100644 --- a/docs/subsystems/workspace.md +++ b/docs/subsystems/workspace.md @@ -64,11 +64,10 @@ interface Workspace { readonly sessionIds: readonly SessionId[] /** - * Stored headers of {@link sessionIds}, in the same order. Read from the - * registry's startup and attach-time header index without persistence I/O; - * headers are immutable, so an indexed header never goes stale. + * List the stored headers of the current members. + * @returns a new array with one header per entry of {@link sessionIds}, in the same order. */ - readonly sessionHeaders: readonly SessionHeader[] + getSessionHeaders(): readonly SessionHeader[] /** * Replace the display title durably. diff --git a/docs/subsystems/workspace.zh.md b/docs/subsystems/workspace.zh.md index 55b4bd531d..3504f9391e 100644 --- a/docs/subsystems/workspace.zh.md +++ b/docs/subsystems/workspace.zh.md @@ -64,11 +64,10 @@ interface Workspace { readonly sessionIds: readonly SessionId[] /** - * Stored headers of {@link sessionIds}, in the same order. Read from the - * registry's startup and attach-time header index without persistence I/O; - * headers are immutable, so an indexed header never goes stale. + * List the stored headers of the current members. + * @returns a new array with one header per entry of {@link sessionIds}, in the same order. */ - readonly sessionHeaders: readonly SessionHeader[] + getSessionHeaders(): readonly SessionHeader[] /** * Replace the display title durably. diff --git a/packages/api/session-controller/README.i18n.yaml b/packages/api/session-controller/README.i18n.yaml index d309647399..5f99650f2f 100644 --- a/packages/api/session-controller/README.i18n.yaml +++ b/packages/api/session-controller/README.i18n.yaml @@ -15,8 +15,8 @@ en: 1fdf707322fb6996 zh: 0204f7e9d4aa3cce /session-controller/use-this-package: - en: 179c281216ad0660 - zh: 81dbc1d8985ab21b + en: 15d6cb30e1e7f5e2 + zh: 21fe7028a4ed4aef /session-controller/client-references: en: e8979a803ec3e194 zh: c567efcd971728ba diff --git a/packages/api/session-controller/README.md b/packages/api/session-controller/README.md index 12e9c840a0..7c71dea39e 100644 --- a/packages/api/session-controller/README.md +++ b/packages/api/session-controller/README.md @@ -43,7 +43,7 @@ Every Remote endpoint is access-controlled: a Peer whose principal is not the ow List rows carry `formatStatus` when available, so Clients can identify migration-required Sessions without requesting their projections. -Host list generation yields between complete rows only when its configured work slice is exhausted; cheap remaining work returns without a forced yield. Request cancellation is checked per row and after each yield and rejects without partial results. Each row is synchronous; the list does not promise one cross-Session snapshot. A Session already queued as cold remains a cached row if it attaches during a yield: Client in-flight mutation replay corrects its availability, and sequenced projections supersede cached hints. An attached Session's summary reads its blankness and last-prompt recency through the [shared Session-list reader](../../session-query/session-query/README.md#shared-list-metadata), and its projection hints carry every summary key computed through `snapshot`. The first summary of an attached Session computes these projections over its whole in-memory log, and later summaries advance them incrementally; this computation runs inside one synchronous row, so `listWorkSliceMs` cannot split it. +Host list generation yields between complete rows only when its configured work slice is exhausted; cheap remaining work returns without a forced yield. Request cancellation is checked per row and after each yield and rejects without partial results. Each row is synchronous; the list does not promise one cross-Session snapshot. A Session already queued as cold remains a cached row if it attaches during a yield: Client in-flight mutation replay corrects its availability, and sequenced projections supersede cached hints. An attached Session's summary reads its blankness and last-prompt recency through [`sessionQuery.getListMetadata`](../../session-query/session-query/README.md#session-list-metadata), and its projection hints carry every summary key computed through `snapshot`. The first summary of an attached Session computes these projections over its whole in-memory log, and later summaries advance them incrementally; this computation runs inside one synchronous row, so `listWorkSliceMs` cannot split it. Client list rows and resident Sessions use the current `sessionListMetadata` projection to reject stale blank-session hints; recency is the later of the summary timestamp and the projected last user prompt. When SessionManager creates an instance before its list row arrives, it reconciles blankness with metadata already retained for that Session. An opened conversation is therefore not reused by New Session even when an older list response still marks it blank. diff --git a/packages/api/session-controller/README.zh.md b/packages/api/session-controller/README.zh.md index 1287e60744..1749a99c4a 100644 --- a/packages/api/session-controller/README.zh.md +++ b/packages/api/session-controller/README.zh.md @@ -43,7 +43,7 @@ Client journal 在发布 follow 快照、live entry 或历史页之前验证当 列表行在状态可用时携带 `formatStatus`,Client 无需请求其投影即可识别需要迁移的 Session。 -Host 仅在配置的工作时间片耗尽时,于完整条目之间让出事件循环;剩余工作较少时直接返回,不强制让出。每行及每次让出之后检查请求取消,取消时拒绝返回部分结果。每行同步计算;列表不承诺跨 Session 的统一快照。已经进入冷态队列的 Session 若在让出期间接入,仍返回缓存行:Client 对进行中请求的变更重放会纠正其可用性,带序号的投影会覆盖缓存提示。已接入 Session 的摘要通过[共享 Session 列表读取函数](../../session-query/session-query/README.zh.md#shared-list-metadata)读取是否为空和最后一次提示词的最近活动时间,其投影提示携带通过 `snapshot` 计算的每个摘要 key。已接入 Session 的首次摘要在其完整内存日志上计算这些投影,之后的摘要增量推进;这次计算在单行的同步工作内进行,`listWorkSliceMs` 无法切分它。 +Host 仅在配置的工作时间片耗尽时,于完整条目之间让出事件循环;剩余工作较少时直接返回,不强制让出。每行及每次让出之后检查请求取消,取消时拒绝返回部分结果。每行同步计算;列表不承诺跨 Session 的统一快照。已经进入冷态队列的 Session 若在让出期间接入,仍返回缓存行:Client 对进行中请求的变更重放会纠正其可用性,带序号的投影会覆盖缓存提示。已接入 Session 的摘要通过[`sessionQuery.getListMetadata`](../../session-query/session-query/README.zh.md#session-list-metadata)读取是否为空和最后一次提示词的最近活动时间,其投影提示携带通过 `snapshot` 计算的每个摘要 key。已接入 Session 的首次摘要在其完整内存日志上计算这些投影,之后的摘要增量推进;这次计算在单行的同步工作内进行,`listWorkSliceMs` 无法切分它。 Client 列表行和驻留 Session 使用当前 `sessionListMetadata` 投影纠正过期的空白会话提示;最近活动时间取摘要时间戳与投影中最后一次用户提示词时间的较晚值。当 SessionManager 在列表行到达前创建实例时,会使用已保留的该 Session 元数据对账空白状态。因此,即使旧列表响应仍将已有对话标为空白,新会话操作也不会复用已经打开过的对话。 diff --git a/packages/api/session-controller/src/list.ts b/packages/api/session-controller/src/list.ts index d2ff0d2a67..e49a59fcd5 100644 --- a/packages/api/session-controller/src/list.ts +++ b/packages/api/session-controller/src/list.ts @@ -8,7 +8,7 @@ import type { ImageAttachmentLimits } from '@deepseek-ai/dsh-attachment' import type { Session, SessionHeader, SessionId } from '@deepseek-ai/dsh-session' import type { ProjectionSnapshot } from '@deepseek-ai/dsh-session-projection' import type {} from '@deepseek-ai/dsh-session-projection-cache' -import { registerSessionListMetadata, SessionQueryError, type SessionRecord, type SessionSearchCursor } from '@deepseek-ai/dsh-session-query' +import { SessionQueryError, type SessionRecord, type SessionSearchCursor } from '@deepseek-ai/dsh-session-query' import { RemoteError } from '@deepseek-ai/dsh-typert-protocol' import { z } from 'zod' import { @@ -52,8 +52,6 @@ export function truncateUnicodeCodePoints(value: string, maximum: number): strin /** Owns list projection registration, bounded cold summaries, and authorized search. */ export class ApiSessionList { - private listMetadata!: (session: Session) => SessionListMetadata - /** * @param ctx - Host context carrying Session, query, persistence, and projection services. * @param workSliceMs - Resolved positive integral list-work budget in milliseconds. @@ -65,7 +63,6 @@ export class ApiSessionList { * @returns when all required registrations are ready. */ async initialize(): Promise { - this.listMetadata = await registerSessionListMetadata(this.ctx) await this.ctx.sessionProjections.register<'imageLimits', null>({ key: 'imageLimits', stateSchema: z.null(), @@ -82,17 +79,17 @@ export class ApiSessionList { /** * Build one current attached-Session summary. - * Blankness and recency come from the shared `sessionListMetadata` reader; projection + * Blankness and recency come from `sessionQuery.getListMetadata`; projection * hints carry every summary key computed through `snapshot`. The first call * for a Session computes these projections over its whole in-memory log, and - * later calls advance them incrementally. The handle read and the hint with + * later calls advance them incrementally. The metadata read and the hint with * the same key come from one cell; the metadata read does not depend on any * other unit's view. * @param session - attached Session to summarize. * @returns current list metadata and available projections. */ summaryFor(session: Session): SessionSummary { - const metadata = this.listMetadata(session) + const metadata = this.ctx.sessionQuery.getListMetadata(session) const projections = this.projectionsFor(session.header, session) return { sessionId: session.id, diff --git a/packages/api/session-controller/tests/agent.host.spec.ts b/packages/api/session-controller/tests/agent.host.spec.ts index aea96d5e04..9f73c9230f 100644 --- a/packages/api/session-controller/tests/agent.host.spec.ts +++ b/packages/api/session-controller/tests/agent.host.spec.ts @@ -35,7 +35,7 @@ async function harness(): Promise<{ ctx: Context; agents: ApiSessionAgentControl await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentRegistry) - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) await ctx.sessionProjections.register(agentPresetProjectionDefinition) ctx.provide('agentDefaultModel', { currentSelection: () => ({ provider: 'fixture', model: 'fixture-model' }), diff --git a/packages/api/session-controller/tests/commands-create-fork.host.spec.ts b/packages/api/session-controller/tests/commands-create-fork.host.spec.ts index eb2093ea18..68eee9071f 100644 --- a/packages/api/session-controller/tests/commands-create-fork.host.spec.ts +++ b/packages/api/session-controller/tests/commands-create-fork.host.spec.ts @@ -50,7 +50,7 @@ async function baseContext(): Promise { await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentRegistry) - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) ctx.provide('agentDefaultModel', { currentSelection: () => ({ provider: 'fixture', model: 'fixture-model' }), saveSelection: () => Promise.resolve(), diff --git a/packages/api/session-controller/tests/commands-queue-attachment.host.spec.ts b/packages/api/session-controller/tests/commands-queue-attachment.host.spec.ts index f575583063..74c9cf2f9b 100644 --- a/packages/api/session-controller/tests/commands-queue-attachment.host.spec.ts +++ b/packages/api/session-controller/tests/commands-queue-attachment.host.spec.ts @@ -42,7 +42,7 @@ async function commandHarness( await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentRegistry) await ctx.plugin(TypertRegistry) - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) await ctx.sessionProjections.register(subagentIdentityProjectionDefinition) const sessionId = SessionId('commands-session') const ancestor = Session.create(SessionId('ancestor')) diff --git a/packages/api/session-controller/tests/controller.host.spec.ts b/packages/api/session-controller/tests/controller.host.spec.ts index 664c4f9244..6822dc89e7 100644 --- a/packages/api/session-controller/tests/controller.host.spec.ts +++ b/packages/api/session-controller/tests/controller.host.spec.ts @@ -38,7 +38,7 @@ describe('SessionController facade', () => { const original = ctx.sessionProjections.register.bind(ctx.sessionProjections) let first = true vi.spyOn(ctx.sessionProjections, 'register').mockImplementation(async (...args: Parameters) => { - if (first) { + if (first && args[0].key === 'imageLimits') { first = false entered.resolve(undefined) await gate.promise diff --git a/packages/api/session-controller/tests/history-controller.host.spec.ts b/packages/api/session-controller/tests/history-controller.host.spec.ts index 1f71f48e5e..4a6925feb6 100644 --- a/packages/api/session-controller/tests/history-controller.host.spec.ts +++ b/packages/api/session-controller/tests/history-controller.host.spec.ts @@ -17,7 +17,7 @@ async function fixture() { const ctx = new Context() roots.push(ctx) await ctx.plugin(SessionStore) - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) const history = new HistoryController(ctx) const web = new WebController(ctx, history, (observation) => { observation[Symbol.dispose]() }) const session = ctx.sessions.create(SessionId('history-target'), { meta: { cwd: '/history-test' } }) diff --git a/packages/api/session-controller/tests/list-scheduling.host.spec.ts b/packages/api/session-controller/tests/list-scheduling.host.spec.ts index 0cba6939d7..3d5c326fd5 100644 --- a/packages/api/session-controller/tests/list-scheduling.host.spec.ts +++ b/packages/api/session-controller/tests/list-scheduling.host.spec.ts @@ -84,7 +84,8 @@ async function harness(rows: readonly Row[], summaryMs = 8, workSliceMs = 8) { return { header: session.header, live: row.phase === 'live', persisted: true } }) const listSessions = vi.fn(async (_signal?: AbortSignal) => records) - ctx.provide('sessionQuery', { listSessions } as never) + const getListMetadata = () => ({ blank: true, lastPromptAt: null }) + ctx.provide('sessionQuery', { listSessions, getListMetadata } as never) ctx.provide('sessionProjectionCache', { cachedSnapshot: (header: SessionRecord['header']) => { recordSummary('cold', header.id) diff --git a/packages/api/session-controller/tests/listeners.host.spec.ts b/packages/api/session-controller/tests/listeners.host.spec.ts index d8f97b9244..bf28c37402 100644 --- a/packages/api/session-controller/tests/listeners.host.spec.ts +++ b/packages/api/session-controller/tests/listeners.host.spec.ts @@ -24,7 +24,7 @@ async function fixture() { const ctx = new Context() roots.push(ctx) await ctx.plugin(SessionStore) - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) const session = ctx.sessions.create(SessionId('listener-target'), { meta: { cwd: '/listeners' } }) const abort = cancellation() const partial: Partial = { id: session.id, session } diff --git a/packages/api/session-controller/tests/session-fork.host.spec.ts b/packages/api/session-controller/tests/session-fork.host.spec.ts index 72b21aa31e..91ad497289 100644 --- a/packages/api/session-controller/tests/session-fork.host.spec.ts +++ b/packages/api/session-controller/tests/session-fork.host.spec.ts @@ -34,7 +34,7 @@ async function composed(workspaces: readonly Workspace[] = []): Promise await ctx.plugin(SystemPrompt, { personaPrefix: '' }) await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentRegistry) - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) ctx.provide('workspaceRegistry', { list: () => workspaces, archivedSessionIds: [] } as never) ctx.agents.setFactory({ createAgent: async (ownerCtx: Context, options: CreateAgentOptions): Promise => { diff --git a/packages/api/session-controller/tests/session-history-journal.host.spec.ts b/packages/api/session-controller/tests/session-history-journal.host.spec.ts index 328e797677..9f55fb0e16 100644 --- a/packages/api/session-controller/tests/session-history-journal.host.spec.ts +++ b/packages/api/session-controller/tests/session-history-journal.host.spec.ts @@ -54,7 +54,7 @@ async function harness(): Promise<{ ctx: Context }> { await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentRegistry) - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) return { ctx } } diff --git a/packages/api/session-controller/tests/session-projections.host.spec.ts b/packages/api/session-controller/tests/session-projections.host.spec.ts index aa4ae6a702..a57622e3a5 100644 --- a/packages/api/session-controller/tests/session-projections.host.spec.ts +++ b/packages/api/session-controller/tests/session-projections.host.spec.ts @@ -540,7 +540,7 @@ describe('session.list projections column', () => { const row = response.value.items.find(item => item.sessionId === session.id) expect(row?.projections?.kind).toBe('sequenced') expect(Object.keys(row?.projections?.values ?? {})).toEqual([...ctx.sessionProjections.summaryKeys()]) - expect(Object.keys(row?.projections?.values ?? {})).toEqual(['conversationContinuation', 'sessionListMetadata']) + expect(Object.keys(row?.projections?.values ?? {})).toEqual(['sessionListMetadata', 'conversationContinuation']) expect(row?.projections?.values.conversationContinuation).toBeNull() }) @@ -796,8 +796,8 @@ describe('Session control projection frames', () => { { type: 'projection', sessionId: session.id, seq: 0, changes: [ { key: 'test/last-user', val: { text: 'm0' } }, - { key: 'conversationContinuation', val: null }, { key: 'sessionListMetadata', val: { blank: true, lastPromptAt: 100 } }, + { key: 'conversationContinuation', val: null }, ], }, { @@ -837,8 +837,8 @@ describe('Session control projection frames', () => { value: { type: 'projection', seq: 0, changes: [ { key: 'test/last-user', val: { text: 'm0' } }, - { key: 'conversationContinuation', val: null }, { key: 'sessionListMetadata', val: { blank: true, lastPromptAt: 100 } }, + { key: 'conversationContinuation', val: null }, ], }, }) diff --git a/packages/api/session-controller/tests/session-search.host.spec.ts b/packages/api/session-controller/tests/session-search.host.spec.ts index 9b14011fbe..2d7c944867 100644 --- a/packages/api/session-controller/tests/session-search.host.spec.ts +++ b/packages/api/session-controller/tests/session-search.host.spec.ts @@ -5,7 +5,7 @@ */ import { describe, expect, it, vi } from 'vitest' -import { Context } from '@deepseek-ai/cordis' +import { Context, Service } from '@deepseek-ai/cordis' import AgentRegistry from '@deepseek-ai/dsh-agent' import { createUserMessage } from '@deepseek-ai/dsh-llm' import SessionStore, { SESSION_FORMAT_VERSION, SessionSeq } from '@deepseek-ai/dsh-session' @@ -73,6 +73,10 @@ class SearchSessionQuery extends SessionQueryEngine { super(ctx) } + initialize(): Promise { + return this[Service.init]() + } + override searchSessions( ...args: Parameters ): ReturnType { @@ -89,8 +93,8 @@ function installSearchQuery( searchSessions: ( ...args: Parameters ) => Promise, -): void { - new SearchSessionQuery(ctx, searchSessions) +): Promise { + return new SearchSessionQuery(ctx, searchSessions).initialize() } describe('session.search', () => { @@ -152,7 +156,7 @@ describe('session.search', () => { }, ], })) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const remote = await createSessionTestRemote(ctx, defaults) const signal = new AbortController().signal @@ -188,7 +192,7 @@ describe('session.search', () => { const ctx = await baseContext() ctx.sessions.create(sid('visible'), { meta: header('visible') }) const searchSessions = vi.fn() - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const remote = await createSessionTestRemote(ctx, defaults) for (const query of ['', ' ', 'contains\0nul', 'x'.repeat(501)]) { @@ -202,7 +206,7 @@ describe('session.search', () => { it('returns an empty page without invoking the index when no session is visible', async () => { const ctx = await baseContext() const searchSessions = vi.fn() - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const remote = await createSessionTestRemote(ctx, defaults) const response = await remote.search( @@ -228,7 +232,7 @@ describe('session.search', () => { const base = hit('visible', index) return { ...base, bestMatch: { ...base.bestMatch, ...bestMatch } } } - installSearchQuery(ctx, () => Promise.resolve({ + await installSearchQuery(ctx, () => Promise.resolve({ items: [ withBestMatch(0, { sessionId: sid('hidden') }), withBestMatch(1, { surface: 'shadowed' }), @@ -263,7 +267,7 @@ describe('session.search', () => { nextCursor: 'page-2', }) .mockResolvedValueOnce({ items: items.slice(19) }) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('match'), new AbortController().signal, @@ -303,7 +307,7 @@ describe('session.search', () => { ...end < items.length ? { nextCursor: `offset-${end}` } : {}, }) }) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('adaptive-page-limit'), @@ -346,7 +350,7 @@ describe('session.search', () => { nextCursor: `page-${searchSessions.mock.calls.length}`, }) }) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('endless-pages'), @@ -411,7 +415,7 @@ describe('session.search', () => { return Promise.reject(new Error('unexpected provider call')) } }) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('stale-restart'), @@ -450,7 +454,7 @@ describe('session.search', () => { nextCursor: `cursor-${searchSessions.mock.calls.length}`, }) }) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('stale-churn'), @@ -479,7 +483,7 @@ describe('session.search', () => { controller.abort() return Promise.reject(stale) }) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('abort-stale'), @@ -500,7 +504,7 @@ describe('session.search', () => { 'provider generation changed before paging', 'SESSION_QUERY_STALE_CURSOR', ))) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('first-page-stale'), @@ -524,7 +528,7 @@ describe('session.search', () => { 'continuation limit is invalid', 'SESSION_QUERY_INVALID_LIMIT', )) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('continuation-invalid-limit'), @@ -551,7 +555,7 @@ describe('session.search', () => { 'SESSION_QUERY_INVALID_LIMIT', ), )) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('minimum-page-limit'), @@ -577,7 +581,7 @@ describe('session.search', () => { 'SESSION_QUERY_INVALID_LIMIT', )) }) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('abort-invalid-limit'), @@ -596,7 +600,7 @@ describe('session.search', () => { ctx.sessions.create(sid('visible'), { meta: header('visible') }) const oversized = Array.from({ length: 21 }, (_, index) => hit(`oversized-${index}`)) const searchSessions = vi.fn(() => Promise.resolve({ items: oversized })) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('oversized-page'), @@ -622,7 +626,7 @@ describe('session.search', () => { } return Promise.resolve({ items: oversized }) }) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('adapted-oversized-page'), @@ -648,7 +652,7 @@ describe('session.search', () => { snippet: `${expected}${'y'.repeat(10_000)}`, }, } - installSearchQuery(ctx, () => Promise.resolve({ items: [overlong] })) + await installSearchQuery(ctx, () => Promise.resolve({ items: [overlong] })) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('bounded-snippet'), @@ -670,7 +674,7 @@ describe('session.search', () => { const searchSessions = vi.fn() .mockResolvedValueOnce({ items: [], nextCursor: 'repeated' }) .mockResolvedValueOnce({ items: [], nextCursor: 'repeated' }) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('repeated-cursor'), @@ -693,7 +697,7 @@ describe('session.search', () => { const searchSessions = vi.fn() .mockResolvedValueOnce({ items: items.slice(0, 20), nextCursor: 'repeated' }) .mockResolvedValueOnce({ items: items.slice(20), nextCursor: 'repeated' }) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('repeated-lookahead-cursor'), @@ -720,7 +724,7 @@ describe('session.search', () => { .mockResolvedValueOnce({ items: items.slice(0, 20), nextCursor: 'page-2' }) .mockResolvedValueOnce({ items: items.slice(0, 20), nextCursor: 'page-3' }) .mockResolvedValueOnce({ items: items.slice(20) }) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('duplicate-pages'), @@ -748,7 +752,7 @@ describe('session.search', () => { controller.abort() return Promise.resolve({ items: [] }) }) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('cancel-continuation'), @@ -777,7 +781,7 @@ describe('session.search', () => { const searchSessions = vi.fn((_request: SessionSearchRequest) => Promise.resolve({ items: [hit('cold-32750')], })) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('large corpus'), @@ -813,7 +817,7 @@ describe('session.search', () => { }, }) as never) const searchSessions = vi.fn() - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('cancel-during-visibility'), @@ -840,7 +844,7 @@ describe('session.search', () => { inspect, }) as never) const searchSessions = vi.fn(() => Promise.resolve({ items: [] })) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const response = await (await createSessionTestRemote(ctx, defaults)).search( request('header-only-visibility'), @@ -876,7 +880,7 @@ describe('session.search', () => { const searchSessions = vi.fn() .mockRejectedValueOnce(aborted) .mockRejectedValueOnce(new Error('database unavailable')) - installSearchQuery(ctx, searchSessions) + await installSearchQuery(ctx, searchSessions) const remote = await createSessionTestRemote(ctx, defaults) const cancelled = await remote.search( diff --git a/packages/api/session-controller/tests/state-controller.host.spec.ts b/packages/api/session-controller/tests/state-controller.host.spec.ts index 5fc74006ff..5b634aaa88 100644 --- a/packages/api/session-controller/tests/state-controller.host.spec.ts +++ b/packages/api/session-controller/tests/state-controller.host.spec.ts @@ -47,7 +47,7 @@ async function fixture() { const ctx = new Context() roots.push(ctx) await ctx.plugin(SessionStore) - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) const session = ctx.sessions.create(SessionId('state-target'), { meta: { cwd: '/state-test' } }) let agent: Agent | undefined const get = vi.fn(() => agent) diff --git a/packages/api/session-controller/tests/subagent-catalog.host.spec.ts b/packages/api/session-controller/tests/subagent-catalog.host.spec.ts index 0f834506d9..98d523ae0b 100644 --- a/packages/api/session-controller/tests/subagent-catalog.host.spec.ts +++ b/packages/api/session-controller/tests/subagent-catalog.host.spec.ts @@ -58,7 +58,7 @@ async function bench() { sessionId === PARENT ? { meta: header, events } : undefined, ), }) as never) - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) provideWorkingDirectoryFixture(ctx) await ctx.plugin(SubagentRuntime) const controller = await createSessionTestController(ctx, defaults) @@ -200,7 +200,7 @@ describe('SessionController subagent catalog', () => { await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentRegistry) - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) const controller = await createSessionTestController(ctx, defaults) const session = ctx.sessions.create(PARENT, { meta: { cwd: '/workspace' } }) const expected = ctx.sessionProjections.snapshot(session) diff --git a/packages/api/session-controller/tests/test-remote.ts b/packages/api/session-controller/tests/test-remote.ts index 04ed6788cf..cb6e5ef89f 100644 --- a/packages/api/session-controller/tests/test-remote.ts +++ b/packages/api/session-controller/tests/test-remote.ts @@ -221,6 +221,10 @@ export function testSessionPersistence( /** Concrete point-read query used by Session Controller tests that do not exercise search. */ class TestSessionQuery extends SessionQueryEngine { + initialize(): Promise { + return this[Service.init]() + } + override searchSessions(): Promise { return Promise.reject(new Error('session search is not configured in this test')) } @@ -230,10 +234,14 @@ class TestSessionQuery extends SessionQueryEngine { } } -/** Install the required projection and point-query services for direct controller tests. */ -export function installSessionReadTestServices(ctx: Context): void { +/** + * Install the required projection and point-query services for direct controller tests. + * @param ctx - test context that receives missing services. + * @returns when the installed query service has registered its projections. + */ +export async function installSessionReadTestServices(ctx: Context): Promise { if (ctx.get('sessionProjections') === undefined) new SessionProjectionRegistry(ctx) - if (ctx.get('sessionQuery') === undefined) new TestSessionQuery(ctx) + if (ctx.get('sessionQuery') === undefined) await new TestSessionQuery(ctx).initialize() } async function installControllers( @@ -294,7 +302,7 @@ async function installControllers( retirePrompt: () => {}, } as never) } - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) if (ctx.get('remoteAccess') === undefined) new RemoteAccessService(ctx) const cwd = vi.spyOn(process, 'cwd').mockReturnValue(defaults.cwd) class TestController extends SessionController { diff --git a/packages/api/session-controller/tests/transport.host.spec.ts b/packages/api/session-controller/tests/transport.host.spec.ts index 8a3df2ae43..461972eb8d 100644 --- a/packages/api/session-controller/tests/transport.host.spec.ts +++ b/packages/api/session-controller/tests/transport.host.spec.ts @@ -86,7 +86,6 @@ function controllers( web: WebController } { roots.add(ctx.root) - installSessionReadTestServices(ctx) const history = new HistoryController(ctx) return { history, web: new WebController(ctx, history, promote) } } @@ -94,7 +93,7 @@ function controllers( async function setup(): Promise<{ ctx: Context; history: HistoryController; web: WebController }> { const ctx = new Context() await ctx.plugin(SessionStore) - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) await ctx.sessionProjections.register(subagentIdentityProjectionDefinition) return { ctx, ...controllers(ctx) } } @@ -130,7 +129,7 @@ describe('Session history and Web follow', () => { it('ends active followers when the owning Controller unloads', async () => { const ctx = new Context() await ctx.plugin(SessionStore) - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) let web!: WebController const owner = ctx.plugin(Object.assign( (inner: Context) => { @@ -273,7 +272,7 @@ describe('Session history and Web follow', () => { it('bridges the unpublished end-seed boundary when a cold source attaches', async () => { const ctx = new Context() await ctx.plugin(SessionStore) - installSessionReadTestServices(ctx) + await installSessionReadTestServices(ctx) let web!: WebController let agentCtx!: Context await ctx.plugin(Object.assign( diff --git a/packages/context/session-reference/tests/session-reference.spec.ts b/packages/context/session-reference/tests/session-reference.spec.ts index e4a6885f8b..cae6553148 100644 --- a/packages/context/session-reference/tests/session-reference.spec.ts +++ b/packages/context/session-reference/tests/session-reference.spec.ts @@ -491,6 +491,7 @@ describe('model-relative reference budgets', () => { const ctx = new Context() contexts.push(ctx) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(TestSessionQueryEngine) const resolverFiber = ctx.plugin(SessionReferenceResolver, config) await resolverFiber @@ -810,6 +811,7 @@ describe('session reference discovery and preparation', () => { it('labels every session by id when no projection face is composed', async () => { const ctx = new Context() await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(TestSessionQueryEngine) await ctx.plugin(SessionReferenceResolver) const target = ctx.sessions.create(SessionId('target'), { meta: { cwd: '/same' } }) @@ -1304,18 +1306,21 @@ describe('session reference discovery and preparation', () => { it('rejects direct invalid configuration before service publication', async () => { const ctx = new Context() await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(TestSessionQueryEngine) expect(() => new SessionReferenceResolver(ctx, { maxReferences: 0 })) .toThrow(expectCode('SESSION_REFERENCE_INVALID_CONFIG')) const oversizedCtx = new Context() await oversizedCtx.plugin(SessionStore) + await oversizedCtx.plugin(SessionProjectionRegistry) await oversizedCtx.plugin(TestSessionQueryEngine) expect(() => new SessionReferenceResolver(oversizedCtx, { maxReferences: 4 })) .toThrow(expectCode('SESSION_REFERENCE_INVALID_CONFIG')) const defaultCtx = new Context() await defaultCtx.plugin(SessionStore) + await defaultCtx.plugin(SessionProjectionRegistry) await defaultCtx.plugin(TestSessionQueryEngine) expect(() => new SessionReferenceResolver(defaultCtx)).not.toThrow() }) diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 6d21ec6d7b..94e821f2c3 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -3280,6 +3280,12 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ summary: 'Unified live-preferred session query service.', description: 'Unified live-preferred session query service.\n\nExact reads, filters, and traces are backend-independent concrete behavior. A backend implements full-text observation, reconciliation, ranking, cursor generations, and query execution on the same `ctx.sessionQuery` service.', methods: [ + { + signature: 'getListMetadata(session: Session): SessionListMetadata', + description: 'Read the metadata that summarizes one live or prepared Session in a Session list.', + parameters: [{ name: 'session', description: 'live or prepared Session to summarize.' }], + returns: 'whether the Session has no turn, and its latest human-authored prompt time.', + }, { signature: 'observeSession( sessionId: SessionId, options: SessionObservationOptions = {}, ): Promise', description: 'Observe one exact live or prepared Session without a persistence listing preflight.', @@ -9100,6 +9106,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'SessionLineageTrace', declaration: 'export type SessionLineageTrace = {\n target: SessionRecord;\n ancestors: SessionRecord[];\n descendants: SessionLineageNode[];\n} & ({\n complete: true;\n root: SessionRecord;\n} | {\n complete: false;\n unresolvedParentId: SessionId;\n});', }, + { + name: 'SessionListMetadata', + declaration: 'export interface SessionListMetadata {\n readonly blank: boolean;\n readonly lastPromptAt: number | null;\n}', + }, { name: 'SessionListRequest', declaration: 'export interface SessionListRequest {\n readonly cursor?: string;\n}', @@ -10774,7 +10784,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'Workspace', - declaration: 'export interface Workspace {\n readonly id: WorkspaceId;\n readonly path: string;\n readonly title: string;\n readonly createdAt: string;\n readonly updatedAt: string;\n readonly sessionIds: readonly SessionId[];\n readonly sessionHeaders: readonly SessionHeader[];\n setTitle(title: string): Promise;\n attachSession(sessionId: SessionId): Promise;\n insertSessionBefore(sessionId: SessionId, beforeSessionId?: SessionId): Promise;\n detachSession(sessionId: SessionId): Promise;\n status(): Promise<\'ok\' | \'missing-dir\'>;\n}', + declaration: 'export interface Workspace {\n readonly id: WorkspaceId;\n readonly path: string;\n readonly title: string;\n readonly createdAt: string;\n readonly updatedAt: string;\n readonly sessionIds: readonly SessionId[];\n getSessionHeaders(): readonly SessionHeader[];\n setTitle(title: string): Promise;\n attachSession(sessionId: SessionId): Promise;\n insertSessionBefore(sessionId: SessionId, beforeSessionId?: SessionId): Promise;\n detachSession(sessionId: SessionId): Promise;\n status(): Promise<\'ok\' | \'missing-dir\'>;\n}', }, { name: 'WorkspaceArchiveSessionRequest', diff --git a/packages/session-query/session-query-sqlite/src/index.ts b/packages/session-query/session-query-sqlite/src/index.ts index 7c95afa28d..48494ebc1d 100644 --- a/packages/session-query/session-query-sqlite/src/index.ts +++ b/packages/session-query/session-query-sqlite/src/index.ts @@ -201,7 +201,7 @@ interface CursorPayload { /** Concrete SQLite owner of the combined `ctx.sessionQuery` service. */ export class SqliteSessionQueryEngine extends SessionQueryEngine { - static override inject = ['sessions'] + static override inject = ['sessions', 'sessionProjections'] static Config: z = z.object({ path: z.string().required(), @@ -261,7 +261,8 @@ export class SqliteSessionQueryEngine extends SessionQueryEngine { } /** Open eagerly only when activation owns the configured readiness boundary. */ - protected async [Service.init](): Promise { + protected override async [Service.init](): Promise { + await super[Service.init]() if (this.config.openAt === 'startup') await this._ensureReady(undefined) } diff --git a/packages/session-query/session-query/README.i18n.yaml b/packages/session-query/session-query/README.i18n.yaml index 8e8ae5bcfd..48d79d6d6a 100644 --- a/packages/session-query/session-query/README.i18n.yaml +++ b/packages/session-query/session-query/README.i18n.yaml @@ -18,8 +18,8 @@ en: dfc90afac9ef47be zh: 0a5aa60a34f24e61 /deepseek-ai-dsh-session-query/use-this-package/what-you-can-do: - en: 608cd6d4c5cf2c35 - zh: 23d3c5a7374b5283 + en: f0baf912893e2edd + zh: b71f2d1df02a8d2a /deepseek-ai-dsh-session-query/use-this-package/filters: en: 1b95403461947ca1 zh: cffa21b03df9f0ad @@ -36,14 +36,14 @@ en: b34fb0d209192ff4 zh: 455bdb024d04f16a /deepseek-ai-dsh-session-query/understand-the-implementation/source-map: - en: 58964ca2cde96c32 - zh: 9699c328cefc9f09 + en: fa54846e5df84028 + zh: de31ff744819413e /deepseek-ai-dsh-session-query/understand-the-implementation/corpus-resolution: - en: 4dde9107d05de6ee - zh: 8c775eb7630e659a -/deepseek-ai-dsh-session-query/understand-the-implementation/shared-list-metadata: - en: 30d9af561283c382 - zh: bc8ceabe718239bf + en: 3254f25af5734621 + zh: 3f8e8e0bbb83095e +/deepseek-ai-dsh-session-query/understand-the-implementation/session-list-metadata: + en: a46a831dce49d0ba + zh: 840d4982f059b41b /deepseek-ai-dsh-session-query/understand-the-implementation/observation-cache: en: 16d4a29af5b2ac07 zh: 7ec4a91f97697d2e diff --git a/packages/session-query/session-query/README.md b/packages/session-query/session-query/README.md index af901c891d..6321321296 100644 --- a/packages/session-query/session-query/README.md +++ b/packages/session-query/session-query/README.md @@ -32,6 +32,7 @@ Use `ctx.sessionQuery` from application code when you need to read or search ses | Operation | What you get | |---|---| | `listSessions()` | Every logical session, newest first, with `live` and `persisted` availability flags and optional `formatStatus` | +| `getListMetadata(session)` | Whether a live or prepared Session has no turn, and its latest human-authored prompt time | | `readSession(id)` | The complete replay-validated raw event log, without making the session live | | `filterSessions(filters)` | Sessions matching ANDed metadata and availability predicates | | `filterEvents(id, filters)` | Semantic event documents matching metadata and literal-text predicates | @@ -92,7 +93,7 @@ The decision history lives in the [unified service decision](../../../.agents/no | [`src/index.ts`](src/index.ts) | Service definition: the abstract `SessionQueryEngine`, concrete reads, config validation | | [`src/corpus.ts`](src/corpus.ts) | Live-preferred corpus resolution, optional persistence binding, batch projections | | [`src/observation.ts`](src/observation.ts) | Live-preferred point observations with a bounded revision-keyed prepared-Session cache | -| [`src/list-metadata.ts`](src/list-metadata.ts) | Shared blankness and human-prompt recency projection registration | +| [`src/list-metadata.ts`](src/list-metadata.ts) | Session-list blankness and human-prompt recency projection definition | | [`src/cold-read.ts`](src/cold-read.ts) | Handle-based cold log read with in-memory interrupted-turn closers | | [`src/types.ts`](src/types.ts) | Public records, filters, requests, and page types | | [`src/config.ts`](src/config.ts) | Inherited config and the closed `SessionQueryError` taxonomy | @@ -106,10 +107,10 @@ The decision history lives in the [unified service decision](../../../.agents/no `SessionCorpus` binds optional `ctx.sessionPersistence` through a fiber and resolves each read live-first: a known live target is snapshotted without consulting persistence; otherwise the session is listed, read completely through a short-lived read handle, and re-checked for a live attachment before cloning. A cold log whose writer crashed mid-turn is balanced in memory with `interruptedTurnClosers` — persistence is never mutated by a read. Header compatibility is asserted between listed and loaded observations. Batch title reads run one metadata listing and bounded-concurrency reads, isolating per-session failures while cancellation rejects the whole batch. - -### Shared list metadata + +### Session-list metadata -`registerSessionListMetadata(ctx)` acquires the shared projection for Session blankness and the latest human-authored prompt time, and returns a synchronous reader for prepared live Sessions. The Session API and optional [listing tools](../tool-session-list/README.md) share one projection unit; disposing a consumer releases only its own reference. Registration requires `sessionProjections`, independently of the query service's header-only `listSessions()` operation. +The service registers the `sessionListMetadata` projection for Session blankness and the latest human-authored prompt time when it starts, and its disposal releases that registration; it therefore requires `sessionProjections`. `getListMetadata(session)` reads the projection synchronously for a live or prepared Session. The Session API and optional [listing tools](../tool-session-list/README.md) read it through `ctx.sessionQuery`. ### Observation cache diff --git a/packages/session-query/session-query/README.zh.md b/packages/session-query/session-query/README.zh.md index c65fc09154..550c62d349 100644 --- a/packages/session-query/session-query/README.zh.md +++ b/packages/session-query/session-query/README.zh.md @@ -32,6 +32,7 @@ kind: "package-reference" | 操作 | 你得到什么 | |---|---| | `listSessions()` | 每个逻辑会话,最新的在前,带 `live` 与 `persisted` 可用性标志及可选 `formatStatus` | +| `getListMetadata(session)` | 实时或已准备的 Session 是否还没有 turn,及其最近一条人工提示词的时间 | | `readSession(id)` | 经过回放校验的完整原始事件日志,且不会让该会话变为实时 | | `filterSessions(filters)` | 匹配 AND 连接的元数据与可用性谓词的会话 | | `filterEvents(id, filters)` | 匹配元数据与字面文本谓词的语义事件文档 | @@ -92,7 +93,7 @@ kind: "package-reference" | [`src/index.ts`](src/index.ts) | 服务定义:抽象 `SessionQueryEngine`、具体读取、配置校验 | | [`src/corpus.ts`](src/corpus.ts) | 实时优先的语料库解析、可选持久化绑定、批量投影 | | [`src/observation.ts`](src/observation.ts) | 实时优先的定点观察,带按修订键控的有界 prepared-Session 缓存 | -| [`src/list-metadata.ts`](src/list-metadata.ts) | 共享的空白状态与人工提示词活动时间投影注册 | +| [`src/list-metadata.ts`](src/list-metadata.ts) | Session 列表空白状态与人工提示词活动时间投影定义 | | [`src/cold-read.ts`](src/cold-read.ts) | 基于句柄的冷日志读取,附内存中的中断轮次闭合事件 | | [`src/types.ts`](src/types.ts) | 公共记录、过滤器、请求与分页类型 | | [`src/config.ts`](src/config.ts) | 继承配置与封闭的 `SessionQueryError` 分类体系 | @@ -106,10 +107,10 @@ kind: "package-reference" `SessionCorpus` 通过 fiber 绑定可选的 `ctx.sessionPersistence`,并实时优先解析每次读取:已知实时目标直接快照,不查询持久化;否则先列出会话,再通过短生命周期的读取句柄完整读出日志,并在克隆前重新检查是否出现实时挂载。写入者在轮次中途崩溃的冷日志用 `interruptedTurnClosers` 在内存中补齐——读取从不修改持久化。列表与加载观察之间会断言 header 兼容性。批量标题读取执行一次元数据列表与有界并发读取,把逐会话失败隔离,而取消会拒绝整个批次。 - -### 共享列表元数据 + +### Session 列表元数据 -`registerSessionListMetadata(ctx)` 获取 Session 空白状态与最近人工提示词时间的共享投影,并返回准备就绪的实时 Session 的同步读取函数。Session API 与可选的[列表工具](../tool-session-list/README.zh.md)共享同一个投影单元;释放消费方时只移除它自己的引用。注册需要 `sessionProjections`,独立于查询服务仅读取 header 的 `listSessions()` 操作。 +服务启动时注册记录 Session 空白状态与最近人工提示词时间的 `sessionListMetadata` 投影,释放服务时移除该注册;因此服务依赖 `sessionProjections`。`getListMetadata(session)` 同步读取实时或已准备 Session 的该投影。Session API 与可选的[列表工具](../tool-session-list/README.zh.md)通过 `ctx.sessionQuery` 读取。 ### 观察缓存 diff --git a/packages/session-query/session-query/package.json b/packages/session-query/session-query/package.json index 0bf1278c42..5d3340a20e 100644 --- a/packages/session-query/session-query/package.json +++ b/packages/session-query/session-query/package.json @@ -49,9 +49,6 @@ "@deepseek-ai/dsh-session-persistence": { "optional": true }, - "@deepseek-ai/dsh-session-projection": { - "optional": true - }, "@deepseek-ai/dsh-session-projection-cache": { "optional": true } diff --git a/packages/session-query/session-query/src/index.ts b/packages/session-query/session-query/src/index.ts index 62dcbcc337..21d924f971 100644 --- a/packages/session-query/session-query/src/index.ts +++ b/packages/session-query/session-query/src/index.ts @@ -13,6 +13,7 @@ import { type SessionId, type SessionSeq as SessionSeqType, } from '@deepseek-ai/dsh-session' +import type { ProjectionHandle } from '@deepseek-ai/dsh-session-projection' import { foldSessionTitle } from '@deepseek-ai/dsh-session-title' import type { SessionTitleSnapshot } from '@deepseek-ai/dsh-session-title' import type { @@ -32,6 +33,7 @@ import type { SessionSearchExecContext, SessionSearchHit, SessionSearchPage, + SessionListMetadata, SessionSearchRequest, SessionSurfaceSnapshot, SessionTitleObservation, @@ -45,6 +47,7 @@ import { type Config, } from './config.ts' import { SessionCorpus } from './corpus.ts' +import { sessionListMetadataDefinition } from './list-metadata.ts' import { SessionObservationReader, type SessionObservation, @@ -60,7 +63,6 @@ import { import * as tracing from './tracing.ts' export type * from './types.ts' -export { registerSessionListMetadata } from './list-metadata.ts' export { SessionSearchCursor } from './cursor.ts' export type { Config, SessionQueryErrorCode } from './config.ts' export { @@ -97,9 +99,10 @@ declare module '@deepseek-ai/cordis' { * generations, and query execution on the same `ctx.sessionQuery` service. */ export abstract class SessionQueryEngine extends Service { - static inject = ['sessions'] + static inject = ['sessions', 'sessionProjections'] private readonly _readWindowMax: number + private _listMetadata!: ProjectionHandle private readonly _corpus: SessionCorpus private readonly _observations: SessionObservationReader @@ -132,6 +135,20 @@ export abstract class SessionQueryEngine extends Service { this._observations = new SessionObservationReader(ctx, preparedSessionCacheSize) } + /** Register the Session-list metadata projection for this service's lifetime. */ + protected async [Service.init](): Promise { + this._listMetadata = await this.ctx.sessionProjections.register(sessionListMetadataDefinition) + } + + /** + * Read the metadata that summarizes one live or prepared Session in a Session list. + * @param session - live or prepared Session to summarize. + * @returns whether the Session has no turn, and its latest human-authored prompt time. + */ + getListMetadata(session: Session): SessionListMetadata { + return this._listMetadata.stateOf(session) + } + /** * Observe one exact live or prepared Session without a persistence listing preflight. * @param sessionId - logical Session identity. diff --git a/packages/session-query/session-query/src/list-metadata.ts b/packages/session-query/session-query/src/list-metadata.ts index 46d77244fe..2a4c3fce71 100644 --- a/packages/session-query/session-query/src/list-metadata.ts +++ b/packages/session-query/session-query/src/list-metadata.ts @@ -1,7 +1,6 @@ -/** Shared Session-list projection ownership for API and model-tool readers. */ +/** Session-list metadata projection definition registered by `SessionQueryEngine`. */ -import type { Context } from '@deepseek-ai/cordis' -import type { Session, SessionEvent } from '@deepseek-ai/dsh-session' +import type { SessionEvent } from '@deepseek-ai/dsh-session' import type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection' import { z } from 'zod' import type { SessionListMetadata } from './types.ts' @@ -25,7 +24,8 @@ function applySessionListMetadata( : { blank, lastPromptAt } } -const sessionListMetadataDefinition = { +/** Blankness and latest human-prompt time folded per Session; persisted at state version 1. */ +export const sessionListMetadataDefinition = { key: 'sessionListMetadata', stateSchema: sessionListMetadataSchema, init: () => ({ blank: true, lastPromptAt: null }), @@ -33,16 +33,3 @@ const sessionListMetadataDefinition = { wire: { viewSchema: sessionListMetadataSchema, view: state => state }, stateVersion: 1, } satisfies ProjectionDefinition<'sessionListMetadata', SessionListMetadata> - -/** - * Acquire the shared Session-list unit on the caller's fiber. - * Concurrent callers share one projection; disposal releases only the caller's reference. - * @param ctx - owner context with the required projection registry. - * @returns a synchronous domain reader ready for prepared live Sessions. - */ -export async function registerSessionListMetadata( - ctx: Context, -): Promise<(session: Session) => SessionListMetadata> { - const handle = await ctx.sessionProjections.register(sessionListMetadataDefinition) - return session => handle.stateOf(session) -} diff --git a/packages/session-query/session-query/tests/list-metadata.spec.ts b/packages/session-query/session-query/tests/list-metadata.spec.ts index 96fd8bf536..14b75460d9 100644 --- a/packages/session-query/session-query/tests/list-metadata.spec.ts +++ b/packages/session-query/session-query/tests/list-metadata.spec.ts @@ -1,12 +1,12 @@ -/** Shared list metadata keeps its values and lifetime across independent consumers. */ +/** Session-list metadata is registered and read through the query service lifecycle. */ import { Context } from '@deepseek-ai/cordis' import { createUserMessage } from '@deepseek-ai/dsh-llm' import SessionStore from '@deepseek-ai/dsh-session' import type { Session } from '@deepseek-ai/dsh-session' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' -import { describe, expect, it, onTestFinished, vi } from 'vitest' -import { registerSessionListMetadata } from '../src/list-metadata.ts' +import { describe, expect, it, onTestFinished } from 'vitest' +import { TestSessionQueryEngine } from './test-service.ts' async function setup() { const ctx = new Context() @@ -23,10 +23,11 @@ function prompt(session: Session) { }), { surfaceOp: 'append' }) } -describe('shared Session-list metadata', () => { +describe('Session-list metadata', () => { it('tracks human prompts and turns while preserving unchanged state references', async () => { const ctx = await setup() - const read = await registerSessionListMetadata(ctx) + await ctx.plugin(TestSessionQueryEngine) + const read = (session: Session) => ctx.sessionQuery.getListMetadata(session) const session = ctx.sessions.create() const initial = read(session) expect(initial).toEqual({ blank: true, lastPromptAt: null }) @@ -51,34 +52,24 @@ describe('shared Session-list metadata', () => { expect(ctx.sessionProjections.checkpoint(session).sessionListMetadata?.ver).toBe(1) }) - it('shares one cell and notification across owners until the last owner unloads', async () => { + it('releases the projection registration when the query service is disposed', async () => { const ctx = await setup() - const first = await ctx.plugin(Object.assign(function firstOwner() {}, { inject: ['sessionProjections'] })) - const second = await ctx.plugin(Object.assign(function secondOwner() {}, { inject: ['sessionProjections'] })) - const firstRead = await registerSessionListMetadata(first.ctx) - const secondRead = await registerSessionListMetadata(second.ctx) + const fiber = await ctx.plugin(TestSessionQueryEngine) const session = ctx.sessions.create() - expect(firstRead(session)).toBe(secondRead(session)) - const changed = vi.fn() - ctx.sessionProjections.onChanged(changed) session.append('turn/start', { turn: 1 }) - expect(changed).toHaveBeenCalledOnce() - expect(firstRead(session)).toBe(secondRead(session)) + expect(ctx.sessionProjections.snapshot(session).values.sessionListMetadata) + .toEqual({ blank: false, lastPromptAt: null }) - await first.dispose() - const event = prompt(session) - expect(secondRead(session)).toEqual({ blank: false, lastPromptAt: event.time }) - expect(ctx.sessionProjections.snapshot(session).values.sessionListMetadata).toEqual(secondRead(session)) - await second.dispose() + await fiber.dispose() expect(ctx.sessionProjections.snapshot(session).values).not.toHaveProperty('sessionListMetadata') }) - it('folds existing live history when the first consumer registers', async () => { + it('folds existing live history when the query service starts', async () => { const ctx = await setup() const session = ctx.sessions.create() session.append('turn/start', { turn: 1 }) const event = prompt(session) - const read = await registerSessionListMetadata(ctx) - expect(read(session)).toEqual({ blank: false, lastPromptAt: event.time }) + await ctx.plugin(TestSessionQueryEngine) + expect(ctx.sessionQuery.getListMetadata(session)).toEqual({ blank: false, lastPromptAt: event.time }) }) }) diff --git a/packages/session-query/tool-session-list/README.i18n.yaml b/packages/session-query/tool-session-list/README.i18n.yaml index 362ea0c6c0..d5264c53d9 100644 --- a/packages/session-query/tool-session-list/README.i18n.yaml +++ b/packages/session-query/tool-session-list/README.i18n.yaml @@ -27,8 +27,8 @@ en: 95ee3e3c0ecedadd zh: 933d267402ceec74 /deepseek-ai-dsh-tool-session-list/understand-the-implementation: - en: 730fef413ce5a404 - zh: 325a5700a9edbda1 + en: ac9f08e72d3f7e64 + zh: 231196ddbb82b779 /deepseek-ai-dsh-tool-session-list/further-exploration: en: 06d8fa5cb2d63b6b zh: 2635b93fccf3dbc9 diff --git a/packages/session-query/tool-session-list/README.md b/packages/session-query/tool-session-list/README.md index 3a17a6f125..3d9cab0fd4 100644 --- a/packages/session-query/tool-session-list/README.md +++ b/packages/session-query/tool-session-list/README.md @@ -65,7 +65,7 @@ Invalid pagination and an unknown `workspace_id` fail with `ToolArgsError` (`INV
Implementation internals — click to expand -A Workspace selection reads `Workspace.sessionHeaders`; an unscoped call uses the existing header-only query listing. Both combine headers with projected metadata. The shared `registerSessionListMetadata` helper acquires the same projection unit used by the Session API; each consumer releases its own registration when disposed. The title projection remains owned by `dsh-session-title`. Cold rows read the projection cache without opening the underlying log, including on a cache miss. No Session Controller or Agent activation is required. +A Workspace selection reads `Workspace.getSessionHeaders()`; an unscoped call uses the existing header-only query listing. Both combine headers with projected metadata. Live rows read blankness and prompt recency through `ctx.sessionQuery.getListMetadata`, the same projection the Session API reads. The title projection remains owned by `dsh-session-title`. Cold rows read the projection cache without opening the underlying log, including on a cache miss. No Session Controller or Agent activation is required. | File | Role | |---|---| diff --git a/packages/session-query/tool-session-list/README.zh.md b/packages/session-query/tool-session-list/README.zh.md index a6dbcf8786..023374121b 100644 --- a/packages/session-query/tool-session-list/README.zh.md +++ b/packages/session-query/tool-session-list/README.zh.md @@ -65,7 +65,7 @@ kind: "package-reference"
实现细节——点击展开 -选定 Workspace 时读取 `Workspace.sessionHeaders`;不指定范围时使用现有的仅 header 查询列表。两者都把 header 与投影元数据结合。共享的 `registerSessionListMetadata` 辅助函数获取 Session API 使用的同一个投影单元;每个消费方在释放时只移除自己的注册。标题投影仍由 `dsh-session-title` 拥有。冷条目读取投影缓存,不打开底层日志,缓存未命中时也一样。不需要 Session 控制器,也不会激活 agent。 +选定 Workspace 时读取 `Workspace.getSessionHeaders()`;不指定范围时使用现有的仅 header 查询列表。两者都把 header 与投影元数据结合。实时条目通过 `ctx.sessionQuery.getListMetadata` 读取空白状态与提示词活动时间,与 Session API 读取同一个投影。标题投影仍由 `dsh-session-title` 拥有。冷条目读取投影缓存,不打开底层日志,缓存未命中时也一样。不需要 Session 控制器,也不会激活 agent。 | 文件 | 职责 | |---|---| diff --git a/packages/session-query/tool-session-list/src/index.ts b/packages/session-query/tool-session-list/src/index.ts index a7d17b0bab..1ec7e96f4b 100644 --- a/packages/session-query/tool-session-list/src/index.ts +++ b/packages/session-query/tool-session-list/src/index.ts @@ -4,7 +4,6 @@ */ import type { Context } from '@deepseek-ai/cordis' -import { registerSessionListMetadata } from '@deepseek-ai/dsh-session-query' import { defineTool } from '@deepseek-ai/dsh-tools' import { listSessions, listWorkspaces } from './list.ts' @@ -21,10 +20,8 @@ const pagination = { /** * Grant tools access to all Workspace and Session metadata in this runtime. * @param ctx - scoped context granting these tools to its callers. - * @returns when the shared list metadata projection and tools are registered. */ -export async function apply(ctx: Context): Promise { - const readMetadata = await registerSessionListMetadata(ctx) +export function apply(ctx: Context): void { ctx.tools.register(defineTool({ name: 'list_workspace', description: 'List workspaces in registry order, including empty workspaces. Returns IDs, titles, paths, and creation and update times.', @@ -75,7 +72,7 @@ export async function apply(ctx: Context): Promise { render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }], }, isConcurrencySafe: () => true, - execute: (args, exec) => listSessions(ctx, readMetadata, args, exec.signal), + execute: (args, exec) => listSessions(ctx, args, exec.signal), presentCall: args => ({ card: 'generic', title: 'List sessions', kind: 'read', rawInput: args.workspace_id }), })) } diff --git a/packages/session-query/tool-session-list/src/list.ts b/packages/session-query/tool-session-list/src/list.ts index 2de007a6eb..a21e68e7b5 100644 --- a/packages/session-query/tool-session-list/src/list.ts +++ b/packages/session-query/tool-session-list/src/list.ts @@ -1,8 +1,8 @@ /** Header-only selection and cached metadata for the read-only listing tools. */ import type { Context } from '@deepseek-ai/cordis' -import type { Session, SessionHeader, SessionId } from '@deepseek-ai/dsh-session' -import type { SessionListMetadata } from '@deepseek-ai/dsh-session-query' +import type { SessionHeader, SessionId } from '@deepseek-ai/dsh-session' +import type {} from '@deepseek-ai/dsh-session-query' import type {} from '@deepseek-ai/dsh-session-projection-cache' import type {} from '@deepseek-ai/dsh-session-title' import { ToolArgsError } from '@deepseek-ai/dsh-tools' @@ -76,14 +76,12 @@ export function listWorkspaces(ctx: Context, input: PageInput, signal: AbortSign * A Workspace selection reads only its members' indexed headers; an unscoped call enumerates * the corpus headers. Subagent Sessions are excluded. * @param ctx - context providing query, Workspace, and projection services. - * @param readLiveMetadata - ready reader owned by this plugin's registration. * @param input - filters and pagination arguments. * @param signal - caller cancellation, forwarded to the corpus listing. * @returns filtered Session metadata ordered by activity, then identity. */ export async function listSessions( ctx: Context, - readLiveMetadata: (session: Session) => SessionListMetadata, input: SessionListInput, signal: AbortSignal, ): Promise { @@ -98,14 +96,14 @@ export async function listSessions( if (workspace === undefined) { throw new ToolArgsError([`workspace_id ${JSON.stringify(input.workspace_id)} is not registered; use list_workspace to find a workspace`]) } - headers = workspace.sessionHeaders + headers = workspace.getSessionHeaders() } const archived = new Set(ctx.workspaceRegistry.archivedSessionIds) const items = [] for (const header of headers) { if (header.origin === 'subagent') continue if (archived.has(header.id) !== (input.archived ?? false)) continue - const metadata = readListMetadata(ctx, header, readLiveMetadata) + const metadata = readListMetadata(ctx, header) items.push({ session_id: header.id, title: metadata.title, @@ -124,13 +122,12 @@ export async function listSessions( function readListMetadata( ctx: Context, header: SessionHeader, - readLiveMetadata: (session: Session) => SessionListMetadata, ): { title: string | null; lastPromptAt: number | null } { const live = ctx.sessions.get(header.id) if (live !== undefined) { return { title: ctx.sessionProjections.snapshot(live, ['title']).values.title ?? null, - lastPromptAt: readLiveMetadata(live).lastPromptAt, + lastPromptAt: ctx.sessionQuery.getListMetadata(live).lastPromptAt, } } const cache = ctx.get('sessionProjectionCache') diff --git a/packages/workspace/workspace/README.i18n.yaml b/packages/workspace/workspace/README.i18n.yaml index 56af9d261a..cd426494c8 100644 --- a/packages/workspace/workspace/README.i18n.yaml +++ b/packages/workspace/workspace/README.i18n.yaml @@ -39,8 +39,8 @@ en: 447ced401b3b14a8 zh: 3ce2105605223945 /deepseek-ai-dsh-workspace/understand-the-implementation/design-philosophy: - en: 512431b309ba0051 - zh: 206c77de2022a541 + en: 9e06dc2424613790 + zh: 806bf45f13ebcc72 /deepseek-ai-dsh-workspace/understand-the-implementation/api-behavior: en: 8fcd81ee32f3c01e zh: 08ac92d085bb8147 diff --git a/packages/workspace/workspace/README.md b/packages/workspace/workspace/README.md index 23d8e88804..a3abb7fbca 100644 --- a/packages/workspace/workspace/README.md +++ b/packages/workspace/workspace/README.md @@ -91,7 +91,7 @@ This section explains the design decisions behind the feature and points at the ### Design philosophy - **One record per canonical path.** `fs.realpath` is the single uniqueness canon: paths are stored canonicalized, so a symlink to an owned directory collides, and uniqueness is string equality of canonical paths. -- **Membership starts from the recorded account.** The header index validates ordered `sessionIds`; missing-directory candidates retain their account, while other invalid candidates are filtered on read and pruned by the next mutation. `sessionHeaders` returns the indexed headers of `sessionIds` in the same order without persistence I/O. The strict canonical-path index used for history bootstrap includes existing directories only. +- **Membership starts from the recorded account.** The header index validates ordered `sessionIds`; missing-directory candidates retain their account, while other invalid candidates are filtered on read and pruned by the next mutation. `getSessionHeaders()` returns the indexed headers of `sessionIds` in the same order without persistence I/O. The strict canonical-path index used for history bootstrap includes existing directories only. - **Header-only reads.** Bootstrap and attach validation read `SessionHeader` fields only; event bodies are never loaded. - **Two-write mutations with an explicit marker.** Create and delete persist a `pendingMutation` marker before the record/order pair can diverge, so startup completes exactly the interrupted operation and unmarked divergence fails loud as corruption. - **Serialized writes.** Registry operations run on one operation chain; entity mutations go through `table.update` on the domain write chain, stamping `updatedAt` and deciding membership at their chain slot. diff --git a/packages/workspace/workspace/README.zh.md b/packages/workspace/workspace/README.zh.md index 02bf670648..6990a70857 100644 --- a/packages/workspace/workspace/README.zh.md +++ b/packages/workspace/workspace/README.zh.md @@ -91,7 +91,7 @@ Workspace 注册不意味着拥有其目录。未来的破坏性文件系统操 ### 设计理念 - **每个规范路径一条记录。** `fs.realpath` 是唯一的一套唯一性规范:路径以规范化形式存储,因此指向已有记录目录的符号链接会与之冲突,唯一性即规范路径的字符串相等。 -- **成员资格以已记录的归属为起点。** 头部索引校验有序的 `sessionIds`;目录缺失的候选保留归属,其他无效候选在读取时过滤,并在下一次变更时剪除。`sessionHeaders` 按相同顺序返回 `sessionIds` 的已索引 header,不做持久化 I/O。历史引导使用的严格规范路径索引只包含现存目录。 +- **成员资格以已记录的归属为起点。** 头部索引校验有序的 `sessionIds`;目录缺失的候选保留归属,其他无效候选在读取时过滤,并在下一次变更时剪除。`getSessionHeaders()` 按相同顺序返回 `sessionIds` 的已索引 header,不做持久化 I/O。历史引导使用的严格规范路径索引只包含现存目录。 - **仅读取头部。** 引导与 attach 校验只读取 `SessionHeader` 字段;事件正文绝不加载。 - **两次写入的变更带显式标记。** 创建与删除在记录/顺序对可能分叉之前先持久化 `pendingMutation` 标记,因此启动只补全被中断的操作,未标记的分叉作为损坏明确报错。 - **串行化写入。** 注册表操作跑在同一条操作链上;实体变更通过领域写链上的 `table.update` 执行,写入 `updatedAt`,并在其所在的链位置决定成员资格。 diff --git a/packages/workspace/workspace/src/entity.ts b/packages/workspace/workspace/src/entity.ts index cecd435181..7bf2ea5727 100644 --- a/packages/workspace/workspace/src/entity.ts +++ b/packages/workspace/workspace/src/entity.ts @@ -111,7 +111,8 @@ export class WorkspaceEntity implements Workspace { return this.record.sessionIds.filter(id => this.host.candidateMatches(id, this.record.path)) } - get sessionHeaders(): readonly SessionHeader[] { + /** Reads the registry's startup and attach-time header index without persistence I/O. */ + getSessionHeaders(): readonly SessionHeader[] { return this.sessionIds.map(id => this.host.sessionHeader(id)) } diff --git a/packages/workspace/workspace/src/types.ts b/packages/workspace/workspace/src/types.ts index bd3ae0a3e4..aa47a38627 100644 --- a/packages/workspace/workspace/src/types.ts +++ b/packages/workspace/workspace/src/types.ts @@ -100,11 +100,10 @@ export interface Workspace { readonly sessionIds: readonly SessionId[] /** - * Stored headers of {@link sessionIds}, in the same order. Read from the - * registry's startup and attach-time header index without persistence I/O; - * headers are immutable, so an indexed header never goes stale. + * List the stored headers of the current members. + * @returns a new array with one header per entry of {@link sessionIds}, in the same order. */ - readonly sessionHeaders: readonly SessionHeader[] + getSessionHeaders(): readonly SessionHeader[] /** * Replace the display title durably. diff --git a/packages/workspace/workspace/tests/workspace.spec.ts b/packages/workspace/workspace/tests/workspace.spec.ts index ddba94bb49..45373bce19 100644 --- a/packages/workspace/workspace/tests/workspace.spec.ts +++ b/packages/workspace/workspace/tests/workspace.spec.ts @@ -667,10 +667,25 @@ describe('Workspace session ordering', () => { expect(workspace.sessionIds).toEqual(['s2', 's1']) await workspace.attachSession(SessionId('s1')) expect(workspace.sessionIds).toEqual(['s2', 's1']) - expect(workspace.sessionHeaders).toEqual([header('s2', dir, 2), header('s1', dir, 1)]) + expect(workspace.getSessionHeaders()).toEqual([header('s2', dir, 2), header('s1', dir, 1)]) expect(storedRecord(result.pool, workspace.id).sessionIds).toEqual(['s2', 's1']) }) + it('includes a newly created and attached Session in later header lists', async () => { + const dir = await makeDir('attach-headers') + const result = await harness() + result.setSessions([header('s1', dir, 1)]) + const workspace = await result.registry.create(dir) + await workspace.attachSession(SessionId('s1')) + const before = workspace.getSessionHeaders() + expect(before).toEqual([header('s1', dir, 1)]) + + result.setSessions([header('s1', dir, 1), header('s2', dir, 2)]) + await workspace.attachSession(SessionId('s2')) + expect(workspace.getSessionHeaders()).toEqual([header('s2', dir, 2), header('s1', dir, 1)]) + expect(before).toEqual([header('s1', dir, 1)]) + }) + it('moves one id before an anchor or to the end, durably', async () => { const dir = await makeDir('insert-before') const result = await harness() @@ -891,7 +906,7 @@ describe('header-validated membership projection', () => { onTestFinished(() => result.ctx.fiber.dispose()) const workspace = result.registry.get(id)! expect(workspace.sessionIds).toEqual(['missing-dir']) - expect(workspace.sessionHeaders).toEqual([header('missing-dir', missing)]) + expect(workspace.getSessionHeaders()).toEqual([header('missing-dir', missing)]) await workspace.setTitle('Validated') expect(storedRecord(pool, id).sessionIds).toEqual(['missing-dir']) }) diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index 12950471bb..f7cf70bae4 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -744,6 +744,7 @@ export const LINK_MAP: Readonly> = { SessionEventTraceRequest: 'session-query.md', SessionEventWindow: 'session-query.md', SessionLineageTrace: 'session-query.md', + SessionListMetadata: 'session-query.md', SessionObservation: 'session-query.md', SessionObservationOptions: 'session-query.md', SessionRecord: 'session-query.md', From 1851e875f429d5049525df9370891204d905404c Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Mon, 16 Nov 2026 13:07:46 +0800 Subject: [PATCH 18/31] feat(tool-session-list): show complete call arguments on tool cards list_session showed only workspace_id and list_workspace showed no input, so calls that differ in archived, limit, or offset rendered identical cards. --- packages/session-query/tool-session-list/src/index.ts | 4 ++-- .../tool-session-list/tests/tool-session-list.spec.ts | 4 ++++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/packages/session-query/tool-session-list/src/index.ts b/packages/session-query/tool-session-list/src/index.ts index 1ec7e96f4b..139b50a023 100644 --- a/packages/session-query/tool-session-list/src/index.ts +++ b/packages/session-query/tool-session-list/src/index.ts @@ -45,7 +45,7 @@ export function apply(ctx: Context): void { }, isConcurrencySafe: () => true, execute: (args, exec) => Promise.resolve(listWorkspaces(ctx, args, exec.signal)), - presentCall: () => ({ card: 'generic', title: 'List workspaces', kind: 'read' }), + presentCall: args => ({ card: 'generic', title: 'List workspaces', kind: 'read', rawInput: args }), })) ctx.tools.register(defineTool({ name: 'list_session', @@ -73,6 +73,6 @@ export function apply(ctx: Context): void { }, isConcurrencySafe: () => true, execute: (args, exec) => listSessions(ctx, args, exec.signal), - presentCall: args => ({ card: 'generic', title: 'List sessions', kind: 'read', rawInput: args.workspace_id }), + presentCall: args => ({ card: 'generic', title: 'List sessions', kind: 'read', rawInput: args }), })) } diff --git a/packages/session-query/tool-session-list/tests/tool-session-list.spec.ts b/packages/session-query/tool-session-list/tests/tool-session-list.spec.ts index 6777822aef..b9d54912f0 100644 --- a/packages/session-query/tool-session-list/tests/tool-session-list.spec.ts +++ b/packages/session-query/tool-session-list/tests/tool-session-list.spec.ts @@ -325,6 +325,10 @@ describe('read-only Session list tools', () => { expect(tool?.isConcurrencySafe?.({})).toBe(true) expect(tool?.presentCall?.({})).toMatchObject({ card: 'generic', kind: 'read' }) } + const page = { limit: 5, offset: 10 } + expect(mounted.ctx.tools.get('list_workspace')?.presentCall?.(page)).toMatchObject({ rawInput: page }) + const filters = { workspace_id: 'w1', archived: true, limit: 5, offset: 10 } + expect(mounted.ctx.tools.get('list_session')?.presentCall?.(filters)).toMatchObject({ rawInput: filters }) await mounted.fiber.dispose() expect(mounted.ctx.tools.get('list_workspace')).toBeUndefined() expect(mounted.ctx.tools.get('list_session')).toBeUndefined() From a65aacaa6ac02529717496fd4d6a2014115f45fa Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Mon, 16 Nov 2026 13:21:21 +0800 Subject: [PATCH 19/31] fix(session): follow sessionQuery's projection dependency and rc.3 version - SessionReferenceResolver injects sessions and sessionProjections, which sessionQuery now requires; its absent-registry label branch is unreachable and is removed. - The translator paid fixture mounts the projection registry beside its SQLite query service. - dsh-tool-session-list follows the master release version 0.2.2-rc.3. --- docs/config-catalog.md | 2 +- docs/config-catalog.zh.md | 2 +- packages/context/session-reference/src/index.ts | 12 ++++-------- .../tests/session-reference.spec.ts | 2 +- packages/experimental/translator/package.json | 1 + .../experimental/translator/tests/paid-fixture.ts | 3 +++ .../session-query/tool-session-list/package.json | 2 +- pnpm-lock.yaml | 3 +++ 8 files changed, 15 insertions(+), 12 deletions(-) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 3806d9008f..21746e40ec 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -3375,7 +3375,7 @@ export type JournalMode = 'wal' | 'delete' | 'truncate' | 'persist' ## `@deepseek-ai/dsh-session-reference` -- `inject`: `sessionQuery` +- `inject`: `sessionQuery` · `sessions` · `sessionProjections` - `source`: [`packages/context/session-reference/src/config.ts:11`](../packages/context/session-reference/src/config.ts) ```ts config-catalog diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 24edf6e1f6..6c6b2d8b93 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -3377,7 +3377,7 @@ export type JournalMode = 'wal' | 'delete' | 'truncate' | 'persist' ## `@deepseek-ai/dsh-session-reference` -- `inject`: `sessionQuery` +- `inject`: `sessionQuery` · `sessions` · `sessionProjections` - `source`: [`packages/context/session-reference/src/config.ts:11`](../packages/context/session-reference/src/config.ts) ```ts config-catalog diff --git a/packages/context/session-reference/src/index.ts b/packages/context/session-reference/src/index.ts index b9f83f8140..4864b7d1c1 100644 --- a/packages/context/session-reference/src/index.ts +++ b/packages/context/session-reference/src/index.ts @@ -105,7 +105,7 @@ function candidateKeys({ record, label, displayTitle }: LabelledCandidate): Sear /** Exact-read consumer that prepares immutable cross-session message context. */ export class SessionReferenceResolver extends TypertRemoteService { - static inject = ['sessionQuery'] + static inject = ['sessionQuery', 'sessions', 'sessionProjections'] static Config: z = z.object({ maxReferences: z.number().step(1).min(1).max(MAX_REFERENCES).default(MAX_REFERENCES), candidateLimit: z.number().step(1).min(1).default(DEFAULT_CANDIDATE_LIMIT), @@ -272,17 +272,13 @@ export class SessionReferenceResolver extends TypertRemoteService { private projectedLabels( items: readonly T[], ): Array { - const projections = this.ctx.get('sessionProjections') - const sessions = this.ctx.get('sessions') - // An attached session answers from its live cut only while the registry is mounted. - const attached = new Map(sessions === undefined || projections === undefined - ? undefined - : sessions.list().map(session => [session.id, session])) + const projections = this.ctx.sessionProjections + const attached = new Map(this.ctx.sessions.list().map(session => [session.id, session])) const cache = this.ctx.get('sessionProjectionCache') const cachedSnapshot = cache?.cachedSnapshot.bind(cache) return items.map((item) => { const session = attached.get(item.record.header.id) - const snapshot = session !== undefined && projections !== undefined + const snapshot = session !== undefined ? projections.snapshot(session, LABEL_KEYS) : cachedSnapshot?.(item.record.header, LABEL_KEYS) const label = titleOf(snapshot) ?? item.record.header.id diff --git a/packages/context/session-reference/tests/session-reference.spec.ts b/packages/context/session-reference/tests/session-reference.spec.ts index e4768fd0af..db9fc4e870 100644 --- a/packages/context/session-reference/tests/session-reference.spec.ts +++ b/packages/context/session-reference/tests/session-reference.spec.ts @@ -821,7 +821,7 @@ describe('session reference discovery and preparation', () => { vi.restoreAllMocks() }) - it('labels every session by id when no projection face is composed', async () => { + it('labels every session by id when no title projection is registered', async () => { const ctx = new Context() await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) diff --git a/packages/experimental/translator/package.json b/packages/experimental/translator/package.json index a8b5ac641f..b30925db07 100644 --- a/packages/experimental/translator/package.json +++ b/packages/experimental/translator/package.json @@ -69,6 +69,7 @@ "@deepseek-ai/dsh-deepseek-account": "workspace:*", "@deepseek-ai/dsh-deepseek-llm-api-extensions": "workspace:*", "@deepseek-ai/dsh-session-log-deepseek": "workspace:*", + "@deepseek-ai/dsh-session-projection": "workspace:*", "@deepseek-ai/dsh-session-query-sqlite": "workspace:*" } } diff --git a/packages/experimental/translator/tests/paid-fixture.ts b/packages/experimental/translator/tests/paid-fixture.ts index 70ee57f4bc..3435e9becd 100644 --- a/packages/experimental/translator/tests/paid-fixture.ts +++ b/packages/experimental/translator/tests/paid-fixture.ts @@ -4,6 +4,7 @@ import { boot } from '@deepseek-ai/dsh-app-boot' import LlmRuntime from '@deepseek-ai/dsh-llm' import SessionStore, { SESSION_FORMAT_VERSION, type SessionId, SessionSeq, type Session, type SessionEvent, type SessionHeader } from '@deepseek-ai/dsh-session' import * as JsonlPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import SqliteSessionQuery from '@deepseek-ai/dsh-session-query-sqlite' import * as Official from '@deepseek-ai/dsh-llm-deepseek-api-key' import * as Account from '@deepseek-ai/dsh-llm-deepseek-account' @@ -136,6 +137,7 @@ export async function paidFixture(cleanups: Array<() => Promise>, options: { id: 'account-custom-id', name: '@deepseek-ai/dsh-llm-deepseek-account', disabled: !withNativeOwners, config: { baseURL } }, { id: 'translator', name: '@deepseek-ai/dsh-experimental-translator', config: translator }, ...options.withSessionQuery === true ? [ + { id: 'projections', name: '@deepseek-ai/dsh-session-projection' }, { id: 'query', name: '@deepseek-ai/dsh-session-query-sqlite', config: { path: join(root, 'query.sqlite'), openAt: 'never' } }, ] : [], ...options.withSessionLog === true ? [ @@ -147,6 +149,7 @@ export async function paidFixture(cleanups: Array<() => Promise>, options: const modules = new Map([ ['@deepseek-ai/dsh-llm', LlmRuntime], ['@deepseek-ai/dsh-session', SessionStore], ['@deepseek-ai/dsh-session-persistence-jsonl', JsonlPersistence], ['@deepseek-ai/dsh-session-query-sqlite', SqliteSessionQuery], + ['@deepseek-ai/dsh-session-projection', SessionProjectionRegistry], [options.officialName ?? '@deepseek-ai/dsh-llm-deepseek-api-key', Official], ['@deepseek-ai/dsh-llm-deepseek-account', Account], ['@deepseek-ai/dsh-experimental-translator', Translator], ['@deepseek-ai/dsh-deepseek-llm-api-extensions', DeepSeekLlmApiExtensionRegistry], diff --git a/packages/session-query/tool-session-list/package.json b/packages/session-query/tool-session-list/package.json index 0c24c7fcae..392a8f22ac 100644 --- a/packages/session-query/tool-session-list/package.json +++ b/packages/session-query/tool-session-list/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-tool-session-list", "description": "Read-only paginated Workspace and Session metadata tools", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.3", "publishConfig": { "access": "public" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 1d0bd1bd5d..be787bcb59 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -12600,6 +12600,9 @@ importers: '@deepseek-ai/dsh-session-persistence-jsonl': specifier: workspace:* version: link:../../session/session-persistence-jsonl + '@deepseek-ai/dsh-session-projection': + specifier: workspace:* + version: link:../../session/session-projection '@deepseek-ai/dsh-session-query-sqlite': specifier: workspace:* version: link:../../session-query/session-query-sqlite From 01aafcb4e9c6fa054fc515819e33b39054d324e6 Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Mon, 16 Nov 2026 13:25:42 +0800 Subject: [PATCH 20/31] docs(session): address remaining list tool review notes - Name the model-visible page limits once and derive the schema text from them. - Type the intermediate Session rows and make list_workspace's execute async. - Document that blank Sessions are listed and that unscoped listing has unit coverage only. - State that the Workspace registry adds no model-visible surface of its own while the optional listing tools expose its metadata. --- docs/subsystems/workspace.i18n.yaml | 4 ++-- docs/subsystems/workspace.md | 2 +- docs/subsystems/workspace.zh.md | 2 +- .../tool-session-list/README.i18n.yaml | 4 ++-- packages/session-query/tool-session-list/README.md | 2 ++ .../session-query/tool-session-list/README.zh.md | 2 ++ .../session-query/tool-session-list/src/index.ts | 6 +++--- .../session-query/tool-session-list/src/list.ts | 13 +++++++++---- packages/workspace/workspace/README.i18n.yaml | 4 ++-- packages/workspace/workspace/README.md | 2 +- packages/workspace/workspace/README.zh.md | 2 +- 11 files changed, 26 insertions(+), 17 deletions(-) diff --git a/docs/subsystems/workspace.i18n.yaml b/docs/subsystems/workspace.i18n.yaml index bf01196282..86c2f01cb1 100644 --- a/docs/subsystems/workspace.i18n.yaml +++ b/docs/subsystems/workspace.i18n.yaml @@ -3,8 +3,8 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/workspace.md /workspaces: - en: 183fd2f466e3279c - zh: 6e79009b7294c240 + en: 70865308120d0b14 + zh: fe5d7406141657e1 /workspaces/identity: en: d61a7e78bbc1fb56 zh: 8397869f70cd5b28 diff --git a/docs/subsystems/workspace.md b/docs/subsystems/workspace.md index c82ba0dbc9..eda76426f7 100644 --- a/docs/subsystems/workspace.md +++ b/docs/subsystems/workspace.md @@ -2,7 +2,7 @@ English | [中文](workspace.zh.md) -A workspace is the persistent record of a directory the user works in: a stable id over a canonical path, a display title, and the ordered account of sessions that belong to it. The subsystem is one package ([dsh-workspace](../../packages/workspace/workspace), `ctx.workspaceRegistry`) — an optional host-side capability, not part of the agent-loop spine, and invisible to models (no tools, no prompt text, no session events). It stores its records through the [storage domain form](storage.md) and validates session membership against [`SessionHeader.cwd`](persistence.md#sessionheader--metadata-beside-the-log), so `storageDomain` and `sessionPersistence` are mandatory startup dependencies: an unavailable persistence peer leaves the plugin pending rather than being mistaken for an empty history. Design record: [domain KV storage Agent Note](../../.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.md); bootstrap and GUI ordering: [Workspace UI product-flow Agent Note](../../.agents/notes/archived/feature/2026-07-25-workspace-ui-product-flow.md). +A workspace is the persistent record of a directory the user works in: a stable id over a canonical path, a display title, and the ordered account of sessions that belong to it. The subsystem is one package ([dsh-workspace](../../packages/workspace/workspace), `ctx.workspaceRegistry`) — an optional host-side capability, not part of the agent-loop spine, and adds no model-visible surface of its own (no tools, no prompt text, no session events); the optional [listing tools](../../packages/session-query/tool-session-list) expose Workspace IDs, titles, and paths to models that are granted them. It stores its records through the [storage domain form](storage.md) and validates session membership against [`SessionHeader.cwd`](persistence.md#sessionheader--metadata-beside-the-log), so `storageDomain` and `sessionPersistence` are mandatory startup dependencies: an unavailable persistence peer leaves the plugin pending rather than being mistaken for an empty history. Design record: [domain KV storage Agent Note](../../.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.md); bootstrap and GUI ordering: [Workspace UI product-flow Agent Note](../../.agents/notes/archived/feature/2026-07-25-workspace-ui-product-flow.md). Source: [`packages/workspace/workspace/src/types.ts`](../../packages/workspace/workspace/src/types.ts) diff --git a/docs/subsystems/workspace.zh.md b/docs/subsystems/workspace.zh.md index 3504f9391e..e800d15107 100644 --- a/docs/subsystems/workspace.zh.md +++ b/docs/subsystems/workspace.zh.md @@ -2,7 +2,7 @@ [English](workspace.md) | 中文 -工作区(workspace)是用户工作目录的持久记录:一个建立在规范路径之上的稳定 id、一个显示标题,以及归属于它的会话的有序账本。该子系统是单个包(package)([dsh-workspace](../../packages/workspace/workspace),`ctx.workspaceRegistry`)——一项宿主侧可选能力,不属于 agent loop(智能体循环)主干,并且对模型不可见(没有工具、没有提示词文本、没有会话事件)。它通过[存储领域数据形式](storage.zh.md)存储自己的记录,并对照 [`SessionHeader.cwd`](persistence.zh.md#sessionheader--metadata-beside-the-log) 校验会话成员资格,因此 `storageDomain` 与 `sessionPersistence` 是必需的启动依赖:持久化这一依赖不可用时,插件保持 pending,而不是把这种不可用误当作空历史。设计记录:[领域 KV 存储 Agent Note(agent 决策记录)](../../.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.zh.md);引导与 GUI 顺序:[Workspace UI 产品流程 Agent Note](../../.agents/notes/archived/feature/2026-07-25-workspace-ui-product-flow.md)。 +工作区(workspace)是用户工作目录的持久记录:一个建立在规范路径之上的稳定 id、一个显示标题,以及归属于它的会话的有序账本。该子系统是单个包(package)([dsh-workspace](../../packages/workspace/workspace),`ctx.workspaceRegistry`)——一项宿主侧可选能力,不属于 agent loop(智能体循环)主干,并且自身不增加模型可见内容(没有工具、没有提示词文本、没有会话事件);可选的[列表工具](../../packages/session-query/tool-session-list)会把 Workspace ID、标题与路径提供给获准使用它们的模型。它通过[存储领域数据形式](storage.zh.md)存储自己的记录,并对照 [`SessionHeader.cwd`](persistence.zh.md#sessionheader--metadata-beside-the-log) 校验会话成员资格,因此 `storageDomain` 与 `sessionPersistence` 是必需的启动依赖:持久化这一依赖不可用时,插件保持 pending,而不是把这种不可用误当作空历史。设计记录:[领域 KV 存储 Agent Note(agent 决策记录)](../../.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.zh.md);引导与 GUI 顺序:[Workspace UI 产品流程 Agent Note](../../.agents/notes/archived/feature/2026-07-25-workspace-ui-product-flow.md)。 源码:[`packages/workspace/workspace/src/types.ts`](../../packages/workspace/workspace/src/types.ts) diff --git a/packages/session-query/tool-session-list/README.i18n.yaml b/packages/session-query/tool-session-list/README.i18n.yaml index d5264c53d9..2c3d1b503c 100644 --- a/packages/session-query/tool-session-list/README.i18n.yaml +++ b/packages/session-query/tool-session-list/README.i18n.yaml @@ -48,8 +48,8 @@ en: 0e201fbbe37798d8 zh: fd4bd41e7393c234 /deepseek-ai-dsh-tool-session-list/known-limitations-and-deferred-work: - en: f0b57c2f2e7a0984 - zh: ed80800cb0d021c8 + en: 2c53c1fc603e0ff2 + zh: 99a58f1e0e3c27fc /deepseek-ai-dsh-tool-session-list/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: e88aeb617ffb74ea diff --git a/packages/session-query/tool-session-list/README.md b/packages/session-query/tool-session-list/README.md index 3d9cab0fd4..f487684915 100644 --- a/packages/session-query/tool-session-list/README.md +++ b/packages/session-query/tool-session-list/README.md @@ -111,6 +111,8 @@ These constraints affect consumers of the lists. - **Cold metadata can be missing or stale** — listing never rebuilds it by reading the full log. A `null` title can mean either no title or unavailable title metadata. - **Pagination is not a stable snapshot** — concurrent registry or Session changes can move entries between calls. Session listing reads every candidate before selecting a page, so the page size does not bound total work; an unscoped call scales with the Session count. +- **Blank sessions are listed** — a Session without a turn, such as a Workspace's unused new Session, is a regular result; its `updated_at` equals `created_at` and its title is usually `null`. +- **Unscoped listing has unit coverage only** — the recorded headless replay passes `workspace_id` on every `list_session` call, so enumeration without a Workspace runs only in unit tests. - **Metadata access is runtime-wide** — callers needing per-agent Workspace authorization require a separately defined access policy before these tools are enabled for them. diff --git a/packages/session-query/tool-session-list/README.zh.md b/packages/session-query/tool-session-list/README.zh.md index 023374121b..e11f949f77 100644 --- a/packages/session-query/tool-session-list/README.zh.md +++ b/packages/session-query/tool-session-list/README.zh.md @@ -111,6 +111,8 @@ kind: "package-reference" - **冷元数据可能缺失或过期**——列表不会通过读取完整日志重建它。标题为 `null` 可能表示没有标题,也可能表示标题元数据不可用。 - **分页不是稳定快照**——并发的注册表或 Session 变化可能让条目在多次调用间移动。会话列表先读取全部候选项,再选取一页,因此每页大小不限制总工作量;不指定范围的调用随 Session 总数增长。 +- **空白会话也会列出**——还没有 turn 的 Session(例如 Workspace 中未使用的新 Session)是普通结果;它的 `updated_at` 等于 `created_at`,标题通常为 `null`。 +- **不指定范围的列表只有单测覆盖**——录制的 headless 回放中每次 `list_session` 调用都带 `workspace_id`,因此不指定 Workspace 的枚举只在单元测试中运行。 - **元数据访问覆盖整个运行时**——需要逐 agent Workspace 授权的调用者,必须先定义独立的访问策略,再为其启用这些工具。 diff --git a/packages/session-query/tool-session-list/src/index.ts b/packages/session-query/tool-session-list/src/index.ts index 139b50a023..f0c2f84b8d 100644 --- a/packages/session-query/tool-session-list/src/index.ts +++ b/packages/session-query/tool-session-list/src/index.ts @@ -5,7 +5,7 @@ import type { Context } from '@deepseek-ai/cordis' import { defineTool } from '@deepseek-ai/dsh-tools' -import { listSessions, listWorkspaces } from './list.ts' +import { DEFAULT_PAGE_LIMIT, listSessions, listWorkspaces, MAX_PAGE_LIMIT } from './list.ts' /** Cordis plugin identity. */ export const name = 'tool-session-list' @@ -13,7 +13,7 @@ export const name = 'tool-session-list' export const inject = ['tools', 'sessions', 'sessionQuery', 'workspaceRegistry', 'sessionProjections'] const pagination = { - limit: { type: 'integer', description: 'Maximum entries to return, from 1 to 100. Defaults to 20.' }, + limit: { type: 'integer', description: `Maximum entries to return, from 1 to ${String(MAX_PAGE_LIMIT)}. Defaults to ${String(DEFAULT_PAGE_LIMIT)}.` }, offset: { type: 'integer', description: 'Number of matching entries to skip. Defaults to 0.' }, } as const @@ -44,7 +44,7 @@ export function apply(ctx: Context): void { render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }], }, isConcurrencySafe: () => true, - execute: (args, exec) => Promise.resolve(listWorkspaces(ctx, args, exec.signal)), + execute: async (args, exec) => listWorkspaces(ctx, args, exec.signal), presentCall: args => ({ card: 'generic', title: 'List workspaces', kind: 'read', rawInput: args }), })) ctx.tools.register(defineTool({ diff --git a/packages/session-query/tool-session-list/src/list.ts b/packages/session-query/tool-session-list/src/list.ts index a21e68e7b5..6f8e9b3175 100644 --- a/packages/session-query/tool-session-list/src/list.ts +++ b/packages/session-query/tool-session-list/src/list.ts @@ -35,16 +35,21 @@ interface SessionListItem { updated_at: string } +/** Entries per page when the model passes no `limit`; part of the model-visible schema. */ +export const DEFAULT_PAGE_LIMIT = 20 +/** Largest accepted `limit`; part of the model-visible schema. */ +export const MAX_PAGE_LIMIT = 100 + /** * Resolve pagination before reading any registry or persistence data. * @param input - model pagination arguments. * @returns the validated count and starting index. */ export function resolvePage(input: PageInput): { limit: number; offset: number } { - const limit = input.limit ?? 20 + const limit = input.limit ?? DEFAULT_PAGE_LIMIT const offset = input.offset ?? 0 - if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100) { - throw new ToolArgsError(['limit must be an integer from 1 to 100']) + if (!Number.isSafeInteger(limit) || limit < 1 || limit > MAX_PAGE_LIMIT) { + throw new ToolArgsError([`limit must be an integer from 1 to ${String(MAX_PAGE_LIMIT)}`]) } if (!Number.isSafeInteger(offset) || offset < 0) { throw new ToolArgsError(['offset must be a non-negative safe integer']) @@ -99,7 +104,7 @@ export async function listSessions( headers = workspace.getSessionHeaders() } const archived = new Set(ctx.workspaceRegistry.archivedSessionIds) - const items = [] + const items: Array & { updatedAt: number }> = [] for (const header of headers) { if (header.origin === 'subagent') continue if (archived.has(header.id) !== (input.archived ?? false)) continue diff --git a/packages/workspace/workspace/README.i18n.yaml b/packages/workspace/workspace/README.i18n.yaml index cd426494c8..1f922bc5f3 100644 --- a/packages/workspace/workspace/README.i18n.yaml +++ b/packages/workspace/workspace/README.i18n.yaml @@ -9,8 +9,8 @@ en: 7a12adba4e7766e3 zh: f6d5c8374f4512c8 /deepseek-ai-dsh-workspace/summary: - en: 30aea62cabd8e8a8 - zh: b22b30ef08fd4713 + en: 587ea2786e0c12a6 + zh: 6bb61ba4379886b4 /deepseek-ai-dsh-workspace/table-of-contents: en: d152484eb41ac6b4 zh: 09388d293f9be9cb diff --git a/packages/workspace/workspace/README.md b/packages/workspace/workspace/README.md index a3abb7fbca..2237c64c31 100644 --- a/packages/workspace/workspace/README.md +++ b/packages/workspace/workspace/README.md @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -Use this package to keep an ordered, persistent list of project directories and the sessions run in each directory. Hosts can build project sidebars, hide sessions from grouping without deleting their histories, and remove projects without deleting folders, files, or sessions. Re-adding a removed directory creates a fresh project; an existing project's sessions stay grouped when its directory disappears. Choose it for GUI or host workflows that need durable project grouping; it is invisible to models and adds no prompt or request-context cost, but requires session persistence and storage backends. +Use this package to keep an ordered, persistent list of project directories and the sessions run in each directory. Hosts can build project sidebars, hide sessions from grouping without deleting their histories, and remove projects without deleting folders, files, or sessions. Re-adding a removed directory creates a fresh project; an existing project's sessions stay grouped when its directory disappears. Choose it for GUI or host workflows that need durable project grouping; it adds no model-visible surface or prompt or request-context cost of its own (the optional [listing tools](../../session-query/tool-session-list/README.md) expose Workspace metadata to models), but requires session persistence and storage backends. ## Table of Contents diff --git a/packages/workspace/workspace/README.zh.md b/packages/workspace/workspace/README.zh.md index 6990a70857..9bbff74562 100644 --- a/packages/workspace/workspace/README.zh.md +++ b/packages/workspace/workspace/README.zh.md @@ -9,7 +9,7 @@ kind: "package-reference" ## 概述 -使用此包可以维护一个有序、持久的项目目录列表,以及在每个目录中运行的会话。宿主可以构建项目侧边栏、在不删除历史的情况下把会话从分组中隐藏,并在不删除文件夹、文件或会话的情况下移除项目。重新添加已移除的目录会创建一个全新项目;已有项目的目录消失时,其会话仍保持原分组。需要持久项目分组的 GUI 或宿主工作流适合使用它;它对模型不可见,不增加提示词或请求上下文成本,但需要会话持久化与存储后端。 +使用此包可以维护一个有序、持久的项目目录列表,以及在每个目录中运行的会话。宿主可以构建项目侧边栏、在不删除历史的情况下把会话从分组中隐藏,并在不删除文件夹、文件或会话的情况下移除项目。重新添加已移除的目录会创建一个全新项目;已有项目的目录消失时,其会话仍保持原分组。需要持久项目分组的 GUI 或宿主工作流适合使用它;它自身不增加模型可见内容,也不增加提示词或请求上下文成本(可选的[列表工具](../../session-query/tool-session-list/README.zh.md)会向模型提供 Workspace 元数据),但需要会话持久化与存储后端。 ## 目录 From 6bb530211a82a913ef4338c38c2017163e508199 Mon Sep 17 00:00:00 2001 From: gengruilin Date: Mon, 16 Nov 2026 15:26:01 +0800 Subject: [PATCH 21/31] refactor(connector-account): type the face from the generated Remote and return its results `ConnectorAccountsRemote` repeated the signatures typert generates for `ctx.remote.connectorAccounts`, and `settle` turned a failed Remote result back into a rejection. The face now types `start` and `cancel` from `ClientRemote['connectorAccounts']` and returns the Remote result. The buttons read `ok` and report a failed result or a rejected call as the failure notice, so the page behaves as before. --- .../ui-connector-account/README.i18n.yaml | 4 +-- .../client/ui-connector-account/README.md | 4 +-- .../client/ui-connector-account/README.zh.md | 4 +-- .../src/client/components.tsx | 16 ++++++++--- .../ui-connector-account/src/client/index.ts | 12 ++------- .../ui-connector-account/src/client/state.ts | 5 ++-- .../ui-connector-account/src/client/types.ts | 21 +++++---------- .../tests/apply.client.spec.ts | 11 ++++---- .../tests/components.client.spec.tsx | 27 ++++++++++++------- 9 files changed, 54 insertions(+), 50 deletions(-) diff --git a/packages/client/ui-connector-account/README.i18n.yaml b/packages/client/ui-connector-account/README.i18n.yaml index 64303c4159..175dc891ee 100644 --- a/packages/client/ui-connector-account/README.i18n.yaml +++ b/packages/client/ui-connector-account/README.i18n.yaml @@ -30,8 +30,8 @@ en: 353a48db7e7dd0f7 zh: 653f3d983d3fd572 /deepseek-ai-dsh-client-ui-connector-account/understand-the-implementation: - en: 8c16bb36ce00d4cc - zh: d52d2a6f2beacf21 + en: 6bfc9077699bd3cd + zh: ead092e865285eee /deepseek-ai-dsh-client-ui-connector-account/further-exploration: en: 029949903a73d283 zh: 6f9a8c2f7620de69 diff --git a/packages/client/ui-connector-account/README.md b/packages/client/ui-connector-account/README.md index 1226880ada..e30ecb7bd6 100644 --- a/packages/client/ui-connector-account/README.md +++ b/packages/client/ui-connector-account/README.md @@ -84,7 +84,7 @@ The `connectorAccount` dictionary holds the copy every account shares: Close, Ca The Host half, `ConnectorAccounts`, is a Remote service. `register()` observes the account's source, and each `watch` stream reads every account's entry after each change, coalescing changes that arrive before the next read: the key and package, the copy, `present(view)`, the operation in progress, and the latest result with its success text. `start` and `cancel` route by key to the account's source. -[`dsh-api-remotes`](../../api/remotes/README.md) mounts the generated `connectorAccounts` Remote. The browser half opens one `watch` stream through `BrowserAccounts`, whose one store holds the Host's accounts by key, whether the stream is delivering, and the latest notice; it also remembers the operations this browser started. It registers one `plugins.detail.badge` entry and one `shell.overlay` notice for the page, and for each account with a package, `plugins.bundle.config` and `plugins.bundle.activation` keyed by the package name, all under the `connectorAccount` namespace. The surfaces receive `start` and `cancel` callbacks that call the Remote and reject when the Host refuses or the call does not answer; the buttons await them and report the started operation to `BrowserAccounts`. An account the Host drops loses its bundle entries, and unloading withdraws every entry and the stream. +[`dsh-api-remotes`](../../api/remotes/README.md) mounts the generated `connectorAccounts` Remote. The browser half opens one `watch` stream through `BrowserAccounts`, whose one store holds the Host's accounts by key, whether the stream is delivering, and the latest notice; it also remembers the operations this browser started. It registers one `plugins.detail.badge` entry and one `shell.overlay` notice for the page, and for each account with a package, `plugins.bundle.config` and `plugins.bundle.activation` keyed by the package name, all under the `connectorAccount` namespace. The surfaces receive `start` and `cancel` callbacks that call the Remote and return its result; the buttons report the operation of a successful start to `BrowserAccounts`, and a failed result or a rejected call as the failure notice. An account the Host drops loses its bundle entries, and unloading withdraws every entry and the stream. | File | Role | |---|---| @@ -94,7 +94,7 @@ The Host half, `ConnectorAccounts`, is a Remote service. `register()` observes t | [`src/client/state.ts`](src/client/state.ts) | The stream store, the operations this browser started, and their pages and notices | | [`src/client/components.tsx`](src/client/components.tsx) | The slot entries of each surface and the buttons' Remote calls | | [`src/client/locales.ts`](src/client/locales.ts) | The shared dictionary | -| [`src/client/types.ts`](src/client/types.ts) | Browser state, notice, Remote, and face types | +| [`src/client/types.ts`](src/client/types.ts) | Browser state, notice, and face types |
diff --git a/packages/client/ui-connector-account/README.zh.md b/packages/client/ui-connector-account/README.zh.md index 845d244b47..9c1569dfc8 100644 --- a/packages/client/ui-connector-account/README.zh.md +++ b/packages/client/ui-connector-account/README.zh.md @@ -84,7 +84,7 @@ export function apply(ctx: Context): void { Host 一半 `ConnectorAccounts` 是一个 Remote 服务。`register()` 观察账号来源,每条 `watch` 流在每次变化后读取每个账号的条目,并合并在下一次读取前到达的变化:键和包、文案、`present(view)`、进行中的操作,以及带成功文本的最新结果。`start` 和 `cancel` 按键路由到该账号的来源。 -[`dsh-api-remotes`](../../api/remotes/README.zh.md) 挂载生成的 `connectorAccounts` Remote。浏览器一半通过 `BrowserAccounts` 打开一条 `watch` 流;它的一个 store 保存按键索引的 Host 账号、流是否在推送,以及最新提示,同时记住本浏览器发起的操作。它为页面注册一个 `plugins.detail.badge` 条目和一个 `shell.overlay` 提示,并为每个带包名的账号注册以包名为键的 `plugins.bundle.config` 和 `plugins.bundle.activation`,全部使用 `connectorAccount` 命名空间。各界面收到 `start` 和 `cancel` 两个回调:它们调用 Remote,在 Host 拒绝或调用没有回应时 reject;按钮等待回调结果,并把启动的操作报告给 `BrowserAccounts`。Host 撤下的账号会失去其插件包条目;卸载时撤下所有条目和流。 +[`dsh-api-remotes`](../../api/remotes/README.zh.md) 挂载生成的 `connectorAccounts` Remote。浏览器一半通过 `BrowserAccounts` 打开一条 `watch` 流;它的一个 store 保存按键索引的 Host 账号、流是否在推送,以及最新提示,同时记住本浏览器发起的操作。它为页面注册一个 `plugins.detail.badge` 条目和一个 `shell.overlay` 提示,并为每个带包名的账号注册以包名为键的 `plugins.bundle.config` 和 `plugins.bundle.activation`,全部使用 `connectorAccount` 命名空间。各界面收到 `start` 和 `cancel` 两个回调:它们调用 Remote 并返回其结果;按钮把启动成功时返回的操作报告给 `BrowserAccounts`,结果为失败或调用被 reject 时报告失败提示。Host 撤下的账号会失去其插件包条目;卸载时撤下所有条目和流。 | 文件 | 职责 | |---|---| @@ -94,7 +94,7 @@ Host 一半 `ConnectorAccounts` 是一个 Remote 服务。`register()` 观察账 | [`src/client/state.ts`](src/client/state.ts) | 流的 store、本浏览器发起的操作,以及它们的页面和提示 | | [`src/client/components.tsx`](src/client/components.tsx) | 各界面的插槽条目,以及按钮的 Remote 调用 | | [`src/client/locales.ts`](src/client/locales.ts) | 共用字典 | -| [`src/client/types.ts`](src/client/types.ts) | 浏览器状态、提示、Remote 和 face 类型 | +| [`src/client/types.ts`](src/client/types.ts) | 浏览器状态、提示和 face 类型 |
diff --git a/packages/client/ui-connector-account/src/client/components.tsx b/packages/client/ui-connector-account/src/client/components.tsx index 483d8924ff..d931d4bb9a 100644 --- a/packages/client/ui-connector-account/src/client/components.tsx +++ b/packages/client/ui-connector-account/src/client/components.tsx @@ -43,22 +43,30 @@ function useAccountCommand( const [busy, setBusy] = useState(false) // A second click before the re-render still finds the first call pending. const pending = useRef(false) - const call = (operation: () => Promise): void => { + // `operation` resolves to whether the Host accepted the call. + const call = (operation: () => Promise): void => { if (pending.current) return pending.current = true setBusy(true) // The Host keeps the diagnostic; the page reports one retryable outcome. - void operation().catch(() => { face.failed() }).finally(() => { pending.current = false; setBusy(false) }) + void operation() + .then((accepted) => { if (!accepted) face.failed() }) + .catch(() => { face.failed() }) + .finally(() => { pending.current = false; setBusy(false) }) } const run = (entry: ConnectorAccountEntry, command: ConnectorAccountCommand): void => { const { key } = entry switch (command.kind) { case 'start': - call(async () => { face.follow(key, await face.start(key, command.operation)) }) + call(async () => { + const started = await face.start(key, command.operation) + if (started.ok) face.follow(key, started.value) + return started.ok + }) return case 'cancel': { const operation = entry.operation - if (operation !== undefined) call(async () => { await face.cancel(key, operation.id) }) + if (operation !== undefined) call(async () => (await face.cancel(key, operation.id)).ok) return } case 'open': diff --git a/packages/client/ui-connector-account/src/client/index.ts b/packages/client/ui-connector-account/src/client/index.ts index d0e9f7cb05..e0e30d6285 100644 --- a/packages/client/ui-connector-account/src/client/index.ts +++ b/packages/client/ui-connector-account/src/client/index.ts @@ -10,7 +10,6 @@ import type {} from '@deepseek-ai/dsh-client-locale/client' import type {} from '@deepseek-ai/dsh-client-ui-layout/client' import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client' import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' -import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' import { ConnectorAccountActivationEntry, ConnectorAccountBadgeEntry, ConnectorAccountSectionEntry, ConnectorAccountToastEntry, } from './components.tsx' @@ -26,13 +25,6 @@ export type { /** The `connectorAccounts` Remote that `dsh-api-remotes` mounts, and the services the slot registrations need. */ export const inject = ['remote', 'remote.connectorAccounts', 'slots', 'locale'] -/** The value of a Remote call, or a rejection with the Host's message when the Host refused it. */ -async function settle(call: Promise>): Promise { - const result = await call - if (!result.ok) throw new Error(result.error.message) - return result.value -} - function registerBundle(ctx: Context, face: ConnectorAccountFace, packageName: string, account: string): () => void { const bundle = { ...face, account } const dispose = ctx.effect(function* () { @@ -58,8 +50,8 @@ export function apply(ctx: Context): void { ctx.effect(() => async () => { await browser.dispose() }, 'connector-account: stream') const face: ConnectorAccountFace = { hooks: { connectorAccounts: browser.state }, - start: (key, operation) => settle(remote.start(key, operation)), - cancel: (key, id) => settle(remote.cancel(key, id)), + start: (key, operation) => remote.start(key, operation), + cancel: (key, id) => remote.cancel(key, id), resolveText: text => ctx.locale.resolveText(text), follow: (key, id) => { browser.follow(key, id) }, failed: () => { browser.failed() }, diff --git a/packages/client/ui-connector-account/src/client/state.ts b/packages/client/ui-connector-account/src/client/state.ts index 332715e431..7a061d98dc 100644 --- a/packages/client/ui-connector-account/src/client/state.ts +++ b/packages/client/ui-connector-account/src/client/state.ts @@ -4,10 +4,11 @@ */ import type { Context } from '@deepseek-ai/cordis' import type { RemoteStream } from '@deepseek-ai/dsh-api-gateway/client' +import type { ClientRemote } from '@deepseek-ai/dsh-api-remotes/client' import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store' import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' import type { ConnectorAccountEntry, ConnectorAccountsView, ConnectorOperationId } from '../types.ts' -import type { ConnectorAccountNotice, ConnectorAccountsRemote, ConnectorAccountsState } from './types.ts' +import type { ConnectorAccountNotice, ConnectorAccountsState } from './types.ts' const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '[::1]']) @@ -45,7 +46,7 @@ export class BrowserAccounts { * @param ctx - the browser context carrying the Remote client. * @param remote - the `connectorAccounts` Remote. */ - constructor(private readonly ctx: Context, remote: Pick) { + constructor(private readonly ctx: Context, remote: Pick) { this.stream = ctx.remote.$stream({ name: 'Connector accounts', open: signal => remote.watch(signal), ended: () => new Error('Connector accounts stream ended'), diff --git a/packages/client/ui-connector-account/src/client/types.ts b/packages/client/ui-connector-account/src/client/types.ts index 89a7a333b0..afff7bc9ad 100644 --- a/packages/client/ui-connector-account/src/client/types.ts +++ b/packages/client/ui-connector-account/src/client/types.ts @@ -1,8 +1,8 @@ /** Browser-side state and face of the accounts the Plugins page shows. */ +import type { ClientRemote } from '@deepseek-ai/dsh-api-remotes/client' import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots' import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' -import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' -import type { ConnectorAccountEntry, ConnectorAccountsView, ConnectorOperationId } from '../types.ts' +import type { ConnectorAccountEntry, ConnectorOperationId } from '../types.ts' /** A transient outcome the page reports outside its own lifetime; `seq` distinguishes repeats. */ export type ConnectorAccountNotice = @@ -18,23 +18,16 @@ export interface ConnectorAccountsState { readonly notice: ConnectorAccountNotice | undefined } -/** The `connectorAccounts` Remote methods the page uses. */ -export interface ConnectorAccountsRemote { - watch(signal: AbortSignal): AsyncIterable - start(key: string, operation: string): Promise> - cancel(key: string, id: ConnectorOperationId): Promise> -} - /** The face every surface entry injects. */ export interface ConnectorAccountFace { hooks: { connectorAccounts: HostObservable } /** - * Start an operation of an account on the Host. Resolves to the operation the Host started, and rejects when the Host - * refuses or the call does not answer. + * Start an operation of an account on the Host. The Remote result carries the operation the Host started, or the + * failure when the Host refuses or the call does not answer. */ - readonly start: (key: string, operation: string) => Promise - /** Cancel an account's operation on the Host; rejects like `start`. */ - readonly cancel: (key: string, id: ConnectorOperationId) => Promise + readonly start: ClientRemote['connectorAccounts']['start'] + /** Cancel an account's operation on the Host; the Remote result carries a failure like `start`. */ + readonly cancel: ClientRemote['connectorAccounts']['cancel'] /** Pick the active language's entry of a registrant's text. */ readonly resolveText: (text: LocalizedText) => string /** Remember an operation this browser started: its authorization page opens here, and its success is reported here. */ diff --git a/packages/client/ui-connector-account/tests/apply.client.spec.ts b/packages/client/ui-connector-account/tests/apply.client.spec.ts index 6c6ad38b68..4dda30bb1c 100644 --- a/packages/client/ui-connector-account/tests/apply.client.spec.ts +++ b/packages/client/ui-connector-account/tests/apply.client.spec.ts @@ -126,13 +126,14 @@ it('shows one tag and one notice entry for the page and each bundle\'s section a expect(faceOf(toast).hooks.connectorAccounts).toBe(face.hooks.connectorAccounts) expect([...face.hooks.connectorAccounts.getSnapshot().accounts.keys()]).toEqual([FIXTURE, OTHER, 'mcp:custom']) expect(face.resolveText({ en: 'Connected', zh: '已连接' })).toBe('Connected') - expect(await face.start(FIXTURE, 'connect')).toBe(OP) + expect(await face.start(FIXTURE, 'connect')).toEqual({ ok: true, value: OP }) expect(b.start).toHaveBeenCalledWith(FIXTURE, 'connect') - await face.cancel(FIXTURE, OP) + expect(await face.cancel(FIXTURE, OP)).toEqual({ ok: true, value: undefined }) expect(b.cancel).toHaveBeenCalledWith(FIXTURE, OP) - // A refusal reaches the buttons as a rejection with the Host's message. - b.start.mockResolvedValueOnce({ ok: false, error: new RemoteError('gateway/internal', 'offline', {}) } as never) - await expect(face.start(FIXTURE, 'connect')).rejects.toThrow('offline') + // A refusal reaches the buttons as the Remote's result. + const refused: RemoteResult = { ok: false, error: new RemoteError('gateway/internal', 'offline', {}) } + b.start.mockResolvedValueOnce(refused) + expect(await face.start(FIXTURE, 'connect')).toBe(refused) face.follow(FIXTURE, OP) face.failed() expect(face.hooks.connectorAccounts.getSnapshot().notice).toEqual({ seq: 1, kind: 'action-failed' }) diff --git a/packages/client/ui-connector-account/tests/components.client.spec.tsx b/packages/client/ui-connector-account/tests/components.client.spec.tsx index 222db693f6..8e645a7bc4 100644 --- a/packages/client/ui-connector-account/tests/components.client.spec.tsx +++ b/packages/client/ui-connector-account/tests/components.client.spec.tsx @@ -4,18 +4,21 @@ import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' import type { PluginsSubject } from '@deepseek-ai/dsh-client-ui-plugin-manager/client' import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' +import { RemoteError, type RemoteResult } from '@deepseek-ai/dsh-typert-protocol' import { afterEach, expect, it, onTestFinished, vi } from 'vitest' import { ConnectorAccountActivationEntry, ConnectorAccountBadgeEntry, ConnectorAccountSectionEntry, ConnectorAccountToastEntry, } from '../src/client/components.tsx' import { zh } from '../src/client/locales.ts' -import type { ConnectorAccountsState } from '../src/client/types.ts' +import type { ConnectorAccountFace, ConnectorAccountsState } from '../src/client/types.ts' import type { ConnectorAccountDisplay, ConnectorAccountEntry, ConnectorOperationId } from '../src/types.ts' afterEach(cleanup) const KEY = '@acme/fixture' const OP = 'op-1' as ConnectorOperationId +const STARTED: RemoteResult = { ok: true, value: OP } +const REFUSED: RemoteResult = { ok: false, error: new RemoteError('gateway/internal', 'offline', {}) } const t = makeTranslate(zh) const resolveText = (text: LocalizedText): string => typeof text === 'string' ? text : text.zh ?? text.en const button = (name: string) => screen.getByRole('button', { name }) @@ -41,8 +44,8 @@ function face(change: Partial = {}, accounts: readonly C } return { useConnectorAccounts: (selector: (value: ConnectorAccountsState) => R): R => selector(current), - start: vi.fn(async (_key: string, _operation: string) => OP), - cancel: vi.fn(async (_key: string, _id: ConnectorOperationId) => {}), + start: vi.fn(async () => STARTED), + cancel: vi.fn(async () => ({ ok: true, value: undefined })), account: KEY, resolveText, follow: vi.fn(), failed: vi.fn(), dismissNotice: vi.fn(), t, } } @@ -67,12 +70,12 @@ it('shows the registrant title, status, detail, notes, and hint, and starts each it('disables the buttons while a call is pending or the Host stream is down', async () => { const props = face() - const answer = Promise.withResolvers() + const answer = Promise.withResolvers>() props.start.mockReturnValueOnce(answer.promise) render() fireEvent.click(button('连接演示')) expect(disabled()).toEqual([true]) - await act(async () => { answer.resolve(OP) }) + await act(async () => { answer.resolve(STARTED) }) expect(disabled()).toEqual([false]) expect(props.failed).not.toHaveBeenCalled() cleanup() @@ -127,11 +130,13 @@ it.each<[string, ConnectorAccountDisplay['failure'], string]>([ expect(screen.getByRole('alert').textContent).toBe(expected) }) -it('reports a start that the Host refused or that never answered, without following it', async () => { +it('reports a start whose result is a failure or whose call rejected, without following it', async () => { const props = face() - props.start.mockRejectedValueOnce(new Error('offline')).mockRejectedValueOnce(new Error('carrier lost')) + props.start.mockResolvedValueOnce(REFUSED).mockRejectedValueOnce(new Error('Remote method is no longer mounted')) render() await click('连接演示') + expect(props.failed).toHaveBeenCalledOnce() + expect(disabled()).toEqual([false]) await click('连接演示') expect(props.failed).toHaveBeenCalledTimes(2) expect(props.follow).not.toHaveBeenCalled() @@ -150,6 +155,10 @@ it('cancels the operation in progress and opens its authorization page again on expect(windowOpen).toHaveBeenCalledWith('https://example.com/a', '_blank', 'noopener,noreferrer') await click('取消') expect(props.cancel).toHaveBeenCalledWith(KEY, OP) + expect(props.failed).not.toHaveBeenCalled() + props.cancel.mockResolvedValueOnce(REFUSED) + await click('取消') + expect(props.failed).toHaveBeenCalledOnce() // A cancel button with no operation in progress calls nothing. cleanup() const idle = sectionOf(display) @@ -216,12 +225,12 @@ it('connects from the prompt through the operation the display names, or only op it('starts once for a second click before the first call answers', async () => { const props = sectionOf({ ...DISCONNECTED, connect: { kind: 'start', operation: 'connect' } }) - const answer = Promise.withResolvers() + const answer = Promise.withResolvers>() props.start.mockReturnValueOnce(answer.promise) render(prompt(props)) fireEvent.click(button('连接演示')) fireEvent.click(button('连接演示')) - await act(async () => { answer.resolve(OP) }) + await act(async () => { answer.resolve(STARTED) }) expect(props.start).toHaveBeenCalledOnce() expect(props.follow).toHaveBeenCalledOnce() }) From 3e42e0f61716b8da672b71b73b0ec1bdfa697906 Mon Sep 17 00:00:00 2001 From: ZiyaZhang <199893125+ZiyaZhang@users.noreply.github.com> Date: Sun, 15 Nov 2026 23:26:13 -0800 Subject: [PATCH 22/31] feat(ui-schedule): recommend a weekly review task The empty automation page lists an eighth built-in recommendation, Weekly review, after Daily brief. Its request asks for a Friday 16:00 task that reviews the week's changes in the current workspace, lists unfinished work and what to do first next week, covers commits and pull requests when the workspace is a code repository, and summarizes in the conversation without changing workspace files. Its tile draws a calendar with a check in the style of the other glyphs, and the copy covers all eight UI languages. --- .../schedule-recommendations-en.expected.md | 2 ++ .../schedule-recommendations-zh.expected.md | 2 ++ apps/web/tests/schedule-manual.e2e.ts | 2 +- packages/client/ui-schedule/README.i18n.yaml | 4 +-- packages/client/ui-schedule/README.md | 2 +- packages/client/ui-schedule/README.zh.md | 2 +- .../src/client/RecommendationArtwork.tsx | 17 ++++++++++ .../src/client/ScheduleRecommendations.tsx | 3 +- .../src/client/recommendation-locales.ts | 32 +++++++++++++++++++ .../tests/browser-plugin.client.spec.ts | 6 ++-- .../tests/task-manager-page.client.spec.tsx | 4 +-- 11 files changed, 65 insertions(+), 11 deletions(-) diff --git a/apps/web/tests/expected/schedule-recommendations-en.expected.md b/apps/web/tests/expected/schedule-recommendations-en.expected.md index 57a00d021e..b11eeadea2 100644 --- a/apps/web/tests/expected/schedule-recommendations-en.expected.md +++ b/apps/web/tests/expected/schedule-recommendations-en.expected.md @@ -3,6 +3,8 @@ - list: - listitem: - button "Daily brief": Daily brief Recent changes in the workspace and what needs follow-up, with what to do first today. Weekdays at 9:00 + - listitem: + - button "Weekly review": Weekly review This week's changes in the workspace, with loose ends and what to do first next week. Fridays at {{clock}} - listitem: - button "Issue scan": Issue scan Sort new issues into bugs, requests, and questions, and flag duplicates and ones that need a reply. Weekdays at {{clock}} - listitem: diff --git a/apps/web/tests/expected/schedule-recommendations-zh.expected.md b/apps/web/tests/expected/schedule-recommendations-zh.expected.md index 68c90f0426..f4d7e76203 100644 --- a/apps/web/tests/expected/schedule-recommendations-zh.expected.md +++ b/apps/web/tests/expected/schedule-recommendations-zh.expected.md @@ -3,6 +3,8 @@ - list: - listitem: - button "每日简报": 每日简报 汇总工作区最近的变化和待跟进的事,列出今天先做什么。 工作日 9:00 + - listitem: + - button "每周回顾": 每周回顾 回顾这周工作区的变化,列出没收尾的事和下周先做什么。 周五 {{clock}} - listitem: - button "Issue 扫描": Issue 扫描 把新开的 issue 分成 bug、需求、提问,标出重复的和需要回复的。 工作日 {{clock}} - listitem: diff --git a/apps/web/tests/schedule-manual.e2e.ts b/apps/web/tests/schedule-manual.e2e.ts index abf438f7e8..46b52df29f 100644 --- a/apps/web/tests/schedule-manual.e2e.ts +++ b/apps/web/tests/schedule-manual.e2e.ts @@ -71,7 +71,7 @@ it.each([ const recommendations = manager.getByRole('region', { name: copy.heading, exact: true }) const recommendation = recommendations.getByRole('button', { name: copy.title, exact: true }) await recommendation.waitFor() - expect(await recommendations.getByRole('button').count()).toBe(7) + expect(await recommendations.getByRole('button').count()).toBe(8) if (draft === '') { expect(await recommendationColumns(recommendations)).toBe(2) await compareOrRefreshGolden( diff --git a/packages/client/ui-schedule/README.i18n.yaml b/packages/client/ui-schedule/README.i18n.yaml index 3745e445aa..e851c470e1 100644 --- a/packages/client/ui-schedule/README.i18n.yaml +++ b/packages/client/ui-schedule/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 405b30feaf48c087 /deepseek-ai-dsh-client-ui-schedule/use-this-package: - en: ff9e353f9330cf8d - zh: 61b0656261a69d4d + en: ac56ad367cd6624f + zh: 47642dc177dd0b58 /deepseek-ai-dsh-client-ui-schedule/use-this-package/time-zone-data-source: en: 4005b800e930f581 zh: ccb9318dad7f7e8f diff --git a/packages/client/ui-schedule/README.md b/packages/client/ui-schedule/README.md index b313e1e810..0776f904f4 100644 --- a/packages/client/ui-schedule/README.md +++ b/packages/client/ui-schedule/README.md @@ -27,7 +27,7 @@ The Automation tasks page and right Sidebar task tab use the same editor for tas Below 768px, the task list uses 20px horizontal insets, matching the Plugins page. -The shipped Web composition mounts `ui-schedule` with Host Schedule. The Automation tasks sidebar entry opens the task list without selecting or activating a Session. New and the adjacent menu's Create in a session action both open a new conversation with a short task-creation prompt in the current UI language, ready for the user to complete and send. When a blank conversation is reused, the prompt is appended on a new line, preserving its text, inline references, and attachments. The same menu offers Create manually. Manual creation opens the same editor as an existing task, validates required fields, and saves a task without starting an Agent or sending the instruction. A failed request leaves the form and its values visible. The empty state shows a decorative document-and-clock illustration whose colors follow the theme. Below the empty Enabled and All views, seven built-in recommended tasks appear in two columns, each with a glyph, title, description, and default run time. Choosing one opens a new conversation with that task's request prefilled in the same way. Each glyph tile takes the empty-state artwork's background color, and its glyph is drawn in blue with a light blue fill. +The shipped Web composition mounts `ui-schedule` with Host Schedule. The Automation tasks sidebar entry opens the task list without selecting or activating a Session. New and the adjacent menu's Create in a session action both open a new conversation with a short task-creation prompt in the current UI language, ready for the user to complete and send. When a blank conversation is reused, the prompt is appended on a new line, preserving its text, inline references, and attachments. The same menu offers Create manually. Manual creation opens the same editor as an existing task, validates required fields, and saves a task without starting an Agent or sending the instruction. A failed request leaves the form and its values visible. The empty state shows a decorative document-and-clock illustration whose colors follow the theme. Below the empty Enabled and All views, eight built-in recommended tasks appear in two columns, each with a glyph, title, description, and default run time. Choosing one opens a new conversation with that task's request prefilled in the same way. Each glyph tile takes the empty-state artwork's background color, and its glyph is drawn in blue with a light blue fill. Enabled, Paused, Ended, and All filters combine with text search over the title, prompt, and linked Session id; the page starts on Enabled. The search-row menu clears all ended tasks after confirmation, preserving active and paused tasks. Selecting a task opens its editable Rules / Records page. Save is enabled only for valid, meaningful changes and sends only changed fields with `expectedUpdatedAt`, or `null` when no stored revision exists. The fields stay editable after saving. Unsaved drafts survive navigation between tasks and away from the page. A conflict retains the whole draft and disables Save. Review with my edits reapplies the changed field groups to the latest values for review before saving; Discard replaces the draft with the latest stored values. For a new task, Discard closes the editor. Late responses cannot change another task's detail. Coarse-pointer search, instruction, and timing fields use 16px text to prevent focus zoom on iOS Safari. diff --git a/packages/client/ui-schedule/README.zh.md b/packages/client/ui-schedule/README.zh.md index 3e108eb805..775887d4e7 100644 --- a/packages/client/ui-schedule/README.zh.md +++ b/packages/client/ui-schedule/README.zh.md @@ -27,7 +27,7 @@ kind: "package-reference" 宽度小于 768px 时,任务列表使用 20px 的左右内边距,与插件页一致。 -发布的 Web 组合将 `ui-schedule` 与宿主 Schedule 一起挂载。自动化任务侧栏入口打开任务列表,不选择或激活会话。“新建”和相邻菜单的“在会话中创建”都会进入新会话,按当前界面语言预填简短的任务创建提示,供用户补充并发送。若复用空白会话,提示会另起一行追加,保留原有文本、行内引用和附件。该菜单还提供“手动创建”。手动创建与已有任务打开同一编辑页,校验必填项并保存任务,不启动 Agent 或发送指令。请求失败时保留表单和已填内容。空态显示装饰性的文档与时钟插图,其颜色随主题变化。“已开启”和“全部”的空态下方以两列列出七个内置推荐任务,每项显示图标、标题、说明和默认运行时间。点击其中一项会同样进入新会话,并预填该任务的请求。推荐图标块使用空态插图的背景色,图标为蓝色线条加浅蓝填充。 +发布的 Web 组合将 `ui-schedule` 与宿主 Schedule 一起挂载。自动化任务侧栏入口打开任务列表,不选择或激活会话。“新建”和相邻菜单的“在会话中创建”都会进入新会话,按当前界面语言预填简短的任务创建提示,供用户补充并发送。若复用空白会话,提示会另起一行追加,保留原有文本、行内引用和附件。该菜单还提供“手动创建”。手动创建与已有任务打开同一编辑页,校验必填项并保存任务,不启动 Agent 或发送指令。请求失败时保留表单和已填内容。空态显示装饰性的文档与时钟插图,其颜色随主题变化。“已开启”和“全部”的空态下方以两列列出八个内置推荐任务,每项显示图标、标题、说明和默认运行时间。点击其中一项会同样进入新会话,并预填该任务的请求。推荐图标块使用空态插图的背景色,图标为蓝色线条加浅蓝填充。 “已开启”“已暂停”“已结束”“全部”筛选结合标题、指令和关联会话 id 搜索,默认显示已开启任务。搜索行菜单在确认后清除全部已结束任务,保留已开启和已暂停任务。选择任务直接打开可编辑的“规则 / 任务运行记录”页面。只有字段有效且有实际修改时才能保存;保存只发送变更字段及 `expectedUpdatedAt`,存储版本缺失时发送 `null`。保存后字段保持可编辑。切换任务或离开页面时保留未保存的草稿。冲突保留整份草稿并禁用保存。“保留修改并复核”将改过的字段组应用到最新值,供保存前复核;“放弃”用最新存储值替换草稿。对于新任务,“放弃”关闭编辑页。迟到响应不会改变其他任务详情。粗指针设备的搜索、指令和时间字段使用 16px 字号,避免 iOS Safari 聚焦时缩放。 diff --git a/packages/client/ui-schedule/src/client/RecommendationArtwork.tsx b/packages/client/ui-schedule/src/client/RecommendationArtwork.tsx index 909ec2f016..0c5ad0ebde 100644 --- a/packages/client/ui-schedule/src/client/RecommendationArtwork.tsx +++ b/packages/client/ui-schedule/src/client/RecommendationArtwork.tsx @@ -38,6 +38,23 @@ export function SunriseGlyph(props: TileGlyphProps): ReactNode { ) } +/** + * Calendar page with a check: a week in review. + * @param props - class of the root SVG. + * @returns the glyph. + */ +export function CalendarCheckGlyph(props: TileGlyphProps): ReactNode { + return ( + + + + + + + + ) +} + /** * Open-issue mark: a ring with a center dot. * @param props - class of the root SVG. diff --git a/packages/client/ui-schedule/src/client/ScheduleRecommendations.tsx b/packages/client/ui-schedule/src/client/ScheduleRecommendations.tsx index b130a538a4..8f3accdd29 100644 --- a/packages/client/ui-schedule/src/client/ScheduleRecommendations.tsx +++ b/packages/client/ui-schedule/src/client/ScheduleRecommendations.tsx @@ -3,13 +3,14 @@ import { useId, type ReactNode } from 'react' import { Button, IconClockOutlineRegular, IconPlusOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' import type { TaskManagerKey } from './task-manager-locales.ts' import { - BranchGlyph, CloudSunGlyph, DumbbellGlyph, IssueGlyph, NewspaperGlyph, PluginCheckGlyph, + BranchGlyph, CalendarCheckGlyph, CloudSunGlyph, DumbbellGlyph, IssueGlyph, NewspaperGlyph, PluginCheckGlyph, SunriseGlyph, type TileGlyphProps, } from './RecommendationArtwork.tsx' import css from './TaskManagerPage.module.css' const RECOMMENDATIONS = [ { id: 'dailyBrief', Glyph: SunriseGlyph }, + { id: 'weeklyReview', Glyph: CalendarCheckGlyph }, { id: 'issueScan', Glyph: IssueGlyph }, { id: 'pluginCompat', Glyph: PluginCheckGlyph }, { id: 'topicTracking', Glyph: NewspaperGlyph }, diff --git a/packages/client/ui-schedule/src/client/recommendation-locales.ts b/packages/client/ui-schedule/src/client/recommendation-locales.ts index ec965a647a..ab52e0392c 100644 --- a/packages/client/ui-schedule/src/client/recommendation-locales.ts +++ b/packages/client/ui-schedule/src/client/recommendation-locales.ts @@ -7,6 +7,10 @@ export const recommendationEn = { 'recommend.dailyBrief.description': 'Recent changes in the workspace and what needs follow-up, with what to do first today.', 'recommend.dailyBrief.schedule': 'Weekdays at 9:00', 'recommend.dailyBrief.prompt': 'Create an automation task named "Daily brief": every weekday at 9:00, review the last 24 hours of changes in the current workspace and list what needs my follow-up and what to do first today; when the workspace is a code repository, also cover new commits, pull requests awaiting my review, and failing CI.', + 'recommend.weeklyReview.title': 'Weekly review', + 'recommend.weeklyReview.description': 'This week\'s changes in the workspace, with loose ends and what to do first next week.', + 'recommend.weeklyReview.schedule': 'Fridays at 16:00', + 'recommend.weeklyReview.prompt': 'Create an automation task named "Weekly review": every Friday at 16:00, review this week\'s changes in the current workspace, summarize what got done, and list what is still unfinished and what to do first next week; when the workspace is a code repository, also cover this week\'s commits, merged pull requests, and pull requests still open. Summarize here only; do not change files in the workspace.', 'recommend.issueScan.title': 'Issue scan', 'recommend.issueScan.description': 'Sort new issues into bugs, requests, and questions, and flag duplicates and ones that need a reply.', 'recommend.issueScan.schedule': 'Weekdays at 10:00', @@ -40,6 +44,10 @@ export const recommendationZh: Record = { 'recommend.dailyBrief.description': '汇总工作区最近的变化和待跟进的事,列出今天先做什么。', 'recommend.dailyBrief.schedule': '工作日 9:00', 'recommend.dailyBrief.prompt': '创建一个名为「每日简报」的自动化任务:每个工作日 9:00 查看当前工作区过去 24 小时的变化,列出需要我跟进的事和今天先做的事;工作区是代码仓库时,也看新提交、待我评审的 PR 和失败的 CI。', + 'recommend.weeklyReview.title': '每周回顾', + 'recommend.weeklyReview.description': '回顾这周工作区的变化,列出没收尾的事和下周先做什么。', + 'recommend.weeklyReview.schedule': '周五 16:00', + 'recommend.weeklyReview.prompt': '创建一个名为「每周回顾」的自动化任务:每周五 16:00 回顾当前工作区这一周的变化,总结这周做了什么,列出还没收尾的事和下周先做的事;工作区是代码仓库时,也看这周的提交、合入的 PR 和还开着的 PR。只在这里汇总,不改工作区里的文件。', 'recommend.issueScan.title': 'Issue 扫描', 'recommend.issueScan.description': '把新开的 issue 分成 bug、需求、提问,标出重复的和需要回复的。', 'recommend.issueScan.schedule': '工作日 10:00', @@ -73,6 +81,10 @@ export const recommendationJa: Record = { 'recommend.dailyBrief.description': 'ワークスペースの最近の変化とフォローが必要なことをまとめ、今日最初にやることを挙げます。', 'recommend.dailyBrief.schedule': '平日 9:00', 'recommend.dailyBrief.prompt': '「デイリーブリーフィング」という名前の自動化タスクを作成してください。平日は毎日 9:00 に、現在のワークスペースの過去24時間の変化を確認し、私がフォローすべきことと今日最初にやることを挙げてください。ワークスペースがコードリポジトリの場合は、新しいコミット、私のレビュー待ちのプルリクエスト、失敗した CI も確認してください。', + 'recommend.weeklyReview.title': '週次レビュー', + 'recommend.weeklyReview.description': '今週のワークスペースの変化を振り返り、やり残したことと来週最初にやることを挙げます。', + 'recommend.weeklyReview.schedule': '毎週金曜日 16:00', + 'recommend.weeklyReview.prompt': '「週次レビュー」という名前の自動化タスクを作成してください。毎週金曜日の 16:00 に、現在のワークスペースの今週の変化を振り返り、今週やったことをまとめて、まだ終わっていないことと来週最初にやることを挙げてください。ワークスペースがコードリポジトリの場合は、今週のコミット、マージされたプルリクエスト、まだオープンのプルリクエストも確認してください。まとめはここでだけ行い、ワークスペースのファイルは変更しないでください。', 'recommend.issueScan.title': 'Issue スキャン', 'recommend.issueScan.description': '新しい Issue をバグ・要望・質問に分類し、重複しているものと返信が必要なものを指摘します。', 'recommend.issueScan.schedule': '平日 10:00', @@ -106,6 +118,10 @@ export const recommendationEs: Record = { 'recommend.dailyBrief.description': 'Cambios recientes en el espacio de trabajo y pendientes de seguimiento, con lo primero que hacer hoy.', 'recommend.dailyBrief.schedule': 'De lunes a viernes a las 9:00', 'recommend.dailyBrief.prompt': 'Crea una tarea de automatización llamada «Resumen diario»: de lunes a viernes a las 9:00, revisa los cambios de las últimas 24 horas en el espacio de trabajo actual y enumera lo que requiere mi seguimiento y lo primero que debo hacer hoy; si el espacio de trabajo es un repositorio de código, incluye también los commits nuevos, los pull requests pendientes de mi revisión y los fallos de CI.', + 'recommend.weeklyReview.title': 'Revisión semanal', + 'recommend.weeklyReview.description': 'Cambios de la semana en el espacio de trabajo, con lo pendiente y lo primero que hacer la próxima semana.', + 'recommend.weeklyReview.schedule': 'Los viernes a las 16:00', + 'recommend.weeklyReview.prompt': 'Crea una tarea de automatización llamada «Revisión semanal»: todos los viernes a las 16:00, repasa los cambios de esta semana en el espacio de trabajo actual, resume lo que se hizo y enumera lo que queda pendiente y lo primero que debo hacer la próxima semana; si el espacio de trabajo es un repositorio de código, incluye también los commits de la semana, los pull requests fusionados y los que siguen abiertos. Haz el resumen solo aquí; no modifiques archivos del espacio de trabajo.', 'recommend.issueScan.title': 'Revisión de issues', 'recommend.issueScan.description': 'Clasifica los issues nuevos en bugs, solicitudes y preguntas, y señala los duplicados y los que necesitan respuesta.', 'recommend.issueScan.schedule': 'De lunes a viernes a las 10:00', @@ -139,6 +155,10 @@ export const recommendationFr: Record = { 'recommend.dailyBrief.description': 'Changements récents dans l\'espace de travail et points à suivre, avec les priorités du jour.', 'recommend.dailyBrief.schedule': 'Du lundi au vendredi à 9:00', 'recommend.dailyBrief.prompt': 'Crée une tâche d\'automatisation nommée « Résumé quotidien » : du lundi au vendredi à 9:00, passe en revue les changements des dernières 24 heures dans l\'espace de travail actuel et liste ce qui demande mon suivi et ce que je dois faire en premier aujourd\'hui ; si l\'espace de travail est un dépôt de code, couvre aussi les nouveaux commits, les pull requests en attente de ma revue et les échecs de CI.', + 'recommend.weeklyReview.title': 'Bilan hebdomadaire', + 'recommend.weeklyReview.description': 'Changements de la semaine dans l\'espace de travail, avec ce qui reste à terminer et les priorités de la semaine prochaine.', + 'recommend.weeklyReview.schedule': 'Le vendredi à 16:00', + 'recommend.weeklyReview.prompt': 'Crée une tâche d\'automatisation nommée « Bilan hebdomadaire » : tous les vendredis à 16:00, passe en revue les changements de la semaine dans l\'espace de travail actuel, résume ce qui a été fait et liste ce qui reste à terminer et ce que je dois faire en premier la semaine prochaine ; si l\'espace de travail est un dépôt de code, couvre aussi les commits de la semaine, les pull requests fusionnées et celles encore ouvertes. Fais le résumé ici uniquement ; ne modifie pas les fichiers de l\'espace de travail.', 'recommend.issueScan.title': 'Analyse des issues', 'recommend.issueScan.description': 'Trie les nouvelles issues en bugs, demandes et questions, et signale les doublons et celles qui nécessitent une réponse.', 'recommend.issueScan.schedule': 'Du lundi au vendredi à 10:00', @@ -172,6 +192,10 @@ export const recommendationDe: Record = { 'recommend.dailyBrief.description': 'Aktuelle Änderungen im Arbeitsbereich und offene Punkte, dazu, was heute zuerst ansteht.', 'recommend.dailyBrief.schedule': 'Mo–Fr um 9:00', 'recommend.dailyBrief.prompt': 'Erstelle eine Automatisierungsaufgabe namens „Tagesüberblick“: Prüfe montags bis freitags um 9:00 Uhr die Änderungen der letzten 24 Stunden im aktuellen Arbeitsbereich und liste auf, was ich nachverfolgen muss und was heute zuerst ansteht; ist der Arbeitsbereich ein Code-Repository, berücksichtige auch neue Commits, auf mein Review wartende Pull Requests und fehlgeschlagene CI-Läufe.', + 'recommend.weeklyReview.title': 'Wochenrückblick', + 'recommend.weeklyReview.description': 'Änderungen der Woche im Arbeitsbereich, dazu offene Punkte und was nächste Woche zuerst ansteht.', + 'recommend.weeklyReview.schedule': 'Freitags um 16:00', + 'recommend.weeklyReview.prompt': 'Erstelle eine Automatisierungsaufgabe namens „Wochenrückblick“: Blicke freitags um 16:00 Uhr auf die Änderungen dieser Woche im aktuellen Arbeitsbereich zurück, fasse zusammen, was erledigt wurde, und liste auf, was noch offen ist und was nächste Woche zuerst ansteht; ist der Arbeitsbereich ein Code-Repository, berücksichtige auch die Commits dieser Woche sowie gemergte und noch offene Pull Requests. Fasse alles nur hier zusammen; ändere keine Dateien im Arbeitsbereich.', 'recommend.issueScan.title': 'Issue-Sichtung', 'recommend.issueScan.description': 'Sortiert neue Issues in Bugs, Feature-Wünsche und Fragen und hebt Duplikate sowie Issues hervor, die eine Antwort brauchen.', 'recommend.issueScan.schedule': 'Mo–Fr um 10:00', @@ -205,6 +229,10 @@ export const recommendationRu: Record = { 'recommend.dailyBrief.description': 'Недавние изменения в рабочей области и то, что требует внимания, а также первоочередные дела на сегодня.', 'recommend.dailyBrief.schedule': 'По будням в 9:00', 'recommend.dailyBrief.prompt': 'Создай задачу автоматизации под названием «Ежедневная сводка»: по будням в 9:00 просматривай изменения в текущей рабочей области за последние 24 часа и перечисляй, что требует моего внимания и с чего начать сегодня; если рабочая область — репозиторий кода, учитывай также новые коммиты, пул-реквесты, ожидающие моего ревью, и сбои CI.', + 'recommend.weeklyReview.title': 'Еженедельный обзор', + 'recommend.weeklyReview.description': 'Изменения за неделю в рабочем пространстве, незавершённые дела и первоочередные задачи на следующую неделю.', + 'recommend.weeklyReview.schedule': 'По пятницам в 16:00', + 'recommend.weeklyReview.prompt': 'Создай задачу автоматизации под названием «Еженедельный обзор»: по пятницам в 16:00 просматривай изменения за эту неделю в текущем рабочем пространстве, подводи итог сделанного и перечисляй, что ещё не завершено и с чего начать на следующей неделе; если рабочее пространство — репозиторий кода, учитывай также коммиты за неделю, слитые и ещё открытые пул-реквесты. Сводку пиши только здесь; файлы в рабочем пространстве не меняй.', 'recommend.issueScan.title': 'Обзор issues', 'recommend.issueScan.description': 'Делит новые issues на баги, пожелания и вопросы и выделяет дубликаты и те, на которые нужно ответить.', 'recommend.issueScan.schedule': 'По будням в 10:00', @@ -238,6 +266,10 @@ export const recommendationPt: Record = { 'recommend.dailyBrief.description': 'Mudanças recentes no espaço de trabalho e o que precisa de acompanhamento, com o que fazer primeiro hoje.', 'recommend.dailyBrief.schedule': 'Segunda a sexta às 9:00', 'recommend.dailyBrief.prompt': 'Crie uma tarefa de automação chamada “Resumo diário”: de segunda a sexta às 9:00, revise as mudanças das últimas 24 horas no espaço de trabalho atual e liste o que precisa do meu acompanhamento e o que fazer primeiro hoje; se o espaço de trabalho for um repositório de código, inclua também os novos commits, os pull requests aguardando minha revisão e as falhas de CI.', + 'recommend.weeklyReview.title': 'Revisão semanal', + 'recommend.weeklyReview.description': 'Mudanças da semana no espaço de trabalho, com o que ficou pendente e o que fazer primeiro na próxima semana.', + 'recommend.weeklyReview.schedule': 'Sextas às 16:00', + 'recommend.weeklyReview.prompt': 'Crie uma tarefa de automação chamada “Revisão semanal”: toda sexta-feira às 16:00, revise as mudanças desta semana no espaço de trabalho atual, resuma o que foi feito e liste o que ainda está pendente e o que fazer primeiro na próxima semana; se o espaço de trabalho for um repositório de código, inclua também os commits da semana, os pull requests mesclados e os que continuam abertos. Faça o resumo só aqui; não altere arquivos do espaço de trabalho.', 'recommend.issueScan.title': 'Varredura de issues', 'recommend.issueScan.description': 'Classifica as novas issues em bugs, solicitações e perguntas e destaca as duplicadas e as que precisam de resposta.', 'recommend.issueScan.schedule': 'Segunda a sexta às 10:00', diff --git a/packages/client/ui-schedule/tests/browser-plugin.client.spec.ts b/packages/client/ui-schedule/tests/browser-plugin.client.spec.ts index b3a9ef6d76..acc5f78520 100644 --- a/packages/client/ui-schedule/tests/browser-plugin.client.spec.ts +++ b/packages/client/ui-schedule/tests/browser-plugin.client.spec.ts @@ -461,14 +461,14 @@ describe('ui-schedule browser half', () => { const panel = injectedFace(ctx.slots.entries('main')[0]!, undefined as never) as TaskManagerInjected for (const dictionary of Object.values(managerLocales)) { const prompts = Object.entries(dictionary).filter(([key]) => key.startsWith('recommend.') && key.endsWith('.prompt')) - expect(prompts).toHaveLength(7) + expect(prompts).toHaveLength(8) for (const [, prompt] of prompts) { expect(prompt).not.toContain('\n') panel.onUseRecommendation(prompt) expect(startSession).toHaveBeenLastCalledWith(undefined, { prompt, whenDraftExists: 'append' }) } } - expect(startSession).toHaveBeenCalledTimes(56) + expect(startSession).toHaveBeenCalledTimes(64) } finally { await fiber.dispose() owner() @@ -479,7 +479,7 @@ describe('ui-schedule browser half', () => { it('states each recommendation\'s shown run time in its request in every language', () => { for (const dictionary of Object.values(managerLocales)) { const schedules = Object.entries(dictionary).filter(([key]) => key.startsWith('recommend.') && key.endsWith('.schedule')) - expect(schedules).toHaveLength(7) + expect(schedules).toHaveLength(8) for (const [key, schedule] of schedules) { const times = schedule.match(/\d{1,2}:\d{2}/g) expect(times).toHaveLength(1) diff --git a/packages/client/ui-schedule/tests/task-manager-page.client.spec.tsx b/packages/client/ui-schedule/tests/task-manager-page.client.spec.tsx index 33eb9e2628..cc26dccb0d 100644 --- a/packages/client/ui-schedule/tests/task-manager-page.client.spec.tsx +++ b/packages/client/ui-schedule/tests/task-manager-page.client.spec.tsx @@ -840,8 +840,8 @@ describe('Task manager catalog', () => { expect(emptyNewTaskButton().textContent).toBe(en['empty.action']) }) - const RECOMMENDATION_IDS = ['dailyBrief', 'issueScan', 'pluginCompat', 'topicTracking', 'branchCleanup', - 'weather', 'workout'] as const + const RECOMMENDATION_IDS = ['dailyBrief', 'weeklyReview', 'issueScan', 'pluginCompat', 'topicTracking', + 'branchCleanup', 'weather', 'workout'] as const function recommendations(dictionary: Dictionary = en): HTMLElement | null { return screen.queryByRole('region', { name: dictionary['recommend.heading'] }) From 1e4b19e78e558c59efc22d2ceb5bf941dd7f6f7f Mon Sep 17 00:00:00 2001 From: gengruilin Date: Mon, 16 Nov 2026 15:35:37 +0800 Subject: [PATCH 23/31] chore(connector-account): match the root version 0.2.2-rc.3 --- packages/client/ui-connector-account/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/client/ui-connector-account/package.json b/packages/client/ui-connector-account/package.json index 25dcf492b8..cb95fb0c25 100644 --- a/packages/client/ui-connector-account/package.json +++ b/packages/client/ui-connector-account/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-connector-account", "description": "Connector account surfaces: the Host registry CLI app plugins and MCP connectors register their accounts with, and the Plugins page section, title tag, activation prompt, and notices it serves over one Remote", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.3", "publishConfig": { "access": "public" }, From d245f8e2858c7f411d6bbbb66f1bbfebde41e656 Mon Sep 17 00:00:00 2001 From: Turtle Date: Mon, 16 Nov 2026 15:55:46 +0800 Subject: [PATCH 24/31] feat(ci): close pull requests after 21 days without activity Refs #8432 --- .github/stale-pull-requests/remind.mjs | 66 ++++++++++++-------- .github/stale-pull-requests/remind.test.mjs | 67 +++++++++++++-------- .github/workflows/stale-pull-requests.yml | 10 +-- 3 files changed, 87 insertions(+), 56 deletions(-) diff --git a/.github/stale-pull-requests/remind.mjs b/.github/stale-pull-requests/remind.mjs index adff87f633..0b863dc865 100644 --- a/.github/stale-pull-requests/remind.mjs +++ b/.github/stale-pull-requests/remind.mjs @@ -1,24 +1,30 @@ /** - * Daily stale pull-request reminders for the `Stale pull requests` workflow. + * Daily stale pull-request reminders and closing for the `Stale pull requests` workflow. * * A pull request's last activity is the latest of its creation, a commit, a force push, a reopen or ready-for-review * event, and a comment or review from a non-bot account. Other timeline events, such as mentions, labels and cross - * references, do not count, so reminder comments never extend it. After 7 and 14 days without activity the workflow - * comments once per stage and mentions the author. Activity starts a new cycle. Pull requests labelled `DO_NOT_CLOSE` - * and pull requests opened by bots receive no reminders. The workflow never closes pull requests. + * references, do not count, so reminder and closing comments never extend it. After 7 and 14 days without activity the + * workflow comments once per stage and mentions the author. After 21 days without activity, and at least 7 days after + * the 14-day reminder, it comments and closes the pull request; the reminder therefore always gives the author 7 days' + * notice, including for pull requests that were already inactive when the workflow started. Activity, including + * reopening, starts a new cycle. Pull requests labelled `DO_NOT_CLOSE` and pull requests opened by bots are neither + * reminded nor closed. * * Each run reads the timeline of every open pull request that is neither exempt nor bot-authored, because `updated_at` - * also changes on events that are not activity. Each run posts at most `MAX_COMMENTS_PER_RUN` reminders, least recently + * also changes on events that are not activity. Each run posts at most `MAX_COMMENTS_PER_RUN` comments, least recently * updated pull requests first, so a backlog spreads over several days within GitHub's content-creation limits. A failed * pull request is reported and skipped. */ -/** Label that exempts a pull request from reminders. */ +/** Label that exempts a pull request from reminders and closing. */ export const EXEMPT_LABEL = 'DO_NOT_CLOSE' /** Days without activity after which each reminder is posted, in ascending order. */ export const REMINDER_DAYS = [7, 14] +/** Days without activity after which a pull request is closed. */ +export const CLOSE_DAYS = 21 + const DAY_MS = 24 * 60 * 60 * 1000 // GitHub asks integrations to wait at least one second between content-creating requests. const COMMENT_INTERVAL_MS = 1000 @@ -55,39 +61,44 @@ function activityTimes(event) { } /** - * Selects the reminder a pull request is due for. + * Selects the reminder or closing a pull request is due for. * @param {object} options * @param {string} options.createdAt Pull-request creation time. * @param {object[]} options.timeline Complete issue timeline of the pull request. * @param {Date} options.now Evaluation time. - * @returns {number | undefined} Due reminder stage in days, or `undefined` when none is due. + * @returns {number | undefined} Due stage in days, `CLOSE_DAYS` for closing, or `undefined` when nothing is due. */ -export function dueReminder({ createdAt, timeline, now }) { +export function dueStage({ createdAt, timeline, now }) { const times = [createdAt, ...timeline.flatMap(activityTimes)].map(time => Date.parse(time)).filter(Number.isFinite) const lastActivity = Math.max(...times) - const due = REMINDER_DAYS.filter(days => now.getTime() - lastActivity >= days * DAY_MS).at(-1) - if (due === undefined) return undefined const sent = timeline .filter(event => event.event === 'commented' && isBot(event.actor) && Date.parse(event.created_at) > lastActivity) - .map(event => Number(MARKER.exec(event.body ?? '')?.[1])) - return sent.some(days => days >= due) ? undefined : due + .map(event => ({ days: Number(MARKER.exec(event.body ?? '')?.[1]), at: Date.parse(event.created_at) })) + const finalReminder = REMINDER_DAYS.at(-1) + const noticeMs = (CLOSE_DAYS - finalReminder) * DAY_MS + if (now.getTime() - lastActivity >= CLOSE_DAYS * DAY_MS && sent.some(({ days, at }) => days === finalReminder && now.getTime() - at >= noticeMs)) { + return CLOSE_DAYS + } + const due = REMINDER_DAYS.filter(days => now.getTime() - lastActivity >= days * DAY_MS).at(-1) + if (due === undefined) return undefined + return sent.some(({ days }) => days >= due) ? undefined : due } /** - * Builds the reminder comment. + * Builds the reminder or closing comment. * @param {string} author Pull-request author login. - * @param {number} days Reminder stage in days. + * @param {number} days Stage in days; `CLOSE_DAYS` builds the closing comment. * @returns {string} Comment body. */ -export function reminderBody(author, days) { - return [ - ``, - `@${author} This pull request has had no activity for ${days} days. Please update it, reply to keep it open, or close it if it is no longer needed. Add the \`${EXEMPT_LABEL}\` label, or ask a maintainer to add it, to stop these reminders.`, - ].join('\n') +export function stageBody(author, days) { + const text = days === CLOSE_DAYS + ? `@${author} This pull request has had no activity for ${days} days and is now closed. Reopen it, or ask a maintainer to reopen it, if you continue the work.` + : `@${author} This pull request has had no activity for ${days} days. Please update it, reply to keep it open, or close it if it is no longer needed. Pull requests are closed after ${CLOSE_DAYS} days without activity and at least ${CLOSE_DAYS - REMINDER_DAYS.at(-1)} days after the ${REMINDER_DAYS.at(-1)}-day reminder. Add the \`${EXEMPT_LABEL}\` label, or ask a maintainer to add it, to stop reminders and closing.` + return `\n${text}` } /** - * Posts every due reminder on open pull requests of the workflow repository. + * Posts every due reminder and closes every due pull request among the open pull requests of the workflow repository. * @param {object} options * @param {object} options.github Authenticated Octokit client from `actions/github-script`. * @param {object} options.context Workflow context from `actions/github-script`. @@ -96,7 +107,7 @@ export function reminderBody(author, days) { * @param {(ms: number) => Promise} [options.sleep] Delay between comments. * @returns {Promise} */ -export async function remindStalePullRequests({ github, context, core, now = new Date(), sleep = ms => new Promise(resolve => setTimeout(resolve, ms)) }) { +export async function processStalePullRequests({ github, context, core, now = new Date(), sleep = ms => new Promise(resolve => setTimeout(resolve, ms)) }) { const { owner, repo } = context.repo const pulls = await github.paginate(github.rest.pulls.list, { owner, repo, state: 'open', sort: 'updated', direction: 'asc', per_page: 100 }) let posted = 0 @@ -107,12 +118,17 @@ export async function remindStalePullRequests({ github, context, core, now = new if (pull.labels.some(label => label.name === EXEMPT_LABEL)) continue try { const timeline = await github.paginate(github.rest.issues.listEventsForTimeline, { owner, repo, issue_number: pull.number, per_page: 100 }) - const days = dueReminder({ createdAt: pull.created_at, timeline, now }) + const days = dueStage({ createdAt: pull.created_at, timeline, now }) if (days === undefined) continue if (posted > 0) await sleep(COMMENT_INTERVAL_MS) - await github.rest.issues.createComment({ owner, repo, issue_number: pull.number, body: reminderBody(pull.user.login, days) }) + await github.rest.issues.createComment({ owner, repo, issue_number: pull.number, body: stageBody(pull.user.login, days) }) posted++ - core.info(`#${pull.number}: posted the ${days}-day reminder`) + if (days === CLOSE_DAYS) { + await github.rest.pulls.update({ owner, repo, pull_number: pull.number, state: 'closed' }) + core.info(`#${pull.number}: closed after ${days} days without activity`) + } else { + core.info(`#${pull.number}: posted the ${days}-day reminder`) + } } catch (error) { failed++ core.warning(`#${pull.number}: ${error.message}`) diff --git a/.github/stale-pull-requests/remind.test.mjs b/.github/stale-pull-requests/remind.test.mjs index cb2d56b437..be430e6576 100644 --- a/.github/stale-pull-requests/remind.test.mjs +++ b/.github/stale-pull-requests/remind.test.mjs @@ -1,47 +1,58 @@ import assert from 'node:assert/strict' import test from 'node:test' -import { dueReminder, reminderBody, remindStalePullRequests } from './remind.mjs' +import { dueStage, stageBody, processStalePullRequests } from './remind.mjs' const now = new Date('2026-11-30T00:00:00Z') const daysAgo = days => new Date(now.getTime() - days * 24 * 60 * 60 * 1000).toISOString() const human = { login: 'author', type: 'User' } const bot = { login: 'github-actions[bot]', type: 'Bot' } const comment = (actor, days, body = 'ok') => ({ event: 'commented', actor, created_at: daysAgo(days), body }) -const reminder = (days, stage) => comment(bot, days, reminderBody('author', stage)) +const reminder = (days, stage) => comment(bot, days, stageBody('author', stage)) test('no reminder is due within 7 days of the last activity', () => { - assert.equal(dueReminder({ createdAt: daysAgo(6), timeline: [], now }), undefined) - assert.equal(dueReminder({ createdAt: daysAgo(30), timeline: [comment(human, 6)], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(6), timeline: [], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(30), timeline: [comment(human, 6)], now }), undefined) }) test('the latest due stage is posted once after the last activity', () => { - assert.equal(dueReminder({ createdAt: daysAgo(7), timeline: [], now }), 7) - assert.equal(dueReminder({ createdAt: daysAgo(10), timeline: [reminder(3, 7)], now }), undefined) - assert.equal(dueReminder({ createdAt: daysAgo(14), timeline: [reminder(7, 7)], now }), 14) - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [], now }), 14) - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [reminder(20, 14)], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(7), timeline: [], now }), 7) + assert.equal(dueStage({ createdAt: daysAgo(10), timeline: [reminder(3, 7)], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(14), timeline: [reminder(7, 7)], now }), 14) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [], now }), 14) + assert.equal(dueStage({ createdAt: daysAgo(17), timeline: [reminder(3, 14)], now }), undefined) +}) + +test('a pull request closes after 21 days without activity and 7 days after the 14-day reminder', () => { + assert.equal(dueStage({ createdAt: daysAgo(21), timeline: [reminder(14, 7), reminder(7, 14)], now }), 21) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [reminder(20, 14)], now }), 21) + // A pull request that was already inactive gets the 14-day reminder first and 7 days' notice. + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [reminder(6, 14)], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [reminder(30, 7)], now }), 14) + // A 14-day reminder from before the last activity gives no notice. + assert.equal(dueStage({ createdAt: daysAgo(60), timeline: [reminder(40, 14), comment(human, 25)], now }), 14) }) test('human activity restarts the cycle and bot activity does not', () => { const sentBefore = [reminder(30, 7), reminder(23, 14)] - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, comment(human, 8)], now }), 7) - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'committed', committer: { date: daysAgo(3) } }], now }), undefined) - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'reviewed', user: human, submitted_at: daysAgo(3) }], now }), undefined) - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'line-commented', comments: [{ user: human, created_at: daysAgo(3) }] }], now }), undefined) - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'head_ref_force_pushed', actor: human, created_at: daysAgo(3) }], now }), undefined) - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, comment({ login: 'ci[bot]', type: 'Bot' }, 1)], now }), undefined) - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, comment({ login: 'ds-review-bot', type: 'User' }, 1)], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, comment(human, 8)], now }), 7) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'committed', committer: { date: daysAgo(3) } }], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'reviewed', user: human, submitted_at: daysAgo(3) }], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'line-commented', comments: [{ user: human, created_at: daysAgo(3) }] }], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'head_ref_force_pushed', actor: human, created_at: daysAgo(3) }], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'reopened', actor: human, created_at: daysAgo(3) }], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, comment({ login: 'ci[bot]', type: 'Bot' }, 1)], now }), 21) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, comment({ login: 'ds-review-bot', type: 'User' }, 1)], now }), 21) }) test('mentions, labels and cross references are not activity', () => { const at = (event, days) => ({ event, actor: human, created_at: daysAgo(days) }) // GitHub records a `mentioned` event for the author right after each reminder. - assert.equal(dueReminder({ createdAt: daysAgo(14), timeline: [reminder(7, 7), at('mentioned', 7 - 1e-5), at('subscribed', 7 - 1e-5)], now }), 14) - assert.equal(dueReminder({ createdAt: daysAgo(20), timeline: [at('labeled', 1), at('cross-referenced', 1), at('review_requested', 1)], now }), 14) + assert.equal(dueStage({ createdAt: daysAgo(14), timeline: [reminder(7, 7), at('mentioned', 7 - 1e-5), at('subscribed', 7 - 1e-5)], now }), 14) + assert.equal(dueStage({ createdAt: daysAgo(20), timeline: [at('labeled', 1), at('cross-referenced', 1), at('review_requested', 1)], now }), 14) }) -test('reminders mention the author and skip exempt and bot-authored pull requests', async () => { +test('reminders and closing mention the author and skip exempt and bot-authored pull requests', async () => { const pull = (number, overrides = {}) => ({ number, user: human, labels: [], created_at: daysAgo(20), updated_at: daysAgo(20), ...overrides }) const pulls = [ pull(1), @@ -51,12 +62,14 @@ test('reminders mention the author and skip exempt and bot-authored pull request pull(4, { updated_at: daysAgo(1) }), pull(6), pull(5), + pull(7, { created_at: daysAgo(30) }), ] const comments = [] + const closed = [] const timelines = [] const github = { rest: { - pulls: { list: 'pulls' }, + pulls: { list: 'pulls', update: async params => closed.push(params) }, issues: { listEventsForTimeline: 'timeline', createComment: async params => { @@ -68,20 +81,22 @@ test('reminders mention the author and skip exempt and bot-authored pull request paginate: async (method, params) => { if (method === 'pulls') return pulls timelines.push(params.issue_number) - return [] + return params.issue_number === 7 ? [reminder(9, 14)] : [] }, } const sleeps = [] const warnings = [] const failures = [] const core = { info() {}, warning: message => warnings.push(message), setFailed: message => failures.push(message) } - await remindStalePullRequests({ github, context: { repo: { owner: 'o', repo: 'r' } }, core, now, sleep: async ms => sleeps.push(ms) }) - assert.deepEqual(timelines, [1, 4, 6, 5]) + await processStalePullRequests({ github, context: { repo: { owner: 'o', repo: 'r' } }, core, now, sleep: async ms => sleeps.push(ms) }) + assert.deepEqual(timelines, [1, 4, 6, 5, 7]) assert.deepEqual(warnings, ['#6: locked']) assert.equal(failures.length, 1) - assert.deepEqual(comments.map(({ issue_number }) => issue_number), [1, 4, 5]) + assert.deepEqual(comments.map(({ issue_number }) => issue_number), [1, 4, 5, 7]) assert.match(comments[0].body, /^\n@author This pull request has had no activity for 14 days\./) - assert.deepEqual(sleeps, [1000, 1000, 1000]) + assert.match(comments[3].body, /^\n@author This pull request has had no activity for 21 days and is now closed\./) + assert.deepEqual(closed, [{ owner: 'o', repo: 'r', pull_number: 7, state: 'closed' }]) + assert.deepEqual(sleeps, [1000, 1000, 1000, 1000]) }) test('a run posts at most 100 reminders', async () => { @@ -91,6 +106,6 @@ test('a run posts at most 100 reminders', async () => { rest: { pulls: { list: 'pulls' }, issues: { listEventsForTimeline: 'timeline', createComment: async () => comments++ } }, paginate: async method => method === 'pulls' ? pulls : [], } - await remindStalePullRequests({ github, context: { repo: { owner: 'o', repo: 'r' } }, core: { info() {} }, now, sleep: async () => {} }) + await processStalePullRequests({ github, context: { repo: { owner: 'o', repo: 'r' } }, core: { info() {} }, now, sleep: async () => {} }) assert.equal(comments, 100) }) diff --git a/.github/workflows/stale-pull-requests.yml b/.github/workflows/stale-pull-requests.yml index a0ccb7f2b5..db1c3f8115 100644 --- a/.github/workflows/stale-pull-requests.yml +++ b/.github/workflows/stale-pull-requests.yml @@ -1,4 +1,4 @@ -# Reminds authors of open pull requests after 7 and 14 days without activity; never closes them. +# Reminds authors of open pull requests after 7 and 14 days without activity and closes them after 21 days. # Rules: .github/stale-pull-requests/remind.mjs. name: Stale pull requests @@ -16,7 +16,7 @@ concurrency: jobs: remind: - name: Remind stale pull requests + name: Remind and close stale pull requests runs-on: ubuntu-latest permissions: contents: read @@ -27,9 +27,9 @@ jobs: with: sparse-checkout: .github/stale-pull-requests persist-credentials: false - - name: Post due reminders + - name: Post due reminders and close stale pull requests uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 with: script: | - const { remindStalePullRequests } = await import(`${process.env.GITHUB_WORKSPACE}/.github/stale-pull-requests/remind.mjs`) - await remindStalePullRequests({ github, context, core }) + const { processStalePullRequests } = await import(`${process.env.GITHUB_WORKSPACE}/.github/stale-pull-requests/remind.mjs`) + await processStalePullRequests({ github, context, core }) From 00dcb5ec10c95b3c3e93ba3ca512fe3af4e5b014 Mon Sep 17 00:00:00 2001 From: Turtle Date: Mon, 16 Nov 2026 15:56:40 +0800 Subject: [PATCH 25/31] fix(ci): close stale pull requests before commenting --- .github/stale-pull-requests/remind.mjs | 9 +++------ .github/stale-pull-requests/remind.test.mjs | 18 +++++++++++++----- 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/.github/stale-pull-requests/remind.mjs b/.github/stale-pull-requests/remind.mjs index 0b863dc865..2545ec49c2 100644 --- a/.github/stale-pull-requests/remind.mjs +++ b/.github/stale-pull-requests/remind.mjs @@ -121,14 +121,11 @@ export async function processStalePullRequests({ github, context, core, now = ne const days = dueStage({ createdAt: pull.created_at, timeline, now }) if (days === undefined) continue if (posted > 0) await sleep(COMMENT_INTERVAL_MS) + // Closing first keeps a failed close from repeating the closing comment on later runs. + if (days === CLOSE_DAYS) await github.rest.pulls.update({ owner, repo, pull_number: pull.number, state: 'closed' }) await github.rest.issues.createComment({ owner, repo, issue_number: pull.number, body: stageBody(pull.user.login, days) }) posted++ - if (days === CLOSE_DAYS) { - await github.rest.pulls.update({ owner, repo, pull_number: pull.number, state: 'closed' }) - core.info(`#${pull.number}: closed after ${days} days without activity`) - } else { - core.info(`#${pull.number}: posted the ${days}-day reminder`) - } + core.info(days === CLOSE_DAYS ? `#${pull.number}: closed after ${days} days without activity` : `#${pull.number}: posted the ${days}-day reminder`) } catch (error) { failed++ core.warning(`#${pull.number}: ${error.message}`) diff --git a/.github/stale-pull-requests/remind.test.mjs b/.github/stale-pull-requests/remind.test.mjs index be430e6576..b8573b7c70 100644 --- a/.github/stale-pull-requests/remind.test.mjs +++ b/.github/stale-pull-requests/remind.test.mjs @@ -63,13 +63,20 @@ test('reminders and closing mention the author and skip exempt and bot-authored pull(6), pull(5), pull(7, { created_at: daysAgo(30) }), + pull(8, { created_at: daysAgo(30) }), ] const comments = [] const closed = [] const timelines = [] const github = { rest: { - pulls: { list: 'pulls', update: async params => closed.push(params) }, + pulls: { + list: 'pulls', + update: async params => { + if (params.pull_number === 8) throw new Error('close failed') + closed.push(params) + }, + }, issues: { listEventsForTimeline: 'timeline', createComment: async params => { @@ -81,7 +88,7 @@ test('reminders and closing mention the author and skip exempt and bot-authored paginate: async (method, params) => { if (method === 'pulls') return pulls timelines.push(params.issue_number) - return params.issue_number === 7 ? [reminder(9, 14)] : [] + return [7, 8].includes(params.issue_number) ? [reminder(9, 14)] : [] }, } const sleeps = [] @@ -89,14 +96,15 @@ test('reminders and closing mention the author and skip exempt and bot-authored const failures = [] const core = { info() {}, warning: message => warnings.push(message), setFailed: message => failures.push(message) } await processStalePullRequests({ github, context: { repo: { owner: 'o', repo: 'r' } }, core, now, sleep: async ms => sleeps.push(ms) }) - assert.deepEqual(timelines, [1, 4, 6, 5, 7]) - assert.deepEqual(warnings, ['#6: locked']) + assert.deepEqual(timelines, [1, 4, 6, 5, 7, 8]) + // A failed close posts no closing comment, so the next run retries without repeating it. + assert.deepEqual(warnings, ['#6: locked', '#8: close failed']) assert.equal(failures.length, 1) assert.deepEqual(comments.map(({ issue_number }) => issue_number), [1, 4, 5, 7]) assert.match(comments[0].body, /^\n@author This pull request has had no activity for 14 days\./) assert.match(comments[3].body, /^\n@author This pull request has had no activity for 21 days and is now closed\./) assert.deepEqual(closed, [{ owner: 'o', repo: 'r', pull_number: 7, state: 'closed' }]) - assert.deepEqual(sleeps, [1000, 1000, 1000, 1000]) + assert.deepEqual(sleeps, [1000, 1000, 1000, 1000, 1000]) }) test('a run posts at most 100 reminders', async () => { From e8473dbb606940fc7118bc09beaa1deec1559a43 Mon Sep 17 00:00:00 2001 From: Turtle Date: Mon, 16 Nov 2026 16:06:37 +0800 Subject: [PATCH 26/31] fix(ci): require a closing notice and retry failed closes --- .github/stale-pull-requests/remind.mjs | 29 ++++++++++++--------- .github/stale-pull-requests/remind.test.mjs | 19 ++++++++++---- 2 files changed, 31 insertions(+), 17 deletions(-) diff --git a/.github/stale-pull-requests/remind.mjs b/.github/stale-pull-requests/remind.mjs index 2545ec49c2..fb625e0d85 100644 --- a/.github/stale-pull-requests/remind.mjs +++ b/.github/stale-pull-requests/remind.mjs @@ -29,7 +29,8 @@ const DAY_MS = 24 * 60 * 60 * 1000 // GitHub asks integrations to wait at least one second between content-creating requests. const COMMENT_INTERVAL_MS = 1000 const MAX_COMMENTS_PER_RUN = 100 -const MARKER = // +// Reminders posted before closing existed use `stale-pr-reminder` and announce no closing, so they are ignored. +const MARKER = // // Review bots that use ordinary user accounts. const BOT_LOGINS = new Set(['ds-review-bot']) @@ -66,7 +67,9 @@ function activityTimes(event) { * @param {string} options.createdAt Pull-request creation time. * @param {object[]} options.timeline Complete issue timeline of the pull request. * @param {Date} options.now Evaluation time. - * @returns {number | undefined} Due stage in days, `CLOSE_DAYS` for closing, or `undefined` when nothing is due. + * @returns {{ days: number, comment: boolean } | undefined} Due stage in days, `CLOSE_DAYS` for closing, and whether its + * comment is still unposted; `undefined` when nothing is due. A closing whose comment was posted but whose close failed + * is due again without a comment. */ export function dueStage({ createdAt, timeline, now }) { const times = [createdAt, ...timeline.flatMap(activityTimes)].map(time => Date.parse(time)).filter(Number.isFinite) @@ -77,11 +80,11 @@ export function dueStage({ createdAt, timeline, now }) { const finalReminder = REMINDER_DAYS.at(-1) const noticeMs = (CLOSE_DAYS - finalReminder) * DAY_MS if (now.getTime() - lastActivity >= CLOSE_DAYS * DAY_MS && sent.some(({ days, at }) => days === finalReminder && now.getTime() - at >= noticeMs)) { - return CLOSE_DAYS + return { days: CLOSE_DAYS, comment: !sent.some(({ days }) => days === CLOSE_DAYS) } } const due = REMINDER_DAYS.filter(days => now.getTime() - lastActivity >= days * DAY_MS).at(-1) - if (due === undefined) return undefined - return sent.some(({ days }) => days >= due) ? undefined : due + if (due === undefined || sent.some(({ days }) => days >= due)) return undefined + return { days: due, comment: true } } /** @@ -94,7 +97,7 @@ export function stageBody(author, days) { const text = days === CLOSE_DAYS ? `@${author} This pull request has had no activity for ${days} days and is now closed. Reopen it, or ask a maintainer to reopen it, if you continue the work.` : `@${author} This pull request has had no activity for ${days} days. Please update it, reply to keep it open, or close it if it is no longer needed. Pull requests are closed after ${CLOSE_DAYS} days without activity and at least ${CLOSE_DAYS - REMINDER_DAYS.at(-1)} days after the ${REMINDER_DAYS.at(-1)}-day reminder. Add the \`${EXEMPT_LABEL}\` label, or ask a maintainer to add it, to stop reminders and closing.` - return `\n${text}` + return `\n${text}` } /** @@ -118,13 +121,15 @@ export async function processStalePullRequests({ github, context, core, now = ne if (pull.labels.some(label => label.name === EXEMPT_LABEL)) continue try { const timeline = await github.paginate(github.rest.issues.listEventsForTimeline, { owner, repo, issue_number: pull.number, per_page: 100 }) - const days = dueStage({ createdAt: pull.created_at, timeline, now }) - if (days === undefined) continue - if (posted > 0) await sleep(COMMENT_INTERVAL_MS) - // Closing first keeps a failed close from repeating the closing comment on later runs. + const stage = dueStage({ createdAt: pull.created_at, timeline, now }) + if (stage === undefined) continue + const { days } = stage + if (stage.comment) { + if (posted > 0) await sleep(COMMENT_INTERVAL_MS) + await github.rest.issues.createComment({ owner, repo, issue_number: pull.number, body: stageBody(pull.user.login, days) }) + posted++ + } if (days === CLOSE_DAYS) await github.rest.pulls.update({ owner, repo, pull_number: pull.number, state: 'closed' }) - await github.rest.issues.createComment({ owner, repo, issue_number: pull.number, body: stageBody(pull.user.login, days) }) - posted++ core.info(days === CLOSE_DAYS ? `#${pull.number}: closed after ${days} days without activity` : `#${pull.number}: posted the ${days}-day reminder`) } catch (error) { failed++ diff --git a/.github/stale-pull-requests/remind.test.mjs b/.github/stale-pull-requests/remind.test.mjs index b8573b7c70..c6033e1fc5 100644 --- a/.github/stale-pull-requests/remind.test.mjs +++ b/.github/stale-pull-requests/remind.test.mjs @@ -1,7 +1,7 @@ import assert from 'node:assert/strict' import test from 'node:test' -import { dueStage, stageBody, processStalePullRequests } from './remind.mjs' +import { dueStage as dueAction, stageBody, processStalePullRequests } from './remind.mjs' const now = new Date('2026-11-30T00:00:00Z') const daysAgo = days => new Date(now.getTime() - days * 24 * 60 * 60 * 1000).toISOString() @@ -9,6 +9,7 @@ const human = { login: 'author', type: 'User' } const bot = { login: 'github-actions[bot]', type: 'Bot' } const comment = (actor, days, body = 'ok') => ({ event: 'commented', actor, created_at: daysAgo(days), body }) const reminder = (days, stage) => comment(bot, days, stageBody('author', stage)) +const dueStage = options => dueAction(options)?.days test('no reminder is due within 7 days of the last activity', () => { assert.equal(dueStage({ createdAt: daysAgo(6), timeline: [], now }), undefined) @@ -31,6 +32,14 @@ test('a pull request closes after 21 days without activity and 7 days after the assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [reminder(30, 7)], now }), 14) // A 14-day reminder from before the last activity gives no notice. assert.equal(dueStage({ createdAt: daysAgo(60), timeline: [reminder(40, 14), comment(human, 25)], now }), 14) + // Reminders posted before closing existed announce no closing. + const legacy = comment(bot, 10, '\n@author This pull request has had no activity for 14 days.') + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [legacy], now }), 14) +}) + +test('a closing whose comment was posted retries the close without another comment', () => { + assert.deepEqual(dueAction({ createdAt: daysAgo(30), timeline: [reminder(9, 14)], now }), { days: 21, comment: true }) + assert.deepEqual(dueAction({ createdAt: daysAgo(30), timeline: [reminder(9, 14), reminder(1, 21)], now }), { days: 21, comment: false }) }) test('human activity restarts the cycle and bot activity does not', () => { @@ -97,12 +106,12 @@ test('reminders and closing mention the author and skip exempt and bot-authored const core = { info() {}, warning: message => warnings.push(message), setFailed: message => failures.push(message) } await processStalePullRequests({ github, context: { repo: { owner: 'o', repo: 'r' } }, core, now, sleep: async ms => sleeps.push(ms) }) assert.deepEqual(timelines, [1, 4, 6, 5, 7, 8]) - // A failed close posts no closing comment, so the next run retries without repeating it. + // A failed close after its comment is retried on the next run without another comment. assert.deepEqual(warnings, ['#6: locked', '#8: close failed']) assert.equal(failures.length, 1) - assert.deepEqual(comments.map(({ issue_number }) => issue_number), [1, 4, 5, 7]) - assert.match(comments[0].body, /^\n@author This pull request has had no activity for 14 days\./) - assert.match(comments[3].body, /^\n@author This pull request has had no activity for 21 days and is now closed\./) + assert.deepEqual(comments.map(({ issue_number }) => issue_number), [1, 4, 5, 7, 8]) + assert.match(comments[0].body, /^\n@author This pull request has had no activity for 14 days\./) + assert.match(comments[3].body, /^\n@author This pull request has had no activity for 21 days and is now closed\./) assert.deepEqual(closed, [{ owner: 'o', repo: 'r', pull_number: 7, state: 'closed' }]) assert.deepEqual(sleeps, [1000, 1000, 1000, 1000, 1000]) }) From 0204d50e3774244efadcba12a1d07f0b9a821d02 Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Mon, 16 Nov 2026 16:57:00 +0800 Subject: [PATCH 27/31] fix(tool-session-list): keep list_workspace execute synchronous An async arrow without await fails the type-aware require-await lint rule. --- packages/session-query/tool-session-list/src/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/session-query/tool-session-list/src/index.ts b/packages/session-query/tool-session-list/src/index.ts index f0c2f84b8d..96d2c315f7 100644 --- a/packages/session-query/tool-session-list/src/index.ts +++ b/packages/session-query/tool-session-list/src/index.ts @@ -44,7 +44,7 @@ export function apply(ctx: Context): void { render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }], }, isConcurrencySafe: () => true, - execute: async (args, exec) => listWorkspaces(ctx, args, exec.signal), + execute: (args, exec) => Promise.resolve(listWorkspaces(ctx, args, exec.signal)), presentCall: args => ({ card: 'generic', title: 'List workspaces', kind: 'read', rawInput: args }), })) ctx.tools.register(defineTool({ From f70ec1ac463eef42b890ab085d441ca648bd6983 Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Mon, 16 Nov 2026 17:35:17 +0800 Subject: [PATCH 28/31] Merge pull request #8348 from deepseek-harness/feat/subagent-report-guidance feat(subagent): tell delegated agents to report results with send_message --- .../subagent-inheritance/child.expected.jsonl | 2 +- .../subagent-settlement/child.expected.jsonl | 2 +- docs/config-catalog.md | 2 +- docs/config-catalog.zh.md | 2 +- docs/module-graph.md | 15 ++++++------ docs/module-graph.zh.md | 15 ++++++------ docs/tool-catalog.i18n.yaml | 8 +++---- docs/tool-catalog.md | 4 ++-- docs/tool-catalog.zh.md | 4 ++-- .../tool-subagent-control/README.i18n.yaml | 8 +++---- .../subagent/tool-subagent-control/README.md | 5 ++-- .../tool-subagent-control/README.zh.md | 5 ++-- .../tool-subagent-control/package.json | 9 ++++++- .../tool-subagent-control/src/index.ts | 6 +++++ .../tests/tool-subagent-control.spec.ts | 24 ++++++++++++++++++- .../tool-subagent-control/tsconfig.json | 3 +++ .../team/tool-agent-team/README.i18n.yaml | 4 ++-- packages/team/tool-agent-team/README.md | 2 +- packages/team/tool-agent-team/README.zh.md | 2 +- pnpm-lock.yaml | 3 +++ scripts/gen-tool-catalog.ts | 2 +- .../session.1.v4.jsonl | 2 +- .../session.1.v4.jsonl | 2 +- .../subagent-continuable/session.1.v4.jsonl | 2 +- .../session.1.v4.jsonl | 2 +- .../subagent-list-agents/session.1.v4.jsonl | 2 +- .../sdk/subagent-mixed/session.1.v4.jsonl | 2 +- .../sdk/subagent-mixed/session.2.v4.jsonl | 2 +- .../subagent-send-message/session.1.v4.jsonl | 2 +- .../notifications.expected.jsonl | 2 +- .../session.1.v4.jsonl | 2 +- .../session.1.v4.jsonl | 2 +- .../session.2.v4.jsonl | 2 +- .../advanced-toolchain/session.1.v4.jsonl | 2 +- .../advanced-toolchain/session.2.v4.jsonl | 2 +- .../session/ralph-loop/session.1.v4.jsonl | 2 +- .../session/ralph-loop/session.2.v4.jsonl | 2 +- .../subagent-agent-preset/session.1.v4.jsonl | 2 +- .../session.1.v4.jsonl | 2 +- .../session.2.v4.jsonl | 2 +- .../session.1.v4.jsonl | 2 +- .../session.1.v4.jsonl | 2 +- .../session.2.v4.jsonl | 2 +- .../session.1.v4.jsonl | 2 +- .../subagent-multi/writer.1.expected.jsonl | 2 +- .../subagent-multi/writer.2.expected.jsonl | 2 +- .../subagent-parallel/session.1.v4.jsonl | 2 +- .../subagent-parallel/session.2.v4.jsonl | 2 +- .../session.1.v4.jsonl | 2 +- .../session.1.v4.jsonl | 2 +- .../subagent-tool-filter/session.1.v4.jsonl | 2 +- .../session/workflow-run/session.1.v4.jsonl | 2 +- .../subagent-fork-schedule/session.1.v4.jsonl | 2 +- 53 files changed, 118 insertions(+), 73 deletions(-) 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 23df1c78fb..9e3ec3e15c 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 @@ -8,7 +8,7 @@ {"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: \"...\" }).\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: \"...\" }).\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":"\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":"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"}}} 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 7fd42a7bc1..498fb3440a 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 @@ -8,7 +8,7 @@ {"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: \"...\" }).\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":"{{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":"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"}}} diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 39d7646afb..8e63f67fe5 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -4774,7 +4774,7 @@ export interface PresetSelectionConfig { ## `@deepseek-ai/dsh-tool-subagent-control` - `inject`: `tools` · `subagents` · `agents` · `systemPrompt` -- `source`: [`packages/subagent/tool-subagent-control/src/index.ts:24`](../packages/subagent/tool-subagent-control/src/index.ts) +- `source`: [`packages/subagent/tool-subagent-control/src/index.ts:25`](../packages/subagent/tool-subagent-control/src/index.ts) ```ts config-catalog /** Optional subagent control tools. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index d1576a36bb..96fd2f6bb3 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -4776,7 +4776,7 @@ export interface PresetSelectionConfig { ## `@deepseek-ai/dsh-tool-subagent-control` - `inject`: `tools` · `subagents` · `agents` · `systemPrompt` -- `source`: [`packages/subagent/tool-subagent-control/src/index.ts:24`](../packages/subagent/tool-subagent-control/src/index.ts) +- `source`: [`packages/subagent/tool-subagent-control/src/index.ts:25`](../packages/subagent/tool-subagent-control/src/index.ts) ```ts config-catalog /** Optional subagent control tools. */ diff --git a/docs/module-graph.md b/docs/module-graph.md index bb9b68cb44..a91a8808e7 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -1376,12 +1376,6 @@ flowchart TD pkg_tool_subagent --> pkg_subagent pkg_tool_subagent --> pkg_system_prompt pkg_tool_subagent --> pkg_tools - pkg_tool_subagent_control --> pkg_agent - pkg_tool_subagent_control --> pkg_llm - pkg_tool_subagent_control --> pkg_session - pkg_tool_subagent_control --> pkg_subagent - pkg_tool_subagent_control --> pkg_system_prompt - pkg_tool_subagent_control --> pkg_tools pkg_api_session_controller --> pkg_agent pkg_api_session_controller --> pkg_agent_default_model pkg_api_session_controller --> pkg_agent_preset_registry @@ -1509,6 +1503,13 @@ flowchart TD pkg_workflow_ptc --> pkg_tools pkg_workflow_ptc --> pkg_workflow pkg_workflow_ptc --> pkg_working_directory + pkg_tool_subagent_control --> pkg_agent + pkg_tool_subagent_control --> pkg_agent_team + pkg_tool_subagent_control --> pkg_llm + pkg_tool_subagent_control --> pkg_session + pkg_tool_subagent_control --> pkg_subagent + pkg_tool_subagent_control --> pkg_system_prompt + pkg_tool_subagent_control --> pkg_tools pkg_schedule --> pkg_agent pkg_schedule --> pkg_api_session_controller pkg_schedule --> pkg_llm @@ -1942,7 +1943,6 @@ flowchart TD | [`subagent-fork-in-process`](../packages/subagent/subagent-fork-in-process) | `subagent` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent) | | [`subagent-spawn-in-process`](../packages/subagent/subagent-spawn-in-process) | `subagent` | [`subagent`](../packages/subagent/subagent) | | [`tool-subagent`](../packages/subagent/tool-subagent) | `subagent` | [`agent`](../packages/core/agent), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | -| [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | `subagent` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`api-session-controller`](../packages/api/session-controller) | `api` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`api-gateway`](../packages/api/gateway), [`attachment`](../packages/attachment/attachment), [`client-connection`](../packages/client/connection), [`client-file-upload`](../packages/client/file-upload), [`commands`](../packages/interaction/commands), [`credentials`](../packages/credentials/credentials), [`file-reference`](../packages/context/file-reference), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`native-command`](../packages/util/native-command), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`session-title`](../packages/session/session-title), [`settings`](../packages/settings/settings), [`skill`](../packages/skill/skill), [`subagent`](../packages/subagent/subagent), [`typert-protocol`](../packages/typert/protocol), [`typert-registry`](../packages/typert/registry), [`util-time`](../packages/util/time), [`util-values`](../packages/util/values), [`util-workspace-path`](../packages/util/workspace-path), [`working-directory`](../packages/session/working-directory), [`workspace`](../packages/workspace/workspace) | | [`plugin-market`](../packages/boot/plugin-market) | `boot` | [`error`](../packages/util/error), [`plugin-manager`](../packages/boot/plugin-manager), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) | | [`headless`](../packages/bundle/headless) | `bundle` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-query`](../packages/session-query/session-query), [`subagent`](../packages/subagent/subagent), [`user-approval`](../packages/interaction/user-approval) | @@ -1958,6 +1958,7 @@ flowchart TD | [`sdk-protocol`](../packages/sdk/protocol) | `sdk` | [`commands`](../packages/interaction/commands), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | | [`agent-team`](../packages/team/agent-team) | `team` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`subagent`](../packages/subagent/subagent), [`typert-protocol`](../packages/typert/protocol) | | [`workflow-ptc`](../packages/workflow/workflow-ptc) | `workflow` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow), [`working-directory`](../packages/session/working-directory) | +| [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | `subagent` | [`agent`](../packages/core/agent), [`agent-team`](../packages/team/agent-team), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`schedule`](../packages/schedule/schedule) | `schedule` | [`agent`](../packages/core/agent), [`api-session-controller`](../packages/api/session-controller), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`storage-domain`](../packages/storage/storage-domain), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`util-time`](../packages/util/time), [`workspace`](../packages/workspace/workspace) | | [`sdk-client`](../packages/sdk/client) | `sdk` | [`llm`](../packages/llm/llm), [`sdk-protocol`](../packages/sdk/protocol), [`session`](../packages/core/session) | | [`tool-agent-team`](../packages/team/tool-agent-team) | `team` | [`agent`](../packages/core/agent), [`agent-team`](../packages/team/agent-team), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index fa21f68cba..9863a414d8 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -1378,12 +1378,6 @@ flowchart TD pkg_tool_subagent --> pkg_subagent pkg_tool_subagent --> pkg_system_prompt pkg_tool_subagent --> pkg_tools - pkg_tool_subagent_control --> pkg_agent - pkg_tool_subagent_control --> pkg_llm - pkg_tool_subagent_control --> pkg_session - pkg_tool_subagent_control --> pkg_subagent - pkg_tool_subagent_control --> pkg_system_prompt - pkg_tool_subagent_control --> pkg_tools pkg_api_session_controller --> pkg_agent pkg_api_session_controller --> pkg_agent_default_model pkg_api_session_controller --> pkg_agent_preset_registry @@ -1511,6 +1505,13 @@ flowchart TD pkg_workflow_ptc --> pkg_tools pkg_workflow_ptc --> pkg_workflow pkg_workflow_ptc --> pkg_working_directory + pkg_tool_subagent_control --> pkg_agent + pkg_tool_subagent_control --> pkg_agent_team + pkg_tool_subagent_control --> pkg_llm + pkg_tool_subagent_control --> pkg_session + pkg_tool_subagent_control --> pkg_subagent + pkg_tool_subagent_control --> pkg_system_prompt + pkg_tool_subagent_control --> pkg_tools pkg_schedule --> pkg_agent pkg_schedule --> pkg_api_session_controller pkg_schedule --> pkg_llm @@ -1944,7 +1945,6 @@ flowchart TD | [`subagent-fork-in-process`](../packages/subagent/subagent-fork-in-process) | `subagent` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent) | | [`subagent-spawn-in-process`](../packages/subagent/subagent-spawn-in-process) | `subagent` | [`subagent`](../packages/subagent/subagent) | | [`tool-subagent`](../packages/subagent/tool-subagent) | `subagent` | [`agent`](../packages/core/agent), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | -| [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | `subagent` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`api-session-controller`](../packages/api/session-controller) | `api` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`api-gateway`](../packages/api/gateway), [`attachment`](../packages/attachment/attachment), [`client-connection`](../packages/client/connection), [`client-file-upload`](../packages/client/file-upload), [`commands`](../packages/interaction/commands), [`credentials`](../packages/credentials/credentials), [`file-reference`](../packages/context/file-reference), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`native-command`](../packages/util/native-command), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`session-title`](../packages/session/session-title), [`settings`](../packages/settings/settings), [`skill`](../packages/skill/skill), [`subagent`](../packages/subagent/subagent), [`typert-protocol`](../packages/typert/protocol), [`typert-registry`](../packages/typert/registry), [`util-time`](../packages/util/time), [`util-values`](../packages/util/values), [`util-workspace-path`](../packages/util/workspace-path), [`working-directory`](../packages/session/working-directory), [`workspace`](../packages/workspace/workspace) | | [`plugin-market`](../packages/boot/plugin-market) | `boot` | [`error`](../packages/util/error), [`plugin-manager`](../packages/boot/plugin-manager), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) | | [`headless`](../packages/bundle/headless) | `bundle` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-query`](../packages/session-query/session-query), [`subagent`](../packages/subagent/subagent), [`user-approval`](../packages/interaction/user-approval) | @@ -1960,6 +1960,7 @@ flowchart TD | [`sdk-protocol`](../packages/sdk/protocol) | `sdk` | [`commands`](../packages/interaction/commands), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | | [`agent-team`](../packages/team/agent-team) | `team` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`subagent`](../packages/subagent/subagent), [`typert-protocol`](../packages/typert/protocol) | | [`workflow-ptc`](../packages/workflow/workflow-ptc) | `workflow` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow), [`working-directory`](../packages/session/working-directory) | +| [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | `subagent` | [`agent`](../packages/core/agent), [`agent-team`](../packages/team/agent-team), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`schedule`](../packages/schedule/schedule) | `schedule` | [`agent`](../packages/core/agent), [`api-session-controller`](../packages/api/session-controller), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`storage-domain`](../packages/storage/storage-domain), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`util-time`](../packages/util/time), [`workspace`](../packages/workspace/workspace) | | [`sdk-client`](../packages/sdk/client) | `sdk` | [`llm`](../packages/llm/llm), [`sdk-protocol`](../packages/sdk/protocol), [`session`](../packages/core/session) | | [`tool-agent-team`](../packages/team/tool-agent-team) | `team` | [`agent`](../packages/core/agent), [`agent-team`](../packages/team/agent-team), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | diff --git a/docs/tool-catalog.i18n.yaml b/docs/tool-catalog.i18n.yaml index 2f947d20f8..c3173a7283 100644 --- a/docs/tool-catalog.i18n.yaml +++ b/docs/tool-catalog.i18n.yaml @@ -9,8 +9,8 @@ en: 6cc2cd9ced70bb09 zh: 1c0e6cb4ba2ed637 /tool-schema-catalog/tool-package-map: - en: 789c9c7932024257 - zh: 6d0465e0463b321c + en: a0118885d7ac9d96 + zh: d6031ede88059ea1 /tool-schema-catalog/deepseek-ai-dsh-plugin-manager: en: e0143916bb634762 zh: e0143916bb634762 @@ -309,8 +309,8 @@ en: 8001eda7e9ff6a25 zh: 2414761029f21404 /tool-schema-catalog/deepseek-ai-dsh-tool-agent-team/team-task-update: - en: 9acd1c5b2fac9853 - zh: 3bd81e9cd1f1c28d + en: 3c25013abbe19446 + zh: 9552eaab1a25adb2 /tool-schema-catalog/deepseek-ai-dsh-tool-todo: en: dea62d26fb18ff68 zh: dea62d26fb18ff68 diff --git a/docs/tool-catalog.md b/docs/tool-catalog.md index dd30a3d823..500ee97fba 100644 --- a/docs/tool-catalog.md +++ b/docs/tool-catalog.md @@ -45,7 +45,7 @@ This table connects model-visible tool names to the plugin package and service s | `@deepseek-ai/dsh-tool-subagent` | `list_subagent_models`, `subagent` | `ctx.tools`, `ctx.subagents`, `ctx.systemPrompt`, `ctx.sessionProjections`, `ctx.llm for model discovery and selected-route validation` | `tool/call`, `tool/result`, `child session events through the chosen provider` | `subagent`, `subagent_fork` | The load-time `toolName` selects the delegation name (default `subagent`); `modelSelection` adds optional route fields. `modelDiscovery` defaults off and registers shared discovery on one instance per scope. Web and Desktop presets enable spawn discovery and route fields and leave `subagent_fork` route fields disabled. The Host settings service records authorization for each new top-level Session; child Sessions inherit it. Without a recorded policy, discovery and explicit selection permit only the current parent route. Every delegation returns the child's name promptly; local children accept follow-ups, while external backends report their single execution automatically. | | `@deepseek-ai/dsh-tool-subagent-control` | `interrupt_agent`, `list_agents`, `send_message`, `wait_agent` | `ctx.tools`, `ctx.subagents`, `ctx.agents` | `tool/call`, `tool/result`, `child session events through ctx.subagents` | - | The shared control tools discover and contact agents in the subagent tree, interrupt owned descendants, and wait for input in the caller’s inbox. Provider-bound `tool-subagent` instances supply delegation tools. | | `@deepseek-ai/dsh-tool-jobs` | `job_kill`, `job_list`, `job_output` | `ctx.tools`, `ctx.jobs`, `ctx.systemPrompt` | `tool/call`, `tool/result`, `user/message via agent.inject() for background completion notices` | - | The kind-agnostic background-job controller: background bash commands and PTY sends are read, listed, and killed through the same three tools. Loading the plugin attaches the controller that arms producers' `ctx.jobs.start()`. | -| `@deepseek-ai/dsh-tool-agent-team` | `team_task_create`, `team_task_get`, `team_task_list`, `team_task_update` | `ctx.tools`, `ctx.systemPrompt`, `ctx.agentTeams`, `ctx.subagents`, `an exact live Team member Agent` | `tool/call`, `team/task`, `tool/result` | - | Four task-board tools share the subagent tree’s root Session. Enabling Team mode on the root Session adds task-board guidance alongside standard subagent delegation and control tools. Standard subagent controls provide required identity independently of Team mode. | +| `@deepseek-ai/dsh-tool-agent-team` | `team_task_create`, `team_task_get`, `team_task_list`, `team_task_update` | `ctx.tools`, `ctx.systemPrompt`, `ctx.agentTeams`, `ctx.subagents`, `an exact live Team member Agent` | `tool/call`, `team/task`, `tool/result` | - | Four task-board tools share the subagent tree’s root Session. Enabling Team mode on the root Session adds task-board guidance alongside standard subagent delegation and control tools. Standard subagent controls provide required identity independently of Team mode; their result report instruction appears only while Team mode is off. | | `@deepseek-ai/dsh-tool-todo` | `todo_write` | `ctx.tools`, `owning Agent session` | `tool/call`, `todo/write`, `tool/result` | - | todo_write is session-owned state; UIs render the latest todo/write event as a checklist. `allowParallelInProgress` is required with no default, so the catalog states its choice: `true`, whose description invites several `in_progress` items. A deployment choosing `false` receives the same tool with a description asking for exactly one active task. | | `@deepseek-ai/dsh-tool-working-directory` | `working_directory` | `ctx.tools`, `ctx.workingDirectory` | `tool/call`, `working-directory/change`, `user context for directory changes`, `tool/result` | - | Reads or changes the calling Session directory. Existing shells and processes retain their own directories; origin metadata and permission roots stay fixed. | | `@deepseek-ai/dsh-experimental-tool-worktree` | `create_worktree` | `ctx.tools`, `ctx.worktrees`, `a calling Agent` | `tool/call`, `Git branch and checkout`, `working-directory/change`, `tool/result` | - | Enabled through the Change requests & worktrees bundle on Web and Desktop; other profiles can select the standalone bundle. Creates a new branch and checkout from a pinned local commit under existing write permissions, then changes the Session directory. Leaving retains the branch and checkout. | @@ -2587,7 +2587,7 @@ Compare-and-set a shared task action using the latest revision from team_task_ge Source: [`packages/team/tool-agent-team/src/index.ts`](../packages/team/tool-agent-team/src/index.ts) -Four task-board tools share the subagent tree’s root Session. Enabling Team mode on the root Session adds task-board guidance alongside standard subagent delegation and control tools. Standard subagent controls provide required identity independently of Team mode. +Four task-board tools share the subagent tree’s root Session. Enabling Team mode on the root Session adds task-board guidance alongside standard subagent delegation and control tools. Standard subagent controls provide required identity independently of Team mode; their result report instruction appears only while Team mode is off. diff --git a/docs/tool-catalog.zh.md b/docs/tool-catalog.zh.md index 80929e113d..f6c004a58a 100644 --- a/docs/tool-catalog.zh.md +++ b/docs/tool-catalog.zh.md @@ -49,7 +49,7 @@ | `@deepseek-ai/dsh-tool-subagent` | `list_subagent_models`、`subagent` | `ctx.tools`、`ctx.subagents`、`ctx.systemPrompt`、`ctx.sessionProjections`、`用于模型发现和所选路由校验的 ctx.llm` | `tool/call`、`tool/result`、`child session events through the chosen provider` | `subagent`、`subagent_fork` | 加载时的 `toolName` 选择委派名称(默认为 `subagent`);`modelSelection` 增加可选路由字段。`modelDiscovery` 默认关闭,每个作用域由一个实例注册共享发现工具。Web 与 Desktop preset 启用 spawn 发现和路由字段,并为 `subagent_fork` 保持路由字段关闭。Host 设置服务为每个新顶层 Session 记录授权;子 Session 继承该授权。没有已记录策略时,发现和显式选择只允许当前父级路由。每次委派都会立即返回子代理的名称;本地子代理接受后续消息,外部后端自动汇报单次执行结果。 | | `@deepseek-ai/dsh-tool-subagent-control` | `interrupt_agent`、`list_agents`、`send_message`、`wait_agent` | `ctx.tools`、`ctx.subagents`、`ctx.agents` | `tool/call`、`tool/result`、`child session events through ctx.subagents` | - | 共享控制工具发现并联系 subagent 树中的 Agent,中断有权控制的后代,并等待调用者收件箱中的输入。绑定提供方的 `tool-subagent` 实例提供委派工具。 | | `@deepseek-ai/dsh-tool-jobs` | `job_kill`、`job_list`、`job_output` | `ctx.tools`、`ctx.jobs`、`ctx.systemPrompt` | `tool/call`、`tool/result`、`user/message via agent.inject() for background completion notices` | - | 与任务种类无关的后台任务控制器:后台 bash 命令与 PTY 发送 都通过相同的 3 个工具读取、列出和终止。加载该插件会挂接控制器,从而启用生产方的 `ctx.jobs.start()`。 | -| `@deepseek-ai/dsh-tool-agent-team` | `team_task_create`, `team_task_get`, `team_task_list`, `team_task_update` | `ctx.tools`, `ctx.systemPrompt`, `ctx.agentTeams`, `ctx.subagents`, `an exact live Team member Agent` | `tool/call`, `team/task`, `tool/result` | - | 四个任务板工具共享 subagent 树的根 Session。在根 Session 开启 Team 模式,会在标准 subagent 委派和控制工具之外增加任务板指导。标准 subagent 控制工具提供必需身份,不受 Team 模式影响。 | +| `@deepseek-ai/dsh-tool-agent-team` | `team_task_create`, `team_task_get`, `team_task_list`, `team_task_update` | `ctx.tools`, `ctx.systemPrompt`, `ctx.agentTeams`, `ctx.subagents`, `an exact live Team member Agent` | `tool/call`, `team/task`, `tool/result` | - | 四个任务板工具共享 subagent 树的根 Session。在根 Session 开启 Team 模式,会在标准 subagent 委派和控制工具之外增加任务板指导。标准 subagent 控制工具提供必需身份,不受 Team 模式影响;其结果汇报要求仅在 Team 模式关闭时出现。 | | `@deepseek-ai/dsh-tool-todo` | `todo_write` | `ctx.tools`、`owning Agent session` | `tool/call`、`todo/write`、`tool/result` | - | todo_write 是会话所有的状态;UI 将最新的 todo/write 事件渲染为检查清单。`allowParallelInProgress` 是没有默认值的必填项,因此本目录明确选择 `true`,对应描述允许同时存在多个 `in_progress` 项。选择 `false` 的部署会获得同一工具,但描述会要求只能有 1 个活动任务。 | | `@deepseek-ai/dsh-tool-working-directory` | `working_directory` | `ctx.tools`, `ctx.workingDirectory` | `tool/call`, `working-directory/change`, `user context for directory changes`, `tool/result` | - | 读取或改变调用方 Session 的目录。已有 shell 和进程保留自己的目录;原始元数据和权限根目录保持不变。 | | `@deepseek-ai/dsh-experimental-tool-worktree` | `create_worktree` | `ctx.tools`, `ctx.worktrees`, `a calling Agent` | `tool/call`, `Git branch and checkout`, `working-directory/change`, `tool/result` | - | 在 Web 和 Desktop 上通过变更请求与工作树组合包启用;其他 profile 可以选择独立组合包。在现有写权限下从固定的本地提交创建新分支与检出目录,再改变 Session 工作目录。离开时保留分支与检出目录。 | @@ -2593,7 +2593,7 @@ subagent_oar 工具在为外部提供方配置的别名之间选择。本目录 来源:[`packages/team/tool-agent-team/src/index.ts`](../packages/team/tool-agent-team/src/index.ts) -四个任务板工具共享 subagent 树的根 Session。在根 Session 开启 Team 模式,会在标准子代理委派和控制工具之外增加任务板指导。标准子代理控制工具提供必需身份,不受 Team 模式影响。 +四个任务板工具共享 subagent 树的根 Session。在根 Session 开启 Team 模式,会在标准子代理委派和控制工具之外增加任务板指导。标准子代理控制工具提供必需身份,不受 Team 模式影响;其结果汇报要求仅在 Team 模式关闭时出现。 diff --git a/packages/subagent/tool-subagent-control/README.i18n.yaml b/packages/subagent/tool-subagent-control/README.i18n.yaml index 36dc72bfa8..49fcadff0b 100644 --- a/packages/subagent/tool-subagent-control/README.i18n.yaml +++ b/packages/subagent/tool-subagent-control/README.i18n.yaml @@ -69,8 +69,8 @@ en: fc88c8ffb8ebc083 zh: 0baf2e5df37d813e /deepseek-ai-dsh-tool-subagent-control/model-experience/identity-and-communication-context/what-the-model-sees: - en: 3f59216388405b66 - zh: 70672463706bc5c5 + en: 2398af9e6e80f928 + zh: 4585ff2e63441896 /deepseek-ai-dsh-tool-subagent-control/model-experience/identity-and-communication-context/what-the-model-sees/subagent-identity: en: fc2b3383d52ded16 zh: d5074e59b79c7afd @@ -78,8 +78,8 @@ en: 37a7eed766856ea0 zh: 4a564f74e08a3252 /deepseek-ai-dsh-tool-subagent-control/model-experience/identity-and-communication-context/kv-cache-effect: - en: 49dc6a07ae9640e3 - zh: 465fcd7cfe452ad2 + en: 8879c43a533f66da + zh: 75f30ae42ea19311 /deepseek-ai-dsh-tool-subagent-control/model-experience/interrupt-result: en: d64e936e83e89a2b zh: b9905c33af6cca45 diff --git a/packages/subagent/tool-subagent-control/README.md b/packages/subagent/tool-subagent-control/README.md index a66d8ce145..6b3bde77fb 100644 --- a/packages/subagent/tool-subagent-control/README.md +++ b/packages/subagent/tool-subagent-control/README.md @@ -125,7 +125,7 @@ Prefix-stable; the schemas do not change at runtime, and a parent and its contin #### What the model sees -Required `subagent:identity` runtime context identifies each agent by name. It is independent of Team mode and tool filtering. When the live root is available, identity context includes messaging and discovery instructions independently for each admitted standard tool. The root sees `You are the root agent. Your name is "lead".` followed by the same guidance. A missing live root is reported with the agent's Session id, without preventing independent work. Automatic result delivery remains owned by the subagent service. A child of the root named `reviewer`, with both tools admitted, sees: +Required `subagent:identity` runtime context identifies each agent by name. Its identity lines are independent of Team mode and tool filtering. When the live root is available, identity context includes messaging and discovery instructions independently for each admitted standard tool. While Team mode is off, a subagent with `send_message` is also told to send a self-contained result to the agent that delegated it when it finishes, and to message any agent as soon as a finding changes what that agent should do next. The root sees `You are the root agent. Your name is "lead".` followed by the same messaging and discovery guidance. A missing live root is reported with the agent's Session id, without preventing independent work. Automatic result delivery remains owned by the subagent service. A child of the root named `reviewer`, with both tools admitted, sees: ##### Subagent identity @@ -135,6 +135,7 @@ Your name is "reviewer". The root agent of your collaboration tree is "lead". To message other agents, use send_message({ agent: "", message: "..." }). +When 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. Use list_agents({}) to find your collaborator agents and their names. ``` @@ -144,7 +145,7 @@ One short context entry per agent, independent of tree size; full names lengthen #### KV Cache effect -Identity and communication guidance follow inherited history as logged runtime context, leaving the shared system prompt and tool definitions unchanged. When a retained snapshot's identity text differs from the current text, one current runtime-context snapshot is appended. This required context remains available with `includeRuntimeContext: false` and is restored after compaction. Team mode does not change it. +Identity and communication guidance follow inherited history as logged runtime context, leaving the shared system prompt and tool definitions unchanged. When a retained snapshot's identity text differs from the current text, one current runtime-context snapshot is appended. This required context remains available with `includeRuntimeContext: false` and is restored after compaction. Switching Team mode adds or removes the report instruction for delegated children, which appends one runtime-context snapshot on the next request. ### Interrupt result diff --git a/packages/subagent/tool-subagent-control/README.zh.md b/packages/subagent/tool-subagent-control/README.zh.md index 2b5a505be5..7dfcd3fda6 100644 --- a/packages/subagent/tool-subagent-control/README.zh.md +++ b/packages/subagent/tool-subagent-control/README.zh.md @@ -125,7 +125,7 @@ kind: "package-reference" #### 模型看到什么 -必需的 `subagent:identity` 运行时上下文按名称标识每个 agent。该上下文独立于 Team 模式和工具过滤。活动根可用时,身份上下文会分别根据标准工具的获准情况提供通信与发现指引。根看到 `You are the root agent. Your name is "lead".`,后接相同指引。活动根缺失时,上下文使用该 agent 的 Session id 明确报告,但不阻止独立工作。自动结果交付仍由 subagent 服务负责。根的子级名为 `reviewer`、两个工具均获准时,它看到: +必需的 `subagent:identity` 运行时上下文按名称标识每个 agent。其中的身份行独立于 Team 模式和工具过滤。活动根可用时,身份上下文会分别根据标准工具的获准情况提供通信与发现指引。Team 模式关闭时,获准 `send_message` 的 subagent 还会被要求在完成时把自包含结果发送给委派它的 agent,并在某项发现改变任一 agent 的下一步行动时立即通知该 agent。根看到 `You are the root agent. Your name is "lead".`,后接相同的通信与发现指引。活动根缺失时,上下文使用该 agent 的 Session id 明确报告,但不阻止独立工作。自动结果交付仍由 subagent 服务负责。根的子级名为 `reviewer`、两个工具均获准时,它看到: ##### Subagent 身份 @@ -135,6 +135,7 @@ Your name is "reviewer". The root agent of your collaboration tree is "lead". To message other agents, use send_message({ agent: "", message: "..." }). +When 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. Use list_agents({}) to find your collaborator agents and their names. ``` @@ -144,7 +145,7 @@ Use list_agents({}) to find your collaborator agents and their names. #### KV Cache 影响 -身份与通信指引作为持久记录的运行时上下文位于继承历史之后,共享系统提示词和工具定义不变。保留快照中的身份文本与当前文本不同时,会追加一份当前运行时上下文快照。设置 `includeRuntimeContext: false` 后,该必需上下文仍会提供,并会在压缩后恢复。Team 模式不会改变它。 +身份与通信指引作为持久记录的运行时上下文位于继承历史之后,共享系统提示词和工具定义不变。保留快照中的身份文本与当前文本不同时,会追加一份当前运行时上下文快照。设置 `includeRuntimeContext: false` 后,该必需上下文仍会提供,并会在压缩后恢复。切换 Team 模式会为委派子级增删汇报要求,并在下一次请求时追加一份运行时上下文快照。 ### 中断结果 diff --git a/packages/subagent/tool-subagent-control/package.json b/packages/subagent/tool-subagent-control/package.json index d5aaeebdb1..190f43675d 100644 --- a/packages/subagent/tool-subagent-control/package.json +++ b/packages/subagent/tool-subagent-control/package.json @@ -38,9 +38,16 @@ "@deepseek-ai/dsh-subagent": "workspace:*", "@deepseek-ai/dsh-tools": "workspace:*", "@deepseek-ai/dsh-agent": "workspace:*", - "@deepseek-ai/dsh-system-prompt": "workspace:*" + "@deepseek-ai/dsh-system-prompt": "workspace:*", + "@deepseek-ai/dsh-agent-team": "workspace:*" + }, + "peerDependenciesMeta": { + "@deepseek-ai/dsh-agent-team": { + "optional": true + } }, "devDependencies": { + "@deepseek-ai/dsh-agent-team": "workspace:*", "@deepseek-ai/dsh-brand": "workspace:*", "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-agent": "workspace:*", diff --git a/packages/subagent/tool-subagent-control/src/index.ts b/packages/subagent/tool-subagent-control/src/index.ts index 8f9ecc95ba..4e59ff8e28 100644 --- a/packages/subagent/tool-subagent-control/src/index.ts +++ b/packages/subagent/tool-subagent-control/src/index.ts @@ -14,6 +14,7 @@ import { defineTool, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import type { ContentBlock } from '@deepseek-ai/dsh-llm' import { ROOT_AGENT_NAME } from '@deepseek-ai/dsh-subagent' import type {} from '@deepseek-ai/dsh-system-prompt' +import type {} from '@deepseek-ai/dsh-agent-team' import { registerListAgents } from './list-agents.ts' import { registerWaitAgent } from './wait-agent.ts' @@ -99,6 +100,11 @@ export function apply(ctx: Context, config: Config = {}): void { const guidance: string[] = [] if (ctx.tools.get(sendMessage.name, scope, toolSet) === sendMessage) { guidance.push('To message other agents, use send_message({ agent: "", message: "..." }).') + // Team mode coordinates results through shared tasks, so only plain delegation asks for a report. + if (names.parent !== undefined && ctx.get('agentTeams')?.isEnabled(agent) !== true) { + guidance.push('When 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.') + } } if (ctx.tools.get(listAgents.name, scope, toolSet) === listAgents) { guidance.push('Use list_agents({}) to find your collaborator agents and their names.') 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 a6b5b08860..868aec9da5 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 @@ -16,6 +16,7 @@ import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-test import type { SessionId } from '@deepseek-ai/dsh-session' import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' import SubagentRuntime, { SubagentError } from '@deepseek-ai/dsh-subagent' +import TeamService from '@deepseek-ai/dsh-agent-team' import * as SubagentFork from '@deepseek-ai/dsh-subagent-fork-in-process' import * as SubagentSpawn from '@deepseek-ai/dsh-subagent-spawn-in-process' import type { GenerateOptions, StreamChunk } from '@deepseek-ai/dsh-llm' @@ -203,9 +204,10 @@ describe('dsh-tool-subagent-control', () => { }) it.each([ + { name: 'send_message', instruction: 'use send_message to send a self-contained result to the agent that delegated you', other: 'Use list_agents' }, { name: 'send_message', instruction: 'To message other agents', other: 'Use list_agents' }, { name: 'list_agents', instruction: 'Use list_agents', other: 'To message other agents' }, - ])('gates $name guidance independently in an agent scope', async ({ name, instruction, other }) => { + ])('gates $name guidance "$instruction" independently in an agent scope', async ({ name, instruction, other }) => { const { ctx, parent } = await setup([]) const { agent: child } = await ctx.agents.create({ sessionId: brandString('communication-child'), @@ -233,6 +235,26 @@ describe('dsh-tool-subagent-control', () => { toolSet.dispose() }) + it('asks a delegated agent to report with send_message only while Team mode is off', async () => { + const { ctx, parent } = await setup([]) + await ctx.plugin(TeamService) + const { agent: child } = await ctx.agents.create({ + sessionId: brandString('team-child'), + meta: { origin: 'subagent', parentSession: parent.id }, + setup: (_ctx, agent) => { bindSubagentActivation(ctx, agent, parent) }, + }) + const report = 'When you finish, use send_message to send a self-contained result to the agent that delegated you.' + const communication = async () => renderContextSnapshot(await ctx.systemPrompt.assemble({ agent: child, scope: child })) + await ctx.agentTeams.setEnabled(parent, false) + expect(await communication()).toContain(report) + await ctx.agentTeams.setEnabled(parent, true) + const team = await communication() + expect(team).not.toContain(report) + expect(team).toContain('To message other agents') + await ctx.agentTeams.setEnabled(parent, false) + expect(await communication()).toContain(report) + }) + it('keeps collaboration instructions when controls are mounted in an agent scope', async () => { const { ctx, parent, controlFiber } = await setup([]) await controlFiber.dispose() diff --git a/packages/subagent/tool-subagent-control/tsconfig.json b/packages/subagent/tool-subagent-control/tsconfig.json index 78c8a11d76..34b7189834 100644 --- a/packages/subagent/tool-subagent-control/tsconfig.json +++ b/packages/subagent/tool-subagent-control/tsconfig.json @@ -34,6 +34,9 @@ }, { "path": "../../core/system-prompt" + }, + { + "path": "../../team/agent-team" } ] } diff --git a/packages/team/tool-agent-team/README.i18n.yaml b/packages/team/tool-agent-team/README.i18n.yaml index 02c1529c0b..fa9b648aeb 100644 --- a/packages/team/tool-agent-team/README.i18n.yaml +++ b/packages/team/tool-agent-team/README.i18n.yaml @@ -39,8 +39,8 @@ en: 3b906bae9ec19393 zh: 42c8dd145c704cb3 /deepseek-ai-dsh-tool-agent-team/understand-the-implementation/policy-and-tools: - en: 79c000a90c6c05a4 - zh: 610e2cebc2431674 + en: c251c8ea9e0eb835 + zh: fe99017a1714ac16 /deepseek-ai-dsh-tool-agent-team/understand-the-implementation/scoped-registration-and-teardown: en: ee8db166c0bc8a9b zh: 6bfe192220e931a6 diff --git a/packages/team/tool-agent-team/README.md b/packages/team/tool-agent-team/README.md index a4d69ef4b3..be1ffa05fa 100644 --- a/packages/team/tool-agent-team/README.md +++ b/packages/team/tool-agent-team/README.md @@ -89,7 +89,7 @@ The [subagent teammates Agent Note](../../../.agents/notes/implemented/architect ### Policy and tools -One plugin registration provides a dynamic `team:policy` section and four conditional task tools. Each provider reads the caller’s root Session selection, including fork children. An unavailable root disables Team tools and guidance. Tree authority comes from `ctx.subagents.rootOf(agent)`; task owners remain Session ids in `ctx.agentTeams`. Owner arguments resolve through `ctx.subagents.resolveName()`, which grants no authority. Results replace the saved `ownerId` and `ownerName` fields with `owner: ownerName ?? ownerId`. Displaying a task or editing its content requires no descendant catalog reads. Identity, discovery, communication, and waiting belong to [subagent controls](../../subagent/tool-subagent-control/README.md) and remain unchanged when Team mode switches. The subagent runtime delivers final results. +One plugin registration provides a dynamic `team:policy` section and four conditional task tools. Each provider reads the caller’s root Session selection, including fork children. An unavailable root disables Team tools and guidance. Tree authority comes from `ctx.subagents.rootOf(agent)`; task owners remain Session ids in `ctx.agentTeams`. Owner arguments resolve through `ctx.subagents.resolveName()`, which grants no authority. Results replace the saved `ownerId` and `ownerName` fields with `owner: ownerName ?? ownerId`. Displaying a task or editing its content requires no descendant catalog reads. Identity, discovery, communication, and waiting belong to [subagent controls](../../subagent/tool-subagent-control/README.md) and keep that ownership when Team mode switches; enabling Team mode removes only their result report instruction. The subagent runtime delivers final results. ### Scoped registration and teardown diff --git a/packages/team/tool-agent-team/README.zh.md b/packages/team/tool-agent-team/README.zh.md index 063fbcbd26..f8fe783cbc 100644 --- a/packages/team/tool-agent-team/README.zh.md +++ b/packages/team/tool-agent-team/README.zh.md @@ -89,7 +89,7 @@ kind: "package-reference" ### 策略与工具 -一次插件注册提供动态的 `team:policy` 段落和四个条件任务工具。各提供方读取调用者根 Session 的选择,包括 fork 子级。根不可用时禁用 Team 工具与指导。树权限从 `ctx.subagents.rootOf(agent)` 派生;在 `ctx.agentTeams` 中任务负责人保留为 Session id。所有者参数通过 `ctx.subagents.resolveName()` 解析,解析不授予权限。结果以 `owner: ownerName ?? ownerId` 取代保存的 `ownerId` 和 `ownerName` 字段。展示任务或编辑其内容无需读取后代目录。身份、发现、通信和等待属于 [subagent 控制工具](../../subagent/tool-subagent-control/README.zh.md),在切换 Team 模式时保持不变。subagent 运行时负责投递最终结果。 +一次插件注册提供动态的 `team:policy` 段落和四个条件任务工具。各提供方读取调用者根 Session 的选择,包括 fork 子级。根不可用时禁用 Team 工具与指导。树权限从 `ctx.subagents.rootOf(agent)` 派生;在 `ctx.agentTeams` 中任务负责人保留为 Session id。所有者参数通过 `ctx.subagents.resolveName()` 解析,解析不授予权限。结果以 `owner: ownerName ?? ownerId` 取代保存的 `ownerId` 和 `ownerName` 字段。展示任务或编辑其内容无需读取后代目录。身份、发现、通信和等待属于 [subagent 控制工具](../../subagent/tool-subagent-control/README.zh.md),切换 Team 模式时归属不变;开启 Team 模式只会去掉其中的结果汇报要求。subagent 运行时负责投递最终结果。 ### 按作用域注册与拆除 diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 206c69c0fe..14b99cef0a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -18303,6 +18303,9 @@ importers: '@deepseek-ai/dsh-agent-loop-testkit': specifier: workspace:* version: link:../../test-support/agent-loop-testkit + '@deepseek-ai/dsh-agent-team': + specifier: workspace:* + version: link:../../team/agent-team '@deepseek-ai/dsh-brand': specifier: workspace:* version: link:../../util/brand diff --git a/scripts/gen-tool-catalog.ts b/scripts/gen-tool-catalog.ts index fda6ce6d8e..02e6084ed4 100644 --- a/scripts/gen-tool-catalog.ts +++ b/scripts/gen-tool-catalog.ts @@ -683,7 +683,7 @@ const TOOL_PACKAGES: ToolPackage[] = [ }, scope: ctx => catalogChildScopes.get(ctx) as Agent, note: - 'Four task-board tools share the subagent tree’s root Session. Enabling Team mode on the root Session adds task-board guidance alongside standard subagent delegation and control tools. Standard subagent controls provide required identity independently of Team mode.', + 'Four task-board tools share the subagent tree’s root Session. Enabling Team mode on the root Session adds task-board guidance alongside standard subagent delegation and control tools. Standard subagent controls provide required identity independently of Team mode; their result report instruction appears only while Team mode is off.', }, { pkg: '@deepseek-ai/dsh-tool-todo', diff --git a/snapshots/sdk/subagent-activation-limit/session.1.v4.jsonl b/snapshots/sdk/subagent-activation-limit/session.1.v4.jsonl index c3cc7b9594..7268d60b9b 100644 --- a/snapshots/sdk/subagent-activation-limit/session.1.v4.jsonl +++ b/snapshots/sdk/subagent-activation-limit/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"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: \"...\" }).\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":"\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":"\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"}} diff --git a/snapshots/sdk/subagent-continuable-inheritance/session.1.v4.jsonl b/snapshots/sdk/subagent-continuable-inheritance/session.1.v4.jsonl index b3cd7ec92c..29891b60f4 100644 --- a/snapshots/sdk/subagent-continuable-inheritance/session.1.v4.jsonl +++ b/snapshots/sdk/subagent-continuable-inheritance/session.1.v4.jsonl @@ -8,7 +8,7 @@ {"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: \"...\" }).\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: \"...\" }).\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":"\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":"\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"}} diff --git a/snapshots/sdk/subagent-continuable/session.1.v4.jsonl b/snapshots/sdk/subagent-continuable/session.1.v4.jsonl index 96eeb690e2..49eb1a6479 100644 --- a/snapshots/sdk/subagent-continuable/session.1.v4.jsonl +++ b/snapshots/sdk/subagent-continuable/session.1.v4.jsonl @@ -12,7 +12,7 @@ {"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: \"...\" }).\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:21}}"},"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":"\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"}} 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 19d523aa3a..a4f658304c 100644 --- a/snapshots/sdk/subagent-fork-in-process/session.1.v4.jsonl +++ b/snapshots/sdk/subagent-fork-in-process/session.1.v4.jsonl @@ -26,7 +26,7 @@ {"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: \"...\" }).\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:12}}"},"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":"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 c2ddc6ba54..3f07ed2107 100644 --- a/snapshots/sdk/subagent-list-agents/session.1.v4.jsonl +++ b/snapshots/sdk/subagent-list-agents/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"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: \"...\" }).\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":"\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":"\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"}} diff --git a/snapshots/sdk/subagent-mixed/session.1.v4.jsonl b/snapshots/sdk/subagent-mixed/session.1.v4.jsonl index d2a0c54601..70de7c510f 100644 --- a/snapshots/sdk/subagent-mixed/session.1.v4.jsonl +++ b/snapshots/sdk/subagent-mixed/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"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: \"...\" }).\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":"\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":"\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"}} diff --git a/snapshots/sdk/subagent-mixed/session.2.v4.jsonl b/snapshots/sdk/subagent-mixed/session.2.v4.jsonl index 38cea8dd55..a88ecf5174 100644 --- a/snapshots/sdk/subagent-mixed/session.2.v4.jsonl +++ b/snapshots/sdk/subagent-mixed/session.2.v4.jsonl @@ -26,7 +26,7 @@ {"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: \"...\" }).\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: \"...\" }).\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":"\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":"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 d2decca80d..5c9f47fad3 100644 --- a/snapshots/sdk/subagent-send-message/session.1.v4.jsonl +++ b/snapshots/sdk/subagent-send-message/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"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: \"...\" }).\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":"\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":"\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"}} diff --git a/snapshots/sdk/subagent-spawn-in-process/notifications.expected.jsonl b/snapshots/sdk/subagent-spawn-in-process/notifications.expected.jsonl index 5feb3241f3..d9b754e40a 100644 --- a/snapshots/sdk/subagent-spawn-in-process/notifications.expected.jsonl +++ b/snapshots/sdk/subagent-spawn-in-process/notifications.expected.jsonl @@ -24,7 +24,7 @@ {"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: \"...\" }).\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":"{{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":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"}}}} 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 42a8cca90a..3a765d41c2 100644 --- a/snapshots/sdk/subagent-spawn-in-process/session.1.v4.jsonl +++ b/snapshots/sdk/subagent-spawn-in-process/session.1.v4.jsonl @@ -8,7 +8,7 @@ {"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: \"...\" }).\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: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: 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":"\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"}} diff --git a/snapshots/session/advanced-toolchain-runtime/session.1.v4.jsonl b/snapshots/session/advanced-toolchain-runtime/session.1.v4.jsonl index 0459818119..a2fdb349d2 100644 --- a/snapshots/session/advanced-toolchain-runtime/session.1.v4.jsonl +++ b/snapshots/session/advanced-toolchain-runtime/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"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: \"...\" }).\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":"\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":"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"}}} diff --git a/snapshots/session/advanced-toolchain-runtime/session.2.v4.jsonl b/snapshots/session/advanced-toolchain-runtime/session.2.v4.jsonl index 5f04bbd358..b324dd8ca4 100644 --- a/snapshots/session/advanced-toolchain-runtime/session.2.v4.jsonl +++ b/snapshots/session/advanced-toolchain-runtime/session.2.v4.jsonl @@ -9,7 +9,7 @@ {"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: \"...\" }).\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: \"...\" }).\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":"\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":"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"}}} diff --git a/snapshots/session/advanced-toolchain/session.1.v4.jsonl b/snapshots/session/advanced-toolchain/session.1.v4.jsonl index c76902452a..5448dc8976 100644 --- a/snapshots/session/advanced-toolchain/session.1.v4.jsonl +++ b/snapshots/session/advanced-toolchain/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"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: \"...\" }).\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:22}}"},"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":"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"}}} diff --git a/snapshots/session/advanced-toolchain/session.2.v4.jsonl b/snapshots/session/advanced-toolchain/session.2.v4.jsonl index c023e2862b..4aeef9e8c1 100644 --- a/snapshots/session/advanced-toolchain/session.2.v4.jsonl +++ b/snapshots/session/advanced-toolchain/session.2.v4.jsonl @@ -9,7 +9,7 @@ {"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: \"...\" }).\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: \"...\" }).\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":"\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":"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"}}} diff --git a/snapshots/session/ralph-loop/session.1.v4.jsonl b/snapshots/session/ralph-loop/session.1.v4.jsonl index 1fc1bef3f1..82a097c2e3 100644 --- a/snapshots/session/ralph-loop/session.1.v4.jsonl +++ b/snapshots/session/ralph-loop/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"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: \"...\" }).\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: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: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"}}} diff --git a/snapshots/session/ralph-loop/session.2.v4.jsonl b/snapshots/session/ralph-loop/session.2.v4.jsonl index 8bcd71e4f5..c73c2a1649 100644 --- a/snapshots/session/ralph-loop/session.2.v4.jsonl +++ b/snapshots/session/ralph-loop/session.2.v4.jsonl @@ -9,7 +9,7 @@ {"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: \"...\" }).\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: \"...\" }).\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":"\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":"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"}}} diff --git a/snapshots/session/subagent-agent-preset/session.1.v4.jsonl b/snapshots/session/subagent-agent-preset/session.1.v4.jsonl index b23559714e..62bf1c479e 100644 --- a/snapshots/session/subagent-agent-preset/session.1.v4.jsonl +++ b/snapshots/session/subagent-agent-preset/session.1.v4.jsonl @@ -10,7 +10,7 @@ {"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: \"...\" }).\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: \"...\" }).\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":"\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":"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"}}} diff --git a/snapshots/session/subagent-archive-lineage/session.1.v4.jsonl b/snapshots/session/subagent-archive-lineage/session.1.v4.jsonl index c29300ad07..ba37cda623 100644 --- a/snapshots/session/subagent-archive-lineage/session.1.v4.jsonl +++ b/snapshots/session/subagent-archive-lineage/session.1.v4.jsonl @@ -10,7 +10,7 @@ {"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: \"...\" }).\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: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: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"}}} diff --git a/snapshots/session/subagent-archive-lineage/session.2.v4.jsonl b/snapshots/session/subagent-archive-lineage/session.2.v4.jsonl index 5244e25c40..a1127c04f6 100644 --- a/snapshots/session/subagent-archive-lineage/session.2.v4.jsonl +++ b/snapshots/session/subagent-archive-lineage/session.2.v4.jsonl @@ -10,7 +10,7 @@ {"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: \"...\" }).\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: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 \"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":"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"}}} 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 bba60d00bc..99c7c7736b 100644 --- a/snapshots/session/subagent-child-question-rejection/session.1.v4.jsonl +++ b/snapshots/session/subagent-child-question-rejection/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"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: \"...\" }).\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: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: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"}}} 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 0f3435e07c..311b781f19 100644 --- a/snapshots/session/subagent-depth-two-rejection/session.1.v4.jsonl +++ b/snapshots/session/subagent-depth-two-rejection/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"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: \"...\" }).\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: \"...\" }).\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":"\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":"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"}}} 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 dfa91ecadc..8ee62bf7c6 100644 --- a/snapshots/session/subagent-depth-two-rejection/session.2.v4.jsonl +++ b/snapshots/session/subagent-depth-two-rejection/session.2.v4.jsonl @@ -9,7 +9,7 @@ {"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: \"...\" }).\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: \"...\" }).\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":"\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":"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"}}} 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 f2650839c3..eeba0b0a5e 100644 --- a/snapshots/session/subagent-max-tokens-partial/session.1.v4.jsonl +++ b/snapshots/session/subagent-max-tokens-partial/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"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: \"...\" }).\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: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: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"}}} diff --git a/snapshots/session/subagent-multi/writer.1.expected.jsonl b/snapshots/session/subagent-multi/writer.1.expected.jsonl index b075fda0c0..dcd07b256c 100644 --- a/snapshots/session/subagent-multi/writer.1.expected.jsonl +++ b/snapshots/session/subagent-multi/writer.1.expected.jsonl @@ -9,7 +9,7 @@ {"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: \"...\" }).\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: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: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"}}} diff --git a/snapshots/session/subagent-multi/writer.2.expected.jsonl b/snapshots/session/subagent-multi/writer.2.expected.jsonl index 37b742eec6..e45c4a496e 100644 --- a/snapshots/session/subagent-multi/writer.2.expected.jsonl +++ b/snapshots/session/subagent-multi/writer.2.expected.jsonl @@ -9,7 +9,7 @@ {"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: \"...\" }).\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: \"...\" }).\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":"\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":"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"}}} diff --git a/snapshots/session/subagent-parallel/session.1.v4.jsonl b/snapshots/session/subagent-parallel/session.1.v4.jsonl index c131526718..7e2d815ada 100644 --- a/snapshots/session/subagent-parallel/session.1.v4.jsonl +++ b/snapshots/session/subagent-parallel/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"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: \"...\" }).\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: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: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"}}} diff --git a/snapshots/session/subagent-parallel/session.2.v4.jsonl b/snapshots/session/subagent-parallel/session.2.v4.jsonl index 6525354d1e..28708982d9 100644 --- a/snapshots/session/subagent-parallel/session.2.v4.jsonl +++ b/snapshots/session/subagent-parallel/session.2.v4.jsonl @@ -9,7 +9,7 @@ {"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: \"...\" }).\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: \"...\" }).\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":"\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":"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"}}} 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 f074f5e678..e68b196770 100644 --- a/snapshots/session/subagent-spawn-in-process/session.1.v4.jsonl +++ b/snapshots/session/subagent-spawn-in-process/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"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: \"...\" }).\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: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: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"}}} diff --git a/snapshots/session/subagent-structured-parent/session.1.v4.jsonl b/snapshots/session/subagent-structured-parent/session.1.v4.jsonl index 9f3180e9f2..73fd031599 100644 --- a/snapshots/session/subagent-structured-parent/session.1.v4.jsonl +++ b/snapshots/session/subagent-structured-parent/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"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: \"...\" }).\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:10}}"},"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":"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"}}} diff --git a/snapshots/session/subagent-tool-filter/session.1.v4.jsonl b/snapshots/session/subagent-tool-filter/session.1.v4.jsonl index 9c2e91a3aa..5bc7d5d835 100644 --- a/snapshots/session/subagent-tool-filter/session.1.v4.jsonl +++ b/snapshots/session/subagent-tool-filter/session.1.v4.jsonl @@ -10,7 +10,7 @@ {"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: \"...\" }).\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: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: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"}}} diff --git a/snapshots/session/workflow-run/session.1.v4.jsonl b/snapshots/session/workflow-run/session.1.v4.jsonl index 5085aaa87e..c7a7977247 100644 --- a/snapshots/session/workflow-run/session.1.v4.jsonl +++ b/snapshots/session/workflow-run/session.1.v4.jsonl @@ -9,7 +9,7 @@ {"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: \"...\" }).\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: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: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"}}} diff --git a/snapshots/web/subagent-fork-schedule/session.1.v4.jsonl b/snapshots/web/subagent-fork-schedule/session.1.v4.jsonl index 4e79a3846a..12daf4b503 100644 --- a/snapshots/web/subagent-fork-schedule/session.1.v4.jsonl +++ b/snapshots/web/subagent-fork-schedule/session.1.v4.jsonl @@ -26,7 +26,7 @@ {"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: \"...\" }).\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: \"...\" }).\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":"\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":"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\"}"}} From 077a9cde0bc0955f5e27cf48431ca8fec609b324 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Mon, 16 Nov 2026 18:10:15 +0800 Subject: [PATCH 29/31] feat(cua): add toggleMouse with initial Windows support (#8425) * feat(cua-windows): implement window-level mouse button toggles * Update guidance * Fix prompt test --- .../profiles/cua-mcp/expected/reference.md | 10 +- .../CuaNative/NativeProtocol.generated.swift | 2 + .../cua-macos/native/protocol.schema.json | 53 +++++++ .../experimental/cua-macos/src/guidance.ts | 1 + .../cua-macos/tests/guidance.spec.ts | 54 +++++-- .../native/desktop-tests/Program.cs | 70 +++++++++ .../native/entry/DesktopExecutor.cs | 6 + .../cua-windows/native/entry/Input.cs | 12 ++ .../cua-windows/native/protocol.schema.json | 53 +++++++ .../cua-windows/native/tests/Program.cs | 22 +++ .../experimental/cua-windows/src/index.ts | 2 +- .../tests/desktop-toggle-mouse.spec.ts | 145 ++++++++++++++++++ .../tests/loader-composition.spec.ts | 6 + .../tests/provider-lifecycle.spec.ts | 1 + packages/experimental/cua/src/api.ts | 3 + packages/experimental/cua/src/guidance.ts | 10 +- packages/experimental/cua/src/protocol.ts | 1 + packages/experimental/cua/src/types.ts | 10 +- packages/experimental/cua/tests/api.spec.ts | 32 ++++ .../cua/tests/native-schema.spec.ts | 7 + .../experimental/cua/tests/protocol.spec.ts | 22 +++ .../cua-run-code/system-prompt.expected.md | 10 +- .../cua-native/system-prompt.expected.md | 10 +- .../cua-native/tool-schemas.expected.json | 49 ++++++ .../session/cua-ptc/system-prompt.expected.md | 10 +- .../system-prompt.expected.md | 10 +- .../cua-run-code/system-prompt.expected.md | 10 +- .../system-prompt.expected.md | 10 +- 28 files changed, 600 insertions(+), 31 deletions(-) create mode 100644 packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts diff --git a/apps/cli/tests/profiles/cua-mcp/expected/reference.md b/apps/cli/tests/profiles/cua-mcp/expected/reference.md index c7ef7c99e1..ea7301ee1b 100644 --- a/apps/cli/tests/profiles/cua-mcp/expected/reference.md +++ b/apps/cli/tests/profiles/cua-mcp/expected/reference.md @@ -31,10 +31,14 @@ Read getAccessibilityTree explicitly before using element ids. Selection and scr - setValue(elementId: string, value: JsonValue) -> ActionResult — write a control value. - selectText(elementId: string, text: string, options?: { prefix?: string, suffix?: string, selectionType?: 'text' | 'cursor_before' | 'cursor_after' }) -> ActionResult — select one literal occurrence or place the cursor beside it, using adjacent context to disambiguate. -## Simulated mouse -Use an explicit window for screenshots and pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. +## Screenshots +Use an explicit window for screenshots. - getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. + +## Simulated mouse +Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window. @@ -48,6 +52,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. +click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. + Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. AX read defaults: maxElements=2000, maxDepth=25. diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift index 39e9f04e49..a7317d8e38 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift @@ -30,6 +30,7 @@ enum NativeProtocol { "sendKeyEvent": ["appHandle", "direction", "key", "runId", "windowId"], "setValue": ["appHandle", "elementId", "snapshotId", "value", "windowId"], "show": ["appHandle", "windowId"], + "toggleMouse": ["appHandle", "direction", "mouseButton", "windowId"], "typeText": ["appHandle", "text", "windowId"], ] static let stringEnums: [String: [String: Set]] = [ @@ -40,5 +41,6 @@ enum NativeProtocol { "requestPermission": ["permission": ["accessibility", "screenRecording"]], "selectText": ["selectionType": ["cursor_after", "cursor_before", "text"]], "sendKeyEvent": ["direction": ["down", "up"]], + "toggleMouse": ["direction": ["down", "up"], "mouseButton": ["left", "middle", "right"]], ] } diff --git a/packages/experimental/cua-macos/native/protocol.schema.json b/packages/experimental/cua-macos/native/protocol.schema.json index 801414e010..472c3f3b80 100644 --- a/packages/experimental/cua-macos/native/protocol.schema.json +++ b/packages/experimental/cua-macos/native/protocol.schema.json @@ -451,6 +451,59 @@ ], "additionalProperties": false }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "toggleMouse" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "string", + "minLength": 1 + }, + "mouseButton": { + "type": "string", + "enum": [ + "left", + "right", + "middle" + ] + }, + "direction": { + "type": "string", + "enum": [ + "down", + "up" + ] + } + }, + "required": [ + "appHandle", + "windowId", + "mouseButton", + "direction" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, { "type": "object", "properties": { diff --git a/packages/experimental/cua-macos/src/guidance.ts b/packages/experimental/cua-macos/src/guidance.ts index 332d36f163..20f5257334 100644 --- a/packages/experimental/cua-macos/src/guidance.ts +++ b/packages/experimental/cua-macos/src/guidance.ts @@ -13,6 +13,7 @@ function operationGuidance(treeAdvice: string): string { ['sendKeyEvent', "Send 'down' to hold a key across tool calls in one program, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this program returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients."], ['getAccessibilityTree', `macOS accepts maxElements up to 100000 and maxDepth up to 512. If the tree is truncated, select a narrower window or raise the reported limit on the next read. ${treeAdvice} Use element ids from the file only while that observation is current.`], ['mouseMove', 'With useSystemPointer omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again.'], + ['toggleMouse', 'Not implemented on macOS.'], ['drag', 'Omitting useSystemPointer or passing false directs the drag to the window without asking for mouse control. An explicit system drag shares the session decision with mouseMove and holds the chosen button along the path in the unobscured foreground window.'], ['click', 'click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying.'], ]) diff --git a/packages/experimental/cua-macos/tests/guidance.spec.ts b/packages/experimental/cua-macos/tests/guidance.spec.ts index f31ca9e6b7..3fb53d70e3 100644 --- a/packages/experimental/cua-macos/tests/guidance.spec.ts +++ b/packages/experimental/cua-macos/tests/guidance.spec.ts @@ -1,4 +1,4 @@ -/** Model-facing guidance enumerates the full available object API without unavailable operations. */ +/** Model-facing guidance lists the object API with platform availability and input constraints. */ import { expect, it } from 'vitest' import type { CuaApi, CuaApp, CuaSurface, CuaWindow } from '@deepseek-ai/dsh-cua/api' import { COMMON_GUIDANCE, withSystemPointerGuidance } from '@deepseek-ai/dsh-cua/guidance' @@ -9,7 +9,7 @@ const accessibilityNames: Array> = [ 'getAccessibilityTree', 'listActions', 'invoke', 'performAction', 'setValue', 'selectText', ] const appNames: Array = ['appHandle', 'activate', 'getWindows', 'getWindow'] -const windowNames: Array = ['windowId', 'getScreenshot', 'mouseMove', 'click', 'scroll', 'drag'] +const windowNames: Array = ['windowId', 'getScreenshot', 'mouseMove', 'toggleMouse', 'click', 'scroll', 'drag'] it('keeps file-tool instructions in PTC and limits the program guidance to available bindings', () => { for (const name of ['tools.write', 'tools.grep', 'tools.read']) { @@ -20,11 +20,13 @@ it('keeps file-tool instructions in PTC and limits the program guidance to avail expect(PROGRAM_GUIDANCE).toContain('session’s file tools') }) -it('keeps exactly three ordered operation headings', () => { - const heads = COMMON_GUIDANCE.match(/^## .+$/gm) - expect(heads).toEqual(['## Accessibility tree', '## Simulated mouse', '## Simulated keyboard']) - expect(COMMON_GUIDANCE.indexOf('## Accessibility tree')).toBeLessThan(COMMON_GUIDANCE.indexOf('## Simulated mouse')) - expect(COMMON_GUIDANCE.indexOf('## Simulated mouse')).toBeLessThan(COMMON_GUIDANCE.indexOf('## Simulated keyboard')) +it('places observation chapters before simulated input with screenshots in their own chapter', () => { + for (const catalog of [COMMON_GUIDANCE, GUIDANCE, PROGRAM_GUIDANCE]) { + expect(catalog.match(/^## .+$/gm)).toEqual(['## Accessibility tree', '## Screenshots', '## Simulated mouse', '## Simulated keyboard']) + const screenshots = catalog.slice(catalog.indexOf('## Screenshots'), catalog.indexOf('## Simulated mouse')) + expect(screenshots).toContain('- getScreenshot() -> Image') + expect(catalog.slice(catalog.indexOf('## Simulated mouse'))).not.toContain('- getScreenshot(') + } }) it('prefixes concise platform guidance before the shared catalog', () => { @@ -67,7 +69,23 @@ it('states the macOS accessibility, keyboard, and mouse levels', () => { } }) -it('enumerates every available method once in its catalog entry', () => { +it('documents explicit mouse-button events immediately after mouseMove', () => { + const lines = COMMON_GUIDANCE.split('\n') + const index = lines.findIndex(line => line.startsWith('- toggleMouse(')) + expect(lines[index - 1]).toMatch(/^- mouseMove\(/) + expect(lines[index]).toBe("- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically.") + expect(index).toBeGreaterThan(lines.indexOf('## Simulated mouse')) + expect(index).toBeLessThan(lines.indexOf('## Simulated keyboard')) +}) + +it.each([GUIDANCE, PROGRAM_GUIDANCE])('marks toggleMouse as unavailable in the macOS method entry', (catalog) => { + const shared = COMMON_GUIDANCE.split('\n').find(line => line.startsWith('- toggleMouse(')) + const entry = catalog.split('\n').find(line => line.startsWith('- toggleMouse(')) + expect(entry).toBe(`${shared} Not implemented on macOS.`) + expect(PLATFORM_GUIDANCE).not.toContain('toggleMouse') +}) + +it('enumerates every public method once in its catalog entry', () => { const signatures = [ ...apiNames.map(name => `cua.${name}(`), ...appNames.filter(name => name !== 'appHandle').map(name => `app.${name}(`), @@ -79,8 +97,8 @@ it('enumerates every available method once in its catalog entry', () => { for (const catalog of [COMMON_GUIDANCE, GUIDANCE, PROGRAM_GUIDANCE]) { for (const signature of signatures) expect(catalog.split('\n').filter(line => line.startsWith(`- ${signature}`))).toHaveLength(1) } - expect(signatures).toHaveLength(25) - expect(new Set(signatures.map(signature => signature.slice(signature.indexOf('.') + 1, -1))).size).toBe(24) + expect(signatures).toHaveLength(26) + expect(new Set(signatures.map(signature => signature.slice(signature.indexOf('.') + 1, -1))).size).toBe(25) expect(COMMON_GUIDANCE).toContain('app.appHandle') expect(COMMON_GUIDANCE).toContain('window.windowId') }) @@ -128,7 +146,8 @@ it('references Modifier without defining its members in shared guidance', () => }) it('states platform-dependent levels without qualifying grouped method names', () => { - expect(COMMON_GUIDANCE).toContain('## Simulated mouse\nUse an explicit window for screenshots and pointer input.') + expect(COMMON_GUIDANCE).toContain('## Screenshots\nUse an explicit window for screenshots.') + expect(COMMON_GUIDANCE).toContain('## Simulated mouse\nUse an explicit window for pointer input.') for (const heading of ['Accessibility tree', 'Simulated keyboard']) { expect(COMMON_GUIDANCE).toContain(`## ${heading}\nAvailable at app or window level depending on the platform.`) } @@ -139,6 +158,15 @@ it('states platform-dependent levels without qualifying grouped method names', ( expect(COMMON_GUIDANCE).toContain('from: [number, number]') }) +it('guides complex input combinations through platform-supported primitive operations', () => { + const advice = 'click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform.' + for (const catalog of [COMMON_GUIDANCE, GUIDANCE, PROGRAM_GUIDANCE]) { + expect(catalog).toContain(advice) + expect(catalog.indexOf(advice)).toBeGreaterThan(catalog.indexOf('- sendKeyEvent(')) + expect(catalog.indexOf(advice)).toBeLessThan(catalog.indexOf('Raw tools use { method, params }')) + } +}) + it('keeps consent, lock, observation, and no-replay rules', () => { expect(COMMON_GUIDANCE).toContain('consent') expect(COMMON_GUIDANCE).toContain('SESSION_LOCKED') @@ -159,6 +187,6 @@ it('documents explicit inspection and separate key arguments', () => { expect(COMMON_GUIDANCE).toContain('perform a left-button double-click') }) -it('omits stale names and unavailable platform operations', () => { - for (const stale of ['getAXState', 'emit', 'disableDiffing', 'performSecondaryAction', 'hover(', 'keyChord', 'window.typeText', 'window.pressKey', 'elementIndex', 'verified: false', 'browser tabs', 'not implemented']) expect(GUIDANCE).not.toContain(stale) +it('omits stale names and unrelated operations', () => { + for (const stale of ['getAXState', 'emit', 'disableDiffing', 'performSecondaryAction', 'hover(', 'keyChord', 'window.typeText', 'window.pressKey', 'elementIndex', 'verified: false', 'browser tabs']) expect(GUIDANCE).not.toContain(stale) }) diff --git a/packages/experimental/cua-windows/native/desktop-tests/Program.cs b/packages/experimental/cua-windows/native/desktop-tests/Program.cs index 58421dec24..3371433909 100644 --- a/packages/experimental/cua-windows/native/desktop-tests/Program.cs +++ b/packages/experimental/cua-windows/native/desktop-tests/Program.cs @@ -11,6 +11,7 @@ internal sealed class FixtureForm : Form internal readonly TextBox Editor = new() { Name = "editor", AccessibleName = "CUA test text", Multiline = true, Bounds = new(20, 20, 440, 100) }; private readonly Button button = new() { Name = "submit", Text = "Record click", Bounds = new(20, 140, 180, 40) }; private int clicks; + private int leftDowns, leftUps, rightDowns, rightUps, middleDowns, middleUps; private readonly ToolTip tooltip = new(); internal FixtureForm(string title) @@ -22,13 +23,55 @@ internal sealed class FixtureForm : Form Controls.Add(Editor); Controls.Add(button); button.Click += (_, _) => clicks++; + button.MouseDown += (_, e) => Count(e.Button, down: true); + button.MouseUp += (_, e) => Count(e.Button, down: false); + Editor.MouseDown += (_, e) => Count(e.Button, down: true); + Editor.MouseUp += (_, e) => Count(e.Button, down: false); tooltip.SetToolTip(button, "CUA hover is retained"); } + private void Count(MouseButtons pressed, bool down) + { + switch (pressed) + { + case MouseButtons.Left: if (down) leftDowns++; else leftUps++; break; + case MouseButtons.Right: if (down) rightDowns++; else rightUps++; break; + case MouseButtons.Middle: if (down) middleDowns++; else middleUps++; break; + } + } + + internal void PointAtButton() => Cursor.Position = button.PointToScreen(new Point(button.Width / 2, button.Height / 2)); + + internal void PointOutside() + { + var bounds = RectangleToScreen(ClientRectangle); + Cursor.Position = new Point(bounds.Right + 40, bounds.Top + 20); + } + + internal void Cover(FixtureForm cover) + { + cover.Bounds = Bounds; + cover.TopMost = true; + cover.Show(); + Activate(); + PointAtButton(); + } + + internal void Uncover(FixtureForm cover) + { + if (cover.Visible) cover.Hide(); + cover.TopMost = false; + Activate(); + PointAtButton(); + } + internal object Inspect() => new { text = Editor.Text, clicks, window = Handle.ToString(CultureInfo.InvariantCulture), foreground = GetForegroundWindow().ToString(CultureInfo.InvariantCulture), cursor = new { x = Cursor.Position.X, y = Cursor.Position.Y }, + under = GetAncestor(WindowFromPoint(Cursor.Position), 2).ToString(CultureInfo.InvariantCulture), + downs = new { left = leftDowns, right = rightDowns, middle = middleDowns }, + ups = new { left = leftUps, right = rightUps, middle = middleUps }, button = new { x = button.Left + button.Width / 2, y = button.Top + button.Height / 2 }, selection = new { start = Editor.SelectionStart, length = Editor.SelectionLength }, buttons = MouseButtons.ToString(), minimized = WindowState == FormWindowState.Minimized, visible = Visible, @@ -41,12 +84,31 @@ internal sealed class FixtureForm : Form } [DllImport("user32.dll")] private static extern nint GetForegroundWindow(); + [DllImport("user32.dll")] private static extern nint WindowFromPoint(Point point); + [DllImport("user32.dll")] private static extern nint GetAncestor(nint window, uint flags); } internal static class Program { private static void Write(object value) { Console.WriteLine(JsonSerializer.Serialize(value)); Console.Out.Flush(); } + private static void ReleaseButtons() + { + var inputs = new[] { 0x0004u, 0x0010u, 0x0040u } + .Select(flags => new Input { Type = 0, Data = new MouseInput { Flags = flags } }).ToArray(); + if (SendInput((uint)inputs.Length, inputs, Marshal.SizeOf()) != inputs.Length) + { + Console.Error.WriteLine("Fixture could not release every mouse button"); + Environment.ExitCode = 1; + } + } + + [StructLayout(LayoutKind.Sequential)] + private struct MouseInput { public int X, Y; public uint Data, Flags, Time; public nuint ExtraInfo; } + + [StructLayout(LayoutKind.Sequential)] + private struct Input { public uint Type; public MouseInput Data; } + [STAThread] private static void Main() { @@ -68,6 +130,11 @@ internal static class Program case "sibling": sibling.Show(); sibling.Activate(); sibling.Editor.Focus(); Write(sibling.Inspect()); break; case "inspect": Write(form.Inspect()); break; case "focus": form.Activate(); form.Editor.Focus(); Write(form.Inspect()); break; + case "pointer": form.PointAtButton(); Write(form.Inspect()); break; + case "pointer-outside": form.PointOutside(); Write(form.Inspect()); break; + case "cover": form.Cover(sibling); Write(new { form = form.Inspect(), sibling = sibling.Inspect() }); break; + case "uncover": form.Uncover(sibling); Write(form.Inspect()); break; + case "release-input": ReleaseButtons(); Write(form.Inspect()); break; case "minimize": form.WindowState = FormWindowState.Minimized; Write(form.Inspect()); break; case "hide": form.Hide(); Write(form.Inspect()); break; case "resize": form.Width += 50; Write(form.Inspect()); break; @@ -93,4 +160,7 @@ internal static class Program [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool AllowSetForegroundWindow(uint processId); + + [DllImport("user32.dll", SetLastError = true)] + private static extern uint SendInput(uint count, [In] Input[] inputs, int size); } diff --git a/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs b/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs index 666bd9c48a..6af36d042f 100644 --- a/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs +++ b/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs @@ -169,6 +169,12 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IA var pointed = Coordinate(app, parameters, context); return Input.MouseMove(app, pointed.Window, pointed.X, pointed.Y, context); } + case "toggleMouse": + { + var target = Selected(app, parameters, context); + Input.ToggleMouse(app, target, String(parameters, "mouseButton"), String(parameters, "direction"), context); + return ActionResult(foreground); + } case "scroll": { var target = Coordinate(app, parameters, context); diff --git a/packages/experimental/cua-windows/native/entry/Input.cs b/packages/experimental/cua-windows/native/entry/Input.cs index 7493acc990..9d186055d5 100644 --- a/packages/experimental/cua-windows/native/entry/Input.cs +++ b/packages/experimental/cua-windows/native/entry/Input.cs @@ -162,6 +162,18 @@ internal static class Input return new { dispatched = true, hoverRoute = "system-pointer", systemPointerMoved = before.X != point.X || before.Y != point.Y }; } + internal static void ToggleMouse(AppState app, WindowState window, string button, string direction, RequestContext context) + { + var flags = Button(button); + if (direction == "down") + { + if (!Win32.GetCursorPos(out var point)) throw new NativeFailure("INPUT_UNAVAILABLE", "The current pointer position is unavailable"); + Hit(app, window, point, context); + } + else Windows.RequireForeground(app, window, context); + Send(Mouse(direction == "down" ? flags.Down : flags.Up)); + } + internal static void Click(AppState app, WindowState window, double x, double y, string button, int count, string[] modifiers, RequestContext context) { if (button != "left" && count != 1) throw new NativeFailure("UNSUPPORTED", "Only left clicks support double-click"); diff --git a/packages/experimental/cua-windows/native/protocol.schema.json b/packages/experimental/cua-windows/native/protocol.schema.json index bb03a5a331..22763d1b61 100644 --- a/packages/experimental/cua-windows/native/protocol.schema.json +++ b/packages/experimental/cua-windows/native/protocol.schema.json @@ -451,6 +451,59 @@ ], "additionalProperties": false }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "toggleMouse" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "string", + "minLength": 1 + }, + "mouseButton": { + "type": "string", + "enum": [ + "left", + "right", + "middle" + ] + }, + "direction": { + "type": "string", + "enum": [ + "down", + "up" + ] + } + }, + "required": [ + "appHandle", + "windowId", + "mouseButton", + "direction" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, { "type": "object", "properties": { diff --git a/packages/experimental/cua-windows/native/tests/Program.cs b/packages/experimental/cua-windows/native/tests/Program.cs index 1a76604edb..520a805ab6 100644 --- a/packages/experimental/cua-windows/native/tests/Program.cs +++ b/packages/experimental/cua-windows/native/tests/Program.cs @@ -56,6 +56,28 @@ foreach (var method in new[] { "listActions", "performAction", "invoke", "mouseM }))); Check(operation.Params.GetProperty("elementId").GetString() == "42/-7/9", "Element operations preserve slash-separated RuntimeIds: " + method); } +foreach (var mouseButton in new[] { "left", "right", "middle" }) +foreach (var direction in new[] { "down", "up" }) +{ + var toggle = NativeRequest.Parse(WireJson.Parse(System.Text.Json.JsonSerializer.Serialize(new + { + id = "mouse", method = "toggleMouse", @params = new { appHandle = "app", windowId = "1", mouseButton, direction }, + }))); + Check(toggle.Params.GetProperty("mouseButton").GetString() == mouseButton + && toggle.Params.GetProperty("direction").GetString() == direction, + "Mouse-button events retain the explicit button and direction"); +} +foreach (var invalid in new[] +{ + """{"appHandle":"app","windowId":"1","mouseButton":"left"}""", + """{"appHandle":"app","windowId":"1","direction":"down"}""", + """{"appHandle":"app","mouseButton":"left","direction":"down"}""", + """{"appHandle":"app","windowId":"1","mouseButton":"back","direction":"down"}""", + """{"appHandle":"app","windowId":"1","mouseButton":"left","direction":"press"}""", + """{"appHandle":"app","windowId":"1","mouseButton":"left","direction":"down","x":1,"y":2}""", +}) + Refuses(() => NativeRequest.Parse(WireJson.Parse("{\"id\":\"mouse\",\"method\":\"toggleMouse\",\"params\":" + invalid + "}")), "INVALID_ARGUMENT"); + var launch = NativeRequest.Parse(WireJson.Parse("""{"id":"launch","method":"launchApp","params":{"appHandle":"pending"}}""")); Check(launch.Method == "launchApp" && launch.Params.GetProperty("appHandle").GetString() == "pending", "Host launch continuation retains the selected application handle"); diff --git a/packages/experimental/cua-windows/src/index.ts b/packages/experimental/cua-windows/src/index.ts index 8e63904c91..3be20956f5 100644 --- a/packages/experimental/cua-windows/src/index.ts +++ b/packages/experimental/cua-windows/src/index.ts @@ -14,7 +14,7 @@ const CAPABILITIES: CuaStartupCapabilities = { platform: 'windows', methods: [ 'getCapabilities', 'listApps', 'getApp', 'activate', 'show', 'listWindows', 'getState', - 'listActions', 'performAction', 'invoke', 'mouseMove', 'click', 'setValue', 'selectText', + 'listActions', 'performAction', 'invoke', 'mouseMove', 'toggleMouse', 'click', 'setValue', 'selectText', 'typeText', 'paste', 'pressKey', 'sendKeyEvent', 'scroll', 'drag', 'screenshot', ], appLevelAccessibility: false, diff --git a/packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts b/packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts new file mode 100644 index 0000000000..25a37bb8e2 --- /dev/null +++ b/packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts @@ -0,0 +1,145 @@ +/** Opt-in real Windows mouse-button toggles through the native helper. */ +import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process' +import { createInterface } from 'node:readline' +import { Context } from '@deepseek-ai/cordis' +import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local' +import { NativeClient } from '@deepseek-ai/dsh-cua/native-client' +import { expect, it } from 'vitest' +import { z } from 'zod' +import { Config } from '../src/index.ts' +import { WindowsNativeRuntime } from '../src/native-runtime.ts' + +const helperPath = process.env.DSH_CUA_DESKTOP_TEST_HELPER +const fixturePath = process.env.DSH_CUA_DESKTOP_TEST_FIXTURE +const Counts = z.object({ left: z.number().int(), right: z.number().int(), middle: z.number().int() }) +const FixtureState = z.object({ + window: z.string(), foreground: z.string(), + cursor: z.object({ x: z.number().int(), y: z.number().int() }), + under: z.string(), buttons: z.string(), clicks: z.number().int(), downs: Counts, ups: Counts, +}) +const Initial = z.object({ pid: z.number().int(), state: FixtureState }) +const Cover = z.object({ form: FixtureState, sibling: FixtureState }) +const App = z.object({ appHandle: z.string(), running: z.boolean() }) +const Windows = z.array(z.object({ windowId: z.string(), title: z.string() })) +const ToggleResult = z.object({ dispatched: z.boolean() }) + +interface Fixture { + readonly child: ChildProcessWithoutNullStreams + readonly exit: Promise + read(schema: z.ZodType): Promise + command(text: string, schema: z.ZodType): Promise +} + +function fixtureProcess(path: string): Fixture { + const child = spawn(path, [], { windowsHide: true }) + child.stderr.pipe(process.stderr) + const reader = createInterface({ input: child.stdout }) + const iterator = reader[Symbol.asyncIterator]() + const exit = new Promise((resolve) => { + child.once('error', (error) => { reader.close(); resolve(error) }) + child.once('exit', (code, signal) => { + reader.close() + resolve(code === 0 ? undefined : new Error(`Fixture exited with code ${code}, signal ${signal}`)) + }) + }) + const read = async (schema: z.ZodType): Promise => { + const next = await iterator.next() + if (next.done) throw new Error('The fixture exited before replying') + return schema.parse(JSON.parse(next.value)) + } + return { child, exit, read, command: async (text, schema) => { child.stdin.write(text + '\n'); return read(schema) } } +} + +async function releaseAndClose(fixture: Fixture): Promise { + let forced = false + const timer = setTimeout(() => { forced = true; fixture.child.kill() }, 5000) + try { + if (fixture.child.exitCode === null && fixture.child.signalCode === null && fixture.child.pid !== undefined) { + // The fixture processes release before close even if an earlier inspection is still awaiting its reply. + fixture.child.stdin.end('release-input\nclose\n') + } + const error = await fixture.exit + if (forced) throw new Error('Fixture shutdown timed out; mouse-button release could not be confirmed', { cause: error }) + if (error) throw error + } finally { clearTimeout(timer) } +} + +it.skipIf(process.platform !== 'win32' || !helperPath || !fixturePath)( + 'toggles mouse buttons without movement, observation, or implicit release', + async ({ onTestFinished, signal }) => { + const fixture = fixtureProcess(fixturePath!) + const ctx = new Context() + const cleanups: Array<() => Promise> = [] + onTestFinished(async () => { + const errors: unknown[] = [] + for (const cleanup of [ + () => releaseAndClose(fixture), ...cleanups.toReversed(), () => ctx.fiber.dispose(), + ]) { + try { await cleanup() } catch (error) { errors.push(error) } + } + if (errors.length > 0) throw new AggregateError(errors, 'Desktop mouse test cleanup failed') + }) + const inspect = () => fixture.command('inspect', FixtureState) + const observed = async (expected: object) => { + let state = await inspect() + await expect.poll(async () => { state = await inspect(); return state }, { timeout: 5000, interval: 25 }).toMatchObject(expected) + return state + } + const initial = await fixture.read(Initial) + const focused = await fixture.command('focus', FixtureState) + expect(focused.window).toBe(initial.state.window) + expect(focused.foreground, 'Windows denied foreground to the private fixture').toBe(focused.window) + expect(focused.buttons).toBe('None') + + await ctx.plugin(LocalSubprocessRuntime) + const nativeRuntime = new WindowsNativeRuntime(ctx, 25, 1000, 'pipe') + cleanups.push(() => nativeRuntime.dispose()) + const native = new NativeClient(ctx, { ...Config({}), helperPath: helperPath!, cwd: process.cwd() }, + (_owner, config) => nativeRuntime.connect(config)) + cleanups.push(() => native.dispose()) + const app = App.parse(await native.request('getApp', { selector: fixturePath! }, signal)) + expect(app.running).toBe(true) + const windows = Windows.parse(await native.request('listWindows', { appHandle: app.appHandle }, signal)) + const windowId = initial.state.window + expect(windows.some(window => window.windowId === windowId)).toBe(true) + const toggle = async (mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') => + ToggleResult.parse(await native.request('toggleMouse', { appHandle: app.appHandle, windowId, mouseButton, direction }, signal)) + + const { cursor } = await fixture.command('pointer', FixtureState) + for (const mouseButton of ['left', 'right', 'middle'] as const) { + const before = await inspect() + expect((await toggle(mouseButton, 'down')).dispatched).toBe(true) + const down = await observed({ cursor, buttons: { left: 'Left', right: 'Right', middle: 'Middle' }[mouseButton], + downs: { [mouseButton]: before.downs[mouseButton] + 1 }, ups: before.ups }) + await native.request('getCapabilities', {}, signal) + expect(await inspect()).toMatchObject({ cursor, buttons: down.buttons, ups: down.ups }) + expect((await toggle(mouseButton, 'up')).dispatched).toBe(true) + await observed({ cursor, buttons: 'None', ups: { [mouseButton]: down.ups[mouseButton] + 1 }, + clicks: down.clicks + (mouseButton === 'left' ? 1 : 0) }) + } + + const sibling = await fixture.command('sibling', FixtureState) + expect(sibling.foreground).toBe(sibling.window) + const background = await inspect() + await expect(toggle('left', 'down')).rejects.toMatchObject({ code: 'FOREGROUND_REQUIRED' }) + expect(await inspect()).toMatchObject({ buttons: 'None', downs: background.downs }) + const restored = await fixture.command('focus', FixtureState) + expect(restored.foreground).toBe(restored.window) + + const cover = await fixture.command('cover', Cover) + expect(cover.form.foreground).toBe(cover.form.window) + expect(cover.form.under).toBe(cover.sibling.window) + await expect(toggle('left', 'down')).rejects.toMatchObject({ code: 'WINDOW_OBSCURED' }) + expect(await inspect()).toMatchObject({ buttons: 'None', downs: cover.form.downs }) + const uncovered = await fixture.command('uncover', FixtureState) + expect(uncovered.foreground).toBe(uncovered.window) + + expect((await toggle('left', 'down')).dispatched).toBe(true) + const pressed = await observed({ buttons: 'Left', downs: { left: uncovered.downs.left + 1 } }) + const outside = await fixture.command('pointer-outside', FixtureState) + expect(outside.cursor).not.toEqual(pressed.cursor) + expect(outside.foreground).toBe(outside.window) + expect(outside.under).not.toBe(outside.window) + expect((await toggle('left', 'up')).dispatched).toBe(true) + await observed({ buttons: 'None', cursor: outside.cursor, ups: { left: pressed.ups.left + 1 }, clicks: pressed.clicks }) + }, 120_000) diff --git a/packages/experimental/cua-windows/tests/loader-composition.spec.ts b/packages/experimental/cua-windows/tests/loader-composition.spec.ts index 3f2dc48b47..e90acbbf49 100644 --- a/packages/experimental/cua-windows/tests/loader-composition.spec.ts +++ b/packages/experimental/cua-windows/tests/loader-composition.spec.ts @@ -31,6 +31,12 @@ it.skipIf(process.platform !== 'win32')('loads the Windows provider and rejects const prompt = await ctx.systemPrompt.assemble({ scope: agent }) expect(prompt.sections.find(section => section.name === 'computer-use:dsh-cua')?.text).toContain('Windows:') expect(prompt.sections.find(section => section.name === 'computer-use:dsh-cua')?.text).not.toContain('useSystemPointer') + const toggleMouse = prompt.sections.find(section => section.name === 'computer-use:dsh-cua')?.text + .split('\n').find(line => line.startsWith('- toggleMouse(')) + expect(toggleMouse).toContain("toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult") + expect(toggleMouse).toContain("Release held buttons explicitly with 'up'; the opposite event is not sent automatically.") + expect(toggleMouse).toContain('press or release the specified mouse button at the current pointer position without moving it.') + expect(toggleMouse).not.toContain('Not implemented') expect(JSON.stringify(ctx.tools.get('cua', agent)!.parameters)).not.toContain('useSystemPointer') const batch = await ctx.tools.execute({ agent, signal: new AbortController().signal, calls: [{ type: 'tool-call', id: brandString('invalid-window'), name: 'cua', diff --git a/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts index 9e8c2601bf..dcee6fa104 100644 --- a/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts @@ -49,6 +49,7 @@ it('uses an absolute fixture without compiling and disposes the Host runtime', a expect(backend.permissionParameters('requestPermission', 'accessibility', 'en')).toEqual({ permission: 'accessibility' }) expect(backend.capabilities).toMatchObject({ platform: 'windows', appLevelAccessibility: false, keyboard: ['window'] }) expect(backend.capabilities.methods).toContain('sendKeyEvent') + expect(backend.capabilities.methods).toContain('toggleMouse') expect(backend.sendKeyEvent).toBeUndefined() const channel = { marker: 'native stream' } native.connect.mockReturnValue(channel) diff --git a/packages/experimental/cua/src/api.ts b/packages/experimental/cua/src/api.ts index 319b2888f6..7e98c2a041 100644 --- a/packages/experimental/cua/src/api.ts +++ b/packages/experimental/cua/src/api.ts @@ -191,6 +191,9 @@ function createCuaObjects(call: ReturnType): { const [x, y] = targetPoint return HoverResult.parse(await base.call('mouseMove', { ...coordinateParams(appHandle, windowId), x, y, ...relative }, options)) }, + async toggleMouse(mouseButton, direction) { + return base.action('toggleMouse', { mouseButton, direction }) + }, async click(targetPoint, options) { const mouseButton = options?.mouseButton ?? 'left' const clickCount = options?.clickCount ?? 1 diff --git a/packages/experimental/cua/src/guidance.ts b/packages/experimental/cua/src/guidance.ts index 35524cf70d..de995fa93e 100644 --- a/packages/experimental/cua/src/guidance.ts +++ b/packages/experimental/cua/src/guidance.ts @@ -36,10 +36,14 @@ Read getAccessibilityTree explicitly before using element ids. Selection and scr - setValue(elementId: string, value: JsonValue) -> ActionResult — write a control value. - selectText(elementId: string, text: string, options?: { prefix?: string, suffix?: string, selectionType?: 'text' | 'cursor_before' | 'cursor_after' }) -> ActionResult — select one literal occurrence or place the cursor beside it, using adjacent context to disambiguate. -## Simulated mouse -Use an explicit window for screenshots and pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. +## Screenshots +Use an explicit window for screenshots. - getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. + +## Simulated mouse +Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - ${hoverSignature} -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window. @@ -53,6 +57,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. +click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. + Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name.` /** diff --git a/packages/experimental/cua/src/protocol.ts b/packages/experimental/cua/src/protocol.ts index 081ff2adc4..7ee5d6f017 100644 --- a/packages/experimental/cua/src/protocol.ts +++ b/packages/experimental/cua/src/protocol.ts @@ -72,6 +72,7 @@ function requestSchema(hover: H, drag: operation('listActions', snapshot), operation('performAction', { ...snapshot, action: z.string().min(1), argument: jsonValue.optional() }), operation('invoke', snapshot), + operation('toggleMouse', { ...window, mouseButton: pointer.mouseButton.unwrap(), direction: z.enum(['down', 'up']) }), z.object({ method: z.literal('mouseMove'), params: hover }).strict(), z.object({ method: z.literal('click'), params: z.union([ z.object({ ...snapshot, ...click }).strict(), diff --git a/packages/experimental/cua/src/types.ts b/packages/experimental/cua/src/types.ts index 4c6d173c24..b38229c220 100644 --- a/packages/experimental/cua/src/types.ts +++ b/packages/experimental/cua/src/types.ts @@ -62,7 +62,7 @@ export interface CuaCoordinateOptions { export type CuaShowResult = z.output /** Modifiers attached to a window-directed pointer gesture. */ export type CuaPointerModifier = NonNullable['modifiers']>[number] -/** Buttons supported by window-directed clicks and drags. */ +/** Buttons supported by window-directed mouse input. */ export type CuaMouseButton = NonNullable['mouseButton']> /** * Left clicks support one or two presses; right and middle clicks support one. @@ -191,6 +191,14 @@ export interface CuaWindow extends CuaSurface { */ mouseMove(target: CuaElementId | readonly [number, number], options?: CuaCoordinateOptions & { useSystemPointer?: boolean }): Promise + /** + * Send one mouse-button down or up event without moving the pointer. + * Does not send the opposite event; callers explicitly release a pressed button. + * @param mouseButton - Mouse button to press or release. + * @param direction - Explicit event direction. + * @returns Whether the provider successfully executed the requested operation. + */ + toggleMouse(mouseButton: CuaMouseButton, direction: 'down' | 'up'): Promise /** * Click a current element id or screenshot-local point. * Cancellation or timeout releases the held button; received input cannot be undone. The operation deadline includes holdMs. diff --git a/packages/experimental/cua/tests/api.spec.ts b/packages/experimental/cua/tests/api.spec.ts index c17a0ea7b7..de8325bfb2 100644 --- a/packages/experimental/cua/tests/api.spec.ts +++ b/packages/experimental/cua/tests/api.spec.ts @@ -953,6 +953,38 @@ describe('input actions', () => { expect(windowFixture.dispatch).not.toHaveBeenCalled() }) + it.each(['left', 'right', 'middle'] as const)('dispatches one %s mouse-button event without an observation', async (mouseButton) => { + const f = fixture() + const app = await f.api.getApp('Editor') + const window = await app.getWindow('23') + expect(app).not.toHaveProperty('toggleMouse') + expectTypeOf().not.toHaveProperty('toggleMouse') + expectTypeOf().parameters.toEqualTypeOf<[ + mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', + ]>() + for (const direction of ['down', 'up'] as const) { + f.dispatch.mockClear() + await expect(window.toggleMouse(mouseButton, direction)).resolves.toEqual(delivered) + expect(f.dispatch).toHaveBeenCalledExactlyOnceWith({ method: 'toggleMouse', params: { + appHandle: 'app-17', windowId: '23', mouseButton, direction, + } }) + } + }) + + it('preserves mouse-button dispatch failures without retries or an opposite event', async () => { + const f = fixture() + const window = await (await f.api.getApp('Editor')).getWindow('23') + f.dispatch.mockClear() + f.dispatch.mockResolvedValueOnce({ dispatched: false }) + await expect(window.toggleMouse('left', 'down')).resolves.toEqual({ dispatched: false }) + const failure = new Error('Mouse-button input is not supported') + f.dispatch.mockRejectedValueOnce(failure) + await expect(window.toggleMouse('left', 'up')).rejects.toBe(failure) + f.dispatch.mockResolvedValueOnce({ dispatched: 'yes' }) + await expect(window.toggleMouse('right', 'up')).rejects.toThrow() + expect(f.dispatch).toHaveBeenCalledTimes(3) + }) + it('retains the snapshot identity for element right and double clicks', async () => { const f = fixture() const app = await f.api.getApp('Editor') diff --git a/packages/experimental/cua/tests/native-schema.spec.ts b/packages/experimental/cua/tests/native-schema.spec.ts index eca0803ce5..68689e2a16 100644 --- a/packages/experimental/cua/tests/native-schema.spec.ts +++ b/packages/experimental/cua/tests/native-schema.spec.ts @@ -57,6 +57,13 @@ it('admits key events with only an explicit direction enum', () => { expect(native.enums.get('sendKeyEvent')?.has('key') ?? false).toBe(false) }) +it('admits mouse-button events with explicit button and direction enums and no coordinates', () => { + const native = nativeProtocol() + expect(native.fields.get('toggleMouse')).toEqual(new Set(['appHandle', 'windowId', 'mouseButton', 'direction'])) + expect(native.enums.get('toggleMouse')?.get('mouseButton')).toEqual(new Set(['left', 'right', 'middle'])) + expect(native.enums.get('toggleMouse')?.get('direction')).toEqual(new Set(['down', 'up'])) +}) + it('accepts a parameter-free object schema without a properties dictionary', () => { replacements.values.set(0, { properties: { method: { const: 'getCapabilities' }, params: { type: 'object' } } }) expect(nativeProtocol().fields.get('getCapabilities')).toEqual(new Set()) diff --git a/packages/experimental/cua/tests/protocol.spec.ts b/packages/experimental/cua/tests/protocol.spec.ts index 8067bb10c4..9716a5ff5e 100644 --- a/packages/experimental/cua/tests/protocol.spec.ts +++ b/packages/experimental/cua/tests/protocol.spec.ts @@ -71,6 +71,28 @@ it('admits arbitrary key names with an explicit key-event direction', () => { expect(Request.parse(request)).toEqual(request) }) +it.each(['left', 'right', 'middle'])('admits explicit %s mouse-button events without coordinates', (mouseButton) => { + for (const schema of [Request, SystemPointerRequest]) { + for (const direction of ['down', 'up']) { + const request = { method: 'toggleMouse', params: { appHandle: 'app', windowId: '23', mouseButton, direction } } + expect(schema.parse(request)).toEqual(request) + } + } +}) + +it.each([ + { mouseButton: undefined }, { mouseButton: 'back' }, + { direction: undefined }, { direction: 'press' }, + { appHandle: undefined }, { windowId: undefined }, + { x: 1 }, { y: 2 }, { relative: true }, { elementId: '0' }, { snapshotId: 'snapshot' }, + { modifiers: [] }, { useSystemPointer: true }, +])('rejects invalid mouse-button event parameters %j', (invalid) => { + const params = { appHandle: 'app', windowId: '23', mouseButton: 'left', direction: 'down', ...invalid } + for (const schema of [Request, SystemPointerRequest]) { + expect(schema.safeParse({ method: 'toggleMouse', params }).success).toBe(false) + } +}) + it.each([ { appHandle: 'app', snapshotId: 'snapshot', elementId: '0' }, { appHandle: 'app', windowId: '23', x: 1, y: 2 }, diff --git a/snapshots/sdk/cua-run-code/system-prompt.expected.md b/snapshots/sdk/cua-run-code/system-prompt.expected.md index 92190be4ef..db7bd43972 100644 --- a/snapshots/sdk/cua-run-code/system-prompt.expected.md +++ b/snapshots/sdk/cua-run-code/system-prompt.expected.md @@ -65,10 +65,14 @@ Read getAccessibilityTree explicitly before using element ids. Selection and scr - setValue(elementId: string, value: JsonValue) -> ActionResult — write a control value. - selectText(elementId: string, text: string, options?: { prefix?: string, suffix?: string, selectionType?: 'text' | 'cursor_before' | 'cursor_after' }) -> ActionResult — select one literal occurrence or place the cursor beside it, using adjacent context to disambiguate. -## Simulated mouse -Use an explicit window for screenshots and pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. +## Screenshots +Use an explicit window for screenshots. - getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. + +## Simulated mouse +Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window. @@ -82,6 +86,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. +click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. + Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. AX read defaults: maxElements=2000, maxDepth=25. diff --git a/snapshots/session/cua-native/system-prompt.expected.md b/snapshots/session/cua-native/system-prompt.expected.md index 572b8f2eb0..3cc3ebd954 100644 --- a/snapshots/session/cua-native/system-prompt.expected.md +++ b/snapshots/session/cua-native/system-prompt.expected.md @@ -66,12 +66,16 @@ Read getAccessibilityTree explicitly before using element ids. Selection and scr - setValue(elementId: string, value: JsonValue) -> ActionResult — write a control value. - selectText(elementId: string, text: string, options?: { prefix?: string, suffix?: string, selectionType?: 'text' | 'cursor_before' | 'cursor_after' }) -> ActionResult — select one literal occurrence or place the cursor beside it, using adjacent context to disambiguate. +## Screenshots +Use an explicit window for screenshots. +- getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. + ## Simulated mouse Leave useSystemPointer unset for ordinary mouseMove and drag calls, even after approval. Prefer selectText for a supported text range and ordinary window-directed drag for a draggable control. If the effect is unclear, inspect the window before choosing another action. Request the system pointer only when the user explicitly asks for it or the intended effect requires it. -Use an explicit window for screenshots and pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. -- getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. +Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemPointer?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemPointer omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. Not implemented on macOS. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemPointer?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemPointer or passing false directs the drag to the window without asking for mouse control. An explicit system drag shares the session decision with mouseMove and holds the chosen button along the path in the unobscured foreground window. @@ -85,6 +89,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. Send 'down' to hold a key across tool calls in one program, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this program returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. + Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. Only if the task cannot be completed without moving the user’s pointer, call await win.mouseMove(target, { useSystemPointer: true }). Prefer an advertised accessibility action, a click on a visible control, or browser tools when possible. The question interrupts the user. When approval is disabled an explicit move can act immediately. Pass true on every physical move, even after approval. Omitting the option or passing false uses the default hover route without prompting. Approval or refusal lasts until this session closes or DSH restarts. A refusal sends no input. If the user dismisses the request, ask again only if they request it. Wait for an outstanding request to finish. Subagents cannot request physical movement. diff --git a/snapshots/session/cua-native/tool-schemas.expected.json b/snapshots/session/cua-native/tool-schemas.expected.json index 1afadeca68..ec3478d7c2 100644 --- a/snapshots/session/cua-native/tool-schemas.expected.json +++ b/snapshots/session/cua-native/tool-schemas.expected.json @@ -462,6 +462,55 @@ ], "additionalProperties": false }, + { + "type": "object", + "properties": { + "method": { + "type": "string", + "const": "toggleMouse" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "string", + "minLength": 1 + }, + "mouseButton": { + "type": "string", + "enum": [ + "left", + "right", + "middle" + ] + }, + "direction": { + "type": "string", + "enum": [ + "down", + "up" + ] + } + }, + "required": [ + "appHandle", + "windowId", + "mouseButton", + "direction" + ], + "additionalProperties": false + } + }, + "required": [ + "method", + "params" + ], + "additionalProperties": false + }, { "type": "object", "properties": { diff --git a/snapshots/session/cua-ptc/system-prompt.expected.md b/snapshots/session/cua-ptc/system-prompt.expected.md index ff53e75417..e081a0a66c 100644 --- a/snapshots/session/cua-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-ptc/system-prompt.expected.md @@ -68,12 +68,16 @@ Read getAccessibilityTree explicitly before using element ids. Selection and scr - setValue(elementId: string, value: JsonValue) -> ActionResult — write a control value. - selectText(elementId: string, text: string, options?: { prefix?: string, suffix?: string, selectionType?: 'text' | 'cursor_before' | 'cursor_after' }) -> ActionResult — select one literal occurrence or place the cursor beside it, using adjacent context to disambiguate. +## Screenshots +Use an explicit window for screenshots. +- getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. + ## Simulated mouse Leave useSystemPointer unset for ordinary mouseMove and drag calls, even after approval. Prefer selectText for a supported text range and ordinary window-directed drag for a draggable control. If the effect is unclear, inspect the window before choosing another action. Request the system pointer only when the user explicitly asks for it or the intended effect requires it. -Use an explicit window for screenshots and pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. -- getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. +Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemPointer?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemPointer omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. Not implemented on macOS. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemPointer?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemPointer or passing false directs the drag to the window without asking for mouse control. An explicit system drag shares the session decision with mouseMove and holds the chosen button along the path in the unobscured foreground window. @@ -87,6 +91,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. Send 'down' to hold a key across tool calls in one program, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this program returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. + Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. Only if the task cannot be completed without moving the user’s pointer, call await win.mouseMove(target, { useSystemPointer: true }). Prefer an advertised accessibility action, a click on a visible control, or browser tools when possible. The question interrupts the user. When approval is disabled an explicit move can act immediately. Pass true on every physical move, even after approval. Omitting the option or passing false uses the default hover route without prompting. Approval or refusal lasts until this session closes or DSH restarts. A refusal sends no input. If the user dismisses the request, ask again only if they request it. Wait for an outstanding request to finish. Subagents cannot request physical movement. 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 893532843c..bb4eb419d5 100644 --- a/snapshots/session/cua-run-code-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-run-code-ptc/system-prompt.expected.md @@ -66,10 +66,14 @@ Read getAccessibilityTree explicitly before using element ids. Selection and scr - setValue(elementId: string, value: JsonValue) -> ActionResult — write a control value. - selectText(elementId: string, text: string, options?: { prefix?: string, suffix?: string, selectionType?: 'text' | 'cursor_before' | 'cursor_after' }) -> ActionResult — select one literal occurrence or place the cursor beside it, using adjacent context to disambiguate. -## Simulated mouse -Use an explicit window for screenshots and pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. +## Screenshots +Use an explicit window for screenshots. - getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. + +## Simulated mouse +Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window. @@ -83,6 +87,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. +click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. + Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. AX read defaults: maxElements=2000, maxDepth=25. diff --git a/snapshots/session/cua-run-code/system-prompt.expected.md b/snapshots/session/cua-run-code/system-prompt.expected.md index 1545776e2c..a194b2db34 100644 --- a/snapshots/session/cua-run-code/system-prompt.expected.md +++ b/snapshots/session/cua-run-code/system-prompt.expected.md @@ -64,10 +64,14 @@ Read getAccessibilityTree explicitly before using element ids. Selection and scr - setValue(elementId: string, value: JsonValue) -> ActionResult — write a control value. - selectText(elementId: string, text: string, options?: { prefix?: string, suffix?: string, selectionType?: 'text' | 'cursor_before' | 'cursor_after' }) -> ActionResult — select one literal occurrence or place the cursor beside it, using adjacent context to disambiguate. -## Simulated mouse -Use an explicit window for screenshots and pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. +## Screenshots +Use an explicit window for screenshots. - getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. + +## Simulated mouse +Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window. @@ -81,6 +85,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. +click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. + Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. AX read defaults: maxElements=2000, maxDepth=25. diff --git a/snapshots/session/ptc-script-retained/system-prompt.expected.md b/snapshots/session/ptc-script-retained/system-prompt.expected.md index 0b31f65856..c2333aa706 100644 --- a/snapshots/session/ptc-script-retained/system-prompt.expected.md +++ b/snapshots/session/ptc-script-retained/system-prompt.expected.md @@ -68,12 +68,16 @@ Read getAccessibilityTree explicitly before using element ids. Selection and scr - setValue(elementId: string, value: JsonValue) -> ActionResult — write a control value. - selectText(elementId: string, text: string, options?: { prefix?: string, suffix?: string, selectionType?: 'text' | 'cursor_before' | 'cursor_after' }) -> ActionResult — select one literal occurrence or place the cursor beside it, using adjacent context to disambiguate. +## Screenshots +Use an explicit window for screenshots. +- getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. + ## Simulated mouse Leave useSystemPointer unset for ordinary mouseMove and drag calls, even after approval. Prefer selectText for a supported text range and ordinary window-directed drag for a draggable control. If the effect is unclear, inspect the window before choosing another action. Request the system pointer only when the user explicitly asks for it or the intended effect requires it. -Use an explicit window for screenshots and pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. -- getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. +Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemPointer?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemPointer omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. Not implemented on macOS. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemPointer?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemPointer or passing false directs the drag to the window without asking for mouse control. An explicit system drag shares the session decision with mouseMove and holds the chosen button along the path in the unobscured foreground window. @@ -87,6 +91,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. Send 'down' to hold a key across tool calls in one program, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this program returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. + Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. Only if the task cannot be completed without moving the user’s pointer, call await win.mouseMove(target, { useSystemPointer: true }). Prefer an advertised accessibility action, a click on a visible control, or browser tools when possible. The question interrupts the user. When approval is disabled an explicit move can act immediately. Pass true on every physical move, even after approval. Omitting the option or passing false uses the default hover route without prompting. Approval or refusal lasts until this session closes or DSH restarts. A refusal sends no input. If the user dismisses the request, ask again only if they request it. Wait for an outstanding request to finish. Subagents cannot request physical movement. From 8cbd73efff1edc494723f8f0f28a1943585b39ce Mon Sep 17 00:00:00 2001 From: ZiyaZhang <199893125+ZiyaZhang@users.noreply.github.com> Date: Mon, 16 Nov 2026 03:48:59 -0800 Subject: [PATCH 30/31] feat(ui-schedule): scope the weekly review to the user's own work The weekly review request now asks for what the user did in the current workspace this week. In a code repository it looks only at the user's commits this week and the pull requests the user opened that merged this week or are still open, instead of every commit and pull request in the repository. The tile description follows the same scope in all eight languages. --- .../schedule-recommendations-en.expected.md | 2 +- .../schedule-recommendations-zh.expected.md | 2 +- .../src/client/recommendation-locales.ts | 32 +++++++++---------- 3 files changed, 18 insertions(+), 18 deletions(-) diff --git a/apps/web/tests/expected/schedule-recommendations-en.expected.md b/apps/web/tests/expected/schedule-recommendations-en.expected.md index b11eeadea2..a51962831d 100644 --- a/apps/web/tests/expected/schedule-recommendations-en.expected.md +++ b/apps/web/tests/expected/schedule-recommendations-en.expected.md @@ -4,7 +4,7 @@ - listitem: - button "Daily brief": Daily brief Recent changes in the workspace and what needs follow-up, with what to do first today. Weekdays at 9:00 - listitem: - - button "Weekly review": Weekly review This week's changes in the workspace, with loose ends and what to do first next week. Fridays at {{clock}} + - button "Weekly review": Weekly review Your work in the workspace this week, with loose ends and what to do first next week. Fridays at {{clock}} - listitem: - button "Issue scan": Issue scan Sort new issues into bugs, requests, and questions, and flag duplicates and ones that need a reply. Weekdays at {{clock}} - listitem: diff --git a/apps/web/tests/expected/schedule-recommendations-zh.expected.md b/apps/web/tests/expected/schedule-recommendations-zh.expected.md index f4d7e76203..2bf44e32c5 100644 --- a/apps/web/tests/expected/schedule-recommendations-zh.expected.md +++ b/apps/web/tests/expected/schedule-recommendations-zh.expected.md @@ -4,7 +4,7 @@ - listitem: - button "每日简报": 每日简报 汇总工作区最近的变化和待跟进的事,列出今天先做什么。 工作日 9:00 - listitem: - - button "每周回顾": 每周回顾 回顾这周工作区的变化,列出没收尾的事和下周先做什么。 周五 {{clock}} + - button "每周回顾": 每周回顾 回顾自己这周在工作区做的事,列出没收尾的事和下周先做什么。 周五 {{clock}} - listitem: - button "Issue 扫描": Issue 扫描 把新开的 issue 分成 bug、需求、提问,标出重复的和需要回复的。 工作日 {{clock}} - listitem: diff --git a/packages/client/ui-schedule/src/client/recommendation-locales.ts b/packages/client/ui-schedule/src/client/recommendation-locales.ts index ab52e0392c..c7c685dac7 100644 --- a/packages/client/ui-schedule/src/client/recommendation-locales.ts +++ b/packages/client/ui-schedule/src/client/recommendation-locales.ts @@ -8,9 +8,9 @@ export const recommendationEn = { 'recommend.dailyBrief.schedule': 'Weekdays at 9:00', 'recommend.dailyBrief.prompt': 'Create an automation task named "Daily brief": every weekday at 9:00, review the last 24 hours of changes in the current workspace and list what needs my follow-up and what to do first today; when the workspace is a code repository, also cover new commits, pull requests awaiting my review, and failing CI.', 'recommend.weeklyReview.title': 'Weekly review', - 'recommend.weeklyReview.description': 'This week\'s changes in the workspace, with loose ends and what to do first next week.', + 'recommend.weeklyReview.description': 'Your work in the workspace this week, with loose ends and what to do first next week.', 'recommend.weeklyReview.schedule': 'Fridays at 16:00', - 'recommend.weeklyReview.prompt': 'Create an automation task named "Weekly review": every Friday at 16:00, review this week\'s changes in the current workspace, summarize what got done, and list what is still unfinished and what to do first next week; when the workspace is a code repository, also cover this week\'s commits, merged pull requests, and pull requests still open. Summarize here only; do not change files in the workspace.', + 'recommend.weeklyReview.prompt': 'Create an automation task named "Weekly review": every Friday at 16:00, review what I did in the current workspace this week and list what is still unfinished and what to do first next week; when the workspace is a code repository, look only at my commits this week and the pull requests I opened that were merged this week or are still open. Summarize here only; do not change files in the workspace.', 'recommend.issueScan.title': 'Issue scan', 'recommend.issueScan.description': 'Sort new issues into bugs, requests, and questions, and flag duplicates and ones that need a reply.', 'recommend.issueScan.schedule': 'Weekdays at 10:00', @@ -45,9 +45,9 @@ export const recommendationZh: Record = { 'recommend.dailyBrief.schedule': '工作日 9:00', 'recommend.dailyBrief.prompt': '创建一个名为「每日简报」的自动化任务:每个工作日 9:00 查看当前工作区过去 24 小时的变化,列出需要我跟进的事和今天先做的事;工作区是代码仓库时,也看新提交、待我评审的 PR 和失败的 CI。', 'recommend.weeklyReview.title': '每周回顾', - 'recommend.weeklyReview.description': '回顾这周工作区的变化,列出没收尾的事和下周先做什么。', + 'recommend.weeklyReview.description': '回顾自己这周在工作区做的事,列出没收尾的事和下周先做什么。', 'recommend.weeklyReview.schedule': '周五 16:00', - 'recommend.weeklyReview.prompt': '创建一个名为「每周回顾」的自动化任务:每周五 16:00 回顾当前工作区这一周的变化,总结这周做了什么,列出还没收尾的事和下周先做的事;工作区是代码仓库时,也看这周的提交、合入的 PR 和还开着的 PR。只在这里汇总,不改工作区里的文件。', + 'recommend.weeklyReview.prompt': '创建一个名为「每周回顾」的自动化任务:每周五 16:00 回顾我这一周在当前工作区做了什么,列出还没收尾的事和下周先做的事;工作区是代码仓库时,只看我这周的提交,以及我提的、这周合入或还开着的 PR。只在这里汇总,不改工作区里的文件。', 'recommend.issueScan.title': 'Issue 扫描', 'recommend.issueScan.description': '把新开的 issue 分成 bug、需求、提问,标出重复的和需要回复的。', 'recommend.issueScan.schedule': '工作日 10:00', @@ -82,9 +82,9 @@ export const recommendationJa: Record = { 'recommend.dailyBrief.schedule': '平日 9:00', 'recommend.dailyBrief.prompt': '「デイリーブリーフィング」という名前の自動化タスクを作成してください。平日は毎日 9:00 に、現在のワークスペースの過去24時間の変化を確認し、私がフォローすべきことと今日最初にやることを挙げてください。ワークスペースがコードリポジトリの場合は、新しいコミット、私のレビュー待ちのプルリクエスト、失敗した CI も確認してください。', 'recommend.weeklyReview.title': '週次レビュー', - 'recommend.weeklyReview.description': '今週のワークスペースの変化を振り返り、やり残したことと来週最初にやることを挙げます。', + 'recommend.weeklyReview.description': '今週ワークスペースで自分がしたことを振り返り、やり残したことと来週最初にやることを挙げます。', 'recommend.weeklyReview.schedule': '毎週金曜日 16:00', - 'recommend.weeklyReview.prompt': '「週次レビュー」という名前の自動化タスクを作成してください。毎週金曜日の 16:00 に、現在のワークスペースの今週の変化を振り返り、今週やったことをまとめて、まだ終わっていないことと来週最初にやることを挙げてください。ワークスペースがコードリポジトリの場合は、今週のコミット、マージされたプルリクエスト、まだオープンのプルリクエストも確認してください。まとめはここでだけ行い、ワークスペースのファイルは変更しないでください。', + 'recommend.weeklyReview.prompt': '「週次レビュー」という名前の自動化タスクを作成してください。毎週金曜日の 16:00 に、今週私が現在のワークスペースでしたことを振り返り、まだ終わっていないことと来週最初にやることを挙げてください。ワークスペースがコードリポジトリの場合は、今週の私のコミットと、私が作成したプルリクエストのうち今週マージされたものとまだオープンのものだけを確認してください。まとめはここでだけ行い、ワークスペースのファイルは変更しないでください。', 'recommend.issueScan.title': 'Issue スキャン', 'recommend.issueScan.description': '新しい Issue をバグ・要望・質問に分類し、重複しているものと返信が必要なものを指摘します。', 'recommend.issueScan.schedule': '平日 10:00', @@ -119,9 +119,9 @@ export const recommendationEs: Record = { 'recommend.dailyBrief.schedule': 'De lunes a viernes a las 9:00', 'recommend.dailyBrief.prompt': 'Crea una tarea de automatización llamada «Resumen diario»: de lunes a viernes a las 9:00, revisa los cambios de las últimas 24 horas en el espacio de trabajo actual y enumera lo que requiere mi seguimiento y lo primero que debo hacer hoy; si el espacio de trabajo es un repositorio de código, incluye también los commits nuevos, los pull requests pendientes de mi revisión y los fallos de CI.', 'recommend.weeklyReview.title': 'Revisión semanal', - 'recommend.weeklyReview.description': 'Cambios de la semana en el espacio de trabajo, con lo pendiente y lo primero que hacer la próxima semana.', + 'recommend.weeklyReview.description': 'Tu trabajo de la semana en el espacio de trabajo, con lo pendiente y lo primero que hacer la próxima semana.', 'recommend.weeklyReview.schedule': 'Los viernes a las 16:00', - 'recommend.weeklyReview.prompt': 'Crea una tarea de automatización llamada «Revisión semanal»: todos los viernes a las 16:00, repasa los cambios de esta semana en el espacio de trabajo actual, resume lo que se hizo y enumera lo que queda pendiente y lo primero que debo hacer la próxima semana; si el espacio de trabajo es un repositorio de código, incluye también los commits de la semana, los pull requests fusionados y los que siguen abiertos. Haz el resumen solo aquí; no modifiques archivos del espacio de trabajo.', + 'recommend.weeklyReview.prompt': 'Crea una tarea de automatización llamada «Revisión semanal»: todos los viernes a las 16:00, repasa lo que hice esta semana en el espacio de trabajo actual y enumera lo que queda pendiente y lo primero que debo hacer la próxima semana; si el espacio de trabajo es un repositorio de código, revisa solo mis commits de esta semana y los pull requests que abrí que se fusionaron esta semana o siguen abiertos. Haz el resumen solo aquí; no modifiques archivos del espacio de trabajo.', 'recommend.issueScan.title': 'Revisión de issues', 'recommend.issueScan.description': 'Clasifica los issues nuevos en bugs, solicitudes y preguntas, y señala los duplicados y los que necesitan respuesta.', 'recommend.issueScan.schedule': 'De lunes a viernes a las 10:00', @@ -156,9 +156,9 @@ export const recommendationFr: Record = { 'recommend.dailyBrief.schedule': 'Du lundi au vendredi à 9:00', 'recommend.dailyBrief.prompt': 'Crée une tâche d\'automatisation nommée « Résumé quotidien » : du lundi au vendredi à 9:00, passe en revue les changements des dernières 24 heures dans l\'espace de travail actuel et liste ce qui demande mon suivi et ce que je dois faire en premier aujourd\'hui ; si l\'espace de travail est un dépôt de code, couvre aussi les nouveaux commits, les pull requests en attente de ma revue et les échecs de CI.', 'recommend.weeklyReview.title': 'Bilan hebdomadaire', - 'recommend.weeklyReview.description': 'Changements de la semaine dans l\'espace de travail, avec ce qui reste à terminer et les priorités de la semaine prochaine.', + 'recommend.weeklyReview.description': 'Votre travail de la semaine dans l\'espace de travail, avec ce qui reste à terminer et les priorités de la semaine prochaine.', 'recommend.weeklyReview.schedule': 'Le vendredi à 16:00', - 'recommend.weeklyReview.prompt': 'Crée une tâche d\'automatisation nommée « Bilan hebdomadaire » : tous les vendredis à 16:00, passe en revue les changements de la semaine dans l\'espace de travail actuel, résume ce qui a été fait et liste ce qui reste à terminer et ce que je dois faire en premier la semaine prochaine ; si l\'espace de travail est un dépôt de code, couvre aussi les commits de la semaine, les pull requests fusionnées et celles encore ouvertes. Fais le résumé ici uniquement ; ne modifie pas les fichiers de l\'espace de travail.', + 'recommend.weeklyReview.prompt': 'Crée une tâche d\'automatisation nommée « Bilan hebdomadaire » : tous les vendredis à 16:00, passe en revue ce que j\'ai fait cette semaine dans l\'espace de travail actuel et liste ce qui reste à terminer et ce que je dois faire en premier la semaine prochaine ; si l\'espace de travail est un dépôt de code, ne regarde que mes commits de la semaine et les pull requests que j\'ai ouvertes qui ont été fusionnées cette semaine ou sont encore ouvertes. Fais le résumé ici uniquement ; ne modifie pas les fichiers de l\'espace de travail.', 'recommend.issueScan.title': 'Analyse des issues', 'recommend.issueScan.description': 'Trie les nouvelles issues en bugs, demandes et questions, et signale les doublons et celles qui nécessitent une réponse.', 'recommend.issueScan.schedule': 'Du lundi au vendredi à 10:00', @@ -193,9 +193,9 @@ export const recommendationDe: Record = { 'recommend.dailyBrief.schedule': 'Mo–Fr um 9:00', 'recommend.dailyBrief.prompt': 'Erstelle eine Automatisierungsaufgabe namens „Tagesüberblick“: Prüfe montags bis freitags um 9:00 Uhr die Änderungen der letzten 24 Stunden im aktuellen Arbeitsbereich und liste auf, was ich nachverfolgen muss und was heute zuerst ansteht; ist der Arbeitsbereich ein Code-Repository, berücksichtige auch neue Commits, auf mein Review wartende Pull Requests und fehlgeschlagene CI-Läufe.', 'recommend.weeklyReview.title': 'Wochenrückblick', - 'recommend.weeklyReview.description': 'Änderungen der Woche im Arbeitsbereich, dazu offene Punkte und was nächste Woche zuerst ansteht.', + 'recommend.weeklyReview.description': 'Die eigene Arbeit dieser Woche im Arbeitsbereich, dazu offene Punkte und was nächste Woche zuerst ansteht.', 'recommend.weeklyReview.schedule': 'Freitags um 16:00', - 'recommend.weeklyReview.prompt': 'Erstelle eine Automatisierungsaufgabe namens „Wochenrückblick“: Blicke freitags um 16:00 Uhr auf die Änderungen dieser Woche im aktuellen Arbeitsbereich zurück, fasse zusammen, was erledigt wurde, und liste auf, was noch offen ist und was nächste Woche zuerst ansteht; ist der Arbeitsbereich ein Code-Repository, berücksichtige auch die Commits dieser Woche sowie gemergte und noch offene Pull Requests. Fasse alles nur hier zusammen; ändere keine Dateien im Arbeitsbereich.', + 'recommend.weeklyReview.prompt': 'Erstelle eine Automatisierungsaufgabe namens „Wochenrückblick“: Blicke freitags um 16:00 Uhr darauf zurück, was ich diese Woche im aktuellen Arbeitsbereich gemacht habe, und liste auf, was noch offen ist und was nächste Woche zuerst ansteht; ist der Arbeitsbereich ein Code-Repository, berücksichtige nur meine Commits dieser Woche und die von mir eröffneten Pull Requests, die diese Woche gemergt wurden oder noch offen sind. Fasse alles nur hier zusammen; ändere keine Dateien im Arbeitsbereich.', 'recommend.issueScan.title': 'Issue-Sichtung', 'recommend.issueScan.description': 'Sortiert neue Issues in Bugs, Feature-Wünsche und Fragen und hebt Duplikate sowie Issues hervor, die eine Antwort brauchen.', 'recommend.issueScan.schedule': 'Mo–Fr um 10:00', @@ -230,9 +230,9 @@ export const recommendationRu: Record = { 'recommend.dailyBrief.schedule': 'По будням в 9:00', 'recommend.dailyBrief.prompt': 'Создай задачу автоматизации под названием «Ежедневная сводка»: по будням в 9:00 просматривай изменения в текущей рабочей области за последние 24 часа и перечисляй, что требует моего внимания и с чего начать сегодня; если рабочая область — репозиторий кода, учитывай также новые коммиты, пул-реквесты, ожидающие моего ревью, и сбои CI.', 'recommend.weeklyReview.title': 'Еженедельный обзор', - 'recommend.weeklyReview.description': 'Изменения за неделю в рабочем пространстве, незавершённые дела и первоочередные задачи на следующую неделю.', + 'recommend.weeklyReview.description': 'Ваша работа за неделю в рабочем пространстве, незавершённые дела и первоочередные задачи на следующую неделю.', 'recommend.weeklyReview.schedule': 'По пятницам в 16:00', - 'recommend.weeklyReview.prompt': 'Создай задачу автоматизации под названием «Еженедельный обзор»: по пятницам в 16:00 просматривай изменения за эту неделю в текущем рабочем пространстве, подводи итог сделанного и перечисляй, что ещё не завершено и с чего начать на следующей неделе; если рабочее пространство — репозиторий кода, учитывай также коммиты за неделю, слитые и ещё открытые пул-реквесты. Сводку пиши только здесь; файлы в рабочем пространстве не меняй.', + 'recommend.weeklyReview.prompt': 'Создай задачу автоматизации под названием «Еженедельный обзор»: по пятницам в 16:00 просматривай мою работу за эту неделю в текущем рабочем пространстве и перечисляй, что ещё не завершено и с чего начать на следующей неделе; если рабочее пространство — репозиторий кода, учитывай только мои коммиты за неделю и мои пул-реквесты, слитые на этой неделе или ещё открытые. Сводку пиши только здесь; файлы в рабочем пространстве не меняй.', 'recommend.issueScan.title': 'Обзор issues', 'recommend.issueScan.description': 'Делит новые issues на баги, пожелания и вопросы и выделяет дубликаты и те, на которые нужно ответить.', 'recommend.issueScan.schedule': 'По будням в 10:00', @@ -267,9 +267,9 @@ export const recommendationPt: Record = { 'recommend.dailyBrief.schedule': 'Segunda a sexta às 9:00', 'recommend.dailyBrief.prompt': 'Crie uma tarefa de automação chamada “Resumo diário”: de segunda a sexta às 9:00, revise as mudanças das últimas 24 horas no espaço de trabalho atual e liste o que precisa do meu acompanhamento e o que fazer primeiro hoje; se o espaço de trabalho for um repositório de código, inclua também os novos commits, os pull requests aguardando minha revisão e as falhas de CI.', 'recommend.weeklyReview.title': 'Revisão semanal', - 'recommend.weeklyReview.description': 'Mudanças da semana no espaço de trabalho, com o que ficou pendente e o que fazer primeiro na próxima semana.', + 'recommend.weeklyReview.description': 'Seu trabalho da semana no espaço de trabalho, com o que ficou pendente e o que fazer primeiro na próxima semana.', 'recommend.weeklyReview.schedule': 'Sextas às 16:00', - 'recommend.weeklyReview.prompt': 'Crie uma tarefa de automação chamada “Revisão semanal”: toda sexta-feira às 16:00, revise as mudanças desta semana no espaço de trabalho atual, resuma o que foi feito e liste o que ainda está pendente e o que fazer primeiro na próxima semana; se o espaço de trabalho for um repositório de código, inclua também os commits da semana, os pull requests mesclados e os que continuam abertos. Faça o resumo só aqui; não altere arquivos do espaço de trabalho.', + 'recommend.weeklyReview.prompt': 'Crie uma tarefa de automação chamada “Revisão semanal”: toda sexta-feira às 16:00, revise o que eu fiz esta semana no espaço de trabalho atual e liste o que ainda está pendente e o que fazer primeiro na próxima semana; se o espaço de trabalho for um repositório de código, veja só os meus commits da semana e os pull requests que eu abri que foram mesclados esta semana ou continuam abertos. Faça o resumo só aqui; não altere arquivos do espaço de trabalho.', 'recommend.issueScan.title': 'Varredura de issues', 'recommend.issueScan.description': 'Classifica as novas issues em bugs, solicitações e perguntas e destaca as duplicadas e as que precisam de resposta.', 'recommend.issueScan.schedule': 'Segunda a sexta às 10:00', From 0c8078e19652d98ab6dbba0a2a42137d536ec189 Mon Sep 17 00:00:00 2001 From: LegGasai Date: Tue, 17 Nov 2026 00:13:00 +0800 Subject: [PATCH 31/31] feat(forge): name worktree branches, start them from remote branches, and show changes being read (#8536) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(forge): name worktree branches, start them from remote branches, and show changes being read The New Session worktree option's base menu now searches local branches and each remote's branches, pins the current branch and every remote's default branch, and names each remote group by its repository. Its last row opens a dialog that names the new branch, starting from `worktreePrefix` and checking Git's branch-name rules; the Host refuses an invalid or taken name. A request records the full ref of its base and the optional name; every attempt uses the name. A remote-tracking base is fetched first: the worktree service gains a `fetch` request field and a `fetch` phase, fetching only that branch without tags. A failed fetch leaves the message waiting with Retry, Use the last fetched version, and Continue without a worktree; a taken name offers Rename. While the changes view reads changes it has not shown yet, it says "Reading changes" above file card placeholders, and the files menu names no count. * fix(worktree): forward only the declared create_worktree arguments The create_worktree parameter object is open, and the tool passed it to the worktree runtime unchanged. Now that a runtime request can ask to fetch, an undeclared `fetch: true` from the model would have fetched, or refused a local `from`. The tool now forwards only `name` and `from`, so it never fetches. * docs(forge): say that only generated worktree branch names come from the Session id * fix(forge): keep the collapsed change request status on one line In the Session panel the collapsed card's number line kept every part at full width inside a clipping row, so a narrow panel cut the most urgent flag off without an ellipsis, such as "有冲突" after "3 项检查失败". The number and status now form one MarqueeText line as wide as the row. While the line with failed checks does not fit, they take the shorter wording without their count; a line that still does not fit ends in an ellipsis and crawls into view with the title while the pointer rests on the card's head. The line measures again when its width or the fonts change. Expanded cards keep their branch names as before. * fix(forge): hide remote credentials and read the branch a tag shares its name with The base menu named an unrecognized remote's group by its fetch URL as `git remote -v` prints it, so a token in the URL, such as `https://oauth2:glpat-...@gitlab.example/...`, reached the browser and showed in the menu. The group now shows the URL without its user name and password. Inspection read the checked-out branch with `symbolic-ref --short HEAD`, which prints `heads/main` while a tag is also named `main`; the New Session option then requested `refs/heads/heads/main` and every worktree attempt failed. Inspection now reads the full ref and takes the name under `refs/heads/`, so the option, the pinned current branch, and the checkout row name `main`. HEAD that names a ref outside `refs/heads/` reads as no branch. * test(worktree): set up nested remotes and line endings the CI runners' Git accepts Git 2.55 on the CI runners refuses `git remote add team` next to an existing `team/fork` remote; the check runs only in `git remote add`, so the longest-remote case now writes the second remote with `git config`, as configuration written earlier or by hand holds it. The test clone also turns off `core.autocrlf`, as `repository` does, because the Windows runner's global setting checked the fetched file out with CRLF. --- apps/web/tests/forge-panel.e2e.ts | 8 +- docs/config-catalog.md | 2 +- docs/config-catalog.zh.md | 2 +- docs/subsystems/forge.md | 120 +++++-- docs/subsystems/forge.zh.md | 120 +++++-- docs/subsystems/worktrees.i18n.yaml | 4 +- docs/subsystems/worktrees.md | 28 +- docs/subsystems/worktrees.zh.md | 28 +- .../client-ui-forge/README.i18n.yaml | 12 +- .../experimental/client-ui-forge/README.md | 20 +- .../experimental/client-ui-forge/README.zh.md | 20 +- .../client-ui-forge/src/branch-name.ts | 74 ++++ .../client-ui-forge/src/client/BaseMenu.tsx | 54 +-- .../src/client/ChangeRequestCard.tsx | 106 +++++- .../src/client/ChangedFiles.tsx | 10 +- .../src/client/ChangesLoading.module.css | 110 ++++++ .../src/client/ChangesLoading.tsx | 69 ++++ .../client-ui-forge/src/client/ChangesTab.tsx | 9 +- .../src/client/Forge.module.css | 27 +- .../src/client/SessionHoverForge.tsx | 3 +- .../src/client/WorktreeNameDialog.module.css | 53 +++ .../src/client/WorktreeNameDialog.tsx | 93 +++++ .../src/client/WorktreeProgress.tsx | 135 ++++++-- .../src/client/WorktreeToggle.module.css | 156 ++++++++- .../src/client/WorktreeToggle.tsx | 240 +++++++++---- .../src/client/branch-search.tsx | 90 +++++ .../client-ui-forge/src/client/checkout.ts | 3 +- .../client-ui-forge/src/client/locales.ts | 320 +++++++++++++++++- .../client-ui-forge/src/client/mount.ts | 26 +- .../experimental/client-ui-forge/src/git.ts | 45 +-- .../experimental/client-ui-forge/src/index.ts | 101 +++--- .../client-ui-forge/src/local-diff.ts | 4 +- .../experimental/client-ui-forge/src/panel.ts | 5 +- .../experimental/client-ui-forge/src/parse.ts | 96 +++++- .../experimental/client-ui-forge/src/types.ts | 79 ++++- .../client-ui-forge/src/worktree.ts | 96 ++++-- .../tests/branch-name.host.spec.ts | 76 +++++ .../tests/change-request-card.client.spec.tsx | 74 +++- .../tests/changes-tab.client.spec.tsx | 31 +- .../tests/client-fixtures.client.ts | 17 +- .../tests/controller.host.spec.ts | 240 +++++++++---- .../client-ui-forge/tests/git.host.spec.ts | 110 ++---- .../tests/mount.client.spec.ts | 60 ++-- .../client-ui-forge/tests/parse.host.spec.ts | 89 ++++- .../worktree-name-dialog.client.spec.tsx | 141 ++++++++ .../tests/worktree-progress.client.spec.tsx | 61 +++- .../tests/worktree-toggle.client.spec.tsx | 268 ++++++++++----- .../tests/worktree.host.spec.ts | 106 ++++-- .../client-ui-forge/tsconfig.client.json | 1 + .../client-ui-forge/tsconfig.host.json | 1 + .../tool-worktree/README.i18n.yaml | 4 +- packages/experimental/tool-worktree/README.md | 2 +- .../experimental/tool-worktree/README.zh.md | 2 +- .../experimental/tool-worktree/src/index.ts | 5 +- .../tests/loader-composition.spec.ts | 7 + .../experimental/worktree/README.i18n.yaml | 8 +- packages/experimental/worktree/README.md | 4 +- packages/experimental/worktree/README.zh.md | 4 +- packages/experimental/worktree/src/index.ts | 61 +++- packages/experimental/worktree/src/types.ts | 12 +- .../worktree/tests/worktree.spec.ts | 87 +++++ .../extensions/tool-cordis/src/api-catalog.ts | 62 ++-- scripts/gen-cordis-catalog.ts | 4 +- scripts/type-equiv.manifest.json | 12 +- 64 files changed, 3111 insertions(+), 806 deletions(-) create mode 100644 packages/experimental/client-ui-forge/src/branch-name.ts create mode 100644 packages/experimental/client-ui-forge/src/client/ChangesLoading.module.css create mode 100644 packages/experimental/client-ui-forge/src/client/ChangesLoading.tsx create mode 100644 packages/experimental/client-ui-forge/src/client/WorktreeNameDialog.module.css create mode 100644 packages/experimental/client-ui-forge/src/client/WorktreeNameDialog.tsx create mode 100644 packages/experimental/client-ui-forge/src/client/branch-search.tsx create mode 100644 packages/experimental/client-ui-forge/tests/branch-name.host.spec.ts create mode 100644 packages/experimental/client-ui-forge/tests/worktree-name-dialog.client.spec.tsx diff --git a/apps/web/tests/forge-panel.e2e.ts b/apps/web/tests/forge-panel.e2e.ts index 92014005f5..04fd421940 100644 --- a/apps/web/tests/forge-panel.e2e.ts +++ b/apps/web/tests/forge-panel.e2e.ts @@ -839,8 +839,8 @@ it.skipIf(MODE === 'record')('starts a Session in a worktree before its first me expect(await git(directory, 'rev-parse', 'HEAD')).toBe(baseCommit) const events = await readPersistedEvents(scaffold, sessionId) expect(worktreeRecords(events)).toEqual([ - { action: 'request', from: 'main' }, - { action: 'request', from: 'release' }, + { action: 'request', from: 'refs/heads/main' }, + { action: 'request', from: 'refs/heads/release' }, { created: { path: directory, branch, baseCommit, repositoryRoot: project } }, ]) // The worktree existed before the turn, so the first model request carried its directory notice. @@ -978,7 +978,9 @@ it.skipIf(MODE === 'record')('keeps the first message waiting when the worktree if (session === undefined) throw new Error('The Session must stay loaded') expect(scaffold.ctx.workingDirectory.get(session)).toBe(project) const events = await readPersistedEvents(scaffold, sessionId) - expect(worktreeRecords(events)).toEqual([{ action: 'request', from: 'main' }, { action: 'request', from: 'release' }, { action: 'cancel' }]) + expect(worktreeRecords(events)).toEqual([ + { action: 'request', from: 'refs/heads/main' }, { action: 'request', from: 'refs/heads/release' }, { action: 'cancel' }, + ]) expect(events.filter(event => event.type === 'turn/start')).toHaveLength(1) expect(events.some(event => event.type === 'user/message' && event.data.source.kind === 'working-directory')).toBe(false) const checkout = (await showSessionPanel(page)).locator('[data-forge-checkout]') diff --git a/docs/config-catalog.md b/docs/config-catalog.md index ffb33f34a6..2beea90aec 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1182,7 +1182,7 @@ export interface CotTranslationPreferences { ## `@deepseek-ai/dsh-experimental-client-ui-forge` - `inject`: `forge` · `forgeSession` · `sessionProjections` · `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `agents` -- `source`: [`packages/experimental/client-ui-forge/src/types.ts:485`](../packages/experimental/client-ui-forge/src/types.ts) +- `source`: [`packages/experimental/client-ui-forge/src/types.ts:530`](../packages/experimental/client-ui-forge/src/types.ts) ```ts config-catalog /** Host settings of the forge panel Remote. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 10a6bbfc1a..6d18e77f5c 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1184,7 +1184,7 @@ export interface CotTranslationPreferences { ## `@deepseek-ai/dsh-experimental-client-ui-forge` - `inject`: `forge` · `forgeSession` · `sessionProjections` · `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `agents` -- `source`: [`packages/experimental/client-ui-forge/src/types.ts:485`](../packages/experimental/client-ui-forge/src/types.ts) +- `source`: [`packages/experimental/client-ui-forge/src/types.ts:530`](../packages/experimental/client-ui-forge/src/types.ts) ```ts config-catalog /** Host settings of the forge panel Remote. */ diff --git a/docs/subsystems/forge.md b/docs/subsystems/forge.md index 11c33f58c9..edf3a8c2d9 100644 --- a/docs/subsystems/forge.md +++ b/docs/subsystems/forge.md @@ -915,7 +915,10 @@ interface ForgeSessionWorktree { readonly path: string /** Branch created for the checkout. */ readonly branch: string - /** Requested base branch, or null when the checkout started from HEAD of the source checkout. */ + /** + * Requested base: the full name of a local or remote-tracking branch, a short branch name that earlier panels + * recorded, or null when the checkout started from HEAD of the source checkout. + */ readonly from: string | null /** Commit object name the branch started from. */ readonly baseCommit: string @@ -928,8 +931,11 @@ interface ForgeSessionWorktree { ```ts type-equiv /** Payload of the `plugin:client-ui-forge/worktree` record. */ type WorktreeRecord = - /** Create a worktree before the Session's first step, starting from `from`, or from HEAD when it is null. */ - | { readonly action: 'request'; readonly from: string | null } + /** + * Create a worktree before the Session's first step, starting from `from`, or from HEAD when it is null, on the + * branch `name`, or on a generated branch name when `name` is absent. + */ + | { readonly action: 'request'; readonly from: string | null; readonly name?: string } /** Withdraw the open request. */ | { readonly action: 'cancel' } /** The requested worktree was created and became the Session's working directory. */ @@ -943,8 +949,13 @@ type WorktreeRecord = ```ts type-equiv /** One open worktree request. */ interface ForgeWorktreeRequest { - /** Base branch, or null for HEAD of the source checkout. */ + /** + * Base: the full name of a local or remote-tracking branch, a short branch name that earlier panels recorded, or + * null for HEAD of the source checkout. A remote-tracking branch is fetched before each attempt that does not skip it. + */ readonly from: string | null + /** New branch name the user chose, which every attempt uses, or null for a generated name per attempt. */ + readonly name: string | null } ``` @@ -962,12 +973,17 @@ type ForgeWorktreeBlocker = ```ts type-equiv /** One running worktree creation. */ interface ForgeWorktreeCreation { - /** Running step: `prepare` validates and creates the branch, then `checkout` writes the files. */ - readonly phase: 'prepare' | 'checkout' + /** + * Running step: `fetch` fetches a remote base branch, `prepare` validates and creates the branch, then + * `checkout` writes the files. + */ + readonly phase: 'fetch' | 'prepare' | 'checkout' /** Branch the attempt creates. */ readonly branch: string - /** Base branch, or null for HEAD. */ + /** Base as the request names it, or null for HEAD. */ readonly from: string | null + /** Whether the attempt fetches its remote base branch first. */ + readonly fetch: boolean /** * Whether a message waits for the creation before its turn starts. Only * such a creation can be stopped, after which the message keeps waiting; a @@ -990,12 +1006,16 @@ interface ForgeWorktreeRestoration { interface ForgeWorktreeFailure { /** Branch the attempt created, or null when it failed before naming one. */ readonly branch: string | null - /** Base branch of the attempt, or null for HEAD. */ + /** Base of the attempt as the request names it, or null for HEAD. */ readonly from: string | null + /** Whether the attempt fetched, or tried to fetch, its remote base branch first. */ + readonly fetch: boolean /** Step that failed. */ - readonly phase: 'prepare' | 'checkout' + readonly phase: 'fetch' | 'prepare' | 'checkout' /** Failure text. */ readonly message: string + /** Whether the branch or the checkout directory of that name already existed, which another name avoids. */ + readonly exists: boolean } ``` @@ -1026,6 +1046,8 @@ interface ForgePanelWorktree { readonly editable: boolean /** Why the checkout cannot host a worktree, or null when it can, before the first inspection, and after a failed one. */ readonly blocker: ForgeWorktreeBlocker | null + /** Prefix of generated branch names, the Config `worktreePrefix`, which a name the user types starts from. */ + readonly namePrefix: string /** Open request, or null without one. */ readonly request: ForgeWorktreeRequest | null /** Created worktree, or null before creation. */ @@ -1086,12 +1108,39 @@ interface ForgePanelState { ``` ```ts type-equiv -/** Local branches offered as the base of a new worktree. */ -interface ForgeBranches { - /** Checked-out branch, or null when HEAD is detached. */ - readonly current: string | null - /** Local branch names, `current` first and then most recently committed first, at most `maxBranches`. */ - readonly branches: readonly string[] +/** Branches offered as the base of a new worktree whose names contain a query. */ +interface ForgeWorktreeBases { + /** Checked-out branch, or null when HEAD is detached or its name does not contain the query. */ + readonly current: ForgeBaseBranch | null + /** Default branch of each remote that names one with `refs/remotes//HEAD`, in remote order. */ + readonly defaults: readonly ForgeRemoteDefault[] + /** Other local branches, most recently committed first, at most `maxBranches`. */ + readonly local: readonly ForgeBaseBranch[] + /** + * Remote-tracking branches of each configured remote in remote order: the remote the checked-out branch tracks, + * then `origin`, then the others as Git lists them. Remotes without a matching branch are left out. + */ + readonly remotes: readonly ForgeRemoteBranches[] +} +``` + +```ts type-equiv +/** A remote's default branch, which `refs/remotes//HEAD` names. */ +interface ForgeRemoteDefault extends ForgeBaseBranch { + /** Remote the branch belongs to; it may contain `/`. */ + readonly remote: string +} +``` + +```ts type-equiv +/** Remote-tracking branches of one remote, without its default branch. */ +interface ForgeRemoteBranches { + /** Remote name such as `origin`; it may contain `/`. */ + readonly name: string + /** `owner/name` of the repository a provider recognizes from the remote's URLs, else its fetch URL, or null without one. */ + readonly repository: string | null + /** Branches named `/`, most recently committed first, at most `maxBranches`. */ + readonly branches: readonly ForgeBaseBranch[] } ``` @@ -1775,13 +1824,16 @@ Serves the forge panel. Following a Session inspects the checkout of its current @Remote async worktreeCleanup(session: Session, revision: number | null): Promise /** - * List the local branches that can start a worktree of the Session's current checkout. - * @param session - Session whose current directory is listed. + * List the branches that can start a worktree of the Session's current checkout: the checked-out branch, each + * remote's default branch, other local branches, and each remote's other remote-tracking branches, remotes in the + * order the panel recognizes code hosts. + * @param session - Session whose checkout is read. + * @param query - text the branch names must contain, ignoring case; empty for every branch. * @param signal - request cancellation. - * @returns the checked-out branch and at most `maxBranches` local branches, the checked-out one first. - * @throws when the current directory is not inside a checkout or Git fails. + * @returns the branches, at most `maxBranches` local branches and `maxBranches` per remote, most recently committed first. + * @throws `forgePanel/not-a-checkout` outside a checkout; the Git error when Git fails or the listed refs exceed `maxDiffBytes`. */ -@Remote async branches(session: Session, signal: AbortSignal): Promise +@Remote async worktreeBases(session: Session, query: string, signal: AbortSignal): Promise /** * List the branches the `branch` scope of the Session's current checkout can compare with. @@ -2114,18 +2166,23 @@ registerLens(lens: ForgeLens): () => Promise /** * Ask for a new worktree before the Session's first turn, replacing an open * request and forgetting a failed attempt. While the next message waits in - * the inbox, or else at the first step proposal, the panel creates a branch - * from `from`, or from HEAD of the current checkout when it is null, and - * enters its checkout. A message that already waits after a failed or - * stopped attempt keeps waiting for {@link ForgePanelController.retryWorktree}. + * the inbox, or else at the first step proposal, the panel creates the + * branch `name`, or a generated branch per attempt when it is null, from + * `from`, or from HEAD of the current checkout when it is null, and enters + * its checkout; a remote-tracking `from` is fetched first. A message that + * already waits after a failed or stopped attempt keeps waiting for + * {@link ForgePanelController.retryWorktree}. * @param session - Session without a started turn. - * @param from - local base branch, or null for HEAD. + * @param from - full name of a local or remote-tracking base branch, or null for HEAD. + * @param name - new branch name, or null to generate one per attempt. * @param signal - request cancellation. - * @throws `forgePanel/invalid-branch` when `from` is empty; `forgePanel/worktrees-unavailable` + * @throws `forgePanel/invalid-branch` when `from` is empty; `forgePanel/invalid-name` when `name` breaks + * a branch-name rule; `forgePanel/branch-exists` when the checkout has a local branch named `name`; + * `forgePanel/not-a-checkout` when a name is checked outside a checkout; `forgePanel/worktrees-unavailable` * without a worktree service; `forgePanel/session-started` after a turn started or the worktree was * created; `forgePanel/session-busy` while the worktree is being created. */ -@Remote async requestWorktree(session: Session, from: string | null, signal: AbortSignal): Promise +@Remote async requestWorktree(session: Session, from: string | null, name: string | null, signal: AbortSignal): Promise /** * Withdraw the open worktree request of a Session with its failed attempt, @@ -2148,13 +2205,16 @@ registerLens(lens: ForgeLens): () => Promise @Remote async stopCreation(session: Session, signal: AbortSignal): Promise /** - * Make another attempt, with a new branch name, at the worktree a message - * of the Session waits for after a failed or stopped attempt. + * Make another attempt, on the requested branch name or a new generated + * one, at the worktree a message of the Session waits for after a failed or + * stopped attempt. * @param session - Session whose message waits. + * @param fetch - false skips fetching a remote-tracking base branch for this attempt, which then starts from the + * commit last fetched. * @param signal - request cancellation. * @throws `forgePanel/not-waiting` when no message waits or an attempt is running. */ -@Remote async retryWorktree(session: Session, signal: AbortSignal): Promise +@Remote async retryWorktree(session: Session, fetch: boolean, signal: AbortSignal): Promise /** * Check out the created worktree of a Session again at its recorded diff --git a/docs/subsystems/forge.zh.md b/docs/subsystems/forge.zh.md index a73e3ecdd2..1f962fae0e 100644 --- a/docs/subsystems/forge.zh.md +++ b/docs/subsystems/forge.zh.md @@ -917,7 +917,10 @@ interface ForgeSessionWorktree { readonly path: string /** Branch created for the checkout. */ readonly branch: string - /** Requested base branch, or null when the checkout started from HEAD of the source checkout. */ + /** + * Requested base: the full name of a local or remote-tracking branch, a short branch name that earlier panels + * recorded, or null when the checkout started from HEAD of the source checkout. + */ readonly from: string | null /** Commit object name the branch started from. */ readonly baseCommit: string @@ -930,8 +933,11 @@ interface ForgeSessionWorktree { ```ts type-equiv /** Payload of the `plugin:client-ui-forge/worktree` record. */ type WorktreeRecord = - /** Create a worktree before the Session's first step, starting from `from`, or from HEAD when it is null. */ - | { readonly action: 'request'; readonly from: string | null } + /** + * Create a worktree before the Session's first step, starting from `from`, or from HEAD when it is null, on the + * branch `name`, or on a generated branch name when `name` is absent. + */ + | { readonly action: 'request'; readonly from: string | null; readonly name?: string } /** Withdraw the open request. */ | { readonly action: 'cancel' } /** The requested worktree was created and became the Session's working directory. */ @@ -945,8 +951,13 @@ type WorktreeRecord = ```ts type-equiv /** One open worktree request. */ interface ForgeWorktreeRequest { - /** Base branch, or null for HEAD of the source checkout. */ + /** + * Base: the full name of a local or remote-tracking branch, a short branch name that earlier panels recorded, or + * null for HEAD of the source checkout. A remote-tracking branch is fetched before each attempt that does not skip it. + */ readonly from: string | null + /** New branch name the user chose, which every attempt uses, or null for a generated name per attempt. */ + readonly name: string | null } ``` @@ -964,12 +975,17 @@ type ForgeWorktreeBlocker = ```ts type-equiv /** One running worktree creation. */ interface ForgeWorktreeCreation { - /** Running step: `prepare` validates and creates the branch, then `checkout` writes the files. */ - readonly phase: 'prepare' | 'checkout' + /** + * Running step: `fetch` fetches a remote base branch, `prepare` validates and creates the branch, then + * `checkout` writes the files. + */ + readonly phase: 'fetch' | 'prepare' | 'checkout' /** Branch the attempt creates. */ readonly branch: string - /** Base branch, or null for HEAD. */ + /** Base as the request names it, or null for HEAD. */ readonly from: string | null + /** Whether the attempt fetches its remote base branch first. */ + readonly fetch: boolean /** * Whether a message waits for the creation before its turn starts. Only * such a creation can be stopped, after which the message keeps waiting; a @@ -992,12 +1008,16 @@ interface ForgeWorktreeRestoration { interface ForgeWorktreeFailure { /** Branch the attempt created, or null when it failed before naming one. */ readonly branch: string | null - /** Base branch of the attempt, or null for HEAD. */ + /** Base of the attempt as the request names it, or null for HEAD. */ readonly from: string | null + /** Whether the attempt fetched, or tried to fetch, its remote base branch first. */ + readonly fetch: boolean /** Step that failed. */ - readonly phase: 'prepare' | 'checkout' + readonly phase: 'fetch' | 'prepare' | 'checkout' /** Failure text. */ readonly message: string + /** Whether the branch or the checkout directory of that name already existed, which another name avoids. */ + readonly exists: boolean } ``` @@ -1028,6 +1048,8 @@ interface ForgePanelWorktree { readonly editable: boolean /** Why the checkout cannot host a worktree, or null when it can, before the first inspection, and after a failed one. */ readonly blocker: ForgeWorktreeBlocker | null + /** Prefix of generated branch names, the Config `worktreePrefix`, which a name the user types starts from. */ + readonly namePrefix: string /** Open request, or null without one. */ readonly request: ForgeWorktreeRequest | null /** Created worktree, or null before creation. */ @@ -1088,12 +1110,39 @@ interface ForgePanelState { ``` ```ts type-equiv -/** Local branches offered as the base of a new worktree. */ -interface ForgeBranches { - /** Checked-out branch, or null when HEAD is detached. */ - readonly current: string | null - /** Local branch names, `current` first and then most recently committed first, at most `maxBranches`. */ - readonly branches: readonly string[] +/** Branches offered as the base of a new worktree whose names contain a query. */ +interface ForgeWorktreeBases { + /** Checked-out branch, or null when HEAD is detached or its name does not contain the query. */ + readonly current: ForgeBaseBranch | null + /** Default branch of each remote that names one with `refs/remotes//HEAD`, in remote order. */ + readonly defaults: readonly ForgeRemoteDefault[] + /** Other local branches, most recently committed first, at most `maxBranches`. */ + readonly local: readonly ForgeBaseBranch[] + /** + * Remote-tracking branches of each configured remote in remote order: the remote the checked-out branch tracks, + * then `origin`, then the others as Git lists them. Remotes without a matching branch are left out. + */ + readonly remotes: readonly ForgeRemoteBranches[] +} +``` + +```ts type-equiv +/** A remote's default branch, which `refs/remotes//HEAD` names. */ +interface ForgeRemoteDefault extends ForgeBaseBranch { + /** Remote the branch belongs to; it may contain `/`. */ + readonly remote: string +} +``` + +```ts type-equiv +/** Remote-tracking branches of one remote, without its default branch. */ +interface ForgeRemoteBranches { + /** Remote name such as `origin`; it may contain `/`. */ + readonly name: string + /** `owner/name` of the repository a provider recognizes from the remote's URLs, else its fetch URL, or null without one. */ + readonly repository: string | null + /** Branches named `/`, most recently committed first, at most `maxBranches`. */ + readonly branches: readonly ForgeBaseBranch[] } ``` @@ -1777,13 +1826,16 @@ Serves the forge panel. Following a Session inspects the checkout of its current @Remote async worktreeCleanup(session: Session, revision: number | null): Promise /** - * List the local branches that can start a worktree of the Session's current checkout. - * @param session - Session whose current directory is listed. + * List the branches that can start a worktree of the Session's current checkout: the checked-out branch, each + * remote's default branch, other local branches, and each remote's other remote-tracking branches, remotes in the + * order the panel recognizes code hosts. + * @param session - Session whose checkout is read. + * @param query - text the branch names must contain, ignoring case; empty for every branch. * @param signal - request cancellation. - * @returns the checked-out branch and at most `maxBranches` local branches, the checked-out one first. - * @throws when the current directory is not inside a checkout or Git fails. + * @returns the branches, at most `maxBranches` local branches and `maxBranches` per remote, most recently committed first. + * @throws `forgePanel/not-a-checkout` outside a checkout; the Git error when Git fails or the listed refs exceed `maxDiffBytes`. */ -@Remote async branches(session: Session, signal: AbortSignal): Promise +@Remote async worktreeBases(session: Session, query: string, signal: AbortSignal): Promise /** * List the branches the `branch` scope of the Session's current checkout can compare with. @@ -2116,18 +2168,23 @@ registerLens(lens: ForgeLens): () => Promise /** * Ask for a new worktree before the Session's first turn, replacing an open * request and forgetting a failed attempt. While the next message waits in - * the inbox, or else at the first step proposal, the panel creates a branch - * from `from`, or from HEAD of the current checkout when it is null, and - * enters its checkout. A message that already waits after a failed or - * stopped attempt keeps waiting for {@link ForgePanelController.retryWorktree}. + * the inbox, or else at the first step proposal, the panel creates the + * branch `name`, or a generated branch per attempt when it is null, from + * `from`, or from HEAD of the current checkout when it is null, and enters + * its checkout; a remote-tracking `from` is fetched first. A message that + * already waits after a failed or stopped attempt keeps waiting for + * {@link ForgePanelController.retryWorktree}. * @param session - Session without a started turn. - * @param from - local base branch, or null for HEAD. + * @param from - full name of a local or remote-tracking base branch, or null for HEAD. + * @param name - new branch name, or null to generate one per attempt. * @param signal - request cancellation. - * @throws `forgePanel/invalid-branch` when `from` is empty; `forgePanel/worktrees-unavailable` + * @throws `forgePanel/invalid-branch` when `from` is empty; `forgePanel/invalid-name` when `name` breaks + * a branch-name rule; `forgePanel/branch-exists` when the checkout has a local branch named `name`; + * `forgePanel/not-a-checkout` when a name is checked outside a checkout; `forgePanel/worktrees-unavailable` * without a worktree service; `forgePanel/session-started` after a turn started or the worktree was * created; `forgePanel/session-busy` while the worktree is being created. */ -@Remote async requestWorktree(session: Session, from: string | null, signal: AbortSignal): Promise +@Remote async requestWorktree(session: Session, from: string | null, name: string | null, signal: AbortSignal): Promise /** * Withdraw the open worktree request of a Session with its failed attempt, @@ -2150,13 +2207,16 @@ registerLens(lens: ForgeLens): () => Promise @Remote async stopCreation(session: Session, signal: AbortSignal): Promise /** - * Make another attempt, with a new branch name, at the worktree a message - * of the Session waits for after a failed or stopped attempt. + * Make another attempt, on the requested branch name or a new generated + * one, at the worktree a message of the Session waits for after a failed or + * stopped attempt. * @param session - Session whose message waits. + * @param fetch - false skips fetching a remote-tracking base branch for this attempt, which then starts from the + * commit last fetched. * @param signal - request cancellation. * @throws `forgePanel/not-waiting` when no message waits or an attempt is running. */ -@Remote async retryWorktree(session: Session, signal: AbortSignal): Promise +@Remote async retryWorktree(session: Session, fetch: boolean, signal: AbortSignal): Promise /** * Check out the created worktree of a Session again at its recorded diff --git a/docs/subsystems/worktrees.i18n.yaml b/docs/subsystems/worktrees.i18n.yaml index a6b14d164b..26785f48c6 100644 --- a/docs/subsystems/worktrees.i18n.yaml +++ b/docs/subsystems/worktrees.i18n.yaml @@ -6,8 +6,8 @@ en: 3a3d69d2b12a78f9 zh: a7a7d12487968bbc /git-worktrees/creation-and-retention: - en: 4c28ae6baae4ef5f - zh: 0c83d90ea3cd3c2e + en: f4e935f589e661fb + zh: b14e021570f2a884 /git-worktrees/request-and-result: en: fbab866bf824d6e0 zh: 73d2a1ee350e1434 diff --git a/docs/subsystems/worktrees.md b/docs/subsystems/worktrees.md index a837e99625..de1ba9722d 100644 --- a/docs/subsystems/worktrees.md +++ b/docs/subsystems/worktrees.md @@ -6,7 +6,7 @@ The experimental [`dsh-experimental-worktree`](../../packages/experimental/workt ## Creation and retention -The calling Session's current directory selects the source repository. Creation pins the requested local commit, branch, or tag before allocating the checkout; omission selects `HEAD`. Each name must identify a new branch and an unused checkout path. The operation neither fetches missing objects nor copies staged, unstaged, untracked, or ignored files from the source checkout. +The calling Session's current directory selects the source repository. Creation pins the requested local commit, branch, or tag before allocating the checkout; omission selects `HEAD`. A request may instead ask to fetch a remote-tracking branch of a configured remote first, which fetches only that branch and pins the fetched commit. Each name must identify a new branch and an unused checkout path. The operation neither fetches other commits or missing objects nor copies staged, unstaged, untracked, or ignored files from the source checkout. The default destination is `/.agents/worktrees/`. `repositoryRoot` is the top-level directory of the caller’s current checkout; a linked checkout therefore contains its own pool. The service writes a `.gitignore` containing `*` and a trailing newline only when its allocation creates the configured pool directory. Existing files and ignore rules are preserved. The calling Session’s existing sandbox policy must permit writes to the destination and shared Git administration directory. Successful Git setup precedes the working-directory change. @@ -17,12 +17,17 @@ Leaving through `working_directory({ cd: path })` retains the checkout and branc The request selects only the new name and local revision. The result identifies the created checkout and exact commit; it does not change the Session's original project or write permissions. An optional callback receives each stage of the creation before it begins. A restoration checks a removed checkout out again at its recorded directory, from its branch or, when the branch is gone, from its base commit. ```ts type-equiv -/** A new checkout from a locally available Git commit, branch, or tag. */ +/** A new checkout from a locally available Git commit, branch, or tag, or from a remote branch fetched first. */ interface CreateWorktreeRequest { /** New branch name, also used as the relative checkout directory; omission generates a name. */ name?: string /** Local revision to resolve before creation; omission selects HEAD. */ from?: string + /** + * Fetch `from` from its remote before resolving it. `from` must then be the full name of a remote-tracking + * branch, `refs/remotes//`, of a configured remote; only that branch is fetched, without tags. + */ + fetch?: boolean } ``` @@ -42,12 +47,13 @@ interface CreatedWorktree { ```ts type-equiv /** - * Stage of one creation or restoration, reported before it begins: `prepare` + * Stage of one creation or restoration, reported before it begins: `fetch` + * fetches the remote base branch of a creation that asks for it; `prepare` * validates the request, allocates the checkout directory, and creates the * branch, which a restoration creates again only when it is gone; `checkout` * writes the files and, for a creation, enters the checkout. */ -type CreateWorktreePhase = 'prepare' | 'checkout' +type CreateWorktreePhase = 'fetch' | 'prepare' | 'checkout' ``` ```ts type-equiv @@ -113,19 +119,21 @@ Creates retained Git worktrees under the mounted filesystem and sandbox provider ```ts cordis-catalog /** - * Create a fresh branch and checkout at a pinned local revision, then enter it. + * Create a fresh branch and checkout at a pinned local revision, then enter it. A request that asks to fetch + * first fetches its remote-tracking branch, only that branch and without tags, then pins the fetched commit. * Existing branches or checkout paths fail. Uncommitted files stay in the source checkout. * Checkout disables configured clean, smudge, and process filters without changing Git config. * Repository-local replacement refs still apply; baseCommit reports the resolved object name. * The new checkout becomes current only after Git setup succeeds. Failures may retain newly * allocated Git/filesystem artifacts; no branch or checkout is removed automatically. * @param agent - caller whose current directory selects the source repository and file policy. - * @param request - optional new name and local revision; defaults are generated name and HEAD. + * @param request - optional new name, local revision, and fetch switch; defaults are generated name, HEAD, and no fetch. * @param signal - cancellation of lookup, creation, and working-directory publication. * @param onPhase - receives each stage before it begins; it must not throw. * @returns canonical checkout path, branch name, pinned commit, and source repository root. - * @throws {WorktreeError} for an invalid request, an existing branch or path, or a failed, oversized, or timed-out - * command; a failure after allocation keeps its `name` and `code` and adds retained-artifact context. + * @throws {WorktreeError} for an invalid request, a fetch request whose `from` is not a remote-tracking branch of a + * configured remote, an existing branch or path, or a failed, oversized, or timed-out command, including the + * fetch; a failure after allocation keeps its `name` and `code` and adds retained-artifact context. */ async create( agent: Agent, request: CreateWorktreeRequest = {}, signal?: AbortSignal, onPhase?: (phase: CreateWorktreePhase) => void, ): Promise @@ -140,12 +148,12 @@ async create( agent: Agent, request: CreateWorktreeRequest = {}, signal?: AbortS * @param agent - caller whose sandbox policy confines the commands. * @param request - recorded directory, branch, base commit, and source repository root. * @param signal - cancellation of the restoration. - * @param onPhase - receives each stage before it begins; it must not throw. + * @param onPhase - receives each stage before it begins, never `fetch`; it must not throw. * @returns the directory and whether the branch was created again. * @throws {WorktreeError} for an invalid request, an existing path, a locked registration, or a failed, oversized, * or timed-out command; a failure after allocation keeps its `name` and `code` and adds retained-artifact context. */ -async restore( agent: Agent, request: RestoreWorktreeRequest, signal?: AbortSignal, onPhase?: (phase: CreateWorktreePhase) => void, ): Promise +async restore( agent: Agent, request: RestoreWorktreeRequest, signal?: AbortSignal, onPhase?: (phase: Exclude) => void, ): Promise /** * Read the archive cleanup of a Session's created checkout; waiting never diff --git a/docs/subsystems/worktrees.zh.md b/docs/subsystems/worktrees.zh.md index 3d2b4d7286..0000bd609c 100644 --- a/docs/subsystems/worktrees.zh.md +++ b/docs/subsystems/worktrees.zh.md @@ -6,7 +6,7 @@ ## 创建与保留 -调用方 Session 的当前目录决定源仓库。创建操作在分配检出目录前,将请求的本地提交、分支或标签固定为具体提交;省略时选择 `HEAD`。每个名称必须对应新分支与未使用的检出路径。操作既不获取缺失对象,也不复制源检出目录中的暂存、未暂存、未跟踪或被忽略文件。 +调用方 Session 的当前目录决定源仓库。创建操作在分配检出目录前,将请求的本地提交、分支或标签固定为具体提交;省略时选择 `HEAD`。请求也可以要求先获取某个已配置远程的远程跟踪分支,此时只获取这一个分支,并固定获取到的提交。每个名称必须对应新分支与未使用的检出路径。操作既不获取其他提交或缺失对象,也不复制源检出目录中的暂存、未暂存、未跟踪或被忽略文件。 默认目标为 `/.agents/worktrees/`。`repositoryRoot` 是调用方当前检出目录的顶层目录;因此,链接检出目录会在自身内部保存工作树父目录。仅当服务的分配操作创建了配置指定的父目录时,服务才会写入内容为 `*` 加换行符的 `.gitignore`。已有文件与忽略规则保持不变。调用方 Session 的现有沙箱策略必须允许写入目标目录与共享 Git 管理目录。Git 初始化成功后才改变工作目录。 @@ -17,12 +17,17 @@ 请求只选择新名称与本地版本。结果标识创建的检出目录与确切提交;它不会改变 Session 的原始项目或写权限。可选的回调会在创建的每个阶段开始之前收到该阶段。恢复会在记录的目录重新检出已删除的检出目录:从它的分支检出;分支也已删除时,从它的基准提交检出。 ```ts type-equiv -/** A new checkout from a locally available Git commit, branch, or tag. */ +/** A new checkout from a locally available Git commit, branch, or tag, or from a remote branch fetched first. */ interface CreateWorktreeRequest { /** New branch name, also used as the relative checkout directory; omission generates a name. */ name?: string /** Local revision to resolve before creation; omission selects HEAD. */ from?: string + /** + * Fetch `from` from its remote before resolving it. `from` must then be the full name of a remote-tracking + * branch, `refs/remotes//`, of a configured remote; only that branch is fetched, without tags. + */ + fetch?: boolean } ``` @@ -42,12 +47,13 @@ interface CreatedWorktree { ```ts type-equiv /** - * Stage of one creation or restoration, reported before it begins: `prepare` + * Stage of one creation or restoration, reported before it begins: `fetch` + * fetches the remote base branch of a creation that asks for it; `prepare` * validates the request, allocates the checkout directory, and creates the * branch, which a restoration creates again only when it is gone; `checkout` * writes the files and, for a creation, enters the checkout. */ -type CreateWorktreePhase = 'prepare' | 'checkout' +type CreateWorktreePhase = 'fetch' | 'prepare' | 'checkout' ``` ```ts type-equiv @@ -113,19 +119,21 @@ Creates retained Git worktrees under the mounted filesystem and sandbox provider ```ts cordis-catalog /** - * Create a fresh branch and checkout at a pinned local revision, then enter it. + * Create a fresh branch and checkout at a pinned local revision, then enter it. A request that asks to fetch + * first fetches its remote-tracking branch, only that branch and without tags, then pins the fetched commit. * Existing branches or checkout paths fail. Uncommitted files stay in the source checkout. * Checkout disables configured clean, smudge, and process filters without changing Git config. * Repository-local replacement refs still apply; baseCommit reports the resolved object name. * The new checkout becomes current only after Git setup succeeds. Failures may retain newly * allocated Git/filesystem artifacts; no branch or checkout is removed automatically. * @param agent - caller whose current directory selects the source repository and file policy. - * @param request - optional new name and local revision; defaults are generated name and HEAD. + * @param request - optional new name, local revision, and fetch switch; defaults are generated name, HEAD, and no fetch. * @param signal - cancellation of lookup, creation, and working-directory publication. * @param onPhase - receives each stage before it begins; it must not throw. * @returns canonical checkout path, branch name, pinned commit, and source repository root. - * @throws {WorktreeError} for an invalid request, an existing branch or path, or a failed, oversized, or timed-out - * command; a failure after allocation keeps its `name` and `code` and adds retained-artifact context. + * @throws {WorktreeError} for an invalid request, a fetch request whose `from` is not a remote-tracking branch of a + * configured remote, an existing branch or path, or a failed, oversized, or timed-out command, including the + * fetch; a failure after allocation keeps its `name` and `code` and adds retained-artifact context. */ async create( agent: Agent, request: CreateWorktreeRequest = {}, signal?: AbortSignal, onPhase?: (phase: CreateWorktreePhase) => void, ): Promise @@ -140,12 +148,12 @@ async create( agent: Agent, request: CreateWorktreeRequest = {}, signal?: AbortS * @param agent - caller whose sandbox policy confines the commands. * @param request - recorded directory, branch, base commit, and source repository root. * @param signal - cancellation of the restoration. - * @param onPhase - receives each stage before it begins; it must not throw. + * @param onPhase - receives each stage before it begins, never `fetch`; it must not throw. * @returns the directory and whether the branch was created again. * @throws {WorktreeError} for an invalid request, an existing path, a locked registration, or a failed, oversized, * or timed-out command; a failure after allocation keeps its `name` and `code` and adds retained-artifact context. */ -async restore( agent: Agent, request: RestoreWorktreeRequest, signal?: AbortSignal, onPhase?: (phase: CreateWorktreePhase) => void, ): Promise +async restore( agent: Agent, request: RestoreWorktreeRequest, signal?: AbortSignal, onPhase?: (phase: Exclude) => void, ): Promise /** * Read the archive cleanup of a Session's created checkout; waiting never diff --git a/packages/experimental/client-ui-forge/README.i18n.yaml b/packages/experimental/client-ui-forge/README.i18n.yaml index a8be717a1b..0116a96b2a 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: 9b31d4a0e8a0ed01 - zh: 38915fb69b6535ce + en: f63d4a049eea1ede + zh: e61269b6df6afcd4 /deepseek-ai-dsh-experimental-client-ui-forge/understand-the-implementation: - en: 37eef1a98654b29a - zh: 0d8bad512b8a2360 + en: 43e18d718e1bda7b + zh: c58f6b5bda5c0c45 /deepseek-ai-dsh-experimental-client-ui-forge/further-exploration: en: fa4d8c579ffc49ff zh: 5856ed7469e4585b @@ -30,8 +30,8 @@ en: 2bc25a99e17789c4 zh: 4bec723fbf249d28 /deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work: - en: 8801648dd9433da6 - zh: be520fb644ea8895 + en: 49fd22a6073c1680 + zh: a2ca41e361799b19 /deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/experimental/client-ui-forge/README.md b/packages/experimental/client-ui-forge/README.md index 64cf0da82d..b1f17893c1 100644 --- a/packages/experimental/client-ui-forge/README.md +++ b/packages/experimental/client-ui-forge/README.md @@ -29,17 +29,17 @@ Enable the [forge bundle](../forge-bundle/README.md) on the Plugins page; it com Panel text follows the application language: Chinese, English, Japanese, Spanish, French, German, Russian, or Portuguese. -- **Worktree option** — on the New Session screen, New worktree sits beside the current branch at the right end of the row with the workspace and mode pickers. Both stay hidden outside a Git checkout. The branch is read-only until New worktree is checked, when it becomes the base branch selector; the menu lists recent local branches. If permissions block an existing request, its selected base stays visible without a selector and the request can still be withdrawn. Hovering, focusing, or tapping the read-only branch or base shows its full description. The option is disabled, with the reason in its tooltip, in a read-only Session and when the checkout or its Git directory lies outside the Session's writable root, as for a project that is itself a linked worktree. Sending the first message hands it to the Session at once, and it waits there while the branch `dsh--<4 random hexadecimal digits>` is created from the base under the repository's `.agents/worktrees/` and its checkout becomes the Session's working directory; the message's turn starts once the worktree exists. +- **Worktree option** — on the New Session screen, New worktree sits beside the current branch at the right end of the row with the workspace and mode pickers. Both stay hidden outside a Git checkout. The branch is read-only until New worktree is checked, when it becomes the base branch selector. The selector's searchable menu lists, most recently committed first, the current branch, then each remote's default branch, then local branches, then one group per remote headed by its name and its repository, `owner/name` for a recognized code host or else its fetch URL without the user name and password a URL can carry; typing filters the rows at once and lists the branches whose names contain the text after a short pause, and Enter chooses the first row. A remote branch is fetched, only that branch and without tags, when the worktree is created. The menu's last row, Name the new branch, opens a dialog whose field starts with the `worktreePrefix` and checks Git's branch-name rules while the name is typed; Save asks the Host, which also refuses a name the checkout already uses as a branch, and keeps the dialog open with the reason. With a chosen name, the selector shows the name before the base, and the dialog offers to use a generated name again. If permissions block an existing request, its selected base stays visible without a selector and the request can still be withdrawn. Hovering, focusing, or tapping the read-only branch or base shows its full description. The option is disabled, with the reason in its tooltip, in a read-only Session and when the checkout or its Git directory lies outside the Session's writable root, as for a project that is itself a linked worktree. Sending the first message hands it to the Session at once, and it waits there while the chosen branch, or else `dsh--<4 random hexadecimal digits>`, is created from the base under the repository's `.agents/worktrees/` and its checkout becomes the Session's working directory; the message's turn starts once the worktree exists. - **Archive cleanup** — archiving a Session lets the [worktree service](../worktree/README.md) reclaim the clean, unreferenced worktree it created, whether through the New Session option or the model's `create_worktree` tool, while retaining the branch and its commits. A scheduled cleanup uses the archive notice “Archived; the worktree will be cleaned up”; one that ends retained returns to the ordinary notice, and one that fails replaces it with a warning while the Session stays archived. Undo cancels deletion before admission or waits for an admitted deletion; a removed checkout uses the existing Restore worktree flow. The bundle's worktree row on the Plugins page offers Keep worktrees when archiving: once saved, archiving keeps every worktree and shows the ordinary archive notice; the switch is read at each archive, so it does not affect a cleanup already scheduled. -- **Creation card** — while the worktree is created, a card above the composer shows the new branch and its two steps, creating the branch and checking out files; More details adds the branch and base. Cancel stops the attempt. After a stopped or failed attempt the message keeps waiting, and the card shows the reason of a failure: Retry tries again with a new branch name, and Continue without a worktree withdraws the request so the message goes on in the current checkout. +- **Creation card** — while the worktree is created, a card above the composer shows the new branch and its steps: fetching a remote base branch, creating the branch, and checking out files; More details adds the branch and base. Cancel stops the attempt. After a stopped or failed attempt the message keeps waiting, and the card shows the reason of a failure: Retry tries again, on the chosen name or a new generated one, and Continue without a worktree withdraws the request so the message goes on in the current checkout. A failed fetch also offers Use the last fetched version, which starts from the remote branch as last fetched. When the chosen branch or its directory already exists, Rename opens the naming dialog, whose Retry saves the new name and tries again. - **Removed worktree** — when the worktree the Session works in has been removed outside the Session, a card above the composer says so, and a message sent meanwhile waits without starting its turn until the worktree is restored or left; the card then says that the message goes on afterwards. Restore worktree, also offered as Restore in the Session panel's checkout row, checks the branch out again at the same directory, or creates the branch again at the commit it started from when the branch is gone too; while it runs, the card follows its two steps, preparing the worktree and checking out files, and the checkout row's Restore turns into a spinner. Continue in the project moves the Session to the source checkout. Meanwhile the checkout row shows a warning glyph. - **Session panel** — the Environment section of the Session panel gains the checkout and local changes rows after the project row, and the connection row at its end while the panel stream is lost, and a Change requests section follows it. The panel has no refresh control: when it opens and when the window regains focus, it inspects the checkout again, checks sign-in, and polls every change request, at most once every 10 seconds per Session, so changes made outside the Session appear on return. A yellow dot on the panel toggle in the Session header marks an open change request with failed checks, requested changes, or conflicts, also while the panel is hidden. - **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. 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 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. - **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. 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. +- **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. - **Review layers, test files, viewed files, and commits** — Above the file tree, the lens keeps All files or the files of one layer, Interface, Implementation, or Tests, each with its count; when the counts do not fit the tree's width, it shows the layer names alone and each count in the hover text of its layer. Where no tree shows, the toolbar offers the lens as a menu. The repository decides first: a file whose root `.gitattributes` sets `dsh-review-layer=test`, `interface`, or `implementation` is in that layer, and one it marks `linguist-generated` is in Tests. Next come the optional `testPaths` and `interfacePaths` globs, which add to the built-in rules and are empty by default. The built-in rules then follow common conventions: test directories and files of Jest, Vitest, `go test`, pytest, RSpec, XCTest, and .NET, snapshots, locale catalogs, and lockfiles are Tests; package manifests, type declarations, headers, stubs, and interface definitions such as Protocol Buffers, GraphQL, and OpenAPI are Interface. Every other file is in Implementation. For example, `*_test.go dsh-review-layer=test` or `api/**/*.yaml dsh-review-layer=interface` in `.gitattributes` records a repository's own convention. Hide test files leaves Tests out of the file tree and the diff without listing them, and disables the Tests lens. Viewed on a file header marks that change of the file viewed and collapses it; the toolbar shows how many of the shown files are viewed, as a ring filled to the viewed share and a label such as 2 / 3 viewed, and `V` marks or clears the file being read: the file holding the focus or the text cursor, else the file at the top of the view. A file whose change differs from the change it was marked at shows Changed since viewed and expands again. The file tree draws a viewed file subdued, and a directory once every file in it is viewed, so the files left to review stand out; a file changed since it was viewed draws as unviewed, and assistive technology reads the state as each row's description. A change of the file mode alone, such as `chmod +x`, also counts as a new change. A change request's view of all its commits uses the viewed marks its provider keeps on the code host, as the GitHub provider does: the view reads them with the diff, shows a mark at once, and saves it at the displayed head, keeping that file's checkbox disabled until the host answers; a file GitHub reports as changed since it was viewed shows Changed since viewed. A mark the host refuses, or one that new commits made stale, returns to its previous state, and a toast says why; a mark the host may have saved without confirming it stays, and a toast says to refresh to see where it stands. When the marks cannot be read, a notice says so and offers Retry, and no file can be marked. Hovering a checkbox tells where its mark is kept. Other marks are kept in this browser per Session, source, path, and change digest, so they survive closing the tab and reloading, and the tabs of one Session share them: a mark in one tab appears in the others and keeps their marks. All commits beside Submit review, and beside the base branch in the Branch scope, lists the commits oldest first, read once until the head, the local branch or base, or a refresh changes them; a click shows one commit and a Shift click the commits from the last one clicked, which must follow each other as first parents: a run that leaves that line, such as one across a merged branch, keeps the menu open and says why; the view then shows those commits' changes, reads unchanged lines at the last of them, and offers Add to input but no GitHub comment or review. Branch commits exclude uncommitted and untracked files. Another base or scope returns to all commits, and chosen commits that are gone or no longer one run offer Show all commits. - **Review threads** — A change request view overlays the review threads its code host read at the shown head. A thread on lines follows the row of its last line, on the side it was written on, or the collapsed unchanged lines that hold it; it shows the place it was written, each comment's avatar, author, time, and Markdown with raw HTML left out, and tags for the change request's author, bots, and comments still pending in the signed-in user's review. A resolved thread folds into one row that unfolds on request. Threads on a whole file open the file, and threads later commits made outdated gather after its lines in a section that shows the end of the hunk they were written on and offers View file at that commit, which reads the file at the commit they were written on with their lines marked. Chosen commits show only new-side threads whose lines number the last chosen commit. The file tree and each file header count unresolved threads. Each click on the count in a header goes to the file's next unresolved thread in the order the file shows them, threads the chosen commits do not hold last, and from the last back to the first; the Threads toolbar button opens the thread list, which groups the threads by file in file tree order and orders each file's threads the same way, shows the Unresolved, Resolved, or All threads, Unresolved first, and opens each thread at its place, choosing all commits for one the chosen commits do not hold. The list docks beside the files in a view at least 1,040px wide, floats over them in a narrower one and closes before it opens a thread there, and takes their whole width below 480px. The list names a truncated read. A thread offers Add to input, which quotes the whole thread, View on GitHub, and the writes the signed-in user may make. Without a pending review, its reply field replies at once, and its menu starts a pending review with the reply; with one, the field adds the reply to it, as GitHub adds every reply of the user to the pending review. Resolve thread and Unresolve thread change its state, and the menu of the user's own comment edits or deletes it after asking, saying when deleting the only comment deletes the thread. A resolved thread stays open while the user writes a reply or an edit in it. A write the code host refuses keeps the text and says why; a write whose outcome is unknown reads the threads again and asks the user to check them before trying again. Every write reads the threads again, since resolving a thread does not change a GitHub pull request's update time. Threads are read again at each status while the view shows, and from the code host after Refresh even while the panel keeps an earlier read; a failed read keeps the last threads and offers Retry, and a provider that does not read reviews shows none. @@ -63,9 +63,9 @@ All files opens a searchable directory tree with the selected file scrolled to i `ForgePanelController` keeps one `SessionPanel` per followed Session and disposes it when the last follower leaves. A panel starts with the Session's working directory and bindings, re-inspects after each `working-directory/change`, `tool/result`, and `sandbox/mode` event, and publishes a new `ForgePanelState` only when the state differs from the published one, so a reinspection that finds the same checkout reaches no follower. Each change request keeps the latest snapshot a poll returned while later polls fail. A failed parallel Git read cancels and joins its siblings. Inspections run one at a time with one trailing rerun, and a result for a directory the Session has since left is dropped. The code host comes from the remotes in order: the upstream's remote, then `origin`, then the rest. When an inspection finds an upstream branch on a remote a provider recognizes, the panel asks `ctx.forgeSession.discoverBranch` to bind that branch's open change requests, once per remote and branch until a refresh. A sign-in probe runs when the recognized host changes and on refresh, within `readinessTimeoutMs`; a refresh settles once the inspection and the probe it started have ended, and poll results arrive later. -Inspection runs `rev-parse --show-toplevel`, `rev-parse --path-format=absolute --git-common-dir`, `rev-parse --path-format=absolute --git-dir`, `symbolic-ref --short HEAD`, `rev-parse --short HEAD`, `rev-parse --abbrev-ref @{upstream}`, and `remote -v`; `branches` runs `symbolic-ref` and `for-each-ref --count=`; `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. +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. `requestWorktree` refuses with `forgePanel/session-started` after a turn started or the worktree was created, with `forgePanel/worktrees-unavailable` without a `worktrees` service, and with `forgePanel/invalid-branch` for an empty branch; `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 with a new branch name, publishing 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, failed step, and reason stay in the panel state as `failure`, or after `stopCreation`, the hold waits: `retryWorktree` makes another attempt, refused with `forgePanel/not-waiting` while none waits or one runs, 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 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. 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. @@ -85,6 +85,7 @@ The browser entry mounts the Remote, then the UI. One stream per Session feeds t | [`src/index.ts`](src/index.ts) | `forgePanel` Remote and per-Session panels | | [`src/panel.ts`](src/panel.ts) | Panel state, inspection scheduling, and sign-in probes | | [`src/worktree.ts`](src/worktree.ts) | Worktree record, projection, waiting messages, and creation at the first step | +| [`src/branch-name.ts`](src/branch-name.ts) | Branch-name rules and branch labels for the Host and the Client | | [`src/states.ts`](src/states.ts) | Change request states for the Session list | | [`src/git.ts`](src/git.ts) | Git queries under Session permissions | | [`src/parse.ts`](src/parse.ts) | Git output parsing and remote order | @@ -114,7 +115,10 @@ The browser entry mounts the Remote, then the UI. One stream per Session feeds t | [`src/client/host-viewed.ts`](src/client/host-viewed.ts) | Viewed marks the code host keeps, with marks being saved | | [`src/client/menu-search.ts`](src/client/menu-search.ts) | Keys of the search field at the top of a menu | | [`src/client/FileLabel.tsx`](src/client/FileLabel.tsx) | Changed file label: name, then directory | -| [`src/client/WorktreeToggle.tsx`](src/client/WorktreeToggle.tsx) | New Session worktree option | +| [`src/client/WorktreeToggle.tsx`](src/client/WorktreeToggle.tsx) | New Session worktree option and its base menu | +| [`src/client/WorktreeNameDialog.tsx`](src/client/WorktreeNameDialog.tsx) | Naming dialog of a worktree branch | +| [`src/client/branch-search.tsx`](src/client/branch-search.tsx) | Search state and status rows of the branch menus | +| [`src/client/ChangesLoading.tsx`](src/client/ChangesLoading.tsx) | Changes view while it reads | | [`src/client/WorktreeProgress.tsx`](src/client/WorktreeProgress.tsx) | Worktree creation and removed-worktree card | | [`src/client/SessionRowForge.tsx`](src/client/SessionRowForge.tsx) | Session row icons | | [`src/client/SessionHoverForge.tsx`](src/client/SessionHoverForge.tsx) | Session row hover card section | @@ -149,7 +153,7 @@ None for a new worktree, as its notice belongs to the first request of the Sessi - **Polling while shown** — status is polled only while a Session list row or an active panel surface for the Session subscribes; retained hidden changes bodies do not subscribe; there are no notifications for checks that finish meanwhile. - **Unopened Sessions in the list** — the Session list reads the worktree and bindings of a Session that is not loaded from its cached summary: a Session without one shows neither, and one last used before this version shows its worktree only after it is opened. - **Inspection triggers** — the checkout is inspected after Session tool results and directory changes; a change made outside the Session appears when the Session panel opens or the window regains focus, at most once every 10 seconds, or after the next tool result. -- **Retained checkouts** — the panel creates a worktree only before a Session's first step and does not remove existing checkout directories or branches; a failed or cancelled attempt can leave its branch or checkout behind. Branch names come from the Session id and random digits, not from the Session title, which does not exist yet. +- **Retained checkouts** — the panel creates a worktree only before a Session's first step and does not remove existing checkout directories or branches; a failed or cancelled attempt can leave its branch or checkout behind. Generated branch names come from the Session id and random digits, not from the Session title, which does not exist yet; a name chosen in the naming dialog replaces them. - **Messages during a turn** — a message that enters while the Agent runs a turn or other maintenance gets no hold: a requested worktree is then created at the first step, where a failure ends the turn without the message, and a removed worktree is not checked, so the working-directory service moves the Session back to the project directory. - **Waiting messages** — while a message waits, the Agent stays idle in maintenance and the composer offers no stop; the card's actions, the Agent's cancellation, or the Remote's stop release it, and callers that wait for the Agent to become idle wait as well. - **Restoring** — restoring recreates the checkout from the branch, or from the commit the branch started from when the branch is gone; changes that were never committed are lost with the removed directory. The [worktree service](../worktree/README.md#use-this-package) validates the recorded target and removes only its missing, unlocked registration. An existing or incomplete directory stays blocked; preserve its files and remove the directory before retrying, or continue in the source project. diff --git a/packages/experimental/client-ui-forge/README.zh.md b/packages/experimental/client-ui-forge/README.zh.md index a35862ac65..0ac9c13997 100644 --- a/packages/experimental/client-ui-forge/README.zh.md +++ b/packages/experimental/client-ui-forge/README.zh.md @@ -29,17 +29,17 @@ kind: "package-reference" 面板文案跟随应用语言,支持中文、英文、日语、西班牙语、法语、德语、俄语和葡萄牙语。 -- **工作树选项**——在新会话页面上,“新建工作树”与当前分支一起位于工作区与模式选择器那一行的右端。不在 Git 检出中时,两者均隐藏。分支默认为只读展示;勾选“新建工作树”后,它变为基准分支选择器,菜单列出最近的本地分支。权限阻止已有请求时,仍只读显示已选基准,并允许取消请求。悬停、聚焦或轻点只读分支或基准会显示完整说明。Session 为只读,或检出及其 Git 目录不在 Session 的可写根内(例如项目本身就是链接 worktree)时,该选项不可用,提示中说明原因。发送第一条消息后,消息立即交给 Session 并在那里等待,同时从基准分支在仓库的 `.agents/worktrees/` 下创建分支 `dsh--<4 位随机十六进制数>`,并把它的检出设为 Session 的工作目录;worktree 建好后这条消息的这一轮才开始。 +- **工作树选项**——在新会话页面上,“新建工作树”与当前分支一起位于工作区与模式选择器那一行的右端。不在 Git 检出中时,两者均隐藏。分支默认为只读展示;勾选“新建工作树”后,它变为基准分支选择器。选择器的菜单可搜索,按最近提交排序依次列出:当前分支、每个远程的默认分支、本地分支,然后每个远程一组,组名旁显示该远程对应的仓库(识别出代码托管仓库时为 `owner/name`,否则为去掉用户名和密码后的获取地址);输入时已列出的行立即过滤,短暂停顿后列出名称包含所输入文字的分支,按 Enter 选择第一行。远程分支在创建 worktree 时获取,只获取这一个分支,不获取标签。菜单最后一行“指定新分支名称…”打开对话框:输入框以 `worktreePrefix` 开头,输入时检查 Git 的分支名规则;“确定”交给 Host,Host 还会拒绝检出中已有的分支名,拒绝时对话框保持打开并显示原因。指定名称后,选择器在基准前显示该名称,对话框也提供“改回自动命名”。权限阻止已有请求时,仍只读显示已选基准,并允许取消请求。悬停、聚焦或轻点只读分支或基准会显示完整说明。Session 为只读,或检出及其 Git 目录不在 Session 的可写根内(例如项目本身就是链接 worktree)时,该选项不可用,提示中说明原因。发送第一条消息后,消息立即交给 Session 并在那里等待,同时从基准分支在仓库的 `.agents/worktrees/` 下创建指定的分支,未指定时为 `dsh--<4 位随机十六进制数>`,并把它的检出设为 Session 的工作目录;worktree 建好后这条消息的这一轮才开始。 - **归档清理**——归档一个会话后,由[工作树服务](../worktree/README.zh.md)回收它创建的干净且无人引用的工作树,无论来自新会话选项还是模型的 `create_worktree` 工具,分支及其提交保留。清理排队后,归档提示为“已归档,工作树将被清理”;最终保留时恢复为普通归档提示,失败时替换为警告而会话仍保持归档。撤销归档会取消尚未获准的删除,或等待已获准的删除结束;已移除的工作树使用现有的“恢复工作树”流程。插件页上该套件的 worktree 行提供“归档时不删除工作树”开关:保存后,归档会保留所有工作树并显示普通归档提示;开关在每次归档时读取,不影响已排队的清理。 -- **创建卡片**——创建 worktree 期间,输入框上方的卡片显示新分支以及“创建分支”“检出文件”两个步骤;“更多详情”会列出分支与基准。“取消”停止这次尝试。尝试被停止或失败后,消息继续等待,失败时卡片显示原因:“重试”换一个新分支名再试;“不使用工作树”撤回请求,消息在当前检出中继续发送。 +- **创建卡片**——创建 worktree 期间,输入框上方的卡片显示新分支及其步骤:获取远程基准分支、创建分支、检出文件;“更多详情”会列出分支与基准。“取消”停止这次尝试。尝试被停止或失败后,消息继续等待,失败时卡片显示原因:“重试”再试一次,使用指定的名称或新的自动名称;“不使用工作树”撤回请求,消息在当前检出中继续发送。获取失败时还提供“使用上次获取的版本”,从上次获取的远程分支开始。指定的分支或其目录已存在时,“更改名称”打开命名对话框,其中的“重试”保存新名称并再试一次。 - **工作树已被删除**——Session 所在的 worktree 在 Session 之外被删除后,输入框上方的卡片会说明这一点;此期间发送的消息会等待、不开始这一轮,直到该 worktree 被恢复或离开,卡片也会说明消息之后会接着发送。“恢复工作树”(会话面板检出行中的“恢复”与之相同)在原目录重新检出该分支;分支也已删除时,从它开始时的提交重新创建分支;恢复期间卡片显示“准备工作树”“检出文件”两个步骤,检出行中的“恢复”变为加载状态。“在项目目录继续”把 Session 移回源检出。此期间检出行显示警示图标。 - **会话面板**——会话面板的“环境”分栏在项目行之后增加检出行与本地变更行,面板流断开时末尾再加连接行,其后是“变更请求”分栏。面板没有刷新控件:打开时以及窗口重新获得焦点时,它会重新检查检出与登录状态,并轮询每个变更请求,每个会话每 10 秒最多一次,因此在 Session 之外做的改动在切回来时就会出现。打开中的变更请求存在检查失败、被要求修改或冲突时,会话标题栏中的面板开关带黄点,面板隐藏时也会显示。 - **检出行**——显示当前检出的分支(分离 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 没有绑定变更请求时,分栏只显示这一行。每张变更请求卡片显示状态图标、单行标题(悬停时滚动显示全文,点击在浏览器中打开)与编号;图标区分打开、草稿、已合并与已关闭,打开中的变更请求(草稿除外)检查失败、被要求修改或有冲突时显示为“需要处理”,与面板开关的黄点一致。卡片的“更多”菜单提供“在浏览器中打开”“复制变更请求链接”、由提供方服务的变更请求的“查看变更”、打开中草稿的“标记为可评审”,以及“从本会话移除”,移除后的 toast 提供“撤销”。已取消的检查单独计数;列出的检查没有失败项时,折叠卡片显示取消数量。折叠的卡片还显示打开的变更请求的检查,以及被要求修改、冲突、草稿中最需要注意的一项;已合并或已关闭的则显示结束时间。这些内容只占一行:含失败检查的一行放不下时,失败检查改用不带数量的短文案;仍放不下的一行末尾显示省略号,并随标题一起滚动显示。展开的卡片显示源分支与目标分支,下面每项一行,由图标与取值组成。打开的变更请求依次是:检查,其菜单按失败、运行中、已取消分组列出检查及其耗时与链接,按需列出通过与跳过的检查,用户可以重跑检查、且有失败检查指向一个其中没有检查仍在进行的重跑时提供“重跑失败项”;评审结论,带前三位评审者的头像与其余人数,其菜单列出每位评审者的类型与最近结论,注明早于最新提交的结论,用户可以请求评审时还能重新请求某位评审者,或通过先列出托管平台建议的搜索向其他人请求评审;合并状态,会注明 head 落后于基线,用户可以更新时提供“更新分支”,其菜单在 merge 与 rebase 之间选择,打开时固定卡片显示的 head,轮询发现 head 变化后禁用“确认更新”;按所选界面语言格式化的变更行数与未解决讨论数(提供方只统计了部分讨论时数字后带 `+`),点击该行打开变更视图;以及合并时托管平台会关闭的关联 issue,各自链接到其页面。讨论数和 issue 标题在悬停 500ms 后以提示显示。已合并或已关闭的显示结束时间与变更行数。“重跑失败项”、评审请求、“更新分支”、“标记为可评审”与“合并”的结果都以 toast 报告,托管平台未确认结果时提示到浏览器中查看变更请求;显示的 head 之后有新提交时不会重跑或更新。主机现在就会合并的变更请求在各行下方提供“合并”,其菜单列出仓库允许的合并方式并选中用户常用的一种,打开时固定卡片显示的 head。“确认合并”使用这个 head;轮询发现 head 变化后禁用确认,需重新检查并打开菜单。每次操作的结果都以 toast 报告;该 head 之后有新提交时不会合并。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 下重新打开、刷新与导航都不会再从托管平台读取。刷新评审标记时,如果比较的提交范围、末端提交和补丁都相同,已经展开的未变更行和正在读取的文件内容会保留。 +- **变更视图**——变更请求卡片上的“变更”一行与“查看变更”菜单项、以及本地变更行会打开一个右侧边栏标签页,列出所有变更的文件;会话面板浮在对话上方时随之关闭。本地标签页名为“本地变更”,默认显示“分支”:工作树与未跟踪文件相对于分叉点的变更。它的标题栏写出当前检出的分支(分离 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 下重新打开、刷新与导航都不会再从托管平台读取。刷新评审标记时,如果比较的提交范围、末端提交和补丁都相同,已经展开的未变更行和正在读取的文件内容会保留。 - **分层、测试文件、已审阅与提交**——文件树上方的分层透镜保留全部文件,或“接口”“实现”“测试”中一层的文件,并显示各自的数量;文件树宽度放不下数量时,只显示各层名称,数量在悬停提示里。不显示文件树时,工具栏以菜单提供透镜。仓库的声明优先:根目录 `.gitattributes` 把文件设为 `dsh-review-layer=test`、`interface` 或 `implementation` 时,文件属于对应的层;标为 `linguist-generated` 的文件属于“测试”。其次是可选的 `testPaths` 与 `interfacePaths`,它们追加在内置规则之前,默认为空。最后是按常见约定写的内置规则:Jest、Vitest、`go test`、pytest、RSpec、XCTest 与 .NET 的测试目录和文件、快照、本地化目录与 lockfile 属于“测试”;包清单、类型声明、头文件、类型存根与 Protocol Buffers、GraphQL、OpenAPI 等接口定义属于“接口”。其余文件属于“实现”。例如在 `.gitattributes` 中写 `*_test.go dsh-review-layer=test` 或 `api/**/*.yaml dsh-review-layer=interface`,即可记录仓库自己的约定。“隐藏测试文件”让文件树与 diff 都不显示“测试”层,也不列出被隐藏的文件,同时停用“测试”透镜。文件标题上的“已审阅”把该文件的这次改动标为已审阅并折叠它;工具栏以按已审阅比例填充的圆环和“已审阅 2 / 3”这样的文字显示已显示文件中已审阅的数量,按 `V` 标记或取消当前阅读的文件:焦点或文本光标所在的文件,否则是视图顶部的文件。改动与标记时不同的文件显示“有新改动”并重新展开。文件树把已审阅的文件置灰,目录下的文件全部已审阅时目录也置灰,以便看出还没审阅的文件;有新改动的文件按未审阅显示,辅助技术把这一状态读作每行的描述。只改文件模式(例如 `chmod +x`)也算新改动。变更请求的全部提交视图使用提供方保存在代码托管平台上的已审阅标记(GitHub 提供方即如此):视图随 diff 一起读取这些标记,勾选后立即显示,并在显示的 head 上保存,平台答复前该文件的复选框保持禁用;GitHub 报告为标记后又有改动的文件显示“有新改动”。平台拒绝或因新提交而过期的标记恢复原状,并以 toast 说明原因;平台可能已保存但未确认的标记保持不变,toast 提示刷新查看实际状态。无法读取标记时,提示条说明原因并提供“重试”,此时不能标记任何文件。悬停复选框会说明标记保存在哪里。其他标记按 Session、变更来源、路径与改动摘要保存在本浏览器中,关闭标签页或重新加载后仍在;同一 Session 的多个标签页共用这些标记:在一个标签页中标记,其他标签页随之更新,且不会覆盖它们的标记。“提交评审”左侧,以及“分支”范围中基准分支右侧的“全部提交”按从旧到新列出提交,读取一次后保留到 head、本地分支或基准变化或刷新为止;单击只看一个提交,按住 Shift 单击看从上次单击的提交到这个提交的连续多个提交,这些提交必须依次是后一个的第一父提交:离开这条链的范围(例如跨越已合并分支的范围)会让菜单保持打开并说明原因;此时视图显示这些提交的改动,在最后一个提交读取未变更的行,提供“添加到输入框”,但不提供 GitHub 评论或评审。“分支”的提交不含未提交与未跟踪的文件。换基准分支或范围后回到全部提交;所选提交已不存在或不再是一条链时提供“查看全部提交”。 - **评审讨论**——变更请求视图会叠加代码托管平台在所显示 head 处读到的评审讨论。行级讨论显示在它最后一行所在的行之后,位于写下时所在的那一侧;若该行折叠在未变更的行中,则显示在折叠行之后。讨论标明写下时的位置,每条评论显示头像、作者、时间和 Markdown 正文(不显示原始 HTML),并用标签标出变更请求作者、机器人账号,以及当前登录用户尚未提交的评审中的评论。已解决的讨论折叠成一行,可以展开。针对整个文件的讨论显示在文件开头;被后续提交改到而过期的讨论集中在文件的行之后,显示写下时那段 hunk 的末尾,并提供“查看当时的文件”,读取写下讨论时那个提交上的文件并标出相应的行。选择了部分提交时,只显示行号对应最后一个所选提交的新版本侧讨论。文件树和每个文件标题都显示未解决讨论数。每点击一次文件标题上的计数,就按文件中的显示顺序跳到该文件的下一条未解决讨论(所选提交中没有的讨论排在最后),到最后一条后回到第一条;工具栏的“讨论”按钮打开讨论列表。列表按文件树顺序分组,组内讨论的顺序与文件中相同,可显示未解决、已解决或全部讨论,默认显示未解决的讨论;点击讨论会跳到它的位置,若所选提交中没有该讨论,会先切换到全部提交。视图宽度不小于 1,040px 时列表停靠在文件旁;更窄时浮在文件之上,并在跳到讨论前先关闭;窄于 480px 时占满文件区的宽度。读取被截断时,列表会注明。讨论上提供“添加到输入框”(把整个讨论作为引用插入)、“在 GitHub 中查看”,以及当前登录用户可以执行的写操作。没有待提交评审时,回复框立即回复,其下拉菜单可以带着这条回复开始待提交评审;有待提交评审时,回复框把回复加入其中,因为 GitHub 会把用户的每条回复都加入待提交评审。“解决讨论”和“取消解决”切换讨论状态;用户自己评论的菜单可以编辑或删除该评论,删除前会先确认,删除讨论中唯一的评论会一并删除讨论,确认时会说明这一点。用户正在讨论中写回复或编辑评论时,即使讨论已被解决,也保持展开。代码托管平台拒绝写操作时保留输入的文字并说明原因;结果不明时会重新读取讨论,并请用户核对后再重试。每次写操作后都会重新读取讨论,因为解决讨论不会改变 GitHub pull request 的更新时间。视图显示期间,每收到一次状态就重新读取讨论;点击刷新后,即使面板还保留着之前的读取结果,也会从代码托管平台重新读取;读取失败时保留上次的讨论并提供重试,提供方不支持读取讨论时不显示讨论。 @@ -63,9 +63,9 @@ diff 按文件树的深度优先顺序排列:同层目录在前、文件在后 `ForgePanelController` 为每个被关注的 Session 保留一个 `SessionPanel`,最后一个关注方离开时销毁它。面板从 Session 的工作目录与绑定开始,在每个 `working-directory/change`、`tool/result` 与 `sandbox/mode` 事件之后重新检查,只在状态与已发布的不同时发布新的 `ForgePanelState`,所以检查结果与原来相同时不会通知任何关注方。每个变更请求在后续轮询失败时保留最近一次轮询得到的快照。并行 Git 读取失败时会取消并等待同批读取结束。检查一次只运行一个,最多再追加一次;Session 已离开的目录的结果会被丢弃。代码托管平台按远端顺序识别:先是上游所在的远端,然后是 `origin`,最后是其余远端。检查发现提供方识别的远端上有上游分支时,面板调用 `ctx.forgeSession.discoverBranch` 绑定该分支打开状态的变更请求;同一远端与分支在刷新前只查找一次。识别出的托管平台变化时以及刷新时,会在 `readinessTimeoutMs` 内检查登录状态;一次刷新在它触发的检查与登录状态检查结束后完成,轮询结果之后才到达。 -检查运行 `rev-parse --show-toplevel`、`rev-parse --path-format=absolute --git-common-dir`、`rev-parse --path-format=absolute --git-dir`、`symbolic-ref --short HEAD`、`rev-parse --short HEAD`、`rev-parse --abbrev-ref @{upstream}` 与 `remote -v`;`branches` 运行 `symbolic-ref` 与 `for-each-ref --count=`;`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 沙箱策略的规范工作区根内时才可用。 +检查运行 `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` 拒绝;`cancelWorktree` 只以第一种拒绝,也不需要 `worktrees` 服务;两者都会忘掉失败的尝试。消息进入有未完成请求的 Session 的收件箱时,一个 `agent/inbox/inserted` 监听器在这次投递唤醒 Agent 之前启动 Session 所属 Agent 的维护任务,因此 Agent 会暂存唤醒,等这次暂留结束后才开始这条消息的这一轮。暂留使用新分支名进行一次尝试,在面板状态中发布正在进行的阶段,设置 `held`,`waiting` 为 `creation`,并记录带源仓库根目录的 `created`。尝试失败(其分支、基准、失败步骤与原因以 `failure` 留在面板状态中)或经 `stopCreation` 停止后,暂留继续等待:`retryWorktree` 再做一次尝试,没有消息等待或已有尝试进行时以 `forgePanel/not-waiting` 拒绝;撤回请求则让消息在当前检出中继续。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 目录必须匹配记录的工作树。插件卸载会取消并等待所有创建、恢复与消息等待任务,然后释放面板读取器和投影。 @@ -85,6 +85,7 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi | [`src/index.ts`](src/index.ts) | `forgePanel` Remote 与按 Session 的面板 | | [`src/panel.ts`](src/panel.ts) | 面板状态、检查调度与登录检查 | | [`src/worktree.ts`](src/worktree.ts) | worktree 记录、投影、等待中的消息,以及在第一步创建 worktree | +| [`src/branch-name.ts`](src/branch-name.ts) | Host 与 Client 共用的分支名规则与分支显示名 | | [`src/states.ts`](src/states.ts) | 会话列表用的变更请求状态 | | [`src/git.ts`](src/git.ts) | 按 Session 权限执行 Git 查询 | | [`src/parse.ts`](src/parse.ts) | Git 输出解析与远端顺序 | @@ -114,7 +115,10 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi | [`src/client/host-viewed.ts`](src/client/host-viewed.ts) | 代码托管平台保存的已审阅标记,以及正在保存的标记 | | [`src/client/menu-search.ts`](src/client/menu-search.ts) | 菜单顶部搜索框的按键处理 | | [`src/client/FileLabel.tsx`](src/client/FileLabel.tsx) | 变更文件的标签:文件名在前,目录在后 | -| [`src/client/WorktreeToggle.tsx`](src/client/WorktreeToggle.tsx) | 新会话的工作树选项 | +| [`src/client/WorktreeToggle.tsx`](src/client/WorktreeToggle.tsx) | 新会话的工作树选项及其基准菜单 | +| [`src/client/WorktreeNameDialog.tsx`](src/client/WorktreeNameDialog.tsx) | worktree 分支的命名对话框 | +| [`src/client/branch-search.tsx`](src/client/branch-search.tsx) | 分支菜单的搜索状态与状态行 | +| [`src/client/ChangesLoading.tsx`](src/client/ChangesLoading.tsx) | 读取中的变更视图 | | [`src/client/WorktreeProgress.tsx`](src/client/WorktreeProgress.tsx) | worktree 创建卡片与 worktree 缺失卡片 | | [`src/client/SessionRowForge.tsx`](src/client/SessionRowForge.tsx) | 会话行图标 | | [`src/client/SessionHoverForge.tsx`](src/client/SessionHoverForge.tsx) | 会话行悬浮卡片中的部分 | @@ -149,7 +153,7 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi - **只在显示时轮询**——只有会话列表的某一行或该 Session 的活动面板界面订阅时才会轮询状态,保活但隐藏的变更正文不订阅;其间检查结束不会有通知。 - **会话列表中未打开的 Session**——会话列表从缓存的摘要中读取未加载 Session 的 worktree 与绑定:没有缓存摘要的 Session 两者都不显示;此版本之前最后使用的 Session 要打开之后才显示其 worktree。 - **检查触发时机**——检出只在 Session 的工具结果与目录变化之后检查;Session 之外的改动在会话面板打开或窗口重新获得焦点时出现(每 10 秒最多一次),否则要等到下一个工具结果。 -- **保留检出**——面板只在 Session 的第一步之前创建 worktree,不删除已有的检出目录或分支;失败或被取消的尝试可能留下分支或检出。分支名取自 Session id 与随机数字,而不是 Session 标题,因为那时标题还不存在。 +- **保留检出**——面板只在 Session 的第一步之前创建 worktree,不删除已有的检出目录或分支;失败或被取消的尝试可能留下分支或检出。自动生成的分支名取自 Session id 与随机数字,而不是 Session 标题,因为那时标题还不存在;在命名对话框中指定的名称会取代它。 - **一轮进行中的消息**——Agent 正在运行一轮或其他维护任务时进入的消息不会被暂留:所请求的 worktree 改为在第一步创建,失败时这一轮结束且不带这条消息;已删除的 worktree 不会被检查,工作目录服务会把 Session 移回项目目录。 - **等待中的消息**——消息等待期间,Agent 以空闲状态处于维护任务中,输入框不提供停止;只有卡片上的操作、Agent 的取消或 Remote 的停止能放行它,等待 Agent 空闲的调用方也会一并等待。 - **恢复**——恢复会从分支重新检出;分支也已删除时,从它开始时的提交重新创建。从未提交的修改随被删除的目录一起丢失。[worktree 服务](../worktree/README.zh.md#use-this-package)校验记录的目标,只移除该目标缺失且未锁定的登记。已有或未恢复完成的目录仍会阻止恢复;请先保存其中的文件并移除目录再重试,或在源项目继续。 diff --git a/packages/experimental/client-ui-forge/src/branch-name.ts b/packages/experimental/client-ui-forge/src/branch-name.ts new file mode 100644 index 0000000000..8b55b4fe86 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/branch-name.ts @@ -0,0 +1,74 @@ +/** Branch-name rules and branch labels shared by the Host and the Client; free of Node imports. */ + +/** Prefix of the full names of local branches. */ +export const LOCAL_REF_PREFIX = 'refs/heads/' + +/** Prefix of the full names of remote-tracking branches. */ +export const REMOTE_REF_PREFIX = 'refs/remotes/' + +/** + * Why a name cannot be a new branch name: Git's rules for `refs/heads/`, plus the worktree service's + * refusal of a leading `-`. + */ +export type BranchNameProblem = + | 'empty' + | 'space' + | 'character' + | 'leading-dash' + | 'leading-slash' + | 'trailing-slash' + | 'double-slash' + | 'double-dot' + | 'trailing-dot' + | 'at' + | 'at-brace' + | 'dot-segment' + | 'lock-segment' + +/** Characters Git refuses anywhere in a ref name: ASCII controls, `~ ^ : ? * [`, and the backslash. */ +const FORBIDDEN = /[\u0000-\u001f\u007f~^:?*[\\]/ + +/** + * Find the first rule a new branch name breaks. `git check-ref-format` stays the final check on the Host. + * @param name - candidate branch name. + * @returns the broken rule, or null when the name passes every rule. + */ +export function branchNameProblem(name: string): BranchNameProblem | null { + if (name.length === 0) return 'empty' + if (/\s/.test(name)) return 'space' + if (FORBIDDEN.test(name)) return 'character' + if (name.startsWith('-')) return 'leading-dash' + if (name.startsWith('/')) return 'leading-slash' + if (name.endsWith('/')) return 'trailing-slash' + if (name.includes('//')) return 'double-slash' + if (name.includes('..')) return 'double-dot' + if (name.endsWith('.')) return 'trailing-dot' + if (name === '@') return 'at' + if (name.includes('@{')) return 'at-brace' + const segments = name.split('/') + if (segments.some(segment => segment.startsWith('.'))) return 'dot-segment' + if (segments.some(segment => segment.endsWith('.lock'))) return 'lock-segment' + return null +} + +/** + * The name a branch shows: a full local or remote-tracking branch name without its `refs/heads/` or + * `refs/remotes/` prefix; any other revision, such as a short name an earlier panel recorded, as it is. + * @param ref - branch or revision. + * @returns the shown name. + */ +export function branchLabel(ref: string): string { + for (const prefix of [LOCAL_REF_PREFIX, REMOTE_REF_PREFIX]) { + if (ref.startsWith(prefix) && ref.length > prefix.length) return ref.slice(prefix.length) + } + return ref +} + +/** + * Whether a revision is the full name of a remote-tracking branch, which a worktree creation fetches first. + * @param ref - branch or revision, or null for HEAD. + * @returns whether `ref` lies under `refs/remotes/`. + */ +export function isRemoteRef(ref: string | null): boolean { + return ref !== null && ref.startsWith(REMOTE_REF_PREFIX) && ref.length > REMOTE_REF_PREFIX.length +} diff --git a/packages/experimental/client-ui-forge/src/client/BaseMenu.tsx b/packages/experimental/client-ui-forge/src/client/BaseMenu.tsx index 0bcabc3408..c0305f7623 100644 --- a/packages/experimental/client-ui-forge/src/client/BaseMenu.tsx +++ b/packages/experimental/client-ui-forge/src/client/BaseMenu.tsx @@ -1,21 +1,19 @@ /** Base branch picker of the local changes view's `branch` scope: the automatic fork point, then remote-tracking and local branches. */ -import { useEffect, useRef, useState, type ReactNode } from 'react' +import { useState, type ReactNode } from 'react' import clsx from 'clsx' import { - Button, IconBranchOutlineRegular, IconCheckOutlineRegular, IconChevronDownOutlineRegular, IconSearchOutlineRegular, - IconWarningTriangleOutlineRegular, Input, Menu, MenuItemButton, StateDot, Tooltip, + IconBranchOutlineRegular, IconCheckOutlineRegular, IconChevronDownOutlineRegular, IconSearchOutlineRegular, + IconWarningTriangleOutlineRegular, Input, Menu, MenuItemButton, Tooltip, } from '@deepseek-ai/dsh-client-ui-primitives' import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' import type { ForgeBaseBranch, ForgeBaseBranches } from '../types.ts' +import { branchSearchStatus, useBranchSearch } from './branch-search.tsx' import type { NS } from './locales.ts' import { searchFieldKeyDown } from './menu-search.ts' import css from './BaseMenu.module.css' -/** Milliseconds between the last keystroke of a search and the listing it reads. */ -const SEARCH_DELAY_MS = 150 - /** Props of the base branch picker. */ export interface BaseMenuProps extends PropsLocale { /** Chosen branch, or null for the automatic fork point. */ @@ -49,32 +47,11 @@ interface BaseOption { */ export function BaseMenu({ chosen, label, missing, visible, list, choose, t }: BaseMenuProps): ReactNode { const [open, setOpen] = useState(false) - const [query, setQuery] = useState('') - const [attempt, setAttempt] = useState(0) - const [listing, setListing] = useState | null>(null) - const search = useRef(null) const shown = visible && open - useEffect(() => { - if (!shown) return - const controller = new AbortController() - const timer = setTimeout(() => { - void list(query, controller.signal).then((result) => { if (!controller.signal.aborted) setListing(result) }) - }, query === '' ? 0 : SEARCH_DELAY_MS) - return () => { - clearTimeout(timer) - controller.abort() - } - }, [shown, query, attempt, list]) - // The portalled menu measures itself hidden before its first frame, and a hidden field cannot take the keyboard. - // A touch screen keeps its on-screen keyboard closed until the field is tapped. - useEffect(() => { - if (!shown || (typeof matchMedia === 'function' && matchMedia('(pointer: coarse)').matches)) return - const frame = requestAnimationFrame(() => { search.current?.focus() }) - return () => { cancelAnimationFrame(frame) } - }, [shown]) + const { query, setQuery, listing, retry, reset, field } = useBranchSearch(shown, list) const close = (): void => { setOpen(false) - setQuery('') + reset() } const pick = (base: ForgeBaseBranch | null): void => { close() @@ -110,20 +87,8 @@ export function BaseMenu({ chosen, label, missing, visible, list, choose, t }: B ].filter(group => group.options.length > 0) const first = groups[0]?.options[0] - let body: ReactNode - if (listing === null) { - body =
{t('diff.base.loading')}
- } else if (!listing.ok) { - body = ( -
- {t('toast.branchesFailed')} - -
- ) - } else if (groups.length === 0) { - body =
{t('diff.base.empty')}
- } else { - body = groups.map(group => ( + const body: ReactNode = branchSearchStatus({ listing, empty: groups.length === 0, retry, className: css.status, t }) + ?? groups.map(group => (
{/* The automatic row's tag names it, so its group shows no heading. */} {group.id !== 'automatic' &&
{group.label}
} @@ -142,7 +107,6 @@ export function BaseMenu({ chosen, label, missing, visible, list, choose, t }: B })}
)) - } return (
- } value={query} + } value={query} aria-label={t('diff.base.search')} placeholder={t('diff.base.search')} onChange={(event) => { setQuery(event.target.value) }} onKeyDown={(event) => { searchFieldKeyDown(event, first === undefined ? undefined : () => { pick(first.base) }) }} /> diff --git a/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx b/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx index f87e7d2912..11f3742b79 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx @@ -1,13 +1,15 @@ /** * 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, 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. + * 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. */ -import { useId, useRef, useState, type ReactNode } from 'react' +import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type PointerEvent, type ReactNode, type RefObject } from 'react' import clsx from 'clsx' import { Button, IconCheckCircleOutlineRegular, IconChevronDownOutlineRegular, IconCloseOutlineRegular, IconCopyOutlineRegular, @@ -170,10 +172,14 @@ function finished(snapshot: ChangeRequestSnapshot, now: number, t: Translate): s return ago === undefined ? state : t('time.finished', { state, time: ago }) } -/** Collapsed status after the number: checks and the most urgent flag, the merge or close time, or a read in progress. */ -function Summary({ snapshot, now, t }: { +/** + * 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. + */ +function Summary({ snapshot, now, short, t }: { readonly snapshot: ChangeRequestSnapshot | null readonly now: number + readonly short: boolean readonly t: Translate }): ReactNode { if (snapshot === null) return @@ -187,7 +193,7 @@ function Summary({ snapshot, now, t }: { {ci.kind !== 'none' && } {ci.kind === 'failed' - ? ci.count > 0 ? t('change.ci.failed', { count: ci.count }) : t('change.ci.failedUnlisted') + ? 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}`)}} @@ -195,6 +201,61 @@ function Summary({ snapshot, now, t }: { ) } +/** + * 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. + * @param snapshot - change request status. + * @param t - copy. + * @returns the line's full text after the number, or null. + */ +function shortenable(snapshot: ChangeRequestSnapshot | null, t: Translate): string | null { + if (snapshot?.state !== 'open') return null + 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 flag = flagOf(snapshot) + return flag === undefined ? full : `${full} ${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 +} + /** 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 ( @@ -432,11 +493,32 @@ export function ChangeRequestCard({ entry, expanded, onToggle, now, actions, loc const tone = toneOf(snapshot) const name = number === null ? snapshot?.title ?? url : t('change.number', { number }) const titleRef = useRef(null) - const marquee = useHoverMarquee(titleRef) + 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 + : notice === undefined ? : null + const parts = ( + <> + {number !== null && {t('change.number', { number })}} + {number !== null && meta !== null && } + {meta} + + ) return (
  • @@ -456,9 +538,7 @@ export function ChangeRequestCard({ entry, expanded, onToggle, now, actions, loc {(number !== null || meta !== null) && (
    - {number !== null && {t('change.number', { number })}} - {number !== null && meta !== null && } - {meta} + {expanded ? parts : {parts}}
    )}
    diff --git a/packages/experimental/client-ui-forge/src/client/ChangedFiles.tsx b/packages/experimental/client-ui-forge/src/client/ChangedFiles.tsx index d3be9bd0c7..51f6a10d55 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangedFiles.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangedFiles.tsx @@ -160,15 +160,19 @@ export function ChangedFiles(props: ChangedFilesProps): ReactNode { /** * Open directory navigation through the existing files toolbar entry. - * @param props - navigator data and whether its owning tab is visible. + * @param props - navigator data, whether its owning tab is visible, and whether the files are still being read, when + * the entry names no count. * @returns the toolbar entry and its portalled menu. */ -export function ChangedFilesMenu({ visible, ...props }: ChangedFilesProps & { readonly visible: boolean }): ReactNode { +export function ChangedFilesMenu({ visible, loading = false, ...props }: ChangedFilesProps & { + readonly visible: boolean + readonly loading?: boolean +}): ReactNode { const [open, setOpen] = useState(false) return { setOpen(false) }} anchor={}> { setOpen(false); props.jump(path) }} /> diff --git a/packages/experimental/client-ui-forge/src/client/ChangesLoading.module.css b/packages/experimental/client-ui-forge/src/client/ChangesLoading.module.css new file mode 100644 index 0000000000..715a958a97 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/ChangesLoading.module.css @@ -0,0 +1,110 @@ +/* The changes view while it reads: one status line, then file cards drawn as skeletons. The cards copy `.file` and + `.fileHeader` of ChangesTab.module.css; the fill and pulse copy the Plugins page skeleton. */ + +.status { + display: flex; + align-items: center; + min-height: 20px; + margin: 0 0 10px; + padding: 0 4px; + color: var(--dsw-alias-label-secondary); + font-size: var(--dsh-content-font-size-secondary, 13px); + line-height: 20px; +} + +.fill { + border-radius: var(--dsw-radius-xs); + background: var(--dsw-alias-bg-skeleton); + animation: forge-skeleton-pulse 2s cubic-bezier(0.36, 0, 0.64, 1) infinite; +} + +@keyframes forge-skeleton-pulse { + 0% { opacity: 1; } + 40% { opacity: 0.6; } + 80%, 100% { opacity: 1; } +} + +@media (prefers-reduced-motion: reduce) { + .fill { animation: none; } +} + +.file { + overflow: clip; + border: 0.5px solid var(--dsw-alias-border-l4); + border-radius: var(--dsw-radius-lg); + background: var(--forge-changes-bg); +} + +.file + .file { + margin-top: 12px; +} + +@container forge-changes (max-width: 380px) { + .file + .file { + margin-top: 8px; + } +} + +.header { + display: flex; + align-items: center; + gap: 8px; + box-sizing: border-box; + min-height: 36px; + padding: 0 10px 0 12px; + border-bottom: 0.5px solid var(--dsw-alias-border-l3); + background: linear-gradient(var(--dsw-alias-interactive-bg-hover), var(--dsw-alias-interactive-bg-hover)), var(--forge-changes-bg); +} + +.folded .header { + border-bottom: 0; +} + +.icon, +.box { + flex: none; + width: 14px; + height: 14px; +} + +.path { + height: 10px; +} + +.counts { + flex: none; + width: 52px; + height: 10px; + margin-left: auto; +} + +.lines { + display: grid; + padding: 5px 0; +} + +.split { + grid-template-columns: 1fr 1fr; +} + +.column + .column { + border-left: 0.5px solid var(--dsw-alias-border-l3); +} + +.line { + display: flex; + align-items: center; + gap: 12px; + height: 18px; + padding: 0 12px; +} + +.number { + flex: none; + width: 20px; + height: 8px; +} + +.code { + height: 8px; +} diff --git a/packages/experimental/client-ui-forge/src/client/ChangesLoading.tsx b/packages/experimental/client-ui-forge/src/client/ChangesLoading.tsx new file mode 100644 index 0000000000..d0c6f88916 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/ChangesLoading.tsx @@ -0,0 +1,69 @@ +/** The changes view's body while it reads: a status line above file cards drawn as skeletons. */ + +import clsx from 'clsx' +import type { ReactNode } from 'react' +import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' +import type { NS } from './locales.ts' +import css from './ChangesLoading.module.css' + +/** Widths, in percent of a line, that the skeleton's code bars cycle through. */ +const CODE_WIDTHS = [62, 48, 74, 35, 81, 56, 44, 69, 28, 52, 77, 39] as const + +/** + * The skeleton cards: a changed file shown in two columns when the view splits sides, an added file, and two + * collapsed files. `path` is the path bar's width in percent of the header. + */ +const FILES = [ + { path: 46, lines: 7, sides: 2 }, + { path: 34, lines: 4, sides: 1 }, + { path: 52, lines: 0, sides: 1 }, + { path: 28, lines: 0, sides: 1 }, +] as const + +function Column({ lines, offset }: { readonly lines: number; readonly offset: number }): ReactNode { + return ( +
    + {Array.from({ length: lines }, (_, index) => ( +
    + + +
    + ))} +
    + ) +} + +/** + * Render the reading state of the changes view. The status line is the only text and announces itself politely; + * the cards are hidden from assistive technology. + * @param props - whether changed files show their sides in two columns, and copy. + * @returns the status line and the skeleton cards. + */ +export function ChangesLoading({ split, t }: { readonly split: boolean } & PropsLocale): ReactNode { + return ( + <> +
    {t('diff.loading')}
    + + + ) +} diff --git a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx index 620fe36e57..c05b0d3feb 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx @@ -19,7 +19,7 @@ import { Button, IconBranchOutlineRegular, IconChevronDownOutlineRegular, IconChevronsUpDownOutlineRegular, IconCompareSplitOutlineRegular, IconInfoOutlineRegular, IconFilesDiffOutlineRegular, IconNowrapFillRegular, IconRightUpOutlineRegular, IconWorkspaceTreeOutlineRegular, IconWrapFillRegular, - Menu, StateDot, Tooltip, + Menu, Tooltip, type MenuEntry, } from '@deepseek-ai/dsh-client-ui-primitives' import type { HostObservable, InjectFace, PropsLocale, PropsRenderSlots, PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots' @@ -53,6 +53,7 @@ import { SectionReach } from './section-reach.ts' import { FileTreePane, type FileTreePosition } from './FileTreePane.tsx' import { changedFileTree, filesInTreeOrder } from './file-tree.ts' import { ChangedFilesMenu, type ChangedFilesProps, type ChangedFilesState } from './ChangedFiles.tsx' +import { ChangesLoading } from './ChangesLoading.tsx' import { drawnLines, matchesHunks, revealGap, textLines, type GapExpansion, type GapReveal } from './diff-rows.ts' import { ChangeRequestGlyph } from './glyphs.tsx' import type { ForgePanelKey, NS } from './locales.ts' @@ -1218,7 +1219,7 @@ export function ChangesTab({
  • ) } else if (failed === null) { - body =
    + body =
    } else { body = (
    @@ -1332,7 +1333,9 @@ export function ChangesTab({ {treeShown &&
    }
    {tab.visible && source.kind === 'local' && { actions.scoped(tab.id, next) }} t={t} />} - {tab.visible && } + {tab.visible && ( + + )} {tab.visible && allFiles.length > 0 && ( )} 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 002a582fb6..3b5b1312a2 100644 --- a/packages/experimental/client-ui-forge/src/client/Forge.module.css +++ b/packages/experimental/client-ui-forge/src/client/Forge.module.css @@ -217,12 +217,35 @@ color: var(--dsw-alias-label-tertiary); } -/* Only the branch names shorten; the number, checks, and flags keep whole words on one line. */ -.meta > :not(.ellipsis) { +/* 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); } diff --git a/packages/experimental/client-ui-forge/src/client/SessionHoverForge.tsx b/packages/experimental/client-ui-forge/src/client/SessionHoverForge.tsx index 5a4f69749e..0287d4380a 100644 --- a/packages/experimental/client-ui-forge/src/client/SessionHoverForge.tsx +++ b/packages/experimental/client-ui-forge/src/client/SessionHoverForge.tsx @@ -9,6 +9,7 @@ import { IconBranchOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' // Type-only: pulls the ui-workspace SlotMap merge (the Session row seats). import type {} from '@deepseek-ai/dsh-client-ui-workspace/client' +import { branchLabel } from '../branch-name.ts' import { ChangeRequestGlyph } from './glyphs.tsx' import type { NS } from './locales.ts' import { useSessionForgeFacts, type SessionListInjected } from './session-list.ts' @@ -41,7 +42,7 @@ export function SessionHoverForge({ sessionId, useSessions, useStates, t }: Sess {worktree.branch} - {t('checkout.worktreeFrom', { base: worktree.from ?? worktree.baseCommit.slice(0, 7) })} + {t('checkout.worktreeFrom', { base: worktree.from === null ? worktree.baseCommit.slice(0, 7) : branchLabel(worktree.from) })}
    )} diff --git a/packages/experimental/client-ui-forge/src/client/WorktreeNameDialog.module.css b/packages/experimental/client-ui-forge/src/client/WorktreeNameDialog.module.css new file mode 100644 index 0000000000..d2c6ff08b8 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/WorktreeNameDialog.module.css @@ -0,0 +1,53 @@ +/* Naming dialog of a worktree branch: the Modal body's field, its message line, and the footer's left action. */ + +.form { + display: flex; + flex-direction: column; + gap: 6px; + min-width: 0; +} + +.label { + color: var(--dsw-alias-label-secondary); + font-size: 13px; + line-height: 20px; +} + +.field { + box-sizing: border-box; + width: 100%; +} + +.field input { + font-family: var(--ds-font-family-code); + font-size: 13px; +} + +.field.invalid, +.field.invalid:focus-within { + border-color: var(--dsw-alias-state-error-primary); +} + +/* Reserves two lines, so a longer reason replacing the hint does not move the footer. */ +.message { + min-height: 36px; + margin: 0; + color: var(--dsw-alias-label-tertiary); + font-size: 12px; + line-height: 18px; + overflow-wrap: anywhere; +} + +.error { + color: var(--dsw-alias-state-error-primary); +} + +.auto { + margin-right: auto; +} + +@media (pointer: coarse) { + .field input { + font-size: 16px; + } +} diff --git a/packages/experimental/client-ui-forge/src/client/WorktreeNameDialog.tsx b/packages/experimental/client-ui-forge/src/client/WorktreeNameDialog.tsx new file mode 100644 index 0000000000..ecba7f09a3 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/WorktreeNameDialog.tsx @@ -0,0 +1,93 @@ +/** Dialog that names the new branch of a requested worktree, from the New Session option or after a failed attempt. */ + +import { useId, useState, type ReactNode } from 'react' +import clsx from 'clsx' +import { Button, Input, Modal } from '@deepseek-ai/dsh-client-ui-primitives' +import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' +import { branchLabel, branchNameProblem } from '../branch-name.ts' +import type { NS } from './locales.ts' +import css from './WorktreeNameDialog.module.css' + +/** + * Outcome of a worktree request: accepted; refused for its branch name, which the dialog shows; or failed otherwise, + * which the request reports itself. + */ +export type WorktreeRequestResult = 'accepted' | 'invalid-name' | 'branch-exists' | 'failed' + +/** Props of the naming dialog. */ +export interface WorktreeNameDialogProps extends PropsLocale { + /** `name` names the branch of the open request; `retry` renames it after a failed attempt, then tries again. */ + readonly mode: 'name' | 'retry' + /** Text the field starts with: the chosen name, or the prefix of generated names. */ + readonly initial: string + /** Prefix of generated names; a field that holds only the prefix names no branch yet. */ + readonly prefix: string + /** Base of the request, or null for HEAD. */ + readonly from: string | null + /** Whether the request already names its branch, which offers a return to generated names. */ + readonly named: boolean + /** + * Request the worktree on `name`, or on generated names for null; in `retry` mode the caller also tries again + * once the request is accepted. + */ + readonly submit: (name: string | null) => Promise + /** Close the dialog without a request. */ + readonly close: () => void +} + +/** + * Render the dialog: one branch name field checked against Git's branch-name rules while it is typed, and checked by + * the Host when it is confirmed. A refused name keeps the dialog open with the reason under the field; an accepted + * request closes it. + * @param props - mode, starting text, prefix, base, the request, and copy. + * @returns the dialog. + */ +export function WorktreeNameDialog({ mode, initial, prefix, from, named, submit, close, t }: WorktreeNameDialogProps): ReactNode { + const [value, setValue] = useState(initial) + const [refusal, setRefusal] = useState<{ readonly name: string; readonly text: string } | null>(null) + const [busy, setBusy] = useState(false) + const fieldId = useId() + const messageId = useId() + // The starting prefix names no branch yet, so it gets the hint rather than a rule it breaks, such as a trailing `/`. + const blank = value === prefix + const problem = blank ? null : branchNameProblem(value) + const error = problem !== null ? t(`branchName.${problem}`) : refusal?.name === value ? refusal.text : null + const retry = mode === 'retry' + const send = (name: string | null): void => { + setBusy(true) + void submit(name).then((result) => { + setBusy(false) + if (result === 'accepted') close() + else if (name !== null && result === 'branch-exists') setRefusal({ name, text: t('branchName.exists', { name }) }) + else if (name !== null && result === 'invalid-name') setRefusal({ name, text: t('branchName.invalid') }) + }) + } + const confirmable = !busy && error === null && !blank + const base = from === null ? null : branchLabel(from) + const hint = blank && prefix !== '' ? t('nameDialog.prefixOnly') : base === null ? t('nameDialog.hintHead') : t('nameDialog.hint', { branch: base }) + return ( + + {named && !retry && ( + + )} + + + }> +
    + + { setValue(event.target.value) }} + onKeyDown={(event) => { + if (event.key !== 'Enter' || event.nativeEvent.isComposing) return + event.preventDefault() + if (confirmable) send(value) + }} /> +

    {error ?? hint}

    +
    +
    + ) +} diff --git a/packages/experimental/client-ui-forge/src/client/WorktreeProgress.tsx b/packages/experimental/client-ui-forge/src/client/WorktreeProgress.tsx index bc3cc19c71..d5ccdc4eb1 100644 --- a/packages/experimental/client-ui-forge/src/client/WorktreeProgress.tsx +++ b/packages/experimental/client-ui-forge/src/client/WorktreeProgress.tsx @@ -11,9 +11,11 @@ import { import type { HostObservable, InjectFace, PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' import { assertNever } from '@deepseek-ai/dsh-util-values' +import { branchLabel } from '../branch-name.ts' import type { ForgeMissingWorktree, ForgePanelWorktree, ForgeSessionWorktree, ForgeWorktreeRestoration } from '../types.ts' import type { ForgePanelKey, NS } from './locales.ts' import type { PanelSnapshot } from './source.ts' +import { WorktreeNameDialog, type WorktreeRequestResult } from './WorktreeNameDialog.tsx' import css from './WorktreeProgress.module.css' /** Business face of the card. */ @@ -22,8 +24,18 @@ export interface WorktreeProgressInjected { readonly hooks: { readonly panel: HostObservable } /** Stop the running attempt a message waits for; the message keeps waiting. */ readonly stop: () => void - /** Make another attempt at the worktree a message waits for. */ - readonly retry: () => void + /** + * Make another attempt at the worktree a message waits for. + * @param fetch - false starts from the remote base branch as last fetched, without fetching it. + */ + readonly retry: (fetch: boolean) => void + /** + * Request the worktree again from the same base on another branch name, before another attempt. + * @param from - base of the open request, or null for HEAD. + * @param name - new branch name. + * @returns the outcome; a failure other than a refused name is already reported. + */ + readonly request: (from: string | null, name: string | null) => Promise /** Withdraw the worktree request, so the waiting message goes on without a worktree. */ readonly withdraw: () => void /** @@ -42,43 +54,57 @@ type Translate = WorktreeProgressProps['t'] type StepState = 'done' | 'running' | 'waiting' | 'failed' -type Phase = 'prepare' | 'checkout' +type Phase = 'fetch' | 'prepare' | 'checkout' -type StepList = readonly { readonly phase: Phase; readonly label: ForgePanelKey }[] +/** Steps in the order they run, each with its label. */ +type StepList = readonly { readonly phase: Phase; readonly label: ReactNode }[] -const CREATION_STEPS: StepList = [ - { phase: 'prepare', label: 'creation.prepare' }, - { phase: 'checkout', label: 'creation.checkout' }, -] - -const RESTORATION_STEPS: StepList = [ - { phase: 'prepare', label: 'restoration.prepare' }, - { phase: 'checkout', label: 'creation.checkout' }, -] - -function stepState(current: 'prepare' | 'checkout', failed: boolean, phase: 'prepare' | 'checkout'): StepState { - if (phase === current) return failed ? 'failed' : 'running' - return phase === 'prepare' ? 'done' : 'waiting' +function stepState(steps: StepList, current: Phase, failed: boolean, phase: Phase): StepState { + const at = steps.findIndex(step => step.phase === current) + const index = steps.findIndex(step => step.phase === phase) + if (index === at) return failed ? 'failed' : 'running' + return index < at ? 'done' : 'waiting' } -function Steps({ steps, phase, failed, t }: { +function Steps({ steps, phase, failed }: { readonly steps: StepList readonly phase: Phase readonly failed: boolean - readonly t: Translate }): ReactNode { return (
      - {steps.map(step => ( -
    • - - {t(step.label)} -
    • - ))} + {steps.map((step) => { + const state = stepState(steps, phase, failed, step.phase) + return ( +
    • + + {step.label} +
    • + ) + })}
    ) } +/** The steps of a creation, which fetches a remote base branch first when it asks to. */ +function creationSteps(creation: CreationView, t: Translate): StepList { + const from = creation.from === null ? null : branchLabel(creation.from) + return [ + ...creation.fetch && from !== null + ? [{ phase: 'fetch' as const, label: t('creation.fetch', { branch: from }) }] + : [], + { phase: 'prepare', label: t('creation.prepare') }, + { phase: 'checkout', label: t('creation.checkout') }, + ] +} + +function restorationSteps(t: Translate): StepList { + return [ + { phase: 'prepare', label: t('restoration.prepare') }, + { phase: 'checkout', label: t('creation.checkout') }, + ] +} + function StepIcon({ state }: { readonly state: StepState }): ReactNode { switch (state) { case 'done': return @@ -93,11 +119,15 @@ function StepIcon({ state }: { readonly state: StepState }): ReactNode { /** One creation as the card shows it: the running attempt, or the failed or stopped one a message waits after. */ interface CreationView { readonly state: 'running' | 'failed' | 'stopped' - readonly phase: 'prepare' | 'checkout' + readonly phase: Phase readonly branch: string | null readonly from: string | null + /** Whether the attempt fetches its remote base branch first. */ + readonly fetch: boolean /** Failure text, or null unless the attempt failed. */ readonly message: string | null + /** Whether the failed attempt found its branch or checkout directory taken. */ + readonly exists: boolean /** Whether a message waits for the running attempt, which can then be stopped. */ readonly held: boolean } @@ -105,10 +135,12 @@ interface CreationView { /** The running attempt, else the failed or stopped one a message waits after, or undefined without either. */ function creationOf(worktree: ForgePanelWorktree): CreationView | undefined { const { creation, failure, waiting } = worktree - if (creation !== null) return { ...creation, state: 'running', message: null } + if (creation !== null) return { ...creation, state: 'running', message: null, exists: false } if (waiting !== 'creation') return undefined if (failure !== null) return { ...failure, state: 'failed', held: false } - return { state: 'stopped', phase: 'prepare', branch: null, from: worktree.request?.from ?? null, message: null, held: false } + return { + state: 'stopped', phase: 'prepare', branch: null, from: worktree.request?.from ?? null, fetch: false, message: null, exists: false, held: false, + } } function Details({ creation, t }: { readonly creation: CreationView; readonly t: Translate }): ReactNode { @@ -121,7 +153,7 @@ function Details({ creation, t }: { readonly creation: CreationView; readonly t: )}
    {t('creation.base')}
    -
    {creation.from ?? t('creation.head')}
    +
    {creation.from === null ? t('creation.head') : branchLabel(creation.from)}
    {creation.message !== null && ( <>
    {t('creation.error')}
    @@ -138,17 +170,38 @@ const CREATION_TITLE: Record = { stopped: 'creation.stopped', } -function CreationCard({ creation, stop, retry, withdraw, t }: { +/** The buttons of a failed or stopped attempt before withdrawing; the first one is the primary action. */ +function waitingActions(creation: CreationView, named: boolean, retry: WorktreeProgressInjected['retry'], rename: () => void, t: Translate): ReactNode { + const again = { key: 'retry', label: t('creation.retry'), act: () => { retry(true) } } + const actions = creation.state === 'failed' && creation.phase === 'fetch' + ? [again, { key: 'fetched', label: t('creation.useFetched'), act: () => { retry(false) } }] + : creation.state === 'failed' && creation.exists && named + ? [{ key: 'rename', label: t('creation.rename'), act: rename }, again] + : [again] + return actions.map((action, index) => ( + + )) +} + +function CreationCard({ creation, open: openRequest, prefix, stop, retry, withdraw, request, t }: { readonly creation: CreationView + /** The open request, whose base a rename keeps and whose branch name it replaces. */ + readonly open: ForgePanelWorktree['request'] + /** Prefix of generated branch names. */ + readonly prefix: string readonly stop: WorktreeProgressInjected['stop'] readonly retry: WorktreeProgressInjected['retry'] readonly withdraw: WorktreeProgressInjected['withdraw'] + readonly request: WorktreeProgressInjected['request'] readonly t: Translate }): ReactNode { const [open, setOpen] = useState(false) + const [renaming, setRenaming] = useState(false) const running = creation.state === 'running' const failed = creation.state === 'failed' const title = t(CREATION_TITLE[creation.state]) + const name = openRequest?.name ?? null + const from = openRequest?.from ?? null return (
    @@ -157,7 +210,7 @@ function CreationCard({ creation, stop, retry, withdraw, t }: { {title} {creation.branch !== null && {creation.branch}}
    - {creation.state !== 'stopped' && } + {creation.state !== 'stopped' && } {(open || failed) &&
    } {!running &&

    {t('creation.waiting')}

    }
    @@ -169,7 +222,7 @@ function CreationCard({ creation, stop, retry, withdraw, t }: { )} {!running && ( - + {waitingActions(creation, name !== null, retry, () => { setRenaming(true) }, t)} )} @@ -180,6 +233,15 @@ function CreationCard({ creation, stop, retry, withdraw, t }: { )}
    + {renaming && name !== null && ( + { + const result = await request(from, next) + if (result === 'accepted') retry(true) + return result + }} + close={() => { setRenaming(false) }} t={t} /> + )}
    ) } @@ -222,7 +284,7 @@ function MissingCard({ created, missing, restoration, waiting, restore, leave, t {t('restoration.title')} {created.branch}
    - + ) @@ -260,11 +322,14 @@ function MissingCard({ created, missing, restoration, waiting, restore, leave, t * @param props - panel hook, actions, and copy. * @returns the card, or nothing while no attempt runs, no message waits, and the worktree exists. */ -export function WorktreeProgress({ usePanel, stop, retry, withdraw, restore, leave, t }: WorktreeProgressProps): ReactNode { +export function WorktreeProgress({ usePanel, stop, retry, withdraw, request, restore, leave, t }: WorktreeProgressProps): ReactNode { const worktree = usePanel(snapshot => snapshot.state?.worktree ?? null) if (worktree === null) return null const creation = creationOf(worktree) - if (creation !== undefined) return + if (creation !== undefined) { + return + } if (worktree.missing === null || worktree.created === null) return null return ( } /** - * Request a worktree from a base branch, replacing an open request. - * @param from - base branch, or null for HEAD. - * @returns whether the Host accepted it. + * Request a worktree from a base on a branch name, replacing an open request. + * @param from - full name of a local or remote-tracking base branch, or null for HEAD. + * @param name - new branch name, or null for a generated one. + * @returns the outcome; a failure other than a refused name is already reported. */ - readonly request: (from: string | null) => Promise + readonly request: (from: string | null, name: string | null) => Promise /** * Withdraw the open request. * @returns whether the Host accepted it. */ readonly cancel: () => Promise /** - * List the local branches of the Session's checkout. - * @returns the branches, or undefined when they could not be read. + * List the branches a worktree of the Session's checkout can start from whose names contain `query`. + * @param query - search text; empty for every branch. + * @param signal - aborts the read. + * @returns the branches, or the failure the menu shows. */ - readonly branches: () => Promise + readonly bases: (query: string, signal: AbortSignal) => Promise> } /** Full props of the New Session option. */ @@ -38,59 +48,156 @@ export type WorktreeToggleProps = InjectFace & PropsLoca type Translate = WorktreeToggleProps['t'] -function BaseMenu({ base, held, branches, request, t }: { - readonly base: string | null - /** Whether the worktree is being created, which freezes the base. */ +/** One selectable branch row: the branch, the remote it belongs to, and the tag that names a pinned row. */ +interface BaseRow { + readonly branch: ForgeBaseBranch + readonly remote?: string + readonly tag?: string +} + +/** What the option says about a request's base. */ +function baseTextOf(from: string | null, t: Translate): string { + return from === null ? t('worktree.baseHead') : t('worktree.base', { branch: branchLabel(from) }) +} + +/** What the option says about a request that names its branch. */ +function namedTipOf(name: string, from: string | null, t: Translate): string { + return from === null ? t('worktree.namedTipHead', { name }) : t('worktree.namedTip', { name, branch: branchLabel(from) }) +} + +/** The full name of a request's base; earlier panels recorded local branches by their short names. */ +function refOf(from: string | null): string | null { + return from === null || from.startsWith('refs/') ? from : `${LOCAL_REF_PREFIX}${from}` +} + +/** A branch name split into a remote's prefix and the rest; local branches have no prefix. */ +function nameParts(branch: ForgeBaseBranch, remote: string | undefined): { readonly prefix: string; readonly rest: string } { + return remote !== undefined && branch.ref.startsWith(REMOTE_REF_PREFIX) + ? { prefix: `${remote}/`, rest: branch.name.slice(remote.length + 1) } + : { prefix: '', rest: branch.name } +} + +function BranchRows({ rows, chosen, pick }: { + readonly rows: readonly BaseRow[] + readonly chosen: string | null + readonly pick: (ref: string) => void +}): ReactNode { + return rows.map(({ branch, remote, tag }) => { + const selected = branch.ref === chosen + const parts = nameParts(branch, remote) + return ( + } current={selected} + onSelect={() => { pick(branch.ref) }}> + + + {parts.prefix !== '' && {parts.prefix}} + {parts.rest} + + {tag !== undefined && {tag}} + {selected && } + + + ) + }) +} + +function WorktreeMenu({ from, name, held, bases, choose, nameBranch, t }: { + readonly from: string | null + readonly name: string | null + /** Whether the worktree is being created, which freezes the request. */ readonly held: boolean - readonly branches: WorktreeToggleInjected['branches'] - readonly request: WorktreeToggleInjected['request'] + readonly bases: WorktreeToggleInjected['bases'] + readonly choose: (ref: string) => void + readonly nameBranch: () => void readonly t: Translate }): ReactNode { - const [listed, setListed] = useState(null) const [open, setOpen] = useState(false) - const [loading, setLoading] = useState(false) - const show = (): void => { - if (open) { - setOpen(false) - return - } - setLoading(true) - void branches().then((result) => { - setLoading(false) - if (result === undefined) return - setListed(result) - setOpen(true) - }) + const { query, setQuery, listing, retry, reset, field } = useBranchSearch(open, bases) + const chosen = refOf(from) + const close = (): void => { + setOpen(false) + reset() } - const items: MenuEntry[] = [ - { type: 'label', id: 'title', text: t('worktree.baseMenu') }, - ...(listed?.branches ?? []).map(name => ({ - id: name, - label: name === listed?.current - ? {name}{t('worktree.currentBranch')} - : {name}, - })), - ] + const pick = (ref: string): void => { + close() + if (ref !== chosen) choose(ref) + } + const value = listing?.ok === true ? listing.value : null + const needle = query.trim().toLowerCase() + const matches = (branch: ForgeBaseBranch): boolean => branch.name.toLowerCase().includes(needle) + const pinned: BaseRow[] = value === null ? [] : [ + ...value.current === null ? [] : [{ branch: value.current, tag: t('worktree.currentBranch') }], + ...value.defaults.map(({ remote, ...branch }) => ({ branch, remote, tag: t('worktree.remoteDefault') })), + ].filter(row => matches(row.branch)) + const local = (value?.local ?? []).filter(matches).map(branch => ({ branch })) + const remotes = (value?.remotes ?? []).map(remote => ({ + ...remote, rows: remote.branches.filter(matches).map(branch => ({ branch, remote: remote.name })), + })) + .filter(remote => remote.rows.length > 0) + const first = pinned[0] ?? local[0] ?? remotes[0]?.rows[0] + + const body: ReactNode = branchSearchStatus({ listing, empty: first === undefined, retry, className: css.status, t }) ?? <> + {pinned.length > 0 &&
    } + {local.length > 0 && ( +
    +
    {t('diff.base.local')}
    + +
    + )} + {remotes.map(remote => ( +
    +
    + {t('worktree.remoteGroup', { remote: remote.name })} + {remote.repository !== null && {remote.repository}} +
    + +
    + ))} + + + const baseText = baseTextOf(from, t) + const label = name === null ? baseText : namedTipOf(name, from, t) return ( { - setOpen(false) - if (id !== base) void request(id) - }} - onClose={() => { setOpen(false) }} side="bottom" align="end" portal + dense + className={css.anchor} + listClassName={css.menu} + onClose={close} anchor={ - + + + } - /> + > +
    +
    + } value={query} + aria-label={t('diff.base.search')} placeholder={t('diff.base.search')} + onChange={(event) => { setQuery(event.target.value) }} + onKeyDown={(event) => { searchFieldKeyDown(event, first === undefined ? undefined : () => { pick(first.branch.ref) }) }} /> +
    +
    {body}
    +
    + : } + onSelect={() => { close(); nameBranch() }}> + + {t(name === null ? 'worktree.name.add' : 'worktree.name.label')} + {name ?? t('worktree.name.auto')} + + +
    +
    +
    ) } @@ -110,35 +217,42 @@ function optionOf(state: ForgePanelState | null): { /** * Render the worktree option while the Session can still start in a worktree: - * the current branch, or the base branch menu once requested, then the checkbox. - * A blocked request keeps its selected base visible without a menu; the checkbox - * only withdraws it. Branch details support pointer, touch, and keyboard access. - * The request stays fixed while the worktree is being created. - * @param props - panel snapshot hook, request actions, and copy. + * the current branch, or the base and branch name menu once requested, then the + * checkbox. The menu searches local branches and each remote's branches and + * opens the naming dialog. A blocked request keeps its selected base visible + * without a menu; the checkbox only withdraws it. Branch details support + * pointer, touch, and keyboard access. The request stays fixed while the + * worktree is being created. + * @param props - panel snapshot hook, request actions, the base listing, and copy. * @returns the option, or nothing outside a known Git checkout, once a turn started, * the request settled, or no worktree service is mounted. */ -export function WorktreeToggle({ usePanel, request, cancel, branches, t }: WorktreeToggleProps): ReactNode { +export function WorktreeToggle({ usePanel, request, cancel, bases, t }: WorktreeToggleProps): ReactNode { const state = usePanel(snapshot => snapshot.state) const [pending, setPending] = useState(null) + const [naming, setNaming] = useState(false) const option = optionOf(state) if (state === null || option === undefined) return null const held = state.worktree.creation !== null const requested = pending ?? state.worktree.request !== null const usable = option.blocker === null const disabled = held || pending !== null || (!usable && !requested) + const currentRef = option.current === null ? null : `${LOCAL_REF_PREFIX}${option.current}` const current = option.current ?? (option.commit === null ? t('checkout.detached') : t('worktree.detachedTip', { commit: option.commit })) - const base = state.worktree.request === null ? option.current : state.worktree.request.from - const branchText = requested ? base === null ? t('worktree.baseHead') : t('worktree.base', { branch: base }) : current + const from = state.worktree.request === null ? currentRef : state.worktree.request.from + const name = state.worktree.request?.name ?? null + const requestedText = name === null ? baseTextOf(from, t) : namedTipOf(name, from, t) + const branchText = requested ? requestedText : current const branchTip = requested || option.current === null ? branchText : t('worktree.currentBranchTip', { branch: option.current }) const change = (checked: boolean): void => { setPending(checked) - void (checked ? request(option.current) : cancel()).then(() => { setPending(null) }) + void (checked ? request(currentRef, null) : cancel()).then(() => { setPending(null) }) } return ( {requested && usable ? ( - + { void request(ref, name) }} nameBranch={() => { setNaming(true) }} /> ) : ( + + ) + } + return empty ?
    {t('diff.base.empty')}
    : null +} diff --git a/packages/experimental/client-ui-forge/src/client/checkout.ts b/packages/experimental/client-ui-forge/src/client/checkout.ts index 1e2a9d4684..d7a390c109 100644 --- a/packages/experimental/client-ui-forge/src/client/checkout.ts +++ b/packages/experimental/client-ui-forge/src/client/checkout.ts @@ -2,6 +2,7 @@ import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' import { abbreviateHomePath } from '@deepseek-ai/dsh-util-workspace-path' +import { branchLabel } from '../branch-name.ts' import type { ForgePanelState } from '../types.ts' import type { NS } from './locales.ts' @@ -52,7 +53,7 @@ export function checkoutLabel(state: ForgePanelState, home: string | undefined, const { root, branch, linked, commit } = state.checkout.checkout const path = abbreviateHomePath(root, home) if (created !== null && created.path === root) { - const base = created.from ?? created.baseCommit.slice(0, 7) + const base = created.from === null ? created.baseCommit.slice(0, 7) : branchLabel(created.from) return { name: branch ?? commit, detached: branch === null, diff --git a/packages/experimental/client-ui-forge/src/client/locales.ts b/packages/experimental/client-ui-forge/src/client/locales.ts index a93ae5afd7..a2a27a90d9 100644 --- a/packages/experimental/client-ui-forge/src/client/locales.ts +++ b/packages/experimental/client-ui-forge/src/client/locales.ts @@ -330,7 +330,6 @@ export const zh = { 'worktree.blocked.read-only': '只读模式下无法使用工作树', 'worktree.base': '基于 {branch}', 'worktree.baseHead': '基于当前 HEAD', - 'worktree.baseMenu': '选择基准分支', 'worktree.currentBranch': '当前分支', 'worktree.currentBranchTip': '当前分支:{branch}', 'worktree.detachedTip': '未在分支上 · {commit}', @@ -347,6 +346,45 @@ export const zh = { 'creation.cancel': '取消', 'creation.stopped': '已停止创建工作树', 'creation.retry': '重试', + 'diff.loading': '正在读取变更…', + 'diff.allFilesLoading': '全部文件', + 'worktree.pinned': '当前分支与远程默认分支', + 'worktree.remoteDefault': '远程默认', + 'worktree.remoteGroup': '远程 · {remote}', + 'worktree.namedTip': '新分支 {name},基于 {branch}', + 'worktree.namedTipHead': '新分支 {name},基于当前 HEAD', + 'worktree.name.add': '指定新分支名称…', + 'worktree.name.label': '新分支名称', + 'worktree.name.auto': '自动命名', + 'nameDialog.title': '命名新分支', + 'nameDialog.retryTitle': '更改分支名称', + 'nameDialog.field': '分支名称', + 'nameDialog.hint': '发送第一条消息时基于 {branch} 新建此分支,工作树目录与分支同名', + 'nameDialog.hintHead': '发送第一条消息时基于当前 HEAD 新建此分支,工作树目录与分支同名', + 'nameDialog.prefixOnly': '在前缀后输入名称', + 'nameDialog.auto': '改回自动命名', + 'nameDialog.cancel': '取消', + 'nameDialog.confirm': '确定', + 'nameDialog.retry': '重试', + 'nameDialog.close': '关闭', + 'branchName.empty': '输入分支名称', + 'branchName.space': '分支名不能包含空格', + 'branchName.character': '分支名不能包含 ~ ^ : ? * [ \\ 这些字符', + 'branchName.leading-dash': '分支名不能以“-”开头', + 'branchName.leading-slash': '分支名不能以“/”开头', + 'branchName.trailing-slash': '分支名不能以“/”结尾', + 'branchName.double-slash': '分支名不能包含连续的“/”', + 'branchName.double-dot': '分支名不能包含“..”', + 'branchName.trailing-dot': '分支名不能以“.”结尾', + 'branchName.at': '分支名不能是“@”', + 'branchName.at-brace': '分支名不能包含“@{”', + 'branchName.dot-segment': '“/”分隔的每一段都不能以“.”开头', + 'branchName.lock-segment': '“/”分隔的每一段都不能以“.lock”结尾', + 'branchName.exists': '分支 {name} 已存在', + 'branchName.invalid': 'Git 不接受这个分支名', + 'creation.fetch': '获取 {branch}', + 'creation.useFetched': '使用上次获取的版本', + 'creation.rename': '更改名称', 'creation.waiting': '消息会在工作树建好后发送', 'missing.title': '工作树不可用', 'missing.unknown': '工作树恢复尚未完成,暂时无法确认分支 {branch} 的状态。请排除恢复错误后重试,或在项目目录继续', @@ -780,7 +818,6 @@ export const en: Record = { 'worktree.blocked.read-only': 'A read-only Session cannot use a worktree', 'worktree.base': 'From {branch}', 'worktree.baseHead': 'From the current HEAD', - 'worktree.baseMenu': 'Base branch', 'worktree.currentBranch': 'Current', 'worktree.currentBranchTip': 'Current branch: {branch}', 'worktree.detachedTip': 'Not on a branch · {commit}', @@ -797,6 +834,45 @@ export const en: Record = { 'creation.cancel': 'Cancel', 'creation.stopped': 'Worktree creation stopped', 'creation.retry': 'Retry', + 'diff.loading': 'Reading changes…', + 'diff.allFilesLoading': 'All files', + 'worktree.pinned': 'Current and remote default branches', + 'worktree.remoteDefault': 'Remote default', + 'worktree.remoteGroup': 'Remote · {remote}', + 'worktree.namedTip': 'New branch {name} from {branch}', + 'worktree.namedTipHead': 'New branch {name} from the current HEAD', + 'worktree.name.add': 'Name the new branch…', + 'worktree.name.label': 'New branch name', + 'worktree.name.auto': 'Generated', + 'nameDialog.title': 'Name the new branch', + 'nameDialog.retryTitle': 'Rename the branch', + 'nameDialog.field': 'Branch name', + 'nameDialog.hint': 'The first message creates this branch from {branch}; the worktree directory takes its name', + 'nameDialog.hintHead': 'The first message creates this branch from the current HEAD; the worktree directory takes its name', + 'nameDialog.prefixOnly': 'Type a name after the prefix', + 'nameDialog.auto': 'Use a generated name', + 'nameDialog.cancel': 'Cancel', + 'nameDialog.confirm': 'Save', + 'nameDialog.retry': 'Retry', + 'nameDialog.close': 'Close', + 'branchName.empty': 'Enter a branch name', + 'branchName.space': 'Branch names cannot contain spaces', + 'branchName.character': 'Branch names cannot contain ~ ^ : ? * [ or \\', + 'branchName.leading-dash': 'Branch names cannot start with “-”', + 'branchName.leading-slash': 'Branch names cannot start with “/”', + 'branchName.trailing-slash': 'Branch names cannot end with “/”', + 'branchName.double-slash': 'Branch names cannot contain “//”', + 'branchName.double-dot': 'Branch names cannot contain “..”', + 'branchName.trailing-dot': 'Branch names cannot end with “.”', + 'branchName.at': 'A branch cannot be named “@”', + 'branchName.at-brace': 'Branch names cannot contain “@{”', + 'branchName.dot-segment': 'No part between slashes can start with “.”', + 'branchName.lock-segment': 'No part between slashes can end with “.lock”', + 'branchName.exists': 'A branch named {name} already exists', + 'branchName.invalid': 'Git does not accept this branch name', + 'creation.fetch': 'Fetch {branch}', + 'creation.useFetched': 'Use the last fetched version', + 'creation.rename': 'Rename', 'creation.waiting': 'The message is sent once the worktree exists', 'missing.title': 'The worktree is unavailable', 'missing.unknown': 'Worktree restoration is incomplete and branch {branch} cannot be inspected. Resolve the restoration error and retry, or continue in the project.', @@ -1234,7 +1310,6 @@ export const ja: Record = { 'worktree.blocked.read-only': '読み取り専用のセッションではワークツリーを使用できません', 'worktree.base': '基点 {branch}', 'worktree.baseHead': '現在の HEAD を基点にする', - 'worktree.baseMenu': '基準ブランチ', 'worktree.currentBranch': '現在', 'worktree.currentBranchTip': '現在のブランチ:{branch}', 'worktree.detachedTip': 'ブランチ上にありません · {commit}', @@ -1251,6 +1326,45 @@ export const ja: Record = { 'creation.cancel': 'キャンセル', 'creation.stopped': 'ワークツリーの作成を停止しました', 'creation.retry': '再試行', + 'diff.loading': '変更を読み取り中…', + 'diff.allFilesLoading': 'すべてのファイル', + 'worktree.pinned': '現在のブランチとリモートのデフォルト', + 'worktree.remoteDefault': 'リモートのデフォルト', + 'worktree.remoteGroup': 'リモート · {remote}', + 'worktree.namedTip': '新しいブランチ {name}、基点 {branch}', + 'worktree.namedTipHead': '新しいブランチ {name}、基点は現在の HEAD', + 'worktree.name.add': '新しいブランチに名前を付ける…', + 'worktree.name.label': '新しいブランチ名', + 'worktree.name.auto': '自動生成', + 'nameDialog.title': '新しいブランチに名前を付ける', + 'nameDialog.retryTitle': 'ブランチ名を変更', + 'nameDialog.field': 'ブランチ名', + 'nameDialog.hint': '最初のメッセージの送信時に {branch} からこのブランチを作成し、ワークツリーのディレクトリも同じ名前になります', + 'nameDialog.hintHead': '最初のメッセージの送信時に現在の HEAD からこのブランチを作成し、ワークツリーのディレクトリも同じ名前になります', + 'nameDialog.prefixOnly': 'プレフィックスの後に名前を入力してください', + 'nameDialog.auto': '自動生成の名前に戻す', + 'nameDialog.cancel': 'キャンセル', + 'nameDialog.confirm': '保存', + 'nameDialog.retry': '再試行', + 'nameDialog.close': '閉じる', + 'branchName.empty': 'ブランチ名を入力してください', + 'branchName.space': 'ブランチ名に空白は使えません', + 'branchName.character': 'ブランチ名に ~ ^ : ? * [ \\ は使えません', + 'branchName.leading-dash': 'ブランチ名を「-」で始めることはできません', + 'branchName.leading-slash': 'ブランチ名を「/」で始めることはできません', + 'branchName.trailing-slash': 'ブランチ名を「/」で終えることはできません', + 'branchName.double-slash': 'ブランチ名に「//」は使えません', + 'branchName.double-dot': 'ブランチ名に「..」は使えません', + 'branchName.trailing-dot': 'ブランチ名を「.」で終えることはできません', + 'branchName.at': 'ブランチ名を「@」にすることはできません', + 'branchName.at-brace': 'ブランチ名に「@{」は使えません', + 'branchName.dot-segment': '「/」で区切った各部分を「.」で始めることはできません', + 'branchName.lock-segment': '「/」で区切った各部分を「.lock」で終えることはできません', + 'branchName.exists': 'ブランチ {name} はすでに存在します', + 'branchName.invalid': 'Git がこのブランチ名を受け付けません', + 'creation.fetch': '{branch} を取得', + 'creation.useFetched': '前回取得したバージョンを使う', + 'creation.rename': '名前を変更', 'creation.waiting': 'ワークツリーの作成後にメッセージを送信します', 'missing.title': 'ワークツリーを利用できません', 'missing.unknown': 'ワークツリーの復元が未完了のため、ブランチ {branch} を確認できません。復元エラーを解消して再試行するか、プロジェクトで続行してください', @@ -1681,7 +1795,6 @@ export const es: Record = { 'worktree.blocked.read-only': 'Una sesión de solo lectura no puede usar un árbol de trabajo', 'worktree.base': 'Desde {branch}', 'worktree.baseHead': 'Desde el HEAD actual', - 'worktree.baseMenu': 'Rama base', 'worktree.currentBranch': 'Actual', 'worktree.currentBranchTip': 'Rama actual: {branch}', 'worktree.detachedTip': 'Sin rama activa · {commit}', @@ -1698,6 +1811,45 @@ export const es: Record = { 'creation.cancel': 'Cancelar', 'creation.stopped': 'Creación del árbol de trabajo detenida', 'creation.retry': 'Reintentar', + 'diff.loading': 'Leyendo los cambios…', + 'diff.allFilesLoading': 'Todos los archivos', + 'worktree.pinned': 'Rama actual y ramas predeterminadas remotas', + 'worktree.remoteDefault': 'Predeterminada remota', + 'worktree.remoteGroup': 'Remoto · {remote}', + 'worktree.namedTip': 'Rama nueva {name} desde {branch}', + 'worktree.namedTipHead': 'Rama nueva {name} desde el HEAD actual', + 'worktree.name.add': 'Poner nombre a la rama nueva…', + 'worktree.name.label': 'Nombre de la rama nueva', + 'worktree.name.auto': 'Generado', + 'nameDialog.title': 'Poner nombre a la rama nueva', + 'nameDialog.retryTitle': 'Cambiar el nombre de la rama', + 'nameDialog.field': 'Nombre de la rama', + 'nameDialog.hint': 'El primer mensaje crea esta rama desde {branch}; el directorio del árbol de trabajo toma su nombre', + 'nameDialog.hintHead': 'El primer mensaje crea esta rama desde el HEAD actual; el directorio del árbol de trabajo toma su nombre', + 'nameDialog.prefixOnly': 'Escribe un nombre después del prefijo', + 'nameDialog.auto': 'Usar un nombre generado', + 'nameDialog.cancel': 'Cancelar', + 'nameDialog.confirm': 'Guardar', + 'nameDialog.retry': 'Reintentar', + 'nameDialog.close': 'Cerrar', + 'branchName.empty': 'Escribe un nombre de rama', + 'branchName.space': 'El nombre de una rama no puede contener espacios', + 'branchName.character': 'El nombre de una rama no puede contener ~ ^ : ? * [ ni \\', + 'branchName.leading-dash': 'El nombre de una rama no puede empezar por «-»', + 'branchName.leading-slash': 'El nombre de una rama no puede empezar por «/»', + 'branchName.trailing-slash': 'El nombre de una rama no puede terminar en «/»', + 'branchName.double-slash': 'El nombre de una rama no puede contener «//»', + 'branchName.double-dot': 'El nombre de una rama no puede contener «..»', + 'branchName.trailing-dot': 'El nombre de una rama no puede terminar en «.»', + 'branchName.at': 'Una rama no puede llamarse «@»', + 'branchName.at-brace': 'El nombre de una rama no puede contener «@{»', + 'branchName.dot-segment': 'Ninguna parte entre barras puede empezar por «.»', + 'branchName.lock-segment': 'Ninguna parte entre barras puede terminar en «.lock»', + 'branchName.exists': 'Ya existe una rama llamada {name}', + 'branchName.invalid': 'Git no acepta este nombre de rama', + 'creation.fetch': 'Obtener {branch}', + 'creation.useFetched': 'Usar la última versión obtenida', + 'creation.rename': 'Cambiar nombre', 'creation.waiting': 'El mensaje se enviará cuando exista el árbol de trabajo', 'missing.title': 'El árbol de trabajo no está disponible', 'missing.unknown': 'La restauración está incompleta y no se puede consultar la rama {branch}. Resuelve el error y reintenta, o continúa en el proyecto', @@ -2128,7 +2280,6 @@ export const fr: Record = { 'worktree.blocked.read-only': 'Une session en lecture seule ne peut pas utiliser d’arbre de travail', 'worktree.base': 'Depuis {branch}', 'worktree.baseHead': 'Depuis le HEAD actuel', - 'worktree.baseMenu': 'Branche de base', 'worktree.currentBranch': 'Actuelle', 'worktree.currentBranchTip': 'Branche actuelle : {branch}', 'worktree.detachedTip': 'Aucune branche active · {commit}', @@ -2145,6 +2296,45 @@ export const fr: Record = { 'creation.cancel': 'Annuler', 'creation.stopped': 'Création de l’arbre de travail arrêtée', 'creation.retry': 'Réessayer', + 'diff.loading': 'Lecture des modifications…', + 'diff.allFilesLoading': 'Tous les fichiers', + 'worktree.pinned': 'Branche actuelle et branches par défaut des dépôts distants', + 'worktree.remoteDefault': 'Par défaut distante', + 'worktree.remoteGroup': 'Distant · {remote}', + 'worktree.namedTip': 'Nouvelle branche {name} depuis {branch}', + 'worktree.namedTipHead': 'Nouvelle branche {name} depuis le HEAD actuel', + 'worktree.name.add': 'Nommer la nouvelle branche…', + 'worktree.name.label': 'Nom de la nouvelle branche', + 'worktree.name.auto': 'Généré', + 'nameDialog.title': 'Nommer la nouvelle branche', + 'nameDialog.retryTitle': 'Renommer la branche', + 'nameDialog.field': 'Nom de la branche', + 'nameDialog.hint': 'Le premier message crée cette branche depuis {branch} ; le répertoire de l’arbre de travail prend son nom', + 'nameDialog.hintHead': 'Le premier message crée cette branche depuis le HEAD actuel ; le répertoire de l’arbre de travail prend son nom', + 'nameDialog.prefixOnly': 'Saisissez un nom après le préfixe', + 'nameDialog.auto': 'Utiliser un nom généré', + 'nameDialog.cancel': 'Annuler', + 'nameDialog.confirm': 'Enregistrer', + 'nameDialog.retry': 'Réessayer', + 'nameDialog.close': 'Fermer', + 'branchName.empty': 'Saisissez un nom de branche', + 'branchName.space': 'Un nom de branche ne peut pas contenir d’espaces', + 'branchName.character': 'Un nom de branche ne peut pas contenir ~ ^ : ? * [ ni \\', + 'branchName.leading-dash': 'Un nom de branche ne peut pas commencer par « - »', + 'branchName.leading-slash': 'Un nom de branche ne peut pas commencer par « / »', + 'branchName.trailing-slash': 'Un nom de branche ne peut pas finir par « / »', + 'branchName.double-slash': 'Un nom de branche ne peut pas contenir « // »', + 'branchName.double-dot': 'Un nom de branche ne peut pas contenir « .. »', + 'branchName.trailing-dot': 'Un nom de branche ne peut pas finir par « . »', + 'branchName.at': 'Une branche ne peut pas s’appeler « @ »', + 'branchName.at-brace': 'Un nom de branche ne peut pas contenir « @{ »', + 'branchName.dot-segment': 'Aucune partie entre barres obliques ne peut commencer par « . »', + 'branchName.lock-segment': 'Aucune partie entre barres obliques ne peut finir par « .lock »', + 'branchName.exists': 'Une branche nommée {name} existe déjà', + 'branchName.invalid': 'Git refuse ce nom de branche', + 'creation.fetch': 'Récupérer {branch}', + 'creation.useFetched': 'Utiliser la dernière version récupérée', + 'creation.rename': 'Renommer', 'creation.waiting': 'Le message sera envoyé après la création de l’arbre de travail', 'missing.title': 'L’arbre de travail est indisponible', 'missing.unknown': 'La restauration est incomplète et la branche {branch} ne peut pas être inspectée. Corrigez l’erreur puis réessayez, ou continuez dans le projet', @@ -2575,7 +2765,6 @@ export const de: Record = { 'worktree.blocked.read-only': 'Eine schreibgeschützte Sitzung kann keinen Arbeitsbaum verwenden', 'worktree.base': 'Aus {branch}', 'worktree.baseHead': 'Aus dem aktuellen HEAD', - 'worktree.baseMenu': 'Basis-Branch', 'worktree.currentBranch': 'Aktuell', 'worktree.currentBranchTip': 'Aktueller Branch: {branch}', 'worktree.detachedTip': 'Auf keinem Branch · {commit}', @@ -2592,6 +2781,45 @@ export const de: Record = { 'creation.cancel': 'Abbrechen', 'creation.stopped': 'Erstellung des Arbeitsbaums angehalten', 'creation.retry': 'Erneut versuchen', + 'diff.loading': 'Änderungen werden gelesen…', + 'diff.allFilesLoading': 'Alle Dateien', + 'worktree.pinned': 'Aktueller Branch und Standard-Branches der Remotes', + 'worktree.remoteDefault': 'Remote-Standard', + 'worktree.remoteGroup': 'Remote · {remote}', + 'worktree.namedTip': 'Neuer Branch {name} aus {branch}', + 'worktree.namedTipHead': 'Neuer Branch {name} aus dem aktuellen HEAD', + 'worktree.name.add': 'Neuen Branch benennen…', + 'worktree.name.label': 'Name des neuen Branches', + 'worktree.name.auto': 'Generiert', + 'nameDialog.title': 'Neuen Branch benennen', + 'nameDialog.retryTitle': 'Branch umbenennen', + 'nameDialog.field': 'Branch-Name', + 'nameDialog.hint': 'Die erste Nachricht erstellt diesen Branch aus {branch}; das Arbeitsbaumverzeichnis erhält denselben Namen', + 'nameDialog.hintHead': 'Die erste Nachricht erstellt diesen Branch aus dem aktuellen HEAD; das Arbeitsbaumverzeichnis erhält denselben Namen', + 'nameDialog.prefixOnly': 'Namen nach dem Präfix eingeben', + 'nameDialog.auto': 'Generierten Namen verwenden', + 'nameDialog.cancel': 'Abbrechen', + 'nameDialog.confirm': 'Speichern', + 'nameDialog.retry': 'Erneut versuchen', + 'nameDialog.close': 'Schließen', + 'branchName.empty': 'Branch-Namen eingeben', + 'branchName.space': 'Branch-Namen dürfen keine Leerzeichen enthalten', + 'branchName.character': 'Branch-Namen dürfen ~ ^ : ? * [ und \\ nicht enthalten', + 'branchName.leading-dash': 'Branch-Namen dürfen nicht mit „-“ beginnen', + 'branchName.leading-slash': 'Branch-Namen dürfen nicht mit „/“ beginnen', + 'branchName.trailing-slash': 'Branch-Namen dürfen nicht auf „/“ enden', + 'branchName.double-slash': 'Branch-Namen dürfen „//“ nicht enthalten', + 'branchName.double-dot': 'Branch-Namen dürfen „..“ nicht enthalten', + 'branchName.trailing-dot': 'Branch-Namen dürfen nicht auf „.“ enden', + 'branchName.at': 'Ein Branch darf nicht „@“ heißen', + 'branchName.at-brace': 'Branch-Namen dürfen „@{“ nicht enthalten', + 'branchName.dot-segment': 'Kein Teil zwischen Schrägstrichen darf mit „.“ beginnen', + 'branchName.lock-segment': 'Kein Teil zwischen Schrägstrichen darf auf „.lock“ enden', + 'branchName.exists': 'Ein Branch namens {name} existiert bereits', + 'branchName.invalid': 'Git akzeptiert diesen Branch-Namen nicht', + 'creation.fetch': '{branch} abrufen', + 'creation.useFetched': 'Zuletzt abgerufene Version verwenden', + 'creation.rename': 'Umbenennen', 'creation.waiting': 'Die Nachricht wird gesendet, sobald der Arbeitsbaum erstellt ist', 'missing.title': 'Arbeitsbaum nicht verfügbar', 'missing.unknown': 'Die Wiederherstellung ist unvollständig und Branch {branch} kann nicht geprüft werden. Den Fehler beheben und erneut versuchen oder im Projekt fortfahren', @@ -3022,7 +3250,6 @@ export const ru: Record = { 'worktree.blocked.read-only': 'Сеанс только для чтения не может использовать рабочее дерево', 'worktree.base': 'На основе {branch}', 'worktree.baseHead': 'На основе текущего HEAD', - 'worktree.baseMenu': 'Базовая ветка', 'worktree.currentBranch': 'Текущая', 'worktree.currentBranchTip': 'Текущая ветка: {branch}', 'worktree.detachedTip': 'Вне ветки · {commit}', @@ -3039,6 +3266,45 @@ export const ru: Record = { 'creation.cancel': 'Отмена', 'creation.stopped': 'Создание рабочего дерева остановлено', 'creation.retry': 'Повторить', + 'diff.loading': 'Чтение изменений…', + 'diff.allFilesLoading': 'Все файлы', + 'worktree.pinned': 'Текущая ветка и ветки по умолчанию удалённых репозиториев', + 'worktree.remoteDefault': 'По умолчанию на удалённом', + 'worktree.remoteGroup': 'Удалённый · {remote}', + 'worktree.namedTip': 'Новая ветка {name} от {branch}', + 'worktree.namedTipHead': 'Новая ветка {name} от текущего HEAD', + 'worktree.name.add': 'Назвать новую ветку…', + 'worktree.name.label': 'Имя новой ветки', + 'worktree.name.auto': 'Создаётся автоматически', + 'nameDialog.title': 'Назвать новую ветку', + 'nameDialog.retryTitle': 'Переименовать ветку', + 'nameDialog.field': 'Имя ветки', + 'nameDialog.hint': 'Первое сообщение создаст эту ветку от {branch}; каталог рабочего дерева получит то же имя', + 'nameDialog.hintHead': 'Первое сообщение создаст эту ветку от текущего HEAD; каталог рабочего дерева получит то же имя', + 'nameDialog.prefixOnly': 'Введите имя после префикса', + 'nameDialog.auto': 'Использовать созданное имя', + 'nameDialog.cancel': 'Отмена', + 'nameDialog.confirm': 'Сохранить', + 'nameDialog.retry': 'Повторить', + 'nameDialog.close': 'Закрыть', + 'branchName.empty': 'Введите имя ветки', + 'branchName.space': 'Имя ветки не может содержать пробелы', + 'branchName.character': 'Имя ветки не может содержать ~ ^ : ? * [ и \\', + 'branchName.leading-dash': 'Имя ветки не может начинаться с «-»', + 'branchName.leading-slash': 'Имя ветки не может начинаться с «/»', + 'branchName.trailing-slash': 'Имя ветки не может заканчиваться на «/»', + 'branchName.double-slash': 'Имя ветки не может содержать «//»', + 'branchName.double-dot': 'Имя ветки не может содержать «..»', + 'branchName.trailing-dot': 'Имя ветки не может заканчиваться на «.»', + 'branchName.at': 'Ветка не может называться «@»', + 'branchName.at-brace': 'Имя ветки не может содержать «@{»', + 'branchName.dot-segment': 'Ни одна часть между косыми чертами не может начинаться с «.»', + 'branchName.lock-segment': 'Ни одна часть между косыми чертами не может заканчиваться на «.lock»', + 'branchName.exists': 'Ветка {name} уже существует', + 'branchName.invalid': 'Git не принимает это имя ветки', + 'creation.fetch': 'Получение {branch}', + 'creation.useFetched': 'Использовать последнюю полученную версию', + 'creation.rename': 'Переименовать', 'creation.waiting': 'Сообщение будет отправлено после создания рабочего дерева', 'missing.title': 'Рабочее дерево недоступно', 'missing.unknown': 'Восстановление не завершено, ветка {branch} недоступна для проверки. Устраните ошибку и повторите попытку или продолжите в проекте', @@ -3469,7 +3735,6 @@ export const pt: Record = { 'worktree.blocked.read-only': 'Uma sessão somente leitura não pode usar uma árvore de trabalho', 'worktree.base': 'A partir de {branch}', 'worktree.baseHead': 'A partir do HEAD atual', - 'worktree.baseMenu': 'Branch base', 'worktree.currentBranch': 'Atual', 'worktree.currentBranchTip': 'Branch atual: {branch}', 'worktree.detachedTip': 'Fora de uma branch · {commit}', @@ -3486,6 +3751,45 @@ export const pt: Record = { 'creation.cancel': 'Cancelar', 'creation.stopped': 'Criação da árvore de trabalho interrompida', 'creation.retry': 'Tentar novamente', + 'diff.loading': 'Lendo as alterações…', + 'diff.allFilesLoading': 'Todos os arquivos', + 'worktree.pinned': 'Branch atual e branches padrão remotos', + 'worktree.remoteDefault': 'Padrão remoto', + 'worktree.remoteGroup': 'Remoto · {remote}', + 'worktree.namedTip': 'Branch novo {name} a partir de {branch}', + 'worktree.namedTipHead': 'Branch novo {name} a partir do HEAD atual', + 'worktree.name.add': 'Dar nome ao branch novo…', + 'worktree.name.label': 'Nome do branch novo', + 'worktree.name.auto': 'Gerado', + 'nameDialog.title': 'Dar nome ao branch novo', + 'nameDialog.retryTitle': 'Renomear o branch', + 'nameDialog.field': 'Nome do branch', + 'nameDialog.hint': 'A primeira mensagem cria este branch a partir de {branch}; o diretório da árvore de trabalho recebe o mesmo nome', + 'nameDialog.hintHead': 'A primeira mensagem cria este branch a partir do HEAD atual; o diretório da árvore de trabalho recebe o mesmo nome', + 'nameDialog.prefixOnly': 'Digite um nome depois do prefixo', + 'nameDialog.auto': 'Usar um nome gerado', + 'nameDialog.cancel': 'Cancelar', + 'nameDialog.confirm': 'Salvar', + 'nameDialog.retry': 'Tentar novamente', + 'nameDialog.close': 'Fechar', + 'branchName.empty': 'Digite um nome de branch', + 'branchName.space': 'Nomes de branch não podem conter espaços', + 'branchName.character': 'Nomes de branch não podem conter ~ ^ : ? * [ nem \\', + 'branchName.leading-dash': 'Nomes de branch não podem começar com “-”', + 'branchName.leading-slash': 'Nomes de branch não podem começar com “/”', + 'branchName.trailing-slash': 'Nomes de branch não podem terminar com “/”', + 'branchName.double-slash': 'Nomes de branch não podem conter “//”', + 'branchName.double-dot': 'Nomes de branch não podem conter “..”', + 'branchName.trailing-dot': 'Nomes de branch não podem terminar com “.”', + 'branchName.at': 'Um branch não pode se chamar “@”', + 'branchName.at-brace': 'Nomes de branch não podem conter “@{”', + 'branchName.dot-segment': 'Nenhuma parte entre barras pode começar com “.”', + 'branchName.lock-segment': 'Nenhuma parte entre barras pode terminar com “.lock”', + 'branchName.exists': 'Já existe um branch chamado {name}', + 'branchName.invalid': 'O Git não aceita este nome de branch', + 'creation.fetch': 'Obter {branch}', + 'creation.useFetched': 'Usar a última versão obtida', + 'creation.rename': 'Renomear', 'creation.waiting': 'A mensagem será enviada após a criação da árvore de trabalho', 'missing.title': 'A árvore de trabalho está indisponível', 'missing.unknown': 'A restauração está incompleta e não é possível inspecionar a branch {branch}. Corrija o erro e tente novamente ou continue no projeto', diff --git a/packages/experimental/client-ui-forge/src/client/mount.ts b/packages/experimental/client-ui-forge/src/client/mount.ts index 0561acb9db..95c90a1fd2 100644 --- a/packages/experimental/client-ui-forge/src/client/mount.ts +++ b/packages/experimental/client-ui-forge/src/client/mount.ts @@ -49,6 +49,7 @@ import { createNoticeSource, createPanelSource, createStreamSource, foldStates, type PanelSource, } from './source.ts' import { numberOf } from './status.ts' +import type { WorktreeRequestResult } from './WorktreeNameDialog.tsx' import { WorktreeProgress, type WorktreeProgressInjected } from './WorktreeProgress.tsx' import { WorktreeSettings } from './WorktreeSettings.tsx' import { WorktreeSettingsForm, type WorktreeSettings as WorktreeSettingsFields } from './worktree-settings-form.ts' @@ -388,6 +389,15 @@ function registerUi(ctx: Context): void { }, } } + /** Request a worktree; a refused branch name goes back to the naming dialog, any other failure to a toast. */ + const requestWorktree = async (sessionId: SessionId, from: string | null, name: string | null): Promise => { + const result = await ctx.remote.forgePanel.requestWorktree(sessionId, from, name) + if (result.ok) return 'accepted' + if (result.error.code === 'forgePanel/branch-exists') return 'branch-exists' + if (result.error.code === 'forgePanel/invalid-name') return 'invalid-name' + settled(result, 'toast.worktreeFailed', { 'forgePanel/session-started': 'toast.worktreeStarted' }) + return 'failed' + } const progressFace = (sessionId: SessionId): WorktreeProgressInjected => { const store = storesOf(sessionId) return { @@ -395,9 +405,10 @@ function registerUi(ctx: Context): void { stop: () => { void ctx.remote.forgePanel.stopCreation(sessionId).then(result => settled(result, 'toast.worktreeFailed')) }, - retry: () => { - void ctx.remote.forgePanel.retryWorktree(sessionId).then(result => settled(result, 'toast.worktreeFailed')) + retry: (fetch) => { + void ctx.remote.forgePanel.retryWorktree(sessionId, fetch).then(result => settled(result, 'toast.worktreeFailed')) }, + request: async (from, name) => await requestWorktree(sessionId, from, name), withdraw: () => { void ctx.remote.forgePanel.cancelWorktree(sessionId).then(result => settled(result, 'toast.worktreeFailed')) }, @@ -408,16 +419,13 @@ function registerUi(ctx: Context): void { } } const worktreeFace = (sessionId: SessionId): WorktreeToggleInjected => { - const worktreeCodes: Partial> = { 'forgePanel/session-started': 'toast.worktreeStarted' } const store = storesOf(sessionId) return { hooks: { panel: store.panel.hooks.panel }, - request: async from => settled(await ctx.remote.forgePanel.requestWorktree(sessionId, from), 'toast.worktreeFailed', worktreeCodes), - cancel: async () => settled(await ctx.remote.forgePanel.cancelWorktree(sessionId), 'toast.worktreeFailed', worktreeCodes), - branches: async () => { - const result = await ctx.remote.forgePanel.branches(sessionId) - return settled(result, 'toast.branchesFailed') && result.ok ? result.value : undefined - }, + request: async (from, name) => await requestWorktree(sessionId, from, name), + cancel: async () => settled(await ctx.remote.forgePanel.cancelWorktree(sessionId), 'toast.worktreeFailed', + { 'forgePanel/session-started': 'toast.worktreeStarted' }), + bases: (query, signal) => ctx.remote.forgePanel.worktreeBases(sessionId, query, signal), } } ctx.slots.inject('conversation.session.panel.section', function* () { diff --git a/packages/experimental/client-ui-forge/src/git.ts b/packages/experimental/client-ui-forge/src/git.ts index c8db71c7a9..076bde1f46 100644 --- a/packages/experimental/client-ui-forge/src/git.ts +++ b/packages/experimental/client-ui-forge/src/git.ts @@ -7,9 +7,10 @@ import type {} from '@deepseek-ai/dsh-sandbox-policy' import type { Session } from '@deepseek-ai/dsh-session' import type { SubprocessCollectedOutputs } from '@deepseek-ai/dsh-subprocess' import { deadline } from '@deepseek-ai/dsh-timeout' -import { baseBranches, parseName, parseRemotes, parseTopLevel } from './parse.ts' +import { LOCAL_REF_PREFIX } from './branch-name.ts' +import { parseName, parseRemotes, parseTopLevel } from './parse.ts' import type { GitRemote } from './parse.ts' -import type { ForgeBranches, ForgeCheckout } from './types.ts' +import type { ForgeCheckout } from './types.ts' /** Resolved Git executable and process limits. */ export interface GitConfig { @@ -128,36 +129,6 @@ export async function inspectCheckout( } } -/** - * List the local branches that can start a worktree of the checkout containing - * `directory`, using the Session's permissions as in {@link inspectCheckout}. - * @param ctx - context that provides `subprocess`, `sandbox`, and `sandboxPolicy`. - * @param config - executable and process limits. - * @param session - Session whose sandbox policy and execution world apply. - * @param directory - absolute directory inside the checkout. - * @param limit - most branch names to return. - * @param signal - cancellation of every command. - * @returns the checked-out branch and local branches, the checked-out one first and then most recently committed first. - * @throws when `directory` is not inside a checkout, or Git cannot run, fails, times out, or prints more than `maxOutputBytes`. - */ -export async function listBranches( - ctx: Context, - config: GitConfig, - session: Session, - directory: string, - limit: number, - signal: AbortSignal, -): Promise { - const [current, refs] = await together(signal, (signal) => { - const git = gitIn(ctx, config, session, directory, signal) - return [ - currentBranch(git), - git('for-each-ref', ['for-each-ref', '--sort=-committerdate', `--count=${limit}`, '--format=%(refname:lstrip=2)', 'refs/heads/']), - ] as const - }) - return { current, branches: baseBranches(current, refs.stdout, limit) } -} - /** A failed read cancels its siblings and returns only after every read has finished cleanup. */ async function together[]>( signal: AbortSignal, @@ -215,10 +186,14 @@ export function gitIn(ctx: Context, config: GitConfig, session: Session, directo runGit(ctx, config, policy, directory, name, args, signal, allowedExitCodes, configOverrides) } -/** Read the checked-out branch, including an unborn one; null when HEAD is detached. */ +/** + * Read the checked-out local branch, including an unborn one; null when HEAD is detached or names a ref outside + * `refs/heads/`. The full ref is read because the short form turns `main` into `heads/main` while a tag shares the name. + */ async function currentBranch(git: Git): Promise { - const head = await git('symbolic-ref', ['symbolic-ref', '--quiet', '--short', 'HEAD'], [0, 1]) - return head.exitCode === 0 ? parseName(head.stdout) : null + const head = await git('symbolic-ref', ['symbolic-ref', '--quiet', 'HEAD'], [0, 1]) + const ref = head.exitCode === 0 ? parseName(head.stdout) : null + return ref !== null && ref.startsWith(LOCAL_REF_PREFIX) ? ref.slice(LOCAL_REF_PREFIX.length) : null } /** Read the abbreviated commit HEAD names; null while the checked-out branch has no commit. */ diff --git a/packages/experimental/client-ui-forge/src/index.ts b/packages/experimental/client-ui-forge/src/index.ts index ebc09dcb61..cc2d4c9494 100644 --- a/packages/experimental/client-ui-forge/src/index.ts +++ b/packages/experimental/client-ui-forge/src/index.ts @@ -21,8 +21,9 @@ import type {} from '@deepseek-ai/dsh-session-query' import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' import { Remote, RemoteError, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' import { assertNever } from '@deepseek-ai/dsh-util-values' -import { gitIn, inspectCheckout, listBranches } from './git.ts' +import { gitIn, hasBranch, inspectCheckout } from './git.ts' import type { Inspection } from './git.ts' +import { branchNameProblem } from './branch-name.ts' import { parseDiff } from './diff.ts' import { aheadOf, BaseMissing, baseBranches, chosenForkPoint, CommitsMissing, CommitsNotLinear, DiffTooLarge, FilterConfigError, forkPoint, @@ -35,14 +36,15 @@ import { lensVersion } from './lens-version.ts' import { rangeStart } from './commit-range.ts' import { ATTRIBUTES_PATH, FileLayers } from './layers.ts' import { missingWorktree, SessionPanel } from './panel.ts' +import { BASE_REF_PREFIXES, parseWorktreeBases, remoteOrder, remoteRepository } from './parse.ts' import { PatchCache } from './patch-cache.ts' import { ReviewCache } from './review-cache.ts' import { ChangeRequestStates, changeRequestStatesDomain } from './states.ts' import type { PanelConfig } from './panel.ts' import type { - Config, ForgeBaseBranches, ForgeBranches, ForgeChangeRequestDiff, ForgeChangeRequestStatesFrame, ForgeCommitRange, ForgeDiffFile, + Config, ForgeBaseBranches, ForgeChangeRequestDiff, ForgeChangeRequestStatesFrame, ForgeCommitRange, ForgeDiffFile, ForgeExtensionState, ForgeLens, ForgeLensFrame, ForgeLensRequest, ForgeLocalCommits, ForgeLocalDiff, ForgeLocalScope, - ForgeMissingWorktree, ForgePanelState, ForgeSessionWorktree, ForgeWorktreeState, + ForgeMissingWorktree, ForgePanelState, ForgeSessionWorktree, ForgeWorktreeBases, ForgeWorktreeState, } from './types.ts' import { forgeWorktreeProjection, messageOf, within, WORKTREE_RECORD, WorktreeCreations } from './worktree.ts' import type { HeldWork } from './worktree.ts' @@ -56,11 +58,10 @@ declare module '@deepseek-ai/cordis' { } } -/** Panel limits plus the branch and commit listing limits, the worktree branch prefix, and the lens and annotation limits. */ +/** Panel limits and worktree branch prefix plus the branch and commit listing limits and the lens and annotation limits. */ type ControllerConfig = PanelConfig & { readonly maxBranches: number readonly maxCommits: number - readonly worktreePrefix: string readonly lensTimeoutMs: number readonly maxLensReadBytes: number readonly maxCachedLensBytes: number @@ -141,7 +142,8 @@ export class ForgePanelController extends TypertRemoteService { ] as const) { if (!Number.isSafeInteger(resolved[key]) || resolved[key] <= 0) throw new Error(`forge-panel: ${key} must be a positive integer`) } - if (!branchPrefix(resolved.worktreePrefix)) throw new Error('forge-panel: worktreePrefix must start a valid Git branch name') + // Generated names append hexadecimal digits, so the prefix followed by one digit must be a valid branch name. + if (branchNameProblem(`${resolved.worktreePrefix}0`) !== null) throw new Error('forge-panel: worktreePrefix must start a valid Git branch name') for (const key of ['testPaths', 'interfacePaths'] as const) { if (resolved[key].some(glob => glob.trim() === '')) throw new Error(`forge-panel: ${key} entries must not be empty`) } @@ -241,15 +243,24 @@ export class ForgePanelController extends TypertRemoteService { } /** - * List the local branches that can start a worktree of the Session's current checkout. - * @param session - Session whose current directory is listed. + * List the branches that can start a worktree of the Session's current checkout: the checked-out branch, each + * remote's default branch, other local branches, and each remote's other remote-tracking branches, remotes in the + * order the panel recognizes code hosts. + * @param session - Session whose checkout is read. + * @param query - text the branch names must contain, ignoring case; empty for every branch. * @param signal - request cancellation. - * @returns the checked-out branch and at most `maxBranches` local branches, the checked-out one first. - * @throws when the current directory is not inside a checkout or Git fails. + * @returns the branches, at most `maxBranches` local branches and `maxBranches` per remote, most recently committed first. + * @throws `forgePanel/not-a-checkout` outside a checkout; the Git error when Git fails or the listed refs exceed `maxDiffBytes`. */ @Remote - async branches(session: Session, signal: AbortSignal): Promise { - return await listBranches(this.home, this.config, session, this.home.workingDirectory.get(session), this.config.maxBranches, signal) + async worktreeBases(session: Session, query: string, signal: AbortSignal): Promise { + signal.throwIfAborted() + const inspection = await this.checkoutOf(session, signal) + // A search can match any branch, so every ref is listed; a repository's refs can far exceed other short Git output. + const git = gitIn(this.home, { ...this.config, maxOutputBytes: this.config.maxDiffBytes }, session, inspection.checkout.root, signal) + const refs = await git('worktree-bases', ['for-each-ref', '--sort=-committerdate', '--format=%(refname)%00%(symref)', ...BASE_REF_PREFIXES]) + return parseWorktreeBases(refs.stdout, inspection.checkout.branch, remoteOrder(inspection.upstream, inspection.remotes), query, + this.config.maxBranches, remote => remoteRepository(remote, url => this.home.forge.repositoryFromRemote(url))) } /** @@ -820,24 +831,34 @@ export class ForgePanelController extends TypertRemoteService { /** * Ask for a new worktree before the Session's first turn, replacing an open * request and forgetting a failed attempt. While the next message waits in - * the inbox, or else at the first step proposal, the panel creates a branch - * from `from`, or from HEAD of the current checkout when it is null, and - * enters its checkout. A message that already waits after a failed or - * stopped attempt keeps waiting for {@link ForgePanelController.retryWorktree}. + * the inbox, or else at the first step proposal, the panel creates the + * branch `name`, or a generated branch per attempt when it is null, from + * `from`, or from HEAD of the current checkout when it is null, and enters + * its checkout; a remote-tracking `from` is fetched first. A message that + * already waits after a failed or stopped attempt keeps waiting for + * {@link ForgePanelController.retryWorktree}. * @param session - Session without a started turn. - * @param from - local base branch, or null for HEAD. + * @param from - full name of a local or remote-tracking base branch, or null for HEAD. + * @param name - new branch name, or null to generate one per attempt. * @param signal - request cancellation. - * @throws `forgePanel/invalid-branch` when `from` is empty; `forgePanel/worktrees-unavailable` + * @throws `forgePanel/invalid-branch` when `from` is empty; `forgePanel/invalid-name` when `name` breaks + * a branch-name rule; `forgePanel/branch-exists` when the checkout has a local branch named `name`; + * `forgePanel/not-a-checkout` when a name is checked outside a checkout; `forgePanel/worktrees-unavailable` * without a worktree service; `forgePanel/session-started` after a turn started or the worktree was * created; `forgePanel/session-busy` while the worktree is being created. */ @Remote - async requestWorktree(session: Session, from: string | null, signal: AbortSignal): Promise { + async requestWorktree(session: Session, from: string | null, name: string | null, signal: AbortSignal): Promise { signal.throwIfAborted() if (from?.length === 0) throw new RemoteError('forgePanel/invalid-branch', 'The base branch name is empty', {}) this.editableWorktree(session) + if (name !== null) { + await this.checkBranchName(session, name, signal) + // The Session may have started or begun a creation while Git answered. + this.editableWorktree(session) + } this.creations.forget(session) - appendPluginRecord(session, WORKTREE_RECORD, { action: 'request', from }) + appendPluginRecord(session, WORKTREE_RECORD, { action: 'request', from, ...name === null ? {} : { name } }) this.creations.recheck(session) } @@ -873,16 +894,19 @@ export class ForgePanelController extends TypertRemoteService { } /** - * Make another attempt, with a new branch name, at the worktree a message - * of the Session waits for after a failed or stopped attempt. + * Make another attempt, on the requested branch name or a new generated + * one, at the worktree a message of the Session waits for after a failed or + * stopped attempt. * @param session - Session whose message waits. + * @param fetch - false skips fetching a remote-tracking base branch for this attempt, which then starts from the + * commit last fetched. * @param signal - request cancellation. * @throws `forgePanel/not-waiting` when no message waits or an attempt is running. */ @Remote - async retryWorktree(session: Session, signal: AbortSignal): Promise { + async retryWorktree(session: Session, fetch: boolean, signal: AbortSignal): Promise { signal.throwIfAborted() - if (!this.creations.retry(session)) { + if (!this.creations.retry(session, fetch)) { throw new RemoteError('forgePanel/not-waiting', 'No message waits for another attempt at the worktree', {}) } } @@ -1060,6 +1084,18 @@ export class ForgePanelController extends TypertRemoteService { return this.worktreeStates.stateOf(session) } + /** + * Refuse a new branch name that breaks a branch-name rule or names a local branch of the Session's checkout. The + * rules cover every name `git check-ref-format` refuses, which the worktree service runs again at creation. + */ + private async checkBranchName(session: Session, name: string, signal: AbortSignal): Promise { + if (branchNameProblem(name) !== null) throw new RemoteError('forgePanel/invalid-name', 'The new branch name is invalid', {}) + const root = (await this.checkoutOf(session, signal)).checkout.root + if (await hasBranch(this.home, this.config, session, root, name, signal)) { + throw new RemoteError('forgePanel/branch-exists', `A local branch named ${name} exists`, {}) + } + } + private editableWorktree(session: Session): ForgeWorktreeState { if (this.home.get('worktrees') === undefined) { throw new RemoteError('forgePanel/worktrees-unavailable', 'No worktree service is mounted', {}) @@ -1346,21 +1382,4 @@ function actionError(failure: ForgeActionFailure): RemoteError { return new RemoteError(code, failure.message, {}) } -/** - * Whether `prefix` followed by hexadecimal digits is a branch name that Git - * accepts: no leading `-` or `/`, no empty component, no component that - * starts with `.` or ends with `.lock`, and none of `..`, `@{`, whitespace, - * control characters, `~`, `^`, `:`, `?`, `*`, `[`, or `\`. - * @param prefix - configured worktree branch prefix. - * @returns whether every generated name passes `git check-ref-format --branch`. - */ -function branchPrefix(prefix: string): boolean { - const name = `${prefix}0` - if (name.startsWith('-') || name.includes('..') || name.includes('@{')) return false - for (const char of name) { - if (char <= ' ' || char === '\x7f' || '~^:?*[\\'.includes(char)) return false - } - return name.split('/').every(part => part.length > 0 && !part.startsWith('.') && !part.endsWith('.lock')) -} - export default ForgePanelController diff --git a/packages/experimental/client-ui-forge/src/local-diff.ts b/packages/experimental/client-ui-forge/src/local-diff.ts index 17c753643a..8568571bf6 100644 --- a/packages/experimental/client-ui-forge/src/local-diff.ts +++ b/packages/experimental/client-ui-forge/src/local-diff.ts @@ -17,6 +17,7 @@ import { gitIn, GitOutputTooLarge } from './git.ts' import type { Git, GitConfig, GitOutput, Inspection } from './git.ts' import { ATTRIBUTES_PATH } from './layers.ts' import type { FileLayers } from './layers.ts' +import { branchLabel } from './branch-name.ts' import { BASE_REF_PREFIXES, parseBaseBranches, parseName, remoteOrder } from './parse.ts' import type { ForgeCommitRange, ForgeLocalChanges, ForgeLocalCommits, ForgeLocalDiff, ForgeLocalScope, ForgeBaseBranches, ForgeSessionWorktree, @@ -114,7 +115,8 @@ const BINARY_PROBE = 8000 */ export async function forkPoint(git: Git, inspection: Inspection, created: ForgeSessionWorktree | null): Promise { if (created !== null && created.path === inspection.checkout.root) { - return { commit: created.baseCommit, label: created.from ?? created.baseCommit.slice(0, 7), worktree: true } + const label = created.from === null ? created.baseCommit.slice(0, 7) : branchLabel(created.from) + return { commit: created.baseCommit, label, worktree: true } } for (const remote of remoteOrder(inspection.upstream, inspection.remotes)) { const head = await git('remote-head', ['symbolic-ref', '--quiet', '--short', `refs/remotes/${remote.name}/HEAD`], [0, 1, 128]) diff --git a/packages/experimental/client-ui-forge/src/panel.ts b/packages/experimental/client-ui-forge/src/panel.ts index 6d4adc4ce0..30db0ee3d1 100644 --- a/packages/experimental/client-ui-forge/src/panel.ts +++ b/packages/experimental/client-ui-forge/src/panel.ts @@ -27,6 +27,8 @@ import type { WorktreeCreations } from './worktree.ts' export interface PanelConfig extends DiffConfig { /** Deadline in milliseconds for one provider sign-in probe. */ readonly readinessTimeoutMs: number + /** Prefix of generated worktree branch names, which a name the user types starts from. */ + readonly worktreePrefix: string } /** The checkout's upstream branch and the remote URL its change requests are looked up at. */ @@ -70,7 +72,7 @@ export class SessionPanel { /** * @param ctx - service context that provides the forge, Session, directory, and process services. - * @param config - Git limits and the sign-in probe deadline. + * @param config - Git limits, the sign-in probe deadline, and the worktree branch name prefix. * @param session - Session the panel describes. * @param worktreeStates - reads the `forgeWorktree` projection of the Session. * @param creations - reads the running creation and restoration, the last failed creation, and what a message of the @@ -229,6 +231,7 @@ export class SessionPanel { return { editable: this.ctx.get('worktrees') !== undefined && !state.locked && state.created === null, blocker: this.blocker, + namePrefix: this.config.worktreePrefix, request: state.request, created: state.created, creation: this.creations.of(this.session), diff --git a/packages/experimental/client-ui-forge/src/parse.ts b/packages/experimental/client-ui-forge/src/parse.ts index b163c40e4a..4041299795 100644 --- a/packages/experimental/client-ui-forge/src/parse.ts +++ b/packages/experimental/client-ui-forge/src/parse.ts @@ -1,6 +1,6 @@ /** Parsers for the porcelain output of the read-only Git commands the panel runs. */ -import type { ForgeBaseBranch } from './types.ts' +import type { ForgeBaseBranch, ForgeRemoteDefault, ForgeWorktreeBases } from './types.ts' /** One remote with the URLs `git remote -v` prints for it. */ export interface GitRemote { @@ -23,7 +23,7 @@ export function parseTopLevel(output: string): string { } /** - * Read the first line of a one-name output such as `git symbolic-ref --short HEAD`. + * Read the first line of a one-name output such as `git symbolic-ref --quiet HEAD`. * @param output - stdout of the command. * @returns the name, or null when the command printed none. */ @@ -67,16 +67,73 @@ export function parseBaseBranches( } /** - * Order worktree base branches: the checked-out branch first, then the other - * listed branches in listed order. + * Select the branches a new worktree can start from out of `git for-each-ref` output, keeping its order within + * each group: the checked-out branch, each remote's default branch, the other local branches, and the other + * remote-tracking branches of each remote. A remote's default branch is the branch its `refs/remotes//HEAD` + * names; remote-tracking branches of unconfigured remotes and other symbolic refs are left out. + * @param output - stdout of `git for-each-ref --format=%(refname)%00%(symref)` over {@link BASE_REF_PREFIXES}. * @param current - checked-out branch, or null when HEAD is detached. - * @param output - stdout of `git for-each-ref --format=%(refname:lstrip=2) refs/heads/`. - * @param limit - most names to return. - * @returns distinct branch names, at most `limit`. + * @param remotes - configured remotes in the order their groups take. + * @param query - text the names must contain, ignoring case; empty or blank for every branch. + * @param limit - most branches in the local group and in each remote's group. + * @param repositoryOf - the repository a remote's group names. + * @returns the branches, with remotes that have no listed branch left out. */ -export function baseBranches(current: string | null, output: string, limit: number): string[] { - const listed = output.split(/\r?\n/).filter(name => name.length > 0 && name !== current) - return (current === null ? listed : [current, ...listed]).slice(0, limit) +export function parseWorktreeBases( + output: string, + current: string | null, + remotes: readonly GitRemote[], + query: string, + limit: number, + repositoryOf: (remote: GitRemote) => string | null, +): ForgeWorktreeBases { + const [heads, tracking] = BASE_REF_PREFIXES + const needle = query.trim().toLowerCase() + const matches = (name: string): boolean => name.toLowerCase().includes(needle) + const listed: string[] = [] + const remoteHeads = new Map() + for (const line of output.split(/\r?\n/)) { + const [ref = '', symref = ''] = line.split('\0') + if (ref.length === 0) continue + if (symref.length === 0) { + listed.push(ref) + continue + } + const owner = ref.startsWith(tracking) ? upstreamBranch(ref.slice(tracking.length), remotes) : undefined + if (owner?.branch === 'HEAD') remoteHeads.set(owner.remote.name, symref) + } + const present = new Set(listed) + const defaultRefs = new Set() + const defaults: ForgeRemoteDefault[] = [] + for (const remote of remotes) { + const target = remoteHeads.get(remote.name) + if (target === undefined || !present.has(target) || !target.startsWith(`${tracking}${remote.name}/`)) continue + defaultRefs.add(target) + const name = target.slice(tracking.length) + if (matches(name)) defaults.push({ ref: target, name, remote: remote.name }) + } + const local: ForgeBaseBranch[] = [] + const groups = remotes.map(remote => ({ remote, branches: [] as ForgeBaseBranch[] })) + for (const ref of listed) { + if (ref.startsWith(heads)) { + const name = ref.slice(heads.length) + if (name !== current && local.length < limit && matches(name)) local.push({ ref, name }) + continue + } + if (!ref.startsWith(tracking) || defaultRefs.has(ref)) continue + const name = ref.slice(tracking.length) + const owner = upstreamBranch(name, remotes)?.remote + const group = groups.find(candidate => candidate.remote === owner) + if (group !== undefined && group.branches.length < limit && matches(name)) group.branches.push({ ref, name }) + } + const currentRef = `${heads}${current ?? ''}` + return { + current: current !== null && present.has(currentRef) && matches(current) ? { ref: currentRef, name: current } : null, + defaults, + local, + remotes: groups.filter(group => group.branches.length > 0) + .map(({ remote, branches }) => ({ name: remote.name, repository: repositoryOf(remote), branches })), + } } /** @@ -123,6 +180,25 @@ export function upstreamBranch( return remote === undefined ? undefined : { remote, branch: upstream.slice(remote.name.length + 1) } } +/** + * Name the repository a remote's group shows: `owner/name` of the first URL a provider recognizes, else the first URL + * without the user name and password a URL can carry as a token, since the name reaches the browser. + * @param remote - remote with its URLs, fetch URL first. + * @param recognize - the repository a provider recognizes from a URL, or undefined. + * @returns the name, or null for a remote without a URL. + */ +export function remoteRepository( + remote: GitRemote, + recognize: (url: string) => { readonly owner: string; readonly name: string } | undefined, +): string | null { + for (const url of remote.urls) { + const repository = recognize(url) + if (repository !== undefined) return `${repository.owner}/${repository.name}` + } + // A URL's user information ends at the last `@` before its path, query, or fragment. + return remote.urls[0]?.replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^/?#]*@/, '$1') ?? null +} + /** * Order remotes for code host recognition: the upstream's remote first, then * `origin`, then the rest in listed order. diff --git a/packages/experimental/client-ui-forge/src/types.ts b/packages/experimental/client-ui-forge/src/types.ts index a8b575a629..edf5da658d 100644 --- a/packages/experimental/client-ui-forge/src/types.ts +++ b/packages/experimental/client-ui-forge/src/types.ts @@ -34,7 +34,10 @@ export interface ForgeSessionWorktree { readonly path: string /** Branch created for the checkout. */ readonly branch: string - /** Requested base branch, or null when the checkout started from HEAD of the source checkout. */ + /** + * Requested base: the full name of a local or remote-tracking branch, a short branch name that earlier panels + * recorded, or null when the checkout started from HEAD of the source checkout. + */ readonly from: string | null /** Commit object name the branch started from. */ readonly baseCommit: string @@ -44,8 +47,11 @@ export interface ForgeSessionWorktree { /** Payload of the `plugin:client-ui-forge/worktree` record. */ export type WorktreeRecord = - /** Create a worktree before the Session's first step, starting from `from`, or from HEAD when it is null. */ - | { readonly action: 'request'; readonly from: string | null } + /** + * Create a worktree before the Session's first step, starting from `from`, or from HEAD when it is null, on the + * branch `name`, or on a generated branch name when `name` is absent. + */ + | { readonly action: 'request'; readonly from: string | null; readonly name?: string } /** Withdraw the open request. */ | { readonly action: 'cancel' } /** The requested worktree was created and became the Session's working directory. */ @@ -57,8 +63,13 @@ export type WorktreeRecord = /** One open worktree request. */ export interface ForgeWorktreeRequest { - /** Base branch, or null for HEAD of the source checkout. */ + /** + * Base: the full name of a local or remote-tracking branch, a short branch name that earlier panels recorded, or + * null for HEAD of the source checkout. A remote-tracking branch is fetched before each attempt that does not skip it. + */ readonly from: string | null + /** New branch name the user chose, which every attempt uses, or null for a generated name per attempt. */ + readonly name: string | null } /** Host-only state of the `forgeWorktree` projection. */ @@ -88,12 +99,17 @@ export type ForgeWorktreeBlocker = /** One running worktree creation. */ export interface ForgeWorktreeCreation { - /** Running step: `prepare` validates and creates the branch, then `checkout` writes the files. */ - readonly phase: 'prepare' | 'checkout' + /** + * Running step: `fetch` fetches a remote base branch, `prepare` validates and creates the branch, then + * `checkout` writes the files. + */ + readonly phase: 'fetch' | 'prepare' | 'checkout' /** Branch the attempt creates. */ readonly branch: string - /** Base branch, or null for HEAD. */ + /** Base as the request names it, or null for HEAD. */ readonly from: string | null + /** Whether the attempt fetches its remote base branch first. */ + readonly fetch: boolean /** * Whether a message waits for the creation before its turn starts. Only * such a creation can be stopped, after which the message keeps waiting; a @@ -112,12 +128,16 @@ export interface ForgeWorktreeRestoration { export interface ForgeWorktreeFailure { /** Branch the attempt created, or null when it failed before naming one. */ readonly branch: string | null - /** Base branch of the attempt, or null for HEAD. */ + /** Base of the attempt as the request names it, or null for HEAD. */ readonly from: string | null + /** Whether the attempt fetched, or tried to fetch, its remote base branch first. */ + readonly fetch: boolean /** Step that failed. */ - readonly phase: 'prepare' | 'checkout' + readonly phase: 'fetch' | 'prepare' | 'checkout' /** Failure text. */ readonly message: string + /** Whether the branch or the checkout directory of that name already existed, which another name avoids. */ + readonly exists: boolean } /** @@ -142,6 +162,8 @@ export interface ForgePanelWorktree { readonly editable: boolean /** Why the checkout cannot host a worktree, or null when it can, before the first inspection, and after a failed one. */ readonly blocker: ForgeWorktreeBlocker | null + /** Prefix of generated branch names, the Config `worktreePrefix`, which a name the user types starts from. */ + readonly namePrefix: string /** Open request, or null without one. */ readonly request: ForgeWorktreeRequest | null /** Created worktree, or null before creation. */ @@ -216,12 +238,35 @@ export interface ForgePanelState { readonly local: ForgeLocalChanges | null } -/** Local branches offered as the base of a new worktree. */ -export interface ForgeBranches { - /** Checked-out branch, or null when HEAD is detached. */ - readonly current: string | null - /** Local branch names, `current` first and then most recently committed first, at most `maxBranches`. */ - readonly branches: readonly string[] +/** Branches offered as the base of a new worktree whose names contain a query. */ +export interface ForgeWorktreeBases { + /** Checked-out branch, or null when HEAD is detached or its name does not contain the query. */ + readonly current: ForgeBaseBranch | null + /** Default branch of each remote that names one with `refs/remotes//HEAD`, in remote order. */ + readonly defaults: readonly ForgeRemoteDefault[] + /** Other local branches, most recently committed first, at most `maxBranches`. */ + readonly local: readonly ForgeBaseBranch[] + /** + * Remote-tracking branches of each configured remote in remote order: the remote the checked-out branch tracks, + * then `origin`, then the others as Git lists them. Remotes without a matching branch are left out. + */ + readonly remotes: readonly ForgeRemoteBranches[] +} + +/** A remote's default branch, which `refs/remotes//HEAD` names. */ +export interface ForgeRemoteDefault extends ForgeBaseBranch { + /** Remote the branch belongs to; it may contain `/`. */ + readonly remote: string +} + +/** Remote-tracking branches of one remote, without its default branch. */ +export interface ForgeRemoteBranches { + /** Remote name such as `origin`; it may contain `/`. */ + readonly name: string + /** `owner/name` of the repository a provider recognizes from the remote's URLs, else its fetch URL, or null without one. */ + readonly repository: string | null + /** Branches named `/`, most recently committed first, at most `maxBranches`. */ + readonly branches: readonly ForgeBaseBranch[] } /** A branch the `branch` scope can compare with. */ @@ -545,6 +590,10 @@ declare module '@deepseek-ai/dsh-typert-protocol' { 'forgePanel/worktrees-unavailable': Record /** The requested base branch name is empty. */ 'forgePanel/invalid-branch': Record + /** The requested new branch name breaks one of Git's branch-name rules, or the worktree service's refusal of a leading `-`. */ + 'forgePanel/invalid-name': Record + /** A local branch with the requested new branch name exists in the Session's checkout. */ + 'forgePanel/branch-exists': Record /** The Session has no created worktree to restore or leave. */ 'forgePanel/no-worktree': Record /** The Session's Agent is not loaded or has other work, so its checkout cannot change now. */ diff --git a/packages/experimental/client-ui-forge/src/worktree.ts b/packages/experimental/client-ui-forge/src/worktree.ts index 122a05efc5..5c8b83b254 100644 --- a/packages/experimental/client-ui-forge/src/worktree.ts +++ b/packages/experimental/client-ui-forge/src/worktree.ts @@ -11,9 +11,10 @@ import type { ProjectionDefinition, ProjectionHandle } from '@deepseek-ai/dsh-se import { assertNever } from '@deepseek-ai/dsh-util-values' import type {} from '@deepseek-ai/dsh-working-directory' import { z } from 'zod' +import { isRemoteRef } from './branch-name.ts' import type { - ForgeMissingWorktree, ForgeSessionWorktree, ForgeWorktreeCreation, ForgeWorktreeFailure, ForgeWorktreeRestoration, ForgeWorktreeState, - ForgeWorktreeWaiting, WorktreeRecord, + ForgeMissingWorktree, ForgeSessionWorktree, ForgeWorktreeCreation, ForgeWorktreeFailure, ForgeWorktreeRequest, ForgeWorktreeRestoration, + ForgeWorktreeState, ForgeWorktreeWaiting, WorktreeRecord, } from './types.ts' /** Plugin record type of worktree requests, withdrawals, and creations. */ @@ -30,7 +31,7 @@ const worktreeSchema: z.ZodType = z.object({ }).strict() const recordSchema: z.ZodType = z.discriminatedUnion('action', [ - z.object({ action: z.literal('request'), from: z.string().min(1).nullable() }).strict(), + z.object({ action: z.literal('request'), from: z.string().min(1).nullable(), name: z.string().min(1).exactOptional() }).strict(), z.object({ action: z.literal('cancel') }).strict(), z.object({ action: z.literal('created'), worktree: worktreeSchema }).strict(), z.object({ action: z.literal('restoring') }).strict(), @@ -38,7 +39,7 @@ const recordSchema: z.ZodType = z.discriminatedUnion('action', [ ]) const stateSchema: z.ZodType = z.object({ - request: z.object({ from: z.string().min(1).nullable() }).strict().nullable(), + request: z.object({ from: z.string().min(1).nullable(), name: z.string().min(1).nullable() }).strict().nullable(), created: worktreeSchema.nullable(), locked: z.boolean(), stepped: z.boolean(), @@ -59,7 +60,7 @@ const stateSchema: z.ZodType = z.object({ */ export const forgeWorktreeProjection = { key: 'forgeWorktree', - stateVersion: 5, + stateVersion: 6, stateSchema, init: header => ({ ...EMPTY, cwd: header.cwd ?? null }), apply, @@ -118,7 +119,7 @@ function applyRecord(state: ForgeWorktreeState, event: SessionEvent): ForgeWorkt const settled = state.created !== null switch (data.action) { case 'request': - return state.locked || settled ? state : { ...state, request: { from: data.from } } + return state.locked || settled ? state : { ...state, request: { from: data.from, name: data.name ?? null } } case 'cancel': return state.locked || settled || state.request === null ? state : { ...state, request: null } case 'created': @@ -134,6 +135,9 @@ function applyRecord(state: ForgeWorktreeState, event: SessionEvent): ForgeWorkt /** A failed attempt to create a requested worktree; `cause` holds the worktree service's error. */ export class CreationFailure extends Error { + /** Whether the branch or the checkout directory of that name already existed. */ + readonly exists: boolean + /** * @param branch - branch the attempt created. * @param phase - step that failed. @@ -143,21 +147,31 @@ export class CreationFailure extends Error { constructor(readonly branch: string, readonly phase: CreateWorktreePhase, readonly reason: string, cause: unknown) { super(`The requested worktree ${branch} could not be created`, { cause }) this.name = 'CreationFailure' + // The worktree service's failures are routed by name and code; a rebuilt error keeps both. + this.exists = cause instanceof Error && cause.name === 'WorktreeError' && 'code' in cause && cause.code === 'WORKTREE_ALREADY_EXISTS' } } /** * The failure a waiting message shows for an attempt. * @param error - what the attempt threw. - * @param from - base branch of the attempt, or null for HEAD. + * @param from - base of the attempt, or null for HEAD. + * @param fetch - whether the attempt fetched its remote base branch first. * @returns the failure. */ -function failureOf(error: unknown, from: string | null): ForgeWorktreeFailure { +function failureOf(error: unknown, from: string | null, fetch: boolean): ForgeWorktreeFailure { return error instanceof CreationFailure - ? { branch: error.branch, from, phase: error.phase, message: error.reason } - : { branch: null, from, phase: 'prepare', message: messageOf(error) } + ? { branch: error.branch, from, fetch, phase: error.phase, message: error.reason, exists: error.exists } + : { branch: null, from, fetch, phase: fetch ? 'fetch' : 'prepare', message: messageOf(error), exists: false } } +/** The next decision on a message that waits after a failed or stopped attempt. */ +type CreationDecision = + /** Make another attempt; `fetch` false skips fetching a remote base branch for it. */ + | { readonly kind: 'retry'; readonly fetch: boolean } + /** The request no longer asks for a worktree, so the message goes on. */ + | { readonly kind: 'recheck' } + /** Work on a Session's checkout that runs as maintenance of its Agent. */ export type HeldWork = (agent: Agent, signal: AbortSignal) => Promise @@ -167,7 +181,7 @@ interface CreationHold { /** Stops the running attempt. */ stop: AbortController | undefined /** The wait for the next decision: another attempt, or reading the request again. */ - next: PromiseWithResolvers<'retry' | 'recheck'> | undefined + next: PromiseWithResolvers | undefined } /** A message's wait for the restoration or leaving of the removed worktree the Session works in. */ @@ -182,8 +196,10 @@ interface RestorationHold { type Hold = CreationHold | RestorationHold /** - * Creates requested worktrees, one attempt with a new branch name per call, - * and holds the turn of a message while the Session's worktree is not ready. + * Creates requested worktrees, one attempt per call on the requested branch + * name or on a new generated one, fetching a remote-tracking base branch + * first unless the attempt skips it, and holds the turn of a message while + * the Session's worktree is not ready. * A hold is maintenance of the Session's Agent that starts while the message * enters the inbox, before the delivery wakes the Agent, so the Agent starts * the message's turn once the hold ends. A creation hold makes an attempt @@ -302,22 +318,27 @@ export class WorktreeCreations { /** * Make another attempt for the message that waits after a failed or stopped one. * @param session - Session whose message waits. + * @param fetch - false skips fetching a remote-tracking base branch for this attempt, which then starts from the + * commit last fetched. * @returns whether a waiting message without a running attempt took the decision. */ - retry(session: Session): boolean { + retry(session: Session, fetch: boolean): boolean { const hold = this.holds.get(session) if (hold?.kind !== 'creation' || hold.next === undefined) return false - hold.next.resolve('retry') + hold.next.resolve({ kind: 'retry', fetch }) return true } /** - * Read the request again after it changed; a withdrawn request lets the waiting message go on. + * Read the request again after it changed: a request that no longer asks for a worktree lets the waiting message + * go on, and a request that still does keeps it waiting for another attempt. * @param session - Session whose request changed. */ recheck(session: Session): void { const hold = this.holds.get(session) - if (hold?.kind === 'creation') hold.next?.resolve('recheck') + if (hold?.kind !== 'creation') return + const state = this.states.stateOf(session) + if (state.request === null || state.created !== null || state.locked) hold.next?.resolve({ kind: 'recheck' }) } /** @@ -395,32 +416,39 @@ export class WorktreeCreations { } /** - * Create a Session's requested worktree with a new branch name, enter it, and - * record it on the Session. The running creation is readable through - * {@link WorktreeCreations.of} until the record exists or the attempt fails. + * Create a Session's requested worktree on the requested branch name, or on a + * new generated one, enter it, and record it on the Session. The running + * creation is readable through {@link WorktreeCreations.of} until the record + * exists or the attempt fails. * @param agent - Agent of the Session. - * @param from - base branch, or null for HEAD of the current checkout. + * @param request - base, or null for HEAD of the current checkout, and branch name, or null to generate one. * @param signal - cancellation of the attempt. * @param held - whether a message waits for the creation before its turn starts. + * @param fetch - whether the attempt fetches its base first; true only for a remote-tracking base branch. * @returns the created worktree. * @throws {@link CreationFailure} when the attempt fails; the cancellation reason once `signal` aborts. */ - async create(agent: Agent, from: string | null, signal: AbortSignal, held: boolean): Promise { - return await this.run(signal, operation => this.createCheckout(agent, from, operation, held)) + async create(agent: Agent, request: ForgeWorktreeRequest, signal: AbortSignal, held: boolean, fetch: boolean): Promise { + return await this.run(signal, operation => this.createCheckout(agent, request, operation, held, fetch)) } - private async createCheckout(agent: Agent, from: string | null, signal: AbortSignal, held: boolean): Promise { + private async createCheckout( + agent: Agent, { from, name }: ForgeWorktreeRequest, signal: AbortSignal, held: boolean, fetch: boolean, + ): Promise { const worktrees = this.ctx.get('worktrees') if (worktrees === undefined) throw new Error('No worktree service is mounted') const session = agent.session - let status: ForgeWorktreeCreation = { phase: 'prepare', branch: generatedWorktreeName(this.prefix, session.id), from, held } + let status: ForgeWorktreeCreation = { + phase: fetch ? 'fetch' : 'prepare', branch: name ?? generatedWorktreeName(this.prefix, session.id), from, fetch, held, + } this.failures.delete(session) this.live.set(session, status) this.changed(session) try { let created: CreatedWorktree try { - created = await worktrees.create(agent, { name: status.branch, ...from === null ? {} : { from } }, signal, (phase) => { + const request = { name: status.branch, ...from === null ? {} : { from }, ...fetch ? { fetch } : {} } + created = await worktrees.create(agent, request, signal, (phase) => { status = { ...status, phase } this.live.set(session, status) this.changed(session) @@ -492,26 +520,28 @@ export class WorktreeCreations { */ private async runCreation(agent: Agent, hold: CreationHold, signal: AbortSignal): Promise { const session = agent.session + let skipFetch = false for (;;) { const state = this.states.stateOf(session) if (state.request === null || state.created !== null || state.locked) return const stop = new AbortController() hold.stop = stop + const fetch = !skipFetch && isRemoteRef(state.request.from) try { - await this.create(agent, state.request.from, AbortSignal.any([signal, stop.signal]), true) + await this.create(agent, state.request, AbortSignal.any([signal, stop.signal]), true, fetch) return } catch (error) { signal.throwIfAborted() if (stop.signal.aborted) this.failures.delete(session) - else this.failures.set(session, failureOf(error, state.request.from)) + else this.failures.set(session, failureOf(error, state.request.from, fetch)) this.changed(session) } finally { hold.stop = undefined } - while (await this.wait(hold, signal) !== 'retry') { - const current = this.states.stateOf(session) - if (current.request === null || current.created !== null || current.locked) return - } + const decision = await this.wait(hold, signal) + // A recheck decides only once the request no longer asks for a worktree. + if (decision.kind === 'recheck') return + skipFetch = !decision.fetch } } @@ -566,7 +596,7 @@ export class WorktreeCreations { private async preStep(agent: Agent, step: number, signal: AbortSignal, next: () => Promise): Promise { const state = this.states.stateOf(agent.session) if (step !== 1 || state.request === null || state.created !== null || state.stepped) return await next() - await this.create(agent, state.request.from, signal, false) + await this.create(agent, state.request, signal, false, isRemoteRef(state.request.from)) const decision = await next() if (decision.kind === 'reject' || decision.messages.length === 0) return decision const notices = agent.inbox.nextStep.filter(message => message.source.kind === 'working-directory') diff --git a/packages/experimental/client-ui-forge/tests/branch-name.host.spec.ts b/packages/experimental/client-ui-forge/tests/branch-name.host.spec.ts new file mode 100644 index 0000000000..f02f93e963 --- /dev/null +++ b/packages/experimental/client-ui-forge/tests/branch-name.host.spec.ts @@ -0,0 +1,76 @@ +/** Branch-name rules and branch labels shared by the Host and the Client. */ +import { execFileSync } from 'node:child_process' +import { describe, expect, it } from 'vitest' +import { branchLabel, branchNameProblem, isRemoteRef } from '../src/branch-name.ts' + +/** Whether Git accepts `name` as a new branch, as the worktree service checks it at creation. */ +function gitAccepts(name: string): boolean { + try { + execFileSync('git', ['check-ref-format', `refs/heads/${name}`], { stdio: 'ignore' }) + return true + } catch (error) { + void error // A nonzero exit is Git's refusal. + return false + } +} + +describe('branchNameProblem', () => { + it.each([ + ['', 'empty'], + ['fix login', 'space'], + ['fix\tlogin', 'space'], + ['fix\u007flogin', 'character'], + ['fix~1', 'character'], + ['fix^', 'character'], + ['a:b', 'character'], + ['a?b', 'character'], + ['a*b', 'character'], + ['a[b', 'character'], + ['a\\b', 'character'], + ['-fix', 'leading-dash'], + ['/fix', 'leading-slash'], + ['fix/', 'trailing-slash'], + ['fix//login', 'double-slash'], + ['fix..login', 'double-dot'], + ['fix.', 'trailing-dot'], + ['@', 'at'], + ['fix@{1}', 'at-brace'], + ['fix/.login', 'dot-segment'], + ['.fix', 'dot-segment'], + ['fix.lock/login', 'lock-segment'], + ['fix.lock', 'lock-segment'], + ] as const)('refuses %j as %s', (name, problem) => { + expect(branchNameProblem(name)).toBe(problem) + }) + + it.each(['fix-login', 'dsh-0a1b2c3d-9f3e', 'fix/login', 'a./b', 'a/@/b', 'é', 'HEAD'])('accepts %j', (name) => { + expect(branchNameProblem(name)).toBeNull() + }) + + it('refuses every name that Git refuses among these', () => { + for (const name of ['fix login', 'a..b', 'x@{y', 'a/.b', 'a/b.', 'aa.lock', 'fix//x', '/x', 'x/', 'a~b', 'a\\b', 'a[b']) { + expect(gitAccepts(name)).toBe(false) + expect(branchNameProblem(name)).not.toBeNull() + } + }) +}) + +describe('branchLabel', () => { + it('drops the prefix of a full local or remote-tracking branch name and keeps any other revision', () => { + expect(branchLabel('refs/heads/fix/login')).toBe('fix/login') + expect(branchLabel('refs/remotes/origin/main')).toBe('origin/main') + expect(branchLabel('main')).toBe('main') + expect(branchLabel('refs/heads/')).toBe('refs/heads/') + expect(branchLabel('refs/tags/v1')).toBe('refs/tags/v1') + }) +}) + +describe('isRemoteRef', () => { + it('recognizes the full name of a remote-tracking branch', () => { + expect(isRemoteRef('refs/remotes/origin/main')).toBe(true) + expect(isRemoteRef('refs/remotes/')).toBe(false) + expect(isRemoteRef('refs/heads/main')).toBe(false) + expect(isRemoteRef('origin/main')).toBe(false) + expect(isRemoteRef(null)).toBe(false) + }) +}) 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 f52d042a69..fa1a11d9c0 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,7 @@ // @vitest-environment jsdom /** One change request card: state glyph, title link, collapsed summary, read notices, and expanded details and actions. */ import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react' -import { afterEach, describe, expect, it, vi } from 'vitest' +import { afterEach, describe, expect, it, onTestFinished, 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' @@ -10,6 +10,7 @@ import css from '../src/client/Forge.module.css' import overview from '../src/client/ChangeRequestOverview.module.css' import type { ForgePanelChangeRequest } from '../src/types.ts' import { check, entry, snapshot, unserved } from './client-fixtures.client.ts' +import './fonts-dom.client.ts' afterEach(cleanup) @@ -19,7 +20,7 @@ const NOW = Date.parse('2026-10-09T12:00:00Z') const MINUS = '−' /** Render one card inside its list, with every action recorded unless `actions` replaces it. */ -function card(value: ForgePanelChangeRequest, options: { expanded?: boolean; actions?: Partial } = {}) { +function card(value: ForgePanelChangeRequest, options: { expanded?: boolean; actions?: Partial; t?: typeof t } = {}) { const openLink = vi.fn<(url: string) => void>() const copyLink = vi.fn<(url: string) => void>() const retry = vi.fn<() => void>() @@ -28,7 +29,8 @@ function card(value: ForgePanelChangeRequest, options: { expanded?: boolean; act const actions: ChangeRequestActions = { openLink, copyLink, retry, remove, ...options.actions } const view = render(
      - +
    , ) const item = view.container.querySelector('[data-forge-change]') @@ -134,6 +136,19 @@ describe('ChangeRequestCard head', () => { } }) + 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', () => { const b = card(entry(7, snapshot(7))) expect(b.item.hasAttribute('data-expanded')).toBe(false) @@ -189,6 +204,59 @@ describe('collapsed ChangeRequestCard', () => { 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']}`) + }) + 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']], diff --git a/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx b/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx index 9addbc324e..defc8a96d0 100644 --- a/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx @@ -224,6 +224,16 @@ function hostStream(frames: readonly F[], failure?: unknown): HostStream { } } +/** + * Whether the view shows its reading state: the reading status above file card placeholders, with the files menu naming + * no count. + */ +function reading(view: ReturnType): boolean { + return view.queryByRole('status')?.textContent === en['diff.loading'] + && view.container.querySelector('[data-forge-changes-skeleton]') !== null + && view.queryByRole('button', { name: en['diff.allFilesLoading'] }) !== null +} + /** Let the Remote reads the view awaits settle. */ async function settle(): Promise { await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)) }) @@ -576,9 +586,18 @@ describe('ChangesTab tooltips', () => { }) describe('ChangesTab local reads', () => { + it('draws the placeholders of a changed file in two columns only while sides are split', async () => { + const m = mount({ state: null }) + const columns = (): number => m.view.container.querySelectorAll('[data-forge-changes-skeleton] > :first-child > :last-child > *').length + expect(reading(m.view)).toBe(true) + expect(columns()).toBe(2) + act(() => { m.store.actions.toggledSplit(TAB) }) + expect(columns()).toBe(1) + }) + it('waits for the panel state, then reads the branch scope and draws its files', async () => { const m = mount({ state: null }) - expect(m.view.container.querySelector('[data-state="ongoing"]')).not.toBeNull() + expect(reading(m.view)).toBe(true) expect(m.view.queryByRole('button', { name: en['changes.local.create'] })).toBeNull() expect(m.view.container.querySelector('[data-forge-head]')?.textContent).toBe('HEAD') expect(m.faces.localDiff).not.toHaveBeenCalled() @@ -627,7 +646,7 @@ describe('ChangesTab local reads', () => { fireEvent.click(m.view.getByRole('button', { name: 'Branch' })) fireEvent.click(m.view.getByRole('menuitem', { name: 'Staged' })) expect(m.store.getSnapshot().byTab[TAB]?.scope).toBe('staged') - expect(m.view.container.querySelector('[data-state="ongoing"]')).not.toBeNull() + expect(reading(m.view)).toBe(true) expect(m.view.getByText('The index compared with HEAD')).toBeTruthy() expect(m.faces.localDiff).toHaveBeenLastCalledWith({ kind: 'staged' }, expect.any(AbortSignal)) await settle() @@ -858,7 +877,7 @@ describe('ChangesTab base branch', () => { fireEvent.click(m.view.getByRole('menuitem', { name: 'topic' })) expect(m.store.getSnapshot().byTab[TAB]?.base).toEqual(TOPIC) expect(m.faces.localDiff).toHaveBeenLastCalledWith({ kind: 'branch', base: TOPIC.ref, commits: null }, expect.any(AbortSignal)) - expect(m.view.container.querySelector('[data-state="ongoing"]')).not.toBeNull() + expect(reading(m.view)).toBe(true) await settle() expect(m.paths()).toHaveLength(6) @@ -1453,7 +1472,7 @@ describe('ChangesTab change requests', () => { const m = mount({ source, setup: (faces) => { faces.changeRequestDiff.mockResolvedValueOnce(REFUSED.staleHead) } }) await settle() expect(m.faces.changeRequestDiff).toHaveBeenCalledOnce() - expect(m.view.queryByRole('status')).toBeNull() + expect(reading(m.view)).toBe(true) expect(m.paths()).toEqual([]) // A later status with the same head reads again, as when the host's answers disagreed for a moment. @@ -1465,7 +1484,7 @@ describe('ChangesTab change requests', () => { act(() => { m.panel.set({ state: later(2, HEAD), disconnected: false }) }) await settle() expect(m.faces.changeRequestDiff).toHaveBeenCalledTimes(2) - expect(m.view.queryByRole('status')).toBeNull() + expect(reading(m.view)).toBe(true) act(() => { m.panel.set({ state: later(3, 'b'.repeat(40)), disconnected: false }) }) await settle() @@ -1520,7 +1539,7 @@ describe('ChangesTab change requests', () => { const m = mount({ source, state: ready({ changeRequests: [entry(7, null)] }) }) await settle() expect(m.faces.changeRequestDiff).not.toHaveBeenCalled() - expect(m.view.queryByRole('status')).toBeNull() + expect(reading(m.view)).toBe(true) act(() => { m.panel.set({ state: ready({ changeRequests: [entry(7, snapshot(7))] }), disconnected: false }) }) await settle() expect(m.faces.changeRequestDiff).toHaveBeenCalledOnce() diff --git a/packages/experimental/client-ui-forge/tests/client-fixtures.client.ts b/packages/experimental/client-ui-forge/tests/client-fixtures.client.ts index d2914b32e9..c7f42366f8 100644 --- a/packages/experimental/client-ui-forge/tests/client-fixtures.client.ts +++ b/packages/experimental/client-ui-forge/tests/client-fixtures.client.ts @@ -138,12 +138,12 @@ export function created(overrides: Partial = {}): ForgeSes /** Running creation of the branch `dsh/0a1b2c3d` from `main`, in its preparation step, that a message waits for. */ export function creation(overrides: Partial = {}): ForgeWorktreeCreation { - return { phase: 'prepare', branch: 'dsh/0a1b2c3d', from: 'main', held: true, ...overrides } + return { phase: 'prepare', branch: 'dsh/0a1b2c3d', from: 'main', fetch: false, held: true, ...overrides } } /** Failed attempt to create the branch `dsh/0a1b2c3d` from `main`, in its preparation step. */ export function failure(overrides: Partial = {}): ForgeWorktreeFailure { - return { branch: 'dsh/0a1b2c3d', from: 'main', phase: 'prepare', message: 'fatal: invalid reference: main', ...overrides } + return { branch: 'dsh/0a1b2c3d', from: 'main', fetch: false, phase: 'prepare', message: 'fatal: invalid reference: main', exists: false, ...overrides } } /** @@ -152,8 +152,8 @@ export function failure(overrides: Partial = {}): ForgeWor */ export function worktree(overrides: Partial = {}): ForgePanelWorktree { return { - editable: false, blocker: null, request: null, created: null, creation: null, failure: null, missing: null, restoration: null, - waiting: null, ...overrides, + editable: false, blocker: null, namePrefix: 'dsh-', request: null, created: null, creation: null, failure: null, missing: null, + restoration: null, waiting: null, ...overrides, } } @@ -171,9 +171,12 @@ export function ready(overrides: Partial = {}, checkoutOverride } } -/** Ready panel state of a Session that waits to start in a worktree requested from `from`, with further worktree facts. */ -export function requested(from: string | null = 'main', overrides: Partial = {}): ForgePanelState { - return ready({ worktree: worktree({ editable: true, request: { from }, ...overrides }) }) +/** + * Ready panel state of a Session that waits to start in a worktree requested from `from` on the branch `name`, or on a + * generated branch for null, with further worktree facts. + */ +export function requested(from: string | null = 'main', overrides: Partial = {}, name: string | null = null): ForgePanelState { + return ready({ worktree: worktree({ editable: true, request: { from, name }, ...overrides }) }) } /** 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 cd8bf7f3b3..08d741cb0f 100644 --- a/packages/experimental/client-ui-forge/tests/controller.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/controller.host.spec.ts @@ -62,8 +62,8 @@ const ready = (state: ForgePanelState): boolean => state.checkout.state === 'rea /** Worktree facts of a Session without a worktree service, request, or creation, whose checkout can host a worktree. */ const UNAVAILABLE = { - editable: false, blocker: null, request: null, created: null, creation: null, failure: null, missing: null, restoration: null, - waiting: null, + editable: false, blocker: null, namePrefix: 'dsh-', request: null, created: null, creation: null, failure: null, missing: null, + restoration: null, waiting: null, } /** Matches a generated branch name with the default prefix. */ @@ -106,7 +106,7 @@ function worktreeState(opened: Bench, session: Session = opened.session): ForgeW * @returns the created worktree. */ async function startInWorktree(opened: Bench, from: string | null = null): Promise { - await opened.ctx.forgePanel.requestWorktree(opened.session, from, signal) + await opened.ctx.forgePanel.requestWorktree(opened.session, from, null, signal) sendPrompt(opened.agent, 'first') await opened.agent.whenIdle() const created = worktreeState(opened)?.created ?? null @@ -964,9 +964,9 @@ describe('forgePanel worktree requests', () => { const follower = reader(opened) await follower.until(ready) - await opened.ctx.forgePanel.requestWorktree(opened.session, null, signal) + await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal) const requested = await follower.next(() => true) - await opened.ctx.forgePanel.requestWorktree(opened.session, 'main', signal) + await opened.ctx.forgePanel.requestWorktree(opened.session, 'main', null, signal) const replaced = await follower.next(() => true) await opened.ctx.forgePanel.cancelWorktree(opened.session, signal) const withdrawn = await follower.next(() => true) @@ -975,8 +975,8 @@ describe('forgePanel worktree requests', () => { const editable = { ...UNAVAILABLE, editable: true } expect(follower.states[0]?.worktree).toEqual(editable) - expect(requested.worktree).toEqual({ ...editable, request: { from: null } }) - expect(replaced.worktree).toEqual({ ...editable, request: { from: 'main' } }) + expect(requested.worktree).toEqual({ ...editable, request: { from: null, name: null } }) + expect(replaced.worktree).toEqual({ ...editable, request: { from: 'main', name: null } }) expect(withdrawn.worktree).toEqual(editable) expect(started.worktree).toEqual(UNAVAILABLE) expect(opened.records).toEqual([{ action: 'request', from: null }, { action: 'request', from: 'main' }, { action: 'cancel' }]) @@ -987,7 +987,7 @@ describe('forgePanel worktree requests', () => { const opened = await open(repo, {}, { worktrees: true }) await opened.ctx.forgePanel.cancelWorktree(opened.session, signal) - await opened.ctx.forgePanel.requestWorktree(opened.session, 'main', signal) + await opened.ctx.forgePanel.requestWorktree(opened.session, 'main', null, signal) await opened.ctx.forgePanel.cancelWorktree(opened.session, signal) await opened.ctx.forgePanel.cancelWorktree(opened.session, signal) @@ -997,10 +997,10 @@ describe('forgePanel worktree requests', () => { it('refuses worktree changes after the first turn starts', async () => { const { repo } = await project() const opened = await open(repo, {}, { worktrees: true }) - await opened.ctx.forgePanel.requestWorktree(opened.session, null, signal) + await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal) startTurn(opened.session, 1) - await expect(opened.ctx.forgePanel.requestWorktree(opened.session, 'main', signal)).rejects.toMatchObject({ code: 'forgePanel/session-started' }) + await expect(opened.ctx.forgePanel.requestWorktree(opened.session, 'main', null, signal)).rejects.toMatchObject({ code: 'forgePanel/session-started' }) await expect(opened.ctx.forgePanel.cancelWorktree(opened.session, signal)).rejects.toMatchObject({ code: 'forgePanel/session-started' }) expect(opened.records).toEqual([{ action: 'request', from: null }]) }) @@ -1008,12 +1008,12 @@ describe('forgePanel worktree requests', () => { it('refuses worktree changes once the worktree exists, before any turn starts', async () => { const { repo } = await project() const opened = await open(repo, {}, { worktrees: true }) - await opened.ctx.forgePanel.requestWorktree(opened.session, null, signal) + await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal) await proposeStep(opened.ctx, opened.agent, { turn: 1, step: 1, messages: [prompt('go')], decision: { kind: 'reject' } }) - await expect(opened.ctx.forgePanel.requestWorktree(opened.session, 'main', signal)).rejects.toMatchObject({ code: 'forgePanel/session-started' }) + await expect(opened.ctx.forgePanel.requestWorktree(opened.session, 'main', null, signal)).rejects.toMatchObject({ code: 'forgePanel/session-started' }) await expect(opened.ctx.forgePanel.cancelWorktree(opened.session, signal)).rejects.toMatchObject({ code: 'forgePanel/session-started' }) - expect(worktreeState(opened)).toMatchObject({ request: { from: null }, locked: false, stepped: false, restoring: false }) + expect(worktreeState(opened)).toMatchObject({ request: { from: null, name: null }, locked: false, stepped: false, restoring: false }) expect(opened.records).toEqual([{ action: 'request', from: null }]) expect(opened.created).toHaveLength(1) }) @@ -1032,13 +1032,13 @@ describe('forgePanel worktree requests', () => { const { repo } = await project() const opened = await open(repo) - await expect(opened.ctx.forgePanel.requestWorktree(opened.session, null, signal)).rejects.toMatchObject({ code: 'forgePanel/worktrees-unavailable' }) + await expect(opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal)).rejects.toMatchObject({ code: 'forgePanel/worktrees-unavailable' }) expect(opened.records).toEqual([]) appendPluginRecord(opened.session, WORKTREE_RECORD, { action: 'request', from: null }) const follower = reader(opened) sendPrompt(opened.agent, 'first') const failed = await follower.until(state => state.worktree.failure !== null) - expect(failed.worktree.failure).toEqual({ branch: null, from: null, phase: 'prepare', message: 'No worktree service is mounted' }) + expect(failed.worktree.failure).toEqual({ branch: null, from: null, fetch: false, phase: 'prepare', message: 'No worktree service is mounted', exists: false }) // Withdrawing needs no worktree service, so the waiting message can go on. await opened.ctx.forgePanel.cancelWorktree(opened.session, signal) await opened.agent.whenIdle() @@ -1056,7 +1056,7 @@ describe('forgePanel worktree requests', () => { const { repo } = await project() const opened = await open(repo, {}, { worktrees: true }) - await expect(opened.ctx.forgePanel.requestWorktree(opened.session, '', signal)).rejects.toMatchObject({ code: 'forgePanel/invalid-branch' }) + await expect(opened.ctx.forgePanel.requestWorktree(opened.session, '', null, signal)).rejects.toMatchObject({ code: 'forgePanel/invalid-branch' }) expect(opened.records).toEqual([]) }) @@ -1065,7 +1065,7 @@ describe('forgePanel worktree requests', () => { const opened = await open(repo, {}, { worktrees: true }) const follower = reader(opened) await follower.until(ready) - await opened.ctx.forgePanel.requestWorktree(opened.session, null, signal) + await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal) startTurn(opened.session, 1) await proposeStep(opened.ctx, opened.agent, { turn: 1, step: 1, messages: [prompt('Fix the bug')] }) @@ -1080,7 +1080,7 @@ describe('forgePanel worktree requests', () => { repository: demo, readiness: { state: 'ready', message: null, signIn: null }, changeRequests: [], - worktree: { ...UNAVAILABLE, request: { from: null }, created }, + worktree: { ...UNAVAILABLE, request: { from: null, name: null }, created }, local: { base: created?.baseCommit.slice(0, 7), files: [] }, }) expect(opened.provider.probes).toEqual(['fake.test']) @@ -1105,7 +1105,7 @@ describe('forgePanel worktree requests', () => { const worktree: ForgeSessionWorktree = { path: join(repo, 'elsewhere'), branch: 'dsh/0a1b2c3d', from: null, baseCommit: 'c'.repeat(40), repositoryRoot: repo } appendPluginRecord(opened.session, WORKTREE_RECORD, { action: 'created', worktree }) - await expect(pending).resolves.toMatchObject({ worktree: { ...UNAVAILABLE, request: { from: null }, created: worktree } }) + await expect(pending).resolves.toMatchObject({ worktree: { ...UNAVAILABLE, request: { from: null, name: null }, created: worktree } }) const later = follower.next(() => true) let republished = false @@ -1117,13 +1117,105 @@ describe('forgePanel worktree requests', () => { }) }) +describe('forgePanel named and remote-based worktrees', () => { + /** Whether the checkout was inspected; a clone of a local path names no code host, so no sign-in state follows. */ + const inspected = (state: ForgePanelState): boolean => state.checkout.state === 'ready' + + /** A clone of a fresh repository, which then gains a commit the clone has not fetched. */ + async function behind(): Promise<{ repo: string; fetched: string }> { + const { path, remove } = await scratch('dsh-forge-remote-') + cleanups.push(remove) + const upstream = await repository(path, 'upstream') + const repo = join(path, 'clone') + await git(path, 'clone', '--quiet', upstream, repo) + return { repo, fetched: await commitAt(upstream, 'remote.txt', '2026-02-01T00:00:00Z') } + } + + it('records a request that names its branch, and refuses an invalid or taken name without recording it', async () => { + const { repo } = await project() + const opened = await open(repo, {}, { worktrees: true }) + await git(repo, 'branch', 'taken') + + await expect(opened.ctx.forgePanel.requestWorktree(opened.session, 'refs/heads/main', 'fix/', signal)) + .rejects.toMatchObject({ code: 'forgePanel/invalid-name' }) + await expect(opened.ctx.forgePanel.requestWorktree(opened.session, 'refs/heads/main', 'taken', signal)) + .rejects.toMatchObject({ code: 'forgePanel/branch-exists' }) + expect(opened.records).toEqual([]) + await opened.ctx.forgePanel.requestWorktree(opened.session, 'refs/heads/main', 'fix/login', signal) + + expect(opened.records).toEqual([{ action: 'request', from: 'refs/heads/main', name: 'fix/login' }]) + expect(worktreeState(opened).request).toEqual({ from: 'refs/heads/main', name: 'fix/login' }) + }) + + it('refuses a named request outside a checkout', async () => { + const opened = await open(await plain(), {}, { worktrees: true }) + + await expect(opened.ctx.forgePanel.requestWorktree(opened.session, null, 'fix/login', signal)).rejects.toMatchObject({ code: 'forgePanel/not-a-checkout' }) + }) + + it('says a named attempt found its branch taken, and creates the worktree once the request names another branch', 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, 'fix/login', signal) + // The branch appears after the request was checked, as when another checkout creates it meanwhile. + await git(repo, 'branch', 'fix/login') + + sendPrompt(opened.agent, 'first') + const failed = await follower.until(state => state.worktree.failure !== null && state.worktree.creation === null) + await opened.ctx.forgePanel.requestWorktree(opened.session, null, 'fix/login-2', signal) + await opened.ctx.forgePanel.retryWorktree(opened.session, true, signal) + await opened.agent.whenIdle() + + expect(failed.worktree.failure).toMatchObject({ branch: 'fix/login', phase: 'prepare', exists: true, fetch: false }) + expect(worktreeState(opened).created).toMatchObject({ branch: 'fix/login-2', from: null }) + expect(queued(opened)).toEqual(['first']) + }) + + it('fetches a remote base branch before creating the worktree from the fetched commit', async () => { + const { repo, fetched } = await behind() + const opened = await open(repo, {}, { worktrees: true }) + const follower = reader(opened) + await follower.until(inspected) + await opened.ctx.forgePanel.requestWorktree(opened.session, 'refs/remotes/origin/main', null, signal) + + sendPrompt(opened.agent, 'first') + const fetching = await follower.until(state => state.worktree.creation?.phase === 'fetch') + await opened.agent.whenIdle() + + expect(fetching.worktree.creation).toMatchObject({ from: 'refs/remotes/origin/main', fetch: true, held: true }) + expect(worktreeState(opened).created).toMatchObject({ from: 'refs/remotes/origin/main', baseCommit: fetched }) + }) + + it('keeps the message waiting after a failed fetch, and starts from the last fetched commit when asked to skip the fetch', async () => { + const { repo } = await behind() + const last = await git(repo, 'rev-parse', 'refs/remotes/origin/main') + await git(repo, 'remote', 'set-url', 'origin', join(repo, 'missing.git')) + const opened = await open(repo, {}, { worktrees: true }) + const follower = reader(opened) + await follower.until(inspected) + await opened.ctx.forgePanel.requestWorktree(opened.session, 'refs/remotes/origin/main', null, signal) + + sendPrompt(opened.agent, 'first') + const failed = await follower.until(state => state.worktree.failure !== null && state.worktree.creation === null) + await opened.ctx.forgePanel.retryWorktree(opened.session, false, signal) + const retrying = await follower.next(state => state.worktree.creation !== null) + await opened.agent.whenIdle() + + expect(failed.worktree.failure).toMatchObject({ phase: 'fetch', fetch: true, exists: false, from: 'refs/remotes/origin/main' }) + expect(retrying.worktree.creation).toMatchObject({ phase: 'prepare', fetch: false }) + expect(worktreeState(opened).created).toMatchObject({ baseCommit: last }) + }) +}) + describe('forgePanel worktree creation while a message waits', () => { it('creates the requested worktree as Agent maintenance while the first message waits in the inbox, showing each step, then starts its turn', 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, signal) + await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal) const preparing = hold(opened.sandbox, 'check-ref-format') const checkingOut = hold(opened.sandbox, 'reset') @@ -1140,11 +1232,11 @@ describe('forgePanel worktree creation while a message waits', () => { const moved = await follower.until(state => state.directory === created?.path && state.checkout.state === 'ready' && state.worktree.waiting === null) const branch = created?.branch ?? '' - const running = { branch, from: null, held: true } - const waiting = { ...UNAVAILABLE, editable: true, request: { from: null }, waiting: 'creation' } + const running = { branch, from: null, fetch: false, held: true } + const waiting = { ...UNAVAILABLE, editable: true, request: { from: null, name: null }, waiting: 'creation' } expect(prepare.worktree).toEqual({ ...waiting, creation: { ...running, phase: 'prepare' } }) expect(checkout.worktree).toEqual({ ...waiting, creation: { ...running, phase: 'checkout' } }) - expect(moved.worktree).toEqual({ ...UNAVAILABLE, request: { from: null }, created }) + expect(moved.worktree).toEqual({ ...UNAVAILABLE, request: { from: null, name: null }, created }) expect(moved.checkout).toEqual({ state: 'ready', checkout: { root: created?.path, branch, linked: true, commit: COMMIT } }) expect(created).toEqual({ path: join(repo, '.agents', 'worktrees', ...branch.split('/')), @@ -1168,19 +1260,19 @@ describe('forgePanel worktree creation while a message waits', () => { const opened = await open(repo, {}, { worktrees: true }) const follower = reader(opened) await follower.until(ready) - await opened.ctx.forgePanel.requestWorktree(opened.session, 'later', signal) + await opened.ctx.forgePanel.requestWorktree(opened.session, 'later', null, signal) sendPrompt(opened.agent, 'first') const failed = await follower.until(state => state.worktree.failure !== null && state.worktree.creation === null) expect(opened.agent.wakes).toBe(0) await git(repo, 'branch', 'later') - await opened.ctx.forgePanel.retryWorktree(opened.session, signal) + await opened.ctx.forgePanel.retryWorktree(opened.session, true, signal) const retrying = await follower.next(state => state.worktree.creation !== null) await opened.agent.whenIdle() expect(failed.worktree).toEqual({ - ...UNAVAILABLE, editable: true, request: { from: 'later' }, waiting: 'creation', - failure: { branch: GENERATED_BRANCH, from: 'later', phase: 'prepare', message: MISSING_BASE }, + ...UNAVAILABLE, editable: true, request: { from: 'later', name: null }, waiting: 'creation', + failure: { branch: GENERATED_BRANCH, from: 'later', fetch: false, phase: 'prepare', message: MISSING_BASE, exists: false }, }) expect(retrying.worktree.failure).toBeNull() const created = worktreeState(opened)?.created ?? null @@ -1197,20 +1289,20 @@ describe('forgePanel worktree creation while a message waits', () => { const opened = await open(repo, {}, { worktrees: true }) const follower = reader(opened) await follower.until(ready) - await opened.ctx.forgePanel.requestWorktree(opened.session, 'later', signal) + await opened.ctx.forgePanel.requestWorktree(opened.session, 'later', null, signal) sendPrompt(opened.agent, 'first') await follower.until(state => state.worktree.failure !== null) - await opened.ctx.forgePanel.requestWorktree(opened.session, 'gone', signal) + await opened.ctx.forgePanel.requestWorktree(opened.session, 'gone', null, signal) const changed = await follower.next(state => state.worktree.request?.from === 'gone') - await opened.ctx.forgePanel.retryWorktree(opened.session, signal) + await opened.ctx.forgePanel.retryWorktree(opened.session, true, signal) const failedAgain = await follower.next(state => state.worktree.failure !== null) const withdrawal = follower.next(state => state.worktree.request === null && state.worktree.waiting === null) await opened.ctx.forgePanel.cancelWorktree(opened.session, signal) await opened.agent.whenIdle() const withdrawn = await withdrawal - expect(changed.worktree).toEqual({ ...UNAVAILABLE, editable: true, request: { from: 'gone' }, waiting: 'creation' }) + expect(changed.worktree).toEqual({ ...UNAVAILABLE, editable: true, request: { from: 'gone', name: null }, waiting: 'creation' }) expect(failedAgain.worktree.failure).toMatchObject({ from: 'gone' }) expect(withdrawn.worktree).toEqual({ ...UNAVAILABLE, editable: true }) expect(opened.agent.wakes).toBe(1) @@ -1225,7 +1317,7 @@ describe('forgePanel worktree creation while a message waits', () => { const opened = await open(repo, {}, { worktrees: true }) const follower = reader(opened) await follower.until(ready) - await opened.ctx.forgePanel.requestWorktree(opened.session, null, signal) + await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal) await opened.ctx.forgePanel.stopCreation(opened.session, signal) const held = hold(opened.sandbox, 'check-ref-format') @@ -1236,10 +1328,10 @@ describe('forgePanel worktree creation while a message waits', () => { held.release() const stopped = await stopping const before = { wakes: opened.agent.wakes, records: [...opened.records], cwd: opened.ctx.workingDirectory.get(opened.session) } - await opened.ctx.forgePanel.retryWorktree(opened.session, signal) + await opened.ctx.forgePanel.retryWorktree(opened.session, true, signal) await opened.agent.whenIdle() - expect(stopped.worktree).toEqual({ ...UNAVAILABLE, editable: true, request: { from: null }, waiting: 'creation' }) + expect(stopped.worktree).toEqual({ ...UNAVAILABLE, editable: true, request: { from: null, name: null }, waiting: 'creation' }) expect(before).toEqual({ wakes: 0, records: [{ action: 'request', from: null }], cwd: repo }) expect(worktreeState(opened)?.created).toMatchObject({ from: null, repositoryRoot: repo }) expect(opened.agent.wakes).toBe(1) @@ -1250,14 +1342,14 @@ describe('forgePanel worktree creation while a message waits', () => { const opened = await open(repo, {}, { worktrees: true }) const follower = reader(opened) await follower.until(ready) - await opened.ctx.forgePanel.requestWorktree(opened.session, 'later', signal) + await opened.ctx.forgePanel.requestWorktree(opened.session, 'later', null, signal) sendPrompt(opened.agent, 'first') await follower.until(state => state.worktree.failure !== null) await git(repo, 'branch', 'later') // Both decisions arrive before the wait resumes, so the next attempt reads the withdrawn request. await Promise.all([ - opened.ctx.forgePanel.retryWorktree(opened.session, signal), + opened.ctx.forgePanel.retryWorktree(opened.session, true, signal), opened.ctx.forgePanel.cancelWorktree(opened.session, signal), ]) await opened.agent.whenIdle() @@ -1270,13 +1362,13 @@ describe('forgePanel worktree creation while a message waits', () => { it('refuses another attempt while no message waits or an attempt runs', async () => { const { repo } = await project() const opened = await open(repo, {}, { worktrees: true }) - await expect(opened.ctx.forgePanel.retryWorktree(opened.session, signal)).rejects.toMatchObject({ code: 'forgePanel/not-waiting' }) - await opened.ctx.forgePanel.requestWorktree(opened.session, null, signal) + await expect(opened.ctx.forgePanel.retryWorktree(opened.session, true, signal)).rejects.toMatchObject({ code: 'forgePanel/not-waiting' }) + await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal) const held = hold(opened.sandbox, 'check-ref-format') sendPrompt(opened.agent, 'first') await held.reached - await expect(opened.ctx.forgePanel.retryWorktree(opened.session, signal)).rejects.toMatchObject({ code: 'forgePanel/not-waiting' }) + await expect(opened.ctx.forgePanel.retryWorktree(opened.session, true, signal)).rejects.toMatchObject({ code: 'forgePanel/not-waiting' }) held.release() await opened.agent.whenIdle() @@ -1289,7 +1381,7 @@ describe('forgePanel worktree creation while a message waits', () => { const opened = await open(repo, {}, { worktrees: true }) const follower = reader(opened) await follower.until(ready) - await opened.ctx.forgePanel.requestWorktree(opened.session, 'later', signal) + await opened.ctx.forgePanel.requestWorktree(opened.session, 'later', null, signal) sendPrompt(opened.agent, 'first') await follower.until(state => state.worktree.failure !== null) @@ -1298,16 +1390,16 @@ describe('forgePanel worktree creation while a message waits', () => { await opened.agent.whenIdle() const ended = await ending - expect(ended.worktree).toEqual({ ...UNAVAILABLE, editable: true, request: { from: 'later' } }) + expect(ended.worktree).toEqual({ ...UNAVAILABLE, editable: true, request: { from: 'later', name: null } }) expect(opened.agent.wakes).toBe(0) expect(queued(opened)).toEqual([]) - expect(worktreeState(opened)).toMatchObject({ request: { from: 'later' }, created: null }) + expect(worktreeState(opened)).toMatchObject({ request: { from: 'later', name: null }, created: null }) }) it('lets the waiting message go on when the panel stops', async () => { const { repo } = await project() const opened = await open(repo, {}, { worktrees: true }) - await opened.ctx.forgePanel.requestWorktree(opened.session, 'later', signal) + await opened.ctx.forgePanel.requestWorktree(opened.session, 'later', null, signal) sendPrompt(opened.agent, 'first') await vi.waitFor(() => { expect(() => opened.agent.runMaintenance(() => Promise.resolve())).toThrow('already has active work') }) @@ -1316,13 +1408,13 @@ describe('forgePanel worktree creation while a message waits', () => { expect(opened.agent.wakes).toBe(1) expect(queued(opened)).toEqual(['first']) - expect(worktreeState(opened)).toMatchObject({ request: { from: 'later' }, created: null }) + expect(worktreeState(opened)).toMatchObject({ request: { from: 'later', name: null }, created: null }) }) it('holds one wait for every message that arrives during it', async () => { const { repo } = await project() const opened = await open(repo, {}, { worktrees: true }) - await opened.ctx.forgePanel.requestWorktree(opened.session, null, signal) + await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal) const held = hold(opened.sandbox, 'check-ref-format') sendPrompt(opened.agent, 'first') @@ -1342,7 +1434,7 @@ describe('forgePanel worktree creation while a message waits', () => { const opened = await open(repo, {}, { worktrees: true }) const follower = reader(opened) await follower.until(ready) - await opened.ctx.forgePanel.requestWorktree(opened.session, null, signal) + await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal) await follower.until(state => state.worktree.request !== null) const release = occupy(opened) @@ -1351,16 +1443,16 @@ describe('forgePanel worktree creation while a message waits', () => { const busy = follower.states.at(-1) await release() - expect(busy?.worktree).toEqual({ ...UNAVAILABLE, editable: true, request: { from: null } }) + expect(busy?.worktree).toEqual({ ...UNAVAILABLE, editable: true, request: { from: null, name: null } }) expect(opened.agent.wakes).toBe(1) - expect(worktreeState(opened)).toMatchObject({ request: { from: null }, created: null }) + expect(worktreeState(opened)).toMatchObject({ request: { from: null, name: null }, created: null }) expect(await branches(repo)).toEqual(['main']) }) it('lets a message go on without a wait once the first turn started, leaving the worktree to the first step', async () => { const { repo } = await project() const opened = await open(repo, {}, { worktrees: true }) - await opened.ctx.forgePanel.requestWorktree(opened.session, null, signal) + await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal) startTurn(opened.session, 1) sendPrompt(opened.agent, 'steer') @@ -1368,7 +1460,7 @@ describe('forgePanel worktree creation while a message waits', () => { expect(opened.agent.wakes).toBe(1) expect(queued(opened)).toEqual(['steer']) - expect(worktreeState(opened)).toMatchObject({ request: { from: null }, created: null, locked: true }) + expect(worktreeState(opened)).toMatchObject({ request: { from: null, name: null }, created: null, locked: true }) expect(await branches(repo)).toEqual(['main']) }) }) @@ -1377,13 +1469,13 @@ describe('forgePanel worktree requests during a creation', () => { it('refuses to change or withdraw the request while the worktree is being created, so the creation is recorded', async () => { const { repo } = await project() const opened = await open(repo, {}, { worktrees: true }) - await opened.ctx.forgePanel.requestWorktree(opened.session, null, signal) + await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal) const held = hold(opened.sandbox, 'check-ref-format') sendPrompt(opened.agent, 'first') await held.reached await expect(opened.ctx.forgePanel.cancelWorktree(opened.session, signal)).rejects.toMatchObject({ code: 'forgePanel/session-busy' }) - await expect(opened.ctx.forgePanel.requestWorktree(opened.session, 'main', signal)) + await expect(opened.ctx.forgePanel.requestWorktree(opened.session, 'main', null, signal)) .rejects.toMatchObject({ code: 'forgePanel/session-busy' }) held.release() await opened.agent.whenIdle() @@ -1425,11 +1517,11 @@ describe('forgePanel removed worktrees', () => { await opened.agent.whenIdle() const restored = await restoration - expect(missing.worktree).toEqual({ ...UNAVAILABLE, request: { from: null }, created, missing: { branchExists: true }, waiting: 'restoration' }) + expect(missing.worktree).toEqual({ ...UNAVAILABLE, request: { from: null, name: null }, created, missing: { branchExists: true }, waiting: 'restoration' }) expect(preparing.worktree).toMatchObject({ missing: { branchExists: true }, restoration: { phase: 'prepare' }, waiting: 'restoration' }) expect(checkingOut.worktree.restoration).toEqual({ phase: 'checkout' }) expect(restored).toMatchObject({ directory: created.path, checkout: { state: 'ready', checkout: { root: created.path, branch: created.branch } } }) - expect(restored.worktree).toEqual({ ...UNAVAILABLE, request: { from: null }, created }) + expect(restored.worktree).toEqual({ ...UNAVAILABLE, request: { from: null, name: null }, created }) expect(await git(created.path, 'rev-parse', 'HEAD')).toBe(tip) expect(await readFile(join(created.path, 'later.txt'), 'utf8')).toBe('later.txt\n') expect(opened.ctx.workingDirectory.get(opened.session)).toBe(created.path) @@ -1458,7 +1550,7 @@ describe('forgePanel removed worktrees', () => { await opened.agent.whenIdle() const restored = await restoration - expect(gone.worktree).toEqual({ ...UNAVAILABLE, request: { from: null }, created, missing: { branchExists: false }, waiting: 'restoration' }) + expect(gone.worktree).toEqual({ ...UNAVAILABLE, request: { from: null, name: null }, created, missing: { branchExists: false }, waiting: 'restoration' }) expect(await git(repo, 'rev-parse', created.branch)).toBe(created.baseCommit) expect(restored.checkout).toEqual({ state: 'ready', checkout: { root: created.path, branch: created.branch, linked: true, commit: COMMIT } }) await expect(access(join(created.path, 'later.txt'))).rejects.toMatchObject({ code: 'ENOENT' }) @@ -1677,7 +1769,7 @@ describe('forgePanel leaving a worktree', () => { expect(opened.agent.inbox.nextStep).toEqual([notice(repo)]) expect(queued(opened)).toEqual(['next']) expect(moved.checkout).toEqual({ state: 'ready', checkout: { root: repo, branch: 'main', linked: false, commit: COMMIT } }) - expect(moved.worktree).toEqual({ ...UNAVAILABLE, request: { from: null }, created }) + expect(moved.worktree).toEqual({ ...UNAVAILABLE, request: { from: null, name: null }, created }) expect(await branches(repo)).toEqual([created.branch, 'main']) }) @@ -1991,23 +2083,37 @@ describe('forgePanel actions', () => { expect(opened.provider.actions).toEqual([]) }) - it('lists the base branches of the Session\'s current checkout, at most maxBranches', async () => { + it('lists the bases of a new worktree: the checked-out branch, remote defaults, local branches, and each remote, at most maxBranches each', async () => { const { repo } = await project() + await withDefaultBranch(repo) + await git(repo, 'remote', 'add', 'fork', '/srv/fork.git') await commitAt(repo, 'main.txt', '2026-03-01T00:00:00Z') await git(repo, 'checkout', '-b', 'older') await commitAt(repo, 'older.txt', '2026-01-01T00:00:00Z') + await git(repo, 'update-ref', 'refs/remotes/origin/topic', 'HEAD') + await git(repo, 'update-ref', 'refs/remotes/fork/idea', 'HEAD') await git(repo, 'checkout', '-b', 'newer', 'main') await commitAt(repo, 'newer.txt', '2026-02-01T00:00:00Z') - const opened = await open(repo, { maxBranches: 2 }) + const opened = await open(repo, { maxBranches: 1 }) - await expect(opened.ctx.forgePanel.branches(opened.session, signal)).resolves.toEqual({ current: 'newer', branches: ['newer', 'main'] }) + await expect(opened.ctx.forgePanel.worktreeBases(opened.session, '', signal)).resolves.toEqual({ + current: { ref: 'refs/heads/newer', name: 'newer' }, + defaults: [{ ref: 'refs/remotes/origin/main', name: 'origin/main', remote: 'origin' }], + local: [{ ref: 'refs/heads/main', name: 'main' }], + remotes: [ + { name: 'origin', repository: 'octo/demo', branches: [{ ref: 'refs/remotes/origin/topic', name: 'origin/topic' }] }, + { name: 'fork', repository: '/srv/fork.git', branches: [{ ref: 'refs/remotes/fork/idea', name: 'fork/idea' }] }, + ], + }) + await expect(opened.ctx.forgePanel.worktreeBases(opened.session, 'IDEA', signal)).resolves.toEqual({ + current: null, defaults: [], local: [], remotes: [{ name: 'fork', repository: '/srv/fork.git', branches: [{ ref: 'refs/remotes/fork/idea', name: 'fork/idea' }] }], + }) }) - it('refuses to list branches outside a checkout', async () => { + it('refuses to list worktree bases outside a checkout', async () => { const opened = await open(await plain()) - await expect(opened.ctx.forgePanel.branches(opened.session, signal)) - .rejects.toThrow(/^git (symbolic-ref|for-each-ref) failed \(128\): fatal: not a git repository/) + await expect(opened.ctx.forgePanel.worktreeBases(opened.session, '', signal)).rejects.toMatchObject({ code: 'forgePanel/not-a-checkout' }) }) it('checks the caller signal before every action', async () => { @@ -2025,8 +2131,8 @@ describe('forgePanel actions', () => { await expect(opened.ctx.forgePanel.changeRequestText(opened.session, pullUrl(1), 'a'.repeat(40), 'x', controller.signal)).rejects.toThrow('closed') await expect(opened.ctx.forgePanel.markReady(opened.session, pullUrl(1), controller.signal)).rejects.toThrow('closed') await expect(opened.ctx.forgePanel.merge(opened.session, pullUrl(1), 'merge', 'a'.repeat(40), controller.signal)).rejects.toThrow('closed') - await expect(opened.ctx.forgePanel.branches(opened.session, controller.signal)).rejects.toThrow('closed') - await expect(opened.ctx.forgePanel.requestWorktree(opened.session, null, controller.signal)).rejects.toThrow('closed') + await expect(opened.ctx.forgePanel.worktreeBases(opened.session, '', controller.signal)).rejects.toThrow('closed') + await expect(opened.ctx.forgePanel.requestWorktree(opened.session, null, null, controller.signal)).rejects.toThrow('closed') await expect(opened.ctx.forgePanel.cancelWorktree(opened.session, controller.signal)).rejects.toThrow('closed') await expect(opened.ctx.forgePanel.stopCreation(opened.session, controller.signal)).rejects.toThrow('closed') await expect(opened.ctx.forgePanel.restoreWorktree(opened.session, controller.signal)).rejects.toThrow('closed') @@ -2039,7 +2145,7 @@ describe('forgePanel lifecycle', () => { it('removes its Remote, worktree projection, and inbox and pre-step listeners when stopped, and folds the recorded request again after a restart', async () => { const { repo } = await project() const opened = await open(repo, {}, { worktrees: true }) - await opened.ctx.forgePanel.requestWorktree(opened.session, null, signal) + await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal) const proposed = prompt('go') const row = opened.ctx.sessionProjections.checkpoint(opened.session).forgeWorktree @@ -2057,7 +2163,7 @@ describe('forgePanel lifecycle', () => { await opened.ctx.plugin(ForgePanelController, {}) expect(opened.ctx.sessionProjections.checkpoint(opened.session).forgeWorktree?.val) - .toEqual({ request: { from: null }, created: null, locked: false, stepped: false, cwd: repo, restoring: false }) + .toEqual({ request: { from: null, name: null }, created: null, locked: false, stepped: false, cwd: repo, restoring: false }) }) }) @@ -2142,7 +2248,7 @@ describe('worktree recovery and unload', () => { const opened = await open(repo, {}, { worktrees: true }) const created = kind !== 'creation' ? await startInWorktree(opened) : undefined if (created !== undefined) await rm(created.path, { recursive: true, force: true }) - else await opened.ctx.forgePanel.requestWorktree(opened.session, null, signal) + else await opened.ctx.forgePanel.requestWorktree(opened.session, null, null, signal) const entered: PromiseWithResolvers = Promise.withResolvers() const released: PromiseWithResolvers = Promise.withResolvers() let cancellation: AbortSignal | undefined diff --git a/packages/experimental/client-ui-forge/tests/git.host.spec.ts b/packages/experimental/client-ui-forge/tests/git.host.spec.ts index b956f0b858..8225d0edf3 100644 --- a/packages/experimental/client-ui-forge/tests/git.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/git.host.spec.ts @@ -5,7 +5,7 @@ import { Context } from '@deepseek-ai/cordis' import { SandboxUnavailableError } from '@deepseek-ai/dsh-sandbox' import LocalSandbox from '@deepseek-ai/dsh-sandbox-local' import { setSandboxMode } from '@deepseek-ai/dsh-sandbox-policy' -import { hasBranch, inspectCheckout, listBranches } from '../src/git.ts' +import { hasBranch, inspectCheckout } from '../src/git.ts' import type { GitConfig } from '../src/git.ts' import { commitAt, git, gitContext, plainSession, repository, sandboxRecord, scratch, script } from './harness.ts' import type { SandboxRecord } from './harness.ts' @@ -67,10 +67,9 @@ describe('Session permissions for Git inspection', () => { const beforeStat = await stat(index) await expect(inspectCheckout(ctx, CONFIG, current, repo, live())).resolves.toMatchObject({ checkout: { branch: 'main' } }) - await expect(listBranches(ctx, CONFIG, current, repo, 50, live())).resolves.toEqual({ current: 'main', branches: ['main'] }) await expect(hasBranch(ctx, CONFIG, current, repo, 'main', live())).resolves.toBe(true) - expect(record.calls).toHaveLength(mode === 'danger-full-access' ? 0 : 10) + expect(record.calls).toHaveLength(mode === 'danger-full-access' ? 0 : 8) expect(record.calls.every(call => call.policy.mode === mode)).toBe(true) expect(await readFile(index)).toEqual(before) expect((await stat(index)).mtimeMs).toBe(beforeStat.mtimeMs) @@ -128,7 +127,7 @@ describe('inspectCheckout', () => { 'rev-parse --path-format=absolute --git-dir', 'rev-parse --short HEAD', 'rev-parse --show-toplevel', - 'symbolic-ref --quiet --short HEAD', + 'symbolic-ref --quiet HEAD', ]) for (const call of record.calls) { expect(call.policy).toMatchObject({ mode: 'workspace-write', workspaceRoot: repo }) @@ -174,6 +173,19 @@ describe('inspectCheckout', () => { }) }) + it('names the checked-out branch while a tag shares its name, and no branch while HEAD names another ref', async () => { + const root = await directory() + const repo = await repository(root) + await git(repo, 'tag', 'main') + const ctx = await context(sandboxRecord(), repo) + + // `git symbolic-ref --short HEAD` prints `heads/main` here. + expect((await inspectCheckout(ctx, CONFIG, session(repo), repo, live()))?.checkout.branch).toBe('main') + await git(repo, 'update-ref', 'refs/remotes/origin/main', 'HEAD') + await git(repo, 'symbolic-ref', 'HEAD', 'refs/remotes/origin/main') + expect((await inspectCheckout(ctx, CONFIG, session(repo), repo, live()))?.checkout.branch).toBeNull() + }) + it('stops when the caller aborts', async () => { const root = await directory() const ctx = await context(sandboxRecord(), root) @@ -243,7 +255,7 @@ describe.skipIf(!posix)('inspectCheckout with a stand-in Git', () => { ` *--git-common-dir*) echo "${alias}/.git" ;;`, ` *--git-dir*) echo "${alias}/.git" ;;`, ' *"rev-parse --short"*) echo 0a1b2c3 ;;', - ' *symbolic-ref*) echo main ;;', + ' *symbolic-ref*) echo refs/heads/main ;;', ' *--abbrev-ref*) echo origin/main ;;', 'esac', ].join('\n')) @@ -307,79 +319,6 @@ describe.skipIf(!posix)('inspectCheckout with a stand-in Git', () => { }) }) -describe('listBranches', () => { - it('lists the checked-out branch first, then local branches by latest commit, with two read-only commands', async () => { - const root = await directory() - const repo = await branched(root) - const record = sandboxRecord() - const ctx = await context(record, repo) - - await expect(listBranches(ctx, CONFIG, session(repo), repo, 50, live())).resolves.toEqual({ - current: 'main', branches: ['main', 'newer', 'older'], - }) - expect(commands(record)).toEqual([ - 'for-each-ref --sort=-committerdate --count=50 --format=%(refname:lstrip=2) refs/heads/', - 'symbolic-ref --quiet --short HEAD', - ]) - for (const call of record.calls) { - expect(call.policy).toMatchObject({ mode: 'workspace-write', workspaceRoot: repo }) - expect(call.argv.slice(1, 1 + GIT_PREFIX.length)).toEqual(GIT_PREFIX) - } - }) - - it('keeps the checked-out branch first when the limit cuts it from the listing', async () => { - const root = await directory() - const repo = await branched(root) - await git(repo, 'checkout', 'older') - const ctx = await context(sandboxRecord(), repo) - - await expect(listBranches(ctx, CONFIG, session(repo), repo, 2, live())).resolves.toEqual({ current: 'older', branches: ['older', 'main'] }) - await expect(listBranches(ctx, CONFIG, session(repo), repo, 1, live())).resolves.toEqual({ current: 'older', branches: ['older'] }) - }) - - it('lists the branches of a detached HEAD without a current one, and an unborn branch alone', async () => { - const root = await directory() - const repo = await branched(root) - await git(repo, 'checkout', '--detach', 'main') - await git(root, 'init', '-b', 'main', 'empty') - const ctx = await context(sandboxRecord(), root) - - await expect(listBranches(ctx, CONFIG, session(root), repo, 2, live())).resolves.toEqual({ current: null, branches: ['main', 'newer'] }) - await expect(listBranches(ctx, CONFIG, session(root), join(root, 'empty'), 50, live())).resolves.toEqual({ current: 'main', branches: ['main'] }) - }) - - it('fails outside a checkout', async () => { - const root = await directory() - const ctx = await context(sandboxRecord(), root) - - await expect(listBranches(ctx, CONFIG, session(root), root, 50, live())) - .rejects.toThrow(/^git (symbolic-ref|for-each-ref) failed \(128\): fatal: not a git repository/) - }) - - it.skipIf(!posix)('names a failing branch listing', async () => { - const root = await directory() - const fake = await script(join(root, 'git'), [ - 'case "$*" in', - ' *for-each-ref*) echo "fatal: bad ref" >&2; exit 2 ;;', - ' *symbolic-ref*) echo main ;;', - 'esac', - ].join('\n')) - const ctx = await context(sandboxRecord(), root) - - await expect(listBranches(ctx, { ...CONFIG, gitCommand: fake }, session(root), root, 50, live())) - .rejects.toThrow('git for-each-ref failed (2): fatal: bad ref') - }) - - it('stops when the caller aborts', async () => { - const root = await directory() - const ctx = await context(sandboxRecord(), root) - const controller = new AbortController() - controller.abort(new Error('closed')) - - await expect(listBranches(ctx, CONFIG, session(root), root, 50, controller.signal)).rejects.toThrow('closed') - }) -}) - describe('hasBranch', () => { it('reports whether a local branch exists with one read-only command per question', async () => { const root = await directory() @@ -445,7 +384,7 @@ const sandboxUsable = await (async () => { })() describe.skipIf(!sandboxUsable)('Git inspection under the local sandbox', () => { - it('reads a checkout and lists its branches under read-only confinement without writing its index', async () => { + it('reads a checkout under read-only confinement without writing its index', async () => { const root = await directory() const repo = await repository(root) await writeFile(join(repo, 'tracked.txt'), 'changed\n') @@ -460,9 +399,8 @@ describe.skipIf(!sandboxUsable)('Git inspection under the local sandbox', () => checkout: { root: repo, branch: 'main', linked: false, commit: await git(repo, 'rev-parse', '--short', 'HEAD') }, commonDir: join(repo, '.git'), upstream: null, remotes: [], }) - await expect(listBranches(ctx, CONFIG, readOnly, repo, 50, live())).resolves.toEqual({ current: 'main', branches: ['main'] }) - expect(confine).toHaveBeenCalledTimes(9) + expect(confine).toHaveBeenCalledTimes(7) expect(confine.mock.calls.every(call => call[1].mode === 'read-only')).toBe(true) expect((await stat(index)).mtimeMs).toBe(before.mtimeMs) await expect(access(join(repo, '.git', 'index.lock'))).rejects.toThrow() @@ -471,7 +409,7 @@ describe.skipIf(!sandboxUsable)('Git inspection under the local sandbox', () => describe('parallel inspection cleanup', () => { - it.each(['checkout', 'branches'] as const)('cancels and joins sibling reads when %s inspection fails', async (kind) => { + it('cancels and joins sibling reads when checkout inspection fails', async () => { const root = await directory() const repo = await repository(root) const ctx = await context(sandboxRecord(), repo) @@ -480,8 +418,8 @@ describe('parallel inspection cleanup', () => { const original = ctx.sandbox.confine.bind(ctx.sandbox) let sibling: AbortSignal | undefined const failure = new Error('inspection failed') - const heldArg = kind === 'checkout' ? '--git-common-dir' : 'symbolic-ref' - const failedArg = kind === 'checkout' ? 'remote' : 'for-each-ref' + const heldArg = '--git-common-dir' + const failedArg = 'remote' const probe = vi.spyOn(ctx.sandbox, 'confine').mockImplementation(async (argv, policy, signal) => { if (argv.includes(heldArg)) { sibling = signal @@ -492,9 +430,7 @@ describe('parallel inspection cleanup', () => { return original(argv, policy, signal) }) let settled = false - const operation = (kind === 'checkout' - ? inspectCheckout(ctx, CONFIG, session(repo), repo, live()) - : listBranches(ctx, CONFIG, session(repo), repo, 50, live())) + const operation = inspectCheckout(ctx, CONFIG, session(repo), repo, live()) .then(() => { settled = true; return undefined }, (error: unknown) => { settled = true; return error }) try { await entered.promise diff --git a/packages/experimental/client-ui-forge/tests/mount.client.spec.ts b/packages/experimental/client-ui-forge/tests/mount.client.spec.ts index 04d66b7c75..fabc4f46de 100644 --- a/packages/experimental/client-ui-forge/tests/mount.client.spec.ts +++ b/packages/experimental/client-ui-forge/tests/mount.client.spec.ts @@ -43,9 +43,9 @@ import type { WorktreeSettingsInjected, WorktreeSettings as WorktreeSettingsFiel import { WorktreeToggle, type WorktreeToggleInjected } from '../src/client/WorktreeToggle.tsx' import type { WorktreeCleanup } from '@deepseek-ai/dsh-experimental-worktree/types' import type { - ForgeBaseBranches, ForgeBranches, ForgeChangeRequestDiff, ForgeChangeRequestStatesFrame, ForgeExtensionState, ForgeLensFrame, + ForgeBaseBranches, ForgeChangeRequestDiff, ForgeChangeRequestStatesFrame, ForgeExtensionState, ForgeLensFrame, ForgeLensRequest, - ForgeCommitRange, ForgeLocalCommits, ForgeLocalDiff, ForgeLocalScope, ForgePanelState, + ForgeCommitRange, ForgeLocalCommits, ForgeLocalDiff, ForgeLocalScope, ForgePanelState, ForgeWorktreeBases, } from '../src/types.ts' import { entry, listState, ready, snapshot, unserved } from './client-fixtures.client.ts' import { brandString } from '@deepseek-ai/dsh-brand' @@ -53,7 +53,7 @@ import { brandString } from '@deepseek-ai/dsh-brand' const REMOTE: TypertRemoteContribution = { package: '@deepseek-ai/dsh-experimental-client-ui-forge', descriptors: [] } const S1 = brandString('s1') const S2 = brandString('s2') -const BRANCHES: ForgeBranches = { current: 'main', branches: ['main', 'release'] } +const BASES: ForgeWorktreeBases = { current: { ref: 'refs/heads/main', name: 'main' }, defaults: [], local: [], remotes: [] } const LOCAL: ForgeLocalDiff = { base: 'origin/main', files: [], omitted: 0 } const CHANGE: ForgeChangeRequestDiff = { headSha: 'a'.repeat(40), files: [], localAhead: null, fileUrls: {} } const COMMITS: ForgeCommitList = { headSha: 'a'.repeat(40), commits: [], truncated: false } @@ -98,6 +98,8 @@ const REFUSED = { busy: { ok: false, error: new RemoteError('forgePanel/session-busy', 'busy', {}) }, restore: { ok: false, error: new RemoteError('forgePanel/restore-failed', 'fatal: \'/work/repo-dsh\' already exists', {}) }, failed: { ok: false, error: new RemoteError('gateway/bad-request', 'failed', {}) }, + exists: { ok: false, error: new RemoteError('forgePanel/branch-exists', 'taken', {}) }, + invalidName: { ok: false, error: new RemoteError('forgePanel/invalid-name', 'invalid', {}) }, stale: { ok: false, error: new RemoteError('forgePanel/stale-head', 'Head branch was modified', {}) }, refused: { ok: false, error: new RemoteError('forgePanel/action-failed', 'Pull Request is not mergeable', {}) }, unknown: { ok: false, error: new RemoteError('forgePanel/action-unknown', 'Something went wrong', {}) }, @@ -128,7 +130,7 @@ function isAttentionFace(value: Record): value is Record): value is Record & WorktreeToggleInjected { - return typeof value.request === 'function' && typeof value.branches === 'function' + return typeof value.request === 'function' && typeof value.bases === 'function' } function isProgressFace(value: Record): value is Record & WorktreeProgressInjected { @@ -204,13 +206,14 @@ async function base() { ): Read => ({ ok: true, value: null })), setFileViewed: vi.fn(async (_sessionId: SessionId, _url: string, _request: ForgeViewedRequest): Promise> => OK), refresh: vi.fn(async (_sessionId: SessionId): Promise> => OK), - requestWorktree: vi.fn(async (_sessionId: SessionId, _from: string | null): Promise> => OK), + requestWorktree: vi.fn(async (_sessionId: SessionId, _from: string | null, _name: string | null): Promise> => OK), cancelWorktree: vi.fn(async (_sessionId: SessionId): Promise> => OK), stopCreation: vi.fn(async (_sessionId: SessionId): Promise> => OK), - retryWorktree: vi.fn(async (_sessionId: SessionId): Promise> => OK), + retryWorktree: vi.fn(async (_sessionId: SessionId, _fetch: boolean): Promise> => OK), restoreWorktree: vi.fn(async (_sessionId: SessionId): Promise> => OK), continueInProject: vi.fn(async (_sessionId: SessionId): Promise> => OK), - branches: vi.fn(async (_sessionId: SessionId): Promise> => ({ ok: true, value: BRANCHES })), + worktreeBases: vi.fn(async (_sessionId: SessionId, _query: string, _signal?: AbortSignal): Read => + ({ ok: true, value: BASES })), localDiff: vi.fn(async (_sessionId: SessionId, _scope: ForgeLocalScope, _signal?: AbortSignal): Read => ({ ok: true, value: LOCAL })), localText: vi.fn(async (_sessionId: SessionId, _scope: ForgeLocalScope, _path: string): Read => ({ ok: true, value: 'a\n' })), @@ -854,10 +857,10 @@ describe('mountForgePanel worktree actions', () => { it('requests and withdraws a worktree through the Remote', async () => { const f = await fixture() const option = f.worktree(S1) - expect(await option.request('release')).toBe(true) - expect(await option.request(null)).toBe(true) + expect(await option.request('refs/heads/release', 'fix/x')).toBe('accepted') + expect(await option.request(null, null)).toBe('accepted') expect(await option.cancel()).toBe(true) - expect(f.forgePanel.requestWorktree.mock.calls).toEqual([[S1, 'release'], [S1, null]]) + expect(f.forgePanel.requestWorktree.mock.calls).toEqual([[S1, 'refs/heads/release', 'fix/x'], [S1, null, null]]) expect(f.forgePanel.cancelWorktree).toHaveBeenCalledWith(S1) expect(f.notice()).toBeNull() await f.dispose() @@ -871,7 +874,7 @@ describe('mountForgePanel worktree actions', () => { const f = await fixture() const option = f.worktree(S1) f.forgePanel.requestWorktree.mockResolvedValueOnce(refusal) - expect(await option.request('main')).toBe(false) + expect(await option.request('refs/heads/main', null)).toBe('failed') expect(f.notice()).toMatchObject({ key, tone: 'failure', seq: 1 }) f.forgePanel.cancelWorktree.mockResolvedValueOnce(refusal) expect(await option.cancel()).toBe(false) @@ -879,33 +882,42 @@ describe('mountForgePanel worktree actions', () => { await f.dispose() }) - it('lists the branches of the Session checkout and reports when they cannot be read', async () => { + it.each([ + ['branch-exists', REFUSED.exists], + ['invalid-name', REFUSED.invalidName], + ] as const)('returns a branch name refused as %s to the naming dialog without a notice', async (result, refusal) => { const f = await fixture() - expect(await f.worktree(S1).branches()).toEqual(BRANCHES) - expect(f.forgePanel.branches).toHaveBeenCalledWith(S1) + f.forgePanel.requestWorktree.mockResolvedValueOnce(refusal) + expect(await f.worktree(S1).request(null, 'taken')).toBe(result) + f.forgePanel.requestWorktree.mockResolvedValueOnce(refusal) + expect(await f.progress(S1).request(null, 'taken')).toBe(result) expect(f.notice()).toBeNull() + await f.dispose() + }) - f.forgePanel.branches.mockResolvedValueOnce(REFUSED.failed) - expect(await f.worktree(S1).branches()).toBeUndefined() - expect(f.notice()).toMatchObject({ key: 'toast.branchesFailed', tone: 'failure' }) + it('lists the bases of a new worktree through the Remote', async () => { + const f = await fixture() + const signal = new AbortController().signal + expect(await f.worktree(S1).bases('rel', signal)).toEqual({ ok: true, value: BASES }) + expect(f.forgePanel.worktreeBases).toHaveBeenCalledWith(S1, 'rel', signal) await f.dispose() }) }) describe('mountForgePanel worktree card actions', () => { it.each([ - ['stops the attempt a message waits for', 'stop' as const, 'stopCreation' as const], - ['makes another attempt for the waiting message', 'retry' as const, 'retryWorktree' as const], - ['withdraws the request so the waiting message goes on', 'withdraw' as const, 'cancelWorktree' as const], - ])('%s through the Remote and reports only a failure', async (_label, action, method) => { + ['stops the attempt a message waits for', 'stop' as const, 'stopCreation' as const, []], + ['makes another attempt for the waiting message', 'retry' as const, 'retryWorktree' as const, [false]], + ['withdraws the request so the waiting message goes on', 'withdraw' as const, 'cancelWorktree' as const, []], + ])('%s through the Remote and reports only a failure', async (_label, action, method, args) => { const f = await fixture() - f.progress(S1)[action]() + f.progress(S1)[action](false) await settle() - expect(f.forgePanel[method]).toHaveBeenCalledWith(S1) + expect(f.forgePanel[method]).toHaveBeenCalledWith(S1, ...args) expect(f.notice()).toBeNull() f.forgePanel[method].mockResolvedValueOnce(REFUSED.busy) - f.progress(S1)[action]() + f.progress(S1)[action](false) await settle() expect(f.notice()).toMatchObject({ key: 'toast.worktreeFailed', tone: 'failure' }) await f.dispose() diff --git a/packages/experimental/client-ui-forge/tests/parse.host.spec.ts b/packages/experimental/client-ui-forge/tests/parse.host.spec.ts index b2c49bd448..6eb9e5bf2d 100644 --- a/packages/experimental/client-ui-forge/tests/parse.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/parse.host.spec.ts @@ -1,5 +1,7 @@ import { describe, expect, it } from 'vitest' -import { baseBranches, parseBaseBranches, parseName, parseRemotes, parseTopLevel, remoteOrder, upstreamBranch } from '../src/parse.ts' +import { + parseBaseBranches, parseName, parseRemotes, parseTopLevel, parseWorktreeBases, remoteOrder, remoteRepository, upstreamBranch, +} from '../src/parse.ts' import type { GitRemote } from '../src/parse.ts' describe('parseTopLevel', () => { @@ -27,24 +29,85 @@ describe('parseName', () => { }) }) -describe('baseBranches', () => { - it('puts the checked-out branch first without repeating it', () => { - expect(baseBranches('feat', 'main\nfeat\nfix\n', 10)).toEqual(['feat', 'main', 'fix']) +describe('parseWorktreeBases', () => { + const remotes: GitRemote[] = [ + { name: 'upstream', urls: ['https://github.com/acme/demo.git'] }, + { name: 'origin', urls: ['git@github.com:me/demo.git'] }, + { name: 'team/fork', urls: ['/srv/team.git'] }, + { name: 'empty', urls: [] }, + ] + const output = [ + 'refs/remotes/upstream/HEAD\0refs/remotes/upstream/master', + 'refs/remotes/origin/HEAD\0refs/remotes/origin/main', + 'refs/remotes/team/fork/HEAD\0refs/remotes/team/fork/gone', + 'refs/remotes/empty/HEAD\0refs/heads/main', + 'refs/remotes/origin/alias\0refs/remotes/origin/main', + 'refs/heads/alias\0refs/heads/main', + 'refs/heads/topic\0', + 'refs/remotes/upstream/master\0', + 'refs/remotes/origin/main\0', + 'refs/remotes/team/fork/feature\0', + 'refs/remotes/upstream/release/2.4\0', + 'refs/remotes/upstream/dev\0', + 'refs/heads/main\0', + 'refs/remotes/stray/main\0', + 'refs/heads/Fix/Login\0', + 'refs/tags/v1\0', + '', + ].join('\r\n') + const repositories = (remote: GitRemote): string | null => remote.urls[0] ?? null + + it('pins the checked-out branch and each remote default, then groups local branches and each remote in remote order', () => { + expect(parseWorktreeBases(output, 'main', remotes, '', 10, repositories)).toEqual({ + current: { ref: 'refs/heads/main', name: 'main' }, + defaults: [ + { ref: 'refs/remotes/upstream/master', name: 'upstream/master', remote: 'upstream' }, + { ref: 'refs/remotes/origin/main', name: 'origin/main', remote: 'origin' }, + ], + local: [{ ref: 'refs/heads/topic', name: 'topic' }, { ref: 'refs/heads/Fix/Login', name: 'Fix/Login' }], + remotes: [ + { + name: 'upstream', + repository: 'https://github.com/acme/demo.git', + branches: [{ ref: 'refs/remotes/upstream/release/2.4', name: 'upstream/release/2.4' }, { ref: 'refs/remotes/upstream/dev', name: 'upstream/dev' }], + }, + { name: 'team/fork', repository: '/srv/team.git', branches: [{ ref: 'refs/remotes/team/fork/feature', name: 'team/fork/feature' }] }, + ], + }) }) - it('keeps the checked-out branch when the listing omits it', () => { - expect(baseBranches('old', 'main\nfeat\n', 2)).toEqual(['old', 'main']) - expect(baseBranches('main', '', 50)).toEqual(['main']) + it('keeps the branches whose names contain the query, ignoring case, at most `limit` in each group', () => { + expect(parseWorktreeBases(output, 'main', remotes, ' FIX ', 10, repositories)).toEqual({ current: null, defaults: [], local: [{ ref: 'refs/heads/Fix/Login', name: 'Fix/Login' }], remotes: [] }) + const limited = parseWorktreeBases(output, null, remotes, '', 1, repositories) + expect(limited.current).toBeNull() + expect(limited.local).toEqual([{ ref: 'refs/heads/topic', name: 'topic' }]) + expect(limited.remotes.map(remote => remote.branches.length)).toEqual([1, 1]) }) - it('lists the branches of a detached HEAD in listed order', () => { - expect(baseBranches(null, 'main\r\nfeat\r\n', 10)).toEqual(['main', 'feat']) - expect(baseBranches(null, '', 10)).toEqual([]) + it('names no current branch on a detached HEAD or an unborn branch', () => { + expect(parseWorktreeBases(output, null, remotes, '', 10, repositories).current).toBeNull() + expect(parseWorktreeBases('', 'main', [], '', 10, repositories)).toEqual({ current: null, defaults: [], local: [], remotes: [] }) + }) +}) + +describe('remoteRepository', () => { + const recognize = (url: string) => url.startsWith('https://host.test/') ? { owner: 'acme', name: 'demo' } : undefined + + it('names the first recognized repository, else the first URL, else nothing', () => { + expect(remoteRepository({ name: 'origin', urls: ['/srv/demo.git', 'https://host.test/acme/demo.git'] }, recognize)).toBe('acme/demo') + expect(remoteRepository({ name: 'fork', urls: ['/srv/fork.git'] }, recognize)).toBe('/srv/fork.git') + expect(remoteRepository({ name: 'empty', urls: [] }, recognize)).toBeNull() }) - it('returns at most `limit` names and skips empty lines', () => { - expect(baseBranches('main', '\nmain\n\nfeat\nfix\n', 2)).toEqual(['main', 'feat']) - expect(baseBranches(null, 'main\nfeat\nfix\n', 1)).toEqual(['main']) + it.each([ + ['a user name and token', 'https://oauth2:glpat-secret@gitlab.internal.test/group/repo.git', 'https://gitlab.internal.test/group/repo.git'], + ['a token as the user name', 'https://ghp_secret@git.internal.test/acme/demo.git', 'https://git.internal.test/acme/demo.git'], + ['an `@` in the password', 'https://user:p@ss@git.internal.test:8443/repo', 'https://git.internal.test:8443/repo'], + ['an SSH user', 'ssh://git@git.internal.test:2222/acme/demo.git', 'ssh://git.internal.test:2222/acme/demo.git'], + ['an `@` only in the path', 'https://git.internal.test/users/@me/repo.git', 'https://git.internal.test/users/@me/repo.git'], + ['the scp-like form, which has no password', 'git@git.internal.test:acme/demo.git', 'git@git.internal.test:acme/demo.git'], + ])('shows an unrecognized URL with %s without its user information', (_label, url, shown) => { + expect(remoteRepository({ name: 'selfhost', urls: [url] }, recognize)).toBe(shown) }) }) diff --git a/packages/experimental/client-ui-forge/tests/worktree-name-dialog.client.spec.tsx b/packages/experimental/client-ui-forge/tests/worktree-name-dialog.client.spec.tsx new file mode 100644 index 0000000000..8eec26d6e4 --- /dev/null +++ b/packages/experimental/client-ui-forge/tests/worktree-name-dialog.client.spec.tsx @@ -0,0 +1,141 @@ +// @vitest-environment jsdom +/** Naming dialog of a worktree branch: the starting text, the rules checked while typing, the Host's refusals, and the retry mode. */ +import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import { en } from '../src/client/locales.ts' +import { WorktreeNameDialog, type WorktreeNameDialogProps } from '../src/client/WorktreeNameDialog.tsx' + +afterEach(() => { + cleanup() + vi.restoreAllMocks() +}) + +const t = makeTranslate(en) + +function mount(props: Partial = {}) { + const submit = vi.fn(async () => 'accepted') + const close = vi.fn() + render() + const dialog = (): HTMLElement => screen.getByRole('dialog') + const field = (): HTMLInputElement => within(dialog()).getByRole('textbox', { name: en['nameDialog.field'] }) + const confirm = (): HTMLElement => within(dialog()).getByRole('button', { name: props.mode === 'retry' ? en['nameDialog.retry'] : en['nameDialog.confirm'] }) + const type = (value: string): void => { fireEvent.change(field(), { target: { value } }) } + const message = (): string | null => field().getAttribute('aria-describedby') === null + ? null : document.getElementById(field().getAttribute('aria-describedby') ?? '')?.textContent ?? null + return { submit, close, dialog, field, confirm, type, message } +} + +describe('WorktreeNameDialog rules', () => { + it.each([ + ['', en['branchName.empty']], + ['fix login', en['branchName.space']], + ['fix~1', en['branchName.character']], + ['-fix', en['branchName.leading-dash']], + ['/fix', en['branchName.leading-slash']], + ['worktree/', en['branchName.trailing-slash']], + ['fix//login', en['branchName.double-slash']], + ['fix..login', en['branchName.double-dot']], + ['fix.', en['branchName.trailing-dot']], + ['@', en['branchName.at']], + ['fix@{1}', en['branchName.at-brace']], + ['fix/.login', en['branchName.dot-segment']], + ['fix.lock/login', en['branchName.lock-segment']], + ])('refuses %j while it is typed', (value, reason) => { + const d = mount() + d.type(value) + expect(d.message()).toBe(reason) + expect(within(d.dialog()).getByRole('alert').textContent).toBe(reason) + expect(d.field().getAttribute('aria-invalid')).toBe('true') + expect(d.confirm().hasAttribute('disabled')).toBe(true) + fireEvent.keyDown(d.field(), { key: 'Enter' }) + expect(d.submit).not.toHaveBeenCalled() + }) + + it('hints at the prefix it starts with, and at the base once a name follows it', () => { + const d = mount({ prefix: 'agent/', initial: 'agent/' }) + expect(d.message()).toBe(en['nameDialog.prefixOnly']) + expect(d.field().getAttribute('aria-invalid')).toBe('false') + expect(d.confirm().hasAttribute('disabled')).toBe(true) + d.type('agent/fix') + expect(d.message()).toBe('The first message creates this branch from main; the worktree directory takes its name') + expect(d.confirm().hasAttribute('disabled')).toBe(false) + }) + + it('without a prefix, starts empty with the base hint, and names the current HEAD for a request without a base', () => { + const d = mount({ prefix: '', initial: '', from: null }) + expect(d.message()).toBe(en['nameDialog.hintHead']) + expect(d.confirm().hasAttribute('disabled')).toBe(true) + }) + + it('takes the keyboard with the caret after the starting text', () => { + const d = mount({ initial: 'dsh-fix', named: true }) + expect(document.activeElement).toBe(d.field()) + expect(d.field().selectionStart).toBe(7) + }) +}) + +describe('WorktreeNameDialog requests', () => { + it('requests the name with Enter, ignores Enter while composing, and closes once the request is accepted', async () => { + const d = mount() + d.type('dsh-fix') + fireEvent.keyDown(d.field(), { key: 'Enter', isComposing: true }) + expect(d.submit).not.toHaveBeenCalled() + fireEvent.keyDown(d.field(), { key: 'a' }) + await act(async () => { fireEvent.keyDown(d.field(), { key: 'Enter' }) }) + expect(d.submit).toHaveBeenCalledWith('dsh-fix') + expect(d.close).toHaveBeenCalledOnce() + }) + + it('stays busy until the Host answers, then shows its refusal for that name only', async () => { + let answer: (result: 'branch-exists' | 'invalid-name' | 'failed') => void = () => {} + const d = mount() + d.submit.mockImplementation(() => new Promise((resolve) => { answer = resolve })) + d.type('dsh-taken') + fireEvent.click(d.confirm()) + expect(d.confirm().hasAttribute('disabled')).toBe(true) + await act(async () => { answer('branch-exists') }) + expect(d.message()).toBe('A branch named dsh-taken already exists') + expect(d.confirm().hasAttribute('disabled')).toBe(true) + + d.type('dsh-odd') + expect(d.confirm().hasAttribute('disabled')).toBe(false) + fireEvent.click(d.confirm()) + await act(async () => { answer('invalid-name') }) + expect(d.message()).toBe(en['branchName.invalid']) + + d.type('dsh-other') + fireEvent.click(d.confirm()) + await act(async () => { answer('failed') }) + expect(d.message()).toBe('The first message creates this branch from main; the worktree directory takes its name') + expect(d.close).not.toHaveBeenCalled() + }) + + it('returns a named request to generated names, ignoring a refusal that names no branch', async () => { + const d = mount({ initial: 'dsh-fix', named: true }) + d.submit.mockResolvedValueOnce('branch-exists') + await act(async () => { fireEvent.click(within(d.dialog()).getByRole('button', { name: en['nameDialog.auto'] })) }) + expect(d.submit).toHaveBeenCalledWith(null) + expect(d.message()).toBe('The first message creates this branch from main; the worktree directory takes its name') + await act(async () => { fireEvent.click(within(d.dialog()).getByRole('button', { name: en['nameDialog.auto'] })) }) + expect(d.close).toHaveBeenCalledOnce() + }) + + it('renames for another attempt in retry mode, without the return to generated names', async () => { + const d = mount({ mode: 'retry', initial: 'dsh-fix', named: true }) + expect(screen.getByRole('dialog', { name: en['nameDialog.retryTitle'] })).toBeTruthy() + expect(within(d.dialog()).queryByRole('button', { name: en['nameDialog.auto'] })).toBeNull() + d.type('dsh-fix-2') + await act(async () => { fireEvent.click(d.confirm()) }) + expect(d.submit).toHaveBeenCalledWith('dsh-fix-2') + }) + + it('closes without a request from Cancel and the close button', () => { + const d = mount() + fireEvent.click(within(d.dialog()).getByRole('button', { name: en['nameDialog.cancel'] })) + fireEvent.click(within(d.dialog()).getByRole('button', { name: en['nameDialog.close'] })) + expect(d.close).toHaveBeenCalledTimes(2) + expect(d.submit).not.toHaveBeenCalled() + }) +}) diff --git a/packages/experimental/client-ui-forge/tests/worktree-progress.client.spec.tsx b/packages/experimental/client-ui-forge/tests/worktree-progress.client.spec.tsx index 71fbdb43b7..fe66410c76 100644 --- a/packages/experimental/client-ui-forge/tests/worktree-progress.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/worktree-progress.client.spec.tsx @@ -3,13 +3,13 @@ * Worktree card: a running creation, which can be stopped while a message waits for it; the failed or stopped attempt a * message waits after; and a removed worktree. */ -import { act, cleanup, fireEvent, render, within } from '@testing-library/react' +import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react' import { afterEach, describe, expect, it, vi } from 'vitest' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { bindSnapshotSelector, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' import { en } from '../src/client/locales.ts' import type { PanelSnapshot } from '../src/client/source.ts' -import { WorktreeProgress } from '../src/client/WorktreeProgress.tsx' +import { WorktreeProgress, type WorktreeProgressInjected } from '../src/client/WorktreeProgress.tsx' import css from '../src/client/WorktreeProgress.module.css' import type { ForgePanelState } from '../src/types.ts' import { created, creation, failure, ready, removed, requested, worktree } from './client-fixtures.client.ts' @@ -21,8 +21,9 @@ const t = makeTranslate(en) function card(state: ForgePanelState | null) { const panel = createSnapshotStore({ state, disconnected: false }) const stop = vi.fn<() => void>() - const retry = vi.fn<() => void>() + const retry = vi.fn() const withdraw = vi.fn<() => void>() + const request = vi.fn(async () => 'accepted') const restore = vi.fn(async (): Promise => undefined) const leave = vi.fn<() => void>() const view = render( @@ -31,6 +32,7 @@ function card(state: ForgePanelState | null) { stop={stop} retry={retry} withdraw={withdraw} + request={request} restore={restore} leave={leave} t={t} @@ -40,7 +42,7 @@ function card(state: ForgePanelState | null) { const publish = (next: ForgePanelState | null): void => { act(() => { panel.set({ state: next, disconnected: false }) }) } - return { view, stop, retry, withdraw, restore, leave, root, publish } + return { view, stop, retry, withdraw, request, restore, leave, root, publish } } /** Glyph a step shows for its state. */ @@ -66,7 +68,7 @@ function details(view: ReturnType): string[][] | null { /** Names of the action buttons the card offers, in order. */ function actions(view: ReturnType): string[] { - const names = [en['creation.retry'], en['creation.skip'], en['creation.cancel']] + const names = [en['creation.retry'], en['creation.skip'], en['creation.cancel'], en['creation.useFetched'], en['creation.rename']] return view.getAllByRole('button').map(button => button.textContent).filter(name => names.includes(name)) } @@ -194,11 +196,58 @@ describe('WorktreeProgress waiting after a failed attempt', () => { const b = card(requested('main', { failure: failure(), waiting: 'creation' })) fireEvent.click(b.view.getByRole('button', { name: en['creation.retry'] })) fireEvent.click(b.view.getByRole('button', { name: en['creation.skip'] })) - expect(b.retry).toHaveBeenCalledOnce() + expect(b.retry).toHaveBeenCalledExactlyOnceWith(true) expect(b.withdraw).toHaveBeenCalledOnce() expect(b.stop).not.toHaveBeenCalled() }) + it('offers to start from the last fetched version after a failed fetch of a remote base branch', () => { + const fetchFailure = failure({ from: 'refs/remotes/origin/main', fetch: true, phase: 'fetch', message: 'fatal: unable to access' }) + const b = card(requested('refs/remotes/origin/main', { failure: fetchFailure, waiting: 'creation' })) + expect(steps(b.view)).toEqual([ + ['Fetch origin/main', 'failed', 'cross'], [en['creation.prepare'], 'waiting', 'ring'], [en['creation.checkout'], 'waiting', 'ring'], + ]) + expect(details(b.view)).toEqual([['Branch', 'dsh/0a1b2c3d'], ['From', 'origin/main'], ['Reason', 'fatal: unable to access']]) + expect(actions(b.view)).toEqual([en['creation.retry'], en['creation.useFetched'], en['creation.skip']]) + fireEvent.click(b.view.getByRole('button', { name: en['creation.useFetched'] })) + fireEvent.click(b.view.getByRole('button', { name: en['creation.retry'] })) + expect(b.retry.mock.calls).toEqual([[false], [true]]) + }) + + it('renames a chosen branch that already exists, then tries again on the new name', async () => { + const taken = failure({ branch: 'fix/login', exists: true, message: 'worktree branch already exists: fix/login' }) + const b = card(requested('refs/heads/main', { failure: taken, waiting: 'creation' }, 'fix/login')) + expect(actions(b.view)).toEqual([en['creation.rename'], en['creation.retry'], en['creation.skip']]) + fireEvent.click(b.view.getByRole('button', { name: en['creation.rename'] })) + const dialog = screen.getByRole('dialog', { name: en['nameDialog.retryTitle'] }) + const field = within(dialog).getByRole('textbox') + expect((field as HTMLInputElement).value).toBe('fix/login') + + b.request.mockResolvedValueOnce('branch-exists') + fireEvent.change(field, { target: { value: 'fix/login-2' } }) + await act(async () => { fireEvent.click(within(dialog).getByRole('button', { name: en['nameDialog.retry'] })) }) + expect(b.retry).not.toHaveBeenCalled() + fireEvent.change(field, { target: { value: 'fix/login-3' } }) + await act(async () => { fireEvent.click(within(dialog).getByRole('button', { name: en['nameDialog.retry'] })) }) + expect(b.request.mock.calls).toEqual([['refs/heads/main', 'fix/login-2'], ['refs/heads/main', 'fix/login-3']]) + expect(b.retry).toHaveBeenCalledExactlyOnceWith(true) + expect(screen.queryByRole('dialog')).toBeNull() + }) + + it('offers no rename for a taken generated name, whose next attempt takes another one', () => { + const b = card(requested('main', { failure: failure({ exists: true }), waiting: 'creation' })) + expect(actions(b.view)).toEqual([en['creation.retry'], en['creation.skip']]) + }) + + it('shows the fetch step of a running creation from a remote base branch', () => { + const b = card(requested('refs/remotes/origin/main', { creation: creation({ from: 'refs/remotes/origin/main', fetch: true, phase: 'fetch' }), waiting: 'creation' })) + expect(steps(b.view)).toEqual([ + ['Fetch origin/main', 'running', 'spinner'], [en['creation.prepare'], 'waiting', 'ring'], [en['creation.checkout'], 'waiting', 'ring'], + ]) + b.publish(requested('refs/remotes/origin/main', { creation: creation({ from: 'refs/remotes/origin/main', fetch: true, phase: 'checkout' }), waiting: 'creation' })) + expect(steps(b.view).map(step => step[1])).toEqual(['done', 'done', 'running']) + }) + it('shows a stopped attempt without steps, with the request\'s base and the same choices', () => { const b = card(requested(null, { waiting: 'creation' })) expect(b.root()?.getAttribute('data-forge-creation')).toBe('stopped') diff --git a/packages/experimental/client-ui-forge/tests/worktree-toggle.client.spec.tsx b/packages/experimental/client-ui-forge/tests/worktree-toggle.client.spec.tsx index baec5b9cb9..738d300a7e 100644 --- a/packages/experimental/client-ui-forge/tests/worktree-toggle.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/worktree-toggle.client.spec.tsx @@ -1,23 +1,40 @@ // @vitest-environment jsdom -/** New Session worktree option: when it shows, why it is disabled, the optimistic checkbox, the base menu, and a running creation. */ +/** + * New Session worktree option: when it shows, why it is disabled, the optimistic checkbox, the searchable base menu + * with remote groups, naming the branch, and a running creation. + */ import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react' import { afterEach, describe, expect, it, vi } from 'vitest' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { bindSnapshotSelector, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' -import menuCss from '@deepseek-ai/dsh-client-ui-primitives/src/Menu.module.css' +import { RemoteError, type RemoteResult } from '@deepseek-ai/dsh-typert-protocol' import { en, zh } from '../src/client/locales.ts' import type { PanelSnapshot } from '../src/client/source.ts' -import { WorktreeToggle } from '../src/client/WorktreeToggle.tsx' -import type { ForgeBranches, ForgeCheckoutState, ForgePanelState, ForgePanelWorktree, ForgeWorktreeBlocker } from '../src/types.ts' +import type { WorktreeRequestResult } from '../src/client/WorktreeNameDialog.tsx' +import { WorktreeToggle, type WorktreeToggleInjected } from '../src/client/WorktreeToggle.tsx' +import type { ForgeCheckoutState, ForgePanelState, ForgePanelWorktree, ForgeWorktreeBases, ForgeWorktreeBlocker } from '../src/types.ts' import { creation, failure, ready, worktree } from './client-fixtures.client.ts' afterEach(() => { cleanup() vi.useRealTimers() + vi.restoreAllMocks() }) const t = makeTranslate(en) -const BRANCHES: ForgeBranches = { current: 'main', branches: ['main', 'release', 'feat/x'] } +const BASES: ForgeWorktreeBases = { + current: { ref: 'refs/heads/main', name: 'main' }, + defaults: [{ ref: 'refs/remotes/upstream/master', name: 'upstream/master', remote: 'upstream' }], + local: [{ ref: 'refs/heads/release', name: 'release' }, { ref: 'refs/heads/feat/x', name: 'feat/x' }], + remotes: [ + { name: 'upstream', repository: 'acme/demo', branches: [{ ref: 'refs/remotes/upstream/feat/y', name: 'upstream/feat/y' }] }, + { name: 'team/fork', repository: null, branches: [{ ref: 'refs/remotes/team/fork/idea', name: 'team/fork/idea' }] }, + ], +} + +function ok(value: ForgeWorktreeBases): RemoteResult { + return { ok: true, value } +} /** Panel state of a Session that can still start in a worktree. */ function editable(overrides: Partial = {}, checkout?: ForgeCheckoutState): ForgePanelState { @@ -32,17 +49,22 @@ function deferred() { return { promise, resolve } } +/** Let the listing reads the menu awaits settle, past the search delay when `ms` is given. */ +async function settle(ms = 0): Promise { + await act(async () => { await new Promise(resolve => setTimeout(resolve, ms)) }) +} + function option(state: ForgePanelState | null, translate = t) { const panel = createSnapshotStore({ state, disconnected: false }) - const request = vi.fn(async (_from: string | null) => true) + const request = vi.fn(async () => 'accepted') const cancel = vi.fn(async () => true) - const branches = vi.fn(async (): Promise => BRANCHES) + const bases = vi.fn(async () => ok(BASES)) const view = render( , ) @@ -58,12 +80,15 @@ function option(state: ForgePanelState | null, translate = t) { const publish = (next: ForgePanelState): void => { act(() => { panel.set({ state: next, disconnected: false }) }) } - return { view, panel, request, cancel, branches, checkbox, base, publish } + const rows = (): string[] => screen.queryAllByRole('menuitem').map(row => row.textContent ?? '') + const search = (): HTMLElement => screen.getByRole('textbox', { name: en['diff.base.search'] }) + return { view, panel, request, cancel, bases, checkbox, base, publish, rows, search } } -/** Open the base branch menu and wait for its branches. */ +/** Open the base menu and wait for its branches. */ async function openMenu(b: ReturnType): Promise { - await act(async () => { fireEvent.click(b.base()!) }) + fireEvent.click(b.base()!) + await settle() return screen.getByRole('menu') } @@ -76,7 +101,6 @@ function hint(b: ReturnType): string | null { act(() => { vi.advanceTimersByTime(500) }) return screen.getByRole('tooltip').textContent } - describe('WorktreeToggle visibility', () => { it.each([ ['before the first state', null], @@ -92,7 +116,7 @@ describe('WorktreeToggle visibility', () => { const b = option(ready()) b.publish(editable()) expect(b.checkbox().checked).toBe(false) - b.publish(ready({ worktree: worktree({ editable: false, request: { from: 'main' } }) })) + b.publish(ready({ worktree: worktree({ editable: false, request: { from: 'main', name: null } }) })) expect(b.view.container.innerHTML).toBe('') }) }) @@ -111,8 +135,8 @@ describe('WorktreeToggle checkbox', () => { }) it.each(['read-only', 'outside-writable-root'] as const)('keeps the selected base visible after %s blocks a request until it is withdrawn', async (blocker) => { - const b = option(editable({ request: { from: 'release' } })) - b.publish(editable({ blocker, request: { from: 'release' } })) + const b = option(editable({ request: { from: 'release', name: null } })) + b.publish(editable({ blocker, request: { from: 'release', name: null } })) expect(b.checkbox().checked).toBe(true) expect(b.checkbox().disabled).toBe(false) expect(b.checkbox().closest('label')?.hasAttribute('data-disabled')).toBe(false) @@ -130,10 +154,10 @@ describe('WorktreeToggle checkbox', () => { }) it('preserves a HEAD base while blocked and restores the selected branch menu when permission returns', () => { - const b = option(editable({ blocker: 'read-only', request: { from: null } })) + const b = option(editable({ blocker: 'read-only', request: { from: null, name: null } })) expect(b.view.getByRole('button', { name: en['worktree.baseHead'] })).toBeTruthy() - b.publish(editable({ blocker: 'read-only', request: { from: 'release' } })) - b.publish(editable({ request: { from: 'release' } })) + b.publish(editable({ blocker: 'read-only', request: { from: 'release', name: null } })) + b.publish(editable({ request: { from: 'release', name: null } })) expect(b.base()?.textContent).toBe('From release') expect(b.checkbox().checked).toBe(true) }) @@ -157,7 +181,7 @@ describe('WorktreeToggle checkbox', () => { b.publish(ready({ worktree: worktree({ editable: true }) }, { branch: null, commit: null })) expect(b.view.getByRole('button', { name: copy['checkout.detached'] })).toBeTruthy() expect(b.request).not.toHaveBeenCalled() - expect(b.branches).not.toHaveBeenCalled() + expect(b.bases).not.toHaveBeenCalled() }) it('offers the option again once the blocker clears', () => { @@ -178,22 +202,22 @@ describe('WorktreeToggle checkbox', () => { const current = b.view.getByText('main') fireEvent.click(current) expect(b.request).not.toHaveBeenCalled() - expect(b.branches).not.toHaveBeenCalled() + expect(b.bases).not.toHaveBeenCalled() }) it('requests a worktree from the current branch and holds the checked state until the Host answers', async () => { const b = option(editable()) - const answer = deferred() + const answer = deferred() b.request.mockReturnValueOnce(answer.promise) fireEvent.click(b.checkbox()) - expect(b.request).toHaveBeenCalledWith('main') + expect(b.request).toHaveBeenCalledWith('refs/heads/main', null) expect(b.checkbox().checked).toBe(true) expect(b.checkbox().disabled).toBe(true) expect(b.base()?.textContent).toBe('From main') - b.publish(editable({ request: { from: 'main' } })) - await act(async () => { answer.resolve(true) }) + b.publish(editable({ request: { from: 'main', name: null } })) + await act(async () => { answer.resolve('accepted') }) expect(b.checkbox().checked).toBe(true) expect(b.checkbox().disabled).toBe(false) expect(b.base()?.textContent).toBe('From main') @@ -203,14 +227,14 @@ describe('WorktreeToggle checkbox', () => { const b = option(ready({ worktree: worktree({ editable: true }) }, { branch: null })) expect(b.view.getByText(`${en['checkout.detached']} · 0a1b2c3`)).toBeTruthy() await act(async () => { fireEvent.click(b.checkbox()) }) - expect(b.request).toHaveBeenCalledWith(null) - b.publish(ready({ worktree: worktree({ editable: true, request: { from: null } }) }, { branch: null })) + expect(b.request).toHaveBeenCalledWith(null, null) + b.publish(ready({ worktree: worktree({ editable: true, request: { from: null, name: null } }) }, { branch: null })) expect(b.base()?.textContent).toBe(en['worktree.baseHead']) }) it('returns to the Host state when the Host refuses the request', async () => { const b = option(editable()) - b.request.mockResolvedValueOnce(false) + b.request.mockResolvedValueOnce('failed') await act(async () => { fireEvent.click(b.checkbox()) }) expect(b.checkbox().checked).toBe(false) expect(b.checkbox().disabled).toBe(false) @@ -218,7 +242,7 @@ describe('WorktreeToggle checkbox', () => { }) it('withdraws an open request and shows the current branch until the Host answers', async () => { - const b = option(editable({ request: { from: 'release' } })) + const b = option(editable({ request: { from: 'release', name: null } })) expect(b.checkbox().checked).toBe(true) expect(b.base()?.textContent).toBe('From release') const answer = deferred() @@ -238,93 +262,171 @@ describe('WorktreeToggle checkbox', () => { }) }) -describe('WorktreeToggle base branch menu', () => { - it('names the current branch for a request from HEAD', () => { - const b = option(editable({ request: { from: null } })) - expect(b.base()?.textContent).toBe('From main') + +describe('WorktreeToggle base menu', () => { + it('names the current branch for a request from HEAD and the short name of a requested branch', () => { + expect(option(editable({ request: { from: null, name: null } })).base()?.textContent).toBe('From the current HEAD') + cleanup() + expect(option(editable({ request: { from: 'refs/remotes/upstream/master', name: null } })).base()?.textContent).toBe('From upstream/master') }) it('sits before the checkbox and opens below its anchor, aligned to the anchor\'s right edge', async () => { - const b = option(editable({ request: { from: 'main' } })) + const b = option(editable({ request: { from: 'refs/heads/main', name: null } })) const anchor = b.base() if (anchor === null) throw new Error('no base branch anchor') expect(anchor.compareDocumentPosition(b.checkbox()) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() - const wrapper = anchor.parentElement - if (wrapper === null) throw new Error('no menu wrapper') const menu = await openMenu(b) expect(anchor.getAttribute('aria-expanded')).toBe('true') expect(menu.dataset.anchorSide).toBe('bottom') expect(menu.dataset.anchorAlign).toBe('end') - expect(menu.style.positionAnchor).not.toBe('') - expect(menu.style.positionAnchor).toBe(wrapper.style.anchorName) }) - it('lists the local branches, marks the current and the chosen one, and requests another base', async () => { - const b = option(editable({ request: { from: 'main' } })) - const answer = deferred() - b.branches.mockReturnValueOnce(answer.promise) + it('pins the current branch and remote defaults, then lists local branches and each remote with its repository', async () => { + const b = option(editable({ request: { from: 'main', name: null } })) fireEvent.click(b.base()!) - expect(b.branches).toHaveBeenCalledOnce() - expect(b.base()?.disabled).toBe(true) - expect(screen.queryByRole('menu')).toBeNull() + expect(screen.getByRole('status').textContent).toBe(en['diff.base.loading']) + await settle() + expect(b.bases).toHaveBeenCalledWith('', expect.any(AbortSignal)) + expect(b.rows()).toEqual([ + `main${en['worktree.currentBranch']}`, `upstream/master${en['worktree.remoteDefault']}`, 'release', 'feat/x', 'upstream/feat/y', + 'team/fork/idea', `${en['worktree.name.add']}${en['worktree.name.auto']}`, + ]) + expect(screen.getAllByRole('group').map(group => group.getAttribute('aria-label'))).toEqual([ + en['worktree.pinned'], en['diff.base.local'], 'Remote · upstream', 'Remote · team/fork', + ]) + expect(screen.getByRole('group', { name: 'Remote · upstream' }).textContent).toContain('acme/demo') + // The short name that earlier panels recorded for a local branch selects that branch. + expect(screen.getByRole('menuitem', { name: /^main/ }).getAttribute('aria-current')).toBe('page') - await act(async () => { answer.resolve(BRANCHES) }) - expect(b.base()?.disabled).toBe(false) - expect(b.base()?.getAttribute('aria-expanded')).toBe('true') - const menu = screen.getByRole('menu') - expect(within(menu).getByText(en['worktree.baseMenu'])).toBeTruthy() - const items = within(menu).getAllByRole('menuitem') - expect(items.map(item => item.textContent)).toEqual([`main${en['worktree.currentBranch']}`, 'release', 'feat/x']) - expect(items.map(item => item.matches(`.${menuCss.selected}`))).toEqual([true, false, false]) - - fireEvent.click(items[1]!) - expect(b.request).toHaveBeenCalledWith('release') + fireEvent.click(screen.getByRole('menuitem', { name: 'team/fork/idea' })) + expect(b.request).toHaveBeenCalledWith('refs/remotes/team/fork/idea', null) expect(screen.queryByRole('menu')).toBeNull() }) - it('closes without a request when the chosen base is selected again', async () => { - const b = option(editable({ request: { from: 'release' } })) - const menu = await openMenu(b) - fireEvent.click(within(menu).getByRole('menuitem', { name: 'release' })) - expect(b.request).not.toHaveBeenCalled() + it('closes without a request when the chosen base is chosen again, from its anchor, and on Escape', async () => { + const b = option(editable({ request: { from: 'refs/heads/release', name: 'fix/x' } })) + await openMenu(b) + fireEvent.click(screen.getByRole('menuitem', { name: 'release' })) expect(screen.queryByRole('menu')).toBeNull() - }) - - it('closes from its anchor and on Escape', async () => { - const b = option(editable({ request: { from: 'main' } })) await openMenu(b) fireEvent.click(b.base()!) expect(screen.queryByRole('menu')).toBeNull() - expect(b.branches).toHaveBeenCalledOnce() - await openMenu(b) fireEvent.keyDown(document, { key: 'Escape' }) expect(screen.queryByRole('menu')).toBeNull() expect(b.request).not.toHaveBeenCalled() }) - it('stays closed when the branches cannot be read', async () => { - const b = option(editable({ request: { from: 'main' } })) - b.branches.mockResolvedValueOnce(undefined) - await act(async () => { fireEvent.click(b.base()!) }) - expect(screen.queryByRole('menu')).toBeNull() - expect(b.base()?.disabled).toBe(false) - expect(b.base()?.getAttribute('aria-expanded')).toBe('false') + it('keeps the chosen name when the base changes', async () => { + const b = option(editable({ request: { from: 'refs/heads/main', name: 'fix/x' } })) + await openMenu(b) + fireEvent.click(screen.getByRole('menuitem', { name: /^upstream\/master/ })) + expect(b.request).toHaveBeenCalledWith('refs/remotes/upstream/master', 'fix/x') }) -}) -describe('WorktreeToggle while the worktree is created', () => { - it('freezes the checkbox and the base branch until the creation fails, which leaves both open to change', () => { - const b = option(editable({ request: { from: 'main' }, creation: creation() })) - expect(b.checkbox().checked).toBe(true) + it('filters the listed rows at once, reads the search after a pause, and chooses the first match with Enter', async () => { + const b = option(editable({ request: { from: 'refs/heads/main', name: null } })) + b.bases.mockImplementation(async query => ok(query === '' ? BASES : { ...BASES, current: null, defaults: [], local: [] })) + await openMenu(b) + fireEvent.change(b.search(), { target: { value: 'IDEA' } }) + expect(b.rows()).toEqual(['team/fork/idea', `${en['worktree.name.add']}${en['worktree.name.auto']}`]) + await settle(200) + expect(b.bases).toHaveBeenLastCalledWith('IDEA', expect.any(AbortSignal)) + fireEvent.keyDown(b.search(), { key: 'Enter' }) + expect(b.request).toHaveBeenCalledWith('refs/remotes/team/fork/idea', null) + }) + + it('says when no branch matches, keeps Enter from choosing, and still offers to name the branch', async () => { + const b = option(editable({ request: { from: 'refs/heads/main', name: null } })) + await openMenu(b) + fireEvent.change(b.search(), { target: { value: 'hotfix' } }) + expect(screen.getByText(en['diff.base.empty'])).toBeTruthy() + fireEvent.keyDown(b.search(), { key: 'Enter' }) + expect(b.request).not.toHaveBeenCalled() + expect(b.rows()).toEqual([`${en['worktree.name.add']}${en['worktree.name.auto']}`]) + }) + + it('reports a failed listing with a retry', async () => { + const b = option(editable({ request: { from: 'refs/heads/main', name: null } })) + b.bases.mockResolvedValueOnce({ ok: false, error: new RemoteError('forgePanel/not-a-checkout', 'gone', {}) }) + await openMenu(b) + const status = screen.getByRole('status') + expect(status.textContent).toBe(`${en['toast.branchesFailed']}${en.retry}`) + fireEvent.click(within(status).getByRole('button', { name: en.retry })) + await settle() + expect(b.bases).toHaveBeenCalledTimes(2) + expect(b.rows()).toHaveLength(7) + }) + + it('stays fixed while the worktree is being created, and opens again once the attempt failed', () => { + const b = option(editable({ request: { from: 'main', name: null }, creation: creation() })) expect(b.checkbox().disabled).toBe(true) - expect(b.checkbox().closest('label')?.hasAttribute('data-disabled')).toBe(true) expect(b.base()?.disabled).toBe(true) - - b.publish(editable({ request: { from: 'main' }, failure: failure() })) - expect(b.checkbox().checked).toBe(true) + b.publish(editable({ request: { from: 'main', name: null }, failure: failure() })) expect(b.checkbox().disabled).toBe(false) - expect(b.checkbox().closest('label')?.hasAttribute('data-disabled')).toBe(false) expect(b.base()?.disabled).toBe(false) }) }) + +describe('WorktreeToggle branch name', () => { + /** Open the naming dialog from the menu's last row. */ + async function nameDialog(b: ReturnType): Promise { + await openMenu(b) + fireEvent.click(screen.getByRole('menuitem', { name: /^(Name the new branch|New branch name)/ })) + return screen.getByRole('dialog', { name: en['nameDialog.title'] }) + } + + it('starts the name from the prefix of generated names and requests the worktree on the typed name', async () => { + const b = option(editable({ request: { from: 'refs/remotes/upstream/master', name: null }, namePrefix: 'agent/' })) + const dialog = await nameDialog(b) + const field = within(dialog).getByRole('textbox', { name: en['nameDialog.field'] }) + expect((field as HTMLInputElement).value).toBe('agent/') + expect(within(dialog).getByText(en['nameDialog.prefixOnly'])).toBeTruthy() + expect(within(dialog).getByRole('button', { name: en['nameDialog.confirm'] }).hasAttribute('disabled')).toBe(true) + expect(within(dialog).queryByRole('button', { name: en['nameDialog.auto'] })).toBeNull() + + fireEvent.change(field, { target: { value: 'agent/fix-login' } }) + expect(within(dialog).getByText(en['nameDialog.hint'].replace('{branch}', 'upstream/master'))).toBeTruthy() + await act(async () => { fireEvent.click(within(dialog).getByRole('button', { name: en['nameDialog.confirm'] })) }) + expect(b.request).toHaveBeenCalledWith('refs/remotes/upstream/master', 'agent/fix-login') + expect(screen.queryByRole('dialog')).toBeNull() + }) + + it('shows a chosen name before its base and offers generated names again', async () => { + const b = option(editable({ request: { from: 'refs/heads/main', name: 'fix/login' } })) + const trigger = b.base()! + expect(trigger.textContent).toBe('fix/login · From main') + expect(trigger.getAttribute('aria-label')).toBe('New branch fix/login from main') + const dialog = await nameDialog(b) + expect(within(dialog).getByRole('textbox').value).toBe('fix/login') + await act(async () => { fireEvent.click(within(dialog).getByRole('button', { name: en['nameDialog.auto'] })) }) + expect(b.request).toHaveBeenCalledWith('refs/heads/main', null) + expect(screen.queryByRole('dialog')).toBeNull() + }) + + it('names the current HEAD for a named request without a base', () => { + const b = option(editable({ request: { from: null, name: 'fix/login' } })) + expect(b.base()?.getAttribute('aria-label')).toBe('New branch fix/login from the current HEAD') + }) + + it('keeps the dialog open with the reason when the Host refuses the name, and closes it on Cancel', async () => { + const b = option(editable({ request: { from: 'refs/heads/main', name: null } })) + const dialog = await nameDialog(b) + const field = within(dialog).getByRole('textbox') + fireEvent.change(field, { target: { value: 'taken' } }) + b.request.mockResolvedValueOnce('branch-exists') + await act(async () => { fireEvent.keyDown(field, { key: 'Enter' }) }) + expect(within(dialog).getByRole('alert').textContent).toBe('A branch named taken already exists') + fireEvent.change(field, { target: { value: 'taken-2' } }) + expect(within(dialog).queryByRole('alert')).toBeNull() + + fireEvent.click(within(dialog).getByRole('button', { name: en['nameDialog.cancel'] })) + expect(screen.queryByRole('dialog')).toBeNull() + expect(b.request).toHaveBeenCalledTimes(1) + }) + + it('shows a chosen name in Chinese copy', () => { + const b = option(editable({ request: { from: 'refs/heads/main', name: 'fix/login' } }), makeTranslate(zh)) + expect(b.base()?.textContent).toBe('fix/login · 基于 main') + }) +}) diff --git a/packages/experimental/client-ui-forge/tests/worktree.host.spec.ts b/packages/experimental/client-ui-forge/tests/worktree.host.spec.ts index 4e18fb6a97..143c885b51 100644 --- a/packages/experimental/client-ui-forge/tests/worktree.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/worktree.host.spec.ts @@ -117,9 +117,9 @@ describe('forgeWorktree projection', () => { const { session, state } = await folded() appendPluginRecord(session, WORKTREE_RECORD, { action: 'request', from: null }) - expect(state()?.request).toEqual({ from: null }) + expect(state()?.request).toEqual({ from: null, name: null }) appendPluginRecord(session, WORKTREE_RECORD, { action: 'request', from: 'main' }) - expect(state()?.request).toEqual({ from: 'main' }) + expect(state()?.request).toEqual({ from: 'main', name: null }) appendPluginRecord(session, WORKTREE_RECORD, { action: 'cancel' }) const withdrawn = state() expect(withdrawn).toEqual(EMPTY) @@ -129,12 +129,24 @@ describe('forgeWorktree projection', () => { appendPluginRecord(session, WORKTREE_RECORD, { action: 'request', from: 'feat' }) startTurn(session, 1) const locked = state() - expect(locked).toEqual({ ...EMPTY, request: { from: 'feat' }, locked: true }) + expect(locked).toEqual({ ...EMPTY, request: { from: 'feat', name: null }, locked: true }) appendPluginRecord(session, WORKTREE_RECORD, { action: 'request', from: 'main' }) appendPluginRecord(session, WORKTREE_RECORD, { action: 'cancel' }) expect(state()).toBe(locked) }) + it('keeps the branch name a request chooses, and none for a request that names no branch or an empty one', async () => { + const { session, state } = await folded() + + appendPluginRecord(session, WORKTREE_RECORD, { action: 'request', from: 'refs/remotes/origin/main', name: 'fix/login' }) + expect(state()?.request).toEqual({ from: 'refs/remotes/origin/main', name: 'fix/login' }) + const named = state() + appendPluginRecord(session, WORKTREE_RECORD, { action: 'request', from: null, name: '' }) + expect(state()).toBe(named) + appendPluginRecord(session, WORKTREE_RECORD, { action: 'request', from: null }) + expect(state()?.request).toEqual({ from: null, name: null }) + }) + it('applies the first created worktree of an open request, after which requests, withdrawals, and creations change nothing', async () => { const { session, state } = await folded() appendPluginRecord(session, WORKTREE_RECORD, { action: 'request', from: 'main' }) @@ -145,7 +157,7 @@ describe('forgeWorktree projection', () => { appendPluginRecord(session, WORKTREE_RECORD, { action: 'request', from: null }) appendPluginRecord(session, WORKTREE_RECORD, { action: 'cancel' }) - expect(created).toEqual({ ...EMPTY, request: { from: 'main' }, created: { ...WORKTREE, from: 'main' } }) + expect(created).toEqual({ ...EMPTY, request: { from: 'main', name: null }, created: { ...WORKTREE, from: 'main' } }) expect(state()).toBe(created) }) @@ -158,8 +170,8 @@ describe('forgeWorktree projection', () => { const created = state() startStep(session, 1) - expect(created).toEqual({ ...EMPTY, request: { from: null }, created: WORKTREE, locked: true }) - expect(state()).toEqual({ ...EMPTY, request: { from: null }, created: WORKTREE, locked: true, stepped: true }) + expect(created).toEqual({ ...EMPTY, request: { from: null, name: null }, created: WORKTREE, locked: true }) + expect(state()).toEqual({ ...EMPTY, request: { from: null, name: null }, created: WORKTREE, locked: true, stepped: true }) }) it('ignores a created worktree without an open request or after the first step starts', async () => { @@ -180,7 +192,7 @@ describe('forgeWorktree projection', () => { const stepped = state() appendPluginRecord(session, WORKTREE_RECORD, { action: 'created', worktree: WORKTREE }) - expect(stepped).toEqual({ ...EMPTY, request: { from: null }, locked: true, stepped: true }) + expect(stepped).toEqual({ ...EMPTY, request: { from: null, name: null }, locked: true, stepped: true }) expect(state()).toBe(stepped) }) @@ -215,7 +227,7 @@ describe('forgeWorktree projection', () => { session.append('step/end', { turn: 1, step: 1 }) expect(state()).toBe(requested) - expect(requested).toEqual({ ...EMPTY, request: { from: 'main' } }) + expect(requested).toEqual({ ...EMPTY, request: { from: 'main', name: null } }) }) }) @@ -280,7 +292,7 @@ describe('creating a requested worktree', () => { const head = await git(repo, 'rev-parse', 'HEAD') request(opened, null) - const result = await opened.creations.create(opened.agent, null, signal, false) + const result = await opened.creations.create(opened.agent, { from: null, name: null }, signal, false, false) const branch = result.branch expect(branch).toMatch(/^dsh-[0-9a-f]{8}$/) @@ -302,9 +314,9 @@ describe('creating a requested worktree', () => { const opened = await creating(repo) request(opened, null) - const result = await opened.creations.create(opened.agent, null, signal, false) + const result = await opened.creations.create(opened.agent, { from: null, name: null }, signal, false, false) - const running = { branch: result.branch, from: null, held: false } + const running = { branch: result.branch, from: null, fetch: false, held: false } expect(opened.changes).toEqual([{ ...running, phase: 'prepare' }, { ...running, phase: 'prepare' }, { ...running, phase: 'checkout' }, null]) expect(opened.recorded).toEqual([null, null, null, worktreeOf(opened)]) expect(worktreeOf(opened)).not.toBeNull() @@ -319,7 +331,7 @@ describe('creating a requested worktree', () => { const opened = await creating(repo) request(opened, 'base') - await opened.creations.create(opened.agent, 'base', signal, false) + await opened.creations.create(opened.agent, { from: 'base', name: null }, signal, false, false) const created = worktreeOf(opened) expect(created).toMatchObject({ from: 'base', baseCommit: base }) @@ -333,7 +345,7 @@ describe('creating a requested worktree', () => { const opened = await creating(repo, { prefix: 'agent/task-' }) request(opened, null) - const result = await opened.creations.create(opened.agent, null, signal, false) + const result = await opened.creations.create(opened.agent, { from: null, name: null }, signal, false, false) expect(result.branch).toMatch(/^agent\/task-[0-9a-f]{8}$/) expect(opened.ctx.workingDirectory.get(opened.session)).toBe(join(repo, '.agents', 'worktrees', ...result.branch.split('/'))) @@ -344,7 +356,7 @@ describe('creating a requested worktree', () => { const opened = await creating(repo) request(opened, 'later') - const attempt = opened.creations.create(opened.agent, 'later', signal, false) + const attempt = opened.creations.create(opened.agent, { from: 'later', name: null }, signal, false, false) const branch = opened.changes[0]?.branch const cause: unknown = expect.objectContaining({ message: MISSING_BASE }) @@ -358,10 +370,10 @@ describe('creating a requested worktree', () => { cause, }) expect(branch).toEqual(GENERATED_BRANCH) - const running = { phase: 'prepare', branch, from: 'later', held: false } + const running = { phase: 'prepare', branch, from: 'later', fetch: false, held: false } expect(opened.changes).toEqual([running, running, null]) expect(opened.records).toEqual([{ action: 'request', from: 'later' }]) - expect(stateOf(opened)).toEqual({ ...EMPTY, request: { from: 'later' }, cwd: repo }) + expect(stateOf(opened)).toEqual({ ...EMPTY, request: { from: 'later', name: null }, cwd: repo }) expect(opened.ctx.workingDirectory.get(opened.session)).toBe(repo) }) @@ -371,7 +383,7 @@ describe('creating a requested worktree', () => { request(opened, null) opened.sandbox.gate = argv => argv.includes('reset') ? Promise.reject(new Error('checkout refused')) : undefined - const attempt = opened.creations.create(opened.agent, null, signal, false) + const attempt = opened.creations.create(opened.agent, { from: null, name: null }, signal, false, false) const branch = opened.changes[0]?.branch ?? '' await expect(attempt).rejects.toMatchObject({ @@ -386,13 +398,52 @@ describe('creating a requested worktree', () => { expect(await branches(repo)).toEqual([branch, 'main']) }) + it('creates the branch a request names on every attempt', async () => { + const repo = await project() + const opened = await creating(repo) + + const result = await opened.creations.create(opened.agent, { from: null, name: 'fix/login' }, signal, false, false) + + expect(result.branch).toBe('fix/login') + expect(opened.changes[0]).toMatchObject({ branch: 'fix/login', phase: 'prepare', fetch: false }) + expect(opened.ctx.workingDirectory.get(opened.session)).toBe(join(repo, '.agents', 'worktrees', 'fix', 'login')) + }) + + it('fetches a remote base branch first, then starts from the fetched commit', async () => { + const { path: parent, remove } = await scratch('dsh-forge-worktree-fetch-') + cleanups.push(remove) + const upstream = await repository(parent, 'upstream') + const repo = join(parent, 'clone') + await git(parent, 'clone', '--quiet', upstream, repo) + const fetched = await commitAt(upstream, 'remote.txt', '2026-02-01T00:00:00Z') + const opened = await creating(repo) + + const result = await opened.creations.create(opened.agent, { from: 'refs/remotes/origin/main', name: null }, signal, false, true) + + expect(result.baseCommit).toBe(fetched) + expect(opened.changes.map(change => change?.phase ?? null)).toEqual(['fetch', 'fetch', 'prepare', 'checkout', null]) + expect(opened.changes[0]).toMatchObject({ from: 'refs/remotes/origin/main', fetch: true }) + await expect(access(join(result.path, 'remote.txt'))).resolves.toBeUndefined() + }) + + it('says when the branch an attempt names already exists', async () => { + const repo = await project() + const opened = await creating(repo) + + await expect(opened.creations.create(opened.agent, { from: null, name: 'main' }, signal, false, false)) + .rejects.toMatchObject({ name: 'CreationFailure', branch: 'main', phase: 'prepare', exists: true }) + opened.sandbox.failure = new Error('confinement denied') + await expect(opened.creations.create(opened.agent, { from: null, name: 'other' }, signal, false, false)) + .rejects.toMatchObject({ name: 'CreationFailure', exists: false }) + }) + it('reports a failure that is not an Error by its text', async () => { const repo = await project() const opened = await creating(repo) request(opened, null) opened.sandbox.failure = 'confinement denied' - await expect(opened.creations.create(opened.agent, null, signal, false)) + await expect(opened.creations.create(opened.agent, { from: null, name: null }, signal, false, false)) .rejects.toMatchObject({ phase: 'prepare', reason: 'confinement denied', cause: 'confinement denied' }) expect(opened.changes.at(-1)).toBeNull() }) @@ -497,7 +548,7 @@ describe('worktree creation at the first step proposal', () => { const repo = await project() const opened = await creating(repo) request(opened, null) - const created = await opened.creations.create(opened.agent, null, signal, false) + const created = await opened.creations.create(opened.agent, { from: null, name: null }, signal, false, false) const reports = opened.changes.length const proposed = prompt('go') @@ -520,7 +571,7 @@ describe('worktree creation at the first step proposal', () => { await expect(proposeStep(opened.ctx, opened.agent, { turn: 1, step: 1, messages: [prompt('go')] })) .rejects.toMatchObject({ name: 'CreationFailure', branch: GENERATED_BRANCH, phase: 'prepare', reason: MISSING_BASE }) const failed = opened.changes[0]?.branch - expect(stateOf(opened)).toEqual({ ...EMPTY, request: { from: 'later' }, locked: true, cwd: repo }) + expect(stateOf(opened)).toEqual({ ...EMPTY, request: { from: 'later', name: null }, locked: true, cwd: repo }) expect(opened.records).toEqual([{ action: 'request', from: 'later' }]) expect(opened.ctx.workingDirectory.get(opened.session)).toBe(repo) @@ -551,7 +602,7 @@ describe('worktree creation at the first step proposal', () => { expect(await settled).toBe(cause) expect(opened.changes.at(-1)).toBeNull() expect(opened.records).toEqual([{ action: 'request', from: null }]) - expect(stateOf(opened)).toEqual({ ...EMPTY, request: { from: null }, cwd: repo }) + expect(stateOf(opened)).toEqual({ ...EMPTY, request: { from: null, name: null }, cwd: repo }) expect(opened.ctx.workingDirectory.get(opened.session)).toBe(repo) expect(await branches(repo)).toEqual(['main']) }) @@ -563,13 +614,24 @@ describe('worktree creation at the first step proposal', () => { await expect(proposeStep(opened.ctx, opened.agent, { turn: 1, step: 1, messages: [prompt('go')] })) .rejects.toThrow('No worktree service is mounted') - expect(stateOf(opened)).toEqual({ ...EMPTY, request: { from: null }, cwd: repo }) + expect(stateOf(opened)).toEqual({ ...EMPTY, request: { from: null, name: null }, cwd: repo }) expect(opened.changes).toEqual([]) expect(opened.ctx.workingDirectory.get(opened.session)).toBe(repo) }) }) +it('names the fetch as the failed step of a remote-based attempt that fails before it reaches the worktree service', async () => { + const opened = await creating(await project(), { worktrees: false }) + request(opened, 'refs/remotes/origin/main') + opened.creations.holdCreation(opened.agent) + await vi.waitFor(() => { expect(opened.creations.failureOf(opened.session)).not.toBeNull() }) + expect(opened.creations.failureOf(opened.session)).toEqual({ + branch: null, from: 'refs/remotes/origin/main', fetch: true, phase: 'fetch', message: 'No worktree service is mounted', exists: false, + }) + await opened.creations.dispose() +}) + it('does not admit a new message hold after worktree operations stop', async () => { const opened = await creating(await project()) request(opened, null) diff --git a/packages/experimental/client-ui-forge/tsconfig.client.json b/packages/experimental/client-ui-forge/tsconfig.client.json index 89f15d9ba8..b0c696724c 100644 --- a/packages/experimental/client-ui-forge/tsconfig.client.json +++ b/packages/experimental/client-ui-forge/tsconfig.client.json @@ -7,6 +7,7 @@ }, "include": [ "src/client", + "src/branch-name.ts", "src/commit-range.ts", "src/css-modules.d.ts", "src/lens-version.ts", diff --git a/packages/experimental/client-ui-forge/tsconfig.host.json b/packages/experimental/client-ui-forge/tsconfig.host.json index d92dfcba55..7486a1fa45 100644 --- a/packages/experimental/client-ui-forge/tsconfig.host.json +++ b/packages/experimental/client-ui-forge/tsconfig.host.json @@ -7,6 +7,7 @@ }, "files": [ "src/index.ts", + "src/branch-name.ts", "src/commit-range.ts", "src/diff.ts", "src/git.ts", diff --git a/packages/experimental/tool-worktree/README.i18n.yaml b/packages/experimental/tool-worktree/README.i18n.yaml index 10910e375f..5d0610fed9 100644 --- a/packages/experimental/tool-worktree/README.i18n.yaml +++ b/packages/experimental/tool-worktree/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-tool-worktree/use-this-package: - en: f357051b201aa5b9 - zh: ace93e12e8d4de82 + en: 57fa5f479232a5c6 + zh: f8c1f2476a2dfef0 /deepseek-ai-dsh-experimental-tool-worktree/understand-the-implementation: en: c03f875211ab69a8 zh: 8f49b82f90a60223 diff --git a/packages/experimental/tool-worktree/README.md b/packages/experimental/tool-worktree/README.md index 2f1b293808..a405055fe8 100644 --- a/packages/experimental/tool-worktree/README.md +++ b/packages/experimental/tool-worktree/README.md @@ -34,7 +34,7 @@ For an explicit composition, mount this function plugin after the worktree runti - name: '@deepseek-ai/dsh-experimental-tool-worktree' ``` -Call `create_worktree({ name?: string, from?: string })`. Success returns the canonical checkout `path`, new `branch`, pinned `baseCommit`, and source `repositoryRoot`, and changes the calling Session's current working directory. To leave, call `working_directory({ cd: path })`; the checkout and branch remain. The [generated tool catalog](../../../docs/tool-catalog.md#deepseek-aidsh-experimental-tool-worktree) owns the exact schema and model-facing description. +Call `create_worktree({ name?: string, from?: string })`. The tool forwards only these two fields to the runtime, so it never fetches. Success returns the canonical checkout `path`, new `branch`, pinned `baseCommit`, and source `repositoryRoot`, and changes the calling Session's current working directory. To leave, call `working_directory({ cd: path })`; the checkout and branch remain. The [generated tool catalog](../../../docs/tool-catalog.md#deepseek-aidsh-experimental-tool-worktree) owns the exact schema and model-facing description. ----- diff --git a/packages/experimental/tool-worktree/README.zh.md b/packages/experimental/tool-worktree/README.zh.md index 8b37299687..d39bef7cb8 100644 --- a/packages/experimental/tool-worktree/README.zh.md +++ b/packages/experimental/tool-worktree/README.zh.md @@ -34,7 +34,7 @@ kind: "package-bundle" - name: '@deepseek-ai/dsh-experimental-tool-worktree' ``` -调用 `create_worktree({ name?: string, from?: string })`。成功会返回规范化检出路径 `path`、新分支 `branch`、固定提交 `baseCommit` 和源仓库根目录 `repositoryRoot`,并改变调用 Session 的当前工作目录。离开时调用 `working_directory({ cd: path })`;检出目录与分支会保留。[生成的工具目录](../../../docs/tool-catalog.zh.md#deepseek-aidsh-experimental-tool-worktree)拥有准确的 schema 与面向模型的描述。 +调用 `create_worktree({ name?: string, from?: string })`。工具只把这两个字段转给运行时,因此从不执行 fetch。成功会返回规范化检出路径 `path`、新分支 `branch`、固定提交 `baseCommit` 和源仓库根目录 `repositoryRoot`,并改变调用 Session 的当前工作目录。离开时调用 `working_directory({ cd: path })`;检出目录与分支会保留。[生成的工具目录](../../../docs/tool-catalog.zh.md#deepseek-aidsh-experimental-tool-worktree)拥有准确的 schema 与面向模型的描述。 ----- diff --git a/packages/experimental/tool-worktree/src/index.ts b/packages/experimental/tool-worktree/src/index.ts index ad526e61ef..6e2edd275b 100644 --- a/packages/experimental/tool-worktree/src/index.ts +++ b/packages/experimental/tool-worktree/src/index.ts @@ -34,9 +34,10 @@ export function apply(ctx: Context): void { }, render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }], }, - async execute(args, exec) { + async execute({ name, from }, exec) { if (exec.agent === undefined) throw new ToolContextUnavailableError('create_worktree requires a calling agent') - return ctx.worktrees.create(exec.agent, args, exec.signal) + // The parameter object is open, so only the declared fields reach the runtime; it never fetches for this tool. + return ctx.worktrees.create(exec.agent, { ...name === undefined ? {} : { name }, ...from === undefined ? {} : { from } }, exec.signal) }, presentCall: args => ({ card: 'generic', title: 'create_worktree', rawInput: args }), })) diff --git a/packages/experimental/tool-worktree/tests/loader-composition.spec.ts b/packages/experimental/tool-worktree/tests/loader-composition.spec.ts index 25af996861..3b28d175b5 100644 --- a/packages/experimental/tool-worktree/tests/loader-composition.spec.ts +++ b/packages/experimental/tool-worktree/tests/loader-composition.spec.ts @@ -106,6 +106,13 @@ describe('worktree tool through real Loader composition', () => { expect(failure.isError && failure.error.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) const existing = await invoke('new-checkout') expect(existing.isError && existing.error.info).toEqual({ name: 'WorktreeError', code: 'WORKTREE_ALREADY_EXISTS' }) + // A forwarded `fetch` would make the runtime refuse `main`, which is not a remote-tracking branch. + const undeclared = await executeToolFixture(context, { + name: 'create_worktree', callId: brandString('undeclared'), arguments: { from: 'main', fetch: true }, agent, + signal: new AbortController().signal, + }) + expect(undeclared.isError).not.toBe(true) + expect(undeclared.value).toMatchObject({ baseCommit, repositoryRoot: path }) expect(context.tools.get('create_worktree')!.presentCall!({ name: 'named' })).toEqual({ card: 'generic', title: 'create_worktree', rawInput: { name: 'named' }, }) diff --git a/packages/experimental/worktree/README.i18n.yaml b/packages/experimental/worktree/README.i18n.yaml index b97e443ecd..18b58d2fdd 100644 --- a/packages/experimental/worktree/README.i18n.yaml +++ b/packages/experimental/worktree/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-worktree/use-this-package: - en: e33f2d32037ef164 - zh: 18528ef31803c6d0 + en: 4c5c550f3abde1af + zh: a10b5f99abc209d3 /deepseek-ai-dsh-experimental-worktree/understand-the-implementation: en: 6971a7ca9073bef1 zh: b977c28a75c7f963 @@ -30,8 +30,8 @@ en: 6826dfaadb24f3da zh: 2e2ee715247fc015 /deepseek-ai-dsh-experimental-worktree/known-limitations-and-deferred-work: - en: 9115db41d1c8eed7 - zh: 87857659a8a47c1d + en: 3ce9e81c2c5ca919 + zh: c06c84179e82f4c2 /deepseek-ai-dsh-experimental-worktree/known-limitations-and-deferred-work/dev-note: en: ad12746a6cc96d8a zh: 66275f30a35c88e4 diff --git a/packages/experimental/worktree/README.md b/packages/experimental/worktree/README.md index 30cfcfca04..1d789edfc5 100644 --- a/packages/experimental/worktree/README.md +++ b/packages/experimental/worktree/README.md @@ -32,7 +32,7 @@ Mount the service alongside `workingDirectory`, `fs`, `subprocess`, `sandbox`, ` - name: '@deepseek-ai/dsh-experimental-tool-worktree' ``` -`ctx.worktrees.create(agent, { name?, from? }, signal?, onPhase?)` creates a new branch and checkout, then enters the canonical checkout directory through `ctx.workingDirectory.set`. `from` resolves to a local commit before creation and defaults to `HEAD`; staged, unstaged, untracked, and ignored source files are not copied. `baseCommit` reports the resolved commit object name; repository-local replacement refs still apply to the checked-out content. Checkout disables configured Git clean, smudge, and process filters without changing repository configuration. An existing branch or checkout path is an error. The returned record contains `path`, `branch`, `baseCommit`, and `repositoryRoot`. An optional fourth argument, `onPhase`, receives `prepare` before validation, directory allocation, and branch creation, and `checkout` before the files are written and the checkout is entered; it must not throw. +`ctx.worktrees.create(agent, { name?, from?, fetch? }, signal?, onPhase?)` creates a new branch and checkout, then enters the canonical checkout directory through `ctx.workingDirectory.set`. `from` resolves to a local commit before creation and defaults to `HEAD`. With `fetch: true`, `from` must be the full name of a remote-tracking branch, `refs/remotes//`, of a configured remote, the longest remote name winning when names nest; creation first runs `git fetch --no-tags --no-recurse-submodules --no-write-fetch-head --no-auto-maintenance +refs/heads/:`, so only that branch is fetched, then resolves the fetched commit. The fetch runs under the Session's sandbox policy and the command deadline, without prompts, and a failed fetch creates nothing; staged, unstaged, untracked, and ignored source files are not copied. `baseCommit` reports the resolved commit object name; repository-local replacement refs still apply to the checked-out content. Checkout disables configured Git clean, smudge, and process filters without changing repository configuration. An existing branch or checkout path is an error. The returned record contains `path`, `branch`, `baseCommit`, and `repositoryRoot`. An optional fourth argument, `onPhase`, receives `fetch` first when the request asks to fetch, `prepare` before validation, directory allocation, and branch creation, and `checkout` before the files are written and the checkout is entered; it must not throw. `ctx.worktrees.restore(agent, { path, branch, baseCommit, repositoryRoot }, signal?, onPhase?)` checks a removed worktree out again at its recorded directory. It validates the recorded repository root, full commit object name, branch, and canonical target inside the configured pool before mutation. It removes only the missing target's unlocked registration with `git worktree remove`; other worktrees and locked registrations remain unchanged. It then checks out the branch when it still exists, or creates the branch again at `baseCommit` when it does not, and reports which happened as `branchRecreated`. An existing directory is an error. The calling Session's working directory does not change, and changes that were never committed are not recovered. Checkout disables filters as creation does. `onPhase` receives `prepare` before validation, target-registration cleanup, and branch creation, and `checkout` before the files are written; it must not throw. @@ -89,7 +89,7 @@ This package contributes no prompt text. Its consumers own the appended tool res - **Retained artifacts** — leaving a worktree keeps its branch and files, and archive cleanup never deletes a branch. Setup failures can also retain partial artifacts, and a failed removal can leave a partial directory for the retained branch to be restored over. -- **Local revisions only** — creation does not fetch commits or missing partial-clone objects, initialize submodules, install dependencies, or copy uncommitted files. On Git that meets the execution requirements, missing local objects cause creation to fail. +- **Local revisions unless asked** — creation fetches only the one remote branch a request asks for; it does not fetch other commits or missing partial-clone objects, initialize submodules, install dependencies, or copy uncommitted files. On Git that meets the execution requirements, missing local objects cause creation to fail. - **Filtered representations** — checkout skips configured filters to avoid executing repository-configured programs or triggering implicit downloads. Git LFS pointers and encrypted blobs stay in their stored representation; hydration or decryption is a separate user-controlled operation. - **Execution requirements** — the subprocess provider must offer Git and Node in the same execution world as the filesystem provider. Git must honor `GIT_NO_LAZY_FETCH`, which Git 2.45 and the 2.39.4, 2.40.2, 2.41.1, 2.42.2, 2.43.4, and 2.44.1 maintenance releases do; older releases ignore it and proceed instead of failing, so creation can fetch missing partial-clone objects from a promisor remote. The `git --no-lazy-fetch` option would reject these releases, but it exists only in Git 2.45 and later and also rejects the patched maintenance releases. The existing sandbox must permit all checkout and shared Git metadata writes. diff --git a/packages/experimental/worktree/README.zh.md b/packages/experimental/worktree/README.zh.md index 28fc6fb0b0..edc02c6a4a 100644 --- a/packages/experimental/worktree/README.zh.md +++ b/packages/experimental/worktree/README.zh.md @@ -32,7 +32,7 @@ kind: "package-reference" - name: '@deepseek-ai/dsh-experimental-tool-worktree' ``` -`ctx.worktrees.create(agent, { name?, from? }, signal?, onPhase?)` 创建新分支与检出目录,再通过 `ctx.workingDirectory.set` 进入规范化的检出目录。`from` 在创建前解析为本地提交,默认是 `HEAD`;暂存、未暂存、未跟踪以及被忽略的源文件均不复制。`baseCommit` 报告解析出的提交对象名称;仓库本地的替换引用仍作用于检出的内容。检出操作禁用已配置的 Git clean、smudge 和 process 过滤器,不修改仓库配置。分支或检出路径已存在时会报错。返回记录包含 `path`、`branch`、`baseCommit` 和 `repositoryRoot`。可选的第四个参数 `onPhase` 在校验、分配目录与创建分支之前收到 `prepare`,在写入文件并进入检出之前收到 `checkout`;它不得抛出异常。 +`ctx.worktrees.create(agent, { name?, from?, fetch? }, signal?, onPhase?)` 创建新分支与检出目录,再通过 `ctx.workingDirectory.set` 进入规范化的检出目录。`from` 在创建前解析为本地提交,默认是 `HEAD`。`fetch: true` 时,`from` 必须是某个已配置远程的远程跟踪分支完整引用名 `refs/remotes//`,远程名相互嵌套时取最长的;创建前先运行 `git fetch --no-tags --no-recurse-submodules --no-write-fetch-head --no-auto-maintenance +refs/heads/:`,只获取这一个分支,再解析获取到的提交。获取在 Session 的沙箱策略与命令期限下运行,不会提示输入,获取失败时不创建任何东西;暂存、未暂存、未跟踪以及被忽略的源文件均不复制。`baseCommit` 报告解析出的提交对象名称;仓库本地的替换引用仍作用于检出的内容。检出操作禁用已配置的 Git clean、smudge 和 process 过滤器,不修改仓库配置。分支或检出路径已存在时会报错。返回记录包含 `path`、`branch`、`baseCommit` 和 `repositoryRoot`。可选的第四个参数 `onPhase` 在请求要求获取时先收到 `fetch`,在校验、分配目录与创建分支之前收到 `prepare`,在写入文件并进入检出之前收到 `checkout`;它不得抛出异常。 `ctx.worktrees.restore(agent, { path, branch, baseCommit, repositoryRoot }, signal?, onPhase?)` 在记录的目录重新检出被删除的 worktree。它在修改前校验记录中的仓库根目录、完整提交对象名、分支和配置池内的规范目标路径。它只通过 `git worktree remove` 移除缺失目标的未锁定登记;其他 worktree 与锁定登记保持不变。随后在分支仍存在时检出该分支,否则在 `baseCommit` 重新创建同名分支,并通过 `branchRecreated` 报告是哪种情况。目录已存在时会报错。调用方 Session 的工作目录不变,从未提交的修改无法恢复。检出与创建时一样禁用过滤器。`onPhase` 在检查目录、清理登记与创建分支之前收到 `prepare`,在写入文件之前收到 `checkout`;它不能抛出异常。 @@ -89,7 +89,7 @@ Git 与目录分配通过挂载的子进程及沙箱提供方执行,沿用调 - **保留的产物**——离开工作树时保留其分支和文件,归档清理也从不删除分支。安装失败同样可能保留部分产物;删除失败可能留下部分目录,可在保留的分支上恢复覆盖。 -- **仅限本地提交**——创建操作不会获取远端提交或部分克隆中缺失的对象、初始化子模块、安装依赖或复制未提交文件。Git 满足执行要求时,本地对象缺失会导致创建失败。 +- **默认仅限本地提交**——创建操作只获取请求指定的那一个远程分支,不会获取其他远端提交或部分克隆中缺失的对象、初始化子模块、安装依赖或复制未提交文件。Git 满足执行要求时,本地对象缺失会导致创建失败。 - **过滤器处理前的内容**——检出时跳过已配置的过滤器,以避免执行仓库配置的程序或隐式下载。Git LFS 指针与加密 blob 保持存储时的形式;拉取实体内容或解密由用户另行执行。 - **执行要求**——子进程提供方必须在与文件系统提供方相同的执行环境中提供 Git 与 Node。Git 必须识别 `GIT_NO_LAZY_FETCH`:Git 2.45 及 2.39.4、2.40.2、2.41.1、2.42.2、2.43.4、2.44.1 维护版本均支持;更早的版本会忽略该变量并继续执行而不报错,因此创建操作可能从 promisor 远程获取缺失的部分克隆对象。`git --no-lazy-fetch` 选项会拒绝这些版本,但它仅在 Git 2.45 及以后存在,也会拒绝上述已修补的维护版本。现有沙箱必须允许写入检出目录与共享 Git 元数据。 diff --git a/packages/experimental/worktree/src/index.ts b/packages/experimental/worktree/src/index.ts index 8e2c5b5ade..5ffbbeb7b8 100644 --- a/packages/experimental/worktree/src/index.ts +++ b/packages/experimental/worktree/src/index.ts @@ -64,8 +64,13 @@ type ResolvedConfig = Required & ProcessConfig interface WorktreeSpec { branch: string revision: string + /** Whether the remote-tracking branch `revision` is fetched before it is resolved. */ + fetch: boolean } +/** Prefix of the full names of remote-tracking branches. */ +const REMOTE_REFS = 'refs/remotes/' + /** Runs one confined Git command; output with an exit code outside `allowedExitCodes` throws. */ type GitRun = (directory: string, args: string[], allowedExitCodes?: number[], env?: NodeJS.ProcessEnv) => ReturnType @@ -147,19 +152,21 @@ export class WorktreeService extends Service { } /** - * Create a fresh branch and checkout at a pinned local revision, then enter it. + * Create a fresh branch and checkout at a pinned local revision, then enter it. A request that asks to fetch + * first fetches its remote-tracking branch, only that branch and without tags, then pins the fetched commit. * Existing branches or checkout paths fail. Uncommitted files stay in the source checkout. * Checkout disables configured clean, smudge, and process filters without changing Git config. * Repository-local replacement refs still apply; baseCommit reports the resolved object name. * The new checkout becomes current only after Git setup succeeds. Failures may retain newly * allocated Git/filesystem artifacts; no branch or checkout is removed automatically. * @param agent - caller whose current directory selects the source repository and file policy. - * @param request - optional new name and local revision; defaults are generated name and HEAD. + * @param request - optional new name, local revision, and fetch switch; defaults are generated name, HEAD, and no fetch. * @param signal - cancellation of lookup, creation, and working-directory publication. * @param onPhase - receives each stage before it begins; it must not throw. * @returns canonical checkout path, branch name, pinned commit, and source repository root. - * @throws {WorktreeError} for an invalid request, an existing branch or path, or a failed, oversized, or timed-out - * command; a failure after allocation keeps its `name` and `code` and adds retained-artifact context. + * @throws {WorktreeError} for an invalid request, a fetch request whose `from` is not a remote-tracking branch of a + * configured remote, an existing branch or path, or a failed, oversized, or timed-out command, including the + * fetch; a failure after allocation keeps its `name` and `code` and adds retained-artifact context. */ async create( agent: Agent, @@ -189,7 +196,7 @@ export class WorktreeService extends Service { * @param agent - caller whose sandbox policy confines the commands. * @param request - recorded directory, branch, base commit, and source repository root. * @param signal - cancellation of the restoration. - * @param onPhase - receives each stage before it begins; it must not throw. + * @param onPhase - receives each stage before it begins, never `fetch`; it must not throw. * @returns the directory and whether the branch was created again. * @throws {WorktreeError} for an invalid request, an existing path, a locked registration, or a failed, oversized, * or timed-out command; a failure after allocation keeps its `name` and `code` and adds retained-artifact context. @@ -198,7 +205,7 @@ export class WorktreeService extends Service { agent: Agent, request: RestoreWorktreeRequest, signal?: AbortSignal, - onPhase?: (phase: CreateWorktreePhase) => void, + onPhase?: (phase: Exclude) => void, ): Promise { const operationSignal = signal === undefined ? this.lifetime.signal : AbortSignal.any([this.lifetime.signal, signal]) operationSignal.throwIfAborted() @@ -252,16 +259,20 @@ export class WorktreeService extends Service { if (!relativePath(branch) || branch.startsWith('-')) throw new WorktreeError('worktree name must be a relative Git branch name', 'WORKTREE_INVALID_ARGUMENT') const revision = request.from ?? 'HEAD' if (revision.length === 0) throw new WorktreeError('worktree from must name a local commit, branch, or tag', 'WORKTREE_INVALID_ARGUMENT') - return { branch, revision } + const fetch = request.fetch === true + if (fetch && !revision.startsWith(REMOTE_REFS)) { + throw new WorktreeError('worktree fetch needs from to name a remote-tracking branch under refs/remotes/', 'WORKTREE_INVALID_ARGUMENT') + } + return { branch, revision, fetch } } private async createCheckout( agent: Agent, - { branch, revision }: WorktreeSpec, + { branch, revision, fetch }: WorktreeSpec, signal: AbortSignal, onPhase: ((phase: CreateWorktreePhase) => void) | undefined, ): Promise { - onPhase?.('prepare') + onPhase?.(fetch ? 'fetch' : 'prepare') const cwd = await this.ctx.workingDirectory.ensure(agent, signal) const policy = this.ctx.sandboxPolicy.resolve({ session: agent.session }) const run = this.gitRunner(policy, signal) @@ -269,6 +280,10 @@ export class WorktreeService extends Service { const rootOutput = await run(cwd, ['rev-parse', '--show-toplevel']) const rootTarget = await this.ctx.fs.resolve(rootOutput.stdout.replace(/\r?\n$/, ''), { cwd, signal }) const repositoryRoot = this.ctx.fs.processPath(rootTarget) + if (fetch) { + await fetchRemoteBranch(run, repositoryRoot, revision) + onPhase?.('prepare') + } const base = await run(repositoryRoot, ['rev-parse', '--verify', '--end-of-options', `${revision}^{commit}`]) const baseCommit = base.stdout.trim() const existing = await run(repositoryRoot, ['show-ref', '--verify', '--quiet', `refs/heads/${branch}`], [0, 1]) @@ -297,7 +312,7 @@ export class WorktreeService extends Service { agent: Agent, { path, branch, baseCommit, repositoryRoot }: RestoreWorktreeRequest, signal: AbortSignal, - onPhase: ((phase: CreateWorktreePhase) => void) | undefined, + onPhase: ((phase: Exclude) => void) | undefined, ): Promise { onPhase?.('prepare') const policy = this.ctx.sandboxPolicy.resolve({ session: agent.session }) @@ -378,6 +393,32 @@ async function assertBranchName(run: GitRun, directory: string, branch: string, if (checked.exitCode !== 0) throw new WorktreeError(`${field} must be a valid Git branch name`, 'WORKTREE_INVALID_ARGUMENT') } +/** + * Fetch one remote branch into its remote-tracking branch, without tags, submodules, `FETCH_HEAD`, or automatic + * maintenance. + * @param run - confined Git runner. + * @param repositoryRoot - root of the source checkout. + * @param ref - remote-tracking branch `refs/remotes//`. + * @throws {WorktreeError} `WORKTREE_INVALID_ARGUMENT` when no configured remote owns `ref`; the command's failure when + * listing the remotes or fetching fails. + */ +async function fetchRemoteBranch(run: GitRun, repositoryRoot: string, ref: string): Promise { + const rest = ref.slice(REMOTE_REFS.length) + const listed = await run(repositoryRoot, ['remote']) + // A remote name may contain slashes, so the longest configured name that owns the ref wins. + const [remote] = listed.stdout.split(/\r?\n/) + .filter(name => name.length > 0 && rest.startsWith(`${name}/`)) + .sort((left, right) => right.length - left.length) + const branch = remote === undefined ? '' : rest.slice(remote.length + 1) + if (remote === undefined || !relativePath(branch)) { + throw new WorktreeError(`worktree from is not a remote-tracking branch of a configured remote: ${ref}`, 'WORKTREE_INVALID_ARGUMENT') + } + await run(repositoryRoot, [ + 'fetch', '--quiet', '--no-tags', '--no-recurse-submodules', '--no-write-fetch-head', '--no-auto-maintenance', + '--end-of-options', remote, `+refs/heads/${branch}:${ref}`, + ]) +} + /** * Add retained-artifact context to a failure without changing its routable identity: * a `HarnessError` keeps its `name` and `code`, and caller cancellation stays an `AbortError`. diff --git a/packages/experimental/worktree/src/types.ts b/packages/experimental/worktree/src/types.ts index da85333e13..da503acaf5 100644 --- a/packages/experimental/worktree/src/types.ts +++ b/packages/experimental/worktree/src/types.ts @@ -1,11 +1,16 @@ /** Public requests and results for creating a Git worktree and entering it, and for restoring a removed one. */ -/** A new checkout from a locally available Git commit, branch, or tag. */ +/** A new checkout from a locally available Git commit, branch, or tag, or from a remote branch fetched first. */ export interface CreateWorktreeRequest { /** New branch name, also used as the relative checkout directory; omission generates a name. */ name?: string /** Local revision to resolve before creation; omission selects HEAD. */ from?: string + /** + * Fetch `from` from its remote before resolving it. `from` must then be the full name of a remote-tracking + * branch, `refs/remotes//`, of a configured remote; only that branch is fetched, without tags. + */ + fetch?: boolean } /** Committed Git baseline and the calling Session's resulting working directory. */ @@ -21,12 +26,13 @@ export interface CreatedWorktree { } /** - * Stage of one creation or restoration, reported before it begins: `prepare` + * Stage of one creation or restoration, reported before it begins: `fetch` + * fetches the remote base branch of a creation that asks for it; `prepare` * validates the request, allocates the checkout directory, and creates the * branch, which a restoration creates again only when it is gone; `checkout` * writes the files and, for a creation, enters the checkout. */ -export type CreateWorktreePhase = 'prepare' | 'checkout' +export type CreateWorktreePhase = 'fetch' | 'prepare' | 'checkout' /** A removed checkout to check out again at its recorded directory. */ export interface RestoreWorktreeRequest { diff --git a/packages/experimental/worktree/tests/worktree.spec.ts b/packages/experimental/worktree/tests/worktree.spec.ts index e2da8a2268..25115bf779 100644 --- a/packages/experimental/worktree/tests/worktree.spec.ts +++ b/packages/experimental/worktree/tests/worktree.spec.ts @@ -426,6 +426,93 @@ describe('creating and entering retained worktrees', () => { }) }) +describe('fetching the remote base branch first', () => { + /** A clone of a new repository, which then gains a commit, a tag, and a branch that the clone has not fetched. */ + async function behindClone(origin = 'origin'): Promise<{ upstream: string; clone: string; fetched: string }> { + const upstream = await repo() + const clone = join(upstream, 'clone') + await git(upstream, 'clone', '--origin', origin, pathToFileURL(upstream).href, clone) + // As `repository` does: a runner's global newline conversion would otherwise rewrite the files a worktree checks out. + await git(clone, 'config', 'core.autocrlf', 'false') + await writeFile(join(upstream, 'tracked.txt'), 'remote\n') + await git(upstream, 'commit', '-am', 'remote') + await git(upstream, 'tag', 'v1') + await git(upstream, 'branch', 'other') + return { upstream, clone, fetched: await git(upstream, 'rev-parse', 'HEAD') } + } + + it('fetches only the chosen branch, without tags, then pins and checks out the fetched commit without an upstream', async () => { + const { clone, fetched } = await behindClone() + ctx = await harness(clone) + const agent = testAgent(ctx, clone) + const phases: string[] = [] + + const result = await ctx.worktrees.create(agent, { name: 'fresh', from: 'refs/remotes/origin/main', fetch: true }, undefined, (phase) => { + phases.push(phase) + }) + + expect(phases).toEqual(['fetch', 'prepare', 'checkout']) + expect(result.baseCommit).toBe(fetched) + expect(await git(clone, 'rev-parse', 'refs/remotes/origin/main')).toBe(fetched) + expect(await contents(join(result.path, 'tracked.txt'))).toBe('remote\n') + expect(await git(clone, 'tag', '--list')).toBe('') + expect(await git(clone, 'for-each-ref', '--format=%(refname)', 'refs/remotes/origin/other')).toBe('') + expect(existsSync(join(clone, '.git', 'FETCH_HEAD'))).toBe(false) + await expect(git(clone, 'config', '--get', 'branch.fresh.merge')).rejects.toThrow() + }) + + it('fetches from the longest configured remote name that owns the branch', async () => { + const { upstream, clone, fetched } = await behindClone('team/fork') + // Newer `git remote add` refuses a name nested with another remote's, but configuration written earlier or by hand + // can hold both. + await git(clone, 'config', 'remote.team.url', join(upstream, 'missing.git')) + await git(clone, 'config', 'remote.team.fetch', '+refs/heads/*:refs/remotes/team/*') + ctx = await harness(clone) + const agent = testAgent(ctx, clone) + + const result = await ctx.worktrees.create(agent, { name: 'forked', from: 'refs/remotes/team/fork/main', fetch: true }) + + expect(result.baseCommit).toBe(fetched) + expect(await git(clone, 'rev-parse', 'refs/remotes/team/fork/main')).toBe(fetched) + }) + + it('refuses a base that is not a remote-tracking branch of a configured remote', async () => { + const { clone } = await behindClone() + ctx = await harness(clone) + const agent = testAgent(ctx, clone) + const phases: string[] = [] + const record = (phase: string): void => { phases.push(phase) } + + await expect(ctx.worktrees.create(agent, { name: 'local', from: 'main', fetch: true }, undefined, record)) + .rejects.toMatchObject({ code: 'WORKTREE_INVALID_ARGUMENT' }) + expect(phases).toEqual([]) + for (const from of ['refs/remotes/gone/main', 'refs/remotes/origin/']) { + await expect(ctx.worktrees.create(agent, { name: 'stray', from, fetch: true }, undefined, record)) + .rejects.toMatchObject({ code: 'WORKTREE_INVALID_ARGUMENT', message: expect.stringContaining(from) as string }) + } + expect(phases).toEqual(['fetch', 'fetch']) + expect(ctx.workingDirectory.get(agent.session)).toBe(clone) + expect(await git(clone, 'branch', '--list', 'stray')).toBe('') + }) + + it('reports a failed fetch without creating a branch, a checkout, or the pool', async () => { + const { upstream, clone } = await behindClone() + await git(clone, 'remote', 'set-url', 'origin', join(upstream, 'missing.git')) + ctx = await harness(clone) + const agent = testAgent(ctx, clone) + const phases: string[] = [] + + await expect(ctx.worktrees.create(agent, { name: 'offline', from: 'refs/remotes/origin/main', fetch: true }, undefined, (phase) => { + phases.push(phase) + })).rejects.toMatchObject({ code: 'WORKTREE_COMMAND_FAILED' }) + + expect(phases).toEqual(['fetch']) + expect(await git(clone, 'branch', '--list', 'offline')).toBe('') + expect(existsSync(join(clone, '.agents'))).toBe(false) + expect(ctx.workingDirectory.get(agent.session)).toBe(clone) + }) +}) + describe('restoring removed worktrees', () => { /** The checkout directories Git registers for `root`, in Git's notation. */ async function registered(root: string): Promise { diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 9f22b44801..380ae763a4 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -1491,11 +1491,11 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ returns: 'the cleanup state, or null without a worktree service, an attempt, or a current revision.', }, { - signature: '@Remote async branches(session: Session, signal: AbortSignal): Promise', - description: 'List the local branches that can start a worktree of the Session\'s current checkout.', - parameters: [{ name: 'session', description: 'Session whose current directory is listed.' }, { name: 'signal', description: 'request cancellation.' }], - returns: 'the checked-out branch and at most `maxBranches` local branches, the checked-out one first.', - throws: ['when the current directory is not inside a checkout or Git fails.'], + signature: '@Remote async worktreeBases(session: Session, query: string, signal: AbortSignal): Promise', + description: 'List the branches that can start a worktree of the Session\'s current checkout: the checked-out branch, each remote\'s default branch, other local branches, and each remote\'s other remote-tracking branches, remotes in the order the panel recognizes code hosts.', + parameters: [{ name: 'session', description: 'Session whose checkout is read.' }, { name: 'query', description: 'text the branch names must contain, ignoring case; empty for every branch.' }, { name: 'signal', description: 'request cancellation.' }], + returns: 'the branches, at most `maxBranches` local branches and `maxBranches` per remote, most recently committed first.', + throws: ['`forgePanel/not-a-checkout` outside a checkout; the Git error when Git fails or the listed refs exceed `maxDiffBytes`.'], }, { signature: '@Remote async diffBases(session: Session, query: string, signal: AbortSignal): Promise', @@ -1661,10 +1661,10 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ throws: ['`forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; `forgePanel/stale-head` when the head moved past `headSha`; `forgePanel/action-failed` with the host\'s reason when the host refuses, cannot be reached, or updates no branches; `forgePanel/action-unknown` when the host did not confirm whether it started the update.'], }, { - signature: '@Remote async requestWorktree(session: Session, from: string | null, signal: AbortSignal): Promise', - description: 'Ask for a new worktree before the Session\'s first turn, replacing an open request and forgetting a failed attempt. While the next message waits in the inbox, or else at the first step proposal, the panel creates a branch from `from`, or from HEAD of the current checkout when it is null, and enters its checkout. A message that already waits after a failed or stopped attempt keeps waiting for ForgePanelController.retryWorktree.', - parameters: [{ name: 'session', description: 'Session without a started turn.' }, { name: 'from', description: 'local base branch, or null for HEAD.' }, { name: 'signal', description: 'request cancellation.' }], - throws: ['`forgePanel/invalid-branch` when `from` is empty; `forgePanel/worktrees-unavailable` without a worktree service; `forgePanel/session-started` after a turn started or the worktree was created; `forgePanel/session-busy` while the worktree is being created.'], + signature: '@Remote async requestWorktree(session: Session, from: string | null, name: string | null, signal: AbortSignal): Promise', + description: 'Ask for a new worktree before the Session\'s first turn, replacing an open request and forgetting a failed attempt. While the next message waits in the inbox, or else at the first step proposal, the panel creates the branch `name`, or a generated branch per attempt when it is null, from `from`, or from HEAD of the current checkout when it is null, and enters its checkout; a remote-tracking `from` is fetched first. A message that already waits after a failed or stopped attempt keeps waiting for ForgePanelController.retryWorktree.', + parameters: [{ name: 'session', description: 'Session without a started turn.' }, { name: 'from', description: 'full name of a local or remote-tracking base branch, or null for HEAD.' }, { name: 'name', description: 'new branch name, or null to generate one per attempt.' }, { name: 'signal', description: 'request cancellation.' }], + throws: ['`forgePanel/invalid-branch` when `from` is empty; `forgePanel/invalid-name` when `name` breaks a branch-name rule; `forgePanel/branch-exists` when the checkout has a local branch named `name`; `forgePanel/not-a-checkout` when a name is checked outside a checkout; `forgePanel/worktrees-unavailable` without a worktree service; `forgePanel/session-started` after a turn started or the worktree was created; `forgePanel/session-busy` while the worktree is being created.'], }, { signature: '@Remote async cancelWorktree(session: Session, signal: AbortSignal): Promise', @@ -1678,9 +1678,9 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ parameters: [{ name: 'session', description: 'Session whose creation stops.' }, { name: 'signal', description: 'request cancellation.' }], }, { - signature: '@Remote async retryWorktree(session: Session, signal: AbortSignal): Promise', - description: 'Make another attempt, with a new branch name, at the worktree a message of the Session waits for after a failed or stopped attempt.', - parameters: [{ name: 'session', description: 'Session whose message waits.' }, { name: 'signal', description: 'request cancellation.' }], + signature: '@Remote async retryWorktree(session: Session, fetch: boolean, signal: AbortSignal): Promise', + description: 'Make another attempt, on the requested branch name or a new generated one, at the worktree a message of the Session waits for after a failed or stopped attempt.', + parameters: [{ name: 'session', description: 'Session whose message waits.' }, { name: 'fetch', description: 'false skips fetching a remote-tracking base branch for this attempt, which then starts from the commit last fetched.' }, { name: 'signal', description: 'request cancellation.' }], throws: ['`forgePanel/not-waiting` when no message waits or an attempt is running.'], }, { @@ -5090,15 +5090,15 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ methods: [ { signature: 'async create( agent: Agent, request: CreateWorktreeRequest = {}, signal?: AbortSignal, onPhase?: (phase: CreateWorktreePhase) => void, ): Promise', - description: 'Create a fresh branch and checkout at a pinned local revision, then enter it. Existing branches or checkout paths fail. Uncommitted files stay in the source checkout. Checkout disables configured clean, smudge, and process filters without changing Git config. Repository-local replacement refs still apply; baseCommit reports the resolved object name. The new checkout becomes current only after Git setup succeeds. Failures may retain newly allocated Git/filesystem artifacts; no branch or checkout is removed automatically.', - parameters: [{ name: 'agent', description: 'caller whose current directory selects the source repository and file policy.' }, { name: 'request', description: 'optional new name and local revision; defaults are generated name and HEAD.' }, { name: 'signal', description: 'cancellation of lookup, creation, and working-directory publication.' }, { name: 'onPhase', description: 'receives each stage before it begins; it must not throw.' }], + description: 'Create a fresh branch and checkout at a pinned local revision, then enter it. A request that asks to fetch first fetches its remote-tracking branch, only that branch and without tags, then pins the fetched commit. Existing branches or checkout paths fail. Uncommitted files stay in the source checkout. Checkout disables configured clean, smudge, and process filters without changing Git config. Repository-local replacement refs still apply; baseCommit reports the resolved object name. The new checkout becomes current only after Git setup succeeds. Failures may retain newly allocated Git/filesystem artifacts; no branch or checkout is removed automatically.', + parameters: [{ name: 'agent', description: 'caller whose current directory selects the source repository and file policy.' }, { name: 'request', description: 'optional new name, local revision, and fetch switch; defaults are generated name, HEAD, and no fetch.' }, { name: 'signal', description: 'cancellation of lookup, creation, and working-directory publication.' }, { name: 'onPhase', description: 'receives each stage before it begins; it must not throw.' }], returns: 'canonical checkout path, branch name, pinned commit, and source repository root.', - throws: ['{WorktreeError} for an invalid request, an existing branch or path, or a failed, oversized, or timed-out command; a failure after allocation keeps its `name` and `code` and adds retained-artifact context.'], + throws: ['{WorktreeError} for an invalid request, a fetch request whose `from` is not a remote-tracking branch of a configured remote, an existing branch or path, or a failed, oversized, or timed-out command, including the fetch; a failure after allocation keeps its `name` and `code` and adds retained-artifact context.'], }, { - signature: 'async restore( agent: Agent, request: RestoreWorktreeRequest, signal?: AbortSignal, onPhase?: (phase: CreateWorktreePhase) => void, ): Promise', + signature: 'async restore( agent: Agent, request: RestoreWorktreeRequest, signal?: AbortSignal, onPhase?: (phase: Exclude) => void, ): Promise', description: 'Check out a removed worktree again at its recorded directory: its branch when the branch still exists, otherwise a new branch of the same name at `baseCommit`. Only the missing target\'s unlocked registration is removed, and an existing directory fails. Changes that were never committed are not recovered. Checkout disables configured clean, smudge, and process filters, as creation does. The calling Session\'s working directory does not change. Failures may retain newly allocated Git/filesystem artifacts.', - parameters: [{ name: 'agent', description: 'caller whose sandbox policy confines the commands.' }, { name: 'request', description: 'recorded directory, branch, base commit, and source repository root.' }, { name: 'signal', description: 'cancellation of the restoration.' }, { name: 'onPhase', description: 'receives each stage before it begins; it must not throw.' }], + parameters: [{ name: 'agent', description: 'caller whose sandbox policy confines the commands.' }, { name: 'request', description: 'recorded directory, branch, base commit, and source repository root.' }, { name: 'signal', description: 'cancellation of the restoration.' }, { name: 'onPhase', description: 'receives each stage before it begins, never `fetch`; it must not throw.' }], returns: 'the directory and whether the branch was created again.', throws: ['{WorktreeError} for an invalid request, an existing path, a locked registration, or a failed, oversized, or timed-out command; a failure after allocation keeps its `name` and `code` and adds retained-artifact context.'], }, @@ -6740,11 +6740,11 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'CreateWorktreePhase', - declaration: 'export type CreateWorktreePhase = \'prepare\' | \'checkout\';', + declaration: 'export type CreateWorktreePhase = \'fetch\' | \'prepare\' | \'checkout\';', }, { name: 'CreateWorktreeRequest', - declaration: 'export interface CreateWorktreeRequest {\n name?: string;\n from?: string;\n}', + declaration: 'export interface CreateWorktreeRequest {\n name?: string;\n from?: string;\n fetch?: boolean;\n}', }, { name: 'CredentialInfo', @@ -7034,10 +7034,6 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'ForgeBaseBranches', declaration: 'export interface ForgeBaseBranches {\n readonly automatic: ForgeAutomaticBase | null;\n readonly remote: readonly ForgeBaseBranch[];\n readonly local: readonly ForgeBaseBranch[];\n}', }, - { - name: 'ForgeBranches', - declaration: 'export interface ForgeBranches {\n readonly current: string | null;\n readonly branches: readonly string[];\n}', - }, { name: 'ForgeChangedFile', declaration: 'export interface ForgeChangedFile {\n readonly path: string;\n readonly additions: number;\n readonly deletions: number;\n readonly binary: boolean;\n}', @@ -7204,7 +7200,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'ForgePanelWorktree', - declaration: 'export interface ForgePanelWorktree {\n readonly editable: boolean;\n readonly blocker: ForgeWorktreeBlocker | null;\n readonly request: ForgeWorktreeRequest | null;\n readonly created: ForgeSessionWorktree | null;\n readonly creation: ForgeWorktreeCreation | null;\n readonly failure: ForgeWorktreeFailure | null;\n readonly missing: ForgeMissingWorktree | null;\n readonly restoration: ForgeWorktreeRestoration | null;\n readonly waiting: ForgeWorktreeWaiting | null;\n}', + declaration: 'export interface ForgePanelWorktree {\n readonly editable: boolean;\n readonly blocker: ForgeWorktreeBlocker | null;\n readonly namePrefix: string;\n readonly request: ForgeWorktreeRequest | null;\n readonly created: ForgeSessionWorktree | null;\n readonly creation: ForgeWorktreeCreation | null;\n readonly failure: ForgeWorktreeFailure | null;\n readonly missing: ForgeMissingWorktree | null;\n readonly restoration: ForgeWorktreeRestoration | null;\n readonly waiting: ForgeWorktreeWaiting | null;\n}', }, { name: 'ForgePendingReview', @@ -7222,6 +7218,14 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'ForgeRegisteredLens', declaration: 'export interface ForgeRegisteredLens {\n readonly id: string;\n readonly version: string;\n}', }, + { + name: 'ForgeRemoteBranches', + declaration: 'export interface ForgeRemoteBranches {\n readonly name: string;\n readonly repository: string | null;\n readonly branches: readonly ForgeBaseBranch[];\n}', + }, + { + name: 'ForgeRemoteDefault', + declaration: 'export interface ForgeRemoteDefault extends ForgeBaseBranch {\n readonly remote: string;\n}', + }, { name: 'ForgeRepository', declaration: 'export interface ForgeRepository {\n readonly forge: string;\n readonly host: string;\n readonly owner: string;\n readonly name: string;\n}', @@ -7298,21 +7302,25 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'ForgeViewedState', declaration: 'export type ForgeViewedState = \'viewed\' | \'unviewed\' | \'dismissed\';', }, + { + name: 'ForgeWorktreeBases', + declaration: 'export interface ForgeWorktreeBases {\n readonly current: ForgeBaseBranch | null;\n readonly defaults: readonly ForgeRemoteDefault[];\n readonly local: readonly ForgeBaseBranch[];\n readonly remotes: readonly ForgeRemoteBranches[];\n}', + }, { name: 'ForgeWorktreeBlocker', declaration: 'export type ForgeWorktreeBlocker = \'not-git\' | \'outside-writable-root\' | \'read-only\';', }, { name: 'ForgeWorktreeCreation', - declaration: 'export interface ForgeWorktreeCreation {\n readonly phase: \'prepare\' | \'checkout\';\n readonly branch: string;\n readonly from: string | null;\n readonly held: boolean;\n}', + declaration: 'export interface ForgeWorktreeCreation {\n readonly phase: \'fetch\' | \'prepare\' | \'checkout\';\n readonly branch: string;\n readonly from: string | null;\n readonly fetch: boolean;\n readonly held: boolean;\n}', }, { name: 'ForgeWorktreeFailure', - declaration: 'export interface ForgeWorktreeFailure {\n readonly branch: string | null;\n readonly from: string | null;\n readonly phase: \'prepare\' | \'checkout\';\n readonly message: string;\n}', + declaration: 'export interface ForgeWorktreeFailure {\n readonly branch: string | null;\n readonly from: string | null;\n readonly fetch: boolean;\n readonly phase: \'fetch\' | \'prepare\' | \'checkout\';\n readonly message: string;\n readonly exists: boolean;\n}', }, { name: 'ForgeWorktreeRequest', - declaration: 'export interface ForgeWorktreeRequest {\n readonly from: string | null;\n}', + declaration: 'export interface ForgeWorktreeRequest {\n readonly from: string | null;\n readonly name: string | null;\n}', }, { name: 'ForgeWorktreeRestoration', diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index a5a4b2e307..a42817d7e9 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -436,7 +436,9 @@ export const LINK_MAP: Readonly> = { ForgeReviewRequest: 'forge.md', ForgeReviewResult: 'forge.md', ForgeBaseBranches: 'forge.md', - ForgeBranches: 'forge.md', + ForgeRemoteBranches: 'forge.md', + ForgeRemoteDefault: 'forge.md', + ForgeWorktreeBases: 'forge.md', ForgeChangeRequestDiff: 'forge.md', ForgeCommit: 'forge.md', ForgeCommitList: 'forge.md', diff --git a/scripts/type-equiv.manifest.json b/scripts/type-equiv.manifest.json index 5c59990dc2..05227e60b8 100644 --- a/scripts/type-equiv.manifest.json +++ b/scripts/type-equiv.manifest.json @@ -2771,7 +2771,17 @@ }, { "doc": "docs/subsystems/forge.md", - "symbol": "ForgeBranches", + "symbol": "ForgeWorktreeBases", + "source": "packages/experimental/client-ui-forge/src/types.ts" + }, + { + "doc": "docs/subsystems/forge.md", + "symbol": "ForgeRemoteDefault", + "source": "packages/experimental/client-ui-forge/src/types.ts" + }, + { + "doc": "docs/subsystems/forge.md", + "symbol": "ForgeRemoteBranches", "source": "packages/experimental/client-ui-forge/src/types.ts" }, {