@deepseek-ai/dsh-subagent-claude-code 0.1.0-rc.6 → 0.1.0-rc.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.i18n.yaml CHANGED
@@ -2,5 +2,5 @@
2
2
  # side as of the last confirmed-consistent state. Both languages carry equal authority;
3
3
  # after editing either side, bring the other along and re-record with:
4
4
  # pnpm run verify-translation-pairing --write packages/subagent/subagent-claude-code/README.md
5
- README.md: 17b14e847baea3eadda7129b5e49f5e65b668cc8
6
- README.zh.md: 5c970f623c794e91ec2c4a6b2c71c6b28c887485
5
+ README.md: 0260d9c82dee82541e5b60ff7fe2c323cf9b7331
6
+ README.zh.md: 0a301ff53589112afe3f7f3d42d334fbebd04083
package/README.md CHANGED
@@ -2,21 +2,21 @@
2
2
 
3
3
  English | [中文](README.zh.md)
4
4
 
5
- This package registers the fixed `claude-code` subagent provider. Each accepted run invokes the official Claude Agent SDK in the delegating Session's workspace, resolves the native `claude` executable through the shared subprocess service, submits one self-contained text task, and returns only the final answer through the shared [`dsh-subagent`](../subagent/README.md) result contract.
5
+ This package registers a Profile-named Claude Code subagent provider whose default name is `claude-code`. Each accepted run invokes the official Claude Agent SDK in the delegating Session's workspace, lets the pinned SDK select its installed platform CLI, submits one self-contained text task, and returns either the strict final answer or a separate safe failure diagnostic through the shared [`dsh-subagent`](../subagent/README.md) result contract.
6
6
 
7
7
  ## Start and ownership
8
8
 
9
9
  `start(request)` accepts only a non-empty sequence of text blocks and derives the child cwd from the parent Session. It creates one private `AbortController`, calls the official SDK `query()`, and publishes the run only after the SDK's `spawnClaudeCodeProcess` hook has supplied a live CLI handle owned by [`dsh-subprocess`](../../subprocess/subprocess/README.md). A failure or cancellation before publication closes the query, terminates any acquired process tree, waits for it to exit, and rejects `start()`.
10
10
 
11
- The SDK receives the exact concatenated text task. The provider iterates the complete SDK message stream and accepts only a `result` message with `subtype: "success"`, `is_error: false`, and a nonblank `result`, followed by normal iterator completion. Every SDK error subtype, an error-marked success, a missing answer, iterator failure, protocol failure, or process failure maps to `error`; the provider produces neither `max-tokens` nor `refusal`.
11
+ The SDK receives the exact concatenated text task. The provider iterates the complete SDK message stream and accepts only a `result` message with `subtype: "success"`, `is_error: false`, and a nonblank `result`, followed by normal iterator completion. Every failure still maps to `error`: the four error subtypes in Agent SDK 0.3.220 retain their exact category, an error-marked or blank success becomes `invalid-success`, a missing result becomes `missing-result`, an unclassified query failure becomes `unknown`, and an early CLI exit becomes `process-exit`. The diagnostic also names the current `query-start`, `query-run`, `process`, or `teardown` stage and independently includes an observed exit code and signal. The provider produces neither `max-tokens` nor `refusal`.
12
12
 
13
- Local cancellation wins the result race and maps to `aborted`. `dispose()` is idempotent: it aborts the run, asks the SDK query to close, invokes the shared process-tree termination escalation, and waits for whole-tree exit. SDK graceful close expresses protocol intent; the subprocess handle remains the authority for process quiescence. Result failure and independent teardown failure remain separate.
13
+ Local cancellation wins the result race and maps to `aborted` without a failure diagnostic. `dispose()` is idempotent: it aborts the run, asks the SDK query to close, invokes the shared process-tree termination escalation, and waits for whole-tree exit. SDK graceful close expresses protocol intent; the subprocess handle remains the authority for process quiescence. Startup and teardown rejections expose the same fixed safe stage and process facts through their Error message, while the original product or Host error remains on the internal cause chain and in the Provider's Host log. Result failure and independent teardown failure remain separate.
14
14
 
15
15
  ## Native settings and interaction
16
16
 
17
- The provider deliberately omits the SDK `settingSources` option. The official SDK therefore reads the host's normal user, project, and local Claude settings relative to the parent Session cwd, including native account state and product configuration. The provider neither copies nor filters those files and does not create or modify login state.
17
+ The provider deliberately omits the SDK `settingSources` option. The official SDK therefore reads the host's normal user, project, and local Claude settings relative to the parent Session cwd, including native account state and product configuration. The provider neither copies nor filters those files and does not create or modify login state. The Profile-selected `permissionMode` is the one query-level override: Claude Code still owns its settings and sandbox, while the selected native mode decides how this unattended query handles permission checks.
18
18
 
19
- Each query sets `persistSession: false` and disables `AskUserQuestion`. It supplies no `canUseTool`, elicitation, or dialog callback, so unattended interactions fail through the SDK instead of waiting for a user interface this provider does not own.
19
+ Each query sets `persistSession: false` and disables `AskUserQuestion`. Except in bypass mode, `canUseTool` immediately denies requests that still require human approval. Plan mode also places `ExitPlanMode` in the SDK's `disallowedTools`, so native settings cannot pre-approve a transition back to execution and the model must return the completed plan as its final answer. MCP elicitation is declined, the known refusal fallback dialog is cancelled, and undeclared dialog kinds use the SDK's no-dialog failure behavior. These decisions never wait for a user interface. When both facts contribute to a failed run, `SubagentResult.diagnostic` contains the structured failure line first and the latest safe permission decision second; the shared result boundary limits the complete text to 4096 UTF-8 bytes. Successful and locally cancelled runs expose neither captured fact.
20
20
 
21
21
  ## Capabilities and context
22
22
 
@@ -26,33 +26,83 @@ The provider advertises no optional start-time capabilities and reports `inherit
26
26
 
27
27
  | Key | Default | Meaning |
28
28
  |---|---|---|
29
+ | `providerName` | `claude-code` | Non-empty registry name on `ctx.subagents`; each mounted instance needs a unique value. |
29
30
  | `env` | `{}` | Explicit SDK/CLI environment layered over the shared credential-scrubbed parent environment. |
31
+ | `permissionMode` | `dontAsk` | Native non-interactive permission policy fixed for every run from this Provider instance. |
30
32
  | `disposeGraceMs` | `3000` | Positive finite grace in milliseconds, no greater than [`MAX_TIMER_DELAY_MS`](../../util/timeout/README.md), between the shared process-tree owner's termination tiers; disposal then waits for whole-tree exit. |
31
33
 
32
- Production resolves `claude` from the subprocess execution world's credential-scrubbed `PATH`, with explicit `env` entries applied, and passes the resulting path to the SDK as `pathToClaudeCodeExecutable`. On Windows, a resolved `.cmd` or `.bat` path is carried as a quoted, per-spawn environment value that `cmd.exe /v:off` expands once, so valid path metacharacters remain data. The pinned SDK's fixed flags then occupy cmd's command tail and contain no cmd metacharacters; they are not ordinary Windows argv. Native settings and authentication remain authoritative. The plugin does not install another CLI, select a model, create a product home, log in, or probe an account. Credential-shaped ambient variables are removed before the explicit `env` overlay is applied, so an API key or token intended for the child must be supplied there. Non-credential endpoint variables such as `ANTHROPIC_BASE_URL`, along with ordinary ambient values such as `PATH` and `HOME`, remain inherited unless overridden.
34
+ | `permissionMode` value | Native behavior |
35
+ |---|---|
36
+ | `dontAsk` | Deny operations that are not already authorized instead of prompting. |
37
+ | `acceptEdits` | Accept file edits; any remaining permission prompt is denied by the unattended callback. |
38
+ | `auto` | Let Claude Code's native classifier allow or deny permission requests. |
39
+ | `plan` | Run in native planning mode, deny execution approval, and return the completed plan as the final answer. |
40
+ | `bypassPermissions` | Explicitly set the SDK's dangerous confirmation and bypass permission checks. |
33
41
 
34
- Shipped profiles load this provider once on the host and start no Claude process until a tool call. Full Agent Presets carry the tool row below with `disabled: true`; copy a preset and remove that field to expose `subagent_claude_code` only to agents composed from the copy. A custom host composition can still use both rows directly.
42
+ Production omits `pathToClaudeCodeExecutable`, so Agent SDK 0.3.220 selects the matching native `claude` or `claude.exe` from its own platform package and passes that absolute command through the custom-spawn hook to `dsh-subprocess`. The provider does not inspect `PATH`, implement platform selection, or fall back to a host `claude`. Native settings and authentication remain authoritative, while `permissionMode` is the only query-level policy override. The plugin does not select a model, create a product home, log in, or probe an account. Credential-shaped ambient variables are removed before the explicit `env` overlay is applied, so an API key or token intended for the child must be supplied there. Non-credential endpoint variables such as `ANTHROPIC_BASE_URL`, along with ordinary ambient values such as `PATH` and `HOME`, remain inherited unless overridden; `PATH` does not choose the Claude executable.
43
+
44
+ This package is an optional Profile Bundle. Install it into the target Profile, then restart that Profile; installation brings the pinned Agent SDK and one compatible platform CLI payload into that Profile, while the declared `cordis.patch.yml` layer registers only the dormant `claude-code` Host provider and starts no Claude process. Removing the package withdraws that provider and its private runtime closure on the next Profile start.
45
+
46
+ ```sh
47
+ dsh plugin --profile <name> add @deepseek-ai/dsh-subagent-claude-code
48
+ dsh plugin --profile <name> remove @deepseek-ai/dsh-subagent-claude-code
49
+ dsh --profile <name>
50
+ ```
51
+
52
+ Installation controls Host availability, not model permission. The Bundle supplies the dormant default `claude-code` row; the Profile may replace that row's complete config or mount additional rows with distinct `providerName`, `permissionMode`, and `env` values. Loading an instance starts no Claude process until a bound tool calls it. Each `dsh-tool-subagent` row names one provider and needs its own `toolName`, so the model sees static tools rather than a dynamic provider selector. Full Agent Presets carry a matching default product tool row with `disabled: true`; copy a preset and remove that field to expose `subagent_claude_code` only to agents composed from the copy. Its `one-shot` policy keeps omitted or `false` `run_in_background` calls in the foreground, while explicit `true` returns a parent-owned Job id for `job_output` or `job_kill`. The base host and full presets already provide the generic Job registry and controls.
53
+
54
+ The standalone composition below shows the complete explicit capability. A Profile based on `@deepseek-ai/dsh-base` keeps its existing Job rows, adds the product provider and tool rows, and does not mount duplicate Job services.
35
55
 
36
56
  ```yaml
37
- - id: subagent-claude-code
57
+ - id: subagent-claude-safe
58
+ name: '@deepseek-ai/dsh-subagent-claude-code'
59
+ config:
60
+ providerName: claude-safe
61
+ permissionMode: dontAsk
62
+ env:
63
+ ANTHROPIC_API_KEY: !!js process.env.ANTHROPIC_API_KEY
64
+
65
+ - id: subagent-claude-bypass
38
66
  name: '@deepseek-ai/dsh-subagent-claude-code'
39
67
  config:
68
+ providerName: claude-bypass
69
+ permissionMode: bypassPermissions
40
70
  env:
41
71
  ANTHROPIC_API_KEY: !!js process.env.ANTHROPIC_API_KEY
72
+ ```
73
+
74
+ ```yaml
75
+ - id: jobs
76
+ name: '@deepseek-ai/dsh-jobs-local'
42
77
 
43
- - id: tool-subagent-claude-code
78
+ - id: tool-jobs
79
+ name: '@deepseek-ai/dsh-tool-jobs'
80
+
81
+ - id: tool-subagent-claude-safe
44
82
  name: '@deepseek-ai/dsh-tool-subagent'
45
83
  disabled: true
46
84
  config:
47
- provider: claude-code
48
- toolName: subagent_claude_code
49
- enableRunInBackground: false
85
+ provider: claude-safe
86
+ toolName: subagent_claude_safe
87
+ backgroundMode: one-shot
88
+ maxDepth: provider-managed
89
+
90
+ - id: tool-subagent-claude-bypass
91
+ name: '@deepseek-ai/dsh-tool-subagent'
92
+ config:
93
+ provider: claude-bypass
94
+ toolName: subagent_claude_bypass
95
+ backgroundMode: one-shot
50
96
  maxDepth: provider-managed
51
97
  ```
52
98
 
53
99
  ## Product compatibility and evidence
54
100
 
55
- The runtime dependency is pinned to `@anthropic-ai/claude-agent-sdk@0.3.220`. Production runs the native `claude` installation. The keyless real-product test uses the SDK-distributed Claude Code 2.1.220 CLI as a deterministic fixture, routed through the same native executable-resolution and Windows batch-shim path; it does not claim compatibility with every independently installed version. Loader composition proves that both product packages coexist without starting either product.
101
+ The runtime dependency is pinned to `@anthropic-ai/claude-agent-sdk@0.3.220`, whose eight platform packages carry Claude Code 2.1.220. A normal install selects one payload for the current OS, CPU, and Linux libc. For the current darwin-arm64 payload, `npm pack --dry-run --json` reports 74,858,812 packed bytes and 256,908,856 unpacked bytes; other platforms may differ, and these values are disclosure rather than an installation threshold. The keyless real-product test runs the SDK-selected CLI against a loopback Messages fixture and asserts that the shared subprocess argv begins with that platform package's native executable. Loader composition proves that installing the Bundle registers only the dormant Claude Code provider and starts no product process.
102
+
103
+ Installing with optional dependencies omitted, using an unsupported platform, or losing the selected payload leaves provider registration dormant but makes the first delegation fail at the SDK startup boundary. The caller receives the safe `query-start` / `unknown` failure fact; the native payload error remains only on the internal cause chain and in the Provider's Host log. The provider neither probes a host CLI nor retries with one.
104
+
105
+ Loader composition proves that the Bundle default, two additional named Claude instances, and the existing Codex package coexist without starting either product.
56
106
 
57
107
  The project owner's identity-scoped distribution authorization covers the official SDK and the official CLI/platform payloads declared by each SDK version. [`THIRD_PARTY_NOTICES.md`](../../../THIRD_PARTY_NOTICES.md) discloses the current optional payload closure without classifying its declared terms as permissive; unrelated non-permissive runtime dependencies continue to fail the notices gate.
58
108
 
@@ -62,7 +112,7 @@ The project owner's identity-scoped distribution authorization covers the offici
62
112
 
63
113
  #### What the model sees
64
114
 
65
- The Claude Code child receives the standalone text task as one fresh SDK query. Its workspace is the parent Session cwd, while its model, system instructions, tools, permissions, and authentication come from the host's native Claude settings and product installation.
115
+ The Claude Code child receives the standalone text task as one fresh SDK query. Its workspace is the parent Session cwd; its model, system instructions, tools, sandbox, and authentication come from native Claude settings, the selected Provider instance's Profile configuration fixes the query's environment and non-interactive permission mode, and the executable version comes from the Bundle's pinned SDK platform payload.
66
116
 
67
117
  #### Token effect
68
118
 
@@ -72,27 +122,28 @@ The child pays for an independent Claude Code context and query. Child tokens do
72
122
 
73
123
  Independent of the parent request cache. Reuse depends only on Claude Code's own model, instructions, tools, native settings, and fresh query.
74
124
 
75
- ### Parent tool result, indirectly
125
+ ### Parent scheduling and results, indirectly
76
126
 
77
127
  #### What the model sees
78
128
 
79
- Through `dsh-tool-subagent`, the parent sees only the strict final Claude Code answer or the consumer's exact error for a non-completed result. Claude Code reasoning, tool activity, intermediate messages, stderr, workspace diffs, usage, and product ids are not copied into the parent Session.
129
+ Through `dsh-tool-subagent`, a foreground call gives the parent the strict final Claude Code answer or an error containing the stop reason and optional safe diagnostic for a non-completed result. That diagnostic can distinguish the fixed SDK error category, lifecycle stage, and observed process outcome without copying raw product text. A background call first returns a Job id; the generic job controls later deliver a completion notice, expose the same final answer or failed status detail through `job_output`, and let `job_kill` request cancellation. Claude Code reasoning, tool activity, intermediate messages, stderr, workspace diffs, usage, product ids, tool inputs, and raw protocol payloads are not copied into the parent Session.
80
130
 
81
131
  #### Token effect
82
132
 
83
- Parent input grows only by the final answer or error retained in the tool result. This provider adds no parent tool schema by itself.
133
+ Foreground input grows by the retained final answer or error. Background input also includes the start acknowledgement, completion notice, and any `job_output`, `job_kill`, or later status results; child tokens still do not enter the parent context. This provider adds no parent tool schema by itself.
84
134
 
85
135
  #### KV Cache effect
86
136
 
87
- Append-only: the new tool result follows the reusable parent request prefix.
137
+ Append-only: foreground adds one result after the reusable parent prefix, while background appends the Job acknowledgement, notice, and later control or collection results. Background scheduling can add a notice-driven turn, but none of these messages rewrites the earlier prefix.
88
138
 
89
139
  ## Known Limitations and Deferred Work
90
140
 
91
141
  - **One fresh query and process per run** — there is no continuation, resume, pooling, progress stream, or product-session persistence.
142
+ - **Static instance selection** — Profile rows fix provider names and tool bindings; calls cannot choose a provider dynamically, and every exposed tool needs a unique `toolName`.
92
143
  - **Host settings are intentionally authoritative** — project and user settings can change model, tools, and behavior; the provider does not provide a filtered or hermetic production mode.
93
- - **Product installation and account state remain native** — a missing or incompatible `claude`, configuration error, or authentication failure is surfaced as a startup or run error; the plugin provides no installer or login flow.
94
- - **The SDK platform CLI remains in the install closure** — production ignores it in favor of the host `claude`, but the current SDK optional dependency is still installed and supplies the keyless compatibility fixture. Removing that payload belongs to the separate product installation-closure follow-up.
95
- - **No human interaction path** — `AskUserQuestion` is disabled and other interactive callbacks are absent, so tasks requiring new approval or input fail instead of suspending.
96
- - **Final text only** — reasoning, intermediate messages, tool traffic, usage, stderr, and workspace diffs remain product-local.
144
+ - **Authentication and account state remain native** — the Bundle supplies the CLI but does not create an account, log in, or rewrite Claude settings; configuration and authentication failures surface with their lifecycle stage and the safe `unknown` fallback rather than a separate public classification.
145
+ - **The SDK platform payload is required at delegation time** — installs that omit optional dependencies, unsupported platforms, and missing or damaged payloads fail at the first query; there is no host-CLI fallback.
146
+ - **No human interaction path** — `AskUserQuestion` is disabled, permission prompts are denied, MCP elicitation is declined, and blocking dialogs fail closed instead of suspending.
147
+ - **Assistant payload is final text only** — a failed run may additionally expose the separate safe diagnostic; reasoning, intermediate messages, tool traffic, usage, stderr, and workspace diffs remain product-local, while generic Job ids, notices, and status come from the shared job runtime.
97
148
  - **No optional shared capabilities** — output schemas, child personas, tool filtering, and harness depth enforcement are rejected by the shared service for this provider.
98
149
  - **No wall-clock timeout or side-effect rollback** — the caller cancels long work, and files or external systems changed before cancellation are not restored.
package/README.zh.md CHANGED
@@ -2,21 +2,21 @@
2
2
 
3
3
  [English](README.md) | 中文
4
4
 
5
- 本包(package)注册固定的 `claude-code` subagent 提供方。每次接受运行请求后,它都会在发起委托的会话工作区中调用官方 Claude Agent SDK,通过共享子进程服务解析原生 `claude` 可执行文件,提交一个自包含的文本任务,并通过共享的 [`dsh-subagent`](../subagent/README.md) 结果约定仅返回最终答案。
5
+ 本包(package)注册由 Profile 命名、默认名称为 `claude-code` 的 Claude Code subagent 提供方。每次接受运行请求后,它都会在发起委托的会话工作区中调用官方 Claude Agent SDK,让锁定版本的 SDK 选择随包安装的平台 CLI,提交一个自包含的文本任务,并通过共享的 [`dsh-subagent`](../subagent/README.md) 结果约定返回严格的最终答案或独立的安全失败诊断。
6
6
 
7
7
  ## 启动与所有权
8
8
 
9
9
  `start(request)` 只接受非空的文本块序列,并根据父会话确定子级 cwd。它会创建一个私有 `AbortController`,调用官方 SDK 的 `query()`,并仅在 SDK 的 `spawnClaudeCodeProcess` 钩子已经提供由 [`dsh-subprocess`](../../subprocess/subprocess/README.md) 管理的活动 CLI 句柄后发布此次运行。若在发布前发生失败或取消,它会关闭 query、终止所有已取得的进程树并等待其退出,然后拒绝 `start()` 调用。
10
10
 
11
- SDK 接收由文本块原样拼接成的任务。提供方会完整迭代 SDK 消息流,而且只接受满足以下条件的 `result` 消息:其 `subtype: "success"`、`is_error: false` 且 `result` 非空白,之后迭代器还须正常结束。所有 SDK 错误子类型、标记为错误的成功消息、缺失答案、迭代器失败、协议失败或进程失败都映射为 `error`;该提供方不会产生 `max-tokens` 或 `refusal`。
11
+ SDK 接收由文本块原样拼接成的任务。提供方会完整迭代 SDK 消息流,而且只接受满足以下条件的 `result` 消息:其 `subtype: "success"`、`is_error: false` 且 `result` 非空白,之后迭代器还须正常结束。所有失败仍映射为 `error`:Agent SDK 0.3.220 的四种错误子类型保留准确类别;标记为错误或内容空白的成功消息成为 `invalid-success`;缺失结果成为 `missing-result`;未分类的 query 失败成为 `unknown`;CLI 提前退出成为 `process-exit`。诊断还会注明当前 `query-start`、`query-run`、`process` 或 `teardown` 阶段,并分别保留已观测到的退出码与信号。该提供方不会产生 `max-tokens` 或 `refusal`。
12
12
 
13
- 本地取消会在结果竞态中胜出并映射为 `aborted`。`dispose()`(资源释放)具有幂等性:它会中止此次运行、请求 SDK query 关闭、调用共享的进程树逐级终止机制,并等待整棵进程树退出。SDK 的优雅关闭只表达协议意图;进程是否完全停稳仍以子进程句柄为准。结果失败与独立的清理失败仍彼此分离。
13
+ 本地取消会在结果竞态中胜出并映射为 `aborted`,且不附带失败诊断。`dispose()`(资源释放)具有幂等性:它会中止此次运行、请求 SDK query 关闭、调用共享的进程树逐级终止机制,并等待整棵进程树退出。SDK 的优雅关闭只表达协议意图;进程是否完全停稳仍以子进程句柄为准。启动与清理拒绝会在 Error 消息中公开同样固定的安全阶段和进程事实,而原始产品或 Host 错误只保留在内部 cause 链与提供方的 Host 日志中。结果失败与独立的清理失败仍彼此分离。
14
14
 
15
15
  ## 原生设置与交互
16
16
 
17
- 提供方故意省略 SDK 的 `settingSources` 选项。因此,官方 SDK 会相对于父会话 cwd 读取宿主机常规的用户、项目和本地 Claude 设置,包括原生账户状态与产品配置。提供方既不复制也不过滤这些文件,也不会创建或修改登录状态。
17
+ 提供方故意省略 SDK 的 `settingSources` 选项。因此,官方 SDK 会相对于父会话 cwd 读取宿主机常规的用户、项目和本地 Claude 设置,包括原生账户状态与产品配置。提供方既不复制也不过滤这些文件,也不会创建或修改登录状态。Profile 选择的 `permissionMode` 是唯一的 query 级覆盖:Claude Code 仍拥有其设置与沙箱,而所选原生模式决定这个无人值守 query 如何处理权限检查。
18
18
 
19
- 每次 query 都设置 `persistSession: false` 并禁用 `AskUserQuestion`。提供方不设置 `canUseTool`、elicitation 或对话回调,因此无人值守交互会经 SDK 失败,而不会等待本提供方不负责的用户界面。
19
+ 每次 query 都设置 `persistSession: false` 并禁用 `AskUserQuestion`。除 bypass 模式外,`canUseTool` 会立即拒绝仍需人工审批的请求。Plan 模式还会把 `ExitPlanMode` 放入 SDK 的 `disallowedTools`,因此原生 settings 无法预先放行回到执行模式的转换,模型必须把完整计划作为最终答案返回。MCP elicitation 会被拒绝,已知的拒绝回退对话会被取消,未声明的对话类型则使用 SDK 的无对话失败行为。这些决定都不会等待用户界面。当两类事实共同参与一次失败运行时,`SubagentResult.diagnostic` 会先写入结构化失败行,再写入最新的安全权限决定;共享结果边界会把完整文本限制在 4096 个 UTF-8 字节以内。成功运行与本地取消都不会公开已捕获的事实。
20
20
 
21
21
  ## 能力与上下文
22
22
 
@@ -26,33 +26,83 @@ SDK 接收由文本块原样拼接成的任务。提供方会完整迭代 SDK
26
26
 
27
27
  | 配置键 | 默认值 | 含义 |
28
28
  |---|---|---|
29
+ | `providerName` | `claude-code` | `ctx.subagents` 中的非空注册名称;每个已挂载实例都需要唯一值。 |
29
30
  | `env` | `{}` | 显式指定的 SDK/CLI 环境,叠加在由共享机制清除凭证后的父环境之上。 |
31
+ | `permissionMode` | `dontAsk` | 为该提供方实例的每次运行固定原生非交互权限策略。 |
30
32
  | `disposeGraceMs` | `3000` | 共享进程树责任方各终止层级之间的宽限期,单位为毫秒且须为正有限值,并不得大于仓库共享的 [`MAX_TIMER_DELAY_MS`](../../util/timeout/README.md);随后资源释放会等待整棵进程树退出。 |
31
33
 
32
- 生产环境从子进程执行世界清除凭证后的 `PATH` 解析 `claude`,再应用显式 `env` 条目,并把所得路径作为 `pathToClaudeCodeExecutable` 交给 SDK。在 Windows 上,解析到的 `.cmd` 或 `.bat` 路径会作为带引号、仅供本次 spawn 使用的环境值交给 `cmd.exe /v:off` 展开一次,因此合法路径中的元字符仍只是数据。锁定版本的 SDK 随后把固定命令行选项放在 cmd 的命令尾部;这些选项不含 cmd 元字符,也并不是普通的 Windows argv。原生设置与身份验证继续是权威来源。本插件不安装另一份 CLI、不选择模型、不创建产品主目录、不执行登录,也不探测账户。具有凭证特征的环境变量会在显式 `env` 覆盖生效前被清除,因此供子进程使用的 API 密钥或 token 必须在该配置中显式提供。除非被覆盖,`ANTHROPIC_BASE_URL` 等非凭证端点变量以及 `PATH` 和 `HOME` 等普通环境变量仍会被继承。
34
+ | `permissionMode` 值 | 原生行为 |
35
+ |---|---|
36
+ | `dontAsk` | 不弹出提示,直接拒绝尚未获授权的操作。 |
37
+ | `acceptEdits` | 接受文件编辑;其余权限提示由无人值守回调拒绝。 |
38
+ | `auto` | 由 Claude Code 原生分类器允许或拒绝权限请求。 |
39
+ | `plan` | 使用原生规划模式,拒绝执行审批,并把完整计划作为最终答案返回。 |
40
+ | `bypassPermissions` | 显式设置 SDK 的危险确认并跳过权限检查。 |
33
41
 
34
- 随附 profile 会在宿主上加载一次该提供方,而且在工具被调用前不会启动 Claude 进程。完整 Agent Preset 携带下列工具行并设置 `disabled: true`;复制一个 preset 后删除该字段,即可只向由该副本组装的 agent 暴露 `subagent_claude_code`。自定义宿主组装仍可直接使用两条配置行。
42
+ 生产环境会省略 `pathToClaudeCodeExecutable`,因此 Agent SDK 0.3.220 会从自己的平台包中选择匹配的原生 `claude` 或 `claude.exe`,再通过 custom-spawn 钩子把该绝对命令交给 `dsh-subprocess`。提供方不会检查 `PATH`、重复实现平台选择,也不会回退到宿主 `claude`。原生设置与身份验证继续是权威来源,而 `permissionMode` 是唯一的 query 级策略覆盖。本插件不选择模型、不创建产品主目录、不执行登录,也不探测账户。具有凭证特征的环境变量会在显式 `env` 覆盖生效前被清除,因此供子进程使用的 API 密钥或 token 必须在该配置中显式提供。除非被覆盖,`ANTHROPIC_BASE_URL` 等非凭证端点变量以及 `PATH` 和 `HOME` 等普通环境变量仍会被继承;`PATH` 不参与选择 Claude 可执行文件。
43
+
44
+ 本包是可选的 Profile Bundle。将它安装进目标 Profile 后重启该 Profile;安装会把锁定的 Agent SDK 与一个兼容的平台 CLI 载荷带入该 Profile,而包所声明的 `cordis.patch.yml` 层只注册休眠的 `claude-code` Host provider,不会启动 Claude 进程。移除该包后,下一次 Profile 启动会撤回这一 provider 及其私有运行时闭包。
45
+
46
+ ```sh
47
+ dsh plugin --profile <name> add @deepseek-ai/dsh-subagent-claude-code
48
+ dsh plugin --profile <name> remove @deepseek-ai/dsh-subagent-claude-code
49
+ dsh --profile <name>
50
+ ```
51
+
52
+ 安装决定 Host 可用性,而不是模型权限。Bundle 会提供休眠的默认 `claude-code` 配置项;Profile 可以替换该配置项的完整 config,也可以挂载更多具有不同 `providerName`、`permissionMode` 与 `env` 的配置项。加载实例本身不会在绑定工具调用前启动 Claude 进程。每个 `dsh-tool-subagent` 配置项指定一个提供方,并需要独立的 `toolName`,因此模型看到的是静态工具,而不是动态提供方选择器。完整 Agent Preset 携带对应的默认产品工具行并设置 `disabled: true`;复制一个 preset 后删除该字段,即可只向由该副本组装的 agent 暴露 `subagent_claude_code`。其 `one-shot` 策略会让省略 `run_in_background` 或传入 `false` 的调用继续在前台等待,而显式传入 `true` 会返回由父 agent 拥有的 Job ID,供 `job_output` 或 `job_kill` 使用。base host(基础宿主)与完整 preset 已提供通用作业注册表和控制工具。
53
+
54
+ 下列独立组装展示完整的显式能力。基于 `@deepseek-ai/dsh-base` 的 Profile 保留已有 Job 配置项,新增产品提供方与工具配置项,而且不重复挂载 Job 服务。
35
55
 
36
56
  ```yaml
37
- - id: subagent-claude-code
57
+ - id: subagent-claude-safe
58
+ name: '@deepseek-ai/dsh-subagent-claude-code'
59
+ config:
60
+ providerName: claude-safe
61
+ permissionMode: dontAsk
62
+ env:
63
+ ANTHROPIC_API_KEY: !!js process.env.ANTHROPIC_API_KEY
64
+
65
+ - id: subagent-claude-bypass
38
66
  name: '@deepseek-ai/dsh-subagent-claude-code'
39
67
  config:
68
+ providerName: claude-bypass
69
+ permissionMode: bypassPermissions
40
70
  env:
41
71
  ANTHROPIC_API_KEY: !!js process.env.ANTHROPIC_API_KEY
72
+ ```
73
+
74
+ ```yaml
75
+ - id: jobs
76
+ name: '@deepseek-ai/dsh-jobs-local'
42
77
 
43
- - id: tool-subagent-claude-code
78
+ - id: tool-jobs
79
+ name: '@deepseek-ai/dsh-tool-jobs'
80
+
81
+ - id: tool-subagent-claude-safe
44
82
  name: '@deepseek-ai/dsh-tool-subagent'
45
83
  disabled: true
46
84
  config:
47
- provider: claude-code
48
- toolName: subagent_claude_code
49
- enableRunInBackground: false
85
+ provider: claude-safe
86
+ toolName: subagent_claude_safe
87
+ backgroundMode: one-shot
88
+ maxDepth: provider-managed
89
+
90
+ - id: tool-subagent-claude-bypass
91
+ name: '@deepseek-ai/dsh-tool-subagent'
92
+ config:
93
+ provider: claude-bypass
94
+ toolName: subagent_claude_bypass
95
+ backgroundMode: one-shot
50
96
  maxDepth: provider-managed
51
97
  ```
52
98
 
53
99
  ## 产品兼容性与证据
54
100
 
55
- 运行时依赖精确锁定为 `@anthropic-ai/claude-agent-sdk@0.3.220`。生产运行使用原生 `claude` 安装。无密钥真实产品测试使用由 SDK 分发的 Claude Code 2.1.220 CLI 作为确定性 fixture(测试前置数据),并通过同一套原生可执行文件解析路径与 Windows batch shim 路径运行;这项测试不声称兼容每个独立安装的版本。Loader 组合证明两个产品包能够共存且不会启动任一产品。
101
+ 运行时依赖精确锁定为 `@anthropic-ai/claude-agent-sdk@0.3.220`,其八个平台包都携带 Claude Code 2.1.220。普通安装会按当前操作系统、CPU 及 Linux libc 选择一个载荷。对于当前 darwin-arm64 载荷,`npm pack --dry-run --json` 报告压缩包为 74,858,812 字节、解包后为 256,908,856 字节;其他平台可能不同,这些数值只用于披露而不是安装阈值。无密钥真实产品测试会让 SDK 选择 CLI,通过回环 Messages fixture 运行它,并断言共享子进程 argv 的首项就是该平台包的原生可执行文件。Loader 组合证明安装该 Bundle 只会注册休眠的 Claude Code provider,不会启动产品进程。
102
+
103
+ 如果安装时省略 optional dependencies、当前平台不受支持,或所选载荷缺失,提供方注册仍保持休眠,但第一次委派会在 SDK 启动边界失败。调用方只会收到安全的 `query-start` / `unknown` 失败事实;原生载荷错误只保留在内部 cause 链和提供方 Host 日志中。提供方既不会探测宿主 CLI,也不会用它重试。
104
+
105
+ Loader 组合证明 Bundle 默认实例、两个额外命名 Claude 实例与现有 Codex 包可以共存,而且不会启动任一产品。
56
106
 
57
107
  限定于项目所有者身份的分发授权涵盖官方 SDK 及每个 SDK 版本声明的官方 CLI/平台载荷。[`THIRD_PARTY_NOTICES.md`](../../../THIRD_PARTY_NOTICES.md) 会披露当前可选载荷闭包,但不会认定其中声明的条款属于宽松许可;其他无关的非宽松运行时依赖仍会使第三方声明门禁失败。
58
108
 
@@ -62,7 +112,7 @@ SDK 接收由文本块原样拼接成的任务。提供方会完整迭代 SDK
62
112
 
63
113
  #### 模型看到的内容
64
114
 
65
- Claude Code 子级会在一个全新的 SDK query 中接收独立文本任务。它的工作区是父会话 cwd;其模型、系统指令、工具、权限和身份验证来自宿主机原生 Claude 设置与产品安装。
115
+ Claude Code 子级会在一个全新的 SDK query 中接收独立文本任务。它的工作区是父会话 cwd;其模型、系统指令、工具、沙箱和身份验证来自原生 Claude 设置,所选提供方实例的 Profile 配置会固定该 query 的环境与非交互权限模式,而可执行版本来自 Bundle 锁定的 SDK 平台载荷。
66
116
 
67
117
  #### 对 token 的影响
68
118
 
@@ -72,27 +122,28 @@ Claude Code 子级会在一个全新的 SDK query 中接收独立文本任务。
72
122
 
73
123
  这与父请求缓存相互独立。能否复用只取决于 Claude Code 自身的模型、指令、工具、原生设置和全新 query。
74
124
 
75
- ### 父级工具结果(间接)
125
+ ### 父级调度与结果(间接)
76
126
 
77
127
  #### 模型看到的内容
78
128
 
79
- 通过 `dsh-tool-subagent`,父级模型只会看到符合严格成功条件的 Claude Code 最终答案,或者在结果未完成时看到消费方给出的原样错误。Claude Code 的推理、工具活动、中间消息、stderr、工作区差异、用量信息和产品标识符均不会复制到父会话。
129
+ 通过 `dsh-tool-subagent`,前台调用会让父级模型看到符合严格成功条件的 Claude Code 最终答案;若结果未完成,错误中会包含终止原因和可选的安全诊断。该诊断可以区分固定 SDK 错误类别、生命周期阶段和已观测的进程结果,而不复制原始产品文本。后台调用会先返回 Job id;随后通用作业控制面会送达完成通知,通过 `job_output` 公开同一最终答案或失败状态 detail,并允许 `job_kill` 请求取消。Claude Code 的推理、工具活动、中间消息、stderr、工作区差异、用量信息、产品标识符、工具输入和原始协议载荷均不会复制到父会话。
80
130
 
81
131
  #### 对 token 的影响
82
132
 
83
- 父级输入只会增加工具结果中保留的最终答案或错误内容。本提供方自身不添加父级工具 schema。
133
+ 前台输入会增加工具结果中保留的最终答案或错误内容。后台输入还会包含启动确认、完成通知,以及 `job_output`、`job_kill` 或后续状态结果;子任务 token 仍不会进入父级上下文。本提供方自身不添加父级工具 schema。
84
134
 
85
135
  #### 对 KV Cache 的影响
86
136
 
87
- 仅追加:新的工具结果接在可复用的父请求前缀之后。
137
+ 仅追加:前台会在可复用的父请求前缀后增加一个结果,后台则会继续追加 Job 启动确认、通知以及后续控制或收集结果。后台调度可能增加一个由通知唤醒的轮次,但这些消息都不会改写更早的前缀。
88
138
 
89
139
  ## 已知限制与后续工作
90
140
 
91
141
  - **每次运行均新建一个 query 和一个进程**:不支持续接、恢复、池化、进度流或产品会话持久化。
142
+ - **静态选择实例**:Profile 配置项固定提供方名称与工具绑定;调用无法动态选择提供方,而且每个公开工具都需要唯一的 `toolName`。
92
143
  - **宿主设置有意保持权威**:项目和用户设置可以改变模型、工具与行为;本提供方不提供经过筛选或与宿主环境隔离的生产模式。
93
- - **产品安装与账户状态仍由原生机制管理**:`claude` 缺失或不兼容、配置错误或身份验证失败都会呈现为启动错误或运行错误;本插件不提供安装程序或登录流程。
94
- - **SDK 平台 CLI 仍在安装闭包内**:生产环境会忽略它,改用宿主提供的 `claude`,但当前 SDK 的可选依赖仍会安装,并提供无密钥兼容性 fixture。移除该载荷属于独立的产品安装闭包后续项。
95
- - **没有人工交互路径**:`AskUserQuestion` 被禁用,其他交互回调也不存在,因此需要新审批或输入的任务会失败而不会挂起。
96
- - **仅返回最终文本**:推理、中间消息、工具通信、用量信息、stderr 和工作区差异仍只保留在产品内部。
144
+ - **身份验证与账户状态仍由原生机制管理**:Bundle 会提供 CLI,但不会创建账户、登录或改写 Claude 设置;配置与身份验证失败会公开其生命周期阶段与安全的 `unknown` 回退,而不会增加单独的公开分类。
145
+ - **委派时必须存在 SDK 平台载荷**:省略 optional dependencies 的安装、不受支持的平台以及缺失或损坏的载荷都会在第一次 query 时失败;不会回退到宿主 CLI。
146
+ - **没有人工交互路径**:`AskUserQuestion` 被禁用,权限提示会被拒绝,MCP elicitation 会被拒绝,阻塞对话会快速失败而不会挂起。
147
+ - **assistant 载荷仅包含最终文本**:失败运行可以额外公开独立的安全诊断;推理、中间消息、工具通信、用量信息、stderr 和工作区差异仍只保留在产品内部,通用 Job id、通知与状态来自共享作业运行时。
97
148
  - **没有可选的共享能力**:对于本提供方,共享服务会拒绝输出 schema、子任务角色设定、工具筛选和 harness 深度强制约束。
98
149
  - **没有按实际经过时间触发的超时或副作用回滚**:长时间运行的工作由调用方取消,且取消前已更改的文件或外部系统不会恢复原状。
@@ -0,0 +1,6 @@
1
+ # This optional Profile layer registers the dormant Claude Code provider. Agent
2
+ # presets separately decide whether one session receives its delegation tool.
3
+
4
+ - insert:
5
+ - id: subagent-claude-code
6
+ name: '@deepseek-ai/dsh-subagent-claude-code'
package/lib/index.js CHANGED
@@ -6,7 +6,6 @@ import { query } from "@anthropic-ai/claude-agent-sdk";
6
6
  import { SessionId } from "@deepseek-ai/dsh-session";
7
7
  import { scrubbedParentEnv } from "@deepseek-ai/dsh-subprocess";
8
8
  import { EventEmitter } from "node:events";
9
- import { extname } from "node:path";
10
9
  //#region lib/types/process.js
11
10
  /**
12
11
  * Projection from the shared managed-process handle to the official Claude
@@ -14,7 +13,6 @@ import { extname } from "node:path";
14
13
  *
15
14
  * @module @deepseek-ai/dsh-subagent-claude-code/process
16
15
  */
17
- const WINDOWS_BATCH_EXECUTABLE_ENV = "DSH_CLAUDE_CODE_EXECUTABLE";
18
16
  function thrown$1(value) {
19
17
  /* v8 ignore next -- the subprocess seam rejects with Error. */
20
18
  return value instanceof Error ? value : new Error(String(value));
@@ -33,28 +31,12 @@ function sdkEnvironmentOverlay(env) {
33
31
  * Translate one official SDK spawn request to the shared process owner.
34
32
  * @param options - command, arguments, workspace, environment, and forwarded signal from the SDK.
35
33
  * @param graceMs - process-tree termination grace.
36
- * @param platform - host platform selecting the Windows batch-shim boundary.
37
34
  * @returns the fully explicit shared subprocess request.
38
- * @remarks The batch-shim path quotes only the resolved executable. The pinned SDK
39
- * supplies fixed flag arguments without cmd metacharacters; cmd reparses that tail.
40
35
  */
41
- function claudeSpawnSpec(options, graceMs, platform = process.platform) {
36
+ function claudeSpawnSpec(options, graceMs) {
42
37
  if (options.cwd === void 0 || options.cwd.length === 0) throw new Error("subagent-claude-code: SDK spawn request omitted its workspace");
43
- const extension = extname(options.command).toLowerCase();
44
- const batchShim = platform === "win32" && (extension === ".cmd" || extension === ".bat");
45
- const env = sdkEnvironmentOverlay(options.env);
46
- const argv = batchShim ? [
47
- "cmd.exe",
48
- "/d",
49
- "/v:off",
50
- "/s",
51
- "/c",
52
- `%${WINDOWS_BATCH_EXECUTABLE_ENV}%`,
53
- ...options.args
54
- ] : [options.command, ...options.args];
55
- if (batchShim) env[WINDOWS_BATCH_EXECUTABLE_ENV] = `"${options.command}"`;
56
38
  return {
57
- argv,
39
+ argv: [options.command, ...options.args],
58
40
  cwd: options.cwd,
59
41
  stdio: {
60
42
  stdin: "pipe",
@@ -63,7 +45,7 @@ function claudeSpawnSpec(options, graceMs, platform = process.platform) {
63
45
  },
64
46
  graceMs,
65
47
  signal: options.signal,
66
- env
48
+ env: sdkEnvironmentOverlay(options.env)
67
49
  };
68
50
  }
69
51
  /**
@@ -75,8 +57,7 @@ var ManagedClaudeCodeProcess = class {
75
57
  stdin;
76
58
  stdout;
77
59
  events = new EventEmitter();
78
- exitCodeValue = null;
79
- signalCodeValue = null;
60
+ outcomeValue;
80
61
  killRequested = false;
81
62
  /**
82
63
  * Project a managed process with piped stdin and stdout.
@@ -88,8 +69,7 @@ var ManagedClaudeCodeProcess = class {
88
69
  this.stdout = child.stdout;
89
70
  this.events.on("error", () => {});
90
71
  child.done.then((outcome) => {
91
- this.exitCodeValue = outcome.exitCode;
92
- this.signalCodeValue = outcome.signal;
72
+ this.outcomeValue = outcome;
93
73
  this.events.emit("exit", outcome.exitCode, outcome.signal);
94
74
  }, (error) => {
95
75
  this.events.emit("error", thrown$1(error));
@@ -101,11 +81,15 @@ var ManagedClaudeCodeProcess = class {
101
81
  }
102
82
  /** Direct-child exit code, or null while running or after signal exit. */
103
83
  get exitCode() {
104
- return this.exitCodeValue;
84
+ return this.outcomeValue?.exitCode ?? null;
105
85
  }
106
86
  /** Direct-child terminating signal, if any. */
107
87
  get signalCode() {
108
- return this.signalCodeValue;
88
+ return this.outcomeValue?.signal ?? null;
89
+ }
90
+ /** Exact managed-process outcome after exit, or undefined while running. */
91
+ get outcome() {
92
+ return this.outcomeValue;
109
93
  }
110
94
  /**
111
95
  * Route the SDK's termination request to the tree-scoped process owner.
@@ -113,7 +97,7 @@ var ManagedClaudeCodeProcess = class {
113
97
  * @returns false only after exit or a previous termination request.
114
98
  */
115
99
  kill(_signal) {
116
- if (this.killRequested || this.exitCodeValue !== null || this.signalCodeValue !== null) return false;
100
+ if (this.killRequested || this.outcomeValue !== void 0) return false;
117
101
  this.killRequested = true;
118
102
  this.child.terminate();
119
103
  return true;
@@ -142,10 +126,68 @@ var ManagedClaudeCodeProcess = class {
142
126
  */
143
127
  /** Default POSIX grace between subprocess termination tiers. */
144
128
  const DEFAULT_DISPOSE_GRACE_MS = 3e3;
129
+ /** Claude Code permission modes that cannot wait for a human response. */
130
+ const CLAUDE_CODE_PERMISSION_MODES = [
131
+ "dontAsk",
132
+ "acceptEdits",
133
+ "auto",
134
+ "plan",
135
+ "bypassPermissions"
136
+ ];
137
+ /** Safe default for unattended Claude Code runs. */
138
+ const DEFAULT_CLAUDE_CODE_PERMISSION_MODE = "dontAsk";
139
+ const SUPPORTED_UNATTENDED_DIALOG_KINDS = ["refusal_fallback_prompt"];
140
+ function failureDiagnostic(facts) {
141
+ const fields = [
142
+ "product: Claude Code",
143
+ `stage: ${facts.stage}`,
144
+ `category: ${facts.category}`
145
+ ];
146
+ const exitCode = facts.outcome?.exitCode;
147
+ if (exitCode !== null && exitCode !== void 0) fields.push(`exit code: ${exitCode}`);
148
+ const signal = facts.outcome?.signal;
149
+ if (signal !== null && signal !== void 0) fields.push(`signal: ${signal}`);
150
+ return `Product subagent failure (${fields.join("; ")})`;
151
+ }
152
+ var ClaudeCodeFailure = class extends Error {
153
+ facts;
154
+ constructor(facts, cause) {
155
+ super(`subagent-claude-code: ${failureDiagnostic(facts)}`, cause === void 0 ? void 0 : { cause });
156
+ this.facts = facts;
157
+ this.name = "ClaudeCodeFailure";
158
+ }
159
+ };
160
+ function sdkFailureCategory(subtype) {
161
+ switch (subtype) {
162
+ case "error_during_execution":
163
+ case "error_max_turns":
164
+ case "error_max_budget_usd":
165
+ case "error_max_structured_output_retries": return subtype;
166
+ default: return "unknown";
167
+ }
168
+ }
169
+ /**
170
+ * Hide an unpublished product startup failure behind fixed safe facts.
171
+ * @param cause - original host-side failure retained only on the Error cause chain.
172
+ * @returns a rejection safe to expose through the subagent start boundary.
173
+ */
174
+ function claudeCodeStartupFailure(cause) {
175
+ return new ClaudeCodeFailure({
176
+ stage: "query-start",
177
+ category: "unknown"
178
+ }, cause);
179
+ }
180
+ function unattendedDiagnostic(mode, request, decision, reason) {
181
+ return `Claude Code unattended decision (mode: ${mode}; request: ${request}; decision: ${decision}): ${reason}`;
182
+ }
145
183
  function thrown(value) {
146
184
  /* v8 ignore next -- typed SDK and subprocess failures reject with Error. */
147
185
  return value instanceof Error ? value : new Error(String(value));
148
186
  }
187
+ /** Read live request cancellation across awaited startup cleanup. */
188
+ function isAborted(signal) {
189
+ return signal.aborted;
190
+ }
149
191
  /**
150
192
  * Validate and preserve the one-shot task before crossing the SDK boundary.
151
193
  * @param prompt - task content accepted from the shared subagent service.
@@ -167,25 +209,43 @@ function textTask(prompt) {
167
209
  * @returns exact final text for a successful, non-error result.
168
210
  */
169
211
  function successfulResult(message) {
170
- if (message.subtype !== "success" || message.is_error || message.result.trim().length === 0) {
171
- const detail = message.subtype === "success" ? "success result was marked as an error or contained no answer" : message.errors.join("; ") || message.subtype;
172
- throw new Error(`subagent-claude-code: Claude Code failed: ${detail}`);
212
+ if (message.subtype !== "success") {
213
+ const category = sdkFailureCategory(message.subtype);
214
+ const detail = category === "unknown" ? void 0 : message.errors.join("; ");
215
+ throw new ClaudeCodeFailure({
216
+ stage: "query-run",
217
+ category
218
+ }, detail === void 0 || detail.length === 0 ? void 0 : new Error(detail));
173
219
  }
220
+ if (message.is_error || message.result.trim().length === 0) throw new ClaudeCodeFailure({
221
+ stage: "query-run",
222
+ category: "invalid-success"
223
+ });
174
224
  return message.result;
175
225
  }
176
226
  /**
177
227
  * Consume the complete SDK stream and require one strict success plus normal
178
228
  * iterator completion.
179
229
  * @param query - published official SDK query.
230
+ * @param onPermissionDenied - records a safe fact when the SDK reports native denial.
231
+ * @param onResult - records that the SDK supplied a terminal result message.
180
232
  * @returns the completed shared result.
181
233
  */
182
- async function consumeClaudeQuery(query) {
234
+ async function consumeClaudeQuery(query, onPermissionDenied, onResult) {
183
235
  let answer;
184
236
  for await (const message of query) {
237
+ if (message.type === "system" && message.subtype === "permission_denied") {
238
+ onPermissionDenied?.();
239
+ continue;
240
+ }
185
241
  if (message.type !== "result") continue;
242
+ onResult?.();
186
243
  answer = successfulResult(message);
187
244
  }
188
- if (answer === void 0) throw new Error("subagent-claude-code: Claude Code ended without a result");
245
+ if (answer === void 0) throw new ClaudeCodeFailure({
246
+ stage: "query-run",
247
+ category: "missing-result"
248
+ });
189
249
  return {
190
250
  output: [{
191
251
  type: "text",
@@ -198,7 +258,8 @@ async function consumeClaudeQuery(query) {
198
258
  * Close the official query, terminate the managed process tree, and wait for
199
259
  * the subprocess owner to prove it is gone.
200
260
  * @param query - official SDK query, when creation reached that point.
201
- * @param child - shared-service handle that owns the CLI process tree.
261
+ * @param child - live shared-service handle that owns the CLI process tree;
262
+ * spawn-failed handles settle at the startup boundary instead.
202
263
  */
203
264
  async function disposeClaudeCodeChild(query, child) {
204
265
  const failures = [];
@@ -207,45 +268,60 @@ async function disposeClaudeCodeChild(query, child) {
207
268
  } catch (error) {
208
269
  failures.push(thrown(error));
209
270
  }
210
- if (child.pid > 0) {
211
- child.terminate();
212
- try {
213
- await child.waitForExit();
214
- } catch (error) {
215
- failures.push(thrown(error));
216
- }
217
- }
271
+ child.terminate();
218
272
  try {
219
- await child.done;
273
+ await child.waitForExit();
220
274
  } catch (error) {
221
275
  failures.push(thrown(error));
222
276
  }
277
+ const outcome = await child.done;
223
278
  const firstFailure = failures[0];
224
- if (failures.length === 1 && firstFailure !== void 0) throw firstFailure;
225
- if (failures.length > 1) throw new AggregateError(failures, "subagent-claude-code: query and process cleanup failed");
279
+ if (firstFailure !== void 0) throw new ClaudeCodeFailure({
280
+ stage: "teardown",
281
+ category: "unknown",
282
+ outcome
283
+ }, failures.length === 1 ? firstFailure : new AggregateError(failures, "Claude Code teardown failures"));
226
284
  }
227
285
  /**
228
286
  * Build the fixed official SDK options for one one-shot provider run.
229
287
  * @param spec - Workspace, environment, process service, and disposal policy.
230
288
  * @param controller - per-run cancellation owner.
231
- * @param capture - receives the real managed child synchronously from the SDK hook.
289
+ * @param capture - receives the shared child and SDK-facing process synchronously.
290
+ * @param captureDiagnostic - receives safe facts from unattended interaction callbacks.
232
291
  * @returns options that inherit native settings while disabling persistence and user questions.
233
292
  */
234
- function claudeQueryOptions(spec, controller, capture) {
293
+ function claudeQueryOptions(spec, controller, capture, captureDiagnostic) {
235
294
  return {
236
295
  abortController: controller,
237
296
  cwd: spec.cwd,
238
- pathToClaudeCodeExecutable: spec.executable,
239
297
  env: {
240
298
  ...scrubbedParentEnv(),
241
299
  ...spec.env
242
300
  },
243
301
  persistSession: false,
244
- disallowedTools: ["AskUserQuestion"],
302
+ disallowedTools: spec.permissionMode === "plan" ? ["AskUserQuestion", "ExitPlanMode"] : ["AskUserQuestion"],
303
+ permissionMode: spec.permissionMode,
304
+ ...spec.permissionMode === "bypassPermissions" ? { allowDangerouslySkipPermissions: true } : { canUseTool: () => {
305
+ captureDiagnostic(unattendedDiagnostic(spec.permissionMode, "tool permission", "denied", "the provider does not request human approval"));
306
+ return Promise.resolve({
307
+ behavior: "deny",
308
+ message: "This unattended Claude Code subagent cannot request human approval."
309
+ });
310
+ } },
311
+ onElicitation: () => {
312
+ captureDiagnostic(unattendedDiagnostic(spec.permissionMode, "MCP elicitation", "declined", "the provider does not collect interactive MCP input"));
313
+ return Promise.resolve({ action: "decline" });
314
+ },
315
+ onUserDialog: () => {
316
+ captureDiagnostic(unattendedDiagnostic(spec.permissionMode, "user dialog", "cancelled", "the provider does not render blocking dialogs"));
317
+ return Promise.resolve({ behavior: "cancelled" });
318
+ },
319
+ supportedDialogKinds: SUPPORTED_UNATTENDED_DIALOG_KINDS,
245
320
  spawnClaudeCodeProcess: (options) => {
246
321
  const child = spec.spawn(claudeSpawnSpec(options, spec.disposeGraceMs));
247
- capture(child);
248
- return new ManagedClaudeCodeProcess(child);
322
+ const process = new ManagedClaudeCodeProcess(child);
323
+ capture(child, process);
324
+ return process;
249
325
  }
250
326
  };
251
327
  }
@@ -266,39 +342,132 @@ async function startClaudeCodeRun(request, spec) {
266
342
  requestCancel();
267
343
  };
268
344
  request.signal.addEventListener("abort", onAbort, { once: true });
345
+ const reportFailure = (error) => {
346
+ try {
347
+ spec.onError?.(error, "error");
348
+ } catch {}
349
+ };
269
350
  let child;
270
351
  let query$1;
352
+ let managedProcess;
353
+ let diagnostic;
354
+ const capturePermissionDiagnostic = (value) => {
355
+ diagnostic = value;
356
+ };
357
+ const prependFailureDiagnostic = (facts) => {
358
+ const failure = failureDiagnostic(facts);
359
+ diagnostic = diagnostic === void 0 ? failure : `${failure}\n${diagnostic}`;
360
+ };
361
+ const captureChild = (captured, process) => {
362
+ child = captured;
363
+ managedProcess = process;
364
+ };
271
365
  try {
272
366
  query$1 = query({
273
367
  prompt,
274
- options: claudeQueryOptions(spec, controller, (captured) => {
275
- child = captured;
276
- })
368
+ options: claudeQueryOptions(spec, controller, captureChild, capturePermissionDiagnostic)
277
369
  });
278
370
  if (child === void 0 || child.pid <= 0) throw new Error("subagent-claude-code: official SDK did not publish a controllable Claude Code process");
279
371
  if (controller.signal.aborted) throw new Error("subagent-claude-code: request was aborted before SDK startup");
280
372
  } catch (error) {
281
373
  request.signal.removeEventListener("abort", onAbort);
282
374
  const cancelledBeforeCleanup = controller.signal.aborted;
375
+ await Promise.resolve();
376
+ const startupFacts = {
377
+ stage: "query-start",
378
+ category: "unknown",
379
+ outcome: managedProcess?.outcome
380
+ };
381
+ const startupFailure = (cause = error) => new ClaudeCodeFailure(startupFacts, thrown(cause));
283
382
  requestCancel();
383
+ if (child !== void 0 && child.pid <= 0) {
384
+ let closeError;
385
+ try {
386
+ query$1?.close();
387
+ } catch (disposeError) {
388
+ closeError = thrown(disposeError);
389
+ }
390
+ let spawnError = thrown(error);
391
+ try {
392
+ await child.done;
393
+ } catch (childError) {
394
+ spawnError = thrown(childError);
395
+ }
396
+ if (closeError !== void 0) {
397
+ const failure = startupFailure(spawnError);
398
+ const cleanupFailure = new ClaudeCodeFailure({
399
+ stage: "teardown",
400
+ category: "unknown"
401
+ }, closeError);
402
+ const aggregate = new AggregateError([failure, cleanupFailure], `${failure.message}; ${cleanupFailure.message}`);
403
+ reportFailure(aggregate);
404
+ throw aggregate;
405
+ }
406
+ if (cancelledBeforeCleanup || isAborted(request.signal)) throw new Error("subagent-claude-code: request was aborted before SDK startup");
407
+ const failure = startupFailure(spawnError);
408
+ reportFailure(failure);
409
+ throw failure;
410
+ }
284
411
  if (child !== void 0) try {
285
412
  await disposeClaudeCodeChild(query$1, child);
286
413
  } catch (disposeError) {
287
- throw new AggregateError([thrown(error), thrown(disposeError)], "subagent-claude-code: startup failed and CLI cleanup also failed");
414
+ const failure = startupFailure();
415
+ const cleanupFailure = thrown(disposeError);
416
+ const aggregate = new AggregateError([failure, cleanupFailure], `${failure.message}; ${cleanupFailure.message}`);
417
+ reportFailure(aggregate);
418
+ throw aggregate;
288
419
  }
289
420
  else if (query$1 !== void 0) try {
290
421
  query$1.close();
291
422
  } catch (disposeError) {
292
- throw new AggregateError([thrown(error), thrown(disposeError)], "subagent-claude-code: startup failed and query cleanup also failed");
423
+ const failure = startupFailure();
424
+ const cleanupFailure = new ClaudeCodeFailure({
425
+ stage: "teardown",
426
+ category: "unknown"
427
+ }, thrown(disposeError));
428
+ const aggregate = new AggregateError([failure, cleanupFailure], `${failure.message}; ${cleanupFailure.message}`);
429
+ reportFailure(aggregate);
430
+ throw aggregate;
293
431
  }
294
- if (cancelledBeforeCleanup || request.signal.aborted) throw new Error("subagent-claude-code: request was aborted before SDK startup");
295
- throw thrown(error);
432
+ if (cancelledBeforeCleanup || isAborted(request.signal)) throw new Error("subagent-claude-code: request was aborted before SDK startup");
433
+ const failure = startupFailure();
434
+ reportFailure(failure);
435
+ throw failure;
296
436
  }
297
437
  const publishedQuery = query$1;
298
438
  const publishedChild = child;
439
+ let receivedResult = false;
299
440
  const result = settleRunResult({
300
- attempt: () => consumeClaudeQuery(publishedQuery),
441
+ attempt: async () => {
442
+ try {
443
+ return await consumeClaudeQuery(publishedQuery, () => {
444
+ capturePermissionDiagnostic(unattendedDiagnostic(spec.permissionMode, "tool permission", "denied", "Claude Code denied the request before an interactive prompt"));
445
+ }, () => {
446
+ receivedResult = true;
447
+ });
448
+ } catch (error) {
449
+ const processOutcome = managedProcess?.outcome;
450
+ let facts;
451
+ if (error instanceof ClaudeCodeFailure) facts = {
452
+ ...error.facts,
453
+ outcome: processOutcome
454
+ };
455
+ else if (processOutcome !== void 0 && !receivedResult) facts = {
456
+ stage: "process",
457
+ category: "process-exit",
458
+ outcome: processOutcome
459
+ };
460
+ else facts = {
461
+ stage: "query-run",
462
+ category: "unknown",
463
+ outcome: processOutcome
464
+ };
465
+ prependFailureDiagnostic(facts);
466
+ throw error instanceof ClaudeCodeFailure ? error : new ClaudeCodeFailure(facts, thrown(error));
467
+ }
468
+ },
301
469
  collectOutput: () => [],
470
+ collectDiagnostic: () => diagnostic,
302
471
  cancelled: () => controller.signal.aborted,
303
472
  onError: spec.onError,
304
473
  signal: request.signal,
@@ -310,60 +479,85 @@ async function startClaudeCodeRun(request, spec) {
310
479
  signal: request.signal,
311
480
  onAbort,
312
481
  requestCancel,
313
- teardown: () => disposeClaudeCodeChild(publishedQuery, publishedChild)
482
+ teardown: async () => {
483
+ try {
484
+ await disposeClaudeCodeChild(publishedQuery, publishedChild);
485
+ } catch (error) {
486
+ const failure = thrown(error);
487
+ reportFailure(failure);
488
+ throw failure;
489
+ }
490
+ }
314
491
  });
315
492
  }
316
493
  //#endregion
317
494
  //#region lib/types/index.js
318
495
  /**
319
- * Fixed Claude Code one-shot subagent provider. Every accepted run invokes
320
- * the official Agent SDK in the delegating Session's workspace and places
321
- * the SDK-spawned real CLI under the shared subprocess owner.
496
+ * Profile-named Claude Code one-shot subagent provider. Every accepted run
497
+ * invokes the official Agent SDK in the delegating Session's workspace and
498
+ * places the SDK-spawned real CLI under the shared subprocess owner.
322
499
  *
323
500
  * @module @deepseek-ai/dsh-subagent-claude-code
324
501
  */
325
502
  const name = "subagent-claude-code";
326
503
  const inject = ["subagents", "subprocess"];
504
+ const DEFAULT_PROVIDER_NAME = "claude-code";
327
505
  const Config = z.object({
506
+ providerName: z.string().min(1).default(DEFAULT_PROVIDER_NAME),
328
507
  env: z.dict(z.string()).default({}),
508
+ permissionMode: z.union([...CLAUDE_CODE_PERMISSION_MODES]).default(DEFAULT_CLAUDE_CODE_PERMISSION_MODE),
329
509
  disposeGraceMs: z.number().default(DEFAULT_DISPOSE_GRACE_MS)
330
510
  });
331
511
  var ClaudeCodeProvider = class {
512
+ name;
332
513
  ctx;
333
514
  config;
334
- name = "claude-code";
335
515
  capabilities = NO_START_CAPABILITIES;
336
516
  inheritsParentContext = false;
337
- constructor(ctx, config) {
517
+ constructor(name, ctx, config) {
518
+ this.name = name;
338
519
  this.ctx = ctx;
339
520
  this.config = config;
340
521
  }
341
522
  async start(request) {
342
523
  const parentCwd = request.parent.session.header.cwd;
343
524
  if (parentCwd === void 0) throw new Error("subagent-claude-code: no working directory for the child — delegate from a parent session that has one");
344
- const executable = await this.ctx.subprocess.resolveExecutable("claude", this.config.env, request.signal);
525
+ let cwd;
526
+ try {
527
+ cwd = resolveChildCwd("subagent-claude-code", void 0, parentCwd);
528
+ } catch (error) {
529
+ if (request.signal.aborted) throw new Error("subagent-claude-code: request was aborted before SDK startup");
530
+ const failure = claudeCodeStartupFailure(error);
531
+ this.ctx.logger.warn(`subagent-claude-code "${this.name}": child start failed: %o`, failure);
532
+ throw failure;
533
+ }
345
534
  return startClaudeCodeRun(request, {
346
- cwd: resolveChildCwd("subagent-claude-code", void 0, parentCwd),
347
- executable,
535
+ cwd,
536
+ permissionMode: this.config.permissionMode,
348
537
  env: this.config.env,
349
538
  disposeGraceMs: this.config.disposeGraceMs,
350
539
  spawn: (spawnSpec) => this.ctx.subprocess.spawn(spawnSpec),
351
540
  onError: (error, stopReason) => {
352
- this.ctx.logger.warn(`subagent-claude-code: child run failed (${stopReason}): ${error.message}`);
541
+ this.ctx.logger.warn(`subagent-claude-code "${this.name}": child run failed (${stopReason}): %o`, error);
353
542
  }
354
543
  });
355
544
  }
356
545
  };
357
546
  /**
358
- * Register the fixed `claude-code` provider.
547
+ * Register one Profile-named Claude Code provider.
359
548
  * @param ctx - context carrying shared subagent and subprocess services.
360
- * @param config - explicit child environment and disposal grace.
549
+ * @param config - registry name, permission mode, child environment, and disposal grace.
361
550
  */
362
551
  function apply(ctx, config) {
363
- const resolved = config;
552
+ const resolved = {
553
+ providerName: config.providerName ?? DEFAULT_PROVIDER_NAME,
554
+ env: config.env,
555
+ permissionMode: config.permissionMode ?? "dontAsk",
556
+ disposeGraceMs: config.disposeGraceMs
557
+ };
364
558
  assertPositiveFinite("subagent-claude-code", "disposeGraceMs", resolved.disposeGraceMs);
365
559
  if (resolved.disposeGraceMs > MAX_TIMER_DELAY_MS) throw new Error(`subagent-claude-code: disposeGraceMs must be no greater than ${MAX_TIMER_DELAY_MS}`);
366
- ctx.subagents.registerProvider(new ClaudeCodeProvider(ctx, resolved));
560
+ ctx.subagents.registerProvider(new ClaudeCodeProvider(resolved.providerName, ctx, resolved));
367
561
  }
368
562
  //#endregion
369
563
  export { Config, apply, inject, name };
@@ -1,29 +1,39 @@
1
1
  /**
2
- * Fixed Claude Code one-shot subagent provider. Every accepted run invokes
3
- * the official Agent SDK in the delegating Session's workspace and places
4
- * the SDK-spawned real CLI under the shared subprocess owner.
2
+ * Profile-named Claude Code one-shot subagent provider. Every accepted run
3
+ * invokes the official Agent SDK in the delegating Session's workspace and
4
+ * places the SDK-spawned real CLI under the shared subprocess owner.
5
5
  *
6
6
  * @module @deepseek-ai/dsh-subagent-claude-code
7
7
  */
8
8
  import type { Context } from '@deepseek-ai/cordis';
9
9
  import z from '@deepseek-ai/schemastery';
10
+ import { type ClaudeCodePermissionMode } from './run.ts';
10
11
  export declare const name = "subagent-claude-code";
11
12
  export declare const inject: string[];
12
- /** Deployment-owned environment and process-release bound. */
13
+ /** Deployment-owned permission, environment, and process-release settings. */
13
14
  export interface Config {
15
+ /** Provider name on `ctx.subagents` (default `claude-code`). */
16
+ providerName?: string;
14
17
  /**
15
18
  * Explicit environment entries layered over the subprocess seam's
16
19
  * credential-scrubbed parent environment.
17
20
  */
18
21
  env?: Record<string, string>;
22
+ /**
23
+ * Native non-interactive mode fixed for this Provider instance. Defaults to
24
+ * `dontAsk`; `acceptEdits` accepts edits, `auto` uses the native classifier,
25
+ * `plan` returns a plan without approving execution, and
26
+ * `bypassPermissions` explicitly skips permission checks.
27
+ */
28
+ permissionMode?: ClaudeCodePermissionMode;
19
29
  /** Grace in milliseconds for Claude Code process-tree termination. */
20
30
  disposeGraceMs?: number;
21
31
  }
22
32
  export declare const Config: z<Config>;
23
33
  /**
24
- * Register the fixed `claude-code` provider.
34
+ * Register one Profile-named Claude Code provider.
25
35
  * @param ctx - context carrying shared subagent and subprocess services.
26
- * @param config - explicit child environment and disposal grace.
36
+ * @param config - registry name, permission mode, child environment, and disposal grace.
27
37
  */
28
38
  export declare function apply(ctx: Context, config: Config): void;
29
39
  //# sourceMappingURL=index.d.ts.map
@@ -5,7 +5,7 @@
5
5
  * @module @deepseek-ai/dsh-subagent-claude-code/process
6
6
  */
7
7
  import type { SpawnedProcess, SpawnOptions } from '@anthropic-ai/claude-agent-sdk';
8
- import { type SubprocessHandle, type SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess';
8
+ import { type SubprocessHandle, type SubprocessOutcome, type SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess';
9
9
  /**
10
10
  * Encode the SDK's complete child environment as a subprocess overlay.
11
11
  * @param env - SDK-composed child environment after its removals and replacements.
@@ -16,12 +16,9 @@ export declare function sdkEnvironmentOverlay(env: SpawnOptions['env']): NodeJS.
16
16
  * Translate one official SDK spawn request to the shared process owner.
17
17
  * @param options - command, arguments, workspace, environment, and forwarded signal from the SDK.
18
18
  * @param graceMs - process-tree termination grace.
19
- * @param platform - host platform selecting the Windows batch-shim boundary.
20
19
  * @returns the fully explicit shared subprocess request.
21
- * @remarks The batch-shim path quotes only the resolved executable. The pinned SDK
22
- * supplies fixed flag arguments without cmd metacharacters; cmd reparses that tail.
23
20
  */
24
- export declare function claudeSpawnSpec(options: SpawnOptions, graceMs: number, platform?: NodeJS.Platform): SubprocessSpawnSpec;
21
+ export declare function claudeSpawnSpec(options: SpawnOptions, graceMs: number): SubprocessSpawnSpec;
25
22
  /**
26
23
  * SDK-facing view of one shared managed process. Protocol transport remains
27
24
  * in the official SDK; this adapter only projects streams and exit events.
@@ -31,8 +28,7 @@ export declare class ManagedClaudeCodeProcess implements SpawnedProcess {
31
28
  readonly stdin: import("stream").Writable;
32
29
  readonly stdout: import("stream").Readable;
33
30
  private readonly events;
34
- private exitCodeValue;
35
- private signalCodeValue;
31
+ private outcomeValue;
36
32
  private killRequested;
37
33
  /**
38
34
  * Project a managed process with piped stdin and stdout.
@@ -45,6 +41,8 @@ export declare class ManagedClaudeCodeProcess implements SpawnedProcess {
45
41
  get exitCode(): number | null;
46
42
  /** Direct-child terminating signal, if any. */
47
43
  get signalCode(): NodeJS.Signals | null;
44
+ /** Exact managed-process outcome after exit, or undefined while running. */
45
+ get outcome(): SubprocessOutcome | undefined;
48
46
  /**
49
47
  * Route the SDK's termination request to the tree-scoped process owner.
50
48
  * @param _signal - SDK-selected signal; the shared seam owns its escalation ladder.
@@ -9,21 +9,34 @@ import { type Options, type Query, type SDKMessage, type SDKResultMessage } from
9
9
  import type { ContentBlock } from '@deepseek-ai/dsh-llm';
10
10
  import { type SubagentResult, type SubagentRun, type SubagentStartRequest, type SubagentStopReason } from '@deepseek-ai/dsh-subagent';
11
11
  import { type SubprocessHandle, type SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess';
12
+ import { ManagedClaudeCodeProcess } from './process.ts';
12
13
  /** Default POSIX grace between subprocess termination tiers. */
13
14
  export declare const DEFAULT_DISPOSE_GRACE_MS = 3000;
15
+ /** Claude Code permission modes that cannot wait for a human response. */
16
+ export declare const CLAUDE_CODE_PERMISSION_MODES: readonly ["dontAsk", "acceptEdits", "auto", "plan", "bypassPermissions"];
17
+ /** Profile-selectable non-interactive Claude Code permission mode. */
18
+ export type ClaudeCodePermissionMode = typeof CLAUDE_CODE_PERMISSION_MODES[number];
19
+ /** Safe default for unattended Claude Code runs. */
20
+ export declare const DEFAULT_CLAUDE_CODE_PERMISSION_MODE: ClaudeCodePermissionMode;
21
+ /**
22
+ * Hide an unpublished product startup failure behind fixed safe facts.
23
+ * @param cause - original host-side failure retained only on the Error cause chain.
24
+ * @returns a rejection safe to expose through the subagent start boundary.
25
+ */
26
+ export declare function claudeCodeStartupFailure(cause: unknown): Error;
14
27
  /** Fully resolved inputs for one official Claude Agent SDK query. */
15
28
  export interface ClaudeCodeRunSpec {
16
29
  /** Parent Session workspace supplied to the SDK and real CLI. */
17
30
  readonly cwd: string;
18
- /** Exact native Claude Code executable resolved from the host PATH. */
19
- readonly executable: string;
31
+ /** Profile-selected native non-interactive permission mode. */
32
+ readonly permissionMode: ClaudeCodePermissionMode;
20
33
  /** Explicit deployment/test environment layered after shared scrubbing. */
21
34
  readonly env: Record<string, string>;
22
35
  /** Subprocess termination grace passed to the shared process-tree owner. */
23
36
  readonly disposeGraceMs: number;
24
37
  /** Shared subprocess service spawn operation. */
25
38
  readonly spawn: (spec: SubprocessSpawnSpec) => SubprocessHandle;
26
- /** Diagnostic sink for a post-publication error flattened into a result. */
39
+ /** Host diagnostic sink for a product failure kept outside model-visible text. */
27
40
  readonly onError?: (error: Error, stopReason: SubagentStopReason) => void;
28
41
  }
29
42
  /**
@@ -42,24 +55,28 @@ export declare function successfulResult(message: SDKResultMessage): string;
42
55
  * Consume the complete SDK stream and require one strict success plus normal
43
56
  * iterator completion.
44
57
  * @param query - published official SDK query.
58
+ * @param onPermissionDenied - records a safe fact when the SDK reports native denial.
59
+ * @param onResult - records that the SDK supplied a terminal result message.
45
60
  * @returns the completed shared result.
46
61
  */
47
- export declare function consumeClaudeQuery(query: AsyncIterable<SDKMessage>): Promise<SubagentResult>;
62
+ export declare function consumeClaudeQuery(query: AsyncIterable<SDKMessage>, onPermissionDenied?: () => void, onResult?: () => void): Promise<SubagentResult>;
48
63
  /**
49
64
  * Close the official query, terminate the managed process tree, and wait for
50
65
  * the subprocess owner to prove it is gone.
51
66
  * @param query - official SDK query, when creation reached that point.
52
- * @param child - shared-service handle that owns the CLI process tree.
67
+ * @param child - live shared-service handle that owns the CLI process tree;
68
+ * spawn-failed handles settle at the startup boundary instead.
53
69
  */
54
70
  export declare function disposeClaudeCodeChild(query: Pick<Query, 'close'> | undefined, child: SubprocessHandle): Promise<void>;
55
71
  /**
56
72
  * Build the fixed official SDK options for one one-shot provider run.
57
73
  * @param spec - Workspace, environment, process service, and disposal policy.
58
74
  * @param controller - per-run cancellation owner.
59
- * @param capture - receives the real managed child synchronously from the SDK hook.
75
+ * @param capture - receives the shared child and SDK-facing process synchronously.
76
+ * @param captureDiagnostic - receives safe facts from unattended interaction callbacks.
60
77
  * @returns options that inherit native settings while disabling persistence and user questions.
61
78
  */
62
- export declare function claudeQueryOptions(spec: ClaudeCodeRunSpec, controller: AbortController, capture: (child: SubprocessHandle) => void): Options;
79
+ export declare function claudeQueryOptions(spec: ClaudeCodeRunSpec, controller: AbortController, capture: (child: SubprocessHandle, process: ManagedClaudeCodeProcess) => void, captureDiagnostic: (diagnostic: string) => void): Options;
63
80
  /**
64
81
  * Start one official Claude Agent SDK query and publish its one-shot run.
65
82
  * @param request - resolved shared subagent request.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@deepseek-ai/dsh-subagent-claude-code",
3
3
  "description": "One-shot Claude Code subagent provider over the official Agent SDK",
4
- "version": "0.1.0-rc.6",
4
+ "version": "0.1.0-rc.8",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -28,33 +28,41 @@
28
28
  "files": [
29
29
  "lib/index.js",
30
30
  "lib/invariant.js",
31
+ "cordis.patch.yml",
31
32
  "lib/types/**/*.d.ts"
32
33
  ],
33
34
  "license": "MIT",
35
+ "dsh": {
36
+ "bundle": {
37
+ "patch": "./cordis.patch.yml"
38
+ }
39
+ },
34
40
  "peerDependencies": {
35
- "@deepseek-ai/dsh-invariants": "^0.1.0-rc.6",
36
- "@deepseek-ai/dsh-llm": "^0.1.0-rc.6",
37
- "@deepseek-ai/dsh-session": "^0.1.0-rc.6",
38
- "@deepseek-ai/dsh-subagent": "^0.1.0-rc.6",
39
- "@deepseek-ai/dsh-subprocess": "^0.1.0-rc.6",
40
- "@deepseek-ai/dsh-timeout": "^0.1.0-rc.6",
41
+ "@deepseek-ai/dsh-invariants": "^0.1.0-rc.8",
42
+ "@deepseek-ai/dsh-llm": "^0.1.0-rc.8",
43
+ "@deepseek-ai/dsh-session": "^0.1.0-rc.8",
44
+ "@deepseek-ai/dsh-subagent": "^0.1.0-rc.8",
45
+ "@deepseek-ai/dsh-subprocess": "^0.1.0-rc.8",
46
+ "@deepseek-ai/dsh-timeout": "^0.1.0-rc.8",
41
47
  "@deepseek-ai/cordis": "^4.0.1"
42
48
  },
43
49
  "dependencies": {
44
50
  "@anthropic-ai/sdk": "0.93.0",
45
51
  "@anthropic-ai/claude-agent-sdk": "0.3.220",
52
+ "@modelcontextprotocol/sdk": "^1.29.0",
53
+ "zod": "^4.4.3",
46
54
  "@deepseek-ai/schemastery": "^3.18.1"
47
55
  },
48
56
  "devDependencies": {
49
- "@deepseek-ai/dsh-agent": "^0.1.0-rc.6",
50
- "@deepseek-ai/dsh-llm": "^0.1.0-rc.6",
51
- "@deepseek-ai/dsh-loader-smoke": "^0.1.0-rc.6",
52
- "@deepseek-ai/dsh-session": "^0.1.0-rc.6",
53
- "@deepseek-ai/dsh-subagent": "^0.1.0-rc.6",
54
- "@deepseek-ai/dsh-subprocess": "^0.1.0-rc.6",
55
- "@deepseek-ai/dsh-timeout": "^0.1.0-rc.6",
56
- "@deepseek-ai/dsh-subprocess-local": "^0.1.0-rc.6",
57
- "@deepseek-ai/cordis": "^4.0.1",
58
- "@deepseek-ai/dsh-invariants": "^0.1.0-rc.6"
57
+ "@deepseek-ai/dsh-agent": "^0.1.0-rc.8",
58
+ "@deepseek-ai/dsh-invariants": "^0.1.0-rc.8",
59
+ "@deepseek-ai/dsh-llm": "^0.1.0-rc.8",
60
+ "@deepseek-ai/dsh-loader-smoke": "^0.1.0-rc.8",
61
+ "@deepseek-ai/dsh-session": "^0.1.0-rc.8",
62
+ "@deepseek-ai/dsh-subagent": "^0.1.0-rc.8",
63
+ "@deepseek-ai/dsh-subprocess": "^0.1.0-rc.8",
64
+ "@deepseek-ai/dsh-subprocess-local": "^0.1.0-rc.8",
65
+ "@deepseek-ai/dsh-timeout": "^0.1.0-rc.8",
66
+ "@deepseek-ai/cordis": "^4.0.1"
59
67
  }
60
68
  }