diff --git a/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.i18n.yaml index cccd955846..510cb78fd5 100644 --- a/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.i18n.yaml @@ -15,8 +15,8 @@ en: 0e1399cad4151f87 zh: 960fa0ccbe0f8fea /agent-note-cooperative-tool-cancellation-at-the-registry-boundary/decision/cancellation-codes-record-whether-dispatch-occurred: - en: 86c5566581c1d3d6 - zh: 3cb71fbb97bdb291 + en: 4d8436958c27f98e + zh: cd4ed8238428a2c4 /agent-note-cooperative-tool-cancellation-at-the-registry-boundary/decision/pre-aborted-entry-short-circuits-after-materialization: en: 53362db6a0c71698 zh: 311de45ca26d3fdc diff --git a/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.md b/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.md index 3f4fbcc597..72a99de358 100644 --- a/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.md +++ b/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.md @@ -32,7 +32,7 @@ An around-dispatch wrapper may replace `exec.signal` for its delegated lifetime `ABORTED_BEFORE_DISPATCH` carries `{ name: 'AbortError' }` and model text `Error: tool call aborted before dispatch`. It applies whenever cancellation prevents body invocation, including pre-aborted entry, cancellation during pre-policy or approval, an aborted wrapper signal, a wrapper success overtaken by caller cancellation before delegation, and agent-loop siblings skipped after turn cancellation. -`ABORTED` carries model text `Error: tool call aborted` and applies only after the body was invoked, including cancellation while an around wrapper or post-policy listener waits after body completion. A started body that throws the signal's reason or an `Error` named `AbortError` without `HarnessError` identity keeps that message and carries `{ name: 'AbortError', code: 'ABORTED' }`. A denial, wrapper failure, other tool failure, or post-policy failure remains more specific than generic cancellation. A timeout owned by timeout-policy remains `TOOL_TIMEOUT`, and contexts deferred before a successful outcome is replaced remain attached. +`ABORTED` carries model text `Error: tool call aborted` and applies only after the body was invoked, including cancellation while an around wrapper or post-policy listener waits after body completion. A started body that throws the signal's reason or an `Error` named `AbortError` without `HarnessError` identity keeps that message and carries `{ name: 'AbortError', code: 'ABORTED' }`. A `tools/execute` wrapper that throws such a value after caller cancellation is classified the same way, with `ABORTED_BEFORE_DISPATCH` when the body never started. A denial, other wrapper failure, other tool failure, or post-policy failure remains more specific than generic cancellation. A timeout owned by timeout-policy remains `TOOL_TIMEOUT`, and contexts deferred before a successful outcome is replaced remain attached. ### Pre-aborted entry short-circuits after materialization diff --git a/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.zh.md b/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.zh.md index 15856a1cce..d098a385da 100644 --- a/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.zh.md @@ -32,7 +32,7 @@ Status: implemented `ABORTED_BEFORE_DISPATCH` 携带 `{ name: 'AbortError' }` 和模型可见文本 `Error: tool call aborted before dispatch`。凡取消阻止工具主体调用时都使用该结果,包括进入时已中止、前置策略或审批期间取消、包装层信号已中止、包装层在委托前返回的成功结果被调用方取消抢先,以及轮次取消后 agent loop(智能体循环)跳过的同批调用。 -`ABORTED` 携带模型可见文本 `Error: tool call aborted`,并且只在工具主体已经调用后使用,包括工具主体完成后环绕包装层或后置策略监听器等待期间发生的取消。已开始的工具主体抛出 signal 的 reason,或不具备 `HarnessError` 身份、name 为 `AbortError` 的 `Error` 时,结果保留该 message,并携带 `{ name: 'AbortError', code: 'ABORTED' }`。拒绝、包装层失败、其他工具失败或后置策略失败比通用取消更具体。timeout-policy 自身拥有的超时仍为 `TOOL_TIMEOUT`,成功结果被取消替换前延后附加的上下文仍会保留。 +`ABORTED` 携带模型可见文本 `Error: tool call aborted`,并且只在工具主体已经调用后使用,包括工具主体完成后环绕包装层或后置策略监听器等待期间发生的取消。已开始的工具主体抛出 signal 的 reason,或不具备 `HarnessError` 身份、name 为 `AbortError` 的 `Error` 时,结果保留该 message,并携带 `{ name: 'AbortError', code: 'ABORTED' }`。`tools/execute` 包装层在调用方取消后抛出这类值时按同样方式归类,工具主体尚未开始时为 `ABORTED_BEFORE_DISPATCH`。拒绝、其他包装层失败、其他工具失败或后置策略失败比通用取消更具体。timeout-policy 自身拥有的超时仍为 `TOOL_TIMEOUT`,成功结果被取消替换前延后附加的上下文仍会保留。 ### 进入时已中止会在物化后短路 diff --git a/.agents/skills/dsh-error-handling/SKILL.md b/.agents/skills/dsh-error-handling/SKILL.md index 67cf503d7a..4312455bed 100644 --- a/.agents/skills/dsh-error-handling/SKILL.md +++ b/.agents/skills/dsh-error-handling/SKILL.md @@ -17,7 +17,7 @@ Convert foreign failures where the dependency is owned. Node errno, SDK, protoco ## Tool failures -The tool registry keeps `error.name` and `error.code` on `tool/result` when the producer supplies them: a `HarnessError` thrown by the tool body, a pre-execute `deny`, guard denial, or post-execute block with `info` (including the registry's approval denials, `ApprovalError` with `APPROVAL_REJECTED`, `APPROVAL_CANCELLED`, or `APPROVAL_UNAVAILABLE`), the registry's own cancellation result (`AbortError` with `ABORTED` or `ABORTED_BEFORE_DISPATCH`, also applied to a signal reason or an `Error` named `AbortError` that the body throws after cancellation), or a `tools/execute` wrapper result such as the timeout policy's `TOOL_TIMEOUT`. Any other thrown value, and a guard denial or block without `info`, persist only text that retry policy, UI, and analytics cannot route on. Every expected failure reachable from a tool body therefore throws a `HarnessError`, normally the owning domain's subclass: +The tool registry keeps `error.name` and `error.code` on `tool/result` when the producer supplies them: a `HarnessError` thrown by the tool body, a pre-execute `deny`, guard denial, or post-execute block with `info` (including the registry's approval denials, `ApprovalError` with `APPROVAL_REJECTED`, `APPROVAL_CANCELLED`, or `APPROVAL_UNAVAILABLE`), the registry's own cancellation result (`AbortError` with `ABORTED` or `ABORTED_BEFORE_DISPATCH`, also applied to a signal reason or an `Error` named `AbortError` that the body or a `tools/execute` wrapper throws after cancellation), or a `tools/execute` wrapper result such as the timeout policy's `TOOL_TIMEOUT`. Any other thrown value, and a guard denial or block without `info`, persist only text that retry policy, UI, and analytics cannot route on. Every expected failure reachable from a tool body therefore throws a `HarnessError`, normally the owning domain's subclass: - Hand-checked argument constraints throw `ToolArgsError` (`INVALID_ARGS`) from `dsh-tools`. - Missing composition or caller context, such as an absent Agent, service, or open turn, throws `ToolContextUnavailableError` (`TOOL_CONTEXT_UNAVAILABLE`) from `dsh-tools`. diff --git a/docs/config-catalog.md b/docs/config-catalog.md index fceecbc280..297101428e 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1068,7 +1068,7 @@ export type Config = BrowserMcpConfig - `inject`: `browserUse` · `agents` · `tools` · `systemPrompt` - `refs`: `ModelConfig` (`@browserbasehq/stagehand`) -- `source`: [`packages/experimental/browser-use-stagehand-native/src/index.ts:29`](../packages/experimental/browser-use-stagehand-native/src/index.ts) +- `source`: [`packages/experimental/browser-use-stagehand-native/src/index.ts:32`](../packages/experimental/browser-use-stagehand-native/src/index.ts) ```ts config-catalog /** Profile-owned browser connection and independent Stagehand model credentials. */ @@ -1471,7 +1471,7 @@ export interface Config { ## `@deepseek-ai/dsh-experimental-subagent-oar` - `inject`: `subagents` -- `source`: [`packages/experimental/subagent-oar/src/index.ts:25`](../packages/experimental/subagent-oar/src/index.ts) +- `source`: [`packages/experimental/subagent-oar/src/index.ts:27`](../packages/experimental/subagent-oar/src/index.ts) ```ts config-catalog /** Native runtime selection and deployment settings for one provider instance. */ @@ -1559,7 +1559,7 @@ export type PaidTranslationProvider = 'deepseek-account' | 'deepseek-official' - `inject`: `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `sessionProjections` - `refs`: `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/experimental/worktree/src/index.ts:36`](../packages/experimental/worktree/src/index.ts) +- `source`: [`packages/experimental/worktree/src/index.ts:39`](../packages/experimental/worktree/src/index.ts) ```ts config-catalog /** Worktree location, generated names, executables, subprocess resource limits, and the archive cleanup switch. */ @@ -1722,7 +1722,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:53`](../packages/experimental/hooks-claude-code/src/index.ts) ```ts config-catalog /** Plugin config: where the CC hook config lives + substitution roots. */ @@ -1761,7 +1761,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:52`](../packages/experimental/hooks-codex/src/index.ts) ```ts config-catalog /** Plugin config: where the Codex hooks.json lives + the model name for payloads. */ @@ -4458,7 +4458,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-ralph` - `inject`: `tools` · `workflowEngine` · `subagents` · `systemPrompt` -- `source`: [`packages/experimental/tool-ralph/src/index.ts:21`](../packages/experimental/tool-ralph/src/index.ts) +- `source`: [`packages/experimental/tool-ralph/src/index.ts:24`](../packages/experimental/tool-ralph/src/index.ts) ```ts config-catalog /** Deployment policy for the fixed Ralph workflow. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index c4afa51973..d28138f61c 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1070,7 +1070,7 @@ export type Config = BrowserMcpConfig - `inject`: `browserUse` · `agents` · `tools` · `systemPrompt` - `refs`: `ModelConfig` (`@browserbasehq/stagehand`) -- `source`: [`packages/experimental/browser-use-stagehand-native/src/index.ts:29`](../packages/experimental/browser-use-stagehand-native/src/index.ts) +- `source`: [`packages/experimental/browser-use-stagehand-native/src/index.ts:32`](../packages/experimental/browser-use-stagehand-native/src/index.ts) ```ts config-catalog /** Profile-owned browser connection and independent Stagehand model credentials. */ @@ -1473,7 +1473,7 @@ export interface Config { ## `@deepseek-ai/dsh-experimental-subagent-oar` - `inject`: `subagents` -- `source`: [`packages/experimental/subagent-oar/src/index.ts:25`](../packages/experimental/subagent-oar/src/index.ts) +- `source`: [`packages/experimental/subagent-oar/src/index.ts:27`](../packages/experimental/subagent-oar/src/index.ts) ```ts config-catalog /** Native runtime selection and deployment settings for one provider instance. */ @@ -1561,7 +1561,7 @@ export type PaidTranslationProvider = 'deepseek-account' | 'deepseek-official' - `inject`: `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `sessionProjections` - `refs`: `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/experimental/worktree/src/index.ts:36`](../packages/experimental/worktree/src/index.ts) +- `source`: [`packages/experimental/worktree/src/index.ts:39`](../packages/experimental/worktree/src/index.ts) ```ts config-catalog /** Worktree location, generated names, executables, subprocess resource limits, and the archive cleanup switch. */ @@ -1724,7 +1724,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:53`](../packages/experimental/hooks-claude-code/src/index.ts) ```ts config-catalog /** Plugin config: where the CC hook config lives + substitution roots. */ @@ -1763,7 +1763,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:52`](../packages/experimental/hooks-codex/src/index.ts) ```ts config-catalog /** Plugin config: where the Codex hooks.json lives + the model name for payloads. */ @@ -4460,7 +4460,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-ralph` - `inject`: `tools` · `workflowEngine` · `subagents` · `systemPrompt` -- `source`: [`packages/experimental/tool-ralph/src/index.ts:21`](../packages/experimental/tool-ralph/src/index.ts) +- `source`: [`packages/experimental/tool-ralph/src/index.ts:24`](../packages/experimental/tool-ralph/src/index.ts) ```ts config-catalog /** Deployment policy for the fixed Ralph workflow. */ diff --git a/docs/module-graph.md b/docs/module-graph.md index 05f1fc5037..94af2008c7 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -498,7 +498,6 @@ flowchart TD pkg_app_boot --> pkg_launch_environment pkg_client_connection --> pkg_scope pkg_experimental_computer_use_cua_driver_mcp --> pkg_computer_use - pkg_experimental_liveshare --> pkg_scope pkg_anonymous_user_id --> pkg_brand pkg_anonymous_user_id --> pkg_home_paths pkg_storage_domain --> pkg_storage @@ -972,11 +971,17 @@ flowchart TD pkg_experimental_browser_use_playwright_mcp --> pkg_working_directory pkg_experimental_browser_use_stagehand_native --> pkg_agent pkg_experimental_browser_use_stagehand_native --> pkg_browser_use + pkg_experimental_browser_use_stagehand_native --> pkg_error pkg_experimental_browser_use_stagehand_native --> pkg_system_prompt pkg_experimental_browser_use_stagehand_native --> pkg_tools pkg_experimental_computer_use_cua_driver_native --> pkg_computer_use + pkg_experimental_computer_use_cua_driver_native --> pkg_error pkg_experimental_computer_use_cua_driver_native --> pkg_system_prompt pkg_experimental_computer_use_cua_driver_native --> pkg_tools + pkg_experimental_liveshare --> pkg_error + pkg_experimental_liveshare --> pkg_fs + pkg_experimental_liveshare --> pkg_scope + pkg_experimental_liveshare --> pkg_tools pkg_hooks_codex --> pkg_agent pkg_hooks_codex --> pkg_hook_protocol pkg_hooks_codex --> pkg_llm @@ -1124,6 +1129,7 @@ flowchart TD pkg_cua --> pkg_ptc_runtime_node pkg_cua --> pkg_scope pkg_cua --> pkg_tool_executor_ptc + pkg_cua --> pkg_tools pkg_cua --> pkg_user_questions pkg_experimental_auto_review --> pkg_agent pkg_experimental_auto_review --> pkg_agent_instructions @@ -1268,6 +1274,7 @@ flowchart TD pkg_compaction_tool_result_pruner --> pkg_token_meter pkg_experimental_browser_use_runtime --> pkg_agent pkg_experimental_browser_use_runtime --> pkg_browser_use + pkg_experimental_browser_use_runtime --> pkg_error pkg_experimental_browser_use_runtime --> pkg_mcp_client pkg_experimental_browser_use_runtime --> pkg_scope pkg_experimental_browser_use_runtime --> pkg_system_prompt @@ -1275,6 +1282,7 @@ flowchart TD pkg_experimental_browser_use_runtime --> pkg_working_directory pkg_experimental_claude_code_mods --> pkg_agent pkg_experimental_claude_code_mods --> pkg_commands + pkg_experimental_claude_code_mods --> pkg_error pkg_experimental_claude_code_mods --> pkg_fs pkg_experimental_claude_code_mods --> pkg_llm pkg_experimental_claude_code_mods --> pkg_scope @@ -1287,6 +1295,7 @@ flowchart TD pkg_experimental_claude_code_mods --> pkg_user_questions pkg_experimental_claude_code_mods --> pkg_working_directory pkg_experimental_worktree --> pkg_agent + pkg_experimental_worktree --> pkg_error pkg_experimental_worktree --> pkg_fs pkg_experimental_worktree --> pkg_sandbox pkg_experimental_worktree --> pkg_sandbox_policy @@ -1432,6 +1441,7 @@ flowchart TD pkg_experimental_client_ui_forge --> pkg_fs pkg_experimental_client_ui_forge --> pkg_session pkg_experimental_client_ui_forge --> pkg_timeout + pkg_experimental_subagent_oar --> pkg_error pkg_experimental_subagent_oar --> pkg_llm pkg_experimental_subagent_oar --> pkg_session pkg_experimental_subagent_oar --> pkg_subagent @@ -1448,6 +1458,7 @@ flowchart TD pkg_hooks_claude_code --> pkg_tools pkg_hooks_claude_code --> pkg_working_directory pkg_tool_ralph --> pkg_agent + pkg_tool_ralph --> pkg_error pkg_tool_ralph --> pkg_llm pkg_tool_ralph --> pkg_subagent pkg_tool_ralph --> pkg_system_prompt @@ -1713,7 +1724,6 @@ flowchart TD | [`app-boot`](../packages/boot/app-boot) | `boot` | [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) | | [`client-connection`](../packages/client/connection) | `client` | [`scope`](../packages/core/scope) | | [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp) | `experimental` | [`computer-use`](../packages/computer-use/computer-use) | -| [`experimental-liveshare`](../packages/experimental/liveshare) | `experimental` | [`scope`](../packages/core/scope) | | [`anonymous-user-id`](../packages/identity/anonymous-user-id) | `identity` | [`brand`](../packages/util/brand), [`home-paths`](../packages/util/home-paths) | | [`storage-domain`](../packages/storage/storage-domain) | `storage` | [`storage`](../packages/storage/storage) | | [`storage-json`](../packages/storage/storage-json) | `storage` | [`storage`](../packages/storage/storage) | @@ -1844,8 +1854,9 @@ flowchart TD | [`cua-windows`](../packages/experimental/cua-windows) | `experimental` | [`agent`](../packages/core/agent), [`computer-use`](../packages/computer-use/computer-use), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | | [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | -| [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | -| [`experimental-computer-use-cua-driver-native`](../packages/experimental/computer-use-cua-driver-native) | `experimental` | [`computer-use`](../packages/computer-use/computer-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | +| [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`error`](../packages/util/error), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | +| [`experimental-computer-use-cua-driver-native`](../packages/experimental/computer-use-cua-driver-native) | `experimental` | [`computer-use`](../packages/computer-use/computer-use), [`error`](../packages/util/error), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | +| [`experimental-liveshare`](../packages/experimental/liveshare) | `experimental` | [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`scope`](../packages/core/scope), [`tools`](../packages/core/tools) | | [`hooks-codex`](../packages/experimental/hooks-codex) | `experimental` | [`agent`](../packages/core/agent), [`hook-protocol`](../packages/experimental/hook-protocol), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`session-title-all-prompts-llm`](../packages/experimental/session-title-all-prompts-llm) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`session-title-llm`](../packages/session/session-title-llm) | | [`terminal-panel`](../packages/experimental/terminal-panel) | `experimental` | [`api-terminal-controller`](../packages/api/terminal-controller), [`output-retention`](../packages/util/output-retention), [`terminal`](../packages/terminal/terminal), [`tools`](../packages/core/tools) | @@ -1874,7 +1885,7 @@ flowchart TD | [`session-query`](../packages/session-query/session-query) | `session-query` | [`llm`](../packages/llm/llm), [`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-title`](../packages/session/session-title), [`tool-todo`](../packages/todo/tool-todo) | | [`api-settings-controller`](../packages/api/settings-controller) | `api` | [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`credentials`](../packages/credentials/credentials), [`native-command`](../packages/util/native-command), [`session`](../packages/core/session), [`settings`](../packages/settings/settings), [`typert-protocol`](../packages/typert/protocol) | | [`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) | +| [`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), [`tools`](../packages/core/tools), [`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), [`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) | @@ -1895,9 +1906,9 @@ flowchart TD | [`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` | [`error`](../packages/util/error), [`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) | -| [`experimental-browser-use-runtime`](../packages/experimental/browser-use-runtime) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`mcp-client`](../packages/mcp/mcp-client), [`scope`](../packages/core/scope), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | -| [`experimental-claude-code-mods`](../packages/experimental/claude-code-mods) | `experimental` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`storage-domain`](../packages/storage/storage-domain), [`subprocess`](../packages/subprocess/subprocess), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) | -| [`experimental-worktree`](../packages/experimental/worktree) | `experimental` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`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), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess), [`working-directory`](../packages/session/working-directory), [`workspace`](../packages/workspace/workspace) | +| [`experimental-browser-use-runtime`](../packages/experimental/browser-use-runtime) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`error`](../packages/util/error), [`mcp-client`](../packages/mcp/mcp-client), [`scope`](../packages/core/scope), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | +| [`experimental-claude-code-mods`](../packages/experimental/claude-code-mods) | `experimental` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`storage-domain`](../packages/storage/storage-domain), [`subprocess`](../packages/subprocess/subprocess), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) | +| [`experimental-worktree`](../packages/experimental/worktree) | `experimental` | [`agent`](../packages/core/agent), [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`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), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess), [`working-directory`](../packages/session/working-directory), [`workspace`](../packages/workspace/workspace) | | [`tool-session-query`](../packages/experimental/tool-session-query) | `experimental` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-query`](../packages/session-query/session-query), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | | [`webhook-github`](../packages/experimental/webhook-github) | `experimental` | [`credentials`](../packages/credentials/credentials), [`host-webserver`](../packages/host/webserver), [`session`](../packages/core/session), [`webhook`](../packages/experimental/webhook) | | [`mcp-manager`](../packages/mcp/mcp-manager) | `mcp` | [`mcp-client`](../packages/mcp/mcp-client), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`util-values`](../packages/util/values) | @@ -1916,11 +1927,11 @@ flowchart TD | [`session-reference`](../packages/context/session-reference) | `context` | [`agent`](../packages/core/agent), [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`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), [`spill`](../packages/spill/spill), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`typert-protocol`](../packages/typert/protocol) | | [`tool-office`](../packages/document/tool-office) | `document` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`office-kit`](../packages/document/office-kit), [`skill`](../packages/skill/skill), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`experimental-worktree`](../packages/experimental/worktree), [`fs`](../packages/fs/fs), [`session`](../packages/core/session), [`timeout`](../packages/util/timeout) | -| [`experimental-subagent-oar`](../packages/experimental/subagent-oar) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess) | +| [`experimental-subagent-oar`](../packages/experimental/subagent-oar) | `experimental` | [`error`](../packages/util/error), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess) | | [`experimental-tool-subagent-oar`](../packages/experimental/tool-subagent-oar) | `experimental` | [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools) | | [`experimental-tool-worktree`](../packages/experimental/tool-worktree) | `experimental` | [`experimental-worktree`](../packages/experimental/worktree), [`tools`](../packages/core/tools) | | [`hooks-claude-code`](../packages/experimental/hooks-claude-code) | `experimental` | [`agent`](../packages/core/agent), [`hook-protocol`](../packages/experimental/hook-protocol), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | -| [`tool-ralph`](../packages/experimental/tool-ralph) | `experimental` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow) | +| [`tool-ralph`](../packages/experimental/tool-ralph) | `experimental` | [`agent`](../packages/core/agent), [`error`](../packages/util/error), [`llm`](../packages/llm/llm), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow) | | [`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) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index c41bde67ed..e7e929e949 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -500,7 +500,6 @@ flowchart TD pkg_app_boot --> pkg_launch_environment pkg_client_connection --> pkg_scope pkg_experimental_computer_use_cua_driver_mcp --> pkg_computer_use - pkg_experimental_liveshare --> pkg_scope pkg_anonymous_user_id --> pkg_brand pkg_anonymous_user_id --> pkg_home_paths pkg_storage_domain --> pkg_storage @@ -974,11 +973,17 @@ flowchart TD pkg_experimental_browser_use_playwright_mcp --> pkg_working_directory pkg_experimental_browser_use_stagehand_native --> pkg_agent pkg_experimental_browser_use_stagehand_native --> pkg_browser_use + pkg_experimental_browser_use_stagehand_native --> pkg_error pkg_experimental_browser_use_stagehand_native --> pkg_system_prompt pkg_experimental_browser_use_stagehand_native --> pkg_tools pkg_experimental_computer_use_cua_driver_native --> pkg_computer_use + pkg_experimental_computer_use_cua_driver_native --> pkg_error pkg_experimental_computer_use_cua_driver_native --> pkg_system_prompt pkg_experimental_computer_use_cua_driver_native --> pkg_tools + pkg_experimental_liveshare --> pkg_error + pkg_experimental_liveshare --> pkg_fs + pkg_experimental_liveshare --> pkg_scope + pkg_experimental_liveshare --> pkg_tools pkg_hooks_codex --> pkg_agent pkg_hooks_codex --> pkg_hook_protocol pkg_hooks_codex --> pkg_llm @@ -1126,6 +1131,7 @@ flowchart TD pkg_cua --> pkg_ptc_runtime_node pkg_cua --> pkg_scope pkg_cua --> pkg_tool_executor_ptc + pkg_cua --> pkg_tools pkg_cua --> pkg_user_questions pkg_experimental_auto_review --> pkg_agent pkg_experimental_auto_review --> pkg_agent_instructions @@ -1270,6 +1276,7 @@ flowchart TD pkg_compaction_tool_result_pruner --> pkg_token_meter pkg_experimental_browser_use_runtime --> pkg_agent pkg_experimental_browser_use_runtime --> pkg_browser_use + pkg_experimental_browser_use_runtime --> pkg_error pkg_experimental_browser_use_runtime --> pkg_mcp_client pkg_experimental_browser_use_runtime --> pkg_scope pkg_experimental_browser_use_runtime --> pkg_system_prompt @@ -1277,6 +1284,7 @@ flowchart TD pkg_experimental_browser_use_runtime --> pkg_working_directory pkg_experimental_claude_code_mods --> pkg_agent pkg_experimental_claude_code_mods --> pkg_commands + pkg_experimental_claude_code_mods --> pkg_error pkg_experimental_claude_code_mods --> pkg_fs pkg_experimental_claude_code_mods --> pkg_llm pkg_experimental_claude_code_mods --> pkg_scope @@ -1289,6 +1297,7 @@ flowchart TD pkg_experimental_claude_code_mods --> pkg_user_questions pkg_experimental_claude_code_mods --> pkg_working_directory pkg_experimental_worktree --> pkg_agent + pkg_experimental_worktree --> pkg_error pkg_experimental_worktree --> pkg_fs pkg_experimental_worktree --> pkg_sandbox pkg_experimental_worktree --> pkg_sandbox_policy @@ -1434,6 +1443,7 @@ flowchart TD pkg_experimental_client_ui_forge --> pkg_fs pkg_experimental_client_ui_forge --> pkg_session pkg_experimental_client_ui_forge --> pkg_timeout + pkg_experimental_subagent_oar --> pkg_error pkg_experimental_subagent_oar --> pkg_llm pkg_experimental_subagent_oar --> pkg_session pkg_experimental_subagent_oar --> pkg_subagent @@ -1450,6 +1460,7 @@ flowchart TD pkg_hooks_claude_code --> pkg_tools pkg_hooks_claude_code --> pkg_working_directory pkg_tool_ralph --> pkg_agent + pkg_tool_ralph --> pkg_error pkg_tool_ralph --> pkg_llm pkg_tool_ralph --> pkg_subagent pkg_tool_ralph --> pkg_system_prompt @@ -1715,7 +1726,6 @@ flowchart TD | [`app-boot`](../packages/boot/app-boot) | `boot` | [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) | | [`client-connection`](../packages/client/connection) | `client` | [`scope`](../packages/core/scope) | | [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp) | `experimental` | [`computer-use`](../packages/computer-use/computer-use) | -| [`experimental-liveshare`](../packages/experimental/liveshare) | `experimental` | [`scope`](../packages/core/scope) | | [`anonymous-user-id`](../packages/identity/anonymous-user-id) | `identity` | [`brand`](../packages/util/brand), [`home-paths`](../packages/util/home-paths) | | [`storage-domain`](../packages/storage/storage-domain) | `storage` | [`storage`](../packages/storage/storage) | | [`storage-json`](../packages/storage/storage-json) | `storage` | [`storage`](../packages/storage/storage) | @@ -1846,8 +1856,9 @@ flowchart TD | [`cua-windows`](../packages/experimental/cua-windows) | `experimental` | [`agent`](../packages/core/agent), [`computer-use`](../packages/computer-use/computer-use), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | | [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | -| [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | -| [`experimental-computer-use-cua-driver-native`](../packages/experimental/computer-use-cua-driver-native) | `experimental` | [`computer-use`](../packages/computer-use/computer-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | +| [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`error`](../packages/util/error), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | +| [`experimental-computer-use-cua-driver-native`](../packages/experimental/computer-use-cua-driver-native) | `experimental` | [`computer-use`](../packages/computer-use/computer-use), [`error`](../packages/util/error), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | +| [`experimental-liveshare`](../packages/experimental/liveshare) | `experimental` | [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`scope`](../packages/core/scope), [`tools`](../packages/core/tools) | | [`hooks-codex`](../packages/experimental/hooks-codex) | `experimental` | [`agent`](../packages/core/agent), [`hook-protocol`](../packages/experimental/hook-protocol), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`session-title-all-prompts-llm`](../packages/experimental/session-title-all-prompts-llm) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`session-title-llm`](../packages/session/session-title-llm) | | [`terminal-panel`](../packages/experimental/terminal-panel) | `experimental` | [`api-terminal-controller`](../packages/api/terminal-controller), [`output-retention`](../packages/util/output-retention), [`terminal`](../packages/terminal/terminal), [`tools`](../packages/core/tools) | @@ -1876,7 +1887,7 @@ flowchart TD | [`session-query`](../packages/session-query/session-query) | `session-query` | [`llm`](../packages/llm/llm), [`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-title`](../packages/session/session-title), [`tool-todo`](../packages/todo/tool-todo) | | [`api-settings-controller`](../packages/api/settings-controller) | `api` | [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`credentials`](../packages/credentials/credentials), [`native-command`](../packages/util/native-command), [`session`](../packages/core/session), [`settings`](../packages/settings/settings), [`typert-protocol`](../packages/typert/protocol) | | [`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) | +| [`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), [`tools`](../packages/core/tools), [`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), [`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) | @@ -1897,9 +1908,9 @@ flowchart TD | [`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` | [`error`](../packages/util/error), [`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) | -| [`experimental-browser-use-runtime`](../packages/experimental/browser-use-runtime) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`mcp-client`](../packages/mcp/mcp-client), [`scope`](../packages/core/scope), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | -| [`experimental-claude-code-mods`](../packages/experimental/claude-code-mods) | `experimental` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`storage-domain`](../packages/storage/storage-domain), [`subprocess`](../packages/subprocess/subprocess), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) | -| [`experimental-worktree`](../packages/experimental/worktree) | `experimental` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`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), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess), [`working-directory`](../packages/session/working-directory), [`workspace`](../packages/workspace/workspace) | +| [`experimental-browser-use-runtime`](../packages/experimental/browser-use-runtime) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`error`](../packages/util/error), [`mcp-client`](../packages/mcp/mcp-client), [`scope`](../packages/core/scope), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | +| [`experimental-claude-code-mods`](../packages/experimental/claude-code-mods) | `experimental` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`storage-domain`](../packages/storage/storage-domain), [`subprocess`](../packages/subprocess/subprocess), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) | +| [`experimental-worktree`](../packages/experimental/worktree) | `experimental` | [`agent`](../packages/core/agent), [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`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), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess), [`working-directory`](../packages/session/working-directory), [`workspace`](../packages/workspace/workspace) | | [`tool-session-query`](../packages/experimental/tool-session-query) | `experimental` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-query`](../packages/session-query/session-query), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | | [`webhook-github`](../packages/experimental/webhook-github) | `experimental` | [`credentials`](../packages/credentials/credentials), [`host-webserver`](../packages/host/webserver), [`session`](../packages/core/session), [`webhook`](../packages/experimental/webhook) | | [`mcp-manager`](../packages/mcp/mcp-manager) | `mcp` | [`mcp-client`](../packages/mcp/mcp-client), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`util-values`](../packages/util/values) | @@ -1918,11 +1929,11 @@ flowchart TD | [`session-reference`](../packages/context/session-reference) | `context` | [`agent`](../packages/core/agent), [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`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), [`spill`](../packages/spill/spill), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`typert-protocol`](../packages/typert/protocol) | | [`tool-office`](../packages/document/tool-office) | `document` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`office-kit`](../packages/document/office-kit), [`skill`](../packages/skill/skill), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`experimental-worktree`](../packages/experimental/worktree), [`fs`](../packages/fs/fs), [`session`](../packages/core/session), [`timeout`](../packages/util/timeout) | -| [`experimental-subagent-oar`](../packages/experimental/subagent-oar) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess) | +| [`experimental-subagent-oar`](../packages/experimental/subagent-oar) | `experimental` | [`error`](../packages/util/error), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess) | | [`experimental-tool-subagent-oar`](../packages/experimental/tool-subagent-oar) | `experimental` | [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools) | | [`experimental-tool-worktree`](../packages/experimental/tool-worktree) | `experimental` | [`experimental-worktree`](../packages/experimental/worktree), [`tools`](../packages/core/tools) | | [`hooks-claude-code`](../packages/experimental/hooks-claude-code) | `experimental` | [`agent`](../packages/core/agent), [`hook-protocol`](../packages/experimental/hook-protocol), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | -| [`tool-ralph`](../packages/experimental/tool-ralph) | `experimental` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow) | +| [`tool-ralph`](../packages/experimental/tool-ralph) | `experimental` | [`agent`](../packages/core/agent), [`error`](../packages/util/error), [`llm`](../packages/llm/llm), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow) | | [`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) | diff --git a/docs/subsystems/liveshare.i18n.yaml b/docs/subsystems/liveshare.i18n.yaml index 608e65a930..40240826c1 100644 --- a/docs/subsystems/liveshare.i18n.yaml +++ b/docs/subsystems/liveshare.i18n.yaml @@ -18,8 +18,8 @@ en: 6b1346e73ab6eab9 zh: 888cfc08c6bc8522 /liveshare/constraining-a-shared-session: - en: 7607ed3f99df06cc - zh: 290c9b8ed064da00 + en: 7fbb31bbc29817d6 + zh: 0a9542ab1d48a9e6 /liveshare/viewer-states: en: b8bcb009e419fa25 zh: 31c4662b52e99ea7 diff --git a/docs/subsystems/liveshare.md b/docs/subsystems/liveshare.md index 604ef23c12..6705717b81 100644 --- a/docs/subsystems/liveshare.md +++ b/docs/subsystems/liveshare.md @@ -38,7 +38,7 @@ Child tool guards recheck the share’s current mode, expiry, viewer admission, Every share lets its viewer drive the *source* Session through the normal prompt path, and any share at either tier installs the bounded sandbox while it is active. `installSourceSessionAccess` registers a confined replacement for every view-surface tool the deployment ships in that Session's own scope, and bounded `edit` and `write` replacements whenever any share over the Session allows writing. The layer is mounted on the Session, but it confines only the turns a share viewer starts: `agent/pre-step` records, in Host memory, whether a turn's admitted input names a share viewer, and the guard and the replacements read that answer for every execution of that turn. A viewer-started turn runs those replacements and nothing else; a turn the owner starts keeps the Session's own tools, including `bash` and its unrestricted filesystem tools. The answer is decided when the turn is admitted and never written to the Session log; a restart recomputes it from the next admitted step. An owner's steering input inside a viewer's turn stays confined with it. Stopping every share over the Session disposes the layer, which restores the Session's own tools; narrowing the last write share to `view` re-installs the read-only layer. -The installation reports whether the source Session is actually confined. A deployment without the `read` tool, or a scope that refuses that replacement's registration, leaves the guard in place and reports the refusal; a tool whose own replacement failed stays refused while the rest of the surface runs, and the reader refuses the prompt with `source-write-unavailable`: no viewer-started turn of a shared Session is driven against the owner's own tools because a limit could not be installed. +The installation reports whether the source Session is actually confined. A deployment without the `read` tool, or a scope that refuses that replacement's registration, leaves the guard in place and reports the refusal; a tool whose own replacement failed stays refused while the rest of the surface runs, and the reader refuses the prompt with `source-write-unavailable`: no viewer-started turn of a shared Session is driven against the owner's own tools because a limit could not be installed. A refusal records the same identity whether the guard or a confined tool decides: a path outside the grant is `FsError` `FS_SANDBOX_DENIED`, and other grant refusals are `LiveshareForkDeniedError` with a `FORK_*` code. Each operation re-reads the Relay grants of the shares that keep the Session drivable, and each reading is synchronous with the tool call it authorizes, so input queued past the grant that admitted it cannot act on that stale admission. The layer is per Session: several shares over one Session share the one installation, a share that carries several source Sessions installs one layer per source, and a share that narrows or ends changes what the layer permits — its bounded write is refused once no active share may write, and the layer is released once no share is left. The Host does not attribute a running turn to the viewer that admitted it, so ending one share's grant stops the Session's running turn rather than singling out that viewer's work; the in-memory viewer-start marker only decides which tool surface that turn runs. diff --git a/docs/subsystems/liveshare.zh.md b/docs/subsystems/liveshare.zh.md index 4c26825027..a274d8957d 100644 --- a/docs/subsystems/liveshare.zh.md +++ b/docs/subsystems/liveshare.zh.md @@ -38,7 +38,7 @@ fork 创建查看者拥有的新会话,源会话保持不变。Fork 授权检 每个分享都让它的 viewer 通过正常 prompt 路径驱动*源*会话,任一档位的分享在活跃期间都会安装有界沙箱。`installSourceSessionAccess` 在该会话自身作用域中为部署提供的每个读取与检索面工具注册受限替代,并在任一同会话分享允许写入时再注册有界 `edit` 与 `write` 替代。执行层挂在会话上,但只约束分享查看者发起的轮次:`agent/pre-step` 在 Host 内存中记录一个轮次的已准入输入是否带有 share-viewer principal,守卫与替代定义对该轮次的每次执行读取这一结论。查看者发起的轮次只能运行这些替代定义;所有者自己发起的轮次保留会话原生工具,包括 `bash` 与不受限的文件工具。该结论在轮次准入时确定,不写入会话日志;重启后从下一个准入步骤重新计算。所有者在查看者轮次中追加的输入仍留在该受限轮次内。该会话的所有分享停止后执行层被释放,会话恢复自己的工具;最后一个可写分享降为 `view` 时重装只读层。 -安装结果报告源会话是否真正受到限制。没有 `read` 工具的部署或拒绝该替代注册的作用域会保留守卫并报告失败;某个工具自己的替代注册失败时,该工具保持拒绝,其余工具面照常运行。读取处理器以 `source-write-unavailable` 拒绝消息:限制未安装时,共享会话中查看者发起的轮次不会用所有者工具驱动。 +安装结果报告源会话是否真正受到限制。没有 `read` 工具的部署或拒绝该替代注册的作用域会保留守卫并报告失败;某个工具自己的替代注册失败时,该工具保持拒绝,其余工具面照常运行。读取处理器以 `source-write-unavailable` 拒绝消息:限制未安装时,共享会话中查看者发起的轮次不会用所有者工具驱动。无论由守卫还是受限工具判定,拒绝都记录同一标识:授权范围外的路径为 `FsError` `FS_SANDBOX_DENIED`,其他授权拒绝为 `LiveshareForkDeniedError` 及 `FORK_*` code。 每次操作都会重新读取维持该会话可驱动的分享的 Relay 授权,且读取与其授权的工具调用在同一同步步骤内完成,因此排队超过其准入授权的输入无法凭过期准入行动。执行层按会话安装:同一会话的多个分享共用一个安装,一条携带多个源会话的分享则为每个源会话各安装一层;分享收窄或结束时改变该层允许的操作——没有任何活跃分享可写时拒绝有界写入,会话不再有分享时释放执行层。Host 不把正在运行的轮次归属给准入它的查看者,因此结束某个分享的授权会停止该会话正在运行的轮次,而不是只挑出该查看者的工作;内存中的查看者轮次标记只决定该轮次运行哪套工具面。 diff --git a/docs/subsystems/tools.i18n.yaml b/docs/subsystems/tools.i18n.yaml index 63e156a03d..e33fb7cdc2 100644 --- a/docs/subsystems/tools.i18n.yaml +++ b/docs/subsystems/tools.i18n.yaml @@ -21,8 +21,8 @@ en: 14522295539ea2fb zh: 572c462f2c6b70ad /tools/execution-extensible-waterfalls-plus-monotonic-policy: - en: 0900eea6efe5a500 - zh: 13fa6eb7dbd8c9dd + en: a6d9db4237438b2a + zh: 1fe07dedc426c5eb /tools/the-enforced-raw-json-schema-subset: en: 28e354bfa2f9cebb zh: be1f75abccf8afdf diff --git a/docs/subsystems/tools.md b/docs/subsystems/tools.md index 27e0af6609..7a36ecf7c1 100644 --- a/docs/subsystems/tools.md +++ b/docs/subsystems/tools.md @@ -540,7 +540,7 @@ interface ToolErrorInfo { } ``` -The result carries only the outcome. Call identity remains on the immutable `ToolExecution` that accompanies it through every hook and on the durable `tool/call` / `tool/result` session events, so wrappers cannot create a second, disagreeing identity. The canonical `value` is execution-local: the loop persists only `content`, `error`, and `meta`, while `tool/ptc-dispatch` stores the sub-call's rendered `content`, `isError`, optional structured `error`, and presentation `meta`. Replay reproduces presentation but cannot reconstruct canonical intermediate values. Optional `ToolErrorInfo.reason` retains raw user-facing detail without adding it to model-facing content. The registry sets `info` from a thrown `HarnessError` (its `name` and `code`), from a pre-execute `deny` that supplies it, and on its own cancellation results (`AbortError` with `ABORTED` or `ABORTED_BEFORE_DISPATCH`); when a started body throws the signal's reason or an `Error` named `AbortError` after cancellation, the result keeps that message and carries `AbortError` with `ABORTED`; a `tools/execute` wrapper may also return a result with `info`, such as the timeout policy's `TOOL_TIMEOUT`. An `ask` that approval does not grant becomes a denial with the name `ApprovalError`, which identifies the registry's denial and is not a thrown class, and `APPROVAL_REJECTED`, `APPROVAL_CANCELLED`, or `APPROVAL_UNAVAILABLE`. A guard denial or post-execute block carries `info` only when it supplies one; any other thrown value produces an `error` without `info`. +The result carries only the outcome. Call identity remains on the immutable `ToolExecution` that accompanies it through every hook and on the durable `tool/call` / `tool/result` session events, so wrappers cannot create a second, disagreeing identity. The canonical `value` is execution-local: the loop persists only `content`, `error`, and `meta`, while `tool/ptc-dispatch` stores the sub-call's rendered `content`, `isError`, optional structured `error`, and presentation `meta`. Replay reproduces presentation but cannot reconstruct canonical intermediate values. Optional `ToolErrorInfo.reason` retains raw user-facing detail without adding it to model-facing content. The registry sets `info` from a thrown `HarnessError` (its `name` and `code`), from a pre-execute `deny` that supplies it, and on its own cancellation results (`AbortError` with `ABORTED` or `ABORTED_BEFORE_DISPATCH`); when a started body throws the signal's reason or an `Error` named `AbortError` after cancellation, the result keeps that message and carries `AbortError` with `ABORTED`, and a `tools/execute` wrapper that throws such a value after caller cancellation gets the same identity, with `ABORTED_BEFORE_DISPATCH` when the body never started; a `tools/execute` wrapper may also return a result with `info`, such as the timeout policy's `TOOL_TIMEOUT`. An `ask` that approval does not grant becomes a denial with the name `ApprovalError`, which identifies the registry's denial and is not a thrown class, and `APPROVAL_REJECTED`, `APPROVAL_CANCELLED`, or `APPROVAL_UNAVAILABLE`. A guard denial or post-execute block carries `info` only when it supplies one; any other thrown value produces an `error` without `info`. On success the registry snapshots and validates the body value, freezes it, and invokes the pure renderer plus the optional presentation metadata projector for native and nested calls. It separately materializes the durable presentation fields immediately before `tools/result`; an invalid value, renderer/projector failure, or non-JSON presentation becomes a JSON-safe `isError`. The final live observer therefore sees the exact execution-local value beside fields safe for the later durable append. diff --git a/docs/subsystems/tools.zh.md b/docs/subsystems/tools.zh.md index 512d153e81..39a9c87bc4 100644 --- a/docs/subsystems/tools.zh.md +++ b/docs/subsystems/tools.zh.md @@ -540,7 +540,7 @@ interface ToolErrorInfo { } ``` -结果仅承载产出。调用身份保留在不可变的 `ToolExecution` 上,后者伴随结果经过每个钩子,并出现在持久化的 `tool/call` / `tool/result` 会话事件上,因此包装层无法创建第二个相互矛盾的身份。规范的 `value` 仅存在于执行期间:循环只持久化 `content`、`error` 和 `meta`,`tool/ptc-dispatch` 则存储子调用渲染后的 `content`、`isError`、可选结构化 `error` 和展示 `meta`。回放可以重现展示,却无法重建规范的中间值。可选的 `ToolErrorInfo.reason` 保留面向用户的原始详情,不将其加入模型可见内容。注册表会在以下情况设置 `info`:抛出的是 `HarnessError`(取其 `name` 和 `code`)、pre-execute 的 `deny` 自带 `info`,以及注册表自己生成的取消结果(`AbortError`,code 为 `ABORTED` 或 `ABORTED_BEFORE_DISPATCH`);已开始的工具主体在取消后抛出 signal 的 reason 或 name 为 `AbortError` 的 `Error` 时,结果保留其 message,并带上 `AbortError` 与 `ABORTED`;`tools/execute` 包装器也可能返回带 `info` 的结果,例如超时策略的 `TOOL_TIMEOUT`。审批未授予的 `ask` 会变成 name 为 `ApprovalError` 的拒绝(该 name 标识注册表的拒绝,并不对应可抛出的类),code 为 `APPROVAL_REJECTED`、`APPROVAL_CANCELLED` 或 `APPROVAL_UNAVAILABLE`。guard 拒绝或 post-execute block 只有自带 `info` 时才会携带它;其他抛出值产生的 `error` 不含 `info`。 +结果仅承载产出。调用身份保留在不可变的 `ToolExecution` 上,后者伴随结果经过每个钩子,并出现在持久化的 `tool/call` / `tool/result` 会话事件上,因此包装层无法创建第二个相互矛盾的身份。规范的 `value` 仅存在于执行期间:循环只持久化 `content`、`error` 和 `meta`,`tool/ptc-dispatch` 则存储子调用渲染后的 `content`、`isError`、可选结构化 `error` 和展示 `meta`。回放可以重现展示,却无法重建规范的中间值。可选的 `ToolErrorInfo.reason` 保留面向用户的原始详情,不将其加入模型可见内容。注册表会在以下情况设置 `info`:抛出的是 `HarnessError`(取其 `name` 和 `code`)、pre-execute 的 `deny` 自带 `info`,以及注册表自己生成的取消结果(`AbortError`,code 为 `ABORTED` 或 `ABORTED_BEFORE_DISPATCH`);已开始的工具主体在取消后抛出 signal 的 reason 或 name 为 `AbortError` 的 `Error` 时,结果保留其 message,并带上 `AbortError` 与 `ABORTED`,`tools/execute` 包装器在调用方取消后抛出这类值时也得到同样的标识,工具主体尚未开始时为 `ABORTED_BEFORE_DISPATCH`;`tools/execute` 包装器也可能返回带 `info` 的结果,例如超时策略的 `TOOL_TIMEOUT`。审批未授予的 `ask` 会变成 name 为 `ApprovalError` 的拒绝(该 name 标识注册表的拒绝,并不对应可抛出的类),code 为 `APPROVAL_REJECTED`、`APPROVAL_CANCELLED` 或 `APPROVAL_UNAVAILABLE`。guard 拒绝或 post-execute block 只有自带 `info` 时才会携带它;其他抛出值产生的 `error` 不含 `info`。 成功时,注册表会快照并校验函数体返回值,将其冻结,然后调用纯渲染器,并为原生与嵌套调用执行可选的展示元数据投影器。注册表会在 `tools/result` 之前另行物化持久展示字段;无效值、渲染器/投影器失败或非 JSON 展示都会转为 JSON 安全的 `isError`。因此,最终实时观察者能看到精确的执行期值,以及可安全用于后续持久追加的字段。 diff --git a/docs/subsystems/worktrees.i18n.yaml b/docs/subsystems/worktrees.i18n.yaml index 23dde9244e..a6b14d164b 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: 53f643c5d30e00b2 - zh: ba9e52efc62c7656 + en: 4c28ae6baae4ef5f + zh: 0c83d90ea3cd3c2e /git-worktrees/request-and-result: en: fbab866bf824d6e0 zh: 73d2a1ee350e1434 diff --git a/docs/subsystems/worktrees.md b/docs/subsystems/worktrees.md index 492a1dbb1a..a837e99625 100644 --- a/docs/subsystems/worktrees.md +++ b/docs/subsystems/worktrees.md @@ -10,7 +10,7 @@ The calling Session's current directory selects the source repository. Creation 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. -Leaving through `working_directory({ cd: path })` retains the checkout and branch. Cancellation or failure can also retain partial artifacts; the error identifies their location. The service aborts and drains pending operations on disposal. The [package README](../../packages/experimental/worktree/README.md) owns configuration and Git requirements. +Leaving through `working_directory({ cd: path })` retains the checkout and branch. Cancellation or failure can also retain partial artifacts; the error identifies their location. Worktree failures throw `WorktreeError` with a `WORKTREE_*` code; a failure after allocation keeps the wrapped error's `name` and `code`, and caller cancellation stays an `AbortError`. The service aborts and drains pending operations on disposal. The [package README](../../packages/experimental/worktree/README.md) owns configuration and Git requirements. ## Request and result @@ -124,6 +124,8 @@ Creates retained Git worktrees under the mounted filesystem and sandbox provider * @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. */ async create( agent: Agent, request: CreateWorktreeRequest = {}, signal?: AbortSignal, onPhase?: (phase: CreateWorktreePhase) => void, ): Promise @@ -140,6 +142,8 @@ async create( agent: Agent, request: CreateWorktreeRequest = {}, signal?: AbortS * @param signal - cancellation of the restoration. * @param onPhase - receives each stage before it begins; 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 diff --git a/docs/subsystems/worktrees.zh.md b/docs/subsystems/worktrees.zh.md index d96ef21893..3d2b4d7286 100644 --- a/docs/subsystems/worktrees.zh.md +++ b/docs/subsystems/worktrees.zh.md @@ -10,7 +10,7 @@ 默认目标为 `/.agents/worktrees/`。`repositoryRoot` 是调用方当前检出目录的顶层目录;因此,链接检出目录会在自身内部保存工作树父目录。仅当服务的分配操作创建了配置指定的父目录时,服务才会写入内容为 `*` 加换行符的 `.gitignore`。已有文件与忽略规则保持不变。调用方 Session 的现有沙箱策略必须允许写入目标目录与共享 Git 管理目录。Git 初始化成功后才改变工作目录。 -通过 `working_directory({ cd: path })` 离开时,会保留检出目录与分支。取消或失败也可能留下部分产物;错误会指出它们的位置。服务销毁时会中止待完成操作并等待它们结束。[包 README](../../packages/experimental/worktree/README.zh.md)拥有配置与 Git 要求。 +通过 `working_directory({ cd: path })` 离开时,会保留检出目录与分支。取消或失败也可能留下部分产物;错误会指出它们的位置。worktree 失败抛出带 `WORKTREE_*` code 的 `WorktreeError`;分配开始后的失败保留被包装错误的 `name` 与 `code`,调用方取消仍为 `AbortError`。服务销毁时会中止待完成操作并等待它们结束。[包 README](../../packages/experimental/worktree/README.zh.md)拥有配置与 Git 要求。 ## 请求与结果 @@ -124,6 +124,8 @@ Creates retained Git worktrees under the mounted filesystem and sandbox provider * @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. */ async create( agent: Agent, request: CreateWorktreeRequest = {}, signal?: AbortSignal, onPhase?: (phase: CreateWorktreePhase) => void, ): Promise @@ -140,6 +142,8 @@ async create( agent: Agent, request: CreateWorktreeRequest = {}, signal?: AbortS * @param signal - cancellation of the restoration. * @param onPhase - receives each stage before it begins; 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 diff --git a/docs/upgrade-guide/v0.2.2-rc.2/experimental-tool-error-codes/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.2/experimental-tool-error-codes/guide.i18n.yaml new file mode 100644 index 0000000000..1ff6a94445 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.2/experimental-tool-error-codes/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.2/experimental-tool-error-codes/guide.md +/: + en: 4d6f7a78d1415f20 + zh: a5a906f4f1266243 +/experimental-plugin-failures-carry-error-codes: + en: 13f43192e549438f + zh: ce8c5bf26aefbd4f +/experimental-plugin-failures-carry-error-codes/change: + en: d5878c5ce6fbfb76 + zh: 2f2d29a1f3a9d6f3 +/experimental-plugin-failures-carry-error-codes/migration: + en: 6365d4f60118cf64 + zh: c2f1378dee8ea4b4 diff --git a/docs/upgrade-guide/v0.2.2-rc.2/experimental-tool-error-codes/guide.md b/docs/upgrade-guide/v0.2.2-rc.2/experimental-tool-error-codes/guide.md new file mode 100644 index 0000000000..c4e579dd36 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.2/experimental-tool-error-codes/guide.md @@ -0,0 +1,28 @@ +--- +kind: upgrade-guide +description: "Experimental and hook plugin tool failures record error codes, NativeError, OarFailure, and StagehandDrainError become HarnessError subclasses, and browser cleanup rejects with BrowserSessionError." +--- + +# Experimental plugin failures carry error codes + +English | [中文](guide.zh.md) + +## Change + +Tool failures from the CUA, browser-use, Cua Driver, worktree, Ralph, terminal, OAR subagent, Liveshare, Claude Code and Codex hook, and claude-code-mods plugins now record `error: { name, code }` on `tool/result`; previously most of these results had no `error`. The [package READMEs](../../../../packages/experimental/README.md) list each class and code. + +Code that handles these failures in-process sees these changes: + +- `NativeError` from `@deepseek-ai/dsh-cua` and `OarFailure` from `@deepseek-ai/dsh-experimental-subagent-oar` now extend `HarnessError` from `@deepseek-ai/dsh-error`. `NativeError` keeps its name, codes, and `CODE: message` text. `OarFailure` drops its `stage` and `category` fields; the same summary stays in `message`, and `code` names the stage. Cancellation before an OAR run starts rejects with a `DOMException` named `AbortError` instead of an `OarFailure`. +- `StagehandDrainError` from `@deepseek-ai/dsh-experimental-browser-use-stagehand-native` now extends `StagehandError` and has the code `STAGEHAND_CLEANUP_FAILED`. +- `SessionResources.dispose()` from `@deepseek-ai/dsh-experimental-browser-use-runtime` rejects with `BrowserSessionError` (`BROWSER_CLEANUP_FAILED`) whose `cause` is the `AggregateError` it previously threw; `instanceof AggregateError` no longer matches. +- Liveshare guard functions return `{ reason, info }` instead of a reason string. +- Argument failures that now throw `ToolArgsError` show `invalid arguments: ` before the message the model sees, and a CUA screenshot request for a model without image input shows `MODEL_DOES_NOT_SUPPORT_IMAGES: ` before its message. + +## Migration + +1. If analytics or retry rules read `tool/result` `error`, add the new names and codes from the package READMEs. Earlier Session logs keep results without `error`. +2. Replace `instanceof AggregateError` checks on `SessionResources.dispose()` rejections with `instanceof BrowserSessionError` and read the individual failures from `error.cause.errors`. +3. Replace reads of `OarFailure.stage` or `category` with `error.code`. +4. If code catches `HarnessError` before `NativeError`, `OarFailure`, or `StagehandDrainError`, move the specific check first where the handling differs. +5. Confirm with `pnpm run typecheck` and your own failure-path tests. diff --git a/docs/upgrade-guide/v0.2.2-rc.2/experimental-tool-error-codes/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.2/experimental-tool-error-codes/guide.zh.md new file mode 100644 index 0000000000..41e8ba1902 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.2/experimental-tool-error-codes/guide.zh.md @@ -0,0 +1,28 @@ +--- +kind: upgrade-guide +description: "Experimental 与 hook 插件的工具失败带上错误 code,NativeError、OarFailure 与 StagehandDrainError 改为 HarnessError 子类,浏览器清理失败改为以 BrowserSessionError 拒绝。" +--- + +# Experimental 插件的失败带上错误 code + +[English](guide.md) | 中文 + +## 变更 + +CUA、browser-use、Cua Driver、worktree、Ralph、终端、OAR 子 agent、Liveshare、Claude Code 与 Codex hook,以及 claude-code-mods 插件的工具失败现在会在 `tool/result` 上记录 `error: { name, code }`;此前这些结果大多没有 `error`。各[包 README](../../../../packages/experimental/README.zh.md) 列出了每个类和 code。 + +在进程内处理这些失败的代码会看到以下变化: + +- `@deepseek-ai/dsh-cua` 的 `NativeError` 与 `@deepseek-ai/dsh-experimental-subagent-oar` 的 `OarFailure` 现在继承 `@deepseek-ai/dsh-error` 的 `HarnessError`。`NativeError` 的 name、code 与 `CODE: message` 文本不变。`OarFailure` 去掉了 `stage` 与 `category` 字段;同样的摘要保留在 `message` 中,`code` 标明阶段。OAR 运行开始前的取消改为以 name 为 `AbortError` 的 `DOMException` 拒绝,不再是 `OarFailure`。 +- `@deepseek-ai/dsh-experimental-browser-use-stagehand-native` 的 `StagehandDrainError` 现在继承 `StagehandError`,code 为 `STAGEHAND_CLEANUP_FAILED`。 +- `@deepseek-ai/dsh-experimental-browser-use-runtime` 的 `SessionResources.dispose()` 改为以 `BrowserSessionError`(`BROWSER_CLEANUP_FAILED`)拒绝,其 `cause` 是此前直接抛出的 `AggregateError`;`instanceof AggregateError` 不再成立。 +- Liveshare 的 guard 函数改为返回 `{ reason, info }`,不再返回原因字符串。 +- 改为抛出 `ToolArgsError` 的参数失败,模型看到的 message 前多了 `invalid arguments: `;为不支持图片输入的模型请求 CUA 截图时,message 前多了 `MODEL_DOES_NOT_SUPPORT_IMAGES: `。 + +## 迁移 + +1. 如果分析或重试规则读取 `tool/result` 的 `error`,按包 README 补充新的 name 与 code。较早的 Session 日志中这些结果仍没有 `error`。 +2. 把对 `SessionResources.dispose()` 拒绝值的 `instanceof AggregateError` 检查改为 `instanceof BrowserSessionError`,并从 `error.cause.errors` 读取各个失败。 +3. 把读取 `OarFailure.stage` 或 `category` 的代码改为读取 `error.code`。 +4. 如果代码在 `NativeError`、`OarFailure` 或 `StagehandDrainError` 之前捕获 `HarnessError`,在处理方式不同的地方把具体类的检查移到前面。 +5. 用 `pnpm run typecheck` 和自己的失败路径测试确认迁移完成。 diff --git a/packages/core/tools/README.i18n.yaml b/packages/core/tools/README.i18n.yaml index be0d5b42f0..4e359e6080 100644 --- a/packages/core/tools/README.i18n.yaml +++ b/packages/core/tools/README.i18n.yaml @@ -45,8 +45,8 @@ en: 2dee0a37e0c1fa38 zh: 0963cba32685612e /deepseek-ai-dsh-tools/understand-the-implementation/execution-and-cancellation: - en: c13b9530c43ffad9 - zh: b97ab1e5d853e065 + en: 9522172a36c6ccc0 + zh: 15a620e2dffbef6b /deepseek-ai-dsh-tools/understand-the-implementation/ptc-mode: en: 83cf9a5077158879 zh: 80508a70a3674226 diff --git a/packages/core/tools/README.md b/packages/core/tools/README.md index 0a802d324a..f9b85bb3b7 100644 --- a/packages/core/tools/README.md +++ b/packages/core/tools/README.md @@ -125,7 +125,7 @@ The registry holds typed `ToolDefinition`s in scoped layers and projects them on ### Execution and cancellation -Each typed invocation materializes and freezes parsed arguments, assigns an opaque correlation token, and runs policy and dispatch. A pre-execute denial may attach `ToolErrorInfo` beside its model-facing reason; the native and PTC durable projections preserve the structured name, code, and optional user-facing reason without adding that detail to model content. Cancellation is cooperative and quiescent: every tool body receives the caller-owned `exec.signal` and must observe it; cancellation before body invocation is `ABORTED_BEFORE_DISPATCH`, after invocation it normally replaces only a successful outcome with `ABORTED`, and a thrown signal reason or `Error` named `AbortError` without `HarnessError` identity keeps its message but carries `ABORTED`. A tool whose successful return confirms an accepted effect that cancellation cannot retract may declare `preserveSuccessOnCancellation: true`; the pipeline captures this declaration before policy begins and retains successful receipts after the body starts, including cancellation during post-execute. Omitted or false preserves ordinary cancellation behavior. Denials, wrapper failures, tool failures, post-policy failures, and timeout-owned `TOOL_TIMEOUT` remain more specific. Unknown and throwing tools become structured errors (`UNKNOWN_TOOL`), so a call fails without ending the turn. +Each typed invocation materializes and freezes parsed arguments, assigns an opaque correlation token, and runs policy and dispatch. A pre-execute denial may attach `ToolErrorInfo` beside its model-facing reason; the native and PTC durable projections preserve the structured name, code, and optional user-facing reason without adding that detail to model content. Cancellation is cooperative and quiescent: every tool body receives the caller-owned `exec.signal` and must observe it; cancellation before body invocation is `ABORTED_BEFORE_DISPATCH`, after invocation it normally replaces only a successful outcome with `ABORTED`, and a thrown signal reason or `Error` named `AbortError` without `HarnessError` identity keeps its message but carries `ABORTED`. A `tools/execute` wrapper that throws such a value after caller cancellation is classified the same way, as `ABORTED_BEFORE_DISPATCH` when the body never started. A tool whose successful return confirms an accepted effect that cancellation cannot retract may declare `preserveSuccessOnCancellation: true`; the pipeline captures this declaration before policy begins and retains successful receipts after the body starts, including cancellation during post-execute. Omitted or false preserves ordinary cancellation behavior. Denials, other wrapper failures, tool failures, post-policy failures, and timeout-owned `TOOL_TIMEOUT` remain more specific. Unknown and throwing tools become structured errors (`UNKNOWN_TOOL`), so a call fails without ending the turn. ### PTC mode diff --git a/packages/core/tools/README.zh.md b/packages/core/tools/README.zh.md index 8ed220dd58..74bdfa8903 100644 --- a/packages/core/tools/README.zh.md +++ b/packages/core/tools/README.zh.md @@ -125,7 +125,7 @@ Agent 步骤的并发上限使用 [agent-loop 配置](../agent-loop/README.zh.md ### 执行与取消 -每次类型化调用都会实体化并冻结解析后的参数、分配不透明关联 token,再运行策略与分发。pre-execute 拒绝可以在模型可见原因旁附带 `ToolErrorInfo`;原生与 PTC 持久投影会保留结构化名称、代码与可选用户可见原因,但不会把该详情加入模型内容。取消采用协作式并等待完全停稳:每个工具主体都收到调用方拥有的 `exec.signal` 且必须观测它;调用主体前的取消为 `ABORTED_BEFORE_DISPATCH`,调用主体后的取消通常只把成功结果替换为 `ABORTED`,抛出的 signal reason,或不具备 `HarnessError` 身份、name 为 `AbortError` 的 `Error`,保留其 message 并携带 `ABORTED`。若工具成功返回即确认了取消无法撤回的已接受效果,可以声明 `preserveSuccessOnCancellation: true`;流水线在策略开始前捕获该声明,在主体启动后保留成功回执,包括 post-execute 期间发生的取消。省略或设为 false 时保留普通取消行为。拒绝、包装层失败、工具失败、后置策略失败与超时产生的 `TOOL_TIMEOUT` 仍保留更具体的结果。未知工具与抛出异常的工具都会变成结构化错误(`UNKNOWN_TOOL`),因此调用会失败而不会结束轮次。 +每次类型化调用都会实体化并冻结解析后的参数、分配不透明关联 token,再运行策略与分发。pre-execute 拒绝可以在模型可见原因旁附带 `ToolErrorInfo`;原生与 PTC 持久投影会保留结构化名称、代码与可选用户可见原因,但不会把该详情加入模型内容。取消采用协作式并等待完全停稳:每个工具主体都收到调用方拥有的 `exec.signal` 且必须观测它;调用主体前的取消为 `ABORTED_BEFORE_DISPATCH`,调用主体后的取消通常只把成功结果替换为 `ABORTED`,抛出的 signal reason,或不具备 `HarnessError` 身份、name 为 `AbortError` 的 `Error`,保留其 message 并携带 `ABORTED`。`tools/execute` 包装层在调用方取消后抛出这类值时按同样方式归类,工具主体尚未开始时为 `ABORTED_BEFORE_DISPATCH`。若工具成功返回即确认了取消无法撤回的已接受效果,可以声明 `preserveSuccessOnCancellation: true`;流水线在策略开始前捕获该声明,在主体启动后保留成功回执,包括 post-execute 期间发生的取消。省略或设为 false 时保留普通取消行为。拒绝、其他包装层失败、工具失败、后置策略失败与超时产生的 `TOOL_TIMEOUT` 仍保留更具体的结果。未知工具与抛出异常的工具都会变成结构化错误(`UNKNOWN_TOOL`),因此调用会失败而不会结束轮次。 ### PTC mode diff --git a/packages/core/tools/src/pipeline.ts b/packages/core/tools/src/pipeline.ts index 6fe1b5bccc..a3e8e9ac26 100644 --- a/packages/core/tools/src/pipeline.ts +++ b/packages/core/tools/src/pipeline.ts @@ -300,7 +300,12 @@ export class ToolExecutionPipeline { /** * Run around-dispatch and the tool body. Tool and unknown-tool failures still * receive post-execute; pipeline failures are already final. Started bodies - * drain on cancellation; successful acceptance receipts may remain successful. + * drain on cancellation before a successful outcome becomes `ABORTED`, unless + * the definition preserves successful acceptance receipts. After + * caller cancellation, a wrapper that throws the caller signal's reason or an + * `Error` named `AbortError` without `HarnessError` identity keeps its message + * and gains `ABORTED`, or `ABORTED_BEFORE_DISPATCH` when the body never + * started; a wrapper's `HarnessError` and other failures stay unchanged. * @param exec - the execution returned by this pipeline's prepare stage. * @returns whether the result still needs post-execute. */ @@ -332,10 +337,19 @@ export class ToolExecutionPipeline { : resultWithDeferredContexts, } } catch (error: unknown) { - return { kind: 'final-result', result: toolErrorResult(error) } + return { kind: 'final-result', result: this.wrapperFailureResult(exec, error) } } } + /** Classify a failure thrown around dispatch; see {@link dispatch}. */ + private wrapperFailureResult(exec: ToolRunContext, error: unknown): ToolExecutionResult { + const state = this.cancellationStates.get(exec) + /* v8 ignore next -- only registry-minted executions reach the staged scheduler methods */ + if (state === undefined) throw new Error('tool registry scheduler invariant violated: missing cancellation state') + if (!isAborted(state.callerSignal) || !isUnclassifiedCancellation(error, state.callerSignal)) return toolErrorResult(error) + return toolErrorResult(error, { name: 'AbortError', code: state.bodyInvoked ? TOOL_ABORTED : TOOL_ABORTED_BEFORE_DISPATCH }) + } + /** * Run post-execute when required, apply definition-owned content finalization, * and publish the lossless, frozen result. Policy and finalization failures diff --git a/packages/core/tools/tests/tools.spec.ts b/packages/core/tools/tests/tools.spec.ts index 95a3ccd18d..cf0828f361 100644 --- a/packages/core/tools/tests/tools.spec.ts +++ b/packages/core/tools/tests/tools.spec.ts @@ -2196,6 +2196,36 @@ describe('ToolRuntime', () => { }) }) + it.each([ + ['the caller reason after the body ran', true, (signal: AbortSignal): never => { throw signal.reason as Error }, { name: 'AbortError', code: TOOL_ABORTED }], + ['the caller reason before the body ran', false, (signal: AbortSignal): never => { throw signal.reason as Error }, { name: 'AbortError', code: TOOL_ABORTED_BEFORE_DISPATCH }], + ['an AbortError after the body ran', true, (): never => { throw new DOMException('wrapper stopped', 'AbortError') }, { name: 'AbortError', code: TOOL_ABORTED }], + ['a HarnessError after the body ran', true, (): never => { throw new HarnessError('wrapper failed', 'WRAPPER_FAILED') }, { name: 'HarnessError', code: 'WRAPPER_FAILED' }], + ['a plain failure after the body ran', true, (): never => { throw new Error('wrapper broke') }, undefined], + ])('classifies %s thrown by a tools/execute listener after cancellation', async (_label, delegate, fail, info) => { + const ctx = await setup() + ctx.tools.register(echoTool) + const controller = new AbortController() + ctx.on('tools/execute', async (exec, next) => { + if (delegate) await next() + controller.abort(new Error('caller stopped')) + return fail(exec.signal) + }) + + const result = await executeToolFixture(ctx, { signal: controller.signal, callId: brandString('c1'), name: 'echo', arguments: { text: 'hi' } }) + expect(result.isError).toBe(true) + expect(result.error?.info).toEqual(info) + }) + + it('keeps a plain tools/execute listener failure without info when the caller did not cancel', async () => { + const ctx = await setup() + ctx.tools.register(echoTool) + ctx.on('tools/execute', async () => { throw new DOMException('wrapper stopped', 'AbortError') }) + + const result = await executeToolFixture(ctx, { signal: testToolSignal, callId: brandString('c1'), name: 'echo', arguments: { text: 'hi' } }) + expect(result.error).toEqual({ message: 'wrapper stopped' }) + }) + it('returns an isError result when a tools/pre-execute listener throws', async () => { const ctx = await setup() ctx.tools.register(echoTool) diff --git a/packages/experimental/browser-use-runtime/README.i18n.yaml b/packages/experimental/browser-use-runtime/README.i18n.yaml index e89da1dd02..b4aaa9d246 100644 --- a/packages/experimental/browser-use-runtime/README.i18n.yaml +++ b/packages/experimental/browser-use-runtime/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: f14f34fce35a8d90 /deepseek-ai-dsh-experimental-browser-use-runtime/use-this-package: - en: 192b3471ff924145 - zh: 7bcb9ca2498ee9a0 + en: de962a9af11ddaf2 + zh: 9e39d3d6b5dcd53e /deepseek-ai-dsh-experimental-browser-use-runtime/understand-the-implementation: en: ad923b17fcb5421c zh: c2449382d6e0c7ff diff --git a/packages/experimental/browser-use-runtime/README.md b/packages/experimental/browser-use-runtime/README.md index 6b2ac99b98..c35ba358ae 100644 --- a/packages/experimental/browser-use-runtime/README.md +++ b/packages/experimental/browser-use-runtime/README.md @@ -29,13 +29,15 @@ This public experimental library is a dependency of the browser providers. It ha Native providers construct `SessionResources` from the package root, supplying resource acquisition and cleanup callbacks. Calls pass the exact live Agent to `run()`; stale owners and a second owner of an exclusive attachment fail before acquisition. Canceling an acquisition wait leaves initialization available to other callers in the same Session; Session disposal aborts and awaits that initialization. Providers keep their registration until `dispose()` finishes. +Ownership failures throw `BrowserSessionError`, exported with its closed `BROWSER_SESSION_ERROR_CODES` list: `BROWSER_OWNER_NOT_LIVE` for a stale owner or a disposing provider, `BROWSER_LOCKED` for a second owner of an exclusive attachment, `BROWSER_CLOSED` for an operation interrupted because its Session's browser closed, `BROWSER_CLEANUP_FAILED` for a failed `dispose()` whose `cause` is an `AggregateError` of each close failure, and `BROWSER_FOREIGN_SESSION` for an MCP call from a Session without its own connection. A canceled wait whose abort reason is not an `Error` rejects with an `AbortError` that carries the `ABORTED` code. + MCP providers use `mountSessionMcp` from `@deepseek-ai/dsh-experimental-browser-use-runtime/mcp`, supplying their fixed server name, executable, arguments, and ownership policy. The mounting context must provide `workingDirectory`. Acquisition uses the [working-directory service](../../session/working-directory/README.md) to validate or recover the current directory and set the MCP server process's initial directory. Retained servers keep that directory when the Session later selects another. The helper awaits one scoped client startup and discovery attempt within each future Agent's `agent/created` event. Agent creation or resume completes after discovery, before queued input runs; a successful client remains owned by that Session across turns. A busy attachment skips startup permanently for that live activation while its other work continues. Releasing the attachment does not retry skipped activations; a newly created or resumed Agent can acquire it. Startup failure or cancellation rejects Agent creation or resume and triggers creation rollback, including client cleanup. Reconnection is disabled. Loading or reloading a provider applies only to future Agent activations. Callers can inspect prompt assembly and scoped tool definitions after awaited Agent creation or resume completes. -Browser tools and resource requests targeting this server use the same queue and require the calling Session's own connection. Other MCP servers remain usable. Inherited server instructions are omitted without ownership; the shared server-name inventory keeps its normal scope behavior. +Browser tools and resource requests targeting this server use the same queue and require the calling Session's own connection; a call without a calling Agent fails with `ToolContextUnavailableError`. Other MCP servers remain usable. Inherited server instructions are omitted without ownership; the shared server-name inventory keeps its normal scope behavior. ----- diff --git a/packages/experimental/browser-use-runtime/README.zh.md b/packages/experimental/browser-use-runtime/README.zh.md index f1cdc018a4..2489cb9db2 100644 --- a/packages/experimental/browser-use-runtime/README.zh.md +++ b/packages/experimental/browser-use-runtime/README.zh.md @@ -29,13 +29,15 @@ kind: "package-library" 原生提供方从包根入口构造 `SessionResources`,提供资源获取与清理回调。调用向 `run()` 传递确切的实时 Agent;失效的所有者与独占附加的第二个所有者在获取资源前失败。取消资源获取等待不会终止初始化,同一 Session 的其他调用方仍可继续等待;释放 Session 会中止并等待该初始化结束。提供方将注册保留到 `dispose()` 完成。 +所有权失败抛出 `BrowserSessionError`,与封闭的 `BROWSER_SESSION_ERROR_CODES` 列表一同导出:`BROWSER_OWNER_NOT_LIVE` 表示所有者失效或提供方正在释放,`BROWSER_LOCKED` 表示独占附加出现第二个所有者,`BROWSER_CLOSED` 表示操作因其 Session 的浏览器关闭而中断,`BROWSER_CLEANUP_FAILED` 表示 `dispose()` 失败,其 `cause` 是汇总各项关闭失败的 `AggregateError`,`BROWSER_FOREIGN_SESSION` 表示没有自己连接的 Session 发起了 MCP 调用。取消等待且中止原因不是 `Error` 时,以带 `ABORTED` 代码的 `AbortError` 拒绝。 + MCP 提供方使用 `@deepseek-ai/dsh-experimental-browser-use-runtime/mcp` 中的 `mountSessionMcp`,提供固定服务器名称、可执行文件、参数与所有权策略。挂载上下文必须提供 `workingDirectory`。获取连接时通过[工作目录服务](../../session/working-directory/README.zh.md)验证或恢复当前目录,并将其设为 MCP 服务器进程的初始目录。Session 后续选择其他目录时,保留的服务器继续使用该目录。辅助库在每个后续 Agent 的 `agent/created` 事件中等待一次有作用域的客户端启动与发现尝试。Agent 创建或恢复在发现完成后结束,随后才运行排队输入;成功的客户端跨轮次归该 Session 所有。 附加连接被占用时,本次激活永久跳过启动,但其他工作继续运行。连接释放不会触发被跳过激活的重试;新创建或恢复的 Agent 可以获取连接。启动失败或取消会拒绝 Agent 创建或恢复,并触发包含客户端清理的创建回滚。重连已禁用。加载或重新加载提供方只作用于后续的 Agent 激活。 调用方在等待 Agent 创建或恢复完成后,即可检查提示词组装和作用域工具定义。 -指向此服务器的浏览器工具调用与资源请求使用同一队列,且要求调用 Session 自己拥有连接。其他 MCP 服务器仍可使用。没有所有权时会省略继承的服务器指导;共享服务器名称目录保留常规作用域行为。 +指向此服务器的浏览器工具调用与资源请求使用同一队列,且要求调用 Session 自己拥有连接;没有调用方 Agent 的调用以 `ToolContextUnavailableError` 失败。其他 MCP 服务器仍可使用。没有所有权时会省略继承的服务器指导;共享服务器名称目录保留常规作用域行为。 ----- diff --git a/packages/experimental/browser-use-runtime/package.json b/packages/experimental/browser-use-runtime/package.json index a7bf8b13b9..7c08921ec7 100644 --- a/packages/experimental/browser-use-runtime/package.json +++ b/packages/experimental/browser-use-runtime/package.json @@ -42,7 +42,8 @@ "@deepseek-ai/dsh-scope": "workspace:*", "@deepseek-ai/dsh-tools": "workspace:*", "@deepseek-ai/dsh-system-prompt": "workspace:*", - "@deepseek-ai/dsh-working-directory": "workspace:*" + "@deepseek-ai/dsh-working-directory": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" }, "dependencies": { "@deepseek-ai/dsh-brand": "workspace:*", @@ -71,6 +72,7 @@ "@deepseek-ai/dsh-attachment-local": "workspace:*", "@deepseek-ai/dsh-session-persistence-jsonl": "workspace:*", "@deepseek-ai/dsh-working-directory": "workspace:*", - "@deepseek-ai/dsh-fs-local": "workspace:*" + "@deepseek-ai/dsh-fs-local": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" } } diff --git a/packages/experimental/browser-use-runtime/src/error.ts b/packages/experimental/browser-use-runtime/src/error.ts new file mode 100644 index 0000000000..04ab420089 --- /dev/null +++ b/packages/experimental/browser-use-runtime/src/error.ts @@ -0,0 +1,38 @@ +/** Machine-routable browser ownership failures. @module */ + +import { HarnessError } from '@deepseek-ai/dsh-error' + +/** + * Every {@link BrowserSessionError} code: + * - `BROWSER_FOREIGN_SESSION` — the browser tool or resource belongs to another Session's browser; this activation cannot use it. + * - `BROWSER_LOCKED` — another live Session reserves the attached browser; wait for its release or use a new activation later. + * - `BROWSER_OWNER_NOT_LIVE` — the calling Agent is no longer the live owner, or the provider is disposing; stop using the browser. + * - `BROWSER_CLOSED` — the Session's browser closed while the operation was admitted; a later call acquires a new browser. + * - `BROWSER_CLEANUP_FAILED` — closing one or more browsers failed; the cause lists each failure and ownership is retained. + */ +export const BROWSER_SESSION_ERROR_CODES = [ + 'BROWSER_FOREIGN_SESSION', + 'BROWSER_LOCKED', + 'BROWSER_OWNER_NOT_LIVE', + 'BROWSER_CLOSED', + 'BROWSER_CLEANUP_FAILED', +] as const + +/** One code from {@link BROWSER_SESSION_ERROR_CODES}. */ +export type BrowserSessionErrorCode = typeof BROWSER_SESSION_ERROR_CODES[number] + +/** Browser ownership failure carrying a stable {@link BrowserSessionErrorCode}. */ +export class BrowserSessionError extends HarnessError { + override readonly code: BrowserSessionErrorCode + + /** + * @param message - names the provider, the ownership problem, and the safe next step. + * @param code - the failure class consumers route on. + * @param options - standard `cause` chaining. + */ + constructor(message: string, code: BrowserSessionErrorCode, options?: ErrorOptions) { + super(message, code, options) + this.name = 'BrowserSessionError' + this.code = code + } +} diff --git a/packages/experimental/browser-use-runtime/src/index.ts b/packages/experimental/browser-use-runtime/src/index.ts index 131c20f68f..256d292b22 100644 --- a/packages/experimental/browser-use-runtime/src/index.ts +++ b/packages/experimental/browser-use-runtime/src/index.ts @@ -6,6 +6,9 @@ import type { Context } from '@deepseek-ai/cordis' import type { Agent } from '@deepseek-ai/dsh-agent' +import { BrowserSessionError } from './error.ts' + +export { BROWSER_SESSION_ERROR_CODES, BrowserSessionError, type BrowserSessionErrorCode } from './error.ts' /** One provider-owned browser or connection and its quiescent cleanup. */ export interface OwnedSessionResource { @@ -37,10 +40,17 @@ interface Entry { closing?: Promise } +/** The cancellation thrown for a non-`Error` abort reason; the tool registry records it as `ABORTED`. */ +function operationCanceled(reason: unknown): Error { + const error = new Error('browser operation canceled', { cause: reason }) + error.name = 'AbortError' + return error +} + /** Stop a caller's wait while retaining handlers on the resource owner's work. */ function awaitOperation(operation: Promise, signal: AbortSignal): Promise { return new Promise((resolve, reject) => { - const aborted = (): void => { reject(signal.reason instanceof Error ? signal.reason : new Error('browser operation canceled', { cause: signal.reason })) } + const aborted = (): void => { reject(signal.reason instanceof Error ? signal.reason : operationCanceled(signal.reason)) } signal.addEventListener('abort', aborted, { once: true }) void operation.then((value) => { signal.removeEventListener('abort', aborted) @@ -140,19 +150,23 @@ export class SessionResources { return this.disposing ??= Promise.resolve().then(async () => { const settled = await Promise.allSettled([...this.entries].map(([agent, entry]) => this.closeEntry(agent, entry))) const errors = settled.flatMap(result => result.status === 'rejected' ? [result.reason as unknown] : []) - if (errors.length > 0) throw new AggregateError(errors, `${this.options.label}: browser cleanup failed`) + if (errors.length > 0) { + throw new BrowserSessionError(`${this.options.label}: browser cleanup failed`, 'BROWSER_CLEANUP_FAILED', { + cause: new AggregateError(errors, `${this.options.label}: browser cleanup failed`), + }) + } await Promise.all([...this.ownerCleanups.values()].map(close => close())) }) } private entry(agent: Agent): Entry { if (this.disposing !== undefined || this.disposedOwners.has(agent) || this.ctx.get('agents')?.get(agent.id) !== agent) { - throw new Error(`${this.options.label}: Session is not a live browser owner`) + throw new BrowserSessionError(`${this.options.label}: Session is not a live browser owner`, 'BROWSER_OWNER_NOT_LIVE') } const current = this.entries.get(agent) if (current !== undefined) return current if (this.options.exclusive && this.entries.size > 0) { - throw new Error(`${this.options.label}: attached browser is already reserved by another Session`) + throw new BrowserSessionError(`${this.options.label}: attached browser is already reserved by another Session`, 'BROWSER_LOCKED') } if (!this.ownerCleanups.has(agent)) { const cleanup = agent.ctx.effect(() => async () => { @@ -184,7 +198,7 @@ export class SessionResources { private closeEntry(agent: Agent, entry: Entry): Promise { return entry.closing ??= Promise.resolve().then(async () => { - entry.controller.abort(new Error(`${this.options.label}: Session browser is closing`)) + entry.controller.abort(new BrowserSessionError(`${this.options.label}: Session browser is closing`, 'BROWSER_CLOSED')) const resource = await entry.ready.catch(() => undefined) try { await resource?.close() diff --git a/packages/experimental/browser-use-runtime/src/mcp.ts b/packages/experimental/browser-use-runtime/src/mcp.ts index e6abcb6aa8..3fb2e0f43e 100644 --- a/packages/experimental/browser-use-runtime/src/mcp.ts +++ b/packages/experimental/browser-use-runtime/src/mcp.ts @@ -8,9 +8,9 @@ import type { BrowserUseProviderName } from '@deepseek-ai/dsh-browser-use/types' import * as McpClient from '@deepseek-ai/dsh-mcp-client' import { createScope } from '@deepseek-ai/dsh-scope' import type { Scope } from '@deepseek-ai/dsh-scope' -import { SessionResources } from './index.ts' +import { BrowserSessionError, SessionResources } from './index.ts' import type {} from '@deepseek-ai/dsh-browser-use' -import type {} from '@deepseek-ai/dsh-tools' +import { ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import type {} from '@deepseek-ai/dsh-system-prompt' import type {} from '@deepseek-ai/dsh-working-directory' @@ -142,7 +142,7 @@ export function mountSessionMcp(ctx: Context, options: SessionMcpOptions): void if (!exec.name.startsWith(toolPrefix)) return next() if (exec.agent !== agent) { if (ctx.tools.get(exec.name, exec.agent) !== ctx.tools.get(exec.name, agent)) return next() - throw new Error(`${options.name}: browser tool belongs to another Session`) + throw new BrowserSessionError(`${options.name}: browser tool belongs to another Session`, 'BROWSER_FOREIGN_SESSION') } return next() }) @@ -200,8 +200,9 @@ export function mountSessionMcp(ctx: Context, options: SessionMcpOptions): void && (exec.arguments as { server?: unknown }).server === options.name if (!exec.name.startsWith(toolPrefix) && !ownResource) return next() const agent = exec.agent - if (agent === undefined || clients.get(agent)?.status !== 'ready') { - throw new Error(`${options.name}: browser tool belongs to another Session`) + if (agent === undefined) throw new ToolContextUnavailableError(`${options.name}: browser tools require a calling Agent`) + if (clients.get(agent)?.status !== 'ready') { + throw new BrowserSessionError(`${options.name}: browser tool belongs to another Session`, 'BROWSER_FOREIGN_SESSION') } return resources.run(agent, exec.signal, async (_scope, combined) => { const original = exec.signal diff --git a/packages/experimental/browser-use-runtime/tests/mcp.spec.ts b/packages/experimental/browser-use-runtime/tests/mcp.spec.ts index 280d897700..8d91ddc566 100644 --- a/packages/experimental/browser-use-runtime/tests/mcp.spec.ts +++ b/packages/experimental/browser-use-runtime/tests/mcp.spec.ts @@ -119,6 +119,8 @@ async function warm(ctx: Context, agent: Agent, signal = new AbortController().s return ctx.systemPrompt.assemble({ agent, scope: agent, signal }) } +const FOREIGN = { name: 'BrowserSessionError', code: 'BROWSER_FOREIGN_SESSION' } + function execute(ctx: Context, agent: Agent, name = TOOL) { return executeToolFixture(ctx, { agent, name, arguments: name === TOOL ? { label: 'direct' } : {}, callId: brandString('direct'), signal: new AbortController().signal }) } @@ -239,7 +241,7 @@ describe('Session MCP Loader composition', () => { expect(model.requests.map(request => request.tools?.map(tool => tool.name))).toEqual([['unrelated'], ['unrelated']]) for (const { agent } of [second, child]) { expect(ctx.tools.schemas(agent).map(tool => tool.name)).toEqual(['unrelated']) - expect((await execute(ctx, agent)).isError).toBe(true) + expect((await execute(ctx, agent)).error?.info).toEqual(FOREIGN) expect((await execute(ctx, agent, 'unrelated')).isError).toBe(false) expect((await warm(ctx, agent)).tools.map(tool => tool.name)).toEqual(['unrelated']) } @@ -250,13 +252,13 @@ describe('Session MCP Loader composition', () => { }) expect(ctx.tools.schemas(child.agent).filter(tool => tool.name.startsWith('mcp__browser-fixture__'))).toEqual([]) expect((await warm(ctx, child.agent)).tools.map(tool => tool.name)).toEqual(['unrelated']) - expect((await execute(ctx, child.agent, 'mcp__browser-fixture__late')).isError).toBe(true) + expect((await execute(ctx, child.agent, 'mcp__browser-fixture__late')).error?.info).toEqual(FOREIGN) expect((await events(root)).filter(event => event.event === 'initialize')).toHaveLength(1) expect((await events(root)).filter(event => event.event === 'call')).toEqual([]) expect((await execute(ctx, first.agent)).isError).toBe(false) await first.dispose() expect((await warm(ctx, child.agent)).tools.some(tool => tool.name === TOOL)).toBe(false) - expect((await execute(ctx, child.agent)).isError).toBe(true) + expect((await execute(ctx, child.agent)).error?.info).toEqual(FOREIGN) expect((await warm(ctx, second.agent)).tools.map(tool => tool.name)).toEqual(['unrelated']) const successor = await ctx.agents.create({ sessionId: brandString('successor') }) expect((await warm(ctx, successor.agent)).tools.some(tool => tool.name === TOOL)).toBe(true) @@ -367,9 +369,9 @@ describe('Session MCP Loader composition', () => { expect(renderPrompt(blocked)).not.toContain('BROWSER_FIXTURE_INSTRUCTION') expect(renderPrompt(blocked)).toContain('browser-fixture') for (const name of ['list_mcp_resources', 'list_mcp_resource_templates', 'read_mcp_resource']) { - expect((await resource(ctx, child.agent, name)).isError).toBe(true) + expect((await resource(ctx, child.agent, name)).error?.info).toEqual(FOREIGN) } - expect((await resource(ctx, undefined)).isError).toBe(true) + expect((await resource(ctx, undefined)).error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) expect((await events(root)).filter(event => event.event === 'resource')).toEqual([]) expect((await resource(ctx, child.agent, 'read_mcp_resource', 'docs')).value) .toEqual({ contents: [{ uri: 'docs://memo', text: 'Independent document.' }] }) @@ -379,7 +381,7 @@ describe('Session MCP Loader composition', () => { expect(browserState(await resource(ctx, parent.agent)).counter).toBe(0) await parent.dispose() expect(renderPrompt(await warm(ctx, child.agent))).not.toContain('BROWSER_FIXTURE_INSTRUCTION') - expect((await resource(ctx, child.agent)).isError).toBe(true) + expect((await resource(ctx, child.agent)).error?.info).toEqual(FOREIGN) const successor = await ctx.agents.create({ sessionId: brandString('resource-successor') }) expect(renderPrompt(await warm(ctx, successor.agent))).toContain('BROWSER_FIXTURE_INSTRUCTION') expect(browserState(await resource(ctx, successor.agent)).counter).toBe(0) @@ -401,7 +403,7 @@ describe('Session MCP Loader composition', () => { name: 'mcp__browser-fixture__parent_only', description: 'A browser operation available only in the parent.', parameters: { type: 'object' }, output: { schema: { type: 'boolean' }, render: () => [] }, execute: parentOnly, }) - expect((await execute(ctx, child.agent, 'mcp__browser-fixture__parent_only')).isError).toBe(true) + expect((await execute(ctx, child.agent, 'mcp__browser-fixture__parent_only')).error?.info).toEqual(FOREIGN) expect(parentOnly).not.toHaveBeenCalled() const parentState = browserState(await resource(ctx, parent.agent)) const childState = browserState(await resource(ctx, child.agent)) diff --git a/packages/experimental/browser-use-runtime/tests/resources.spec.ts b/packages/experimental/browser-use-runtime/tests/resources.spec.ts index 2f681d88e9..152e1ea59e 100644 --- a/packages/experimental/browser-use-runtime/tests/resources.spec.ts +++ b/packages/experimental/browser-use-runtime/tests/resources.spec.ts @@ -5,11 +5,16 @@ import type { Agent } from '@deepseek-ai/dsh-agent' import { unsupportedModel, unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' import { Session, type SessionId } from '@deepseek-ai/dsh-session' import { afterEach, describe, expect, it, vi } from 'vitest' -import { SessionResources } from '../src/index.ts' +import { BrowserSessionError, SessionResources } from '../src/index.ts' +import type { BrowserSessionErrorCode } from '../src/index.ts' import { brandString } from '@deepseek-ai/dsh-brand' const contexts: Context[] = [] +function browserError(code: BrowserSessionErrorCode, message: string) { + return { constructor: BrowserSessionError, name: 'BrowserSessionError', code, message: expect.stringContaining(message) as string } +} + async function fixture() { const ctx = new Context() contexts.push(ctx) @@ -51,13 +56,13 @@ describe('Session browser resource ownership', () => { expect(open).toHaveBeenCalledTimes(2) await a.dispose() expect(close).toHaveBeenCalledTimes(1) - await expect(resources.get(a.agent)).rejects.toThrow('not a live browser owner') + await expect(resources.get(a.agent)).rejects.toMatchObject(browserError('BROWSER_OWNER_NOT_LIVE', 'not a live browser owner')) const resumed = await owner('a') expect(await resources.get(resumed.agent)).not.toBe(first) await resources.dispose() expect(close).toHaveBeenCalledTimes(3) expect(resources.available(b.agent)).toBe(false) - await expect(resources.get(b.agent)).rejects.toThrow('not a live browser owner') + await expect(resources.get(b.agent)).rejects.toMatchObject(browserError('BROWSER_OWNER_NOT_LIVE', 'not a live browser owner')) }) it('reserves an attached browser while acquisition or cleanup is pending', async () => { @@ -79,14 +84,14 @@ describe('Session browser resource ownership', () => { const first = resources.get(a.agent) expect(resources.available(a.agent)).toBe(true) expect(resources.available(b.agent)).toBe(false) - await expect(resources.get(b.agent)).rejects.toThrow('already reserved') + await expect(resources.get(b.agent)).rejects.toMatchObject(browserError('BROWSER_LOCKED', 'already reserved')) opened.resolve(undefined) await first const disposing = a.dispose() await closing.promise expect(resources.available(a.agent)).toBe(false) expect(resources.available(b.agent)).toBe(false) - await expect(resources.get(b.agent)).rejects.toThrow('already reserved') + await expect(resources.get(b.agent)).rejects.toMatchObject(browserError('BROWSER_LOCKED', 'already reserved')) released.resolve(undefined) await disposing expect(resources.available(b.agent)).toBe(true) @@ -260,7 +265,7 @@ describe('Session browser resource ownership', () => { const resources = new SessionResources(ctx, { label: 'test', exclusive: false, open }) const controller = new AbortController() const waiting = resources.get(a.agent, controller.signal) - const canceled = expect(waiting).rejects.toMatchObject({ message: 'browser operation canceled', cause: 'stop' }) + const canceled = expect(waiting).rejects.toMatchObject({ name: 'AbortError', message: 'browser operation canceled', cause: 'stop' }) await entered.promise controller.abort('stop') await canceled @@ -286,7 +291,7 @@ describe('Session browser resource ownership', () => { async open() { entered.resolve(undefined); await release.promise; return { value: {}, close } }, }) const acquiring = resources.get(a.agent) - const rejected = expect(acquiring).rejects.toThrow('closing') + const rejected = expect(acquiring).rejects.toMatchObject(browserError('BROWSER_CLOSED', 'closing')) await entered.promise const ownerDisposal = a.dispose() const providerDisposal = resources.dispose() @@ -315,7 +320,7 @@ describe('Session browser resource ownership', () => { await stopped.promise signal.throwIfAborted() }) - const rejected = expect(call).rejects.toThrow('closing') + const rejected = expect(call).rejects.toMatchObject(browserError('BROWSER_CLOSED', 'closing')) await running.promise await resources.dispose() await rejected @@ -331,9 +336,9 @@ describe('Session browser resource ownership', () => { }) await resources.get(a.agent) await a.dispose() - await expect(resources.get(b.agent)).rejects.toThrow('already reserved') - await expect(resources.dispose()).rejects.toThrow('browser cleanup failed') - await expect(resources.get(b.agent)).rejects.toThrow('not a live browser owner') + await expect(resources.get(b.agent)).rejects.toMatchObject(browserError('BROWSER_LOCKED', 'already reserved')) + await expect(resources.dispose()).rejects.toMatchObject(browserError('BROWSER_CLEANUP_FAILED', 'browser cleanup failed')) + await expect(resources.get(b.agent)).rejects.toMatchObject(browserError('BROWSER_OWNER_NOT_LIVE', 'not a live browser owner')) }) }) @@ -356,6 +361,6 @@ it('reports early disposal cleanup failure while retaining the owned resource', await canceled await a.dispose() expect(warning).toHaveBeenCalledWith(expect.stringContaining('cleanup during Session cancellation failed')) - await expect(resources.dispose()).rejects.toThrow('browser cleanup failed') + await expect(resources.dispose()).rejects.toMatchObject(browserError('BROWSER_CLEANUP_FAILED', 'browser cleanup failed')) warning.mockRestore() }) diff --git a/packages/experimental/browser-use-runtime/tsconfig.json b/packages/experimental/browser-use-runtime/tsconfig.json index 00b48e2bd2..18d490d01b 100644 --- a/packages/experimental/browser-use-runtime/tsconfig.json +++ b/packages/experimental/browser-use-runtime/tsconfig.json @@ -23,6 +23,9 @@ { "path": "../../core/tools" }, + { + "path": "../../util/error" + }, { "path": "../../core/scope" }, diff --git a/packages/experimental/browser-use-stagehand-native/README.i18n.yaml b/packages/experimental/browser-use-stagehand-native/README.i18n.yaml index 21daa32757..1ed9d62414 100644 --- a/packages/experimental/browser-use-stagehand-native/README.i18n.yaml +++ b/packages/experimental/browser-use-stagehand-native/README.i18n.yaml @@ -24,8 +24,8 @@ en: fea3ad16a77fc478 zh: cf551a8a2d183f93 /deepseek-ai-dsh-experimental-browser-use-stagehand-native/understand-the-implementation: - en: 123351a7c3d46f3e - zh: bf1cc2628edeb8d7 + en: 73d71db97181cced + zh: b399d77fd05fbdb2 /deepseek-ai-dsh-experimental-browser-use-stagehand-native/further-exploration: en: eff8f4541eb26ca7 zh: 76a61fe9bd48df2a diff --git a/packages/experimental/browser-use-stagehand-native/README.md b/packages/experimental/browser-use-stagehand-native/README.md index b6726b3650..2acddfa04c 100644 --- a/packages/experimental/browser-use-stagehand-native/README.md +++ b/packages/experimental/browser-use-stagehand-native/README.md @@ -89,6 +89,8 @@ env -u NODE_USE_ENV_PROXY DSH_STAGEHAND_E2E=1 pnpm exec vitest run --config vite The host owns each launched Chromium process and its temporary profile before waiting for CDP readiness. Chromium receives the standard scrubbed child environment, preserving paths, locale, and proxy settings while excluding credential-shaped variables and DSH identity. Both modes connect the SDK inside a dedicated Worker. The Worker receives no ambient environment except the explicit source TypeScript configuration path, so its CDP connection does not inherit host proxy settings. SDK close waits for active operations. Cleanup terminates the connection Worker after the configured SDK grace; launch also kills and awaits its owned Chromium process before removing the profile. Attached external browsers remain open. Cleanup failures follow the [ownership limits](#known-limitations-and-deferred-work) below. +Failed calls carry `error.name` and `error.code` on `tool/result`. The host validates arguments before dispatch and rejects ones the method's schema refuses with `ToolArgsError` (`INVALID_ARGS`); a call without an exact live Agent fails with `ToolContextUnavailableError`, and ownership failures use the runtime's `BrowserSessionError` codes. Other failures throw `StagehandError` with a closed set of codes: `STAGEHAND_ACT_FAILED` when Stagehand reports an unsuccessful action, `STAGEHAND_TAB_NOT_FOUND` for an unavailable tab, `STAGEHAND_OPERATION_FAILED` for any other SDK or browser failure, `STAGEHAND_WORKER_FAILED` when the Worker exits, closes, or breaks the message protocol, and `STAGEHAND_CLEANUP_FAILED` from the `StagehandDrainError` subclass when SDK requests do not drain. Worker replies carry a `StagehandError`'s name and code beside its message, and the host rebuilds the same code; any other Worker failure, including an unknown name or code, becomes `STAGEHAND_OPERATION_FAILED` with the Worker's message. + The [native runtime](src/native.ts) passes the explicit model configuration to Stagehand's public initialization API. The adapter pins Zod to the version required by Stagehand because extraction passes Zod schemas to the SDK. Stagehand owns the model requests, response validation, and token accounting inside its browser extension. DSH records browser tool inputs and returned data, including SDK result metadata, through the existing Session log. Underlying inference request/response capture and integration into DSH Session usage accounting are deferred. diff --git a/packages/experimental/browser-use-stagehand-native/README.zh.md b/packages/experimental/browser-use-stagehand-native/README.zh.md index d980760c27..efa263afe5 100644 --- a/packages/experimental/browser-use-stagehand-native/README.zh.md +++ b/packages/experimental/browser-use-stagehand-native/README.zh.md @@ -89,6 +89,8 @@ env -u NODE_USE_ENV_PROXY DSH_STAGEHAND_E2E=1 pnpm exec vitest run --config vite 宿主在等待 CDP 就绪前即拥有启动的 Chromium 进程及其临时配置目录。Chromium 接收标准清理后的子进程环境,保留路径、区域设置和代理配置,排除凭据形式的变量及 DSH 身份信息。两种模式都在独立 Worker 中连接 SDK。Worker 除显式的源码 TypeScript 配置路径外不接收宿主环境,因此其 CDP 连接不继承宿主代理设置。SDK 关闭会等待活动操作。清理在配置的 SDK 宽限时间后终止连接 Worker;启动模式还会终止并等待自有 Chromium 进程退出,再移除配置目录。外部连接的浏览器保持运行。清理失败遵循下方的[所有权限制](#known-limitations-and-deferred-work)。 +失败调用在 `tool/result` 上带有 `error.name` 与 `error.code`。宿主在派发前验证参数,方法 schema 拒绝的参数以 `ToolArgsError`(`INVALID_ARGS`)失败;没有确切实时 Agent 的调用以 `ToolContextUnavailableError` 失败,所有权失败使用运行时库的 `BrowserSessionError` 代码。其他失败抛出 `StagehandError`,其代码为封闭集合:Stagehand 报告动作未成功时为 `STAGEHAND_ACT_FAILED`,标签页不可用时为 `STAGEHAND_TAB_NOT_FOUND`,其他 SDK 或浏览器失败为 `STAGEHAND_OPERATION_FAILED`,Worker 退出、关闭或违反消息协议时为 `STAGEHAND_WORKER_FAILED`,SDK 请求未能结束时由 `StagehandDrainError` 子类给出 `STAGEHAND_CLEANUP_FAILED`。Worker 回复在消息旁携带 `StagehandError` 的名称和代码,宿主据此重建相同代码;其他 Worker 失败,包括未知名称或代码,以 Worker 的消息成为 `STAGEHAND_OPERATION_FAILED`。 + [原生运行时](src/native.ts)将显式模型配置传入 Stagehand 的公开初始化 API。适配器将 Zod 固定为 Stagehand 要求的版本,因为提取操作会向 SDK 传递 Zod schema。Stagehand 在其浏览器扩展中负责模型请求、响应验证与 token 计量。DSH 通过现有 Session 日志记录浏览器工具输入和返回数据,包括 SDK 结果元数据。底层推理请求/响应捕获及其与 DSH Session 用量计量的集成均属暂缓工作。 diff --git a/packages/experimental/browser-use-stagehand-native/package.json b/packages/experimental/browser-use-stagehand-native/package.json index 60bc689b36..959cd932d1 100644 --- a/packages/experimental/browser-use-stagehand-native/package.json +++ b/packages/experimental/browser-use-stagehand-native/package.json @@ -41,7 +41,8 @@ "@deepseek-ai/dsh-agent": "workspace:*", "@deepseek-ai/dsh-browser-use": "workspace:*", "@deepseek-ai/dsh-system-prompt": "workspace:*", - "@deepseek-ai/dsh-tools": "workspace:*" + "@deepseek-ai/dsh-tools": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" }, "dependencies": { "@deepseek-ai/dsh-brand": "workspace:*", @@ -71,6 +72,7 @@ "@deepseek-ai/dsh-tool-executor-native": "workspace:*", "@deepseek-ai/dsh-tool-testkit": "workspace:*", "@deepseek-ai/dsh-tools": "workspace:*", - "tsx": "^4.23.13" + "tsx": "^4.23.13", + "@deepseek-ai/dsh-error": "workspace:*" } } diff --git a/packages/experimental/browser-use-stagehand-native/src/error.ts b/packages/experimental/browser-use-stagehand-native/src/error.ts new file mode 100644 index 0000000000..e5db840212 --- /dev/null +++ b/packages/experimental/browser-use-stagehand-native/src/error.ts @@ -0,0 +1,61 @@ +/** Machine-routable Stagehand browser failures, shared by the host and its browser Worker. @module */ + +import { HarnessError } from '@deepseek-ai/dsh-error' + +/** + * Every {@link StagehandError} code: + * - `STAGEHAND_ACT_FAILED` — Stagehand reported that a natural-language action did not succeed; inspect the page and + * rephrase or retry. + * - `STAGEHAND_TAB_NOT_FOUND` — the requested tab, or an active tab, is unavailable; list tabs and select a current pageId. + * - `STAGEHAND_OPERATION_FAILED` — the Stagehand SDK or browser failed the operation in a way this provider does not + * classify; the message carries the SDK's text. + * - `STAGEHAND_WORKER_FAILED` — the browser Worker exited, closed, or broke its message protocol; a later call reconnects. + * - `STAGEHAND_CLEANUP_FAILED` — SDK requests did not drain before the Worker terminated; the connection is not reused. + */ +export const STAGEHAND_ERROR_CODES = [ + 'STAGEHAND_ACT_FAILED', + 'STAGEHAND_TAB_NOT_FOUND', + 'STAGEHAND_OPERATION_FAILED', + 'STAGEHAND_WORKER_FAILED', + 'STAGEHAND_CLEANUP_FAILED', +] as const + +/** One code from {@link STAGEHAND_ERROR_CODES}. */ +export type StagehandErrorCode = typeof STAGEHAND_ERROR_CODES[number] + +/** + * Narrow a code received across the Worker boundary. + * @param code - untrusted code from a Worker reply. + * @returns whether the code is one of {@link STAGEHAND_ERROR_CODES}. + */ +export function isStagehandErrorCode(code: unknown): code is StagehandErrorCode { + return (STAGEHAND_ERROR_CODES as readonly unknown[]).includes(code) +} + +/** Stagehand browser failure carrying a stable {@link StagehandErrorCode}. */ +export class StagehandError extends HarnessError { + override readonly code: StagehandErrorCode + + /** + * @param message - names the browser operation and the safe next step. + * @param code - the failure class consumers route on. + * @param options - standard `cause` chaining. + */ + constructor(message: string, code: StagehandErrorCode, options?: ErrorOptions) { + super(message, code, options) + this.name = 'StagehandError' + this.code = code + } +} + +/** SDK requests did not drain before their connection Worker terminated; code `STAGEHAND_CLEANUP_FAILED`. */ +export class StagehandDrainError extends StagehandError { + /** + * @param message - the drain failure and its underlying cleanup error. + * @param options - standard `cause` chaining. + */ + constructor(message: string, options?: ErrorOptions) { + super(message, 'STAGEHAND_CLEANUP_FAILED', options) + this.name = 'StagehandDrainError' + } +} diff --git a/packages/experimental/browser-use-stagehand-native/src/index.ts b/packages/experimental/browser-use-stagehand-native/src/index.ts index 06870a2331..13e9c17b81 100644 --- a/packages/experimental/browser-use-stagehand-native/src/index.ts +++ b/packages/experimental/browser-use-stagehand-native/src/index.ts @@ -10,14 +10,17 @@ import type { BrowserUseProviderName } from '@deepseek-ai/dsh-browser-use/types' import { SessionResources } from '@deepseek-ai/dsh-experimental-browser-use-runtime' import { createMcpToolDefinition } from '@deepseek-ai/dsh-mcp-client' import { z } from 'zod' -import { browserInputs, stagehandModelSchema, StagehandDrainError } from './native.ts' +import { browserInputs, stagehandModelSchema } from './native.ts' +import { StagehandDrainError } from './error.ts' import type { BrowserMethod, NativeBrowserRuntime, StagehandModelConfig } from './native.ts' import { openBrowserWorker } from './worker-client.ts' import { launchChromium } from './launch.ts' import type {} from '@deepseek-ai/dsh-agent' import type {} from '@deepseek-ai/dsh-browser-use' import type {} from '@deepseek-ai/dsh-system-prompt' -import type {} from '@deepseek-ai/dsh-tools' +import { ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' + +export { StagehandDrainError, StagehandError, type StagehandErrorCode } from './error.ts' /** Cordis identity for the native Stagehand provider. */ export const name = 'experimental-browser-use-stagehand-native' @@ -190,7 +193,14 @@ function mountTools(ctx: Context, resources: SessionResources): if (!names.has(exec.name)) return next() const agent = exec.agent if (agent === undefined || ctx.agents.get(agent.id) !== agent) { - throw new Error('Stagehand browser tools require an exact live Agent') + throw new ToolContextUnavailableError('Stagehand browser tools require an exact live Agent') + } + // Arguments are checked before the browser is acquired, so an invalid first call launches nothing. + // A non-object value is read as `{}`, exactly as the MCP bridge passes it to the call. + const args = typeof exec.arguments === 'object' && exec.arguments !== null ? exec.arguments : {} + const parsed = browserInputs[exec.name.slice('stagehand_'.length) as BrowserMethod].safeParse(args) + if (!parsed.success) { + throw new ToolArgsError(parsed.error.issues.map(issue => `${['arguments', ...issue.path].join('.')}: ${issue.message}`)) } return resources.run(agent, exec.signal, async (resource, activeSignal) => { const upstreamSignal = exec.signal diff --git a/packages/experimental/browser-use-stagehand-native/src/native.ts b/packages/experimental/browser-use-stagehand-native/src/native.ts index 34cab652b2..8710615734 100644 --- a/packages/experimental/browser-use-stagehand-native/src/native.ts +++ b/packages/experimental/browser-use-stagehand-native/src/native.ts @@ -4,6 +4,9 @@ import { StagehandClientCreateConfigSchema } from '@browserbasehq/stagehand' import type { ModelConfig, Page, StagehandBrowser } from '@browserbasehq/stagehand' import { assertNever } from '@deepseek-ai/dsh-util-values' import { z } from 'zod' +import { StagehandError } from './error.ts' + +export { StagehandDrainError } from './error.ts' /** Profile-owned model settings accepted by the pinned Stagehand SDK. */ export interface StagehandModelConfig { @@ -67,9 +70,6 @@ export const browserInputs = { /** Closed set of native browser operations. */ export type BrowserMethod = keyof typeof browserInputs -/** SDK requests did not drain before their connection Worker terminated. */ -export class StagehandDrainError extends Error {} - /** Native browser operations and SDK cleanup owned by one live Session. */ export interface NativeBrowserRuntime { /** @@ -131,7 +131,7 @@ export async function openNativeBrowser(config: NativeBrowserConfig): Promise candidate.pageId === pageId) - if (page === undefined) throw new Error('Stagehand browser tab is unavailable; list tabs to select a current pageId') + if (page === undefined) throw new StagehandError('Stagehand browser tab is unavailable; list tabs to select a current pageId', 'STAGEHAND_TAB_NOT_FOUND') return page } diff --git a/packages/experimental/browser-use-stagehand-native/src/worker-client.ts b/packages/experimental/browser-use-stagehand-native/src/worker-client.ts index 103c8dd81c..10b37e7d1f 100644 --- a/packages/experimental/browser-use-stagehand-native/src/worker-client.ts +++ b/packages/experimental/browser-use-stagehand-native/src/worker-client.ts @@ -1,7 +1,7 @@ /** Isolated Stagehand Workers own CDP connections; the host owns browser processes. */ import { Worker } from 'node:worker_threads' -import { StagehandDrainError } from './native.ts' +import { StagehandDrainError, StagehandError } from './error.ts' import type { NativeBrowserConfig, NativeBrowserRuntime } from './native.ts' import { request } from './worker-rpc.ts' @@ -32,8 +32,8 @@ export async function openBrowserWorker( let termination: Promise | undefined const terminate = () => termination ??= worker.terminate() const lifetime = new AbortController() - worker.once('error', (error) => { lifetime.abort(error) }) - worker.once('exit', (code) => { lifetime.abort(new Error(`Stagehand browser Worker exited (${code})`)) }) + worker.once('error', (error) => { lifetime.abort(new StagehandError(error.message, 'STAGEHAND_WORKER_FAILED', { cause: error })) }) + worker.once('exit', (code) => { lifetime.abort(new StagehandError(`Stagehand browser Worker exited (${code})`, 'STAGEHAND_WORKER_FAILED')) }) let closing: Promise | undefined const close = () => closing ??= (async () => { let timeout: ReturnType | undefined @@ -71,7 +71,7 @@ export async function openBrowserWorker( async execute(method, args, signal) { signal?.throwIfAborted() lifetime.signal.throwIfAborted() - if (closing !== undefined) throw new Error('Stagehand browser Worker is closed') + if (closing !== undefined) throw new StagehandError('Stagehand browser Worker is closed', 'STAGEHAND_WORKER_FAILED') const canceled = () => { void close().catch((error: unknown) => { lifetime.abort(error) }) } signal?.addEventListener('abort', canceled, { once: true }) try { diff --git a/packages/experimental/browser-use-stagehand-native/src/worker-rpc.ts b/packages/experimental/browser-use-stagehand-native/src/worker-rpc.ts index 75c201ace6..5e96aa9afc 100644 --- a/packages/experimental/browser-use-stagehand-native/src/worker-rpc.ts +++ b/packages/experimental/browser-use-stagehand-native/src/worker-rpc.ts @@ -3,12 +3,28 @@ import { MessageChannel, MessagePort } from 'node:worker_threads' import type { Worker } from 'node:worker_threads' import { z } from 'zod' +import { isStagehandErrorCode, StagehandError } from './error.ts' const responseSchema = z.discriminatedUnion('ok', [ z.object({ ok: z.literal(true), value: z.unknown() }).strict(), - z.object({ ok: z.literal(false), error: z.string() }).strict(), + z.object({ ok: z.literal(false), error: z.string(), name: z.string().optional(), code: z.string().optional() }).strict(), ]) +/** + * Rebuild a Worker operation failure on the host. A {@link StagehandError} + * keeps its code; any other failure, including an unknown name or code, + * becomes `STAGEHAND_OPERATION_FAILED` with the Worker's message. + */ +function operationFailure(failure: { error: string; name?: string | undefined; code?: string | undefined }): StagehandError { + return failure.name === 'StagehandError' && isStagehandErrorCode(failure.code) + ? new StagehandError(failure.error, failure.code) + : new StagehandError(failure.error, 'STAGEHAND_OPERATION_FAILED') +} + +function workerFailure(message: string, cause?: unknown): StagehandError { + return new StagehandError(message, 'STAGEHAND_WORKER_FAILED', cause === undefined ? undefined : { cause }) +} + /** Transferable reply channel paired with a validated operation payload. */ export const requestSchema = z.object({ method: z.string(), @@ -22,29 +38,32 @@ export const requestSchema = z.object({ * @param method - operation understood by the receiver. * @param args - structured-cloneable request data. * @param signal - owning Worker lifetime, when observed by the caller. - * @returns the receiver's value, rejecting malformed responses and peer shutdown. + * @returns the receiver's value. Malformed responses and peer shutdown reject with `STAGEHAND_WORKER_FAILED`; + * a receiver failure rejects as rebuilt by its `StagehandError` code. */ export async function request(target: MessagePort | Worker, method: string, args?: unknown, signal?: AbortSignal): Promise { signal?.throwIfAborted() const { port1, port2 } = new MessageChannel() const result = Promise.withResolvers() const abort = () => { - result.reject(signal?.reason instanceof Error ? signal.reason : new Error('Stagehand Worker request canceled')) + result.reject(signal?.reason instanceof Error ? signal.reason : workerFailure('Stagehand Worker request canceled', signal?.reason)) } + const transportFailure = (error: Error): void => { result.reject(workerFailure(error.message, error)) } try { signal?.addEventListener('abort', abort, { once: true }) port1.once('message', (raw: unknown) => { const response = responseSchema.safeParse(raw) - if (!response.success) result.reject(response.error) + if (!response.success) result.reject(workerFailure('Stagehand Worker returned a malformed response', response.error)) else if (response.data.ok) result.resolve(response.data.value) - else result.reject(new Error(response.data.error)) + else result.reject(operationFailure(response.data)) }) - port1.once('messageerror', result.reject) - port1.once('close', () => { result.reject(new Error('Stagehand Worker reply channel closed')) }) + port1.once('messageerror', transportFailure) + port1.once('close', () => { result.reject(workerFailure('Stagehand Worker reply channel closed')) }) try { target.postMessage({ method, args, reply: port2 }, [port2]) } catch (error) { - result.reject(error) + // postMessage reports clone and transfer failures as DOMException instances. + transportFailure(error as Error) } return await result.promise } finally { @@ -56,6 +75,7 @@ export async function request(target: MessagePort | Worker, method: string, args /** * Validate and answer one request without leaving rejected callbacks unobserved. + * A rejected {@link StagehandError} sends its `name` and `code` beside the message. * @param raw - untrusted message received from the Worker boundary. * @param execute - owner that validates and executes the method arguments. * @returns after the response has been posted and the reply port released. @@ -65,7 +85,9 @@ export async function answer(raw: unknown, execute: (method: string, args: unkno try { reply.postMessage({ ok: true, value: await execute(method, args) }) } catch (error) { - reply.postMessage({ ok: false, error: error instanceof Error ? error.message : String(error) }) + reply.postMessage(error instanceof StagehandError + ? { ok: false, error: error.message, name: error.name, code: error.code } + : { ok: false, error: error instanceof Error ? error.message : String(error) }) } finally { reply.close() } diff --git a/packages/experimental/browser-use-stagehand-native/tests/provider.spec.ts b/packages/experimental/browser-use-stagehand-native/tests/provider.spec.ts index 6c7caaf2fb..c3bbda0b3f 100644 --- a/packages/experimental/browser-use-stagehand-native/tests/provider.spec.ts +++ b/packages/experimental/browser-use-stagehand-native/tests/provider.spec.ts @@ -43,6 +43,7 @@ vi.mock('../src/launch.ts', async (importActual) => { }) vi.mock('../src/worker-client.ts', async () => { const { openNativeBrowser } = await import('../src/native.ts') + const { StagehandError } = await import('../src/error.ts') return { async openBrowserWorker(config: NativeBrowserConfig, signal: AbortSignal, warn: (message: string) => void) { acquisition.signal = signal @@ -55,7 +56,7 @@ vi.mock('../src/worker-client.ts', async () => { })() return { async execute(method: import('../src/native.ts').BrowserMethod, args: unknown, signal?: AbortSignal) { - if (closing !== undefined) throw new Error('Fixture connection is closed') + if (closing !== undefined) throw new StagehandError('Fixture connection is closed', 'STAGEHAND_WORKER_FAILED') const cancel = () => { void close().catch(() => {}) } signal?.addEventListener('abort', cancel, { once: true }) try { return await native.execute(method, args) } finally { signal?.removeEventListener('abort', cancel) } @@ -91,6 +92,8 @@ beforeEach(async () => { afterEach(async () => { await ctx.fiber.dispose() }) +const INVALID_ARGS = { name: 'ToolArgsError', code: 'INVALID_ARGS' } + function execute(agent: Agent, suffix: string, args: unknown, signal = new AbortController().signal) { return executeToolFixture(ctx, { agent, name: `stagehand_${suffix}`, arguments: args, callId: brandString(`test-${suffix}`), signal }) } @@ -120,11 +123,27 @@ it('lazily launches distinct browsers and preserves each Session tab state', asy it('reserves an attached browser for one live owner and rejects model connection overrides', async () => { await ctx.plugin(Provider, { model: nativeModel, mode: 'attach', cdpEndpoint: 'http://localhost:9222' }) expect((await execute(first, 'tabs', { action: 'list' })).isError).toBe(false) - expect((await execute(second, 'tabs', { action: 'list' })).isError).toBe(true) + expect((await execute(second, 'tabs', { action: 'list' })).error?.info).toEqual({ name: 'BrowserSessionError', code: 'BROWSER_LOCKED' }) expect(fixture.browsers).toHaveLength(1) expect(fixture.browsers[0]?.options).toEqual({ cdpUrl: 'http://localhost:9222' }) - expect((await execute(first, 'navigate', { url: 'https://example.com', cdpEndpoint: 'http://other' })).isError).toBe(true) - expect((await execute(first, 'act', { instruction: 'click', model: 'other' })).isError).toBe(true) + expect((await execute(first, 'navigate', { url: 'https://example.com', cdpEndpoint: 'http://other' })).error?.info).toEqual(INVALID_ARGS) + expect((await execute(first, 'act', { instruction: 'click', model: 'other' })).error?.info).toEqual(INVALID_ARGS) + const malformed = await execute(first, 'navigate', { url: 'not a url' }) + expect(malformed.error?.info).toEqual(INVALID_ARGS) + expect(malformed.content).toEqual([{ type: 'text', text: 'Error: invalid arguments: arguments.url: Invalid URL' }]) +}) + +it('rejects invalid arguments before acquiring a browser', async () => { + await ctx.plugin(Provider, { model: nativeModel, mode: 'launch' }) + expect((await execute(first, 'navigate', { url: 'not a url' })).error?.info).toEqual(INVALID_ARGS) + expect(fixture.browsers).toEqual([]) +}) + +it('reads non-object arguments as an empty request, as the MCP bridge does', async () => { + await ctx.plugin(Provider, { model: nativeModel, mode: 'launch' }) + const result = await execute(first, 'screenshot', null) + expect(result.isError).toBe(false) + expect(fixture.browsers).toHaveLength(1) }) it('uses its independent model for actions, observations, and a caller-selected extraction schema', async () => { @@ -143,14 +162,15 @@ it('uses its independent model for actions, observations, and a caller-selected fixture.actResult = { success: false, message: 'Fixture button unavailable' } fixture.result = { extraction: 'Missing button' } const refused = await execute(first, 'act', { instruction: 'Click the missing button' }) - expect(refused.isError).toBe(true) + expect(refused.error?.info).toEqual({ name: 'StagehandError', code: 'STAGEHAND_ACT_FAILED' }) expect(JSON.stringify(refused.content)).toContain('Fixture button unavailable') }) it('refuses unavailable tabs and calls without an exact live Agent', async () => { await ctx.plugin(Provider, { model: nativeModel, mode: 'launch' }) - expect((await execute(first, 'navigate', { url: 'https://example.com', pageId: 'missing' })).isError).toBe(true) - expect((await executeToolFixture(ctx, { name: 'stagehand_tabs', arguments: { action: 'list' }, callId: brandString('agentless'), signal: new AbortController().signal })).isError).toBe(true) + expect((await execute(first, 'navigate', { url: 'https://example.com', pageId: 'missing' })).error?.info).toEqual({ name: 'StagehandError', code: 'STAGEHAND_TAB_NOT_FOUND' }) + expect((await executeToolFixture(ctx, { name: 'stagehand_tabs', arguments: { action: 'list' }, callId: brandString('agentless'), signal: new AbortController().signal })).error?.info) + .toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) ctx.tools.register({ name: 'unrelated', description: 'An independent tool.', parameters: { type: 'object' }, output: { schema: { type: 'boolean' }, render: () => [{ type: 'text', text: 'independent' }] }, execute: async () => true }) const unrelated = await executeToolFixture(ctx, { agent: first, name: 'unrelated', arguments: {}, callId: brandString('unrelated'), signal: new AbortController().signal }) expect(unrelated.isError).toBe(false) @@ -242,7 +262,9 @@ it.each(['cancel', 'dispose'] as const)('drains native inference before completi } finally { release.resolve() await disposal - expect((await operation).isError).toBe(true) + const settled = await operation + expect(settled.isError).toBe(true) + if (reason === 'cancel') expect(settled.error?.info).toEqual({ name: 'AbortError', code: 'ABORTED' }) } expect(fixture.browsers[0]?.stagehandClosed).toBe(true) expect(fixture.browsers[0]?.closed).toBe(false) @@ -413,9 +435,9 @@ it('blocks reconnection and another owner after canceled native work fails to dr } finally { release.resolve() } - expect((await operation).isError).toBe(true) - expect((await execute(first, 'tabs', { action: 'list' })).isError).toBe(true) - expect((await execute(second, 'tabs', { action: 'list' })).isError).toBe(true) + expect((await operation).error?.info).toEqual({ name: 'AbortError', code: 'ABORTED' }) + expect((await execute(first, 'tabs', { action: 'list' })).error?.info).toEqual({ name: 'StagehandError', code: 'STAGEHAND_WORKER_FAILED' }) + expect((await execute(second, 'tabs', { action: 'list' })).error?.info).toEqual({ name: 'BrowserSessionError', code: 'BROWSER_LOCKED' }) expect(fixture.browsers).toHaveLength(1) await provider.dispose() expect(fixture.browsers[0]?.closed).toBe(false) diff --git a/packages/experimental/browser-use-stagehand-native/tests/worker-client.spec.ts b/packages/experimental/browser-use-stagehand-native/tests/worker-client.spec.ts index d5eeaca667..f20b9f3f27 100644 --- a/packages/experimental/browser-use-stagehand-native/tests/worker-client.spec.ts +++ b/packages/experimental/browser-use-stagehand-native/tests/worker-client.spec.ts @@ -8,6 +8,10 @@ import { openBrowserWorker } from '../src/worker-client.ts' import type { NativeBrowserConfig, NativeBrowserRuntime } from '../src/native.ts' import { nativeModel } from './fixtures/stagehand.ts' +function workerFailed(message: RegExp) { + return { name: 'StagehandError', code: 'STAGEHAND_WORKER_FAILED', message: expect.stringMatching(message) as string } +} + const state = vi.hoisted(() => ({ workers: [] as Worker[], entries: [] as string[] })) vi.mock('node:worker_threads', async (importActual) => { const actual = await importActual() @@ -94,18 +98,19 @@ it('terminates a Worker whose initialization overlaps acquisition cancellation', it('fails active and later operations when the Worker exits', async () => { const runtime = await open('crash') const exited = once(state.workers[0]!, 'exit') - await expect(runtime.execute('tabs', { action: 'list' })).rejects.toThrow(/Worker (exited|reply channel closed)/u) + await expect(runtime.execute('tabs', { action: 'list' })) + .rejects.toMatchObject(workerFailed(/Worker (exited|reply channel closed)/u)) await exited - await expect(runtime.execute('tabs', { action: 'list' })).rejects.toThrow('Worker exited (23)') - await expect(runtime.close()).rejects.toThrow('Worker exited (23)') + await expect(runtime.execute('tabs', { action: 'list' })).rejects.toMatchObject(workerFailed(/Worker exited \(23\)/u)) + await expect(runtime.close()).rejects.toMatchObject({ name: 'StagehandDrainError', code: 'STAGEHAND_CLEANUP_FAILED', message: expect.stringContaining('Worker exited (23)') as string }) }) it.each(['closing', 'close-failure'])('rejects cleanup after an undrained extension (%s) even though its Worker terminates', async (scenario) => { const runtime = await openBrowserWorker({ ...config(scenario), shutdownGraceMs: 20 }, new AbortController().signal, warn) runtimes.push(runtime) const closing = runtime.close() - const rejected = expect(closing).rejects.toThrow(/cleanup timed out|did not drain/u) - await expect(runtime.execute('tabs', { action: 'list' })).rejects.toThrow('Worker is closed') + const rejected = expect(closing).rejects.toMatchObject({ name: 'StagehandDrainError', code: 'STAGEHAND_CLEANUP_FAILED', message: expect.stringMatching(/cleanup timed out|did not drain/u) as string }) + await expect(runtime.execute('tabs', { action: 'list' })).rejects.toMatchObject(workerFailed(/Worker is closed/u)) await rejected expect(warn).toHaveBeenCalledWith(expect.stringContaining('SDK cleanup did not finish')) expect(state.workers[0]?.threadId).toBe(-1) @@ -114,7 +119,7 @@ it.each(['closing', 'close-failure'])('rejects cleanup after an undrained extens it('rejects cleanup after a Worker crashes', async () => { const runtime = await open('error') - await expect(runtime.execute('tabs', { action: 'list' })).rejects.toThrow() + await expect(runtime.execute('tabs', { action: 'list' })).rejects.toMatchObject(workerFailed(/./u)) await expect(runtime.close()).rejects.toThrow() expect(state.workers[0]?.threadId).toBe(-1) }) diff --git a/packages/experimental/browser-use-stagehand-native/tests/worker-rpc.spec.ts b/packages/experimental/browser-use-stagehand-native/tests/worker-rpc.spec.ts index e67c50be26..9fbf5ec3eb 100644 --- a/packages/experimental/browser-use-stagehand-native/tests/worker-rpc.spec.ts +++ b/packages/experimental/browser-use-stagehand-native/tests/worker-rpc.spec.ts @@ -4,6 +4,7 @@ import { getEventListeners, once } from 'node:events' import { MessageChannel } from 'node:worker_threads' import type { MessagePort } from 'node:worker_threads' import { afterEach, expect, it, vi } from 'vitest' +import { StagehandError } from '../src/error.ts' import { answer, request, requestSchema } from '../src/worker-rpc.ts' const cleanups: Array<() => Promise> = [] @@ -51,13 +52,37 @@ it.each([new Error('Browser operation failed'), 'Browser operation refused'])( const { port1, port2 } = channel() const incoming = receive(port2) const result = request(port1, 'navigate', { url: 'https://example.com' }) - const rejected = expect(result).rejects.toThrow(failure instanceof Error ? failure.message : failure) + const rejected = expect(result).rejects.toMatchObject({ + constructor: StagehandError, code: 'STAGEHAND_OPERATION_FAILED', message: failure instanceof Error ? failure.message : failure, + }) const raw = await incoming await answer(raw, async () => { throw failure }) await rejected }, ) +it('rebuilds a StagehandError from its transported name and code', async () => { + const { port1, port2 } = channel() + const incoming = receive(port2) + const result = request(port1, 'act', { instruction: 'Click the button.' }) + const rejected = expect(result).rejects.toMatchObject({ constructor: StagehandError, name: 'StagehandError', code: 'STAGEHAND_ACT_FAILED', message: 'Button missing' }) + await answer(await incoming, async () => { throw new StagehandError('Button missing', 'STAGEHAND_ACT_FAILED') }) + await rejected +}) + +it.each([ + { ok: false, error: 'Unknown failure', name: 'StagehandError', code: 'STAGEHAND_UNKNOWN' }, + { ok: false, error: 'Foreign failure', name: 'OtherError', code: 'STAGEHAND_ACT_FAILED' }, +])('classifies an unknown transported identity as an operation failure: %j', async (response) => { + const { port1, port2 } = channel() + const incoming = receive(port2) + const result = request(port1, 'act', { instruction: 'Click the button.' }) + const rejected = expect(result).rejects.toMatchObject({ name: 'StagehandError', code: 'STAGEHAND_OPERATION_FAILED', message: response.error }) + const { reply } = requestSchema.parse(await incoming) + reply.postMessage(response) + await rejected +}) + it.each([ { ok: true, value: 'unexpected', extra: true }, { ok: false, error: 42 }, @@ -66,7 +91,7 @@ it.each([ const { port1, port2 } = channel() const incoming = receive(port2) const result = request(port1, 'tabs', { action: 'list' }) - const rejected = expect(result).rejects.toThrow() + const rejected = expect(result).rejects.toMatchObject({ name: 'StagehandError', code: 'STAGEHAND_WORKER_FAILED', message: 'Stagehand Worker returned a malformed response' }) const raw = await incoming const { reply } = requestSchema.parse(raw) const closed = once(reply, 'close') @@ -79,7 +104,7 @@ it('rejects peer shutdown before a response instead of leaving the request pendi const { port1, port2 } = channel() const incoming = receive(port2) const result = request(port1, 'observe', { instruction: 'Find a button.' }) - const rejected = expect(result).rejects.toThrow('Worker reply channel closed') + const rejected = expect(result).rejects.toMatchObject({ name: 'StagehandError', code: 'STAGEHAND_WORKER_FAILED', message: expect.stringContaining('Worker reply channel closed') as string }) const raw = await incoming const { reply } = requestSchema.parse(raw) const closed = once(reply, 'close') @@ -94,7 +119,7 @@ it.each([new Error('Session disposed'), 'canceled'])( const incoming = receive(port2) const controller = new AbortController() const result = request(port1, 'act', { instruction: 'Click the button.' }, controller.signal) - const rejected = expect(result).rejects.toThrow(reason instanceof Error ? reason.message : 'Worker request canceled') + const rejected = expect(result).rejects.toMatchObject(reason instanceof Error ? reason : { name: 'StagehandError', code: 'STAGEHAND_WORKER_FAILED', message: 'Stagehand Worker request canceled' }) const raw = await incoming const { reply } = requestSchema.parse(raw) const closed = once(reply, 'close') @@ -120,7 +145,7 @@ it('does not dispatch an already canceled request', async () => { it('reports clone failure when request arguments cannot cross a Worker boundary', async () => { const { port1 } = channel() - await expect(request(port1, 'extract', { callback() {} })).rejects.toThrow(/clone/u) + await expect(request(port1, 'extract', { callback() {} })).rejects.toMatchObject({ name: 'StagehandError', code: 'STAGEHAND_WORKER_FAILED', message: expect.stringMatching(/clone/u) as string }) }) it('rejects malformed request envelopes before invoking the operation', async () => { diff --git a/packages/experimental/browser-use-stagehand-native/tests/worker.spec.ts b/packages/experimental/browser-use-stagehand-native/tests/worker.spec.ts index 6ca927c88c..a6f38dbff1 100644 --- a/packages/experimental/browser-use-stagehand-native/tests/worker.spec.ts +++ b/packages/experimental/browser-use-stagehand-native/tests/worker.spec.ts @@ -36,8 +36,10 @@ it('dispatches browser arguments using the independently configured native model await request(peer, 'ready') expect(await request(peer, 'navigate', { url: 'https://fixture.example' })).toMatchObject({ content: [{ type: 'text' }] }) expect(await request(peer, 'extract', { instruction: 'Read the heading' })).toMatchObject({ content: [{ type: 'text' }] }) - await expect(request(peer, 'navigate', { url: 'invalid' })).rejects.toThrow() - await expect(request(peer, 'unavailable')).rejects.toThrow() + await expect(request(peer, 'navigate', { url: 'https://fixture.example', pageId: 'missing' })) + .rejects.toMatchObject({ name: 'StagehandError', code: 'STAGEHAND_TAB_NOT_FOUND', message: expect.stringContaining('tab is unavailable') as string }) + await expect(request(peer, 'navigate', { url: 'invalid' })).rejects.toMatchObject({ name: 'StagehandError', code: 'STAGEHAND_OPERATION_FAILED' }) + await expect(request(peer, 'unavailable')).rejects.toMatchObject({ name: 'StagehandError', code: 'STAGEHAND_OPERATION_FAILED' }) await request(peer, 'close') expect(fixture.models).toEqual([{ modelName: 'openai/gpt-5.4-mini', apiKey: 'fixture-model-key' }]) expect(fixture.browsers[0]?.stagehandClosed).toBe(true) @@ -48,7 +50,7 @@ it('reports initialization failure without closing an external browser', async ( const { fixture, peer } = await prepare() fixture.createError = new Error('Fixture extension unavailable') await import('../src/worker.ts') - await expect(request(peer, 'ready')).rejects.toThrow('Fixture extension unavailable') + await expect(request(peer, 'ready')).rejects.toMatchObject({ name: 'StagehandError', code: 'STAGEHAND_OPERATION_FAILED', message: 'Fixture extension unavailable' }) expect(fixture.browsers[0]?.closed).toBe(false) }) diff --git a/packages/experimental/browser-use-stagehand-native/tsconfig.json b/packages/experimental/browser-use-stagehand-native/tsconfig.json index 1cd503c3e9..95e31dcd1f 100644 --- a/packages/experimental/browser-use-stagehand-native/tsconfig.json +++ b/packages/experimental/browser-use-stagehand-native/tsconfig.json @@ -10,6 +10,7 @@ { "path": "../../core/agent" }, { "path": "../../core/tools" }, { "path": "../../core/system-prompt" }, + { "path": "../../util/error" }, { "path": "../../mcp/mcp-client" }, { "path": "../../subprocess/subprocess" }, { "path": "../../util/values" }, diff --git a/packages/experimental/claude-code-mods/README.i18n.yaml b/packages/experimental/claude-code-mods/README.i18n.yaml index 21dc02b3cf..484b7840b1 100644 --- a/packages/experimental/claude-code-mods/README.i18n.yaml +++ b/packages/experimental/claude-code-mods/README.i18n.yaml @@ -69,8 +69,8 @@ en: fe8166c6d3eb962a zh: 5f8fe74778a78166 /deepseek-ai-dsh-experimental-claude-code-mods/model-experience/tool-outcomes-a-mod-decides/what-the-model-sees: - en: 5b4aa2a1ec36106b - zh: c28c286f2a04d716 + en: 71a9604f6d265e08 + zh: f085a2c072047676 /deepseek-ai-dsh-experimental-claude-code-mods/model-experience/tool-outcomes-a-mod-decides/token-effect: en: cbf27f737c6254e6 zh: 333cbb22f97f8955 diff --git a/packages/experimental/claude-code-mods/README.md b/packages/experimental/claude-code-mods/README.md index fe0de7b2c5..723c6e7e53 100644 --- a/packages/experimental/claude-code-mods/README.md +++ b/packages/experimental/claude-code-mods/README.md @@ -184,7 +184,7 @@ Append-only: added context and submitted prompts follow the reusable request pre #### What the model sees -A `{ deny: reason }` answer renders `Error: ` as the tool result. A `{ result }` answer renders through the tool's own presenter when the tool is mod-registered or the value satisfies the tool's output schema, and as an error-shaped result carrying the text otherwise. A result rewritten after `next` replaces the tool's content text. A dropped prompt ends the turn as `blocked` with no model-visible message. A mod that holds a `tool.call` (Blast Radius) delays the result until a button decides; the model sees only the outcome. +A `{ deny: reason }` answer renders `Error: ` as the tool result. A `{ result }` answer renders through the tool's own presenter when the tool is mod-registered or the value satisfies the tool's output schema, and as an error-shaped result carrying the text otherwise. A deny records `ModDenied` with `MOD_DENIED`, an error-shaped answer records `ModAnswered` with `MOD_ANSWERED`, and a call to a mod-registered tool that no `tool.call` hook answers fails with `ModUnansweredError` and `MOD_UNANSWERED`. A result rewritten after `next` replaces the tool's content text. A dropped prompt ends the turn as `blocked` with no model-visible message. A mod that holds a `tool.call` (Blast Radius) delays the result until a button decides; the model sees only the outcome. #### Token effect diff --git a/packages/experimental/claude-code-mods/README.zh.md b/packages/experimental/claude-code-mods/README.zh.md index a1533ce40a..59fb0c5d59 100644 --- a/packages/experimental/claude-code-mods/README.zh.md +++ b/packages/experimental/claude-code-mods/README.zh.md @@ -184,7 +184,7 @@ Message from the "" mod: #### 模型看到什么 -`{ deny: reason }` 答案把 `Error: ` 渲染为工具结果。`{ result }` 答案在工具为模组注册或值满足工具输出 schema 时经工具自身的呈现器渲染,否则作为携带该文本的错误形态结果。`next` 之后改写的结果替换工具的内容文本。被丢弃的提示词以 `blocked` 结束该轮,没有模型可见的消息。持有 `tool.call` 的模组(Blast Radius)把结果推迟到按钮决定为止;模型只看到结局。 +`{ deny: reason }` 答案把 `Error: ` 渲染为工具结果。`{ result }` 答案在工具为模组注册或值满足工具输出 schema 时经工具自身的呈现器渲染,否则作为携带该文本的错误形态结果。拒绝记录 `ModDenied` 与 `MOD_DENIED`,错误形态的答案记录 `ModAnswered` 与 `MOD_ANSWERED`,没有 `tool.call` 钩子作答的模组注册工具调用以 `ModUnansweredError` 与 `MOD_UNANSWERED` 失败。`next` 之后改写的结果替换工具的内容文本。被丢弃的提示词以 `blocked` 结束该轮,没有模型可见的消息。持有 `tool.call` 的模组(Blast Radius)把结果推迟到按钮决定为止;模型只看到结局。 #### Token 影响 diff --git a/packages/experimental/claude-code-mods/package.json b/packages/experimental/claude-code-mods/package.json index f4056d64cc..a4db21abb9 100644 --- a/packages/experimental/claude-code-mods/package.json +++ b/packages/experimental/claude-code-mods/package.json @@ -75,7 +75,8 @@ "@deepseek-ai/dsh-tools": "workspace:*", "@deepseek-ai/dsh-typert-protocol": "workspace:*", "@deepseek-ai/dsh-user-questions": "workspace:*", - "@deepseek-ai/dsh-working-directory": "workspace:*" + "@deepseek-ai/dsh-working-directory": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" }, "devDependencies": { "@deepseek-ai/cordis": "workspace:~", @@ -105,6 +106,7 @@ "@deepseek-ai/dsh-typert-protocol": "workspace:*", "@deepseek-ai/dsh-user-questions": "workspace:*", "@deepseek-ai/dsh-working-directory": "workspace:*", - "@deepseek-ai/dsh-session-persistence-jsonl": "workspace:*" + "@deepseek-ai/dsh-session-persistence-jsonl": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" } } diff --git a/packages/experimental/claude-code-mods/src/host-ops.ts b/packages/experimental/claude-code-mods/src/host-ops.ts index 1ad62ef0c7..e91e618dbb 100644 --- a/packages/experimental/claude-code-mods/src/host-ops.ts +++ b/packages/experimental/claude-code-mods/src/host-ops.ts @@ -15,6 +15,7 @@ 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 { brandString } from '@deepseek-ai/dsh-brand' +import { HarnessError } from '@deepseek-ai/dsh-error' import { createUserMessage, type ToolCallId } from '@deepseek-ai/dsh-llm' import type { ContentBlock, Message } from '@deepseek-ai/dsh-llm' import { scopeOf } from '@deepseek-ai/dsh-scope' @@ -77,6 +78,14 @@ const storeDomainSpec = defineDomain({ tables: { store: domainTable>(zod.record(zod.string(), zod.json())) }, }) +/** A call to a mod-registered tool that no `tool.call` hook answered; code `MOD_UNANSWERED`. */ +export class ModUnansweredError extends HarnessError { + constructor(message: string) { + super(message, 'MOD_UNANSWERED') + this.name = 'ModUnansweredError' + } +} + /** Options the host op table is built from. */ export interface HostOpsOptions { readonly ctx: Context @@ -340,7 +349,7 @@ export function createHostOps(options: HostOpsOptions): OpTable { render: (_args, value) => [{ type: 'text', text: value as string }], }, execute() { - return Promise.reject(new Error(`${mod.name} registered ${fullName} but no tool.call hook answered it; add on('tool.call', { tool: '${fullName}' }, hook)`)) + return Promise.reject(new ModUnansweredError(`${mod.name} registered ${fullName} but no tool.call hook answered it; add on('tool.call', { tool: '${fullName}' }, hook)`)) }, } track(registry.register(definition), binding.agent) diff --git a/packages/experimental/claude-code-mods/src/index.ts b/packages/experimental/claude-code-mods/src/index.ts index 5a725ae533..38821d2366 100644 --- a/packages/experimental/claude-code-mods/src/index.ts +++ b/packages/experimental/claude-code-mods/src/index.ts @@ -48,7 +48,7 @@ export type { BoxProps, ButtonProps, TextProps, UiElement, UiElements, UiNode } export { defineMod, type ModConfig, type ModPlugin, type ModSpec } from './define-mod.ts' export { DEFAULT_TOOL_ALIASES } from './tool-names.ts' export { KNOWN_EVENTS } from './matcher.ts' -export { MODS_API_VERSION } from './host-ops.ts' +export { ModUnansweredError, MODS_API_VERSION } from './host-ops.ts' /** Plugin config: the limits mod hooks run under. */ export interface Config { diff --git a/packages/experimental/claude-code-mods/tests/bridge.spec.ts b/packages/experimental/claude-code-mods/tests/bridge.spec.ts index f09874df02..e22ff34231 100644 --- a/packages/experimental/claude-code-mods/tests/bridge.spec.ts +++ b/packages/experimental/claude-code-mods/tests/bridge.spec.ts @@ -730,6 +730,8 @@ describe('mod tools: registration errors and unanswered calls', () => { expect(results[0]).toEqual([true, { type: 'text', text: "Error: tools-mod registered mcp__tools-mod__orphan but no tool.call hook answered it; add on('tool.call', { tool: 'mcp__tools-mod__orphan' }, hook)" }]) expect(results[1]).toEqual([false, { type: 'text', text: '{"structured":true}' }]) expect(results[2]).toEqual([false, { type: 'text', text: '' }]) + const unanswered = events(agent).find(e => e.type === 'tool/result') + expect(unanswered?.type === 'tool/result' && unanswered.data.error).toEqual({ name: 'ModUnansweredError', code: 'MOD_UNANSWERED' }) }) }) diff --git a/packages/experimental/claude-code-mods/tsconfig.json b/packages/experimental/claude-code-mods/tsconfig.json index 8cd83417e7..978b8449c0 100644 --- a/packages/experimental/claude-code-mods/tsconfig.json +++ b/packages/experimental/claude-code-mods/tsconfig.json @@ -64,6 +64,9 @@ }, { "path": "../../session/working-directory" + }, + { + "path": "../../util/error" } ] } diff --git a/packages/experimental/computer-use-cua-driver-native/README.i18n.yaml b/packages/experimental/computer-use-cua-driver-native/README.i18n.yaml index 6cd4a52c83..5ebb61d5c9 100644 --- a/packages/experimental/computer-use-cua-driver-native/README.i18n.yaml +++ b/packages/experimental/computer-use-cua-driver-native/README.i18n.yaml @@ -27,8 +27,8 @@ en: c3022cbadb94589b zh: b426ea3dbeafd352 /deepseek-ai-dsh-experimental-computer-use-cua-driver-native/understand-the-implementation: - en: b397becc466ba383 - zh: 758a149cf002bd11 + en: 2affc3aae95c8e1b + zh: 392fa0f65037e291 /deepseek-ai-dsh-experimental-computer-use-cua-driver-native/further-exploration: en: d24023319ead888c zh: ab28be480aced0a9 diff --git a/packages/experimental/computer-use-cua-driver-native/README.md b/packages/experimental/computer-use-cua-driver-native/README.md index 3d5fb83810..2d7a304444 100644 --- a/packages/experimental/computer-use-cua-driver-native/README.md +++ b/packages/experimental/computer-use-cua-driver-native/README.md @@ -63,9 +63,12 @@ The provider reserves the shared computer-use registration before loading native | File | Role | |---|---| | [src/index.ts](src/index.ts) | Native runtime ownership, catalog validation, tool registration, and provider guidance | +| [src/error.ts](src/error.ts) | `CuaDriverError` and its closed code list | Tool definitions reuse the existing MCP result adapter. Cua Driver's JSON catalog determines the schemas; its raw result supplies canonical text, structured output, and image bytes. The computer-use service carries only the provider name and exclusive registration. +A rejected native call throws `CuaDriverError` with `CUA_DRIVER_FAILED`, keeping the SDK's message and its error as `cause`; once the call or the provider is canceled, the cancellation propagates instead. A raw result that is not JSON throws `CUA_DRIVER_INVALID_RESULT`. Upstream tool refusals reported in a result stay with the MCP result adapter. + ----- diff --git a/packages/experimental/computer-use-cua-driver-native/README.zh.md b/packages/experimental/computer-use-cua-driver-native/README.zh.md index 5fba221cc0..58b5769d6e 100644 --- a/packages/experimental/computer-use-cua-driver-native/README.zh.md +++ b/packages/experimental/computer-use-cua-driver-native/README.zh.md @@ -63,9 +63,12 @@ env -u NODE_USE_ENV_PROXY DSH_COMPUTER_USE_NATIVE_E2E=1 node node_modules/vitest | 文件 | 职责 | |---|---| | [src/index.ts](src/index.ts) | 原生运行时所有权、目录校验、工具注册和提供者指导文本 | +| [src/error.ts](src/error.ts) | `CuaDriverError` 及其封闭代码列表 | 工具定义复用现有 MCP 结果适配器。Cua Driver 的 JSON 目录决定 schema,其原始结果提供规范文本、结构化输出和图像字节。电脑操作服务只保存提供者名称并保证独占注册。 +原生调用被拒绝时抛出带 `CUA_DRIVER_FAILED` 的 `CuaDriverError`,保留 SDK 的消息并以其错误作为 `cause`;调用或提供者已取消时改为传播取消。原始结果不是 JSON 时抛出 `CUA_DRIVER_INVALID_RESULT`。结果中报告的上游工具拒绝仍由 MCP 结果适配器处理。 + ----- diff --git a/packages/experimental/computer-use-cua-driver-native/package.json b/packages/experimental/computer-use-cua-driver-native/package.json index 37bd96ea78..3340f7eb42 100644 --- a/packages/experimental/computer-use-cua-driver-native/package.json +++ b/packages/experimental/computer-use-cua-driver-native/package.json @@ -35,7 +35,8 @@ "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-computer-use": "workspace:*", "@deepseek-ai/dsh-system-prompt": "workspace:*", - "@deepseek-ai/dsh-tools": "workspace:*" + "@deepseek-ai/dsh-tools": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" }, "dependencies": { "@deepseek-ai/dsh-brand": "workspace:*", @@ -60,6 +61,7 @@ "@deepseek-ai/dsh-system-prompt": "workspace:*", "@deepseek-ai/dsh-tool-executor-native": "workspace:*", "@deepseek-ai/dsh-tool-testkit": "workspace:*", - "@deepseek-ai/dsh-tools": "workspace:*" + "@deepseek-ai/dsh-tools": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" } } diff --git a/packages/experimental/computer-use-cua-driver-native/src/error.ts b/packages/experimental/computer-use-cua-driver-native/src/error.ts new file mode 100644 index 0000000000..fac0c7a07a --- /dev/null +++ b/packages/experimental/computer-use-cua-driver-native/src/error.ts @@ -0,0 +1,33 @@ +/** Machine-routable Cua Driver SDK failures. @module */ + +import { HarnessError } from '@deepseek-ai/dsh-error' + +/** + * Every {@link CuaDriverError} code: + * - `CUA_DRIVER_FAILED` — the native SDK rejected the tool call; the message carries the SDK's text. + * Inspect fresh desktop state before retrying. + * - `CUA_DRIVER_INVALID_RESULT` — the native SDK returned a result that is not JSON; report it rather than retrying unchanged. + */ +export const CUA_DRIVER_ERROR_CODES = [ + 'CUA_DRIVER_FAILED', + 'CUA_DRIVER_INVALID_RESULT', +] as const + +/** One code from {@link CUA_DRIVER_ERROR_CODES}. */ +export type CuaDriverErrorCode = typeof CUA_DRIVER_ERROR_CODES[number] + +/** Cua Driver native SDK failure carrying a stable {@link CuaDriverErrorCode}; the SDK's error is its `cause`. */ +export class CuaDriverError extends HarnessError { + override readonly code: CuaDriverErrorCode + + /** + * @param message - names the failed Cua Driver tool or the SDK's own message. + * @param code - the failure class consumers route on. + * @param options - standard `cause` chaining. + */ + constructor(message: string, code: CuaDriverErrorCode, options?: ErrorOptions) { + super(message, code, options) + this.name = 'CuaDriverError' + this.code = code + } +} diff --git a/packages/experimental/computer-use-cua-driver-native/src/index.ts b/packages/experimental/computer-use-cua-driver-native/src/index.ts index c8bae5f713..86f787ab74 100644 --- a/packages/experimental/computer-use-cua-driver-native/src/index.ts +++ b/packages/experimental/computer-use-cua-driver-native/src/index.ts @@ -13,6 +13,9 @@ import type { CuaDriver as NativeDriver } from '@trycua/cua-driver' import type {} from '@deepseek-ai/dsh-computer-use' import type {} from '@deepseek-ai/dsh-system-prompt' import type {} from '@deepseek-ai/dsh-tools' +import { CuaDriverError } from './error.ts' + +export { CuaDriverError, type CuaDriverErrorCode } from './error.ts' /** Cordis plugin identity for the native Cua Driver provider. */ export const name = 'experimental-computer-use-cua-driver-native' @@ -110,9 +113,16 @@ export async function apply(ctx: Context): Promise { async call(args, execution) { const combined = AbortSignal.any([execution.signal, lifetime.signal]) combined.throwIfAborted() - const result = await activeDriver.callTool(tool.name, JSON.stringify(args), { signal: combined }) + const result = await activeDriver.callTool(tool.name, JSON.stringify(args), { signal: combined }).catch((error: unknown) => { + combined.throwIfAborted() + throw new CuaDriverError(error instanceof Error ? error.message : String(error), 'CUA_DRIVER_FAILED', { cause: error }) + }) combined.throwIfAborted() - return JSON.parse(result.rawJson) as unknown + try { + return JSON.parse(result.rawJson) as unknown + } catch (error) { + throw new CuaDriverError(`Cua Driver tool "${tool.name}" returned a result that is not JSON`, 'CUA_DRIVER_INVALID_RESULT', { cause: error }) + } }, }) inner.tools.register(definition) diff --git a/packages/experimental/computer-use-cua-driver-native/tests/fixtures/cua-driver.ts b/packages/experimental/computer-use-cua-driver-native/tests/fixtures/cua-driver.ts index fe0f35a288..42fb547b27 100644 --- a/packages/experimental/computer-use-cua-driver-native/tests/fixtures/cua-driver.ts +++ b/packages/experimental/computer-use-cua-driver-native/tests/fixtures/cua-driver.ts @@ -37,6 +37,7 @@ export const fixture: { createError?: Error list?: (signal?: AbortSignal) => Promise call?: (name: string, args: Record, signal?: AbortSignal) => Promise + rawJson?: string shutdown?: () => Promise } = { creates: 0, destroys: 0, shutdowns: 0, clicked: false, calls: [] } @@ -50,6 +51,7 @@ export function resetFixture(): void { delete fixture.createError delete fixture.list delete fixture.call + delete fixture.rawJson delete fixture.shutdown } @@ -68,6 +70,7 @@ export class CuaDriver { async callTool(name: string, argsJson: string, options?: { signal: AbortSignal }): Promise<{ rawJson: string }> { const args = JSON.parse(argsJson) as Record fixture.calls.push({ name, args, ...options ? { signal: options.signal } : {} }) + if (fixture.rawJson !== undefined) return { rawJson: fixture.rawJson } if (fixture.call) return { rawJson: JSON.stringify(await fixture.call(name, args, options?.signal)) } if (name === 'get_window_state') { return { rawJson: JSON.stringify({ diff --git a/packages/experimental/computer-use-cua-driver-native/tests/provider.spec.ts b/packages/experimental/computer-use-cua-driver-native/tests/provider.spec.ts index dc55cdc64f..bb0aa271e8 100644 --- a/packages/experimental/computer-use-cua-driver-native/tests/provider.spec.ts +++ b/packages/experimental/computer-use-cua-driver-native/tests/provider.spec.ts @@ -99,6 +99,39 @@ describe('Cua Driver native provider', () => { expect(result.content).toEqual([{ type: 'text', text: 'Error: background_unavailable' }]) }) + it.each([new Error('native helper unavailable'), 'native helper unavailable'])('classifies a native SDK call failure: %s', async (failure) => { + fixture.call = async () => { throw failure } + await ctx.plugin(NativeProvider) + const result = await execute('click', { pid: 9, window_id: 7 }) + expect(result.error?.info).toEqual({ name: 'CuaDriverError', code: 'CUA_DRIVER_FAILED' }) + expect(result.content).toEqual([{ type: 'text', text: 'Error: native helper unavailable' }]) + }) + + it('reports cancellation instead of a native failure once the caller cancels', async () => { + const called: PromiseWithResolvers = Promise.withResolvers() + fixture.call = async (_name, _args, signal) => { + called.resolve() + await new Promise(resolve => signal?.addEventListener('abort', resolve, { once: true })) + throw new Error('native call interrupted') + } + await ctx.plugin(NativeProvider) + const controller = new AbortController() + const result = executeToolFixture(ctx, { + name: 'cua_driver_native__click', callId: brandString('native-cancel'), arguments: { pid: 9, window_id: 7 }, signal: controller.signal, + }) + await called.promise + controller.abort(new Error('Stop clicking')) + expect((await result).error).toEqual({ message: 'Stop clicking', info: { name: 'AbortError', code: 'ABORTED' } }) + }) + + it('classifies a native result that is not JSON', async () => { + fixture.rawJson = '{not json' + await ctx.plugin(NativeProvider) + const result = await execute('click', { pid: 9, window_id: 7 }) + expect(result.error?.info).toEqual({ name: 'CuaDriverError', code: 'CUA_DRIVER_INVALID_RESULT' }) + expect(result.content).toEqual([{ type: 'text', text: 'Error: Cua Driver tool "click" returned a result that is not JSON' }]) + }) + it('leaves an unrelated tool running when the native provider unloads', async () => { const started = Promise.withResolvers() const settled = Promise.withResolvers() diff --git a/packages/experimental/computer-use-cua-driver-native/tsconfig.json b/packages/experimental/computer-use-cua-driver-native/tsconfig.json index e7a04bc8a6..10ef2604da 100644 --- a/packages/experimental/computer-use-cua-driver-native/tsconfig.json +++ b/packages/experimental/computer-use-cua-driver-native/tsconfig.json @@ -12,6 +12,7 @@ { "path": "../../computer-use/computer-use" }, { "path": "../../core/tools" }, { "path": "../../core/system-prompt" }, + { "path": "../../util/error" }, { "path": "../../mcp/mcp-client" } ] } diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index ab845aa5dc..71331ebe83 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -27,7 +27,7 @@ import NodeRuntime from '@deepseek-ai/dsh-ptc-runtime-node' import { createRunCodeTool } from '@deepseek-ai/dsh-tool-executor-ptc/run-code' import Sandbox from '@deepseek-ai/dsh-sandbox-local' import SandboxPolicy from '@deepseek-ai/dsh-sandbox-policy' -import { LlmAdapter, type ToolCallId, type LlmResolvedModelInfo, type StreamChunk } from '@deepseek-ai/dsh-llm' +import { LlmAdapter, LlmError, type ToolCallId, type LlmResolvedModelInfo, type StreamChunk } from '@deepseek-ai/dsh-llm' import type { SessionId } from '@deepseek-ai/dsh-session' import Subprocess from '@deepseek-ai/dsh-subprocess' import SubprocessLocal from '@deepseek-ai/dsh-subprocess-local' @@ -35,7 +35,7 @@ import { expect, it, onTestFinished, vi } from 'vitest' import sharp from 'sharp' import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' import * as NativeProvider from '../src/index.ts' -import type { NativeClient } from '@deepseek-ai/dsh-cua/native-client' +import { NativeError, type NativeClient } from '@deepseek-ai/dsh-cua/native-client' import type { NativeBuildSpec } from '../src/native-build.ts' import { brandString } from '@deepseek-ai/dsh-brand' @@ -386,6 +386,7 @@ it.each(['Allow for this session', 'Deny'])('obtains %s before a stopped applica answer.resolve({ answers: [{ id: 'cua-app-access', selected: [choice] }] }) const result = await pending expect(result.isError).toBe(choice === 'Deny') + if (choice === 'Deny') expect(result.error?.info).toEqual({ name: 'NativeError', code: 'APP_ACCESS_DENIED' }) expect(native.request.mock.calls.map(call => call[0])).toEqual(choice === 'Deny' ? ['getApp'] : ['getApp', 'launchApp']) if (choice !== 'Deny') expect(result.value).toMatchObject({ appHandle: 'pending-app', running: true }) }) @@ -399,9 +400,25 @@ it('rejects a launch result that changes the approved handle', async () => { } }).mockResolvedValueOnce({ appHandle: 'another-app', name: 'Fixture', running: true }) const result = await f.execute('getApp', { selector: 'Fixture' }) expect(result.isError).toBe(true) + expect(result.error?.info).toEqual({ name: 'NativeError', code: 'NATIVE_PROTOCOL' }) expect(JSON.stringify(result.content)).toContain('another handle') }) +it.each([true, false])('classifies native cancellation by whether the caller cancelled (%s)', async (callerCancelled) => { + const f = await setup() + await f.execute() + const controller = new AbortController() + native.request.mockImplementationOnce(async () => { + if (callerCancelled) controller.abort() + throw new NativeError('NATIVE_CANCELLED', 'Operation cancelled; inspect fresh state before retrying input') + }) + const result = await f.execute('listApps', {}, controller.signal) + expect(result.isError).toBe(true) + expect(result.error?.info).toEqual(callerCancelled + ? { name: 'AbortError', code: 'ABORTED' } + : { name: 'NativeError', code: 'NATIVE_CANCELLED' }) +}) + it('rejects a model attempt to call the private launch operation', async () => { const f = await setup() expect((await f.execute('launchApp', { appHandle: 'unapproved' })).isError).toBe(true) @@ -602,13 +619,35 @@ it('reports failed cleanup after waiting for other owners and releasing their Ag } finally { release.resolve(); await closing } }) +it('names the missing field of a request that matches none of its accepted forms', async () => { + const f = await setup() + const result = await f.execute('click', { appHandle: 'app', windowId: '7', x: 20 }) + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) + const text = JSON.stringify(result.content) + expect(text).toContain('params: matches none of the accepted forms') + expect(text).toContain('params.y: Invalid input: expected number, received undefined') + expect(native.request).not.toHaveBeenCalled() +}) + +it('names an unknown top-level request key', async () => { + const f = await setup() + const result = await executeToolFixture(f.ctx, { + agent: f.handle.agent, signal: new AbortController().signal, callId: brandString('extra-key'), name: 'cua', + arguments: { method: 'listApps', params: {}, extra: 1 }, + }) + expect(result.content).toEqual([{ type: 'text', text: 'Error: invalid arguments: arguments: Unrecognized key: "extra"' }]) +}) + it('rejects malformed and unowned operations before acquiring a helper', async () => { const f = await setup() - expect((await f.execute('screenshot', { pid: 9, windowId: '7' })).isError).toBe(true) + const malformed = await f.execute('screenshot', { pid: 9, windowId: '7' }) + expect(malformed.isError).toBe(true) + expect(malformed.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) const unowned = await executeToolFixture(f.ctx, { signal: new AbortController().signal, callId: brandString('unowned'), name: 'cua', arguments: { method: 'listApps', params: {} }, }) expect(unowned.isError).toBe(true) + expect(unowned.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) expect(native.instances).toEqual([]) expect(native.request).not.toHaveBeenCalled() }) @@ -620,6 +659,7 @@ it.each([false, true])('rejects an ended Agent with prior helper acquisition %s' const requests = native.request.mock.calls.length const result = await f.execute() expect(result.isError).toBe(true) + expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) expect(JSON.stringify(result.content)).toContain('agent has been disposed') expect(native.instances).toHaveLength(acquired ? 1 : 0) expect(native.request).toHaveBeenCalledTimes(requests) @@ -703,6 +743,7 @@ it('preserves screenshot attachments and invalidates pixel coordinates when wind native.request.mockClear() const click = await f.execute('click', { appHandle: 'app-one', windowId: '7', x: 0, y: 0 }) expect(click.isError).toBe(true) + expect(click.error?.info).toEqual({ name: 'NativeError', code: 'SCREENSHOT_REQUIRED' }) expect(JSON.stringify(click.content)).toContain('SCREENSHOT_REQUIRED') expect(native.request).not.toHaveBeenCalled() }) @@ -773,6 +814,7 @@ it.each([{ pixelWidth: 2 }, { pixelHeight: 2 }])('rejects native screenshot dime native.request.mockResolvedValue({ ...imageMetadata, ...invalid, mimeType: 'image/png', data: imageData }) const result = await f.execute('screenshot', { appHandle: 'app-one', windowId: '7' }) expect(result.isError).toBe(true) + expect(result.error?.info).toEqual({ name: 'NativeError', code: 'NATIVE_PROTOCOL' }) expect(JSON.stringify(result.content)).toContain('dimensions disagree') expect(result.content.some(block => block.type === 'image')).toBe(false) }) @@ -783,6 +825,7 @@ it('refuses screenshot capture when no attachment store is mounted', async () => native.request.mockClear() const result = await f.execute('screenshot', { appHandle: 'app-one', windowId: '7' }) expect(result.isError).toBe(true) + expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) expect(JSON.stringify(result.content)).toContain('require an attachment store') expect(native.request).not.toHaveBeenCalled() }) @@ -830,7 +873,7 @@ it.each(['unresolved', 'unknown', 'text-only', 'provider-error'] as const)( await f.ctx.plugin(LocalAttachmentStore, { dshHome: root }) const saved = vi.spyOn(f.ctx.attachments, 'saveImages') const resolve = vi.spyOn(f.ctx.llm, 'resolveModelInfo') - if (route === 'provider-error') resolve.mockRejectedValue(new Error('model lookup failed')) + if (route === 'provider-error') resolve.mockRejectedValue(new LlmError('model lookup failed', 'UNKNOWN_MODEL')) else resolve.mockResolvedValue({ provider: 'image-fixture', id: 'vision', name: 'Vision', ...route === 'text-only' ? { inputModalities: ['text'] } : {}, }) @@ -838,7 +881,10 @@ it.each(['unresolved', 'unknown', 'text-only', 'provider-error'] as const)( const result = await f.execute('screenshot', { appHandle: 'app-one', windowId: '7' }) expect(result.isError).toBe(true) expect(JSON.stringify(result.content)).toContain(route === 'unresolved' ? 'model route could not be resolved' - : route === 'provider-error' ? 'model lookup failed' : 'declare image input') + : route === 'provider-error' ? 'model lookup failed' : 'MODEL_DOES_NOT_SUPPORT_IMAGES: CUA screenshots require model') + expect(result.error?.info).toEqual(route === 'unresolved' + ? { name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' } + : route === 'provider-error' ? { name: 'LlmError', code: 'UNKNOWN_MODEL' } : { name: 'NativeError', code: 'MODEL_DOES_NOT_SUPPORT_IMAGES' }) expect(native.request).not.toHaveBeenCalled() expect(saved).not.toHaveBeenCalled() }, @@ -1094,6 +1140,7 @@ it('rejects an application handle before any helper or consent has been acquired const f = await setup() const result = await f.execute('getState', { appHandle: 'unselected-app' }) expect(result.isError).toBe(true) + expect(result.error?.info).toEqual({ name: 'NativeError', code: 'APP_ACCESS_REQUIRED' }) expect(JSON.stringify(result.content)).toContain('APP_ACCESS_REQUIRED') expect(native.instances).toHaveLength(0) expect(native.request).not.toHaveBeenCalled() diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index 51ad47b62f..b63a98ec24 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -15,8 +15,8 @@ en: 5db4d4fea25493b9 zh: 65ab64fc24eb0d09 /deepseek-ai-dsh-cua/use-this-package: - en: c59986e14b6cf9ad - zh: 10c7f6acef208342 + en: a0d79d7f114c6adf + zh: 5370d9997dbb1faa /deepseek-ai-dsh-cua/use-this-package/permission-controls: en: 754ca69ec462325a zh: 440d76acf2666689 diff --git a/packages/experimental/cua/README.md b/packages/experimental/cua/README.md index ab0f2757cf..453632e669 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -45,7 +45,7 @@ Keyboard methods are available in the scopes a provider declares; the provider o Connect PTC with `connectCua(() => tools.cua)` or supply a custom dispatcher to `createCuaApi(dispatch)`. Observation methods return their results to the program. Call `inspect(await app.getWindows())` to display a result, or pass a filtered value. `window.getScreenshot()` returns an `Image` whose `path` is readable by the program and whose `width` and `height` describe the stored pixels. Use `inspect("before", before, "after", after)` to display selected screenshots. Read the window ID from `window.windowId`. -`tools.cua` screenshot operations return `Image` in TypeScript programs. Host-side canonical screenshot results carry encoded image data and a durable `attachment` reference; the native renderer projects coordinate metadata and the image into model content. Capture requires an attachment store and either a configured `screenshotTarget` or a resolved model route declaring image input. Admission and storage failures reject the call. +`tools.cua` screenshot operations return `Image` in TypeScript programs. Host-side canonical screenshot results carry encoded image data and a durable `attachment` reference; the native renderer projects coordinate metadata and the image into model content. Capture requires an attachment store and either a configured `screenshotTarget` or a resolved model route declaring image input. Admission and storage failures reject the call. Failed calls carry structured identity: native and host refusals use `NativeError` with the native or host code, such as `APP_ACCESS_DENIED`, `NATIVE_TIMEOUT`, or `MODEL_DOES_NOT_SUPPORT_IMAGES` for a model without image input, which stays on `NativeError` because it is the package's one error class and its message keeps the `CODE: ` prefix every `NativeError` carries; a missing Agent, attachment store, or model route uses `ToolContextUnavailableError`; arguments the schema cannot check use `ToolArgsError`; native cancellation after the caller cancels records `AbortError` with `ABORTED`. The object bridge preserves the screenshot bytes and validated metadata without uploading or emitting the same image again. Application consent precedes launch, observation, capture, and input. Session access is stored by conversation and application identity and survives DSH restart and Computer Use disablement. Other conversations require their own consent. Saved grants require a platform-provided reusable application identity. Refusal and revocation close affected Agent connections, so their old objects require fresh selection. No input is replayed after cancellation, timeout, or reconnect. diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index c8afb9db62..9de21bee77 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -45,7 +45,7 @@ kind: "package-reference" 通过 `connectCua(() => tools.cua)` 连接 PTC,或将自定义分派器传给 `createCuaApi(dispatch)`。观察方法返回结果供程序使用。需要展示时,调用 `inspect(await app.getWindows())` 或传入筛选后的值。`window.getScreenshot()` 返回 `Image`,其 `path` 指向程序可读取的附件文件,`width` 和 `height` 是图片的像素尺寸。使用 `inspect("操作前", before, "操作后", after)` 展示选中的截图,从 `window.windowId` 读取窗口 ID。 -`tools.cua` 的截图操作在 TypeScript 程序中返回 `Image`。宿主侧的规范化截图结果包含编码图像数据与持久的 `attachment` 引用;原生渲染器将坐标元数据和图片投影为模型内容。截图前要求附件服务可用,且已配置 `screenshotTarget` 或当前模型路由声明图片输入。图片接入或保存失败会拒绝调用。 +`tools.cua` 的截图操作在 TypeScript 程序中返回 `Image`。宿主侧的规范化截图结果包含编码图像数据与持久的 `attachment` 引用;原生渲染器将坐标元数据和图片投影为模型内容。截图前要求附件服务可用,且已配置 `screenshotTarget` 或当前模型路由声明图片输入。图片接入或保存失败会拒绝调用。 失败调用带有结构化标识:原生与 Host 拒绝使用 `NativeError` 及原生或 Host code,例如 `APP_ACCESS_DENIED`、`NATIVE_TIMEOUT`,模型不支持图片输入时为 `MODEL_DOES_NOT_SUPPORT_IMAGES`,它仍属于 `NativeError`,因为这是本包唯一的错误类,其 message 也与所有 `NativeError` 一样带 `CODE: ` 前缀;缺少 Agent、附件服务或模型路由时使用 `ToolContextUnavailableError`;参数 schema 无法检查的参数错误使用 `ToolArgsError`;调用方取消后的原生取消记录为 `AbortError` 与 `ABORTED`。对象桥接保留截图字节和已校验的元数据,不重复上传或输出同一张图片。 应用授权发生在启动、观察、截图和输入之前。会话许可按对话和应用身份持久化,重启 DSH 或关闭 Computer Use 后仍可复用,其他对话需要单独授权。长期许可要求平台提供可复用的应用身份。拒绝或撤销会关闭受影响的 Agent 连接,因此旧对象必须重新选择目标。取消、超时或重新连接后均不重放输入。 diff --git a/packages/experimental/cua/package.json b/packages/experimental/cua/package.json index 790f0a43cc..3f12c4940e 100644 --- a/packages/experimental/cua/package.json +++ b/packages/experimental/cua/package.json @@ -101,6 +101,7 @@ "@deepseek-ai/dsh-attachment": "workspace:*", "@deepseek-ai/dsh-scope": "workspace:*", "@deepseek-ai/dsh-ptc-runtime-node": "workspace:*", + "@deepseek-ai/dsh-tools": "workspace:*", "@deepseek-ai/dsh-tool-executor-ptc": "workspace:*" }, "dependencies": { diff --git a/packages/experimental/cua/src/index.ts b/packages/experimental/cua/src/index.ts index 0f48ec7ee7..201fd438ee 100644 --- a/packages/experimental/cua/src/index.ts +++ b/packages/experimental/cua/src/index.ts @@ -24,7 +24,7 @@ import { CuaConfigFields, type CuaScreenshotTargetConfig, type CuaStandaloneRunC import { fixedScreenshotTarget, installCuaTools } from './tool-registration.ts' import { CuaCoordinates } from './coordinates.ts' import { observeNativeWindows } from './native-observation.ts' -import type { ToolDefinition, ToolExecution } from '@deepseek-ai/dsh-tools' +import { ToolArgsError, ToolContextUnavailableError, type ToolDefinition, type ToolExecution } from '@deepseek-ai/dsh-tools' import type {} from '@deepseek-ai/dsh-subprocess' import type {} from '@deepseek-ai/dsh-computer-use' import type {} from '@deepseek-ai/dsh-ptc-runtime' @@ -96,10 +96,39 @@ export const CuaConfig = Schema.object(CuaConfigFields) satisfies Schema): Agent { - if (!execution.agent) throw new Error('dsh-cua requires an agent-owned execution') + if (!execution.agent) throw new ToolContextUnavailableError('dsh-cua requires an agent-owned execution') return execution.agent } +/** + * Describe one request issue for the model. A union that no accepted form matches lists each form's own + * issues, so the model learns which field to add or remove, such as a missing `params.y`. + * @param issue - one issue from parsing the request. + * @param base - path of the value the issue belongs to. + * @returns a single-line violation naming the field and the reason. + */ +function requestViolation(issue: z.core.$ZodIssue, base: readonly PropertyKey[] = []): string { + const path = [...base, ...issue.path] + const field = path.length > 0 ? path.map(String).join('.') : 'arguments' + if (issue.code !== 'invalid_union' || issue.errors.length === 0) return `${field}: ${issue.message}` + const forms = issue.errors.map(form => `(${form.map(nested => requestViolation(nested, path)).join('; ')})`) + return `${field}: matches none of the accepted forms: ${forms.join(' or ')}` +} + +/** Parse the tool request; refinements the parameter schema cannot express fail as argument errors. */ +function parseRequest(schema: z.ZodType, args: unknown): T { + const parsed = schema.safeParse(args) + if (!parsed.success) throw new ToolArgsError(parsed.error.issues.map(issue => requestViolation(issue))) + return parsed.data +} + +/** Native cancellation after the caller cancelled keeps its diagnostic; the tool registry records it as `ABORTED`. */ +function callerCancelled(error: NativeError): Error { + const cancelled = new Error(error.message, { cause: error }) + cancelled.name = 'AbortError' + return cancelled +} + interface CuaExecution extends ToolExecution { agent: Agent nativeClient: NativeClient @@ -121,7 +150,7 @@ function renderResult(args: unknown, value: JsonValue): ContentBlock[] { /** Resolve the attachment store and the request-image target before requesting a screenshot. */ async function screenshotStore(ctx: Context, execution: Readonly, configured: CuaScreenshotTargetConfig | undefined) { const attachments = ctx.get('attachments') - if (!attachments) throw new Error('CUA screenshots require an attachment store') + if (!attachments) throw new ToolContextUnavailableError('CUA screenshots require an attachment store') if (configured !== undefined) { return { attachments, target: (image: ImageAttachmentRef): ImageRequestTarget => fixedScreenshotTarget(configured, image) } } @@ -130,10 +159,14 @@ async function screenshotStore(ctx: Context, execution: Readonly, const provider = routed?.provider ?? agent.options.provider const model = routed?.model ?? agent.options.model const llm = ctx.get('llm') - if (provider === undefined || model === undefined || llm === undefined) throw new Error('CUA screenshot model route could not be resolved') + if (provider === undefined || model === undefined || llm === undefined) { + throw new ToolContextUnavailableError('CUA screenshot model route could not be resolved') + } const info = await llm.resolveModelInfo(provider, model, execution.signal) execution.signal.throwIfAborted() - if (!info.inputModalities?.includes('image')) throw new Error(`CUA screenshots require model "${model}" to declare image input`) + if (!info.inputModalities?.includes('image')) { + throw new NativeError('MODEL_DOES_NOT_SUPPORT_IMAGES', `CUA screenshots require model "${model}" to declare image input`) + } return { attachments, target: (image: ImageAttachmentRef) => llm.imageRequestTarget(provider, model, image) } } @@ -202,7 +235,7 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) }>() const closedOwners = new WeakSet() function ownerFor(agent: Agent) { - if (closedOwners.has(agent) || ctx.agents.get(agent.id) !== agent) throw new Error('dsh-cua agent has been disposed') + if (closedOwners.has(agent) || ctx.agents.get(agent.id) !== agent) throw new ToolContextUnavailableError('dsh-cua agent has been disposed') const existing = ownerCleanups.get(agent) if (existing) return existing const controller = new AbortController() @@ -336,7 +369,7 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) parameters: { ...z.record(z.string(), z.json()).parse(z.toJSONSchema(requestSchema)), type: 'object' }, output: { schema: {}, render: renderResult }, async execute(args, execution) { - const request = requestSchema.parse(args) + const request = parseRequest(requestSchema, args) const agent = executionAgent(execution) execution.signal.throwIfAborted() lifetime.signal.throwIfAborted() @@ -386,6 +419,9 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) pending.set(operation, agent) try { return await operation + } catch (error) { + if (execution.signal.aborted && error instanceof NativeError && error.code === 'NATIVE_CANCELLED') throw callerCancelled(error) + throw error } finally { pending.delete(operation) } diff --git a/packages/experimental/cua/src/native-client.ts b/packages/experimental/cua/src/native-client.ts index c00477888a..6bc2a30eb5 100644 --- a/packages/experimental/cua/src/native-client.ts +++ b/packages/experimental/cua/src/native-client.ts @@ -19,15 +19,21 @@ const ScreenshotDiagnostic = z.object({ }) const WireReply = z.union([Reply, ScreenshotDiagnostic.extend({ type: z.literal('diagnostic') })]) -/** Native refusal or transport failure with a stable machine-readable code. */ +/** + * Native refusal, transport failure, or host-side CUA refusal with a stable machine-readable code. + * The helper supplies its own codes, such as `APP_ACCESS_DENIED` or `STALE_SNAPSHOT`, so consumers + * tolerate unknown codes; the host adds `NATIVE_*` transport codes, application-access codes, + * and `MODEL_DOES_NOT_SUPPORT_IMAGES` for a screenshot requested by a model without image input. + */ export class NativeError extends HarnessError { /** - * @param code - Native error code or a transport-owned NATIVE_* code. + * @param code - Native error code or a host-owned code. * @param message - Actionable diagnostic, without its code prefix. * @param options - Original failure when available. */ constructor(code: string, message: string, options?: ErrorOptions) { super(`${code}: ${message}`, code, options) + this.name = 'NativeError' } } diff --git a/packages/experimental/cua/tests/native-client.spec.ts b/packages/experimental/cua/tests/native-client.spec.ts index 2433dd6979..6344aca101 100644 --- a/packages/experimental/cua/tests/native-client.spec.ts +++ b/packages/experimental/cua/tests/native-client.spec.ts @@ -503,7 +503,9 @@ describe('native helper transport', () => { it('rejects a pre-cancelled operation without writing or invalidating acquired handles', async () => { const f = fixture() - await expect(f.client.request('click', {}, AbortSignal.abort())).rejects.toMatchObject({ code: 'NATIVE_CANCELLED' }) + const rejected = f.client.request('click', {}, AbortSignal.abort()) + await expect(rejected).rejects.toBeInstanceOf(HarnessError) + await expect(rejected).rejects.toMatchObject({ name: 'NativeError', code: 'NATIVE_CANCELLED' }) expect(f.requests).toEqual([]) expect(f.client.disposed).toBe(false) }) diff --git a/packages/experimental/hook-protocol/README.i18n.yaml b/packages/experimental/hook-protocol/README.i18n.yaml index ca049db303..7e97bb1af7 100644 --- a/packages/experimental/hook-protocol/README.i18n.yaml +++ b/packages/experimental/hook-protocol/README.i18n.yaml @@ -39,8 +39,8 @@ en: 7f9239eaea5a945c zh: 9ba6a2ea955d4934 /deepseek-ai-dsh-hook-protocol/understand-the-implementation/source-map: - en: 0d8956a6d8608ee0 - zh: 9f554284c4c0a36e + en: 60f13bbc4bd35669 + zh: a523f557a26dfade /deepseek-ai-dsh-hook-protocol/further-exploration: en: 8b585ce73c2be2cc zh: c0270fd001e1352b diff --git a/packages/experimental/hook-protocol/README.md b/packages/experimental/hook-protocol/README.md index b443839fd1..d5dc514099 100644 --- a/packages/experimental/hook-protocol/README.md +++ b/packages/experimental/hook-protocol/README.md @@ -88,6 +88,7 @@ The [hook-protocol-lib Agent Note](../../../.agents/notes/archived/feature/2026- | [`src/runner.ts`](src/runner.ts) | `runHook` execution through `ctx.shell` and `DEFAULT_HOOK_TIMEOUT_MS` | | [`src/codec.ts`](src/codec.ts) | Exit-code and structured-stdout decoding into `HookOutput` | | [`src/merge.ts`](src/merge.ts) | Most-restrictive merge and the `MergedHookOutcome` type | +| [`src/errors.ts`](src/errors.ts) | `HookError` name with `HOOK_DENIED` and `HOOK_BLOCKED` codes recorded on denied and blocked tool calls | | [`src/events.ts`](src/events.ts) | `hook/*` event declaration, append helpers, stderr summary | | [`src/detached.ts`](src/detached.ts) | Detached-run quiescence tracking | | [`src/types.ts`](src/types.ts) | `HookOutput`, `MatcherGroup`, `CommandHook`, and the `hook/*` payload types | diff --git a/packages/experimental/hook-protocol/README.zh.md b/packages/experimental/hook-protocol/README.zh.md index 6a7a444b65..be0a129d87 100644 --- a/packages/experimental/hook-protocol/README.zh.md +++ b/packages/experimental/hook-protocol/README.zh.md @@ -88,6 +88,7 @@ kind: "package-library" | [`src/runner.ts`](src/runner.ts) | 通过 `ctx.shell` 的 `runHook` 执行与 `DEFAULT_HOOK_TIMEOUT_MS` | | [`src/codec.ts`](src/codec.ts) | 退出码与结构化 stdout 解码为 `HookOutput` | | [`src/merge.ts`](src/merge.ts) | 最严格合并与 `MergedHookOutcome` 类型 | +| [`src/errors.ts`](src/errors.ts) | 被拒绝和被阻塞的工具调用所记录的 `HookError` 名称及 `HOOK_DENIED`、`HOOK_BLOCKED` code | | [`src/events.ts`](src/events.ts) | `hook/*` 事件声明、追加辅助函数、stderr 摘要 | | [`src/detached.ts`](src/detached.ts) | 脱离运行的完全停稳跟踪 | | [`src/types.ts`](src/types.ts) | `HookOutput`、`MatcherGroup`、`CommandHook` 与 `hook/*` 载荷类型 | diff --git a/packages/experimental/hook-protocol/src/errors.ts b/packages/experimental/hook-protocol/src/errors.ts new file mode 100644 index 0000000000..f529308766 --- /dev/null +++ b/packages/experimental/hook-protocol/src/errors.ts @@ -0,0 +1,10 @@ +/** Structured error identity that hook-backed tool policies record on denied and blocked calls. @module */ + +/** Error name shared by every hook policy failure. */ +export const HOOK_ERROR_NAME = 'HookError' + +/** Code for a call a `PreToolUse` hook denied before dispatch; the model should not retry the call unchanged. */ +export const HOOK_DENIED = 'HOOK_DENIED' + +/** Code for a result a `PostToolUse` hook blocked after dispatch; the hook's feedback replaces the result. */ +export const HOOK_BLOCKED = 'HOOK_BLOCKED' diff --git a/packages/experimental/hook-protocol/src/index.ts b/packages/experimental/hook-protocol/src/index.ts index f36b86b44b..f50ed03bc9 100644 --- a/packages/experimental/hook-protocol/src/index.ts +++ b/packages/experimental/hook-protocol/src/index.ts @@ -13,6 +13,7 @@ export type { MatcherGroup, MatcherMode, } from './types.ts' +export { HOOK_BLOCKED, HOOK_DENIED, HOOK_ERROR_NAME } from './errors.ts' export { matcherDiagnostic, matchesMatcher, selectHookGroups } from './matcher.ts' export { parseHookOutput } from './codec.ts' export { DEFAULT_HOOK_TIMEOUT_MS, runHook } from './runner.ts' diff --git a/packages/experimental/hooks-claude-code/README.i18n.yaml b/packages/experimental/hooks-claude-code/README.i18n.yaml index dec4a60dd0..7e512a4396 100644 --- a/packages/experimental/hooks-claude-code/README.i18n.yaml +++ b/packages/experimental/hooks-claude-code/README.i18n.yaml @@ -72,8 +72,8 @@ en: 82be8d95921ef639 zh: 11c185068ec18932 /deepseek-ai-dsh-hooks-claude-code/model-experience/blocked-prompt-or-tool-outcome/what-the-model-sees: - en: 1313b662532a2bda - zh: 4002d38540286a94 + en: fe02a31c04fd91d1 + zh: 39e55aad9940eae4 /deepseek-ai-dsh-hooks-claude-code/model-experience/blocked-prompt-or-tool-outcome/token-effect: en: 7c13e10d2a0e3151 zh: 54ffd88bca4fce3a diff --git a/packages/experimental/hooks-claude-code/README.md b/packages/experimental/hooks-claude-code/README.md index 97dd24d8d7..bda6fce76c 100644 --- a/packages/experimental/hooks-claude-code/README.md +++ b/packages/experimental/hooks-claude-code/README.md @@ -155,7 +155,7 @@ Append-only; newly visible content follows the reusable request prefix and does #### What the model sees -Provider-supplied reasons pass through verbatim. When absent, a denied tool becomes `Error: blocked by PreToolUse hook`, blocked post-tool feedback is exactly `blocked by PostToolUse hook`, and a blocking stop adds steering exactly `continue: blocked by Stop hook`; a blocked prompt is discarded with no model-visible message, ending the turn as `blocked`. `systemMessage` and `updatedInput` are logged or warned but are not model-visible in this implementation. +Provider-supplied reasons pass through verbatim. When absent, a denied tool becomes `Error: blocked by PreToolUse hook`, blocked post-tool feedback is exactly `blocked by PostToolUse hook`, and a blocking stop adds steering exactly `continue: blocked by Stop hook`; a blocked prompt is discarded with no model-visible message, ending the turn as `blocked`. Denied tool calls record `HookError` with `HOOK_DENIED` on `tool/result`, and blocked post-tool results record `HookError` with `HOOK_BLOCKED`. `systemMessage` and `updatedInput` are logged or warned but are not model-visible in this implementation. #### Token effect diff --git a/packages/experimental/hooks-claude-code/README.zh.md b/packages/experimental/hooks-claude-code/README.zh.md index 829ddd92bf..b91000df0e 100644 --- a/packages/experimental/hooks-claude-code/README.zh.md +++ b/packages/experimental/hooks-claude-code/README.zh.md @@ -155,7 +155,7 @@ hook 不返回上下文时没有成本。Hook 文本取决于数据,会被记 #### 模型看到什么 -提供方提供的原因逐字传递。缺失原因时,已拒绝工具变为 `Error: blocked by PreToolUse hook`,已阻塞工具后反馈精确为 `blocked by PostToolUse hook`,阻塞 stop 则精确添加 steering `continue: blocked by Stop hook`;已阻塞提示词不会产生任何模型可见消息,而是以 `blocked` 结束该轮次。`systemMessage` 与 `updatedInput` 会被记录或警告,但在此实现中对模型不可见。 +提供方提供的原因逐字传递。缺失原因时,已拒绝工具变为 `Error: blocked by PreToolUse hook`,已阻塞工具后反馈精确为 `blocked by PostToolUse hook`,阻塞 stop 则精确添加 steering `continue: blocked by Stop hook`;已阻塞提示词不会产生任何模型可见消息,而是以 `blocked` 结束该轮次。已拒绝的工具调用在 `tool/result` 上记录 `HookError` 与 `HOOK_DENIED`,已阻塞的工具后结果记录 `HookError` 与 `HOOK_BLOCKED`。`systemMessage` 与 `updatedInput` 会被记录或警告,但在此实现中对模型不可见。 #### Token 影响 diff --git a/packages/experimental/hooks-claude-code/src/index.ts b/packages/experimental/hooks-claude-code/src/index.ts index 5e2b59d3d8..19f957ddca 100644 --- a/packages/experimental/hooks-claude-code/src/index.ts +++ b/packages/experimental/hooks-claude-code/src/index.ts @@ -30,6 +30,9 @@ import { createDetachedRuns, DEFAULT_HOOK_TIMEOUT_MS, DEFAULT_STDERR_SUMMARY_MAX_CHARS, + HOOK_BLOCKED, + HOOK_DENIED, + HOOK_ERROR_NAME, mergeHookOutputs, runHook, selectHookGroups, @@ -243,7 +246,7 @@ export function apply(ctx: Context, config: Config): void { ctx.on('tools/pre-execute', async (exec, next): Promise => { const turn = lastTurn(ctx, exec.agent) const merged = await runPoint('PreToolUse', exec.name, preToolPayload(exec), { ...exec.agent ? { agent: exec.agent } : {}, turn, signal: exec.signal }) - if (merged.decision === 'deny') return { kind: 'deny', reason: merged.reason ?? 'blocked by PreToolUse hook' } + if (merged.decision === 'deny') return { kind: 'deny', reason: merged.reason ?? 'blocked by PreToolUse hook', info: { name: HOOK_ERROR_NAME, code: HOOK_DENIED } } if (merged.decision === 'ask') return { kind: 'ask', ...merged.reason !== undefined ? { reason: merged.reason } : {} } return next() }) @@ -254,7 +257,12 @@ export function apply(ctx: Context, config: Config): void { const merged = await runPoint('PostToolUse', exec.name, postToolPayload(exec, result), { ...exec.agent ? { agent: exec.agent } : {}, turn, signal: exec.signal }) const context = contextFrom(merged) if (merged.decision === 'deny') { - return { kind: 'block', feedback: [{ type: 'text', text: merged.reason ?? 'blocked by PostToolUse hook' }], ...context ? { additionalContexts: [context] } : {} } + return { + kind: 'block', + feedback: [{ type: 'text', text: merged.reason ?? 'blocked by PostToolUse hook' }], + info: { name: HOOK_ERROR_NAME, code: HOOK_BLOCKED }, + ...context ? { additionalContexts: [context] } : {}, + } } // Our hooks did not block. DELEGATE so a later listener can still block/replace, // then fold our context onto its decision (a downstream block carries it too). diff --git a/packages/experimental/hooks-claude-code/tests/coverage-cases.ts b/packages/experimental/hooks-claude-code/tests/coverage-cases.ts index c1433727c1..a0b933165c 100644 --- a/packages/experimental/hooks-claude-code/tests/coverage-cases.ts +++ b/packages/experimental/hooks-claude-code/tests/coverage-cases.ts @@ -303,6 +303,7 @@ export function defineCoverageCases(group: CoverageGroup): void { await waitForIdle(ctx, agent) const result = events(agent).find(e => e.type === 'tool/result') expect(result?.type === 'tool/result' && result.data.message.content.some(b => b.type === 'text' && b.text.includes('blocked by PreToolUse hook'))).toBe(true) + expect(result?.type === 'tool/result' && result.data.error).toEqual({ name: 'HookError', code: 'HOOK_DENIED' }) }) it('PostToolUse deny with EMPTY stderr + no context uses the default feedback', async () => { @@ -317,6 +318,7 @@ export function defineCoverageCases(group: CoverageGroup): void { await waitForIdle(ctx, agent) const result = events(agent).find(e => e.type === 'tool/result') expect(result?.type === 'tool/result' && result.data.message.content.some(b => b.type === 'text' && b.text.includes('blocked by PostToolUse hook'))).toBe(true) + expect(result?.type === 'tool/result' && result.data.error).toEqual({ name: 'HookError', code: 'HOOK_BLOCKED' }) }) it('SubagentStop with no registered child runs the hook cleanly (fire-and-forget)', async () => { diff --git a/packages/experimental/hooks-codex/README.i18n.yaml b/packages/experimental/hooks-codex/README.i18n.yaml index be1bac6e41..b106a77cc2 100644 --- a/packages/experimental/hooks-codex/README.i18n.yaml +++ b/packages/experimental/hooks-codex/README.i18n.yaml @@ -72,8 +72,8 @@ en: 82be8d95921ef639 zh: 11c185068ec18932 /deepseek-ai-dsh-hooks-codex/model-experience/blocked-prompt-or-tool-outcome/what-the-model-sees: - en: fd44027de2255f3f - zh: d880eb4d2d3f6af8 + en: ca7de360c3a5f25e + zh: 639c09fef35e4a2d /deepseek-ai-dsh-hooks-codex/model-experience/blocked-prompt-or-tool-outcome/token-effect: en: 7c13e10d2a0e3151 zh: 54ffd88bca4fce3a diff --git a/packages/experimental/hooks-codex/README.md b/packages/experimental/hooks-codex/README.md index 3c054a0613..dedb1cb03b 100644 --- a/packages/experimental/hooks-codex/README.md +++ b/packages/experimental/hooks-codex/README.md @@ -151,7 +151,7 @@ Append-only; newly visible content follows the reusable request prefix and does #### What the model sees -Provider-supplied reasons pass through verbatim. When absent, a denied tool becomes `Error: blocked by PreToolUse hook`, blocked post-tool feedback is exactly `blocked by PostToolUse hook`, and a blocking stop adds steering exactly `continue: blocked by Stop hook`; a blocked prompt is discarded with no model-visible message, ending the turn as `blocked`. Codex `systemMessage` is not surfaced. +Provider-supplied reasons pass through verbatim. When absent, a denied tool becomes `Error: blocked by PreToolUse hook`, blocked post-tool feedback is exactly `blocked by PostToolUse hook`, and a blocking stop adds steering exactly `continue: blocked by Stop hook`; a blocked prompt is discarded with no model-visible message, ending the turn as `blocked`. Denied tool calls record `HookError` with `HOOK_DENIED` on `tool/result`, and blocked post-tool results record `HookError` with `HOOK_BLOCKED`. Codex `systemMessage` is not surfaced. #### Token effect diff --git a/packages/experimental/hooks-codex/README.zh.md b/packages/experimental/hooks-codex/README.zh.md index 420e13b2fb..8c3d78176b 100644 --- a/packages/experimental/hooks-codex/README.zh.md +++ b/packages/experimental/hooks-codex/README.zh.md @@ -151,7 +151,7 @@ hook 不返回上下文时没有成本。Hook 文本取决于数据,会被记 #### 模型看到什么 -提供方提供的原因逐字传递。缺失原因时,已拒绝工具变为 `Error: blocked by PreToolUse hook`,已阻塞工具后反馈精确为 `blocked by PostToolUse hook`,阻塞 stop 则精确添加 steering `continue: blocked by Stop hook`;已阻塞提示词不会产生任何模型可见消息,而是以 `blocked` 结束该轮次。Codex `systemMessage` 不会呈现。 +提供方提供的原因逐字传递。缺失原因时,已拒绝工具变为 `Error: blocked by PreToolUse hook`,已阻塞工具后反馈精确为 `blocked by PostToolUse hook`,阻塞 stop 则精确添加 steering `continue: blocked by Stop hook`;已阻塞提示词不会产生任何模型可见消息,而是以 `blocked` 结束该轮次。已拒绝的工具调用在 `tool/result` 上记录 `HookError` 与 `HOOK_DENIED`,已阻塞的工具后结果记录 `HookError` 与 `HOOK_BLOCKED`。Codex `systemMessage` 不会呈现。 #### Token 影响 diff --git a/packages/experimental/hooks-codex/src/index.ts b/packages/experimental/hooks-codex/src/index.ts index 2d9b3c3daf..4a04055c20 100644 --- a/packages/experimental/hooks-codex/src/index.ts +++ b/packages/experimental/hooks-codex/src/index.ts @@ -33,6 +33,9 @@ import { createDetachedRuns, DEFAULT_HOOK_TIMEOUT_MS, DEFAULT_STDERR_SUMMARY_MAX_CHARS, + HOOK_BLOCKED, + HOOK_DENIED, + HOOK_ERROR_NAME, mergeHookOutputs, runHook, selectHookGroups, @@ -228,7 +231,7 @@ export function apply(ctx: Context, config: Config): void { const turn = lastTurn(ctx, exec.agent) const merged = await runPoint('PreToolUse', exec.name, preToolPayload(ctx, exec, model), { ...exec.agent ? { agent: exec.agent } : {}, turn, signal: exec.signal }) /* jscpd:ignore-end */ - if (merged.decision === 'deny') return { kind: 'deny', reason: merged.reason ?? 'blocked by PreToolUse hook' } + if (merged.decision === 'deny') return { kind: 'deny', reason: merged.reason ?? 'blocked by PreToolUse hook', info: { name: HOOK_ERROR_NAME, code: HOOK_DENIED } } return next() }) @@ -239,7 +242,12 @@ export function apply(ctx: Context, config: Config): void { const merged = await runPoint('PostToolUse', exec.name, postToolPayload(ctx, exec, result, model), { ...exec.agent ? { agent: exec.agent } : {}, turn, signal: exec.signal }) const context = contextFrom(merged) if (merged.decision === 'deny') { - return { kind: 'block', feedback: [{ type: 'text', text: merged.reason ?? 'blocked by PostToolUse hook' }], ...context ? { additionalContexts: [context] } : {} } + return { + kind: 'block', + feedback: [{ type: 'text', text: merged.reason ?? 'blocked by PostToolUse hook' }], + info: { name: HOOK_ERROR_NAME, code: HOOK_BLOCKED }, + ...context ? { additionalContexts: [context] } : {}, + } } // Context alone is not a veto: DELEGATE, then fold our context onto the // downstream decision (a downstream block carries it too). diff --git a/packages/experimental/hooks-codex/tests/coverage-cases.ts b/packages/experimental/hooks-codex/tests/coverage-cases.ts index 6e77124a69..fd9ebbb558 100644 --- a/packages/experimental/hooks-codex/tests/coverage-cases.ts +++ b/packages/experimental/hooks-codex/tests/coverage-cases.ts @@ -236,6 +236,7 @@ export function defineCoverageCases(groups: CoverageGroup | readonly CoverageGro const r = events(agent).find(e => e.type === 'tool/result') expect(r?.type === 'tool/result' && r.data.message.isError).toBe(true) expect(r?.type === 'tool/result' && r.data.message.content.some(b => b.type === 'text' && b.text.includes('blocked by PostToolUse hook'))).toBe(true) + expect(r?.type === 'tool/result' && r.data.error).toEqual({ name: 'HookError', code: 'HOOK_BLOCKED' }) }) it('PostToolUse additionalContext (clean exit) is attached after the result', async () => { @@ -438,6 +439,7 @@ export function defineCoverageCases(groups: CoverageGroup | readonly CoverageGro agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } })); await waitForIdle(ctx, agent) const r = events(agent).find(e => e.type === 'tool/result') expect(r?.type === 'tool/result' && r.data.message.content.some(b => b.type === 'text' && b.text.includes('blocked by PreToolUse hook'))).toBe(true) + expect(r?.type === 'tool/result' && r.data.error).toEqual({ name: 'HookError', code: 'HOOK_DENIED' }) }) it('PostToolUse block AND additionalContext are surfaced together', async () => { diff --git a/packages/experimental/liveshare/README.i18n.yaml b/packages/experimental/liveshare/README.i18n.yaml index 881d9de1e4..3ee1afd4ce 100644 --- a/packages/experimental/liveshare/README.i18n.yaml +++ b/packages/experimental/liveshare/README.i18n.yaml @@ -33,8 +33,8 @@ en: 2052fd7c4e9c3f98 zh: 5ef2ac5ad9ec7990 /deepseek-ai-dsh-experimental-liveshare/understand-the-implementation: - en: 74c336962ca47ab5 - zh: ae3628a038bd4791 + en: 37d649ff38fca348 + zh: c73e526eac1e3778 /deepseek-ai-dsh-experimental-liveshare/further-exploration: en: 0570170704bbe5b6 zh: 832f86024b26e5b3 diff --git a/packages/experimental/liveshare/README.md b/packages/experimental/liveshare/README.md index 07f2cc8d39..70a67fb833 100644 --- a/packages/experimental/liveshare/README.md +++ b/packages/experimental/liveshare/README.md @@ -109,7 +109,7 @@ The Owner Gateway decides each call on the Session and Workspace it names and re The viewer page is the Owner's own Web shell. The Liveshare server fetches the Owner's rendered index document through an `asset` read and places the carrier script from [viewer-carrier.ts](../liveshare-protocol/src/viewer-carrier.ts) first in it. Shell assets, client plugin bundles, and the three exact top-level files the index references against the document base — `manifest.webmanifest`, `favicon.svg`, and `favicon-dark.svg` — arrive through the same read, from the Owner's frontend reader and client module registry, so the page runs every Owner plugin at the Owner's version. Source maps are refused on every asset path, and that check is the authoritative one: an `asset` read forwarded through the Liveshare server arrives here unread, so the Liveshare server's own same-named rule covers its page-resource route only. The served document also drops its manifest link, which a browser would otherwise fetch without credentials. The carrier converts Connection calls and Gateway streams into `POST {base}/__share/rpc` requests, and forwards the read-only page-origin owner routes the Liveshare server cannot answer — `/open-in-app/apps` and `/api/present.host` — through that channel instead of leaving them to the Liveshare server's tail. The Liveshare server supplies the authenticated actor outside the opaque body. The Owner's read handler dispatches each reader's calls and streams into its own Connection and Gateway as one Peer per share and reader, whose `share-viewer` principal carries the share and the server-asserted identity. The Gateway decides that Peer's calls, and the Session notifications it forwards to it, through [`dsh-api-remote-access`](../../api/remote-access/README.md) from the `share-viewer` policy this package registers: a served reader holds read roles on the shared Session, its own forks, and the Workspaces holding them, fork and write roles whose conditions apply the share's tier and its own fork switch, and nothing else; attachment upload rides the read roles. The read handler keeps the share-lifecycle refusals, Liveshare server authority refresh, cold Session preparation, and fork orchestration, reads the policy's write rules before it prepares or dispatches a prompt or stop, and disposes a reader's Peer when its grant ends, the share stops or expires, or a re-check refuses it. Preparing a share's source Session also starts when a reader asks for its page or opens a stream, so a host that restarted before that Session's agent was live still gains the actions it drives with; a share whose Session cannot be confined states that instead of the read-only fact. This package's browser face mounts the viewer surfaces when the carrier's `__DSH_LIVESHARE_VIEWER__` global is present and the Share action otherwise. The served index assigns the reader's own access snapshot to the global that every index sets to the owner baseline, and the page then follows the reader's `remoteAccess/follow` snapshot; CSS hiding is not authorization. -Fork requests bind the actor, share, source, operation identity, and completed prefix. A durable reservation and the recorded child let a retry of a recorded operation replay the same child; the owner's `SessionForkRequest` mints the child id, so a request interrupted after the child was created but before it was recorded forks again. Registry mutations are asynchronous and resolve only after locked read-modify-write and atomic publication; callers must await reservation, recording, and revocation. Cold activation uses the Host’s ordinary Agent lookup, with serial `agent/created` enforcement before queued input can run, not a Remote `session/prepare` endpoint. The child scope retains one fail-closed guard; reconnection replaces its enforcement installation, and releasing an old installation cannot remove its successor. +Fork requests bind the actor, share, source, operation identity, and completed prefix. A durable reservation and the recorded child let a retry of a recorded operation replay the same child; the owner's `SessionForkRequest` mints the child id, so a request interrupted after the child was created but before it was recorded forks again. Registry mutations are asynchronous and resolve only after locked read-modify-write and atomic publication; callers must await reservation, recording, and revocation. Cold activation uses the Host’s ordinary Agent lookup, with serial `agent/created` enforcement before queued input can run, not a Remote `session/prepare` endpoint. The child scope retains one fail-closed guard; reconnection replaces its enforcement installation, and releasing an old installation cannot remove its successor. Refusals carry one identity per condition whether the guard or a confined replacement decides: a path outside the granted workspace is `FsError` `FS_SANDBOX_DENIED`; a tool, or a write, that the fork's limit or the share's current grant does not admit is `LiveshareForkDeniedError` `FORK_TOOL_NOT_PERMITTED`; the guard's other refusals use the remaining `FORK_*` codes in [fork-errors.ts](src/host/fork-errors.ts); and arguments a replacement cannot confine fail with `ToolArgsError`. A reader's prompt reaches the Session as a `user-rpc` message whose `source.principal` names that reader, and the pre-step re-checks every entering message's viewer against the Relay's admission before it reaches the model. Execution is confined per turn: while any share over the Session is active, a turn whose admitted input names a share viewer runs the Host's confined replacements for the read and search surface (`read`, `read_image`, `glob`, `grep`, `present`), keeps the deployment's own definitions of the tools with no local file effect (`todo_write`, `skill`, `web_search`, `web_fetch`), admits the PTC transport `run_code` from the selected executor, and, when some share may write, its bounded `edit` and `write`. Every other tool is refused to that turn, and every path a permitted call declares is resolved and checked against the granted root. An owner-started turn keeps the Session's native tools until the last share stops or expires. The turn decision is Host memory only, recomputed for each turn and never appended to the Session log. Each operation re-reads the shares' current Relay grants and checks the resolved target against the granted root. A reader's stop is dispatched through the Gateway like a prompt: the `share-viewer` policy admits it while the share's tier is established and the Session is confined, and the owner's own Session controller stops whatever turn the Session is running, including one the owner started. Reads and writes preserve the normal write-observation policy. See the [LiveShare subsystem](../../../docs/subsystems/liveshare.md) for the execution rules. diff --git a/packages/experimental/liveshare/README.zh.md b/packages/experimental/liveshare/README.zh.md index c50adc1756..91343b4ad3 100644 --- a/packages/experimental/liveshare/README.zh.md +++ b/packages/experimental/liveshare/README.zh.md @@ -109,7 +109,7 @@ Owner Gateway 按调用指明的 Session 与工作区判定每次调用,并拒 查看页就是 Owner 自己的 Web shell。Liveshare 服务端通过 `asset` 读取取得 Owner 渲染好的 index 文档,并把 [viewer-carrier.ts](../liveshare-protocol/src/viewer-carrier.ts) 生成的载体脚本放在文档最前面。Shell 资源、客户端插件 bundle,以及 index 相对文档基准引用的三个确切顶层文件(`manifest.webmanifest`、`favicon.svg`、`favicon-dark.svg`)都经同一读取取得,来自 Owner 的前端读取服务和客户端模块注册表,因此页面以 Owner 的版本运行 Owner 的全部插件。任何 asset 路径上的 source map 都被拒绝,且该判定是权威的:经 Liveshare 服务端转发的 `asset` 读取会原样到达这里,因此 Liveshare 服务端侧的同名规则只覆盖它自己的页面资源路由;被服务的文档还会去掉自己的 manifest 链接,否则浏览器会不带凭据地抓取它。载体把 Connection 调用和 Gateway 流转换为 `POST {base}/__share/rpc` 请求,并把 Liveshare 服务端无法作答的只读页面源 Owner 路由(`/open-in-app/apps` 与 `/api/present.host`)也经该通道转发,而不是留给 Liveshare 服务端尾部。Liveshare 服务端在不透明请求体之外提供已认证主体。Owner 读取处理器把每位读者的调用和流以「每个分享、每位读者一个 Peer」分派进自己的 Connection 与 Gateway,该 Peer 的 `share-viewer` principal 携带分享与服务端断言的身份。Gateway 依据本包注册的 `share-viewer` 策略,经 [`dsh-api-remote-access`](../../api/remote-access/README.zh.md) 判定该 Peer 的调用以及转发给它的会话通知:受服务的读者持有共享会话、其自己的 fork 及包含它们的工作区上的读取角色,持有条件按分享档位与其自身 fork 开关判定的 fork 与写入角色,此外别无授权;附件上传随读取角色生效。读取处理器保留分享生命周期拒绝、Liveshare 服务端授权刷新、冷会话准备和 fork 编排,在准备或分派提示词与停止之前读取策略的写入规则,并在授权结束、分享停止或过期、或复检拒绝时释放读者的 Peer。读者索取页面或打开流时也会开始准备该分享的源会话,因此宿主重启时该会话的 agent 尚未存活也能补上驱动所需的层;无法被 confine 的分享会如实说明该状态,而不再声明只读。存在载体写入的 `__DSH_LIVESHARE_VIEWER__` 全局变量时,本包的浏览器端挂载查看页界面,否则挂载分享操作。读者收到的 index 把读者自己的访问快照赋给每个 index 设为所有者基线的同一全局变量,页面随后跟随读者的 `remoteAccess/follow` 快照;CSS 隐藏不构成授权。 -Fork 请求绑定主体、分享、源会话、操作身份和已完成前缀。持久化预留记录与已记录的分叉会话使重试已记录的操作时重放同一分叉会话;owner 的 `SessionForkRequest` 自己生成分叉会话 id,因此在分叉会话已创建、但尚未记录时中断的请求会再次 fork。注册表变更为异步操作,仅在加锁的读取、修改与原子发布后完成;调用方必须等待预留、记录与撤销。冷态激活使用 Host 常规 Agent lookup,由串行 `agent/created` 在排队输入运行前安装限制,不使用 Remote `session/prepare` 端点。分叉会话作用域保留单个默认拒绝的 guard;重连替换其限制安装,释放旧安装不会移除继任。 +Fork 请求绑定主体、分享、源会话、操作身份和已完成前缀。持久化预留记录与已记录的分叉会话使重试已记录的操作时重放同一分叉会话;owner 的 `SessionForkRequest` 自己生成分叉会话 id,因此在分叉会话已创建、但尚未记录时中断的请求会再次 fork。注册表变更为异步操作,仅在加锁的读取、修改与原子发布后完成;调用方必须等待预留、记录与撤销。冷态激活使用 Host 常规 Agent lookup,由串行 `agent/created` 在排队输入运行前安装限制,不使用 Remote `session/prepare` 端点。分叉会话作用域保留单个默认拒绝的 guard;重连替换其限制安装,释放旧安装不会移除继任。无论由 guard 还是受限替换工具判定,同一种拒绝只有一个标识:授权工作区外的路径为 `FsError` `FS_SANDBOX_DENIED`;fork 的限制或分享当前授权不允许的工具或写入为 `LiveshareForkDeniedError` `FORK_TOOL_NOT_PERMITTED`;guard 的其他拒绝使用 [fork-errors.ts](src/host/fork-errors.ts) 中其余的 `FORK_*` code;替换工具无法限制的参数以 `ToolArgsError` 失败。 读者的提示词以 `user-rpc` 消息进入会话,其 `source.principal` 指明该读者;pre-step 在每条进入消息到达模型前,按 Relay 的准入重新检查其查看者。执行按轮次受限:只要有分享处于活跃状态,已准入输入中带有 share-viewer principal 的轮次就运行 Host 挂载的读取与检索面(`read`、`read_image`、`glob`、`grep`、`present`)受限替代、保留无本地文件副作用工具(`todo_write`、`skill`、`web_search`、`web_fetch`)的原生定义、放行选定执行器提供的 PTC 传输工具 `run_code`,以及(当某个分享允许写入时)有界 `edit` 与 `write`。其余所有工具对该轮次一律拒绝,且每次允许的调用声明的每个路径都会解析并按获授根目录检查。所有者自己发起的轮次保留会话原生工具,直到最后一个分享停止或过期。该轮次判定只存在于 Host 内存,按轮次重算,不写入会话日志。每次操作都会重新读取分享当前的 Relay 授权,并按获授根目录检查解析后的目标。读者的停止与提示词一样经 Gateway 分派:`share-viewer` 策略在分享档位确立且会话受沙箱限制时放行,随后由所有者自己的会话控制器停止该会话当前运行的轮次,包括所有者发起的轮次。读写保留正常写入观察策略。执行规则见 [LiveShare 子系统](../../../docs/subsystems/liveshare.zh.md)。 diff --git a/packages/experimental/liveshare/package.json b/packages/experimental/liveshare/package.json index 8bd5992baa..cccfc1296e 100644 --- a/packages/experimental/liveshare/package.json +++ b/packages/experimental/liveshare/package.json @@ -73,7 +73,10 @@ }, "peerDependencies": { "@deepseek-ai/cordis": "workspace:~", - "@deepseek-ai/dsh-scope": "workspace:*" + "@deepseek-ai/dsh-scope": "workspace:*", + "@deepseek-ai/dsh-fs": "workspace:*", + "@deepseek-ai/dsh-tools": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" }, "devDependencies": { "@deepseek-ai/dsh-session": "workspace:*", @@ -148,7 +151,8 @@ "@deepseek-ai/dsh-workspace": "workspace:*", "@types/ws": "^8.18.1", "react": "^18.2.0", - "react-dom": "^18.2.0" + "react-dom": "^18.2.0", + "@deepseek-ai/dsh-error": "workspace:*" }, "dsh": { "bundle": { diff --git a/packages/experimental/liveshare/src/host/fork-enforcement.ts b/packages/experimental/liveshare/src/host/fork-enforcement.ts index 12a19af436..2e48ce170e 100644 --- a/packages/experimental/liveshare/src/host/fork-enforcement.ts +++ b/packages/experimental/liveshare/src/host/fork-enforcement.ts @@ -24,10 +24,12 @@ import type { FsWriteOutcome, FsWriteIntent, } from '@deepseek-ai/dsh-fs' -import type { PreToolDecision, ToolDefinition, ToolExecution } from '@deepseek-ai/dsh-tools' +import { FsError } from '@deepseek-ai/dsh-fs' +import { ToolArgsError, type PreToolDecision, type ToolDefinition, type ToolExecution } from '@deepseek-ai/dsh-tools' import type { Session } from '@deepseek-ai/dsh-session' import type { SandboxExecutionPolicy } from '@deepseek-ai/dsh-sandbox' import { scopeOf } from '@deepseek-ai/dsh-scope' +import { forkToolDenial, LiveshareForkDeniedError } from './fork-errors.ts' import { forkToolGuard, installChildEnforcement, type ForkToolExecution } from './fork-tool-guard.ts' import { READ_ONLY_FORK_CEILING, WRITE_FORK_CEILING } from './fork-policy.ts' import type { ForkRegistry } from './fork-registry.ts' @@ -237,7 +239,7 @@ export function installSourceSessionAccess(target: SourceSessionAccess): SourceS const input = isRecord(args) ? args : {} const call = profile.call(input) if (call === undefined) { - throw new Error(`a shared session may only use ${profile.name} with the paths it declares`) + throw new ToolArgsError([`a shared session may only use ${profile.name} with the paths it declares`]) } // A pathless search reads the workspace default, so its replacement supplies the working directory // as the root it checks and hands to the tool. @@ -263,12 +265,12 @@ export function installSourceSessionAccess(target: SourceSessionAccess): SourceS await target.refreshAuthorization?.() // The Session's current shares decide, not the tier the layer was installed for: a share can // narrow to view while this layer stays mounted. - if (!gate.mayWrite()) throw new Error('this share does not allow writing this Session') + if (!gate.mayWrite()) throw new LiveshareForkDeniedError('this share does not allow writing this Session', 'FORK_TOOL_NOT_PERMITTED') const input = isRecord(args) ? args : {} const requested = input.file_path const content = input.content if (typeof requested !== 'string' || requested === '' || typeof content !== 'string') { - throw new Error('a shared session may only write a named file with text content') + throw new ToolArgsError(['a shared session may only write a named file with text content']) } const candidate = await fs.resolve(requested, { cwd: target.cwd, signal: exec.signal }) assertGranted(fs, target.grantedRoot, candidate, 'write') @@ -280,7 +282,7 @@ export function installSourceSessionAccess(target: SourceSessionAccess): SourceS const policy = target.resolvePolicy() // The shares can narrow while the intent awaited: the final refresh above reads the new state, so // ask the gate again before anything is written instead of trusting the earlier verdict. - if (!gate.mayWrite()) throw new Error('this share does not allow writing this Session') + if (!gate.mayWrite()) throw new LiveshareForkDeniedError('this share does not allow writing this Session', 'FORK_TOOL_NOT_PERMITTED') const outcome = await fs.writeText(candidate, content, intent, exec.signal, policy) // The published version is this caller's own next basis, exactly as the shipped write records it: // without it a second write of the same file would meet a policy that saw nothing since the read. @@ -300,10 +302,10 @@ export function installSourceSessionAccess(target: SourceSessionAccess): SourceS register(FORK_EDIT_TOOL, deploymentEdit, async (args, exec) => { if (!confined(exec)) return await deploymentEdit.execute(args, exec) await target.refreshAuthorization?.() - if (!gate.mayWrite()) throw new Error('this share does not allow writing this Session') + if (!gate.mayWrite()) throw new LiveshareForkDeniedError('this share does not allow writing this Session', 'FORK_TOOL_NOT_PERMITTED') const edit = sharedEditArguments(args) if (edit === undefined) { - throw new Error('a shared session may only edit a named file by replacing non-empty text') + throw new ToolArgsError(['a shared session may only edit a named file by replacing non-empty text']) } const candidate = await fs.resolve(edit.filePath, { cwd: target.cwd, signal: exec.signal }) assertGranted(fs, target.grantedRoot, candidate, 'write') @@ -312,7 +314,7 @@ export function installSourceSessionAccess(target: SourceSessionAccess): SourceS const intent = await context.waterfall('fs/edit-intent', candidate, exec, () => undefined) await target.refreshAuthorization?.() const policy = target.resolvePolicy() - if (!gate.mayWrite()) throw new Error('this share does not allow writing this Session') + if (!gate.mayWrite()) throw new LiveshareForkDeniedError('this share does not allow writing this Session', 'FORK_TOOL_NOT_PERMITTED') const outcome = await fs.editText( candidate, { oldString: edit.oldString, newString: edit.newString, replaceAll: edit.replaceAll }, @@ -339,7 +341,7 @@ export function installSourceSessionAccess(target: SourceSessionAccess): SourceS // identity. A name answering to a different definition — a scope-registered shadow — is refused. const deployment = passthrough.get(execution.name) if (deployment !== undefined && deploymentOf(execution.name) === deployment) return undefined - return `a shared session may not use ${execution.name}` + return forkToolDenial(`a shared session may not use ${execution.name}`, 'FORK_TOOL_NOT_PERMITTED') }) disposers.push(guard) return { @@ -406,30 +408,19 @@ export interface ForkEnforcementFs { ) => Promise } -/** A refusal of a target outside the granted workspace; callers identify it by `code` alone. */ -type GrantedRootRefusal = Error & { readonly code: 'FS_SANDBOX_DENIED' } - -/** - * Build the refusal of a target outside the granted workspace. - * @param message - What was refused and why. - * @returns An `Error` carrying the `FS_SANDBOX_DENIED` code. - */ -function grantedRootRefusal(message: string): GrantedRootRefusal { - return Object.assign(new Error(message), { code: 'FS_SANDBOX_DENIED' as const }) -} - /** * Refuse a resolved target that the granted root does not contain. * @param fs - Filesystem whose containment rule decides. * @param root - The granted workspace root. * @param candidate - The resolved target one call names. * @param operation - The operation named in the refusal. - * @throws GrantedRootRefusal when the granted root does not contain `candidate`. + * @throws FsError `FS_SANDBOX_DENIED` when the granted root does not contain `candidate`. */ function assertGranted(fs: ForkEnforcementFs, root: FsTarget, candidate: FsTarget, operation: 'read' | 'write'): void { if (fs.contains(root, candidate)) return - throw grantedRootRefusal( + throw new FsError( `cannot ${operation} "${candidate.displayPath}": it is not inside the workspace this session was granted`, + 'FS_SANDBOX_DENIED', ) } @@ -692,7 +683,7 @@ export function installForkEnforcement( const { childContext, childScope, fs, forks } = target const requireAuthorized = (tool: string): void => { if (!forks.enforcementInstalled(target.childSessionId) || target.authorized?.(tool) === false) { - throw new Error('this fork no longer holds permission for this tool') + throw new LiveshareForkDeniedError('this fork no longer holds permission for this tool', 'FORK_TOOL_NOT_PERMITTED') } } /** @@ -775,7 +766,7 @@ export function installForkEnforcement( const input = isRecord(args) ? args : {} const call = profile.call(input) if (call === undefined) { - throw new Error(`a fork may only use ${profile.name} with the paths it declares`) + throw new ToolArgsError([`a fork may only use ${profile.name} with the paths it declares`]) } // A pathless search reads the workspace default, so its replacement supplies the working directory // as the root it checks and hands to the tool. @@ -784,7 +775,7 @@ export function installForkEnforcement( for (const path of named) { const candidate = await fs.resolve(path, { cwd: target.cwd, signal: exec.signal }) if (!fs.contains(target.grantedRoot, candidate)) { - throw new Error('a fork may only read inside the workspace it was granted') + throw new FsError('a fork may only read inside the workspace it was granted', 'FS_SANDBOX_DENIED') } canonical.push(fs.processPath(candidate)) } @@ -819,13 +810,13 @@ export function installForkEnforcement( const requested = input.file_path const content = input.content if (typeof requested !== 'string' || requested === '' || typeof content !== 'string') { - throw new Error('a fork may only write a named file with text content') + throw new ToolArgsError(['a fork may only write a named file with text content']) } await target.refreshAuthorized?.() requireAuthorized(FORK_WRITE_TOOL) const candidate = await fs.resolve(requested, { cwd: target.cwd, signal: exec.signal }) if (!fs.contains(target.grantedRoot, candidate)) { - throw new Error('a fork may only write inside the workspace it was granted') + throw new FsError('a fork may only write inside the workspace it was granted', 'FS_SANDBOX_DENIED') } const intent = await childContext.waterfall('fs/write-intent', candidate, exec, () => undefined) await target.refreshAuthorized?.() @@ -861,13 +852,13 @@ export function installForkEnforcement( register(FORK_EDIT_TOOL, deployment, async (args, exec) => { const edit = sharedEditArguments(args) if (edit === undefined) { - throw new Error('a fork may only edit a named file by replacing non-empty text') + throw new ToolArgsError(['a fork may only edit a named file by replacing non-empty text']) } await target.refreshAuthorized?.() requireAuthorized(FORK_EDIT_TOOL) const candidate = await fs.resolve(edit.filePath, { cwd: target.cwd, signal: exec.signal }) if (!fs.contains(target.grantedRoot, candidate)) { - throw new Error('a fork may only write inside the workspace it was granted') + throw new FsError('a fork may only write inside the workspace it was granted', 'FS_SANDBOX_DENIED') } // The edit intent comes from the same waterfall the shipped edit uses, so the deployment's // read-before-write rule keeps deciding here too. diff --git a/packages/experimental/liveshare/src/host/fork-errors.ts b/packages/experimental/liveshare/src/host/fork-errors.ts new file mode 100644 index 0000000000..5de4bbe04b --- /dev/null +++ b/packages/experimental/liveshare/src/host/fork-errors.ts @@ -0,0 +1,71 @@ +/** Structured refusals of tool use by a forked or shared Session's viewer-driven turns. @module */ + +import { HarnessError } from '@deepseek-ai/dsh-error' + +/** + * Every {@link LiveshareForkDeniedError} code: + * - `FORK_LIMITS_UNINSTALLED` — no execution limit is installed for the calling fork; nothing it runs can be vouched for. + * - `FORK_CHILD_UNKNOWN` — the call cannot be attributed to a fork child. + * - `FORK_CHILD_MISMATCH` — the call reaches into a Session other than the fork it came from. + * - `FORK_TOOL_NOT_PERMITTED` — the fork's limit or the share's current grant does not admit the tool or its write. + * - `FORK_PATHS_UNKNOWN` — the tool's filesystem effect could not be established, so it could not be authorized. + * + * The model should not retry a refused call unchanged; only `FORK_PATHS_UNKNOWN` can succeed with other arguments. + * A path outside the granted workspace is a filesystem refusal instead: the guard and the confined tools both + * record it as `FsError` with `FS_SANDBOX_DENIED`. + */ +export const LIVESHARE_FORK_DENIED_CODES = [ + 'FORK_LIMITS_UNINSTALLED', + 'FORK_CHILD_UNKNOWN', + 'FORK_CHILD_MISMATCH', + 'FORK_TOOL_NOT_PERMITTED', + 'FORK_PATHS_UNKNOWN', +] as const + +/** One code from {@link LIVESHARE_FORK_DENIED_CODES}. */ +export type LiveshareForkDeniedCode = typeof LIVESHARE_FORK_DENIED_CODES[number] + +/** Error name recorded on every liveshare grant refusal, thrown or returned by a guard. */ +export const LIVESHARE_FORK_DENIED_ERROR_NAME = 'LiveshareForkDeniedError' + +/** A tool use the fork's execution limit or the share's grant refused inside a tool body. */ +export class LiveshareForkDeniedError extends HarnessError { + override readonly code: LiveshareForkDeniedCode + + /** + * @param message - Model-facing refusal. + * @param code - The refused condition. + */ + constructor(message: string, code: LiveshareForkDeniedCode) { + super(message, code) + this.name = 'LiveshareForkDeniedError' + this.code = code + } +} + +/** A guard refusal: the model-facing reason and the structured identity the tool runtime records. */ +export interface ForkToolDenial { + readonly reason: string + readonly info: + | { readonly name: typeof LIVESHARE_FORK_DENIED_ERROR_NAME; readonly code: LiveshareForkDeniedCode } + | { readonly name: 'FsError'; readonly code: 'FS_SANDBOX_DENIED' } +} + +/** + * Build a guard refusal of the grant. + * @param reason - Model-facing refusal. + * @param code - The refused condition. + * @returns The refusal in the structure `ToolGuard` denials take. + */ +export function forkToolDenial(reason: string, code: LiveshareForkDeniedCode): ForkToolDenial { + return { reason, info: { name: LIVESHARE_FORK_DENIED_ERROR_NAME, code } } +} + +/** + * Build a guard refusal of a path outside the granted workspace, with the identity the confined tools throw. + * @param reason - Model-facing refusal. + * @returns The refusal in the structure `ToolGuard` denials take. + */ +export function outsideWorkspaceDenial(reason: string): ForkToolDenial { + return { reason, info: { name: 'FsError', code: 'FS_SANDBOX_DENIED' } } +} diff --git a/packages/experimental/liveshare/src/host/fork-tool-guard.ts b/packages/experimental/liveshare/src/host/fork-tool-guard.ts index 05fb3dac9d..a75de9cba3 100644 --- a/packages/experimental/liveshare/src/host/fork-tool-guard.ts +++ b/packages/experimental/liveshare/src/host/fork-tool-guard.ts @@ -3,14 +3,23 @@ * * It is registered on one child's context, so it speaks for that child alone: it refuses anything the * ceiling does not permit, and it decides paths through the host's real filesystem authorization - * rather than by comparing strings or trusting a tool name. The return value is the reason string the - * tool runtime expects, and a refusal is monotonic — nothing downstream can turn it back into an - * allow. + * rather than by comparing strings or trusting a tool name. A refusal is a `ToolGuard` denial: the + * model-facing reason with the structured error identity the tool runtime records, and it is + * monotonic — nothing downstream can turn it back into an allow. */ -import { forkToolDecision, type ForkToolDecision } from './fork-ceiling.ts' +import { forkToolDecision, type ForkToolDecision, type ForkToolRefusal } from './fork-ceiling.ts' +import { forkToolDenial, outsideWorkspaceDenial, type ForkToolDenial, type LiveshareForkDeniedCode } from './fork-errors.ts' import type { ForkCeiling } from './fork-policy.ts' +/** The recorded code for each grant refusal a fork tool decision names; a path outside the workspace is a filesystem refusal. */ +const REFUSAL_CODES: Readonly, LiveshareForkDeniedCode>> = { + 'fork-ceiling-uninstalled': 'FORK_LIMITS_UNINSTALLED', + 'fork-tool-not-permitted': 'FORK_TOOL_NOT_PERMITTED', + 'fork-child-mismatch': 'FORK_CHILD_MISMATCH', + 'fork-paths-unknown': 'FORK_PATHS_UNKNOWN', +} + /** One tool execution as the runtime presents it to a guard. */ export interface ForkToolExecution { /** Tool being dispatched, as the harness names it. */ @@ -137,7 +146,7 @@ export function decideForkToolUse( /** * Build the guard one child's tool runtime registers. * - * The returned function matches `ToolGuard` structurally — a reason string or undefined — so the host + * The returned function matches `ToolGuard` structurally — a denial with its error identity or undefined — so the host * registers it with `tools.guard(...)` on the child's own context without this package depending on the * tool runtime. * @param ports Host services the guard cannot decide for itself. @@ -150,14 +159,14 @@ export function forkToolGuard( ports: ForkToolGuardPorts, ceilingOf: (childSessionId: string) => ForkCeiling | undefined, describe: (execution: ForkToolExecution) => { readonly paths: readonly string[] | undefined; readonly noFileEffect: boolean }, -): (execution: ForkToolExecution) => string | undefined { +): (execution: ForkToolExecution) => ForkToolDenial | undefined { return (execution) => { const childSessionId = ports.childOf(execution) // An execution this guard cannot attribute to a child is refused: the guard speaks for children, // and an unattributed call is not one it can vouch for. - if (childSessionId === undefined) return 'a fork may not act without a child session' + if (childSessionId === undefined) return forkToolDenial('a fork may not act without a child session', 'FORK_CHILD_UNKNOWN') if (!ports.enforcementInstalled(childSessionId)) { - return 'read-only execution limits are not installed for this fork' + return forkToolDenial('read-only execution limits are not installed for this fork', 'FORK_LIMITS_UNINSTALLED') } const decision = decideForkToolUse(ceilingOf(childSessionId), { childSessionId, @@ -165,7 +174,10 @@ export function forkToolGuard( ...describe(execution), ...(execution.token === undefined ? {} : { token: execution.token }), }, ports) - return decision.ok ? undefined : decision.message + if (decision.ok) return undefined + return decision.code === 'fork-path-outside-workspace' + ? outsideWorkspaceDenial(decision.message) + : forkToolDenial(decision.message, REFUSAL_CODES[decision.code]) } } @@ -181,7 +193,7 @@ export interface ChildEnforcementPorts { */ readonly registerGuard: ( context: Context, - guard: (execution: ForkToolExecution) => string | undefined, + guard: (execution: ForkToolExecution) => ForkToolDenial | undefined, ) => (() => void) | undefined /** Record that this child's limit is installed; false when this host never recorded that child. */ readonly recordEnforcement: (childSessionId: string, ceiling: ForkCeiling) => boolean @@ -202,7 +214,7 @@ export interface ChildEnforcementPorts { /** One context owns the persistent guard and its replaceable enforcement installation. */ interface ChildGuardOwner { installation?: { - readonly guard: (execution: ForkToolExecution) => string | undefined + readonly guard: (execution: ForkToolExecution) => ForkToolDenial | undefined readonly dispose: () => void } } @@ -225,7 +237,7 @@ export function installChildEnforcement( input: { readonly childSessionId: string readonly ceiling: ForkCeiling - readonly guard: (execution: ForkToolExecution) => string | undefined + readonly guard: (execution: ForkToolExecution) => ForkToolDenial | undefined readonly verdictSource: (execution: ForkToolExecution) => Promise }, ports: ChildEnforcementPorts, @@ -240,7 +252,7 @@ export function installChildEnforcement( if (owner === undefined) { const created: ChildGuardOwner = {} if (ports.registerGuard(context, execution => created.installation === undefined - ? 'read-only execution limits are not installed for this fork' + ? forkToolDenial('read-only execution limits are not installed for this fork', 'FORK_LIMITS_UNINSTALLED') : created.installation.guard(execution)) === undefined) { disposeVerdicts() return undefined diff --git a/packages/experimental/liveshare/tests/fork-denial.ts b/packages/experimental/liveshare/tests/fork-denial.ts new file mode 100644 index 0000000000..479d76bcba --- /dev/null +++ b/packages/experimental/liveshare/tests/fork-denial.ts @@ -0,0 +1,28 @@ +/** Matcher for liveshare fork guard refusals. */ +import { expect } from 'vitest' +import type { LiveshareForkDeniedCode } from '../src/host/fork-errors.ts' + +/** + * Match a guard refusal by its reason text and recorded code. + * @param reason - Text the model-facing reason contains, or a pattern it matches. + * @param code - The refusal's recorded code. + * @returns An asymmetric matcher for `toEqual`. + */ +export function denial(reason: string | RegExp, code: LiveshareForkDeniedCode): unknown { + return { + reason: (typeof reason === 'string' ? expect.stringContaining(reason) : expect.stringMatching(reason)) as string, + info: { name: 'LiveshareForkDeniedError', code }, + } +} + +/** + * Match a guard refusal of a path outside the granted workspace. + * @param reason - Text the model-facing reason contains, or a pattern it matches. + * @returns An asymmetric matcher for `toEqual`. + */ +export function outsideDenial(reason: string | RegExp): unknown { + return { + reason: (typeof reason === 'string' ? expect.stringContaining(reason) : expect.stringMatching(reason)) as string, + info: { name: 'FsError', code: 'FS_SANDBOX_DENIED' }, + } +} diff --git a/packages/experimental/liveshare/tests/fork-enforcement-unit.spec.ts b/packages/experimental/liveshare/tests/fork-enforcement-unit.spec.ts index 0f0feb0f36..8f363f6c26 100644 --- a/packages/experimental/liveshare/tests/fork-enforcement-unit.spec.ts +++ b/packages/experimental/liveshare/tests/fork-enforcement-unit.spec.ts @@ -13,6 +13,8 @@ import { preflightForkChild, } from '../src/host/fork-enforcement.ts' import type { ForkEnforcementFailure } from '../src/host/fork-enforcement.ts' +import { denial, outsideDenial } from './fork-denial.ts' +import type { ForkToolDenial } from '../src/host/fork-errors.ts' interface RegisteredTool { readonly name: string @@ -33,7 +35,7 @@ function harness(options: { readonly read?: RegisteredTool; readonly write?: Reg const registered = new Map() if (options.read !== undefined) registered.set(options.read.name, options.read) if (options.write !== undefined) registered.set(options.write.name, options.write) - let guardFunction: ((execution: Record) => string | undefined) | undefined + let guardFunction: ((execution: Record) => ForkToolDenial | undefined) | undefined const tools = { get: vi.fn((name: string) => registered.get(name)), register: vi.fn((definition: RegisteredTool) => { @@ -41,7 +43,7 @@ function harness(options: { readonly read?: RegisteredTool; readonly write?: Reg registered.set(definition.name, definition) return () => { registered.delete(definition.name) } }), - guard: vi.fn((guard: (execution: Record) => string | undefined) => { + guard: vi.fn((guard: (execution: Record) => ForkToolDenial | undefined) => { guardFunction = guard return () => {} }), @@ -112,10 +114,10 @@ describe('confined fork tools', () => { const h = harness({ read }) installForkEnforcement(h.target as never, h.failure) const confined = h.registered.get('read')! - await expect(confined.execute({}, { signal: undefined })).rejects.toThrow('may only use read with the paths') - await expect(confined.execute('not a record', { signal: undefined })).rejects.toThrow('may only use read with the paths') + await expect(confined.execute({}, { signal: undefined })).rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('may only use read with the paths') as string }) + await expect(confined.execute('not a record', { signal: undefined })).rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('may only use read with the paths') as string }) await expect(confined.execute({ file_path: 'outside.txt' }, { signal: undefined })) - .rejects.toThrow('inside the workspace') + .rejects.toMatchObject({ name: 'FsError', code: 'FS_SANDBOX_DENIED', message: expect.stringContaining('inside the workspace') as string }) // The grant itself decides, so a path the fake reports inside succeeds and runs the deployment body. const inside = await confined.execute({ file_path: 'inside.ts' }, { signal: undefined }) expect(inside).toBe('ran') @@ -123,7 +125,7 @@ describe('confined fork tools', () => { h.forks.enforcementInstalled.mockReturnValue(false) await expect(confined.execute({ file_path: 'inside.ts' }, { signal: undefined })) - .rejects.toThrow('no longer holds permission') + .rejects.toMatchObject({ name: 'LiveshareForkDeniedError', code: 'FORK_TOOL_NOT_PERMITTED', message: expect.stringContaining('no longer holds permission') as string }) }) it('refuses a read it could not register and keeps the registration error', () => { @@ -154,15 +156,15 @@ describe('confined fork tools', () => { // The body runs the deployment's own argument checks itself, because it replaces its execution. await expect(edit.execute('not a record', { signal: undefined })) - .rejects.toThrow('replacing non-empty text') - await expect(edit.execute({}, { signal: undefined })).rejects.toThrow('replacing non-empty text') + .rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('replacing non-empty text') as string }) + await expect(edit.execute({}, { signal: undefined })).rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('replacing non-empty text') as string }) await expect(edit.execute({ file_path: 'inside.ts', old_string: '', new_string: 'b' }, { signal: undefined })) - .rejects.toThrow('replacing non-empty text') + .rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('replacing non-empty text') as string }) await expect(edit.execute({ file_path: 'inside.ts', old_string: 'a', new_string: 'a' }, { signal: undefined })) - .rejects.toThrow('replacing non-empty text') + .rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('replacing non-empty text') as string }) // The containment check runs inside the body too, so a target the guard did not see is still refused. await expect(edit.execute({ file_path: '../outside.ts', old_string: 'a', new_string: 'b' }, { signal: undefined })) - .rejects.toThrow('inside the workspace') + .rejects.toMatchObject({ name: 'FsError', code: 'FS_SANDBOX_DENIED', message: expect.stringContaining('inside the workspace') as string }) expect(h.fs.editText).not.toHaveBeenCalled() const result = await edit.execute({ @@ -182,7 +184,7 @@ describe('confined fork tools', () => { h.forks.enforcementInstalled.mockReturnValue(false) await expect(edit.execute({ file_path: 'inside.ts', old_string: 'a', new_string: 'b' }, { signal: undefined })) - .rejects.toThrow('no longer holds permission') + .rejects.toMatchObject({ name: 'LiveshareForkDeniedError', code: 'FORK_TOOL_NOT_PERMITTED', message: expect.stringContaining('no longer holds permission') as string }) }) it('refuses a write-capable child when the deployment ships no write to replace', () => { @@ -209,14 +211,14 @@ describe('confined fork tools', () => { const confined = h.registered.get('write')! await expect(confined.execute({ file_path: 'inside.ts' }, { signal: undefined })) - .rejects.toThrow('named file with text content') + .rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('named file with text content') as string }) await expect(confined.execute('not a record', { signal: undefined })) - .rejects.toThrow('named file with text content') + .rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('named file with text content') as string }) await expect(confined.execute({ file_path: '../outside', content: 'x' }, { signal: undefined })) - .rejects.toThrow('inside the workspace') + .rejects.toMatchObject({ name: 'FsError', code: 'FS_SANDBOX_DENIED', message: expect.stringContaining('inside the workspace') as string }) h.forks.enforcementInstalled.mockReturnValue(false) await expect(confined.execute({ file_path: 'inside.ts', content: 'x' }, { signal: undefined })) - .rejects.toThrow('no longer holds permission') + .rejects.toMatchObject({ name: 'LiveshareForkDeniedError', code: 'FORK_TOOL_NOT_PERMITTED', message: expect.stringContaining('no longer holds permission') as string }) h.forks.enforcementInstalled.mockReturnValue(true) const result = await confined.execute({ file_path: 'inside.ts', content: 'hello' }, { signal: undefined }) @@ -230,18 +232,18 @@ describe('confined fork tools', () => { const h = harness({ read }) installForkEnforcement(h.target as never, h.failure) h.forks.enforcedCeiling.mockReturnValue(READ_ONLY_FORK_CEILING) - const guard = h.guard() as (execution: Record) => string | undefined + const guard = h.guard() as (execution: Record) => ForkToolDenial | undefined expect(guard).toBeDefined() expect(guard?.({ name: 'read', arguments: { file_path: 'inside.ts' }, agent: { id: 'other' } })) - .toContain('without a child session') + .toEqual(denial('without a child session', 'FORK_CHILD_UNKNOWN')) h.target.authorized = () => false expect(guard?.({ name: 'read', arguments: { file_path: 'inside.ts' }, agent: { id: 'child-1' }, token: Symbol('t') })) - .toContain('which this host did not install') + .toEqual(denial('which this host did not install', 'FORK_TOOL_NOT_PERMITTED')) h.target.authorized = () => true expect(guard?.({ name: 'read', arguments: { file_path: 'inside.ts' }, agent: { id: 'child-1' } })) - .toContain('may only read inside the workspace') + .toEqual(outsideDenial('may only read inside the workspace')) // A definition visible from both registries is trusted even though this host did not install it. const visible = harness({ read }) @@ -249,9 +251,9 @@ describe('confined fork tools', () => { visible.forks.enforcedCeiling.mockReturnValue(READ_ONLY_FORK_CEILING) const visibleGuard = visible.guard() expect(visibleGuard?.({ name: 'read', arguments: { file_path: 'inside.ts' }, agent: { id: 'child-1' } })) - .toContain('may only read inside the workspace') + .toEqual(outsideDenial('may only read inside the workspace')) expect(visibleGuard?.({ name: 'write', arguments: {}, agent: { id: 'child-1' } })) - .toContain('may not use write') + .toEqual(denial('may not use write', 'FORK_TOOL_NOT_PERMITTED')) // A tool the ceiling allows but this host did not install is trusted only when both registries // hand back the same definition. @@ -263,9 +265,9 @@ describe('confined fork tools', () => { // The ceiling names grep, but this installation never registered a confined grep for the child: // the name alone does not make the deployment's definition executable. expect(visibleToolGuard?.({ name: 'grep', arguments: { file_path: 'inside.ts' }, agent: { id: 'child-1' } })) - .toContain('which this host did not install') + .toEqual(denial('which this host did not install', 'FORK_TOOL_NOT_PERMITTED')) expect(visibleToolGuard?.({ name: 'ghost', arguments: {}, agent: { id: 'child-1' } })) - .toContain('which this host did not install') + .toEqual(denial('which this host did not install', 'FORK_TOOL_NOT_PERMITTED')) // A verdict produced for this execution authorizes its path. const token = Symbol('verified') @@ -273,7 +275,7 @@ describe('confined fork tools', () => { ((value: Record, next: () => unknown) => Promise) | undefined await preExecute?.({ token, arguments: { file_path: 'inside.ts' }, agent: { id: 'child-1' } }, () => 'next') expect(h.guard()?.({ name: 'read', arguments: { file_path: 'inside.ts' }, agent: { id: 'child-1' }, token })) - .toContain('may only read inside the workspace') + .toEqual(outsideDenial('may only read inside the workspace')) }) it('admits the PTC transport for a fork child while nested calls stay separately judged', () => { @@ -281,13 +283,13 @@ describe('confined fork tools', () => { expect(installForkEnforcement(h.target as never, h.failure)).toBeDefined() h.forks.enforcedCeiling.mockReturnValue(READ_ONLY_FORK_CEILING) h.describe.mockReturnValue({ paths: [], noFileEffect: true }) - const guard = h.guard() as (execution: Record) => string | undefined + const guard = h.guard() as (execution: Record) => ForkToolDenial | undefined // The transport's program runs under the owner's standing policy; the name alone widens no tool. expect(guard({ name: 'run_code', arguments: { code: 'return 1', description: 'run' }, agent: { id: 'child-1' } })) .toBeUndefined() // A nested shell call is a separate execution this same guard refuses. expect(guard({ name: 'bash', arguments: { command: 'ls' }, agent: { id: 'child-1' } })) - .toContain('may not use bash') + .toEqual(denial('may not use bash', 'FORK_TOOL_NOT_PERMITTED')) }) it('refuses a no-effect tool whose visible definition changed after the limit was installed', () => { @@ -297,14 +299,14 @@ describe('confined fork tools', () => { expect(installForkEnforcement(h.target as never, h.failure)).toBeDefined() h.forks.enforcedCeiling.mockReturnValue(READ_ONLY_FORK_CEILING) h.describe.mockReturnValue({ paths: [], noFileEffect: true }) - const guard = h.guard() as (execution: Record) => string | undefined + const guard = h.guard() as (execution: Record) => ForkToolDenial | undefined const call = () => guard({ name: 'todo_write', arguments: {}, agent: { id: 'child-1' } }) // The deployment's own definition is the one the limit vouched for, so the no-effect tool runs. expect(call()).toBeUndefined() // A different definition answering to the same name is not the one this host installed or vouched // for; the name alone is not permission. h.registered.set('todo_write', deploymentTool('todo_write')) - expect(call()).toContain('which this host did not install') + expect(call()).toEqual(denial('which this host did not install', 'FORK_TOOL_NOT_PERMITTED')) }) it('records no verdicts for an execution that names no path', async () => { @@ -461,8 +463,8 @@ describe('source-session sandbox', () => { for (const name of options.tools ?? ['read']) deployments.set(name, deploymentTool(name)) const registered = new Map(deployments) const installed = new Map() - let guardFunction: ((execution: Record) => string | undefined) | undefined - const guard = vi.fn((fn: (execution: Record) => string | undefined) => { + let guardFunction: ((execution: Record) => ForkToolDenial | undefined) | undefined + const guard = vi.fn((fn: (execution: Record) => ForkToolDenial | undefined) => { guardFunction = fn return () => {} }) @@ -538,10 +540,10 @@ describe('source-session sandbox', () => { .map(profile => profile.name).sort(), ) - const guard = h.guardFunction() as (execution: { readonly name: string }) => string | undefined + const guard = h.guardFunction() as (execution: { readonly name: string }) => ForkToolDenial | undefined for (const name of sharedToolNames('view')) expect(guard({ name })).toBeUndefined() for (const name of ['write', 'edit', 'bash', 'pwsh', 'cua', 'plugin_manager', 'schedule_create', 'ghost']) { - expect(guard({ name })).toContain('may not use') + expect(guard({ name })).toEqual(denial('may not use', 'FORK_TOOL_NOT_PERMITTED')) expect(h.installed.has(name)).toBe(false) } }) @@ -550,11 +552,11 @@ describe('source-session sandbox', () => { const h = sourceHarness({ tools: sharedToolNames('view'), writeGate: { mayWrite: () => true } }) const installed = installSourceSessionAccess(h.target as never) expect(installed.readConfined).toBe(true) - const guard = h.guardFunction() as (execution: { readonly name: string; readonly arguments?: unknown }) => string | undefined + const guard = h.guardFunction() as (execution: { readonly name: string; readonly arguments?: unknown }) => ForkToolDenial | undefined // The program itself declares no path; each nested call re-enters this pipeline as its own execution. expect(guard({ name: 'run_code', arguments: { code: 'return 1', description: 'run' } })).toBeUndefined() - expect(guard({ name: 'bash', arguments: { command: 'ls' } })).toContain('may not use bash') - expect(guard({ name: 'ghost', arguments: {} })).toContain('may not use ghost') + expect(guard({ name: 'bash', arguments: { command: 'ls' } })).toEqual(denial('may not use bash', 'FORK_TOOL_NOT_PERMITTED')) + expect(guard({ name: 'ghost', arguments: {} })).toEqual(denial('may not use ghost', 'FORK_TOOL_NOT_PERMITTED')) }) it('resolves each tool’s declared paths and delegates with their canonical form', async () => { @@ -609,7 +611,7 @@ describe('source-session sandbox', () => { ['present', { files: [{ path: 'inside.ts' }, { path: 'outside/secret.txt' }] }], ] for (const [name, args] of outsideCalls) { - await expect(h.call(name, args)).rejects.toThrow('inside the workspace') + await expect(h.call(name, args)).rejects.toMatchObject({ name: 'FsError', code: 'FS_SANDBOX_DENIED', message: expect.stringContaining('inside the workspace') as string }) } const malformed: [string, unknown][] = [ @@ -621,7 +623,7 @@ describe('source-session sandbox', () => { ['present', { files: 'not a list' }], ] for (const [name, args] of malformed) { - await expect(h.call(name, args)).rejects.toThrow('with the paths it declares') + await expect(h.call(name, args)).rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('with the paths it declares') as string }) } // A resolution the filesystem refuses is the refusal: no verdict is guessed from the spelling. @@ -640,9 +642,9 @@ describe('source-session sandbox', () => { // There is no owner bypass: the sandbox belongs to the Session, so every turn reads through it. await expect(confined.execute({ file_path: 'x' }, { signal: undefined })).resolves.toBe('ran') expect(refresh).toHaveBeenCalledTimes(1) - await expect(confined.execute({}, { signal: undefined })).rejects.toThrow('only use read with the paths') - await expect(confined.execute('not a record', { signal: undefined })).rejects.toThrow('only use read with the paths') - await expect(confined.execute({ file_path: 'outside' }, { signal: undefined })).rejects.toThrow('inside the workspace') + await expect(confined.execute({}, { signal: undefined })).rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('only use read with the paths') as string }) + await expect(confined.execute('not a record', { signal: undefined })).rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('only use read with the paths') as string }) + await expect(confined.execute({ file_path: 'outside' }, { signal: undefined })).rejects.toMatchObject({ name: 'FsError', code: 'FS_SANDBOX_DENIED', message: expect.stringContaining('inside the workspace') as string }) await expect(confined.execute({ file_path: 'inside.ts' }, { signal: undefined })).resolves.toBe('ran') // Every call re-reads the grants before it consumes them, including one it then refuses. expect(refresh).toHaveBeenCalledTimes(5) @@ -663,8 +665,8 @@ describe('source-session sandbox', () => { const installed = installSourceSessionAccess(h.target as never) expect(installed).toMatchObject({ readConfined: true, registrationFailure: { tool: 'glob' } }) expect(h.installed.has('glob')).toBe(false) - const guard = h.guardFunction() as (execution: { readonly name: string }) => string | undefined - expect(guard({ name: 'glob' })).toContain('may not use') + const guard = h.guardFunction() as (execution: { readonly name: string }) => ForkToolDenial | undefined + expect(guard({ name: 'glob' })).toEqual(denial('may not use', 'FORK_TOOL_NOT_PERMITTED')) expect(guard({ name: 'grep' })).toBeUndefined() }) @@ -673,8 +675,8 @@ describe('source-session sandbox', () => { installSourceSessionAccess(h.target as never) // Nothing casts the deployment's missing present tool into a permit: the guard only knows registered // names. - const guard = h.guardFunction() as (execution: { readonly name: string }) => string | undefined - expect(guard({ name: 'present' })).toContain('may not use') + const guard = h.guardFunction() as (execution: { readonly name: string }) => ForkToolDenial | undefined + expect(guard({ name: 'present' })).toEqual(denial('may not use', 'FORK_TOOL_NOT_PERMITTED')) expect(h.installed.has('present')).toBe(false) }) @@ -683,19 +685,19 @@ describe('source-session sandbox', () => { expect(installSourceSessionAccess(h.target as never)).toMatchObject({ readConfined: true, writeConfined: true }) const confined = h.installed.get('write')! - await expect(confined.execute({ file_path: 'inside.ts' }, { signal: undefined })).rejects.toThrow('named file with text content') - await expect(confined.execute('not a record', { signal: undefined })).rejects.toThrow('named file with text content') + await expect(confined.execute({ file_path: 'inside.ts' }, { signal: undefined })).rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('named file with text content') as string }) + await expect(confined.execute('not a record', { signal: undefined })).rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('named file with text content') as string }) await expect(confined.execute({ file_path: '../outside', content: 'x' }, { signal: undefined })) - .rejects.toThrow('inside the workspace') + .rejects.toMatchObject({ name: 'FsError', code: 'FS_SANDBOX_DENIED', message: expect.stringContaining('inside the workspace') as string }) const narrowing = sourceHarness({ tools: ['read', 'write'], writeGate: { mayWrite: vi.fn().mockReturnValueOnce(true).mockReturnValue(false) } }) expect(installSourceSessionAccess(narrowing.target as never).writeConfined).toBe(true) await expect(narrowing.installed.get('write')!.execute({ file_path: 'inside.ts', content: 'x' }, { signal: undefined })) - .rejects.toThrow('does not allow writing') + .rejects.toMatchObject({ name: 'LiveshareForkDeniedError', code: 'FORK_TOOL_NOT_PERMITTED', message: expect.stringContaining('does not allow writing') as string }) const blocked = sourceHarness({ tools: ['read', 'write'], writeGate: { mayWrite: () => false } }) installSourceSessionAccess(blocked.target as never) await expect(blocked.installed.get('write')!.execute({ file_path: 'inside.ts', content: 'x' }, { signal: undefined })) - .rejects.toThrow('does not allow writing') + .rejects.toMatchObject({ name: 'LiveshareForkDeniedError', code: 'FORK_TOOL_NOT_PERMITTED', message: expect.stringContaining('does not allow writing') as string }) h.target.write = { mayWrite: () => true } const result = await confined.execute({ file_path: 'inside.ts', content: 'hello' }, { signal: undefined }) @@ -712,15 +714,15 @@ describe('source-session sandbox', () => { const edit = h.installed.get('edit')! await expect(edit.execute({ file_path: 'inside.ts', old_string: '', new_string: 'b' }, { signal: undefined })) - .rejects.toThrow('replacing non-empty text') + .rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('replacing non-empty text') as string }) await expect(edit.execute({ file_path: '', old_string: 'a', new_string: 'b' }, { signal: undefined })) - .rejects.toThrow('replacing non-empty text') + .rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('replacing non-empty text') as string }) await expect(edit.execute({ file_path: 'inside.ts', old_string: 'a', new_string: 'a' }, { signal: undefined })) - .rejects.toThrow('replacing non-empty text') + .rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('replacing non-empty text') as string }) await expect(edit.execute({ file_path: 'inside.ts', old_string: 'a' }, { signal: undefined })) - .rejects.toThrow('replacing non-empty text') + .rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('replacing non-empty text') as string }) await expect(edit.execute({ file_path: 'outside.ts', old_string: 'a', new_string: 'b' }, { signal: undefined })) - .rejects.toThrow('inside the workspace') + .rejects.toMatchObject({ name: 'FsError', code: 'FS_SANDBOX_DENIED', message: expect.stringContaining('inside the workspace') as string }) // The intent comes from the shipped waterfall, and the edit is written under the Session policy. const result = await edit.execute({ file_path: 'inside.ts', old_string: 'old', new_string: 'new', replace_all: true }, { signal: undefined }) expect(result).toEqual({ path: '/granted/inside.ts', before: 'old', after: 'new' }) @@ -741,9 +743,9 @@ describe('source-session sandbox', () => { installSourceSessionAccess(closedEdit.target as never) await expect(closedEdit.installed.get('edit')!.execute({ file_path: 'inside.ts', old_string: 'a', new_string: 'b', - }, { signal: undefined })).rejects.toThrow('does not allow writing') + }, { signal: undefined })).rejects.toMatchObject({ name: 'LiveshareForkDeniedError', code: 'FORK_TOOL_NOT_PERMITTED', message: expect.stringContaining('does not allow writing') as string }) // The replacement's own argument check refuses arguments it cannot read. - await expect(edit.execute('not a record', { signal: undefined })).rejects.toThrow('replacing non-empty text') + await expect(edit.execute('not a record', { signal: undefined })).rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringContaining('replacing non-empty text') as string }) // A share that narrows while the edit intent awaits stops the edit before it reaches the backend. const narrowing = sourceHarness({ @@ -753,7 +755,7 @@ describe('source-session sandbox', () => { installSourceSessionAccess(narrowing.target as never) await expect(narrowing.installed.get('edit')!.execute({ file_path: 'inside.ts', old_string: 'a', new_string: 'b', - }, { signal: undefined })).rejects.toThrow('does not allow writing') + }, { signal: undefined })).rejects.toMatchObject({ name: 'LiveshareForkDeniedError', code: 'FORK_TOOL_NOT_PERMITTED', message: expect.stringContaining('does not allow writing') as string }) expect(narrowing.fs.editText).not.toHaveBeenCalled() }) @@ -772,20 +774,20 @@ describe('source-session sandbox', () => { }) const installed = installSourceSessionAccess(h.target as never) expect(installed).toMatchObject({ readConfined: true, writeConfined: true, registrationFailure: { tool: 'edit' } }) - const guard = h.guardFunction() as (execution: { readonly name: string }) => string | undefined - expect(guard({ name: 'edit' })).toContain('may not use') + const guard = h.guardFunction() as (execution: { readonly name: string }) => ForkToolDenial | undefined + expect(guard({ name: 'edit' })).toEqual(denial('may not use', 'FORK_TOOL_NOT_PERMITTED')) expect(guard({ name: 'write' })).toBeUndefined() }) it('refuses a no-effect tool once another definition answers to its name', () => { const h = sourceHarness({ tools: [...sharedToolNames('view')] }) installSourceSessionAccess(h.target as never) - const guard = h.guardFunction() as (execution: { readonly name: string }) => string | undefined + const guard = h.guardFunction() as (execution: { readonly name: string }) => ForkToolDenial | undefined // The definition the installation found at install time is the one it vouches for. expect(guard({ name: 'todo_write' })).toBeUndefined() // A scope registration that replaces it later is a different tool under a permitted name. h.registered.set('todo_write', deploymentTool('todo_write')) - expect(guard({ name: 'todo_write' })).toContain('may not use') + expect(guard({ name: 'todo_write' })).toEqual(denial('may not use', 'FORK_TOOL_NOT_PERMITTED')) }) it('guards every tool but this installation’s replacements', () => { @@ -793,20 +795,20 @@ describe('source-session sandbox', () => { installSourceSessionAccess(h.target as never) const provider = h.guardFunction() as ((execution: unknown) => unknown) | undefined expect(provider).toBeDefined() - expect(provider?.({ arguments: {} })).toContain('may not use') - expect(provider?.({ arguments: {}, name: 'other' })).toContain('may not use') + expect(provider?.({ arguments: {} })).toEqual(denial('may not use', 'FORK_TOOL_NOT_PERMITTED')) + expect(provider?.({ arguments: {}, name: 'other' })).toEqual(denial('may not use', 'FORK_TOOL_NOT_PERMITTED')) expect(provider?.({ arguments: {}, name: 'read' })).toBeUndefined() // A view Session installs no write or edit name, so the guard refuses the deployment's own. - expect(provider?.({ arguments: {}, name: 'write' })).toContain('may not use') - expect(provider?.({ arguments: {}, name: 'edit' })).toContain('may not use') + expect(provider?.({ arguments: {}, name: 'write' })).toEqual(denial('may not use', 'FORK_TOOL_NOT_PERMITTED')) + expect(provider?.({ arguments: {}, name: 'edit' })).toEqual(denial('may not use', 'FORK_TOOL_NOT_PERMITTED')) // A name the deployment has but this installation did not register is refused: the name is not // evidence that a constrained definition would run. - expect(provider?.({ arguments: {}, name: 'glob' })).toContain('may not use') + expect(provider?.({ arguments: {}, name: 'glob' })).toEqual(denial('may not use', 'FORK_TOOL_NOT_PERMITTED')) const writable = sourceHarness({ tools: ['read', 'write'], writeGate: { mayWrite: () => true } }) installSourceSessionAccess(writable.target as never) const writableGuard = writable.guardFunction() as ((execution: unknown) => unknown) | undefined expect(writableGuard?.({ arguments: {}, name: 'write' })).toBeUndefined() - expect(writableGuard?.({ arguments: {}, name: 'edit' })).toContain('may not use') + expect(writableGuard?.({ arguments: {}, name: 'edit' })).toEqual(denial('may not use', 'FORK_TOOL_NOT_PERMITTED')) }) }) diff --git a/packages/experimental/liveshare/tests/readonly-fork-enforcement-wiring.spec.ts b/packages/experimental/liveshare/tests/readonly-fork-enforcement-wiring.spec.ts index 086f53312f..df54ba3e90 100644 --- a/packages/experimental/liveshare/tests/readonly-fork-enforcement-wiring.spec.ts +++ b/packages/experimental/liveshare/tests/readonly-fork-enforcement-wiring.spec.ts @@ -30,6 +30,8 @@ import { import { ForkRegistry } from '../src/host/fork-registry.ts' import { SHARED_TOOL_PROFILES } from '../src/host/shared-tools.ts' import type { ForkToolExecution } from '../src/host/fork-tool-guard.ts' +import { denial, outsideDenial } from './fork-denial.ts' +import type { ForkToolDenial } from '../src/host/fork-errors.ts' const child = 'child-1' /** The viewer identity the registry recorded for this child. */ @@ -55,14 +57,14 @@ const readDefinition: ToolDefinition = { /** One child context capturing what the wiring registers on it. */ function childContext() { const captured: { - guard?: (execution: ForkToolExecution) => string | undefined + guard?: (execution: ForkToolExecution) => ForkToolDenial | undefined preExecute?: (execution: ForkToolExecution, next: () => Promise) => Promise result?: (execution: ForkToolExecution) => void readonly definitions: Map } = { definitions: new Map() } const ctx = Object.assign(new Context(), { tools: { - guard: (guard: (execution: ForkToolExecution) => string | undefined) => { + guard: (guard: (execution: ForkToolExecution) => ForkToolDenial | undefined) => { captured.guard = guard return () => { delete captured.guard } }, @@ -337,12 +339,12 @@ describe('fork enforcement wiring', () => { agent: { id: child }, token: Symbol('another-execution'), } - expect(captured.guard?.(other)).toMatch(/workspace/u) + expect(captured.guard?.(other)).toEqual(outsideDenial(/workspace/u)) // A path the resolution did not confirm is refused for that same execution. const outside: ForkToolExecution = { ...inside, arguments: { file_path: '/etc/passwd' } } await captured.preExecute?.(outside, () => Promise.resolve({ kind: 'allow' })) - expect(captured.guard?.(outside)).toMatch(/workspace/u) + expect(captured.guard?.(outside)).toEqual(outsideDenial(/workspace/u)) }) it('refuses a child whose scope cannot register the confined read, and keeps the prompt gate closed', async () => { @@ -434,8 +436,8 @@ describe('fork enforcement wiring', () => { // definitions... const call = (name: string) => ({ name, arguments: {}, agent: { id: child }, token: Symbol(name) }) as never - expect(captured.guard?.(call('read'))).toMatch(/may not use/u) - expect(captured.guard?.(call('bash'))).toMatch(/may not use/u) + expect(captured.guard?.(call('read'))).toEqual(denial(/may not use/u, 'FORK_TOOL_NOT_PERMITTED')) + expect(captured.guard?.(call('bash'))).toEqual(denial(/may not use/u, 'FORK_TOOL_NOT_PERMITTED')) // ...and a released layer stops refusing anything. installation.dispose() expect(captured.guard).toBeUndefined() @@ -547,7 +549,7 @@ describe('fork enforcement wiring', () => { // the child running with no limit at all. expect(captured.guard).toBeDefined() expect(captured.guard?.({ name: 'read', arguments: {}, agent: { id: child } })) - .toMatch(/limits are not installed/u) + .toEqual(denial(/limits are not installed/u, 'FORK_LIMITS_UNINSTALLED')) expect(captured.preExecute).toBeUndefined() expect(captured.result).toBeUndefined() expect(forks.enforcementInstalled(child)).toBe(false) diff --git a/packages/experimental/liveshare/tests/readonly-fork-tool-guard.spec.ts b/packages/experimental/liveshare/tests/readonly-fork-tool-guard.spec.ts index e3af0ee83a..8ee08cfd81 100644 --- a/packages/experimental/liveshare/tests/readonly-fork-tool-guard.spec.ts +++ b/packages/experimental/liveshare/tests/readonly-fork-tool-guard.spec.ts @@ -13,6 +13,8 @@ import { type ForkToolExecution, } from '../src/host/fork-tool-guard.ts' import { READ_ONLY_FORK_CEILING, WRITE_FORK_CEILING } from '../src/host/fork-policy.ts' +import { denial, outsideDenial } from './fork-denial.ts' +import { forkToolDenial, type ForkToolDenial } from '../src/host/fork-errors.ts' const child = 'child-1' @@ -127,14 +129,14 @@ describe('fork tool guard', () => { it('replaces the same context’s released guard and keeps calls denied during teardown', async () => { const context = {} - const guards: ((exec: ForkToolExecution) => string | undefined)[] = [] + const guards: ((exec: ForkToolExecution) => ForkToolDenial | undefined)[] = [] let source: ((exec: ForkToolExecution) => Promise) | undefined let installed = false - const duringTeardown: (string | undefined)[] = [] + const duringTeardown: (ForkToolDenial | undefined)[] = [] const call = execution('read', { path: '/granted/a.ts' }) const host = { contextOf: () => context, - registerGuard: (_context: object, guard: (exec: ForkToolExecution) => string | undefined) => { + registerGuard: (_context: object, guard: (exec: ForkToolExecution) => ForkToolDenial | undefined) => { guards.push(guard) return () => { guards.splice(guards.indexOf(guard), 1) } }, @@ -153,7 +155,7 @@ describe('fork tool guard', () => { const dispose = installChildEnforcement({ childSessionId: child, ceiling: READ_ONLY_FORK_CEILING, - guard: exec => installed && verdicts.has(exec) ? undefined : 'missing verdict', + guard: exec => installed && verdicts.has(exec) ? undefined : forkToolDenial('missing verdict', 'FORK_PATHS_UNKNOWN'), verdictSource: async (exec) => { verdicts.add(exec) }, }, host) return () => { verdicts.clear(); dispose?.() } @@ -162,7 +164,7 @@ describe('fork tool guard', () => { await source?.(call) expect(guards[0]?.(call)).toBeUndefined() first() - expect(guards[0]?.(call)).toBeTypeOf('string') + expect(guards[0]?.(call)).toHaveProperty('reason') const second = install() try { await source?.(call) @@ -174,21 +176,21 @@ describe('fork tool guard', () => { second() } expect(installed).toBe(false) - expect(guards[0]?.(call)).toBeTypeOf('string') - expect(duringTeardown.every(reason => typeof reason === 'string')).toBe(true) + expect(guards[0]?.(call)).toHaveProperty('reason') + expect(duringTeardown.every(denied => denied !== undefined)).toBe(true) }) it('keeps a persistent refusal when reinstallation fails and does not share an inherited owner', () => { const parent = {} const nested = Object.create(parent) as object - const guards = new Map string | undefined)[]>() + const guards = new Map ForkToolDenial | undefined)[]>() let available = true - const registrationChecks: (string | undefined)[] = [] + const registrationChecks: (ForkToolDenial | undefined)[] = [] const call = execution('read') const install = (context: object, reason: string) => installChildEnforcement({ childSessionId: child, ceiling: READ_ONLY_FORK_CEILING, - guard: () => reason, + guard: () => forkToolDenial(reason, 'FORK_TOOL_NOT_PERMITTED'), verdictSource: async () => {}, }, { contextOf: () => context, @@ -208,14 +210,14 @@ describe('fork tool guard', () => { const second = install(parent, 'replacement') expect(guards.get(parent)).toHaveLength(1) expect(guards.get(nested)).toHaveLength(1) - expect(guards.get(parent)?.[0]?.(call)).toBe('replacement') - expect(guards.get(nested)?.[0]?.(call)).toBe('nested') + expect(guards.get(parent)?.[0]?.(call)?.reason).toBe('replacement') + expect(guards.get(nested)?.[0]?.(call)?.reason).toBe('nested') first?.() - expect(guards.get(parent)?.[0]?.(call)).toBe('replacement') + expect(guards.get(parent)?.[0]?.(call)?.reason).toBe('replacement') available = false expect(install(parent, 'failed')).toBeUndefined() - expect(guards.get(parent)?.[0]?.(call)).toMatch(/limits are not installed/u) - expect(registrationChecks.slice(2).every(reason => typeof reason === 'string')).toBe(true) + expect(guards.get(parent)?.[0]?.(call)).toEqual(denial(/limits are not installed/u, 'FORK_LIMITS_UNINSTALLED')) + expect(registrationChecks.slice(2).every(denied => denied !== undefined)).toBe(true) second?.() childDispose?.() }) @@ -269,17 +271,17 @@ describe('fork tool guard', () => { const guard = forkToolGuard(host, () => READ_ONLY_FORK_CEILING, describeTool) // The path check runs through the host's resolution, not a prefix comparison in the guard. - expect(guard(execution('read', { path: '/etc/passwd' }))).toMatch(/may only read inside the workspace/u) + expect(guard(execution('read', { path: '/etc/passwd' }))).toEqual(outsideDenial(/may only read inside the workspace/u)) expect(refused).toContain('/etc/passwd') // Acting capabilities are refused before any path is even considered. for (const tool of ['bash', 'pwsh', 'cua', 'plugin_manager', 'schedule_create', 'write', 'edit', 'subagent']) { - expect(guard(execution(tool, { path: '/granted/a.ts' }))).toMatch(/may not use/u) + expect(guard(execution(tool, { path: '/granted/a.ts' }))).toEqual(denial(/may not use/u, 'FORK_TOOL_NOT_PERMITTED')) } // The write ceiling admits the two mutation tools; every other acting capability stays refused. const writeGuard = forkToolGuard(host, () => WRITE_FORK_CEILING, describeTool) expect(writeGuard(execution('write', { path: '/granted/a.ts' }))).toBeUndefined() expect(writeGuard(execution('edit', { path: '/granted/a.ts' }))).toBeUndefined() - expect(writeGuard(execution('bash', { path: '/granted/a.ts' }))).toMatch(/may not use/u) + expect(writeGuard(execution('bash', { path: '/granted/a.ts' }))).toEqual(denial(/may not use/u, 'FORK_TOOL_NOT_PERMITTED')) }) it('refuses a permitted name whose definition is one the child registered for itself', () => { @@ -293,16 +295,16 @@ describe('fork tool guard', () => { // a name-only ceiling would run it here. expect(forkToolGuard(shadowed.ports, () => READ_ONLY_FORK_CEILING, describeTool)( execution('read', { path: '/granted/a.ts' }), - )).toMatch(/which this host did not install/u) + )).toEqual(denial(/which this host did not install/u, 'FORK_TOOL_NOT_PERMITTED')) }) it('refuses while the child’s own limit is not installed, and unattributed calls always', () => { const { ports: host } = ports({ installed: false }) const guard = forkToolGuard(host, () => READ_ONLY_FORK_CEILING, () => ({ paths: [], noFileEffect: true })) - expect(guard(execution('read'))).toMatch(/limits are not installed/u) + expect(guard(execution('read'))).toEqual(denial(/limits are not installed/u, 'FORK_LIMITS_UNINSTALLED')) // A call this guard cannot attribute to a child is not one it can vouch for. - expect(guard({ name: 'read', arguments: {} })).toMatch(/without a child session/u) + expect(guard({ name: 'read', arguments: {} })).toEqual(denial(/without a child session/u, 'FORK_CHILD_UNKNOWN')) }) it('refuses an unparsed or empty path set instead of reading it as "no paths"', () => { @@ -310,14 +312,14 @@ describe('fork tool guard', () => { const guard = forkToolGuard(host, () => READ_ONLY_FORK_CEILING, describeTool) // Neither unparsed arguments nor an empty path set establish that a read has no filesystem effect. - expect(guard(execution('read'))).toMatch(/paths could not be established/u) + expect(guard(execution('read'))).toEqual(denial(/paths could not be established/u, 'FORK_PATHS_UNKNOWN')) const emptyPaths = forkToolGuard(host, () => READ_ONLY_FORK_CEILING, () => ({ paths: [], noFileEffect: false })) - expect(emptyPaths(execution('read'))).toMatch(/filesystem effect could not be established/u) + expect(emptyPaths(execution('read'))).toEqual(denial(/filesystem effect could not be established/u, 'FORK_PATHS_UNKNOWN')) // grep is on the surface, but a pathless call this fixture cannot place establishes no effect either. - expect(guard(execution('grep'))).toMatch(/filesystem effect could not be established/u) + expect(guard(execution('grep'))).toEqual(denial(/filesystem effect could not be established/u, 'FORK_PATHS_UNKNOWN')) // The no-filesystem escape hatch only ever applies to a tool the ceiling permits; the read-only // ceiling permits only read tools, so a tool outside it is refused before paths are considered. - expect(guard(execution('clock'))).toMatch(/may not use/u) + expect(guard(execution('clock'))).toEqual(denial(/may not use/u, 'FORK_TOOL_NOT_PERMITTED')) }) }) diff --git a/packages/experimental/liveshare/tests/share-host-listeners.spec.ts b/packages/experimental/liveshare/tests/share-host-listeners.spec.ts index 8a7068dc34..aa78d1e0d2 100644 --- a/packages/experimental/liveshare/tests/share-host-listeners.spec.ts +++ b/packages/experimental/liveshare/tests/share-host-listeners.spec.ts @@ -12,6 +12,8 @@ import type {} from '../src/index.ts' import type { ForkToolExecution } from '../src/host/fork-tool-guard.ts' import { FakeTunnelWorker } from './tunnel-supervision-fake-worker.ts' import { shareViewerPrincipal } from '../src/host/viewer-principal.ts' +import { denial } from './fork-denial.ts' +import type { ForkToolDenial } from '../src/host/fork-errors.ts' vi.mock('../src/host/tunnel-worker.ts', async () => { const { FakeTunnelWorker: Fake } = await import('./tunnel-supervision-fake-worker.ts') @@ -322,7 +324,7 @@ describe('viewer turn confinement', () => { const mounted = await mount({ state: stateFile({ shares: [stored()] }) }) const root = '/workspace' const registered = new Map() - let guard: ((execution: ForkToolExecution) => string | undefined) | undefined + let guard: ((execution: ForkToolExecution) => ForkToolDenial | undefined) | undefined const read: ToolDefinition = { name: 'read', description: 'a deployment read', parameters: {}, output: { @@ -352,7 +354,7 @@ describe('viewer turn confinement', () => { registered.set(definition.name, definition) return () => { registered.delete(definition.name) } }, - guard: (registeredGuard: (execution: ForkToolExecution) => string | undefined) => { + guard: (registeredGuard: (execution: ForkToolExecution) => ForkToolDenial | undefined) => { guard = registeredGuard return () => { guard = undefined } }, @@ -382,23 +384,23 @@ describe('viewer turn confinement', () => { // A viewer-started turn is confined: the shell is not a name this installation replaced. await expect(runStep(1, [viewerMessage])).resolves.toMatchObject({ kind: 'enter' }) - expect(guard()?.({ name: 'bash', arguments: { command: 'ls' }, agent: live })).toMatch(/may not use bash/u) + expect(guard()?.({ name: 'bash', arguments: { command: 'ls' }, agent: live })).toEqual(denial(/may not use bash/u, 'FORK_TOOL_NOT_PERMITTED')) // The owner's steering input joins that same turn, which stays confined. await expect(runStep(1, [ownerMessage])).resolves.toMatchObject({ kind: 'enter' }) - expect(guard()?.({ name: 'bash', arguments: { command: 'ls' }, agent: live })).toMatch(/may not use bash/u) + expect(guard()?.({ name: 'bash', arguments: { command: 'ls' }, agent: live })).toEqual(denial(/may not use bash/u, 'FORK_TOOL_NOT_PERMITTED')) // The next turn is the owner's: the deployment's own tools run, unchanged by the mounted layer. await expect(runStep(2, [ownerMessage])).resolves.toMatchObject({ kind: 'enter' }) expect(guard()?.({ name: 'bash', arguments: { command: 'ls' }, agent: live })).toBeUndefined() // An execution this host cannot attribute to an Agent is confined rather than escaping the layer. expect(guard()?.({ name: 'bash', arguments: { command: 'ls' }, agent: { id: 42 } })) - .toMatch(/may not use bash/u) + .toEqual(denial(/may not use bash/u, 'FORK_TOOL_NOT_PERMITTED')) // A viewer message in a later step of the owner's running turn narrows that same turn. await expect(runStep(2, [viewerMessage])).resolves.toMatchObject({ kind: 'enter' }) - expect(guard()?.({ name: 'bash', arguments: { command: 'ls' }, agent: live })).toMatch(/may not use bash/u) + expect(guard()?.({ name: 'bash', arguments: { command: 'ls' }, agent: live })).toEqual(denial(/may not use bash/u, 'FORK_TOOL_NOT_PERMITTED')) // A viewer's later turn is confined again. await expect(runStep(3, [viewerMessage])).resolves.toMatchObject({ kind: 'enter' }) - expect(guard()?.({ name: 'bash', arguments: { command: 'ls' }, agent: live })).toMatch(/may not use bash/u) + expect(guard()?.({ name: 'bash', arguments: { command: 'ls' }, agent: live })).toEqual(denial(/may not use bash/u, 'FORK_TOOL_NOT_PERMITTED')) await mounted.ctx.fiber.dispose() }) }) diff --git a/packages/experimental/liveshare/tests/write-current-policy.spec.ts b/packages/experimental/liveshare/tests/write-current-policy.spec.ts index 5068ef180f..9c770c9c44 100644 --- a/packages/experimental/liveshare/tests/write-current-policy.spec.ts +++ b/packages/experimental/liveshare/tests/write-current-policy.spec.ts @@ -256,6 +256,7 @@ describe('LiveShare current write policy', () => { const result = await pending expect(result.isError).toBe(true) expect(text(result)).toContain('does not allow writing this Session') + expect(result.error?.info).toEqual({ name: 'LiveshareForkDeniedError', code: 'FORK_TOOL_NOT_PERMITTED' }) // The final gate asked again after the refresh; trusting the first verdict would have let this write // reach fs.writeText. expect(mayWriteChecks).toBe(2) diff --git a/packages/experimental/liveshare/tsconfig.host.json b/packages/experimental/liveshare/tsconfig.host.json index 193a22ba67..3db1885611 100644 --- a/packages/experimental/liveshare/tsconfig.host.json +++ b/packages/experimental/liveshare/tsconfig.host.json @@ -32,6 +32,9 @@ { "path": "../../session/session-projection" }, { "path": "../liveshare-protocol/tsconfig.host.json" }, { "path": "../../client/modules" }, - { "path": "../../host/frontend-static" } + { "path": "../../host/frontend-static" }, + { + "path": "../../util/error" + } ] } diff --git a/packages/experimental/subagent-oar/README.i18n.yaml b/packages/experimental/subagent-oar/README.i18n.yaml index 73105066a2..3b536bf9b8 100644 --- a/packages/experimental/subagent-oar/README.i18n.yaml +++ b/packages/experimental/subagent-oar/README.i18n.yaml @@ -27,8 +27,8 @@ en: cfc28b43567604a6 zh: 04ef0d698c3b47f7 /deepseek-ai-dsh-experimental-subagent-oar/understand-the-implementation: - en: 19b537fd24aa1dfd - zh: fee12542bb2fc1a6 + en: ba50ae754617fbaf + zh: d808f24ea87fe549 /deepseek-ai-dsh-experimental-subagent-oar/further-exploration: en: 089fe63b9b457247 zh: 482382e68e5c4e2e diff --git a/packages/experimental/subagent-oar/README.md b/packages/experimental/subagent-oar/README.md index f2820bf71a..7a52ac5be6 100644 --- a/packages/experimental/subagent-oar/README.md +++ b/packages/experimental/subagent-oar/README.md @@ -104,7 +104,7 @@ The example mounts two instances of the same provider and the [external delegati The dependency patch applies environment overrides to native installation probes. It permits Claude's explicit `--permission-mode` and suppresses OAR's forced permission bypass when that argument is present. The example passes `--permission-mode dontAsk --permission-prompts none`. Codex receives `-c sandbox_mode="workspace-write"`. OAR sets Codex approval policy to `never`. Neither path forwards native approval requests to a DSH interaction UI. Codex startup failure stops app-server and waits for its exit, including a response without a thread id. -Only root assistant text contributes to the answer. When OAR supplies message ids, the last nonempty message is selected; otherwise root text is concatenated. Native reasoning, tool events, and transcript history do not enter the parent Session. Native history follows the selected runtime's own persistence behavior. Provider errors retain native causes for local debugging; default logs emit only safe stage and category summaries because native causes can contain credentials. +Only root assistant text contributes to the answer. When OAR supplies message ids, the last nonempty message is selected; otherwise root text is concatenated. Native reasoning, tool events, and transcript history do not enter the parent Session. Native history follows the selected runtime's own persistence behavior. Provider errors retain native causes for local debugging; default logs emit only safe stage and category summaries because native causes can contain credentials. Provider failures throw `OarFailure` with a closed `code`: `OAR_INVALID_TASK` for an empty or non-text task, `OAR_RUNTIME_UNAVAILABLE` for a missing, unsupported, or unprobeable runtime, `OAR_START_FAILED` for session startup, and `OAR_DISPOSE_FAILED` for session disposal; `OAR_TURN_FAILED` and `OAR_ABORT_FAILED` classify turn and interruption failures reported to the observer. Cancellation before the run starts rejects with a `DOMException` named `AbortError`, which the tool registry records as `ABORTED`. diff --git a/packages/experimental/subagent-oar/README.zh.md b/packages/experimental/subagent-oar/README.zh.md index 89e6f8405d..8f0d6b9cd5 100644 --- a/packages/experimental/subagent-oar/README.zh.md +++ b/packages/experimental/subagent-oar/README.zh.md @@ -104,7 +104,7 @@ kind: "package-reference" 依赖补丁对原生安装探测应用环境覆盖,并允许 Claude 显式使用 `--permission-mode`,并在存在该参数时关闭 OAR 强制的权限绕过。示例传入 `--permission-mode dontAsk --permission-prompts none`。Codex 接收 `-c sandbox_mode="workspace-write"`。OAR 将 Codex 审批策略设为 `never`。两条路径均不将原生审批请求转发到 DSH 交互界面。Codex 启动失败时会停止 app-server 并等待其退出,包括响应中缺少线程 id 的情况。 -只有根智能体文本参与答复。当 OAR 提供消息 id 时,选择最后一条非空消息;否则拼接根文本。原生推理、工具事件和转录历史不会进入父 Session。原生历史遵循所选运行时自身的持久化行为。提供方错误保留原生原因供本地调试;默认日志仅输出安全的阶段和类别摘要,因为原生原因可能包含凭据。 +只有根智能体文本参与答复。当 OAR 提供消息 id 时,选择最后一条非空消息;否则拼接根文本。原生推理、工具事件和转录历史不会进入父 Session。原生历史遵循所选运行时自身的持久化行为。提供方错误保留原生原因供本地调试;默认日志仅输出安全的阶段和类别摘要,因为原生原因可能包含凭据。提供方失败抛出 `OarFailure`,其 `code` 为封闭集合:任务为空或含非文本内容时为 `OAR_INVALID_TASK`,运行时缺失、不受支持或探测失败时为 `OAR_RUNTIME_UNAVAILABLE`,会话启动失败为 `OAR_START_FAILED`,会话释放失败为 `OAR_DISPOSE_FAILED`;`OAR_TURN_FAILED` 和 `OAR_ABORT_FAILED` 用于分类报告给观察者的轮次失败与中断失败。运行开始前取消时以 name 为 `AbortError` 的 `DOMException` 拒绝,工具注册表将其记为 `ABORTED`。 diff --git a/packages/experimental/subagent-oar/package.json b/packages/experimental/subagent-oar/package.json index a7635e6359..e818e22e7e 100644 --- a/packages/experimental/subagent-oar/package.json +++ b/packages/experimental/subagent-oar/package.json @@ -39,7 +39,8 @@ "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-subagent": "workspace:*", - "@deepseek-ai/dsh-subprocess": "workspace:*" + "@deepseek-ai/dsh-subprocess": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" }, "dependencies": { "@agentclientprotocol/sdk": "^1.4.0", @@ -70,6 +71,7 @@ "@deepseek-ai/dsh-tool-jobs": "workspace:*", "@deepseek-ai/dsh-tools": "workspace:*", "@deepseek-ai/dsh-agent-loop-testkit": "workspace:*", - "@deepseek-ai/dsh-experimental-tool-subagent-oar": "workspace:*" + "@deepseek-ai/dsh-experimental-tool-subagent-oar": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" } } diff --git a/packages/experimental/subagent-oar/src/index.ts b/packages/experimental/subagent-oar/src/index.ts index 3aa63f42fd..6ea224c68e 100644 --- a/packages/experimental/subagent-oar/src/index.ts +++ b/packages/experimental/subagent-oar/src/index.ts @@ -16,6 +16,8 @@ import { import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' import { startOarRun, type OarRunSpec } from './run.ts' +export { OarFailure, type OarFailureCode } from './run.ts' + export const name = 'experimental-subagent-oar' export const inject = ['subagents'] diff --git a/packages/experimental/subagent-oar/src/run.ts b/packages/experimental/subagent-oar/src/run.ts index b695d8f176..0f5584c426 100644 --- a/packages/experimental/subagent-oar/src/run.ts +++ b/packages/experimental/subagent-oar/src/run.ts @@ -16,6 +16,7 @@ import type { } from '@botiverse/oar' import { awaitTurnEnd } from '@botiverse/oar/observe' import { brandString } from '@deepseek-ai/dsh-brand' +import { HarnessError } from '@deepseek-ai/dsh-error' import type { ContentBlock } from '@deepseek-ai/dsh-llm' import type { SessionId } from '@deepseek-ai/dsh-session' import { @@ -49,7 +50,7 @@ export interface OarRunSpec { } type FailureStage = 'installation' | 'startup' | 'turn' | 'abort' | 'dispose' -type FailureCategory = FailureClass | RejectionCode | 'not-found' | 'unsupported' | 'cancelled' | 'timeout' +type FailureCategory = FailureClass | RejectionCode | 'not-found' | 'unsupported' | 'timeout' const failureAdvice: Readonly> = { installation: 'Install and authenticate the selected runtime before retrying.', @@ -59,13 +60,58 @@ const failureAdvice: Readonly> = { dispose: 'The runtime may still be active; check it before starting another task.', } -class OarFailure extends Error { - constructor(readonly stage: FailureStage, readonly category: FailureCategory, options?: ErrorOptions) { - super(`OAR subagent failure (stage: ${stage}; category: ${category}). ${failureAdvice[stage]}`, options) +/** + * Every {@link OarFailure} code: + * - `OAR_INVALID_TASK` — the task is empty or contains a non-text block; send one non-empty text task. + * - `OAR_RUNTIME_UNAVAILABLE` — the selected runtime is unsupported, not installed, or its installation probe failed; + * install and authenticate it before retrying. + * - `OAR_START_FAILED` — the runtime could not open or publish a session; check its installation, authentication, and launch settings. + * - `OAR_TURN_FAILED` — the native turn failed or was rejected; check the runtime and its account before retrying. + * - `OAR_ABORT_FAILED` — the runtime did not accept interruption; session disposal was requested. + * - `OAR_DISPOSE_FAILED` — session disposal failed and the runtime may still be active; check it before starting another task. + */ +export const OAR_FAILURE_CODES = [ + 'OAR_INVALID_TASK', + 'OAR_RUNTIME_UNAVAILABLE', + 'OAR_START_FAILED', + 'OAR_TURN_FAILED', + 'OAR_ABORT_FAILED', + 'OAR_DISPOSE_FAILED', +] as const + +/** One code from {@link OAR_FAILURE_CODES}. */ +export type OarFailureCode = typeof OAR_FAILURE_CODES[number] + +const stageCodes: Readonly> = { + installation: 'OAR_RUNTIME_UNAVAILABLE', + startup: 'OAR_START_FAILED', + turn: 'OAR_TURN_FAILED', + abort: 'OAR_ABORT_FAILED', + dispose: 'OAR_DISPOSE_FAILED', +} + +/** OAR delegation failure carrying a stable {@link OarFailureCode}; native causes stay in `cause` and can contain secrets. */ +export class OarFailure extends HarnessError { + override readonly code: OarFailureCode + + /** + * @param message - safe summary without native detail. + * @param code - failure class. + * @param options - native cause, retained for local debugging. + */ + constructor(message: string, code: OarFailureCode, options?: ErrorOptions) { + super(message, code, options) this.name = 'OarFailure' + this.code = code } } +/** Build the safe stage and category summary for one native failure. */ +function stageFailure(stage: FailureStage, category: FailureCategory, options?: ErrorOptions): OarFailure { + const message = `OAR subagent failure (stage: ${stage}; category: ${category}). ${failureAdvice[stage]}` + return new OarFailure(message, stageCodes[stage], options) +} + function reportFailure(spec: OarRunSpec, error: OarFailure): void { try { spec.onError?.(error, 'error') @@ -78,20 +124,21 @@ function reportFailure(spec: OarRunSpec, error: OarFailure): void { * Validate one text task before opening a native session. * @param prompt - content supplied by the shared subagent service. * @returns the text blocks in their original order, without inserted separators. + * @throws {OarFailure} `OAR_INVALID_TASK` when the task is empty or contains a non-text block. */ export function textTask(prompt: readonly ContentBlock[]): string { if (prompt.length === 0) { - throw new Error('subagent-oar: the one-shot task must contain only text blocks') + throw new OarFailure('subagent-oar: the one-shot task must contain only text blocks', 'OAR_INVALID_TASK') } const texts: string[] = [] for (const block of prompt) { if (block.type !== 'text') { - throw new Error('subagent-oar: the one-shot task must contain only text blocks') + throw new OarFailure('subagent-oar: the one-shot task must contain only text blocks', 'OAR_INVALID_TASK') } texts.push(block.text) } if (texts.every(text => text.trim().length === 0)) { - throw new Error('subagent-oar: the one-shot task must not be empty') + throw new OarFailure('subagent-oar: the one-shot task must not be empty', 'OAR_INVALID_TASK') } return texts.join('') } @@ -101,15 +148,16 @@ function isAborted(signal: AbortSignal): boolean { return signal.aborted } -function cancellationFailure(): OarFailure { - return new OarFailure('startup', 'cancelled') +/** The caller cancelled delegation before the run was published. */ +function cancellationFailure(): DOMException { + return new DOMException('OAR subagent startup was cancelled', 'AbortError') } async function disposeSession(session: Session, spec: OarRunSpec): Promise { try { await session.dispose() } catch (error: unknown) { - const failure = new OarFailure('dispose', 'unknown', { cause: error }) + const failure = stageFailure('dispose', 'unknown', { cause: error }) reportFailure(spec, failure) throw failure } @@ -125,7 +173,7 @@ function completedTurn(outcome: TurnOutcome, output: readonly ContentBlock[]): S return { output, stopReason: 'error', - diagnostic: new OarFailure('turn', outcome.failure).message, + diagnostic: stageFailure('turn', outcome.failure).message, } /* v8 ignore next -- OAR supplies the closed TurnOutcome union; native parsing belongs to its adapters. */ default: return assertNever(outcome) @@ -156,7 +204,7 @@ function publishRun( try { await session.abort() } catch (error: unknown) { - reportFailure(spec, new OarFailure('abort', 'unknown', { cause: error })) + reportFailure(spec, stageFailure('abort', 'unknown', { cause: error })) } } const interrupt = (reason: 'cancelled' | 'timeout'): void => { @@ -191,7 +239,7 @@ function publishRun( return { output: collectOutput(), stopReason: 'error', - diagnostic: new OarFailure('turn', admitted.code).message, + diagnostic: stageFailure('turn', admitted.code).message, } } const outcome = await awaitTurnEnd(session, admitted.seq, inputId) @@ -206,11 +254,11 @@ function publishRun( stopped.promise, ]) } catch (error: unknown) { - throw new OarFailure('turn', 'unknown', { cause: error }) + throw stageFailure('turn', 'unknown', { cause: error }) } }, collectOutput, - collectDiagnostic: () => new OarFailure('turn', 'unknown').message, + collectDiagnostic: () => stageFailure('turn', 'unknown').message, cancelled: () => phase === 'cancelled', onError: spec.onError, signal: request.signal, @@ -252,16 +300,16 @@ export async function startOarRun( try { installation = await spec.runtime.installation?.({ env: oarEnvironment(spec.env) }) } catch (error: unknown) { - const failure = new OarFailure('installation', 'unknown', { cause: error }) + const failure = stageFailure('installation', 'unknown', { cause: error }) reportFailure(spec, failure) throw failure } if (isAborted(request.signal)) throw cancellationFailure() if (installation === undefined || installation.kind === 'unsupported') { - throw new OarFailure('installation', 'unsupported') + throw stageFailure('installation', 'unsupported') } if (installation.kind === 'not_found') { - throw new OarFailure('installation', 'not-found') + throw stageFailure('installation', 'not-found') } let session: Session @@ -275,7 +323,7 @@ export async function startOarRun( }) } catch (error: unknown) { if (isAborted(request.signal)) throw cancellationFailure() - const failure = new OarFailure('startup', 'unknown', { cause: error }) + const failure = stageFailure('startup', 'unknown', { cause: error }) reportFailure(spec, failure) throw failure } @@ -288,7 +336,7 @@ export async function startOarRun( try { run = publishRun(session, prompt, request, spec) } catch (error: unknown) { - const failure = new OarFailure('startup', 'unknown', { cause: error }) + const failure = stageFailure('startup', 'unknown', { cause: error }) reportFailure(spec, failure) await disposeSession(session, spec) throw failure diff --git a/packages/experimental/subagent-oar/tests/subagent-oar.spec.ts b/packages/experimental/subagent-oar/tests/subagent-oar.spec.ts index d58bd44436..f9833ad14f 100644 --- a/packages/experimental/subagent-oar/tests/subagent-oar.spec.ts +++ b/packages/experimental/subagent-oar/tests/subagent-oar.spec.ts @@ -112,7 +112,7 @@ describe('OAR provider composition', () => { const provider = ctx.subagents.getProvider('oar') const run = await provider!.start!(await request()) await expect(run.result).resolves.toMatchObject({ output: [{ type: 'text', text: 'registered answer' }] }) - await expect(run.dispose()).rejects.toThrow('stage: dispose') + await expect(run.dispose()).rejects.toMatchObject({ name: 'OarFailure', code: 'OAR_DISPOSE_FAILED' }) expect(options[0]).toMatchObject({ model: 'native-model', effort: 'high' }) } finally { await ctx.fiber.dispose() @@ -142,9 +142,10 @@ describe('OAR provider composition', () => { describe('OAR task input', () => { it('preserves consecutive text and rejects non-text or blank input', () => { expect(textTask([{ type: 'text', text: 'one' }, { type: 'text', text: 'two' }])).toBe('onetwo') - expect(() => textTask([])).toThrow() - expect(() => textTask([{ type: 'text', text: ' \n ' }])).toThrow() - expect(() => textTask([{ type: 'reasoning', text: 'private' }])).toThrow() + const invalid = { name: 'OarFailure', code: 'OAR_INVALID_TASK' } + expect(() => textTask([])).toThrow(expect.objectContaining(invalid)) + expect(() => textTask([{ type: 'text', text: ' \n ' }])).toThrow(expect.objectContaining(invalid)) + expect(() => textTask([{ type: 'reasoning', text: 'private' }])).toThrow(expect.objectContaining(invalid)) }) it('removes inherited credentials and retains explicit environment deletion', () => { @@ -234,7 +235,7 @@ describe('OAR one-shot execution', () => { const install = vi.fn>() const session = vi.fn(base.session) const runtime: Runtime = { ...base, install, session, installation: async () => ({ kind: 'not_found' }) } - await expect(startOarRun(await request(), spec(runtime))).rejects.toThrow() + await expect(startOarRun(await request(), spec(runtime))).rejects.toMatchObject({ name: 'OarFailure', code: 'OAR_RUNTIME_UNAVAILABLE' }) expect(install).not.toHaveBeenCalled() expect(session).not.toHaveBeenCalled() }) @@ -242,7 +243,7 @@ describe('OAR one-shot execution', () => { it('rejects a runtime with no installation probe', async () => { const base = scriptedRuntime({ turn: () => {} }) const { installation: _installation, ...runtime } = base - await expect(startOarRun(await request(), spec(runtime))).rejects.toThrow() + await expect(startOarRun(await request(), spec(runtime))).rejects.toMatchObject({ name: 'OarFailure', code: 'OAR_RUNTIME_UNAVAILABLE' }) }) it('does not open after cancellation wins installation probing', async () => { @@ -260,7 +261,7 @@ describe('OAR one-shot execution', () => { } const controller = new AbortController() const opening = startOarRun(await request(controller.signal), spec(runtime)) - const rejected = expect(opening).rejects.toThrow() + const rejected = expect(opening).rejects.toMatchObject({ name: 'AbortError' }) await probed.promise controller.abort() release.resolve(undefined) @@ -282,7 +283,7 @@ describe('OAR one-shot execution', () => { } const controller = new AbortController() const opening = startOarRun(await request(controller.signal), spec(runtime)) - const rejected = expect(opening).rejects.toThrow() + const rejected = expect(opening).rejects.toMatchObject({ name: 'AbortError' }) await entered.promise controller.abort() release.resolve(undefined) @@ -295,7 +296,9 @@ describe('OAR one-shot execution', () => { const probe = vi.fn(observed.runtime.installation) const controller = new AbortController() controller.abort() - await expect(startOarRun(await request(controller.signal), spec({ ...observed.runtime, installation: probe }))).rejects.toThrow() + await expect(startOarRun(await request(controller.signal), spec({ ...observed.runtime, installation: probe }))).rejects.toMatchObject({ + name: 'AbortError', + }) expect(probe).not.toHaveBeenCalled() }) @@ -384,7 +387,7 @@ describe('OAR one-shot execution', () => { const run = await startOarRun(await request(), spec(runtime, { onError })) const result = await run.result expect(result.output).toEqual([{ type: 'text', text: 'completed answer' }]) - await expect(run.dispose()).rejects.toThrow('stage: dispose') + await expect(run.dispose()).rejects.toMatchObject({ name: 'OarFailure', code: 'OAR_DISPOSE_FAILED' }) expect(onError).toHaveBeenCalled() }) it('selects the last non-empty identified root message', async () => { @@ -426,7 +429,9 @@ describe('OAR one-shot execution', () => { ...scriptedRuntime({ turn: () => {} }), installation: async () => { throw cause }, } - await expect(startOarRun(await request(), spec(runtime, { onError }))).rejects.toMatchObject({ cause }) + await expect(startOarRun(await request(), spec(runtime, { onError }))).rejects.toMatchObject({ + name: 'OarFailure', code: 'OAR_RUNTIME_UNAVAILABLE', cause, + }) expect(onError).toHaveBeenCalledOnce() expect(onError.mock.calls[0]?.[0].message).toContain('stage: installation; category: unknown') expect(onError.mock.calls[0]?.[0].cause).toBe(cause) @@ -437,12 +442,16 @@ describe('OAR one-shot execution', () => { const controller = new AbortController() const base = scriptedRuntime({ turn: () => {} }) const runtime: Runtime = { ...base, session: async () => { throw new Error('PRIVATE_START_DETAIL') } } - await expect(startOarRun(await request(), spec(runtime, { effort: 'high' }))).rejects.toThrow('stage: startup; category: unknown') + await expect(startOarRun(await request(), spec(runtime, { effort: 'high' }))).rejects.toMatchObject({ + name: 'OarFailure', code: 'OAR_START_FAILED', message: expect.stringContaining('stage: startup; category: unknown') as string, + }) const canceled: Runtime = { ...base, session: async () => { controller.abort() throw new Error('PRIVATE_START_DETAIL') } } - await expect(startOarRun(await request(controller.signal), spec(canceled))).rejects.toThrow('category: cancelled') + await expect(startOarRun(await request(controller.signal), spec(canceled))).rejects.toMatchObject({ + name: 'AbortError', + }) }) it('cleans an opened session when event subscription fails', async () => { @@ -516,7 +525,9 @@ describe('OAR one-shot execution', () => { return unsubscribe } } } } - await expect(startOarRun(await request(controller.signal), spec(runtime))).rejects.toThrow('category: cancelled') + await expect(startOarRun(await request(controller.signal), spec(runtime))).rejects.toMatchObject({ + name: 'AbortError', + }) expect(observed.dispose).toHaveBeenCalledOnce() }) @@ -538,7 +549,7 @@ describe('OAR one-shot execution', () => { await active.promise controller.abort() await expect(run.result).resolves.toMatchObject({ stopReason: 'aborted' }) - await expect(run.dispose()).rejects.toThrow('stage: dispose') + await expect(run.dispose()).rejects.toMatchObject({ name: 'OarFailure', code: 'OAR_DISPOSE_FAILED' }) }) }) diff --git a/packages/experimental/subagent-oar/tsconfig.json b/packages/experimental/subagent-oar/tsconfig.json index 1b419fb0ca..7476070bbb 100644 --- a/packages/experimental/subagent-oar/tsconfig.json +++ b/packages/experimental/subagent-oar/tsconfig.json @@ -37,6 +37,9 @@ }, { "path": "../../subprocess/subprocess" + }, + { + "path": "../../util/error" } ] } diff --git a/packages/experimental/tool-ralph/README.i18n.yaml b/packages/experimental/tool-ralph/README.i18n.yaml index b3f96e6e46..7cfcc7b211 100644 --- a/packages/experimental/tool-ralph/README.i18n.yaml +++ b/packages/experimental/tool-ralph/README.i18n.yaml @@ -18,8 +18,8 @@ en: 13380e1170c6a3b5 zh: 2f2665f2ee5ff6f7 /deepseek-ai-dsh-tool-ralph/use-this-package/calling-the-tool: - en: f43e8fbcf272ac45 - zh: 46719b415d9ad4bf + en: 577c4a894c1edf7a + zh: 48d401ba4c6769b9 /deepseek-ai-dsh-tool-ralph/use-this-package/what-each-round-sees: en: 2d8b861c4bcb9424 zh: 63c7b2d00c324727 diff --git a/packages/experimental/tool-ralph/README.md b/packages/experimental/tool-ralph/README.md index 0a9d944525..65acbde9ff 100644 --- a/packages/experimental/tool-ralph/README.md +++ b/packages/experimental/tool-ralph/README.md @@ -29,7 +29,7 @@ The `ralph` tool runs a fixed foreground loop: one fresh child per round works o ### Calling the tool -The model submits `{ objective, maxRounds? }` and the call blocks until the whole run settles. The deployment config's `maxRounds` is both the default and a ceiling on a call override. The terminal result is `complete`, `blocked`, or `budget-limited`, carrying the last bounded report and the number of rounds started; an ordinary child failure returns an error naming the failed round and retaining the last successful handoff when one exists. +The model submits `{ objective, maxRounds? }` and the call blocks until the whole run settles. The deployment config's `maxRounds` is both the default and a ceiling on a call override. The terminal result is `complete`, `blocked`, or `budget-limited`, carrying the last bounded report and the number of rounds started; an ordinary child failure returns an error naming the failed round and retaining the last successful handoff when one exists. Failures carry `RalphError` with a closed code: `RALPH_ROUND_FAILED` for a child round that ends without a structured report, `RALPH_WORKFLOW_FAILED` for a workflow that errors or is cancelled by something other than the caller, including a child report that fails validation inside the workflow because the workflow returns its errors only as text, `RALPH_INVALID_RESULT` for a malformed workflow value, and `RALPH_PROVIDER_UNAVAILABLE` or `RALPH_PROVIDER_UNSUPPORTED` for a provider route violation. An empty objective or an out-of-range `maxRounds` is a `ToolArgsError`, and caller cancellation is an `AbortError`. ### What each round sees diff --git a/packages/experimental/tool-ralph/README.zh.md b/packages/experimental/tool-ralph/README.zh.md index 8eedae966c..4660e2d919 100644 --- a/packages/experimental/tool-ralph/README.zh.md +++ b/packages/experimental/tool-ralph/README.zh.md @@ -29,7 +29,7 @@ kind: "package-reference" ### 调用工具 -模型提交 `{ objective, maxRounds? }`,调用会阻塞到整个运行结算。部署配置中的 `maxRounds` 既是默认值,也是调用覆盖值的上限。终态结果为 `complete`、`blocked` 或 `budget-limited`,携带最后一份有界报告与已启动的 Round 数量;普通子 agent 失败会返回错误,其中标明失败的 Round,并在存在时保留上一次成功交接。 +模型提交 `{ objective, maxRounds? }`,调用会阻塞到整个运行结算。部署配置中的 `maxRounds` 既是默认值,也是调用覆盖值的上限。终态结果为 `complete`、`blocked` 或 `budget-limited`,携带最后一份有界报告与已启动的 Round 数量;普通子 agent 失败会返回错误,其中标明失败的 Round,并在存在时保留上一次成功交接。失败携带 `RalphError`,其 code 为封闭集合:子 agent Round 结束时没有结构化报告为 `RALPH_ROUND_FAILED`,workflow 出错或被调用方以外的原因取消为 `RALPH_WORKFLOW_FAILED`,其中包括在 workflow 内校验失败的子 agent 报告,因为 workflow 只以文本返回错误,workflow 返回值格式错误为 `RALPH_INVALID_RESULT`,提供方路由不符合要求为 `RALPH_PROVIDER_UNAVAILABLE` 或 `RALPH_PROVIDER_UNSUPPORTED`。空目标或超出范围的 `maxRounds` 是 `ToolArgsError`,调用方取消是 `AbortError`。 ### 每个 Round 看到什么 diff --git a/packages/experimental/tool-ralph/package.json b/packages/experimental/tool-ralph/package.json index cbf3c019a4..22b68dee09 100644 --- a/packages/experimental/tool-ralph/package.json +++ b/packages/experimental/tool-ralph/package.json @@ -38,7 +38,8 @@ "@deepseek-ai/dsh-system-prompt": "workspace:*", "@deepseek-ai/dsh-tools": "workspace:*", "@deepseek-ai/dsh-workflow": "workspace:*", - "@deepseek-ai/cordis": "workspace:~" + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-error": "workspace:*" }, "dependencies": { "@deepseek-ai/schemastery": "workspace:~" @@ -61,6 +62,7 @@ "@deepseek-ai/dsh-workflow": "workspace:*", "@deepseek-ai/dsh-workflow-ptc": "workspace:*", "@deepseek-ai/cordis": "workspace:~", - "@deepseek-ai/dsh-session-projection": "workspace:*" + "@deepseek-ai/dsh-session-projection": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" } } diff --git a/packages/experimental/tool-ralph/src/error.ts b/packages/experimental/tool-ralph/src/error.ts new file mode 100644 index 0000000000..5b0b1cb10e --- /dev/null +++ b/packages/experimental/tool-ralph/src/error.ts @@ -0,0 +1,39 @@ +/** Machine-routable Ralph loop failures. @module */ + +import { HarnessError } from '@deepseek-ai/dsh-error' + +/** + * Every {@link RalphError} code: + * - `RALPH_PROVIDER_UNAVAILABLE` — the configured subagent provider is not registered; load it or change `subagentProvider`. + * - `RALPH_PROVIDER_UNSUPPORTED` — the configured provider lacks structured output or inherits parent context; + * configure a fresh structured-output provider. + * - `RALPH_WORKFLOW_FAILED` — the fixed workflow ended with an error or was cancelled without caller cancellation; report the message. + * - `RALPH_INVALID_RESULT` — the fixed workflow returned a malformed report or terminal value; do not trust the result. + * - `RALPH_ROUND_FAILED` — a round's child failed before producing a structured report; the message carries the last handoff. + */ +export const RALPH_ERROR_CODES = [ + 'RALPH_PROVIDER_UNAVAILABLE', + 'RALPH_PROVIDER_UNSUPPORTED', + 'RALPH_WORKFLOW_FAILED', + 'RALPH_INVALID_RESULT', + 'RALPH_ROUND_FAILED', +] as const + +/** One code from {@link RALPH_ERROR_CODES}. */ +export type RalphErrorCode = typeof RALPH_ERROR_CODES[number] + +/** Ralph loop failure carrying a stable {@link RalphErrorCode}. */ +export class RalphError extends HarnessError { + override readonly code: RalphErrorCode + + /** + * @param message - parent-facing failure text. + * @param code - failure class. + * @param options - standard `cause` chaining. + */ + constructor(message: string, code: RalphErrorCode, options?: ErrorOptions) { + super(message, code, options) + this.name = 'RalphError' + this.code = code + } +} diff --git a/packages/experimental/tool-ralph/src/index.ts b/packages/experimental/tool-ralph/src/index.ts index 48708c12ca..aeef0b6d18 100644 --- a/packages/experimental/tool-ralph/src/index.ts +++ b/packages/experimental/tool-ralph/src/index.ts @@ -10,13 +10,16 @@ import z from '@deepseek-ai/schemastery' import type { ContentBlock } from '@deepseek-ai/dsh-llm' import type { JsonValue } from '@deepseek-ai/dsh-util-values' import type { SubagentProvider } from '@deepseek-ai/dsh-subagent' -import { defineTool } from '@deepseek-ai/dsh-tools' +import { defineTool, ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import type { ToolCallView, ToolResultView } from '@deepseek-ai/dsh-tools' import type { WorkflowResult, WorkflowRun } from '@deepseek-ai/dsh-workflow' +import { RalphError } from './error.ts' export const name = 'tool-ralph' export const inject = ['tools', 'workflowEngine', 'subagents', 'systemPrompt'] +export { RalphError, type RalphErrorCode } from './error.ts' + /** Deployment policy for the fixed Ralph workflow. */ export interface Config { /** Fresh structured-output provider used for every round (default `spawn`). */ @@ -206,10 +209,10 @@ function resolveConfig(config: Config): ResolvedConfig { function resolveMaxRounds(requested: number | undefined, ceiling: number): number { const value = requested ?? ceiling if (!Number.isSafeInteger(value) || value < 1) { - throw new TypeError('Ralph maxRounds must be a positive safe integer') + throw new ToolArgsError(['Ralph maxRounds must be a positive safe integer']) } if (value > ceiling) { - throw new TypeError(`Ralph maxRounds ${value} exceeds the deployment ceiling ${ceiling}`) + throw new ToolArgsError([`Ralph maxRounds ${value} exceeds the deployment ceiling ${ceiling}`]) } return value } @@ -218,13 +221,13 @@ function resolveMaxRounds(requested: number | undefined, ceiling: number): numbe function requireFreshProvider(ctx: Context, name: string): SubagentProvider { const provider = ctx.subagents.getProvider(name) if (provider === undefined) { - throw new Error(`Ralph subagent provider "${name}" is not registered`) + throw new RalphError(`Ralph subagent provider "${name}" is not registered`, 'RALPH_PROVIDER_UNAVAILABLE') } if (!provider.capabilities.outputSchema) { - throw new Error(`Ralph subagent provider "${name}" does not support structured output`) + throw new RalphError(`Ralph subagent provider "${name}" does not support structured output`, 'RALPH_PROVIDER_UNSUPPORTED') } if (provider.inheritsParentContext) { - throw new Error(`Ralph subagent provider "${name}" inherits parent context; Ralph requires a fresh provider`) + throw new RalphError(`Ralph subagent provider "${name}" inherits parent context; Ralph requires a fresh provider`, 'RALPH_PROVIDER_UNSUPPORTED') } return provider } @@ -251,7 +254,7 @@ function readReport(value: unknown, expectedStatus: RalphRoundStatus, maxChars: || !normalizedList(value['nextSteps']) || typeof value['blocker'] !== 'string' || value['blocker'] !== value['blocker'].trim()) { - throw new Error('Ralph workflow returned a malformed round report') + throw new RalphError('Ralph workflow returned a malformed round report', 'RALPH_INVALID_RESULT') } const report: RalphRoundReport = { status: expectedStatus, @@ -261,18 +264,18 @@ function readReport(value: unknown, expectedStatus: RalphRoundStatus, maxChars: blocker: value['blocker'], } if (expectedStatus === 'continue' && (report.nextSteps.length === 0 || report.blocker !== '')) { - throw new Error('Ralph workflow returned an invalid continuing report') + throw new RalphError('Ralph workflow returned an invalid continuing report', 'RALPH_INVALID_RESULT') } if (expectedStatus === 'complete' && (report.evidence.length === 0 || report.nextSteps.length !== 0 || report.blocker !== '')) { - throw new Error('Ralph workflow returned an invalid completion report') + throw new RalphError('Ralph workflow returned an invalid completion report', 'RALPH_INVALID_RESULT') } if (expectedStatus === 'blocked' && !normalizedText(report.blocker)) { - throw new Error('Ralph workflow returned an invalid blocked report') + throw new RalphError('Ralph workflow returned an invalid blocked report', 'RALPH_INVALID_RESULT') } const chars = JSON.stringify(report).length if (chars > maxChars) { - throw new Error(`Ralph workflow returned an oversized handoff (${chars} > ${maxChars})`) + throw new RalphError(`Ralph workflow returned an oversized handoff (${chars} > ${maxChars})`, 'RALPH_INVALID_RESULT') } return report } @@ -284,40 +287,40 @@ function readRunResult(value: unknown, maxRounds: number, maxHandoffChars: numbe || !Number.isSafeInteger(value['roundsStarted']) || value['roundsStarted'] < 1 || value['roundsStarted'] > maxRounds) { - throw new Error('Ralph workflow returned a malformed terminal result') + throw new RalphError('Ralph workflow returned a malformed terminal result', 'RALPH_INVALID_RESULT') } const roundsStarted = value['roundsStarted'] switch (value['status']) { case 'complete': if (Object.keys(value).sort().join(',') !== 'report,roundsStarted,status') { - throw new Error('Ralph workflow returned a malformed terminal result') + throw new RalphError('Ralph workflow returned a malformed terminal result', 'RALPH_INVALID_RESULT') } return { status: 'complete', roundsStarted, report: readReport(value['report'], 'complete', maxHandoffChars) } case 'blocked': if (Object.keys(value).sort().join(',') !== 'report,roundsStarted,status') { - throw new Error('Ralph workflow returned a malformed terminal result') + throw new RalphError('Ralph workflow returned a malformed terminal result', 'RALPH_INVALID_RESULT') } return { status: 'blocked', roundsStarted, report: readReport(value['report'], 'blocked', maxHandoffChars) } case 'budget-limited': if (Object.keys(value).sort().join(',') !== 'report,roundsStarted,status') { - throw new Error('Ralph workflow returned a malformed terminal result') + throw new RalphError('Ralph workflow returned a malformed terminal result', 'RALPH_INVALID_RESULT') } if (roundsStarted !== maxRounds) { - throw new Error('Ralph workflow returned budget-limited before the round limit') + throw new RalphError('Ralph workflow returned budget-limited before the round limit', 'RALPH_INVALID_RESULT') } return { status: 'budget-limited', roundsStarted, report: readReport(value['report'], 'continue', maxHandoffChars) } case 'round-failed': { if (Object.keys(value).sort().join(',') !== 'lastReport,roundsStarted,status') { - throw new Error('Ralph workflow returned a malformed terminal result') + throw new RalphError('Ralph workflow returned a malformed terminal result', 'RALPH_INVALID_RESULT') } if (roundsStarted === 1) { if (value['lastReport'] !== null) { - throw new Error('Ralph workflow returned an invalid first-round failure') + throw new RalphError('Ralph workflow returned an invalid first-round failure', 'RALPH_INVALID_RESULT') } return { status: 'round-failed', roundsStarted } } if (value['lastReport'] === null) { - throw new Error('Ralph workflow returned a round failure without its last handoff') + throw new RalphError('Ralph workflow returned a round failure without its last handoff', 'RALPH_INVALID_RESULT') } return { status: 'round-failed', @@ -326,7 +329,7 @@ function readRunResult(value: unknown, maxRounds: number, maxHandoffChars: numbe } } default: - throw new Error('Ralph workflow returned an unknown terminal status') + throw new RalphError('Ralph workflow returned an unknown terminal status', 'RALPH_INVALID_RESULT') } } @@ -346,6 +349,11 @@ function stopReasonError(result: WorkflowResult): string | undefined { } } +/** The cancellation for a workflow the caller cancelled; the tool registry records it as `ABORTED`. */ +function ralphAborted(message: string): DOMException { + return new DOMException(message, 'AbortError') +} + const TRUNCATION_NOTICE = '\n… [truncated]' /** Bound complete parent-facing text, including its envelope and truncation marker. */ @@ -435,10 +443,10 @@ export function apply(ctx: Context, config: Config): void { async execute(args, exec) { const parent = exec.agent if (parent === undefined) { - throw new Error('Ralph tool requires a calling agent (exec.agent was undefined)') + throw new ToolContextUnavailableError('Ralph tool requires a calling agent (exec.agent was undefined)') } const objective = args.objective.trim() - if (objective.length === 0) throw new Error('Ralph objective must be a non-empty string') + if (objective.length === 0) throw new ToolArgsError(['Ralph objective must be a non-empty string']) const maxRounds = resolveMaxRounds(args.maxRounds, resolved.maxRounds) void requireFreshProvider(ctx, resolved.subagentProvider) @@ -458,9 +466,9 @@ export function apply(ctx: Context, config: Config): void { try { const settled = await run.result const error = stopReasonError(settled) - if (error !== undefined) throw new Error(error) + if (error !== undefined) throw settled.stopReason === 'cancelled' && exec.signal.aborted ? ralphAborted(error) : new RalphError(error, 'RALPH_WORKFLOW_FAILED') const value = readRunResult(settled.value, maxRounds, resolved.maxHandoffChars) - if (value.status === 'round-failed') throw new Error(renderRoundFailure(value, resolved.maxResultChars)) + if (value.status === 'round-failed') throw new RalphError(renderRoundFailure(value, resolved.maxResultChars), 'RALPH_ROUND_FAILED') return { runId: run.id, agentsStarted: settled.agentsStarted, diff --git a/packages/experimental/tool-ralph/tests/integration.spec.ts b/packages/experimental/tool-ralph/tests/integration.spec.ts index 5e52cc7104..44f873b6b0 100644 --- a/packages/experimental/tool-ralph/tests/integration.spec.ts +++ b/packages/experimental/tool-ralph/tests/integration.spec.ts @@ -284,6 +284,7 @@ describe('dsh-tool-ralph over the real spawn and sandboxed PTC stack', () => { const result = await pending expect(result.isError).toBe(true) expect((result.content[0] as { text: string }).text).toContain('Ralph workflow was cancelled') + expect(result.isError && result.error.info).toEqual({ name: 'AbortError', code: 'ABORTED' }) expect(outcomes).toEqual(['cancelled']) expect(ctx.agents.get(children[0]!.id)).toBeUndefined() } finally { diff --git a/packages/experimental/tool-ralph/tests/tool-ralph.spec.ts b/packages/experimental/tool-ralph/tests/tool-ralph.spec.ts index d4d8651983..783d7b341c 100644 --- a/packages/experimental/tool-ralph/tests/tool-ralph.spec.ts +++ b/packages/experimental/tool-ralph/tests/tool-ralph.spec.ts @@ -238,6 +238,7 @@ describe('dsh-tool-ralph', () => { expect(firstResult.isError).toBe(true) expect((firstResult.content[0] as { text: string }).text).toContain('Ralph round 1 child failed') expect((firstResult.content[0] as { text: string }).text).toContain('No previous handoff was available.') + expect(firstResult.error?.info).toEqual({ name: 'RalphError', code: 'RALPH_ROUND_FAILED' }) const later = execute(ctx, { objective: 'Ship it.', maxRounds: 2 }, { agent: parent }) await vi.waitFor(() => { expect(engine.requests).toHaveLength(2) }) @@ -256,8 +257,10 @@ describe('dsh-tool-ralph', () => { const failed = execute(ctx, { objective: 'Work.' }, { agent: parent }) await vi.waitFor(() => { expect(engine.requests).toHaveLength(1) }) engine.settle({ value: null, stopReason: 'error', error: 'child report malformed', agentsStarted: 1 }) - expect(((await failed).content[0] as { text: string }).text) + const failedResult = await failed + expect((failedResult.content[0] as { text: string }).text) .toContain('Ralph workflow failed: child report malformed') + expect(failedResult.error?.info).toEqual({ name: 'RalphError', code: 'RALPH_WORKFLOW_FAILED' }) const unknown = execute(ctx, { objective: 'Work.' }, { agent: parent }) await vi.waitFor(() => { expect(engine.requests).toHaveLength(2) }) @@ -267,7 +270,9 @@ describe('dsh-tool-ralph', () => { const cancelled = execute(ctx, { objective: 'Work.' }, { agent: parent }) await vi.waitFor(() => { expect(engine.requests).toHaveLength(3) }) engine.settle({ value: null, stopReason: 'cancelled', error: 'user stopped', agentsStarted: 0 }) - expect(((await cancelled).content[0] as { text: string }).text).toContain('cancelled (user stopped)') + const cancelledResult = await cancelled + expect((cancelledResult.content[0] as { text: string }).text).toContain('cancelled (user stopped)') + expect(cancelledResult.error?.info).toEqual({ name: 'RalphError', code: 'RALPH_WORKFLOW_FAILED' }) const bare = execute(ctx, { objective: 'Work.' }, { agent: parent }) await vi.waitFor(() => { expect(engine.requests).toHaveLength(4) }) @@ -282,7 +287,10 @@ describe('dsh-tool-ralph', () => { const pending = execute(ctx, { objective: 'Work.' }, { agent: parent, signal: controller.signal }) await vi.waitFor(() => { expect(engine.requests).toHaveLength(1) }) controller.abort() - expect((await pending).isError).toBe(true) + const aborted = await pending + expect(aborted.isError).toBe(true) + expect(aborted.error?.info).toEqual({ name: 'AbortError', code: 'ABORTED' }) + expect((aborted.content[0] as { text: string }).text).toContain('Ralph workflow was cancelled (parent step aborted)') const already = new AbortController() already.abort() @@ -308,11 +316,17 @@ describe('dsh-tool-ralph', () => { it('rejects absent authority, empty objectives, bad round caps, and schema-invalid calls before start', async () => { const { ctx, engine, parent } = await setup({ config: { maxRounds: 3 } }) - expect((await execute(ctx, { objective: 'Work.' })).isError).toBe(true) - expect((await execute(ctx, { objective: ' ' }, { agent: parent })).isError).toBe(true) - for (const maxRounds of [0, 1.5, Number.NaN, 4]) { - expect((await execute(ctx, { objective: 'Work.', maxRounds }, { agent: parent })).isError).toBe(true) + expect((await execute(ctx, { objective: 'Work.' })).error?.info) + .toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) + expect((await execute(ctx, { objective: ' ' }, { agent: parent })).error?.info).toEqual({ + name: 'ToolArgsError', code: 'INVALID_ARGS', + }) + for (const maxRounds of [0, 1.5, 4]) { + expect((await execute(ctx, { objective: 'Work.', maxRounds }, { agent: parent })).error?.info).toEqual({ + name: 'ToolArgsError', code: 'INVALID_ARGS', + }) } + expect((await execute(ctx, { objective: 'Work.', maxRounds: Number.NaN }, { agent: parent })).isError).toBe(true) const missing = await execute(ctx, {}, { agent: parent }) expect(missing.error?.info?.code).toBe('INVALID_ARGS') expect(engine.requests).toHaveLength(0) @@ -320,17 +334,20 @@ describe('dsh-tool-ralph', () => { it('rejects missing, unstructured, and parent-context-inheriting provider routes', async () => { const missing = await setup({ provider: false }) - expect(((await execute(missing.ctx, { objective: 'Work.' }, { agent: missing.parent })).content[0] as { text: string }).text) - .toContain('is not registered') + const missingResult = await execute(missing.ctx, { objective: 'Work.' }, { agent: missing.parent }) + expect((missingResult.content[0] as { text: string }).text).toContain('is not registered') + expect(missingResult.error?.info).toEqual({ name: 'RalphError', code: 'RALPH_PROVIDER_UNAVAILABLE' }) expect(missing.engine.requests).toHaveLength(0) const unstructured = await setup({ provider: new StubProvider({ outputSchema: false }) }) - expect(((await execute(unstructured.ctx, { objective: 'Work.' }, { agent: unstructured.parent })).content[0] as { text: string }).text) - .toContain('does not support structured output') + const unstructuredResult = await execute(unstructured.ctx, { objective: 'Work.' }, { agent: unstructured.parent }) + expect((unstructuredResult.content[0] as { text: string }).text).toContain('does not support structured output') + expect(unstructuredResult.error?.info).toEqual({ name: 'RalphError', code: 'RALPH_PROVIDER_UNSUPPORTED' }) const inherited = await setup({ provider: new StubProvider({ inheritsParentContext: true }) }) - expect(((await execute(inherited.ctx, { objective: 'Work.' }, { agent: inherited.parent })).content[0] as { text: string }).text) - .toContain('inherits parent context') + const inheritedResult = await execute(inherited.ctx, { objective: 'Work.' }, { agent: inherited.parent }) + expect((inheritedResult.content[0] as { text: string }).text).toContain('inherits parent context') + expect(inheritedResult.error?.info).toEqual({ name: 'RalphError', code: 'RALPH_PROVIDER_UNSUPPORTED' }) }) it('rejects invalid direct-apply config before touching injected services', () => { @@ -372,6 +389,7 @@ describe('dsh-tool-ralph', () => { ) expect(result.isError).toBe(true) expect((result.content[0] as { text: string }).text).toContain(testCase.message) + expect(result.error?.info).toEqual({ name: 'RalphError', code: 'RALPH_INVALID_RESULT' }) } }) diff --git a/packages/experimental/tool-ralph/tsconfig.json b/packages/experimental/tool-ralph/tsconfig.json index 77ebc9e761..148e3f53b6 100644 --- a/packages/experimental/tool-ralph/tsconfig.json +++ b/packages/experimental/tool-ralph/tsconfig.json @@ -34,6 +34,9 @@ }, { "path": "../../workflow/workflow" + }, + { + "path": "../../util/error" } ] } diff --git a/packages/experimental/tool-subagent-oar/src/index.ts b/packages/experimental/tool-subagent-oar/src/index.ts index aab8ac7266..f3eb638958 100644 --- a/packages/experimental/tool-subagent-oar/src/index.ts +++ b/packages/experimental/tool-subagent-oar/src/index.ts @@ -2,8 +2,8 @@ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' -import { defineTool } from '@deepseek-ai/dsh-tools' -import type {} from '@deepseek-ai/dsh-subagent' +import { defineTool, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' +import { SubagentError } from '@deepseek-ai/dsh-subagent' export const name = 'experimental-tool-subagent-oar' export const inject = ['tools', 'subagents'] @@ -84,12 +84,12 @@ export function apply(ctx: Context, config: Config): void { isConcurrencySafe: () => true, async execute(args, exec) { const parent = exec.agent - if (parent === undefined) throw new Error('subagent_oar requires a calling agent') + if (parent === undefined) throw new ToolContextUnavailableError('subagent_oar requires a calling agent') // The parameter enum admits only keys from this immutable configuration. const providerName = providers.get(args.runtime) as string const provider = ctx.subagents.getProvider(providerName) if (provider !== undefined && (provider.prepareContinuable !== undefined || provider.inheritsParentContext)) { - throw new Error('subagent_oar requires a one-shot provider with independent conversation context') + throw new SubagentError('subagent_oar requires a one-shot provider with independent conversation context', 'UNSUPPORTED_CAPABILITY') } const activation = await ctx.subagents.startActivation({ provider: providerName, diff --git a/packages/experimental/tool-subagent-oar/tests/tool-subagent-oar.spec.ts b/packages/experimental/tool-subagent-oar/tests/tool-subagent-oar.spec.ts index 9b9b3d142a..534b51b335 100644 --- a/packages/experimental/tool-subagent-oar/tests/tool-subagent-oar.spec.ts +++ b/packages/experimental/tool-subagent-oar/tests/tool-subagent-oar.spec.ts @@ -95,6 +95,7 @@ it('fails visibly when the selected provider disappears', async (test) => { arguments: { runtime: 'missing', description: 'task', prompt: 'task' }, }) expect(result.isError).toBe(true) + expect(result.isError && result.error.info).toEqual({ name: 'SubagentError', code: 'NO_PROVIDER' }) expect(calls).toEqual([]) }) @@ -121,10 +122,12 @@ it('requires a caller and independently scoped one-shot providers', async (test) name: 'subagent_oar', arguments: args, callId: brandString(randomUUID()), signal: test.signal, }) expect(noParent.isError).toBe(true) + expect(noParent.isError && noParent.error.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) const inherited = await executeToolFixture(ctx, { agent: parent, name: 'subagent_oar', arguments: args, callId: brandString(randomUUID()), signal: test.signal, }) expect(inherited.isError).toBe(true) + expect(inherited.isError && inherited.error.info).toEqual({ name: 'SubagentError', code: 'UNSUPPORTED_CAPABILITY' }) expect(JSON.stringify(inherited.content)).toContain('independent conversation') }) diff --git a/packages/experimental/tool-terminal/README.i18n.yaml b/packages/experimental/tool-terminal/README.i18n.yaml index 9c42634e60..02dc0d007f 100644 --- a/packages/experimental/tool-terminal/README.i18n.yaml +++ b/packages/experimental/tool-terminal/README.i18n.yaml @@ -30,8 +30,8 @@ en: 2ad49d4f69deb06d zh: 5f29972b5feec7e3 /deepseek-ai-dsh-tool-terminal/use-this-package/observable-outcomes-and-failures: - en: 321a982fdbbf4ada - zh: 8c2636e5379815e1 + en: f8549c20403b1d65 + zh: ef98b292e71de6ac /deepseek-ai-dsh-tool-terminal/understand-the-implementation: en: 6302fca8fef89136 zh: 6327d56edb798ab2 diff --git a/packages/experimental/tool-terminal/README.md b/packages/experimental/tool-terminal/README.md index 03f213dff3..d14805f522 100644 --- a/packages/experimental/tool-terminal/README.md +++ b/packages/experimental/tool-terminal/README.md @@ -65,7 +65,7 @@ The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-a ### Observable outcomes and failures -A foreground send returns the terminal's new output plus `wait: ` and the session status; `session_exit` means the top-level shell exited, while `inferred_idle` or `timeout` never proves the foreground command exited. Opening a session with an unregistered backend type fails. Results larger than `maxResultBytes` are truncated at a UTF-8 boundary with a marker. +A foreground send returns the terminal's new output plus `wait: ` and the session status; `session_exit` means the top-level shell exited, while `inferred_idle` or `timeout` never proves the foreground command exited. Opening a session with an unregistered backend type fails. Failed calls carry a structured error identity: an empty `type` or `sessionId` is a `ToolArgsError` (`INVALID_ARGS`), a call without a calling Agent or a background send without the jobs service is a `ToolContextUnavailableError`, a background send with `enableRunInBackground: false` is a `ToolArgsError` (`INVALID_ARGS`) because the schema does not offer `run_in_background`, a cancelled foreground send is an `AbortError`, and terminal service failures keep their `TerminalError` code. Results larger than `maxResultBytes` are truncated at a UTF-8 boundary with a marker. ----- diff --git a/packages/experimental/tool-terminal/README.zh.md b/packages/experimental/tool-terminal/README.zh.md index 097ede5cf7..d6bd337a62 100644 --- a/packages/experimental/tool-terminal/README.zh.md +++ b/packages/experimental/tool-terminal/README.zh.md @@ -65,7 +65,7 @@ kind: "package-reference" ### 可观察结果与失败 -前台发送返回终端的新输出以及 `wait: <原因>` 与会话状态;`session_exit` 表示顶层 shell 已退出,而 `inferred_idle` 或 `timeout` 绝不证明前台命令已退出。用未注册的后端类型打开会话会失败。大于 `maxResultBytes` 的结果会在 UTF-8 边界处截断并附标记。 +前台发送返回终端的新输出以及 `wait: <原因>` 与会话状态;`session_exit` 表示顶层 shell 已退出,而 `inferred_idle` 或 `timeout` 绝不证明前台命令已退出。用未注册的后端类型打开会话会失败。失败的调用带有结构化错误标识:`type` 或 `sessionId` 为空时为 `ToolArgsError`(`INVALID_ARGS`),没有调用方 Agent 或后台发送缺少 jobs 服务时为 `ToolContextUnavailableError`,`enableRunInBackground: false` 时的后台发送为 `ToolArgsError`(`INVALID_ARGS`),因为 schema 不提供 `run_in_background`,被取消的前台发送为 `AbortError`,终端服务失败保留其 `TerminalError` code。大于 `maxResultBytes` 的结果会在 UTF-8 边界处截断并附标记。 ----- diff --git a/packages/experimental/tool-terminal/src/index.ts b/packages/experimental/tool-terminal/src/index.ts index 1d38410af9..3798a58de9 100644 --- a/packages/experimental/tool-terminal/src/index.ts +++ b/packages/experimental/tool-terminal/src/index.ts @@ -13,7 +13,7 @@ import type { ContentBlock } from '@deepseek-ai/dsh-llm' import { brandString } from '@deepseek-ai/dsh-brand' import type { TerminalSendOperation, TerminalSendResult, TerminalSessionId as TerminalSessionIdType, TerminalSignal } from '@deepseek-ai/dsh-terminal' import type {} from '@deepseek-ai/dsh-jobs' -import { defineTool } from '@deepseek-ai/dsh-tools' +import { defineTool, ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import type { ToolDefinition } from '@deepseek-ai/dsh-tools' import { sendSource } from './background.ts' import { boundTerminalText, renderList, renderRead, renderSend, renderSpawn } from './render.ts' @@ -118,13 +118,18 @@ const BACKGROUND_JOB_OUTPUT_SCHEMA = { } as const function requireAgent(agent: Agent | undefined): Agent { - if (agent === undefined) throw new Error('terminal tools require an initiating agent') + if (agent === undefined) throw new ToolContextUnavailableError('terminal tools require an initiating agent') return agent } +/** The cancellation for a foreground send the caller cancelled; the tool registry records it as `ABORTED`. */ +function sendAborted(): DOMException { + return new DOMException('terminal send aborted', 'AbortError') +} + function sessionId(args: SessionArgs): TerminalSessionIdType { if (args.sessionId.length === 0) { - throw new Error('sessionId must be a non-empty string') + throw new ToolArgsError(['sessionId must be a non-empty string']) } return brandString(args.sessionId) } @@ -183,7 +188,7 @@ export function apply(ctx: Context, config: Config = {}): void { render: (_args, value) => [{ type: 'text', text: renderSpawn(value, maxResultBytes) }], }, async execute(args: SpawnArgs, exec) { - if (args.type.length === 0) throw new Error('type must be a non-empty string') + if (args.type.length === 0) throw new ToolArgsError(['type must be a non-empty string']) const owner = requireAgent(exec.agent) const cwd = await ctx.workingDirectory.ensure(owner, exec.signal) const result = await ctx.terminals.spawn(owner, { @@ -253,9 +258,9 @@ export function apply(ctx: Context, config: Config = {}): void { const id = sessionId(args) const request = { text: args.text, submit: args.submit ?? true } if (args.run_in_background === true) { - if (!enableRunInBackground) throw new Error('background terminal sends are disabled by tool-terminal configuration') + if (!enableRunInBackground) throw new ToolArgsError(['run_in_background is disabled by tool-terminal configuration (enableRunInBackground: false)']) const jobs = ctx.get('jobs') - if (jobs === undefined) throw new Error('background terminal sends require @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs') + if (jobs === undefined) throw new ToolContextUnavailableError('background terminal sends require @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs') let cancelRequested = false let operation: TerminalSendOperation | undefined const jobId = jobs.start({ @@ -284,7 +289,7 @@ export function apply(ctx: Context, config: Config = {}): void { } const operation = ctx.terminals.startSend(owner, id, { ...request, signal: exec.signal }) const result = await operation.done - if (exec.signal.aborted) throw new Error('terminal send aborted') + if (exec.signal.aborted) throw sendAborted() return { kind: 'foreground' as const, ...result } }, presentCall(args) { diff --git a/packages/experimental/tool-terminal/tests/tools.spec.ts b/packages/experimental/tool-terminal/tests/tools.spec.ts index 03e20b7660..47d75518a0 100644 --- a/packages/experimental/tool-terminal/tests/tools.spec.ts +++ b/packages/experimental/tool-terminal/tests/tools.spec.ts @@ -293,17 +293,21 @@ describe('tool-terminal foreground API', () => { it('fails without an initiating agent and rejects background before writing', async () => { const { ctx, agent, stub } = await setup(false) - expect((await call(ctx, 'terminal_open', { type: 'stub' })).isError).toBe(true) + expect((await call(ctx, 'terminal_open', { type: 'stub' })).error?.info) + .toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) await call(ctx, 'terminal_open', { type: 'stub' }, agent) const result = await call(ctx, 'terminal_send', { sessionId: 'pty-1', text: 'sleep 1', run_in_background: true }, agent) expect(result.isError).toBe(true) + expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) expect(stub.sessions[0]?.operation).toBeUndefined() }) it('validates required values and forwards optional spawn/read arguments', async () => { const { ctx, agent } = await setup(false) - expect((await call(ctx, 'terminal_open', { type: '' }, agent)).isError).toBe(true) - expect((await call(ctx, 'terminal_send', { sessionId: '', text: 'x' }, agent)).isError).toBe(true) + expect((await call(ctx, 'terminal_open', { type: '' }, agent)).error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) + expect((await call(ctx, 'terminal_send', { sessionId: '', text: 'x' }, agent)).error?.info).toEqual({ + name: 'ToolArgsError', code: 'INVALID_ARGS', + }) expect((await call(ctx, 'terminal_send', { sessionId: 1, text: 'x' }, agent)).isError).toBe(true) expect((await call(ctx, 'terminal_send', { sessionId: 'pty-1', text: 1 }, agent)).isError).toBe(true) await call(ctx, 'terminal_open', { type: 'stub', name: 'named', cwd: '/tmp' }, agent) @@ -321,7 +325,9 @@ describe('tool-terminal foreground API', () => { expect(definition?.presentResult?.({ sessionId: 'pty-1', text: 'x' }, { content: [], isError: false })).toBeUndefined() expect(definition?.presentResult?.({ sessionId: 'pty-1', text: 'x' }, { content: [{ type: 'text', text: 'a' }, { type: 'text', text: 'b' }], isError: false })).toBeUndefined() expect(definition?.presentResult?.({ sessionId: 'pty-1', text: 'x' }, { content: [undefined as never], isError: false })).toBeUndefined() - expect(definition?.presentResult?.({ sessionId: 'pty-1', text: 'x' }, { content: [{ type: 'text', text: 'ok' }], isError: false })).toEqual({ card: 'terminal', output: 'ok' }) + expect(definition?.presentResult?.({ sessionId: 'pty-1', text: 'x' }, { content: [{ type: 'text', text: 'ok' }], isError: false })).toEqual({ + card: 'terminal', output: 'ok', + }) expect(ctx.tools.get('terminal_open')?.presentCall?.({ type: 'stub' })).toMatchObject({ card: 'generic', title: 'Open terminal stub' }) expect(ctx.tools.get('terminal_open')?.presentCall?.({ type: 'stub', name: 'main' })).toMatchObject({ card: 'generic', title: 'Open terminal main' }) @@ -339,7 +345,7 @@ describe('tool-terminal foreground API', () => { await call(disabled.ctx, 'terminal_open', { type: 'stub' }, disabled.agent) expect((await call(disabled.ctx, 'terminal_send', { sessionId: 'pty-1', text: 'work', run_in_background: true, - }, disabled.agent)).isError).toBe(true) + }, disabled.agent)).error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) const defaults = await setupBase(false) ToolPty.apply(defaults.ctx) @@ -504,7 +510,9 @@ describe('tool-terminal task integration', () => { await expect.poll(() => stub.sessions[0]!.operation).toBeDefined() controller.abort() stub.sessions[0]!.operation?.cancel() - expect((await pending).isError).toBe(true) + const cancelled = await pending + expect(cancelled.isError).toBe(true) + expect(cancelled.error?.info).toEqual({ name: 'AbortError', code: 'ABORTED' }) }) it('renders the already-closing kill result', async () => { diff --git a/packages/experimental/tool-worktree/src/index.ts b/packages/experimental/tool-worktree/src/index.ts index 53f035f7d7..ad526e61ef 100644 --- a/packages/experimental/tool-worktree/src/index.ts +++ b/packages/experimental/tool-worktree/src/index.ts @@ -2,7 +2,7 @@ import type { Context } from '@deepseek-ai/cordis' import type {} from '@deepseek-ai/dsh-experimental-worktree' -import { defineTool } from '@deepseek-ai/dsh-tools' +import { defineTool, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' /** Cordis plugin name. */ export const name = 'tool-worktree' @@ -35,7 +35,7 @@ export function apply(ctx: Context): void { render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }], }, async execute(args, exec) { - if (exec.agent === undefined) throw new Error('create_worktree requires a calling agent') + if (exec.agent === undefined) throw new ToolContextUnavailableError('create_worktree requires a calling agent') return ctx.worktrees.create(exec.agent, args, 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 3e4aee727a..25af996861 100644 --- a/packages/experimental/tool-worktree/tests/loader-composition.spec.ts +++ b/packages/experimental/tool-worktree/tests/loader-composition.spec.ts @@ -103,7 +103,12 @@ describe('worktree tool through real Loader composition', () => { }) expect(failure.isError).toBe(true) expect(failure.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('\n')).toContain('requires a calling agent') - expect(context.tools.get('create_worktree')!.presentCall!({ name: 'named' })).toEqual({ card: 'generic', title: 'create_worktree', rawInput: { name: 'named' } }) + 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' }) + expect(context.tools.get('create_worktree')!.presentCall!({ name: 'named' })).toEqual({ + card: 'generic', title: 'create_worktree', rawInput: { name: 'named' }, + }) const entry = [...context.loader.entries()].find(candidate => candidate.options.name === 'cordis:@deepseek-ai/dsh-experimental-tool-worktree') await entry!.fiber!.dispose() expect(context.tools.schemas().some(tool => tool.name === 'create_worktree')).toBe(false) diff --git a/packages/experimental/worktree/README.i18n.yaml b/packages/experimental/worktree/README.i18n.yaml index 5e9a6604cb..b97e443ecd 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: 7fb20cca0a3154e5 - zh: 41bf0aa2bf753c07 + en: e33f2d32037ef164 + zh: 18528ef31803c6d0 /deepseek-ai-dsh-experimental-worktree/understand-the-implementation: en: 6971a7ca9073bef1 zh: b977c28a75c7f963 diff --git a/packages/experimental/worktree/README.md b/packages/experimental/worktree/README.md index e164f86600..30cfcfca04 100644 --- a/packages/experimental/worktree/README.md +++ b/packages/experimental/worktree/README.md @@ -38,6 +38,8 @@ Mount the service alongside `workingDirectory`, `fs`, `subprocess`, `sandbox`, ` Every creation appends a `plugin:worktree/created` record to the Session log after the directory change, so the `worktree` projection lists the Session's checkouts with `owned` false for one inside a fork-inherited prefix. When the Workspace archives a Session, the service registers one `scheduled` cleanup for the first checkout that Session created itself and returns; the inspection runs in the background. While `retainOnArchive` is on, archiving registers nothing and every checkout stays; the field is volatile and read at each archive, and the [Forge panel](../client-ui-forge/README.md) edits it as a switch on the bundle's worktree row of the Plugins page. The checkout is retained while any unarchived Session refers to it, by a recorded creation or by a working directory inside it (a Session beneath an archived subagent ancestor counts as archived; cold Sessions are read from the projection cache or their log), and while the creator's sandbox policy is read-only. An eligible checkout is removed with a non-force `git worktree remove` under the creator's policy after a second use check inside the path lock, which also holds `ensure` and `set` into that path through `working-directory/access`; the branch and its commits remain. Tracked changes, untracked files, an initialized submodule (a repository in the checkout's administrative `modules` directory), locks, detached HEAD, a mismatched branch, and targets outside the configured pool retain the checkout. Ignored files and edits to skip-worktree or assume-unchanged files do not: `git status` reports neither, and Git discards them with the checkout. A committed embedded repository is not inspected; Git refuses that removal, so the attempt settles as `failed`. Inspection stops reading `git status` at its first entry and streams the worktree listing, keeping its entries in memory while it looks for the checkout; neither output is bounded by `maxOutputBytes`. Processes are not consulted: a process still writing there makes Git refuse, and an idle one fails its next command. Unarchiving cancels an unadmitted removal and waits for an admitted one. `cleanupOf(session, revision)` reads the attempt, or waits for a named revision to settle, as `scheduled`, `retained`, `removed`, or `failed`; a failure leaves the Session archived and logs a warning. Checkouts created before this event existed, and Sessions archived earlier, are not swept. +Expected failures throw `WorktreeError` with a stable `code`: `WORKTREE_INVALID_ARGUMENT` for a name Git or the pool rules reject, an empty start revision, or a restoration record that violates a documented constraint, while a start revision or base commit Git cannot resolve fails as `WORKTREE_COMMAND_FAILED`; `WORKTREE_ALREADY_EXISTS` for an existing branch or path; `WORKTREE_LOCKED` for a locked registration; `WORKTREE_COMMAND_FAILED`, `WORKTREE_OUTPUT_TOO_LARGE`, and `WORKTREE_TIMEOUT` for a command that exits unsuccessfully, exceeds `maxOutputBytes`, or exceeds `timeoutMs`; and `WORKTREE_UNAVAILABLE` after service disposal. A failure after directory allocation adds the retained-artifact context to its message and keeps the original error's `name` and `code`; caller cancellation stays an `AbortError`. + The default checkout directory is `/.agents/worktrees/`. The returned `repositoryRoot` is the top-level directory of the caller’s current checkout; when it is a linked checkout, the pool is nested inside it. Omitted names join the `dsh-` prefix, the first eight hexadecimal digits of the UUID in the Session id, a hyphen, and four random hexadecimal digits, such as `dsh-6b1f02c4-9a3e`; a Session id without a UUID gets eight random hexadecimal digits after the prefix. `generatedWorktreeName` exports the same rule for callers that name a worktree before creating it. The service writes a `.gitignore` containing `*` and a trailing newline only when its allocation creates the pool; existing files and ignore rules are preserved. Each Git and Node command runs under its own `timeoutMs` deadline, 5 minutes by default, so checking out a large repository on a slow filesystem can finish; cancellation still stops the running command. Relative `directory`, generated `namePrefix`, executable choices, process limits, and `retainOnArchive` are configurable in the [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-worktree). ----- diff --git a/packages/experimental/worktree/README.zh.md b/packages/experimental/worktree/README.zh.md index 5c497a2606..28fc6fb0b0 100644 --- a/packages/experimental/worktree/README.zh.md +++ b/packages/experimental/worktree/README.zh.md @@ -38,6 +38,8 @@ kind: "package-reference" 每次创建都会在目录切换之后向 Session 日志追加一条 `plugin:worktree/created` 事件,因此 `worktree` 投影列出该 Session 的检出目录,位于 fork 继承前缀内的条目 `owned` 为 false。Workspace 归档某个 Session 时,服务为该 Session 自己创建的第一个检出目录登记一条 `scheduled` 清理并立即返回;检查在后台进行。`retainOnArchive` 开启时,归档不登记任何清理,所有检出目录都保留;该字段是 volatile 字段,每次归档时读取,[Forge 面板](../client-ui-forge/README.zh.md)在插件页该套件的 worktree 行上以开关编辑它。只要任一未归档 Session 仍引用该目录——通过记录的创建,或通过位于其中的工作目录(祖先子代理已归档的 Session 视为已归档;冷 Session 从投影缓存或其日志读取)——或创建者的沙箱策略为只读,目录就保留。符合条件的目录在路径锁内再做一次使用检查后,用创建者的策略执行不带 force 的 `git worktree remove`;路径锁同时通过 `working-directory/access` 阻塞进入该路径的 `ensure` 与 `set`;分支及其提交保留。跟踪文件改动、未跟踪文件、已初始化的子模块(仓库位于检出目录管理目录的 `modules` 中)、锁、分离 HEAD、分支不匹配以及位于配置池之外的目标都会保留目录。被忽略的文件以及对 skip-worktree 或 assume-unchanged 文件的改动不会:`git status` 不报告这两类内容,Git 删除目录时一并丢弃它们。检查不识别已提交的内嵌仓库;Git 会拒绝这类删除,本次尝试以 `failed` 结束。检查读到 `git status` 的第一条记录即停止,并以流式读取工作树列表,查找该检出目录期间在内存中保留其条目;两者的输出都不受 `maxOutputBytes` 限制。不检查进程:仍在写入的进程会让 Git 拒绝删除,空闲进程的下一条命令会失败。取消归档会取消尚未获准的删除,并等待已获准的删除结束。`cleanupOf(session, revision)` 读取本次尝试,或等待指定修订号结束,状态为 `scheduled`、`retained`、`removed` 或 `failed`;失败时 Session 仍保持归档并记录警告。此事件存在之前创建的检出目录,以及更早归档的 Session,不会被扫描。 +预期失败抛出 `WorktreeError`,其 `code` 为:名称被 Git 或池规则拒绝、起始修订为空或恢复记录违反文档约束时为 `WORKTREE_INVALID_ARGUMENT`,Git 无法解析的起始修订或基础提交则以 `WORKTREE_COMMAND_FAILED` 失败;分支或路径已存在时为 `WORKTREE_ALREADY_EXISTS`;登记被锁定时为 `WORKTREE_LOCKED`;命令以失败状态退出、超过 `maxOutputBytes` 或超过 `timeoutMs` 时分别为 `WORKTREE_COMMAND_FAILED`、`WORKTREE_OUTPUT_TOO_LARGE` 和 `WORKTREE_TIMEOUT`;服务释放后为 `WORKTREE_UNAVAILABLE`。目录分配之后的失败会在消息中加入保留产物的说明,并保留原错误的 `name` 与 `code`;调用方取消仍是 `AbortError`。 + 默认检出目录是 `/.agents/worktrees/`。返回的 `repositoryRoot` 是调用方当前检出目录的顶层目录;如果它是链接检出目录,工作树父目录就嵌套在其中。省略名称时,名称由前缀 `dsh-`、Session id 中 UUID 的前 8 位十六进制数、一个连字符和 4 位随机十六进制数组成,例如 `dsh-6b1f02c4-9a3e`;Session id 不含 UUID 时,前缀后接 8 位随机十六进制数。`generatedWorktreeName` 导出同一规则,供在创建前确定名称的调用方使用。仅当服务的分配操作创建了父目录时,服务才会写入内容为 `*` 加换行符的 `.gitignore`;已有文件与忽略规则保持不变。每条 Git 和 Node 命令各自受 `timeoutMs` 时限约束,默认 5 分钟,使大仓库在较慢的文件系统上也能完成检出;取消仍会终止正在运行的命令。相对路径 `directory`、生成名称使用的 `namePrefix`、可执行程序、进程限制与 `retainOnArchive` 可在[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-worktree)中查阅。 ----- diff --git a/packages/experimental/worktree/package.json b/packages/experimental/worktree/package.json index aeeb9e49d5..921d2be276 100644 --- a/packages/experimental/worktree/package.json +++ b/packages/experimental/worktree/package.json @@ -54,7 +54,8 @@ "@deepseek-ai/dsh-settings": "workspace:*", "@deepseek-ai/dsh-subprocess": "workspace:*", "@deepseek-ai/dsh-working-directory": "workspace:*", - "@deepseek-ai/dsh-workspace": "workspace:*" + "@deepseek-ai/dsh-workspace": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" }, "devDependencies": { "@deepseek-ai/dsh-brand": "workspace:*", @@ -78,6 +79,7 @@ "@deepseek-ai/dsh-subprocess-local": "workspace:*", "@deepseek-ai/dsh-system-prompt": "workspace:*", "@deepseek-ai/dsh-working-directory": "workspace:*", - "@deepseek-ai/dsh-workspace": "workspace:*" + "@deepseek-ai/dsh-workspace": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" } } diff --git a/packages/experimental/worktree/src/error.ts b/packages/experimental/worktree/src/error.ts new file mode 100644 index 0000000000..57a2b394f8 --- /dev/null +++ b/packages/experimental/worktree/src/error.ts @@ -0,0 +1,43 @@ +/** Machine-routable worktree creation and restoration failures. @module */ + +import { HarnessError } from '@deepseek-ai/dsh-error' + +/** + * Every {@link WorktreeError} code: + * - `WORKTREE_INVALID_ARGUMENT` — the branch name, start revision, or restoration request violates a documented + * constraint; correct it and retry. + * - `WORKTREE_ALREADY_EXISTS` — the branch or checkout path already exists; choose another name or reuse the existing checkout. + * - `WORKTREE_LOCKED` — Git keeps the missing checkout's registration locked; unlock it before restoring. + * - `WORKTREE_COMMAND_FAILED` — a Git or directory-allocation command exited unsuccessfully; the message carries its status and stderr. + * - `WORKTREE_OUTPUT_TOO_LARGE` — a command's output exceeded the configured `maxOutputBytes`; raise the limit or inspect the repository. + * - `WORKTREE_TIMEOUT` — a command exceeded the configured `timeoutMs`; its effects are unknown, so inspect the repository before retrying. + * - `WORKTREE_UNAVAILABLE` — the worktree service was disposed; retry after it is loaded again. + */ +export const WORKTREE_ERROR_CODES = [ + 'WORKTREE_INVALID_ARGUMENT', + 'WORKTREE_ALREADY_EXISTS', + 'WORKTREE_LOCKED', + 'WORKTREE_COMMAND_FAILED', + 'WORKTREE_OUTPUT_TOO_LARGE', + 'WORKTREE_TIMEOUT', + 'WORKTREE_UNAVAILABLE', +] as const + +/** One code from {@link WORKTREE_ERROR_CODES}. */ +export type WorktreeErrorCode = typeof WORKTREE_ERROR_CODES[number] + +/** Worktree failure carrying a stable {@link WorktreeErrorCode}. */ +export class WorktreeError extends HarnessError { + override readonly code: WorktreeErrorCode + + /** + * @param message - names the operation and the safe next step. + * @param code - failure class. + * @param options - standard `cause` chaining. + */ + constructor(message: string, code: WorktreeErrorCode, options?: ErrorOptions) { + super(message, code, options) + this.name = 'WorktreeError' + this.code = code + } +} diff --git a/packages/experimental/worktree/src/index.ts b/packages/experimental/worktree/src/index.ts index b445ec72b7..8e2c5b5ade 100644 --- a/packages/experimental/worktree/src/index.ts +++ b/packages/experimental/worktree/src/index.ts @@ -11,8 +11,10 @@ import { appendPluginRecord } from '@deepseek-ai/dsh-session' import type { Session } from '@deepseek-ai/dsh-session' import type { ProjectionHandle } from '@deepseek-ai/dsh-session-projection' import type {} from '@deepseek-ai/dsh-working-directory' +import { HarnessError } from '@deepseek-ai/dsh-error' import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' import { WorktreeReclamation } from './archive.ts' +import { WorktreeError } from './error.ts' import { PREPARE_DIRECTORY } from './directory.ts' import { generatedWorktreeName } from './name.ts' import { runCommand, scanCommand } from './process.ts' @@ -31,6 +33,7 @@ export type { export { generatedWorktreeName } from './name.ts' export { CREATED_RECORD, createdWorktreeSchema, worktreeProjection } from './projection.ts' export type { WorktreeProjectionState } from './projection.ts' +export { WorktreeError, type WorktreeErrorCode } from './error.ts' /** Worktree location, generated names, executables, subprocess resource limits, and the archive cleanup switch. */ export interface Config { @@ -121,7 +124,7 @@ export class WorktreeService extends Service { } } ctx.effect(() => async () => { - this.lifetime.abort(new Error('worktree service disposed')) + this.lifetime.abort(new WorktreeError('worktree service disposed', 'WORKTREE_UNAVAILABLE')) await Promise.allSettled(this.pending) }) // The Forge panel draws the retain switch on this row's Plugins page. @@ -155,6 +158,8 @@ export class WorktreeService extends Service { * @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. */ async create( agent: Agent, @@ -186,6 +191,8 @@ export class WorktreeService extends Service { * @param signal - cancellation of the restoration. * @param onPhase - receives each stage before it begins; 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, @@ -242,9 +249,9 @@ export class WorktreeService extends Service { private resolve(agent: Agent, request: CreateWorktreeRequest): WorktreeSpec { const branch = request.name ?? generatedWorktreeName(this.config.namePrefix, agent.session.id) - if (!relativePath(branch) || branch.startsWith('-')) throw new Error('worktree name must be a relative Git branch name') + 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 Error('worktree from must name a local commit, branch, or tag') + if (revision.length === 0) throw new WorktreeError('worktree from must name a local commit, branch, or tag', 'WORKTREE_INVALID_ARGUMENT') return { branch, revision } } @@ -258,19 +265,19 @@ export class WorktreeService extends Service { const cwd = await this.ctx.workingDirectory.ensure(agent, signal) const policy = this.ctx.sandboxPolicy.resolve({ session: agent.session }) const run = this.gitRunner(policy, signal) - await run(cwd, ['check-ref-format', `refs/heads/${branch}`]) + await assertBranchName(run, cwd, branch, 'worktree name') 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) 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]) - if (existing.exitCode === 0) throw new Error(`worktree branch already exists: ${branch}`) + if (existing.exitCode === 0) throw new WorktreeError(`worktree branch already exists: ${branch}`, 'WORKTREE_ALREADY_EXISTS') const pool = await this.ctx.fs.resolve(this.config.directory, { cwd: repositoryRoot, signal }) const poolPath = this.ctx.fs.processPath(pool) const destination = await this.ctx.fs.resolve(branch, { cwd: poolPath, signal }) const path = this.ctx.fs.processPath(destination) - if (await this.ctx.fs.lstat(path, undefined, signal) !== undefined) throw new Error(`worktree path already exists: ${path}`) + if (await this.ctx.fs.lstat(path, undefined, signal) !== undefined) throw new WorktreeError(`worktree path already exists: ${path}`, 'WORKTREE_ALREADY_EXISTS') try { await this.prepareDirectory(policy, repositoryRoot, poolPath, path, signal) await run(repositoryRoot, ['--work-tree', repositoryRoot, 'worktree', 'add', '--no-checkout', '-b', branch, '--', path, baseCommit]) @@ -282,7 +289,7 @@ export class WorktreeService extends Service { appendPluginRecord(agent.session, CREATED_RECORD, created) return created } catch (error) { - throw new Error(`Could not finish worktree ${branch} at ${path}. Any created checkout and branch are retained. ${error instanceof Error ? error.message : String(error)}`, { cause: error }) + throw retainedFailure(`Could not finish worktree ${branch} at ${path}. Any created checkout and branch are retained.`, error, signal) } } @@ -295,18 +302,20 @@ export class WorktreeService extends Service { onPhase?.('prepare') const policy = this.ctx.sandboxPolicy.resolve({ session: agent.session }) const run = this.gitRunner(policy, signal) - if (await this.ctx.fs.lstat(path, undefined, signal) !== undefined) throw new Error(`worktree path already exists: ${path}`) - if (!relativePath(branch) || branch.startsWith('-')) throw new Error('worktree branch must be a relative Git branch name') - if (!/^(?:[a-f\d]{40}|[a-f\d]{64})$/i.test(baseCommit)) throw new Error('worktree baseCommit must be a full commit object name') + if (await this.ctx.fs.lstat(path, undefined, signal) !== undefined) throw new WorktreeError(`worktree path already exists: ${path}`, 'WORKTREE_ALREADY_EXISTS') + if (!relativePath(branch) || branch.startsWith('-')) throw new WorktreeError('worktree branch must be a relative Git branch name', 'WORKTREE_INVALID_ARGUMENT') + if (!/^(?:[a-f\d]{40}|[a-f\d]{64})$/i.test(baseCommit)) throw new WorktreeError('worktree baseCommit must be a full commit object name', 'WORKTREE_INVALID_ARGUMENT') const identity = await checkoutIdentity(this.ctx, this.config.directory, { path, branch, baseCommit, repositoryRoot }, run, signal) - if (identity === null) throw new Error('worktree restoration must use a canonical directory inside the configured pool of the source checkout root') - await run(repositoryRoot, ['check-ref-format', `refs/heads/${branch}`]) + if (identity === null) { + throw new WorktreeError('worktree restoration must use a canonical directory inside the configured pool of the source checkout root', 'WORKTREE_INVALID_ARGUMENT') + } + await assertBranchName(run, repositoryRoot, branch, 'worktree branch') await run(repositoryRoot, ['rev-parse', '--verify', '--end-of-options', `${baseCommit}^{commit}`]) const scan = this.gitScanner(policy, signal) const fields = await registration(this.ctx, { path, branch, baseCommit, repositoryRoot }, identity.target, scan, signal) if (fields !== undefined) { - if (fields.some(field => field === 'locked' || field.startsWith('locked '))) throw new Error(`worktree is locked: ${path}`) - if (await this.ctx.fs.lstat(path, undefined, signal) !== undefined) throw new Error(`worktree path already exists: ${path}`) + if (fields.some(field => field === 'locked' || field.startsWith('locked '))) throw new WorktreeError(`worktree is locked: ${path}`, 'WORKTREE_LOCKED') + if (await this.ctx.fs.lstat(path, undefined, signal) !== undefined) throw new WorktreeError(`worktree path already exists: ${path}`, 'WORKTREE_ALREADY_EXISTS') await run(repositoryRoot, ['worktree', 'remove', '--', path]) } const existing = await run(repositoryRoot, ['show-ref', '--verify', '--quiet', `refs/heads/${branch}`], [0, 1]) @@ -323,7 +332,7 @@ export class WorktreeService extends Service { await run(path, ['--work-tree', path, 'reset', '--hard', '--no-recurse-submodules', 'HEAD'], undefined, overrides) return { path, branchRecreated } } catch (error) { - throw new Error(`Could not restore worktree ${branch} at ${path}. Any created checkout and branch are retained. ${error instanceof Error ? error.message : String(error)}`, { cause: error }) + throw retainedFailure(`Could not restore worktree ${branch} at ${path}. Any created checkout and branch are retained.`, error, signal) } } @@ -357,6 +366,41 @@ export class WorktreeService extends Service { } } +/** + * Reject a name Git does not accept as a branch. + * @param run - confined Git runner. + * @param directory - repository directory for the check. + * @param branch - candidate branch name. + * @param field - request field named in the failure. + */ +async function assertBranchName(run: GitRun, directory: string, branch: string, field: string): Promise { + const checked = await run(directory, ['check-ref-format', `refs/heads/${branch}`], [0, 1]) + if (checked.exitCode !== 0) throw new WorktreeError(`${field} must be a valid Git branch name`, 'WORKTREE_INVALID_ARGUMENT') +} + +/** + * 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`. + * A `HarnessError` subclass other than `WorktreeError` is rebuilt as a plain `HarnessError`, so + * callers route on `name` and `code` rather than on `instanceof` the original subclass. + * @param context - operation summary placed before the original message. + * @param error - failure thrown after allocation began. + * @param signal - operation cancellation. + * @returns the error to throw, with `error` as its cause. + */ +function retainedFailure(context: string, error: unknown, signal: AbortSignal): Error { + const message = `${context} ${error instanceof Error ? error.message : String(error)}` + if (error instanceof WorktreeError) return new WorktreeError(message, error.code, { cause: error }) + if (error instanceof HarnessError) { + const wrapped = new HarnessError(message, error.code, { cause: error }) + wrapped.name = error.name + return wrapped + } + const wrapped = new Error(message, { cause: error }) + if (signal.aborted && (error === signal.reason || (error instanceof Error && error.name === 'AbortError'))) wrapped.name = 'AbortError' + return wrapped +} + /** * Build the environment that disables every configured clean, smudge, and * process filter of the checkout for one command, without changing Git config. diff --git a/packages/experimental/worktree/src/process.ts b/packages/experimental/worktree/src/process.ts index f4bb56273a..5a66022b30 100644 --- a/packages/experimental/worktree/src/process.ts +++ b/packages/experimental/worktree/src/process.ts @@ -6,7 +6,8 @@ import type { SandboxExecutionPolicy } from '@deepseek-ai/dsh-sandbox' import type { SubprocessCollect, SubprocessCollectedOutputs, SubprocessHandle, SubprocessOutcome, SubprocessOutputReader, } from '@deepseek-ai/dsh-subprocess' -import { deadline } from '@deepseek-ai/dsh-timeout' +import { deadline, timeoutOf } from '@deepseek-ai/dsh-timeout' +import { WorktreeError } from './error.ts' /** Resolved process resource limits owned by the worktree service. */ export interface ProcessConfig { @@ -37,6 +38,8 @@ const GIT_ENV: NodeJS.ProcessEnv = Object.fromEntries([ * @param allowedExitCodes - command-specific successful statuses. * @param env - command-local environment overrides, applied after Git selector removal. * @returns complete bounded stdout and the exit code. + * @throws {WorktreeError} `WORKTREE_COMMAND_FAILED`, `WORKTREE_OUTPUT_TOO_LARGE`, or `WORKTREE_TIMEOUT`; + * caller cancellation propagates its reason. */ export async function runCommand( ctx: Context, @@ -49,20 +52,22 @@ export async function runCommand( env: NodeJS.ProcessEnv = {}, ): Promise<{ stdout: string; exitCode: number }> { using timeout = deadline(signal, config.timeoutMs, 'WORKTREE_TIMEOUT') - const child = await spawnCommand(ctx, config, policy, cwd, argv, timeout.signal, env, { maxBytes: config.maxOutputBytes }) - try { - const outcome = await child.done - timeout.signal.throwIfAborted() - // The spawn spec above collects both streams. - const captured = child.collected as Required - const exitCode = allowedExitCode(outcome, captured.stderr, allowedExitCodes) - const stdout = captured.stdout.readFrom(0) - if (stdout.lossy) throw new Error('worktree command output exceeds maxOutputBytes') - return { stdout: stdout.text, exitCode } - } finally { - child.terminate() - await child.waitForExit() - } + return await classifyTimeout(config, timeout.signal, async () => { + const child = await spawnCommand(ctx, config, policy, cwd, argv, timeout.signal, env, { maxBytes: config.maxOutputBytes }) + try { + const outcome = await child.done + timeout.signal.throwIfAborted() + // The spawn spec above collects both streams. + const captured = child.collected as Required + const exitCode = allowedExitCode(outcome, captured.stderr, allowedExitCodes) + const stdout = captured.stdout.readFrom(0) + if (stdout.lossy) throw new WorktreeError('worktree command output exceeds maxOutputBytes', 'WORKTREE_OUTPUT_TOO_LARGE') + return { stdout: stdout.text, exitCode } + } finally { + child.terminate() + await child.waitForExit() + } + }) } /** @@ -81,6 +86,7 @@ export async function runCommand( * @param signal - operation cancellation. * @param onField - synchronous consumer of each field in order; false ends the command. * @returns true when `onField` ended the command, false when it exited successfully first. + * @throws {WorktreeError} `WORKTREE_COMMAND_FAILED` or `WORKTREE_TIMEOUT`; caller cancellation propagates its reason. */ export async function scanCommand( ctx: Context, @@ -92,36 +98,38 @@ export async function scanCommand( onField: (field: string) => boolean, ): Promise { using timeout = deadline(signal, config.timeoutMs, 'WORKTREE_TIMEOUT') - const child = await spawnCommand(ctx, config, policy, cwd, argv, timeout.signal, {}, 'pipe') - try { - // The spawn spec above pipes stdout and collects stderr. - const stdout = child.stdout as Readable - stdout.setEncoding('utf8') - let pending = '' - let stopped = false - for await (const chunk of stdout as AsyncIterable) { - const fields = (pending + chunk).split('\0') - pending = fields.splice(-1).join('') - if (!fields.every(field => onField(field))) { - stopped = true - break + return await classifyTimeout(config, timeout.signal, async () => { + const child = await spawnCommand(ctx, config, policy, cwd, argv, timeout.signal, {}, 'pipe') + try { + // The spawn spec above pipes stdout and collects stderr. + const stdout = child.stdout as Readable + stdout.setEncoding('utf8') + let pending = '' + let stopped = false + for await (const chunk of stdout as AsyncIterable) { + const fields = (pending + chunk).split('\0') + pending = fields.splice(-1).join('') + if (!fields.every(field => onField(field))) { + stopped = true + break + } } - } - if (stopped) { + if (stopped) { + child.terminate() + await Promise.allSettled([child.done]) + timeout.signal.throwIfAborted() + return true + } + const outcome = await child.done + timeout.signal.throwIfAborted() + allowedExitCode(outcome, child.collected.stderr as SubprocessOutputReader, [0]) + return false + } finally { child.terminate() await Promise.allSettled([child.done]) - timeout.signal.throwIfAborted() - return true + await child.waitForExit() } - const outcome = await child.done - timeout.signal.throwIfAborted() - allowedExitCode(outcome, child.collected.stderr as SubprocessOutputReader, [0]) - return false - } finally { - child.terminate() - await Promise.allSettled([child.done]) - await child.waitForExit() - } + }) } /** Resolve, confine, and start one command whose stderr is collected within `maxOutputBytes`. */ @@ -154,11 +162,21 @@ async function spawnCommand( /** * The exit code of a command that exited with an allowed status. - * @throws when the command was signalled or exited with another status, quoting its stderr. + * @throws {WorktreeError} `WORKTREE_COMMAND_FAILED` when the command was signalled or exited with another status, quoting its stderr. */ function allowedExitCode(outcome: SubprocessOutcome, stderr: SubprocessOutputReader, allowedExitCodes: readonly number[]): number { if (outcome.exitCode === null || !allowedExitCodes.includes(outcome.exitCode)) { - throw new Error(`worktree command failed (${outcome.signal ?? outcome.exitCode}): ${stderr.readFrom(0).text.trim()}`) + throw new WorktreeError(`worktree command failed (${outcome.signal ?? outcome.exitCode}): ${stderr.readFrom(0).text.trim()}`, 'WORKTREE_COMMAND_FAILED') } return outcome.exitCode } + +/** Run one command under a deadline, converting its elapsed deadline into `WORKTREE_TIMEOUT`. */ +async function classifyTimeout(config: ProcessConfig, signal: AbortSignal, body: () => Promise): Promise { + try { + return await body() + } catch (error) { + if (timeoutOf(signal, 'WORKTREE_TIMEOUT') === undefined) throw error + throw new WorktreeError(`worktree command exceeded ${config.timeoutMs}ms; inspect the repository before retrying`, 'WORKTREE_TIMEOUT', { cause: error }) + } +} diff --git a/packages/experimental/worktree/tests/checkout-safety.spec.ts b/packages/experimental/worktree/tests/checkout-safety.spec.ts index 0ac4bd6a4d..7d4fe4a80d 100644 --- a/packages/experimental/worktree/tests/checkout-safety.spec.ts +++ b/packages/experimental/worktree/tests/checkout-safety.spec.ts @@ -121,7 +121,9 @@ describe('worktree checkout Git configuration', () => { ctx = await harness(root) const agent = testAgent(ctx, root) - await expect(ctx.worktrees.create(agent, { name: 'invalid' })).rejects.toThrow(/Any created checkout and branch are retained.*bad config line/s) + await expect(ctx.worktrees.create(agent, { name: 'invalid' })).rejects.toMatchObject({ + name: 'WorktreeError', code: 'WORKTREE_COMMAND_FAILED', message: expect.stringMatching(/Any created checkout and branch are retained.*bad config line/s) as string, + }) expect(ctx.workingDirectory.get(agent.session)).toBe(root) await access(join(root, '.agents/worktrees/invalid/.git')) @@ -135,7 +137,9 @@ describe('worktree checkout Git configuration', () => { ctx = await harness(root, { maxOutputBytes: 256 }) const agent = testAgent(ctx, root) - await expect(ctx.worktrees.create(agent, { name: 'bounded' })).rejects.toThrow('output exceeds maxOutputBytes') + await expect(ctx.worktrees.create(agent, { name: 'bounded' })).rejects.toMatchObject({ + code: 'WORKTREE_OUTPUT_TOO_LARGE', message: expect.stringContaining('output exceeds maxOutputBytes') as string, + }) expect(ctx.workingDirectory.get(agent.session)).toBe(root) await access(join(root, '.agents/worktrees/bounded/.git')) diff --git a/packages/experimental/worktree/tests/worktree.spec.ts b/packages/experimental/worktree/tests/worktree.spec.ts index 33c9b84f21..e2da8a2268 100644 --- a/packages/experimental/worktree/tests/worktree.spec.ts +++ b/packages/experimental/worktree/tests/worktree.spec.ts @@ -5,6 +5,7 @@ import { pathToFileURL } from 'node:url' import { pluginRecordOf } from '@deepseek-ai/dsh-session' import { afterEach, describe, expect, it, vi } from 'vitest' import type { Context } from '@deepseek-ai/cordis' +import { FsError } from '@deepseek-ai/dsh-fs' import WorktreeService from '../src/index.ts' import type { RestoreWorktreeRequest } from '../src/index.ts' import { contents, git, harness, repository, testAgent } from './harness.ts' @@ -186,7 +187,9 @@ describe('creating and entering retained worktrees', () => { ctx = await harness(partial) const agent = testAgent(ctx, partial) - await expect(ctx.worktrees.create(agent, { name: 'local-only' })).rejects.toThrow('worktree command failed') + await expect(ctx.worktrees.create(agent, { name: 'local-only' })).rejects.toMatchObject({ + code: 'WORKTREE_COMMAND_FAILED', message: expect.stringContaining('worktree command failed') as string, + }) expect(await git(partial, 'rev-list', '--objects', '--missing=print', 'HEAD')).toBe(missing) expect(ctx.workingDirectory.get(agent.session)).toBe(partial) @@ -210,7 +213,9 @@ describe('creating and entering retained worktrees', () => { return resolveExecutable(command, env, signal) }) const operation = service.create(testAgent(ctx, root), { name: 'cancelled' }) - const rejection = expect(operation).rejects.toThrow('worktree service disposed') + const rejection = expect(operation).rejects.toMatchObject({ + name: 'WorktreeError', code: 'WORKTREE_UNAVAILABLE', message: 'worktree service disposed', + }) let disposal: Promise | undefined try { const signal = await entered.promise @@ -227,7 +232,9 @@ describe('creating and entering retained worktrees', () => { await disposal expect(disposed).toBe(true) expect(await readdir(root)).toEqual(['.git', 'tracked.txt']) - await expect(service.create(testAgent(ctx, root, 'after-disposal'))).rejects.toThrow('worktree service disposed') + await expect(service.create(testAgent(ctx, root, 'after-disposal'))).rejects.toMatchObject({ + name: 'WorktreeError', code: 'WORKTREE_UNAVAILABLE', message: 'worktree service disposed', + }) } finally { release.resolve(undefined) await Promise.allSettled([operation, rejection, disposal]) @@ -275,24 +282,41 @@ describe('creating and entering retained worktrees', () => { const agent = testAgent(ctx, root) await git(root, 'branch', 'existing') await mkdir(join(root, '.agents/worktrees/occupied'), { recursive: true }) - await expect(ctx.worktrees.create(agent, { name: 'existing' })).rejects.toThrow('branch already exists') - await expect(ctx.worktrees.create(agent, { name: 'occupied' })).rejects.toThrow('path already exists') - await expect(ctx.worktrees.create(agent, { name: 'missing', from: 'unavailable' })).rejects.toThrow('command failed') - await expect(ctx.worktrees.create(agent, { name: '../escape' })).rejects.toThrow('relative Git branch') - await expect(ctx.worktrees.create(agent, { name: 'invalid name' })).rejects.toThrow('command failed') - await expect(ctx.worktrees.create(agent, { from: '' })).rejects.toThrow('from must name') + await expect(ctx.worktrees.create(agent, { name: 'existing' })).rejects.toMatchObject({ + name: 'WorktreeError', code: 'WORKTREE_ALREADY_EXISTS', message: expect.stringContaining('branch already exists') as string, + }) + await expect(ctx.worktrees.create(agent, { name: 'occupied' })).rejects.toMatchObject({ + name: 'WorktreeError', code: 'WORKTREE_ALREADY_EXISTS', message: expect.stringContaining('path already exists') as string, + }) + await expect(ctx.worktrees.create(agent, { name: 'missing', from: 'unavailable' })).rejects.toMatchObject({ + name: 'WorktreeError', code: 'WORKTREE_COMMAND_FAILED', + }) + await expect(ctx.worktrees.create(agent, { name: '../escape' })).rejects.toMatchObject({ + code: 'WORKTREE_INVALID_ARGUMENT', message: expect.stringContaining('relative Git branch') as string, + }) + await expect(ctx.worktrees.create(agent, { name: 'invalid name' })).rejects.toMatchObject({ + code: 'WORKTREE_INVALID_ARGUMENT', message: 'worktree name must be a valid Git branch name', + }) + await expect(ctx.worktrees.create(agent, { from: '' })).rejects.toMatchObject({ + code: 'WORKTREE_INVALID_ARGUMENT', message: expect.stringContaining('from must name') as string, + }) expect(ctx.workingDirectory.get(agent.session)).toBe(root) expect(await git(root, 'worktree', 'list', '--porcelain')).not.toContain('/occupied') expect(await readdir(join(root, '.agents/worktrees'))).toEqual(['occupied']) }) - it('retains the checkout and branch if publishing the new cwd fails', async () => { + it.each([ + ['an unclassified failure', new Error('directory publication failed'), { name: 'Error' }], + ['a classified failure', new FsError('directory publication failed', 'FS_NOT_FOUND'), { name: 'FsError', code: 'FS_NOT_FOUND' }], + ])('retains the checkout and branch if publishing the new cwd fails with %s', async (_label, failure, identity) => { const root = await repo() ctx = await harness(root) const agent = testAgent(ctx, root) await ctx.workingDirectory.ensure(agent) - vi.spyOn(ctx.workingDirectory, 'set').mockRejectedValueOnce(new Error('directory publication failed')) - await expect(ctx.worktrees.create(agent, { name: 'retained' })).rejects.toThrow('Any created checkout and branch are retained') + vi.spyOn(ctx.workingDirectory, 'set').mockRejectedValueOnce(failure) + await expect(ctx.worktrees.create(agent, { name: 'retained' })).rejects.toMatchObject({ + ...identity, message: expect.stringContaining('Any created checkout and branch are retained') as string, + }) expect(ctx.workingDirectory.get(agent.session)).toBe(root) expect(await git(root, 'branch', '--list', 'retained')).toContain('retained') expect(await contents(join(root, '.agents/worktrees/retained/tracked.txt'))).toBe('initial\n') @@ -342,11 +366,44 @@ describe('creating and entering retained worktrees', () => { const root = await repo() ctx = await harness(root, { maxOutputBytes: 1 }) const agent = testAgent(ctx, root) - await expect(ctx.worktrees.create(agent, { name: 'bounded' })).rejects.toThrow('output exceeds maxOutputBytes') + await expect(ctx.worktrees.create(agent, { name: 'bounded' })).rejects.toMatchObject({ + code: 'WORKTREE_OUTPUT_TOO_LARGE', message: 'worktree command output exceeds maxOutputBytes', + }) expect(ctx.workingDirectory.get(agent.session)).toBe(root) expect(await readdir(root)).toEqual(['.git', 'tracked.txt']) }) + it('reports an elapsed command deadline as a timeout', async () => { + const root = await repo() + ctx = await harness(root, { timeoutMs: 20 }) + const agent = testAgent(ctx, root) + vi.spyOn(ctx.subprocess, 'resolveExecutable').mockImplementation((_command, _env, signal) => new Promise((_resolve, reject) => { + signal?.addEventListener('abort', () => { reject(signal.reason as Error) }, { once: true }) + })) + await expect(ctx.worktrees.create(agent, { name: 'slow' })).rejects.toMatchObject({ + name: 'WorktreeError', code: 'WORKTREE_TIMEOUT', message: 'worktree command exceeded 20ms; inspect the repository before retrying', + }) + expect(await readdir(root)).toEqual(['.git', 'tracked.txt']) + }) + + it.each([ + ['a separate AbortError', () => new DOMException('publication aborted', 'AbortError'), 'AbortError'], + ['a distinct failure', () => new Error('publication failed during cancellation'), 'Error'], + ])('classifies %s thrown after caller cancellation', async (_label, failure, name) => { + const root = await repo() + ctx = await harness(root) + const agent = testAgent(ctx, root) + await ctx.workingDirectory.ensure(agent) + const controller = new AbortController() + vi.spyOn(ctx.workingDirectory, 'set').mockImplementationOnce(() => { + controller.abort('caller stopped') + return Promise.reject(failure()) + }) + await expect(ctx.worktrees.create(agent, { name: 'cancelled-publication' }, controller.signal)).rejects.toMatchObject({ + name, message: expect.stringContaining('Any created checkout and branch are retained') as string, + }) + }) + it('retains a caller cancellation reason when allocation is cancelled before its child starts', async () => { const root = await repo() ctx = await harness(root) @@ -358,7 +415,9 @@ describe('creating and entering retained worktrees', () => { return resolveExecutable(command, env, signal) }) try { - await expect(ctx.worktrees.create(agent, { name: 'cancelled-allocation' }, controller.signal)).rejects.toThrow('caller stopped') + await expect(ctx.worktrees.create(agent, { name: 'cancelled-allocation' }, controller.signal)).rejects.toMatchObject({ + name: 'AbortError', message: expect.stringContaining('caller stopped') as string, + }) expect(ctx.workingDirectory.get(agent.session)).toBe(root) expect(await readdir(root)).toEqual(['.git', 'tracked.txt']) } finally { @@ -458,7 +517,9 @@ describe('restoring removed worktrees', () => { const created = await ctx.worktrees.create(agent, { name: 'topic' }) const spawn = vi.spyOn(ctx.subprocess, 'spawn') - await expect(ctx.worktrees.restore(agent, created)).rejects.toThrow(`worktree path already exists: ${created.path}`) + await expect(ctx.worktrees.restore(agent, created)).rejects.toMatchObject({ + code: 'WORKTREE_ALREADY_EXISTS', message: `worktree path already exists: ${created.path}`, + }) expect(spawn).not.toHaveBeenCalled() }) @@ -469,7 +530,9 @@ describe('restoring removed worktrees', () => { const agent = testAgent(ctx, root) const path = join(root, '.agents/worktrees/vanished') const request: RestoreWorktreeRequest = { path, branch: 'vanished', baseCommit: 'f'.repeat(40), repositoryRoot: root } - await expect(ctx.worktrees.restore(agent, request)).rejects.toThrow('worktree command failed') + await expect(ctx.worktrees.restore(agent, request)).rejects.toMatchObject({ + code: 'WORKTREE_COMMAND_FAILED', message: expect.stringContaining('worktree command failed') as string, + }) await expect(access(path)).rejects.toMatchObject({ code: 'ENOENT' }) expect(await git(root, 'branch', '--list', 'vanished')).toBe('') expect(ctx.workingDirectory.get(agent.session)).toBe(root) @@ -489,7 +552,9 @@ describe('restoring removed worktrees', () => { }) try { await expect(ctx.worktrees.restore(agent, created, controller.signal)) - .rejects.toThrow(`Could not restore worktree topic at ${created.path}. Any created checkout and branch are retained. caller stopped`) + .rejects.toMatchObject({ + name: 'AbortError', message: `Could not restore worktree topic at ${created.path}. Any created checkout and branch are retained. caller stopped`, + }) await expect(access(created.path)).rejects.toMatchObject({ code: 'ENOENT' }) } finally { probe.mockRestore() @@ -509,7 +574,9 @@ describe('restoring removed worktrees', () => { await expect(service.restore(agent, request, AbortSignal.abort(new Error('cancelled')))).rejects.toThrow('cancelled') await fiber!.dispose() - await expect(service.restore(agent, request)).rejects.toThrow('worktree service disposed') + await expect(service.restore(agent, request)).rejects.toMatchObject({ + name: 'WorktreeError', code: 'WORKTREE_UNAVAILABLE', message: 'worktree service disposed', + }) expect(spawn).not.toHaveBeenCalled() expect(await readdir(root)).toEqual(['.git', 'tracked.txt']) @@ -536,7 +603,7 @@ describe('restoration validation', () => { request.repositoryRoot = join(root, '.agents') request.path = join(request.repositoryRoot, '.agents/worktrees/topic') } - await expect(ctx.worktrees.restore(agent, request)).rejects.toThrow() + await expect(ctx.worktrees.restore(agent, request)).rejects.toMatchObject({ name: 'WorktreeError', code: 'WORKTREE_INVALID_ARGUMENT' }) expect(await git(root, 'worktree', 'list', '--porcelain')).toBe(before) await expect(access(created.path)).rejects.toMatchObject({ code: 'ENOENT' }) await expect(access(join(root, 'outside'))).rejects.toMatchObject({ code: 'ENOENT' }) @@ -550,7 +617,9 @@ describe('restoration validation', () => { await git(root, 'worktree', 'lock', created.path) await rm(created.path, { recursive: true, force: true }) const before = await git(root, 'worktree', 'list', '--porcelain') - await expect(ctx.worktrees.restore(agent, created)).rejects.toThrow('worktree is locked') + await expect(ctx.worktrees.restore(agent, created)).rejects.toMatchObject({ + name: 'WorktreeError', code: 'WORKTREE_LOCKED', message: expect.stringContaining('worktree is locked') as string, + }) expect(await git(root, 'worktree', 'list', '--porcelain')).toBe(before) }) }) @@ -567,7 +636,9 @@ it('rejects a restore path redirected outside the pool by a symlink', async () = await mkdir(outside) await symlink(outside, link, 'junction') const before = await git(root, 'worktree', 'list', '--porcelain') - await expect(ctx.worktrees.restore(agent, { ...created, path: join(link, 'topic') })).rejects.toThrow('configured pool') + await expect(ctx.worktrees.restore(agent, { ...created, path: join(link, 'topic') })).rejects.toMatchObject({ + code: 'WORKTREE_INVALID_ARGUMENT', message: expect.stringContaining('configured pool') as string, + }) expect(await readdir(outside)).toEqual([]) expect(await git(root, 'worktree', 'list', '--porcelain')).toBe(before) }) diff --git a/packages/experimental/worktree/tsconfig.json b/packages/experimental/worktree/tsconfig.json index 82f74490dd..b62504acfa 100644 --- a/packages/experimental/worktree/tsconfig.json +++ b/packages/experimental/worktree/tsconfig.json @@ -55,6 +55,9 @@ }, { "path": "../../settings/settings" + }, + { + "path": "../../util/error" } ] } diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index d57fd22f7f..b191415ac8 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -5019,12 +5019,14 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ 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.' }], 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.'], }, { signature: 'async restore( agent: Agent, request: RestoreWorktreeRequest, signal?: AbortSignal, onPhase?: (phase: CreateWorktreePhase) => 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.' }], 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.'], }, { signature: 'async cleanupOf(session: Session, revision: number | null): Promise', diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 656c4e4359..a7a02be45d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -9053,6 +9053,9 @@ importers: '@deepseek-ai/dsh-browser-use': specifier: workspace:* version: link:../../browser-use/browser-use + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error '@deepseek-ai/dsh-fs-local': specifier: workspace:* version: link:../../fs/fs-local @@ -9156,6 +9159,9 @@ importers: '@deepseek-ai/dsh-browser-use': specifier: workspace:* version: link:../../browser-use/browser-use + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error '@deepseek-ai/dsh-llm': specifier: workspace:* version: link:../../llm/llm @@ -9223,6 +9229,9 @@ importers: '@deepseek-ai/dsh-commands': specifier: workspace:* version: link:../../interaction/commands + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error '@deepseek-ai/dsh-fs': specifier: workspace:* version: link:../../fs/fs @@ -9980,6 +9989,9 @@ importers: '@deepseek-ai/dsh-computer-use': specifier: workspace:* version: link:../../computer-use/computer-use + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error '@deepseek-ai/dsh-llm': specifier: workspace:* version: link:../../llm/llm @@ -11258,6 +11270,9 @@ importers: '@deepseek-ai/dsh-cua': specifier: workspace:* version: link:../cua + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error '@deepseek-ai/dsh-experimental-api-speech-to-text': specifier: workspace:* version: link:../api-speech-to-text @@ -11710,6 +11725,9 @@ importers: '@deepseek-ai/dsh-app-boot': specifier: workspace:* version: link:../../boot/app-boot + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error '@deepseek-ai/dsh-experimental-tool-subagent-oar': specifier: workspace:* version: link:../tool-subagent-oar @@ -11848,6 +11866,9 @@ importers: '@deepseek-ai/dsh-brand': specifier: workspace:* version: link:../../util/brand + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error '@deepseek-ai/dsh-llm': specifier: workspace:* version: link:../../llm/llm @@ -12462,6 +12483,9 @@ importers: '@deepseek-ai/dsh-brand': specifier: workspace:* version: link:../../util/brand + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error '@deepseek-ai/dsh-fs': specifier: workspace:* version: link:../../fs/fs diff --git a/scripts/package-dependency-policy.ts b/scripts/package-dependency-policy.ts index 9e6579715a..c6e6e8b2b9 100644 --- a/scripts/package-dependency-policy.ts +++ b/scripts/package-dependency-policy.ts @@ -97,6 +97,8 @@ const PEER_REQUIRED_HOST_EXPORTS = { // appendPluginRecord writes through the Session class's private log; pluginRecordOf is stateless. '@deepseek-ai/dsh-session': ['SESSION_FORMAT_VERSION', 'appendPluginRecord', 'pluginRecordOf'], '@deepseek-ai/dsh-session-persistence': ['SessionPersistenceNotFoundError'], + // Error classes have instance identity; CUA and Liveshare throw the registry's own copy so `instanceof` against it matches. + '@deepseek-ai/dsh-tools': ['ToolArgsError', 'ToolContextUnavailableError'], // Readers recognize a deadline's TimeoutReason only by `instanceof` against their own copy. '@deepseek-ai/dsh-timeout': ['deadline', 'timeoutOf'], } as const satisfies HostDependencyExports diff --git a/snapshots/session/hook-cc-posttool-block/session.v4.jsonl b/snapshots/session/hook-cc-posttool-block/session.v4.jsonl index a1e627dea7..67e8f5a68d 100644 --- a/snapshots/session/hook-cc-posttool-block/session.v4.jsonl +++ b/snapshots/session/hook-cc-posttool-block/session.v4.jsonl @@ -18,7 +18,7 @@ {"type":"job/settled","data":{"jobId":"{{id:1}}","owner":"{{session:1}}","kind":"bash","label":"echo HELLO","startedAt":1791427832187,"toolCall":{"callId":"call_00_VAByyMjsct4c7P6k1ysX9256","rootCallId":"call_00_VAByyMjsct4c7P6k1ysX9256"},"finishedAt":1791427832190,"status":"completed","cause":"producer","producerReported":true,"detail":"exit code: 0"}} {"type":"hook/invoked","data":{"turn":1,"point":"PostToolUse","dialect":"claude-code","handlerId":"claude-code:PostToolUse:1","matcher":"bash"}} {"type":"hook/result","data":{"turn":1,"point":"PostToolUse","handlerId":"claude-code:PostToolUse:1","decision":"block","exitCode":2,"stderrSummary":"tool output rejected by policy: retry once","durationMs":7.767333000000008}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_00_VAByyMjsct4c7P6k1ysX9256"},"toolCallId":"call_00_VAByyMjsct4c7P6k1ysX9256","content":[{"type":"text","text":"tool output rejected by policy: retry once"}],"isError":true,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_00_VAByyMjsct4c7P6k1ysX9256"},"toolCallId":"call_00_VAByyMjsct4c7P6k1ysX9256","content":[{"type":"text","text":"tool output rejected by policy: retry once"}],"isError":true,"id":"{{message:5}}"},"error":{"name":"HookError","code":"HOOK_BLOCKED"}},"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":"reasoning","text":"The first call was rejected by policy. The user said to retry once. Let me retry."},{"type":"tool-call","id":"call_00_tDV4j1p5eAeHTtQhXOfn6856","name":"bash","arguments":"{\"command\": \"echo HELLO\", \"description\": \"Echo HELLO to stdout\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"usage":{"inputTokens":59,"outputTokens":89,"cacheReadTokens":3328,"reasoningTokens":21},"stream":[{"type":"chunk","time":1791427832215,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1791427832215,"index":0,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["The"," first"," call"," was"," rejected"," by"," policy","."," The"," user"," said"," to"," ret","ry"," once","."," Let"," me"," ret","ry","."]},{"type":"chunk","time":1791427832215,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1791427832215,"index":1,"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],"id":"call_00_tDV4j1p5eAeHTtQhXOfn6856","name":"bash","args":["","{","\"","command","\"",": ","\"","echo"," HE","LL","O","\"",", ","\"","description","\"",": ","\"","E","cho"," HE","LL","O"," to"," stdout","\"","}"]},{"type":"chunk","time":1791427832215,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The first call was rejected by policy. The user said to retry once. Let me retry."}}},{"type":"chunk","time":1791427832215,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_tDV4j1p5eAeHTtQhXOfn6856","name":"bash","arguments":"{\"command\": \"echo HELLO\", \"description\": \"Echo HELLO to stdout\"}"}}},{"type":"chunk","time":1791427832215,"chunk":{"type":"usage","usage":{"inputTokens":59,"outputTokens":89,"cacheReadTokens":3328,"reasoningTokens":21}}},{"type":"chunk","time":1791427832215,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} diff --git a/snapshots/session/hook-cc-pretool-deny/session.v4.jsonl b/snapshots/session/hook-cc-pretool-deny/session.v4.jsonl index 8351089e37..7f3c3460fd 100644 --- a/snapshots/session/hook-cc-pretool-deny/session.v4.jsonl +++ b/snapshots/session/hook-cc-pretool-deny/session.v4.jsonl @@ -16,7 +16,7 @@ {"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_00_JliP571Bh0QQ8QExbSPk0080","name":"bash","arguments":"{\"command\": \"echo HELLO\", \"description\": \"Run echo HELLO\"}"}} {"type":"hook/invoked","data":{"turn":1,"point":"PreToolUse","dialect":"claude-code","handlerId":"claude-code:PreToolUse:1","matcher":"bash"}} {"type":"hook/result","data":{"turn":1,"point":"PreToolUse","handlerId":"claude-code:PreToolUse:1","decision":"block","exitCode":2,"stderrSummary":"bash is disabled by policy in this session","durationMs":4.3560419999998885}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_00_JliP571Bh0QQ8QExbSPk0080"},"toolCallId":"call_00_JliP571Bh0QQ8QExbSPk0080","content":[{"type":"text","text":"Error: bash is disabled by policy in this session"}],"isError":true,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_00_JliP571Bh0QQ8QExbSPk0080"},"toolCallId":"call_00_JliP571Bh0QQ8QExbSPk0080","content":[{"type":"text","text":"Error: bash is disabled by policy in this session"}],"isError":true,"id":"{{message:5}}"},"error":{"name":"HookError","code":"HOOK_DENIED"}},"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":"reasoning","text":"The bash tool is disabled by policy. I need to report this error verbatim back to the user."},{"type":"text","text":"The tool returned:\n\n> Error: bash is disabled by policy in this session\n\nI cannot run the command because the bash tool is disabled by policy."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"usage":{"inputTokens":167,"outputTokens":52,"cacheReadTokens":2816,"reasoningTokens":21},"stream":[{"type":"chunk","time":1788699376419,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1788699376419,"index":0,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["The"," bash"," tool"," is"," disabled"," by"," policy","."," I"," need"," to"," report"," this"," error"," verb","atim"," back"," to"," the"," user","."]},{"type":"chunk","time":1788699376419,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1788699376419,"index":1,"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],"texts":["The"," tool"," returned",":\n\n",">"," Error",":"," bash"," is"," disabled"," by"," policy"," in"," this"," session","\n\n","I"," cannot"," run"," the"," command"," because"," the"," bash"," tool"," is"," disabled"," by"," policy","."]},{"type":"chunk","time":1788699376419,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The bash tool is disabled by policy. I need to report this error verbatim back to the user."}}},{"type":"chunk","time":1788699376419,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"The tool returned:\n\n> Error: bash is disabled by policy in this session\n\nI cannot run the command because the bash tool is disabled by policy."}}},{"type":"chunk","time":1788699376419,"chunk":{"type":"usage","usage":{"inputTokens":167,"outputTokens":52,"cacheReadTokens":2816,"reasoningTokens":21}}},{"type":"chunk","time":1788699376419,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} diff --git a/snapshots/session/hook-codex-posttool-block/session.v4.jsonl b/snapshots/session/hook-codex-posttool-block/session.v4.jsonl index d5ac303791..8b28942d0e 100644 --- a/snapshots/session/hook-codex-posttool-block/session.v4.jsonl +++ b/snapshots/session/hook-codex-posttool-block/session.v4.jsonl @@ -18,7 +18,7 @@ {"type":"job/settled","data":{"jobId":"{{id:1}}","owner":"{{session:1}}","kind":"bash","label":"echo HELLO","startedAt":1791427839150,"toolCall":{"callId":"call_00_1rmSWHhVchVg7PDTmegT0421","rootCallId":"call_00_1rmSWHhVchVg7PDTmegT0421"},"finishedAt":1791427839153,"status":"completed","cause":"producer","producerReported":true,"detail":"exit code: 0"}} {"type":"hook/invoked","data":{"turn":1,"point":"PostToolUse","dialect":"codex","handlerId":"codex:PostToolUse:1","matcher":"bash"}} {"type":"hook/result","data":{"turn":1,"point":"PostToolUse","handlerId":"codex:PostToolUse:1","decision":"block","exitCode":2,"stderrSummary":"tool output rejected by codex policy: summarize instead","durationMs":3.2890840000000026}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_00_1rmSWHhVchVg7PDTmegT0421"},"toolCallId":"call_00_1rmSWHhVchVg7PDTmegT0421","content":[{"type":"text","text":"tool output rejected by codex policy: summarize instead"}],"isError":true,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_00_1rmSWHhVchVg7PDTmegT0421"},"toolCallId":"call_00_1rmSWHhVchVg7PDTmegT0421","content":[{"type":"text","text":"tool output rejected by codex policy: summarize instead"}],"isError":true,"id":"{{message:5}}"},"error":{"name":"HookError","code":"HOOK_BLOCKED"}},"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":"reasoning","text":"The tool output was rejected by codex policy. Let me quote what I got back."},{"type":"text","text":"```\ntool output rejected by codex policy: summarize instead\n```"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"usage":{"inputTokens":44,"outputTokens":39,"cacheReadTokens":3328,"reasoningTokens":18},"stream":[{"type":"chunk","time":1791427839171,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1791427839171,"index":0,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["The"," tool"," output"," was"," rejected"," by"," code","x"," policy","."," Let"," me"," quote"," what"," I"," got"," back","."]},{"type":"chunk","time":1791427839171,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1791427839171,"index":1,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["```\n","<","tool","_result",">","tool"," output"," rejected"," by"," code","x"," policy",":"," summarize"," instead","\n","```"]},{"type":"chunk","time":1791427839171,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The tool output was rejected by codex policy. Let me quote what I got back."}}},{"type":"chunk","time":1791427839171,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"```\ntool output rejected by codex policy: summarize instead\n```"}}},{"type":"chunk","time":1791427839171,"chunk":{"type":"usage","usage":{"inputTokens":44,"outputTokens":39,"cacheReadTokens":3328,"reasoningTokens":18}}},{"type":"chunk","time":1791427839171,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} diff --git a/snapshots/session/hook-codex-pretool-block/session.v4.jsonl b/snapshots/session/hook-codex-pretool-block/session.v4.jsonl index db5b065f89..fba7fa8a20 100644 --- a/snapshots/session/hook-codex-pretool-block/session.v4.jsonl +++ b/snapshots/session/hook-codex-pretool-block/session.v4.jsonl @@ -16,7 +16,7 @@ {"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_00_tv0SMeLXaTuyuVrOxnV97085","name":"bash","arguments":"{\"command\": \"echo HELLO\", \"description\": \"Run echo HELLO\"}"}} {"type":"hook/invoked","data":{"turn":1,"point":"PreToolUse","dialect":"codex","handlerId":"codex:PreToolUse:1","matcher":"bash"}} {"type":"hook/result","data":{"turn":1,"point":"PreToolUse","handlerId":"codex:PreToolUse:1","decision":"block","exitCode":2,"stderrSummary":"bash is disabled by codex policy in this session","durationMs":4.577334000000064}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_00_tv0SMeLXaTuyuVrOxnV97085"},"toolCallId":"call_00_tv0SMeLXaTuyuVrOxnV97085","content":[{"type":"text","text":"Error: bash is disabled by codex policy in this session"}],"isError":true,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_00_tv0SMeLXaTuyuVrOxnV97085"},"toolCallId":"call_00_tv0SMeLXaTuyuVrOxnV97085","content":[{"type":"text","text":"Error: bash is disabled by codex policy in this session"}],"isError":true,"id":"{{message:5}}"},"error":{"name":"HookError","code":"HOOK_DENIED"}},"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":"reasoning","text":"The bash tool is disabled by policy in this session. I need to report this result verbatim to the user."},{"type":"text","text":"The tool result I got back verbatim is:\n\n```\nError: bash is disabled by codex policy in this session\n```"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"usage":{"inputTokens":171,"outputTokens":49,"cacheReadTokens":2816,"reasoningTokens":23},"stream":[{"type":"chunk","time":1788699385953,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1788699385953,"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],"texts":["The"," bash"," tool"," is"," disabled"," by"," policy"," in"," this"," session","."," I"," need"," to"," report"," this"," result"," verb","atim"," to"," the"," user","."]},{"type":"chunk","time":1788699385953,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1788699385953,"index":1,"dt":[0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["The"," tool"," result"," I"," got"," back"," verb","atim"," is",":\n\n","```\n","Error",":"," bash"," is"," disabled"," by"," code","x"," policy"," in"," this"," session","\n","```"]},{"type":"chunk","time":1788699385954,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The bash tool is disabled by policy in this session. I need to report this result verbatim to the user."}}},{"type":"chunk","time":1788699385954,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"The tool result I got back verbatim is:\n\n```\nError: bash is disabled by codex policy in this session\n```"}}},{"type":"chunk","time":1788699385954,"chunk":{"type":"usage","usage":{"inputTokens":171,"outputTokens":49,"cacheReadTokens":2816,"reasoningTokens":23}}},{"type":"chunk","time":1788699385954,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} diff --git a/snapshots/session/packed-chunks/writer.expected.jsonl b/snapshots/session/packed-chunks/writer.expected.jsonl index 15643d81a2..d7a236f20c 100644 --- a/snapshots/session/packed-chunks/writer.expected.jsonl +++ b/snapshots/session/packed-chunks/writer.expected.jsonl @@ -16,7 +16,7 @@ {"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_00_JliP571Bh0QQ8QExbSPk0080","name":"bash","arguments":"{\"command\": \"echo HELLO\", \"description\": \"Run echo HELLO\"}"}} {"type":"hook/invoked","data":{"turn":1,"point":"PreToolUse","dialect":"claude-code","handlerId":"claude-code:PreToolUse:1","matcher":"bash"}} {"type":"hook/result","data":{"turn":1,"point":"PreToolUse","handlerId":"claude-code:PreToolUse:1","decision":"block","exitCode":2,"stderrSummary":"bash is disabled by policy in this session","durationMs":4.6690830000000005}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_00_JliP571Bh0QQ8QExbSPk0080"},"toolCallId":"call_00_JliP571Bh0QQ8QExbSPk0080","content":[{"type":"text","text":"Error: bash is disabled by policy in this session"}],"isError":true,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_00_JliP571Bh0QQ8QExbSPk0080"},"toolCallId":"call_00_JliP571Bh0QQ8QExbSPk0080","content":[{"type":"text","text":"Error: bash is disabled by policy in this session"}],"isError":true,"id":"{{message:5}}"},"error":{"name":"HookError","code":"HOOK_DENIED"}},"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":"reasoning","text":"The bash tool is disabled by policy. I need to report this error verbatim back to the user."},{"type":"text","text":"The tool returned:\n\n> Error: bash is disabled by policy in this session\n\nI cannot run the command because the bash tool is disabled by policy."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"usage":{"inputTokens":167,"outputTokens":52,"cacheReadTokens":2816,"reasoningTokens":21},"stream":[{"type":"chunk","time":1793597716898,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1793597716898,"index":0,"dt":[0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0],"texts":["The"," bash"," tool"," is"," disabled"," by"," policy","."," I"," need"," to"," report"," this"," error"," verb","atim"," back"," to"," the"," user","."]},{"type":"chunk","time":1793597716899,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1793597716899,"index":1,"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],"texts":["The"," tool"," returned",":\n\n",">"," Error",":"," bash"," is"," disabled"," by"," policy"," in"," this"," session","\n\n","I"," cannot"," run"," the"," command"," because"," the"," bash"," tool"," is"," disabled"," by"," policy","."]},{"type":"chunk","time":1793597716899,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The bash tool is disabled by policy. I need to report this error verbatim back to the user."}}},{"type":"chunk","time":1793597716899,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"The tool returned:\n\n> Error: bash is disabled by policy in this session\n\nI cannot run the command because the bash tool is disabled by policy."}}},{"type":"chunk","time":1793597716899,"chunk":{"type":"usage","usage":{"inputTokens":167,"outputTokens":52,"cacheReadTokens":2816,"reasoningTokens":21}}},{"type":"chunk","time":1793597716899,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"}