Merge origin/master into feat/session-control-message

This commit is contained in:
Dudu-0223 committed 2026-11-12 14:43:27 +08:00
commit 5eb55495d2
147 files changed
+1633 -542

No files matched your search

@@ -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
@@ -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
@@ -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`,成功结果被取消替换前延后附加的上下文仍会保留。
### 进入时已中止会在物化后短路
+1 -1
View File
@@ -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`.
+6 -6
View File
@@ -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. */
+6 -6
View File
@@ -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. */
+21 -10
View File
@@ -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) |
+21 -10
View File
@@ -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) |
+2 -2
View File
@@ -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
+1 -1
View File
@@ -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.
+1 -1
View File
@@ -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 不把正在运行的轮次归属给准入它的查看者,因此结束某个分享的授权会停止该会话正在运行的轮次,而不是只挑出该查看者的工作;内存中的查看者轮次标记只决定该轮次运行哪套工具面。
+2 -2
View File
@@ -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
+1 -1
View File
@@ -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.
+1 -1
View File
@@ -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`。因此,最终实时观察者能看到精确的执行期值,以及可安全用于后续持久追加的字段。
+2 -2
View File
@@ -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
+5 -1
View File
@@ -10,7 +10,7 @@ The calling Session's current directory selects the source repository. Creation
The default destination is `<current checkout root>/.agents/worktrees/<name>`. `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<CreatedWorktree>
@@ -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<RestoredWorktree>
+5 -1
View File
@@ -10,7 +10,7 @@
默认目标为 `<current checkout root>/.agents/worktrees/<name>`。`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<CreatedWorktree>
@@ -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<RestoredWorktree>
@@ -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
@@ -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.
@@ -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` 和自己的失败路径测试确认迁移完成。
+2 -2
View File
@@ -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
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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
+16 -2
View File
@@ -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
+30
View File
@@ -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<ToolCallId>('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<ToolCallId>('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)
@@ -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
@@ -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.
-----
@@ -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 服务器仍可使用。没有所有权时会省略继承的服务器指导;共享服务器名称目录保留常规作用域行为。
-----
@@ -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:*"
}
}
@@ -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
}
}
@@ -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<T> {
@@ -37,10 +40,17 @@ interface Entry<T> {
closing?: Promise<void>
}
/** 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<T>(operation: Promise<T>, signal: AbortSignal): Promise<T> {
return new Promise<T>((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<T> {
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<T> {
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<T> {
private closeEntry(agent: Agent, entry: Entry<T>): Promise<void> {
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()
@@ -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
@@ -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<ToolCallId>('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<SessionId>('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<SessionId>('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))
@@ -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<number>(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()
})
@@ -23,6 +23,9 @@
{
"path": "../../core/tools"
},
{
"path": "../../util/error"
},
{
"path": "../../core/scope"
},
@@ -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
@@ -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.
</details>
@@ -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 用量计量的集成均属暂缓工作。
</details>
@@ -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:*"
}
}
@@ -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'
}
}
@@ -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<BrowserResource>):
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
@@ -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<Na
const result = await stagehand.act(args.instruction, {
page: await selectPage(browser, args.pageId), timeout: config.operationTimeoutMs,
})
if (!result.data.success) throw new Error(result.data.message)
if (!result.data.success) throw new StagehandError(result.data.message, 'STAGEHAND_ACT_FAILED')
return textResult(result)
}
case 'observe': {
@@ -159,7 +159,7 @@ async function selectPage(browser: StagehandBrowser, pageId: string | undefined)
const page = pageId === undefined
? await browser.context.activePage()
: (await browser.context.pages()).find(candidate => 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
}
@@ -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<number> | 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<void> | undefined
const close = () => closing ??= (async () => {
let timeout: ReturnType<typeof setTimeout> | 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 {
@@ -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<unknown> {
signal?.throwIfAborted()
const { port1, port2 } = new MessageChannel()
const result = Promise.withResolvers<unknown>()
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()
}
@@ -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<ToolCallId>(`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<ToolCallId>('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<ToolCallId>('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<ToolCallId>('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)
@@ -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<typeof import('node:worker_threads')>()
@@ -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)
})
@@ -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<void>> = []
@@ -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 () => {
@@ -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)
})
@@ -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" },
@@ -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
@@ -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: <reason>` 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: <reason>` 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
@@ -184,7 +184,7 @@ Message from the "<plugin>" mod:
#### 模型看到什么
`{ deny: reason }` 答案把 `Error: <reason>` 渲染为工具结果。`{ result }` 答案在工具为模组注册或值满足工具输出 schema 时经工具自身的呈现器渲染,否则作为携带该文本的错误形态结果。`next` 之后改写的结果替换工具的内容文本。被丢弃的提示词以 `blocked` 结束该轮,没有模型可见的消息。持有 `tool.call` 的模组(Blast Radius)把结果推迟到按钮决定为止;模型只看到结局。
`{ deny: reason }` 答案把 `Error: <reason>` 渲染为工具结果。`{ result }` 答案在工具为模组注册或值满足工具输出 schema 时经工具自身的呈现器渲染,否则作为携带该文本的错误形态结果。拒绝记录 `ModDenied` 与 `MOD_DENIED`,错误形态的答案记录 `ModAnswered` 与 `MOD_ANSWERED`,没有 `tool.call` 钩子作答的模组注册工具调用以 `ModUnansweredError` 与 `MOD_UNANSWERED` 失败。`next` 之后改写的结果替换工具的内容文本。被丢弃的提示词以 `blocked` 结束该轮,没有模型可见的消息。持有 `tool.call` 的模组(Blast Radius)把结果推迟到按钮决定为止;模型只看到结局。
#### Token 影响
@@ -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:*"
}
}
@@ -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<string, Record<string, JsonValue>>(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<AgentBinding> {
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)
@@ -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 {
@@ -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' })
})
})
@@ -64,6 +64,9 @@
},
{
"path": "../../session/working-directory"
},
{
"path": "../../util/error"
}
]
}
@@ -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
@@ -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.
</details>
-----
@@ -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 结果适配器处理。
</details>
-----
@@ -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:*"
}
}
@@ -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
}
}
@@ -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<void> {
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)
@@ -37,6 +37,7 @@ export const fixture: {
createError?: Error
list?: (signal?: AbortSignal) => Promise<string>
call?: (name: string, args: Record<string, unknown>, signal?: AbortSignal) => Promise<unknown>
rawJson?: string
shutdown?: () => Promise<void>
} = { 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<string, unknown>
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({
@@ -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<void> = 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<ToolCallId>('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<AbortSignal>()
const settled = Promise.withResolvers<boolean>()
@@ -12,6 +12,7 @@
{ "path": "../../computer-use/computer-use" },
{ "path": "../../core/tools" },
{ "path": "../../core/system-prompt" },
{ "path": "../../util/error" },
{ "path": "../../mcp/mcp-client" }
]
}
@@ -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<ToolCallId>('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<ToolCallId>('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()
+2 -2
View File
@@ -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
+1 -1
View File
@@ -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.
+1 -1
View File
@@ -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 连接,因此旧对象必须重新选择目标。取消、超时或重新连接后均不重放输入。
+1
View File
@@ -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": {
+43 -7
View File
@@ -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<Record<
function executionAgent(execution: Readonly<ToolExecution>): 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<T>(schema: z.ZodType<T>, 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<CuaExecution>, 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<CuaExecution>,
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<Agent>()
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)
}
@@ -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'
}
}
@@ -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)
})
@@ -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
@@ -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 |
@@ -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/*` 载荷类型 |
@@ -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'
@@ -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'
@@ -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
@@ -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
@@ -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 影响
@@ -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<PreToolDecision> => {
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).
@@ -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 () => {
@@ -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
+1 -1
View File
@@ -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
@@ -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 影响
+10 -2
View File
@@ -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).
@@ -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 () => {
@@ -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
+1 -1
View File
@@ -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.
+1 -1
View File
@@ -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)。
+6 -2
View File
@@ -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": {
@@ -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<FsEditOutcome>
}
/** 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.
@@ -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' } }
}
@@ -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<Record<Exclude<ForkToolRefusal, 'fork-path-outside-workspace'>, 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<Context> {
*/
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<Context> {
/** 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<Context>(
input: {
readonly childSessionId: string
readonly ceiling: ForkCeiling
readonly guard: (execution: ForkToolExecution) => string | undefined
readonly guard: (execution: ForkToolExecution) => ForkToolDenial | undefined
readonly verdictSource: (execution: ForkToolExecution) => Promise<void>
},
ports: ChildEnforcementPorts<Context>,
@@ -240,7 +252,7 @@ export function installChildEnforcement<Context>(
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
@@ -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' },
}
}
@@ -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<string, RegisteredTool>()
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, unknown>) => string | undefined) | undefined
let guardFunction: ((execution: Record<string, unknown>) => 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, unknown>) => string | undefined) => {
guard: vi.fn((guard: (execution: Record<string, unknown>) => 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, unknown>) => string | undefined
const guard = h.guard() as (execution: Record<string, unknown>) => 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<string, unknown>, next: () => unknown) => Promise<unknown>) | 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, unknown>) => string | undefined
const guard = h.guard() as (execution: Record<string, unknown>) => 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, unknown>) => string | undefined
const guard = h.guard() as (execution: Record<string, unknown>) => 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<string, RegisteredTool>(deployments)
const installed = new Map<string, RegisteredTool>()
let guardFunction: ((execution: Record<string, unknown>) => string | undefined) | undefined
const guard = vi.fn((fn: (execution: Record<string, unknown>) => string | undefined) => {
let guardFunction: ((execution: Record<string, unknown>) => ForkToolDenial | undefined) | undefined
const guard = vi.fn((fn: (execution: Record<string, unknown>) => 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'))
})
})
@@ -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<PreToolDecision>) => Promise<PreToolDecision>
result?: (execution: ForkToolExecution) => void
readonly definitions: Map<string, ToolDefinition>
} = { 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)
@@ -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<void>) | 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<object, ((exec: ForkToolExecution) => string | undefined)[]>()
const guards = new Map<object, ((exec: ForkToolExecution) => 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'))
})
})
Loaded 100 of 147 files, more files were not shown because too many files have changed in this diff. Show more