@deepseek-ai/dsh-subagent 0.2.2-rc.4 → 0.2.3-alpha.1

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.
Files changed (53) hide show
  1. package/README.i18n.yaml +20 -8
  2. package/README.md +21 -5
  3. package/README.zh.md +21 -5
  4. package/lib/index.js +94 -42
  5. package/lib/typert.host.js +45 -7
  6. package/lib/typert.remote-client.d.ts.map +1 -1
  7. package/lib/typert.remote-client.js +2 -2
  8. package/lib/types/activation.d.ts +2 -0
  9. package/lib/types/activation.d.ts.map +1 -1
  10. package/lib/types/activation.js +4 -0
  11. package/lib/types/activation.js.map +1 -1
  12. package/lib/types/child-agent.d.ts +8 -4
  13. package/lib/types/child-agent.d.ts.map +1 -1
  14. package/lib/types/child-agent.js +14 -8
  15. package/lib/types/child-agent.js.map +1 -1
  16. package/lib/types/control-types.d.ts +1 -1
  17. package/lib/types/depth.d.ts +1 -1
  18. package/lib/types/depth.d.ts.map +1 -1
  19. package/lib/types/depth.js +3 -2
  20. package/lib/types/depth.js.map +1 -1
  21. package/lib/types/error.d.ts +83 -2
  22. package/lib/types/error.d.ts.map +1 -1
  23. package/lib/types/error.js +8 -1
  24. package/lib/types/error.js.map +1 -1
  25. package/lib/types/index.d.ts +11 -3
  26. package/lib/types/index.d.ts.map +1 -1
  27. package/lib/types/index.js +13 -1
  28. package/lib/types/index.js.map +1 -1
  29. package/lib/types/manager.d.ts +7 -1
  30. package/lib/types/manager.d.ts.map +1 -1
  31. package/lib/types/manager.js +30 -10
  32. package/lib/types/manager.js.map +1 -1
  33. package/lib/types/out-of-process.d.ts +1 -0
  34. package/lib/types/out-of-process.d.ts.map +1 -1
  35. package/lib/types/out-of-process.js +5 -3
  36. package/lib/types/out-of-process.js.map +1 -1
  37. package/lib/types/structured.d.ts.map +1 -1
  38. package/lib/types/structured.js +4 -2
  39. package/lib/types/structured.js.map +1 -1
  40. package/lib/types/types.d.ts +12 -4
  41. package/lib/types/types.d.ts.map +1 -1
  42. package/lib/types/types.js.map +1 -1
  43. package/package.json +49 -48
  44. package/src/activation.ts +5 -0
  45. package/src/child-agent.ts +14 -9
  46. package/src/control-types.ts +1 -1
  47. package/src/depth.ts +3 -2
  48. package/src/error.ts +86 -2
  49. package/src/index.ts +18 -2
  50. package/src/manager.ts +37 -11
  51. package/src/out-of-process.ts +5 -3
  52. package/src/structured.ts +4 -1
  53. package/src/types.ts +13 -4
package/README.i18n.yaml CHANGED
@@ -15,8 +15,8 @@
15
15
  en: d152484eb41ac6b4
16
16
  zh: 09388d293f9be9cb
17
17
  /deepseek-ai-dsh-subagent/use-this-package:
18
- en: 924b8c15f9529028
19
- zh: 9fb0c399b5a79e3e
18
+ en: a1b7ee0ede0a92a4
19
+ zh: 239fea312abae13b
20
20
  /deepseek-ai-dsh-subagent/use-this-package/enabling-delegation:
21
21
  en: c0718955687ff245
22
22
  zh: eb2d3cdbe92e0fe2
@@ -24,8 +24,8 @@
24
24
  en: 86c982223fab1a3a
25
25
  zh: 3d220d8ed84eab9a
26
26
  /deepseek-ai-dsh-subagent/use-this-package/activation-capacity:
27
- en: 4b40bd380bea81ce
28
- zh: 896a584190981168
27
+ en: e71b0b167a363335
28
+ zh: 7589fd81779fd757
29
29
  /deepseek-ai-dsh-subagent/use-this-package/local-and-external-children:
30
30
  en: d6eef66bc1d293fe
31
31
  zh: e4754d38212c0b2e
@@ -39,8 +39,8 @@
39
39
  en: bf3175c2218a16dd
40
40
  zh: 4be9271efe71ddb7
41
41
  /deepseek-ai-dsh-subagent/use-this-package/failure-and-recovery:
42
- en: 0dc416ded19e304e
43
- zh: 4726e5fe5f188709
42
+ en: c097c297e75f3bd4
43
+ zh: 0b09f2870ccc6a64
44
44
  /deepseek-ai-dsh-subagent/understand-the-implementation:
45
45
  en: 74d91b364b23f88d
46
46
  zh: 19cc558105efe8df
@@ -51,8 +51,8 @@
51
51
  en: 5923a61c09d9ae04
52
52
  zh: 15202a92872a11e9
53
53
  /deepseek-ai-dsh-subagent/understand-the-implementation/provider-preparation-and-structured-output:
54
- en: 61cddba23f4e7d1c
55
- zh: 052c8331a747403f
54
+ en: 824914462110bcf1
55
+ zh: ae5ce35d09801728
56
56
  /deepseek-ai-dsh-subagent/understand-the-implementation/activation-settlement:
57
57
  en: ba22f6dd5f15f405
58
58
  zh: a469c6a4e49adea9
@@ -68,6 +68,18 @@
68
68
  /deepseek-ai-dsh-subagent/model-experience:
69
69
  en: 215e7ba838619b7b
70
70
  zh: a311da3843709f90
71
+ /deepseek-ai-dsh-subagent/model-experience/message-authorship:
72
+ en: 4350a9a08e35641b
73
+ zh: 75cd6deac5f7430a
74
+ /deepseek-ai-dsh-subagent/model-experience/message-authorship/what-the-model-sees:
75
+ en: 572bb322919ae1cb
76
+ zh: 5c49bbd85cf0fd31
77
+ /deepseek-ai-dsh-subagent/model-experience/message-authorship/token-effect:
78
+ en: 8611aab0a4bcb5b4
79
+ zh: c2286d8a73b818ac
80
+ /deepseek-ai-dsh-subagent/model-experience/message-authorship/kv-cache-effect:
81
+ en: 55d5610dcc9049e3
82
+ zh: 382e85de9c81cb11
71
83
  /deepseek-ai-dsh-subagent/model-experience/settlement-notice:
72
84
  en: f7cec22ba9d3fb4f
73
85
  zh: 67b1d40f9b136f71
package/README.md CHANGED
@@ -25,7 +25,7 @@ Use `dsh-subagent` to delegate work through named providers and collect managed
25
25
  <a id="use-this-package"></a>
26
26
  ## Use this package
27
27
 
28
- Each start accepts an optional `cwd`; relative paths resolve against the parent's current working directory, and omission captures that current directory. The child keeps its parent's origin metadata and permission roots. A child-owned directory value follows any inherited history, survives continuation and restart, and is independent of later parent changes.
28
+ Each start accepts an optional Host-chosen `cwd`; a relative path resolves against the parent's current directory, and omission starts the child in that directory. The child keeps its parent's origin metadata and enters its starting directory through `ctx.workingDirectory.set`. A child-owned directory value follows any inherited history, survives continuation and restart, and is independent of later parent changes.
29
29
 
30
30
  This package is the contract every delegation setup shares. You enable it by mounting the service together with one or more provider backends and the model-facing delegation tool; from then on, an agent can delegate work and the service routes each request to the named provider.
31
31
 
@@ -52,7 +52,9 @@ The limits section on the **Plugins → Subagent** page edits the Host’s `suba
52
52
 
53
53
  Set `maxActiveSubagents` on the host plugin to limit live and materializing children in each subagent tree. It defaults to `8` and accepts positive safe integers. A top-level parent starts a pool shared by its local and external descendants; the root parent consumes no slot. Creation and cold resume reserve before yielding, and disposal returns the slot only after cleanup. Instances with pending inbox work and stopping activations remain counted. Sending to a resident child reuses its slot. Delegation depth is a separate policy.
54
54
 
55
- The current `maxActiveSubagents` value is sampled before every new or cold-resumed Activation. Raising it admits more children in existing trees; lowering it leaves resident children running and refuses further admissions until usage is below the limit.
55
+ Consumers read the current limit through `ctx.subagents.maxActiveSubagents`; admission samples the same value before every new or cold-resumed Activation. Raising it admits more children in existing trees; lowering it leaves resident children running and refuses further admissions until usage is below the limit.
56
+
57
+ `ctx.subagents.capacityOf(caller)` returns `{ running, limit }` for the live caller's tree. `running` counts occupied slots, including starting, idle resident, stopping, and external children; it excludes the root and may exceed `limit` after a decrease. Reading capacity reserves no slot.
56
58
 
57
59
  At capacity, creation or cold resume rejects with `ACTIVATION_LIMIT_REACHED` (browser prompts receive `subagent/delivery-unavailable`): wait for a child to finish or continue using the existing agents. Admission does not queue, because a parent waiting for descendants must not wait for its own occupied slot. Slots are process-local and do not constrain cumulative Session history or token usage.
58
60
 
@@ -79,7 +81,7 @@ In-process spawn accepts an independent `agentPreset`; fork and external backend
79
81
 
80
82
  ### Failure and recovery
81
83
 
82
- Starting without the `agents` service rejects with `CONTINUATION_UNAVAILABLE`; an available runtime rejects a missing or replaced parent with `UNAUTHORIZED`. Providers implementing neither execution method are rejected at registration with `UNSUPPORTED_CAPABILITY`; unsupported requested capabilities reject creation with the same code. If a provider is removed or replaced while directory resolution is pending, creation rejects with `PROVIDER_CHANGED` before invoking either provider; retry the delegation against the current registration. The caller signal cancels only unpublished work; after publication, `dispose()` cancels the exact activation and waits for its resource cleanup. Creation descendants continue independently; hosts must await `drainDescendants([root])` before disposing the root handle to stop all members and await pending startup. `result` settles after teardown and notifications, carrying output, optional structured data, and a stop reason; capture failures reject it after teardown. Cleanup failures reject `dispose()` and mark the lifecycle end as failed; the result promise and parent notification retain the captured execution result.
84
+ Every `SubagentError` carries one code from the closed `SubagentErrorCode` union in [`src/error.ts`](src/error.ts), which documents each condition. Starting without the `agents` service rejects with `CONTINUATION_UNAVAILABLE`; an available runtime rejects a missing or replaced parent with `UNAUTHORIZED`. Providers implementing neither execution method are rejected at registration with `UNSUPPORTED_CAPABILITY`; unsupported requested capabilities reject creation with the same code. If a provider is removed or replaced while directory resolution is pending, creation rejects with `PROVIDER_CHANGED` before invoking either provider; retry the delegation against the current registration. Every creation failure below is a `SubagentError`: a child beyond the requested depth rejects with the `SubagentDepthError` subclass and `DEPTH_EXCEEDED`, an invalid runtime `subagentDepth` with `INVALID_DEPTH`, a selected preset without the preset service with `PRESET_UNAVAILABLE` (an unknown or unloadable selected preset keeps the registry's `RemoteError` code), a local child without the working-directory service with `WORKING_DIRECTORY_UNAVAILABLE`, and an out-of-process child whose cwd is relative or not enterable with `INVALID_CWD`. A cold target whose persisted descriptor is corrupt rejects with `NOT_RESUMABLE`, and `structured_output` called while input is pending fails with `STRUCTURED_OUTPUT_PENDING_INPUT`. The caller signal cancels only unpublished work; after publication, `dispose()` cancels the exact activation and waits for its resource cleanup. Creation descendants continue independently; hosts must await `drainDescendants([root])` before disposing the root handle to stop all members and await pending startup. `result` settles after teardown and notifications, carrying output, optional structured data, and a stop reason; capture failures reject it after teardown. Cleanup failures reject `dispose()` and mark the lifecycle end as failed; the result promise and parent notification retain the captured execution result.
83
85
 
84
86
  -----
85
87
 
@@ -118,7 +120,7 @@ This section explains how the service is built and where the observable behavior
118
120
 
119
121
  ### Provider preparation and structured output
120
122
 
121
- The service validates requested capabilities and binds execution to that exact provider instance before creation. The manager receives the bound operation rather than a provider lookup. Local providers supply only `prepareContinuable()`: spawn returns fresh state and fork returns a completed-turn seed. The manager captures the parent model settings, delegated permissions, and composition before creating the child. External providers retain `start()` as a transport adapter and retain their own permission systems. The common manager owns their published execution. Structured tools, instructions, validation, and terminal guards belong to one local activation; they are not persisted as resume configuration. The child can submit its structured result after consuming accepted input. Work that depends on descendants must explicitly wait for their results. Staging a result closes further input through tool-result policy and any enclosing PTC execution; a rejected result reopens input, while a committed result keeps it closed. Later cold resume has no structured schema.
123
+ The service validates requested capabilities and binds execution to that exact provider instance before creation. The manager receives the bound operation rather than a provider lookup. Local providers supply only `prepareContinuable()`: spawn returns fresh state and fork returns an unmodified completed-turn prefix. The manager forwards that prefix as the seed and its length as the fork cut. The manager captures the parent model settings, delegated permissions, and composition before creating the child. External providers retain `start()` as a transport adapter and retain their own permission systems. The common manager owns their published execution. Structured tools, instructions, validation, and terminal guards belong to one local activation; they are not persisted as resume configuration. The child can submit its structured result after consuming accepted input. Work that depends on descendants must explicitly wait for their results. Staging a result closes further input through tool-result policy and any enclosing PTC execution; a rejected result reopens input, while a committed result keeps it closed. Later cold resume has no structured schema.
122
124
 
123
125
  External providers mint a fresh `SubagentRun.id` for each execution in the runtime's shared Session id namespace, across all parents and providers. A collision with a resident Agent, Session, or activation rejects startup with `DUPLICATE_CHILD` and disposes the new external handle without replacing the existing execution.
124
126
 
@@ -170,6 +172,20 @@ Read these pages when the package-level contract is not enough. They move from t
170
172
  <a id="model-experience"></a>
171
173
  ## Model Experience
172
174
 
175
+ ### Message authorship
176
+
177
+ #### What the model sees
178
+
179
+ Local continuable agents receive initial delegated tasks and later agent-to-agent messages with the `agent-message` source and the actual sender's Session id. Both start with `Agent <sender name> sent a message: ` followed by the supplied content blocks. Direct human messages keep their original content and `user` source. The child delegation-scope statement below tells the child that user messages without the agent prefix come from the human user and that it answers them in its reply. Root input and retained history are unchanged.
180
+
181
+ #### Token effect
182
+
183
+ One short author prefix per initial delegated task or agent-to-agent message. Human input adds no attribution tokens; the authorship rule is part of the child's fixed delegation statement.
184
+
185
+ #### KV Cache effect
186
+
187
+ The initial task follows any inherited history; later messages append without changing retained history.
188
+
173
189
  ### Settlement notice
174
190
 
175
191
  #### What the model sees
@@ -213,7 +229,7 @@ Every in-process child's runtime-context snapshot carries the `subagent:delegati
213
229
  ##### The delegation-scope statement
214
230
 
215
231
  ```markdown
216
- You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the job needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.
232
+ You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it. Messages from other agents begin with "Agent <name> sent a message:". Other user messages come from the human user, who reads this conversation directly. You can still message other agents to coordinate, but answer the human user in your reply.
217
233
  ```
218
234
 
219
235
  #### Token effect
package/README.zh.md CHANGED
@@ -25,7 +25,7 @@ kind: "package-reference"
25
25
  <a id="use-this-package"></a>
26
26
  ## 使用本包
27
27
 
28
- 每次启动可传入可选的 `cwd`;相对路径以父级当前工作目录解析,省略时捕获该当前目录。子级保留父级的起始目录元数据与权限根目录。子级自己的目录值位于继承历史之后,在继续与重启后保留,并独立于父级之后的目录变化。
28
+ 每次启动可传入由 Host 选定的可选 `cwd`;相对路径以父级的当前目录解析,省略时子级从该目录启动。子级保留父级的起始目录元数据,并通过 `ctx.workingDirectory.set` 进入它的起始目录。子级自己的目录值位于继承历史之后,在继续与重启后保留,并独立于父级之后的目录变化。
29
29
 
30
30
  本包是每个委派组合都共享的约定。你通过把服务与一个或多个提供方后端以及面向模型的委派工具一起挂载来启用它;此后 agent 即可委派工作,服务会把每个请求路由到具名提供方。
31
31
 
@@ -52,7 +52,9 @@ kind: "package-reference"
52
52
 
53
53
  在 Host 插件上设置 `maxActiveSubagents`,限制每棵 subagent 树中在线和正在创建的子级数量。默认值为 `8`,接受正安全整数。顶层父级建立由本地和外部后代共享的池,根父级不占名额。新建和冷恢复在让出执行前预留名额,资源释放完成后才归还。有待处理收件箱内容以及正在停止的 activation 仍计入容量;向驻留子级发送消息复用其名额。委派深度是独立策略。
54
54
 
55
- 每次新建或冷恢复 Activation 前都会读取当前 `maxActiveSubagents`。调高后已有树可接纳更多子代理;调低后驻留子代理继续运行,使用量降至上限以下前拒绝新接纳。
55
+ 调用方通过 `ctx.subagents.maxActiveSubagents` 读取当前上限;每次新建或冷恢复 Activation 前,准入也读取同一个值。调高后已有树可接纳更多子代理;调低后驻留子代理继续运行,使用量降至上限以下前拒绝新接纳。
56
+
57
+ `ctx.subagents.capacityOf(caller)` 返回在线调用方所在树的 `{ running, limit }`。`running` 统计已占用名额,包含启动中、空闲驻留、停止中和外部子级;不包含根,且调低上限后可以超过 `limit`。读取容量不会预留名额。
56
58
 
57
59
  容量耗尽时,新建或冷恢复以 `ACTIVATION_LIMIT_REACHED` 拒绝(浏览器消息返回 `subagent/delivery-unavailable`):等待子代理完成,或继续使用现有代理。接纳不会排队,避免等待后代的父代理又等待自己占用的名额。名额仅存在于当前进程,不限制累计 Session 历史或 token 用量。
58
60
 
@@ -79,7 +81,7 @@ kind: "package-reference"
79
81
 
80
82
  ### 失败与恢复
81
83
 
82
- 缺少 `agents` 服务时,启动请求以 `CONTINUATION_UNAVAILABLE` 拒绝;运行时可用但父级缺失或被替换时,以 `UNAUTHORIZED` 拒绝。未实现任何执行方法的提供方会在注册时以 `UNSUPPORTED_CAPABILITY` 被拒绝;请求不受支持的能力会以同一码使创建失败。如果等待目录解析期间提供方被移除或替换,创建会在调用任何一方之前以 `PROVIDER_CHANGED` 拒绝;调用方可根据当前注册重试委派。调用方信号仅取消尚未发布的工作;发布后通过 `dispose()` 取消该次 activation,并等待其资源清理完成。创建后代独立继续运行;宿主必须在释放根句柄前等待 `drainDescendants([root])`,以停止所有成员并等待正在启动的工作。`result` 在清理与通知结束后完成,携带输出、可选结构化数据与停止原因;结果捕获故障在清理后使其拒绝。清理失败使 `dispose()` 拒绝,并将生命周期结束事件标记为失败;结果 promise 与父级通知保留已捕获的执行结果。
84
+ 每个 `SubagentError` 都携带 [`src/error.ts`](src/error.ts) 中封闭联合类型 `SubagentErrorCode` 的一个 code,该文件逐条说明各条件。缺少 `agents` 服务时,启动请求以 `CONTINUATION_UNAVAILABLE` 拒绝;运行时可用但父级缺失或被替换时,以 `UNAUTHORIZED` 拒绝。未实现任何执行方法的提供方会在注册时以 `UNSUPPORTED_CAPABILITY` 被拒绝;请求不受支持的能力会以同一码使创建失败。如果等待目录解析期间提供方被移除或替换,创建会在调用任何一方之前以 `PROVIDER_CHANGED` 拒绝;调用方可根据当前注册重试委派。以下创建失败均为 `SubagentError`:超出请求深度的子代以 `SubagentDepthError` 子类和 `DEPTH_EXCEEDED` 拒绝,无效的运行时 `subagentDepth` 以 `INVALID_DEPTH` 拒绝,选择了 preset 但缺少 preset 服务时以 `PRESET_UNAVAILABLE` 拒绝(所选 preset 未知或无法加载时保留 registry 的 `RemoteError` code),缺少工作目录服务的本地子代以 `WORKING_DIRECTORY_UNAVAILABLE` 拒绝,cwd 为相对路径或不可进入的进程外子代以 `INVALID_CWD` 拒绝。持久化 descriptor 损坏的冷目标以 `NOT_RESUMABLE` 拒绝,有待处理输入时调用 `structured_output` 以 `STRUCTURED_OUTPUT_PENDING_INPUT` 失败。调用方信号仅取消尚未发布的工作;发布后通过 `dispose()` 取消该次 activation,并等待其资源清理完成。创建后代独立继续运行;宿主必须在释放根句柄前等待 `drainDescendants([root])`,以停止所有成员并等待正在启动的工作。`result` 在清理与通知结束后完成,携带输出、可选结构化数据与停止原因;结果捕获故障在清理后使其拒绝。清理失败使 `dispose()` 拒绝,并将生命周期结束事件标记为失败;结果 promise 与父级通知保留已捕获的执行结果。
83
85
 
84
86
  -----
85
87
 
@@ -118,7 +120,7 @@ kind: "package-reference"
118
120
 
119
121
  ### 提供方准备与结构化输出
120
122
 
121
- 服务在创建前校验请求能力,并把执行绑定到该确切提供方实例。管理器接收绑定后的操作,而不再按名称查找提供方。本地提供方只提供 `prepareContinuable()`:spawn 返回全新状态,fork 返回已完成轮次的初始内容。管理器在创建子级前捕获父级模型设置、委派权限和组合。外部提供方保留 `start()` 作为传输适配器,并保留各自的权限系统;统一管理器拥有已发布的执行。结构化工具、指令、校验与终止保护仅属于一次本地 activation,不作为恢复配置持久化。子代理消费已接受的输入后即可提交结构化结果。依赖后代结果的工作必须显式等待。结果暂存后,在工具结果策略及外层 PTC 执行完成前拒绝继续输入;结果被拒绝后重新开放输入,提交成功后则保持关闭。后续冷恢复不带结构化 schema。
123
+ 服务在创建前校验请求能力,并把执行绑定到该确切提供方实例。管理器接收绑定后的操作,而不再按名称查找提供方。本地提供方只提供 `prepareContinuable()`:spawn 返回全新状态,fork 返回未经变换的已完成轮次前缀。管理器将该前缀作为 seed、其长度作为 fork 截点传递。管理器在创建子级前捕获父级模型设置、委派权限和组合。外部提供方保留 `start()` 作为传输适配器,并保留各自的权限系统;统一管理器拥有已发布的执行。结构化工具、指令、校验与终止保护仅属于一次本地 activation,不作为恢复配置持久化。子代理消费已接受的输入后即可提交结构化结果。依赖后代结果的工作必须显式等待。结果暂存后,在工具结果策略及外层 PTC 执行完成前拒绝继续输入;结果被拒绝后重新开放输入,提交成功后则保持关闭。后续冷恢复不带结构化 schema。
122
124
 
123
125
  外部提供方为每次执行生成新的 `SubagentRun.id`,在运行时共享的 Session id 命名空间中跨所有父级和提供方保持唯一。与驻留 Agent、Session 或 activation 冲突时,启动以 `DUPLICATE_CHILD` 拒绝,并释放新的外部句柄,不替换已有执行。
124
126
 
@@ -170,6 +172,20 @@ kind: "package-reference"
170
172
  <a id="model-experience"></a>
171
173
  ## 模型体验
172
174
 
175
+ ### 消息作者
176
+
177
+ #### 模型看到什么
178
+
179
+ 本地可续聊 agent 收到的初始委派任务与后续 agent 间消息都使用 `agent-message` source,并记录实际发送方的 Session ID。两者均以 `Agent <sender name> sent a message: ` 开头,后接原始内容块。真人直接发给子会话的消息保留原始内容和 `user` source。下方的子级委派范围声明告诉子 agent:不带 agent 前缀的 user 消息来自真人用户,并应在回复中直接回答。主 agent 的输入与已有历史不变。
180
+
181
+ #### Token 影响
182
+
183
+ 每条初始委派任务或 agent 间消息增加一个简短作者前缀。真人输入不增加来源 token;作者规则属于子 agent 固定的委派声明。
184
+
185
+ #### KV Cache 影响
186
+
187
+ 初始任务位于继承历史之后;后续消息只追加,不改写已有历史。
188
+
173
189
  ### 结算通知
174
190
 
175
191
  #### 模型看到什么
@@ -213,7 +229,7 @@ Your final answer is delivered automatically if your parent is still online. Inc
213
229
  ##### 委派范围声明
214
230
 
215
231
  ```markdown
216
- You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the job needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.
232
+ You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it. Messages from other agents begin with "Agent <name> sent a message:". Other user messages come from the human user, who reads this conversation directly. You can still message other agents to coordinate, but answer the human user in your reply.
217
233
  ```
218
234
 
219
235
  #### Token 影响
package/lib/index.js CHANGED
@@ -7,11 +7,12 @@ import { canonicalClientTimeZone } from "@deepseek-ai/dsh-util-time";
7
7
  import { Remote, RemoteError, TypertRemoteService, principalOf } from "@deepseek-ai/dsh-typert-protocol";
8
8
  import { AttachmentError } from "@deepseek-ai/dsh-attachment";
9
9
  import { z as z$1 } from "zod";
10
- import { HarnessError, ReasoningEffortId, boundContextSummary, contentHasImage, createUserMessage, errorChain, joinAssistantStreamText } from "@deepseek-ai/dsh-llm";
10
+ import { HarnessError, boundContextSummary, contentHasImage, createUserMessage, errorChain, joinAssistantStreamText } from "@deepseek-ai/dsh-llm";
11
11
  import { foldConsumedWork } from "@deepseek-ai/dsh-agent";
12
12
  import { randomUUID } from "node:crypto";
13
13
  import { isAbsolute, resolve } from "node:path";
14
14
  import { SessionLogOffset, SessionSeq } from "@deepseek-ai/dsh-session";
15
+ import { PERSONA_PREFIX_SECTION } from "@deepseek-ai/dsh-system-prompt";
15
16
  import { assertNever, snapshotJsonValue } from "@deepseek-ai/dsh-util-values";
16
17
  import { appendChunkedList, chunkedListSchema, iterateChunkedList } from "@deepseek-ai/dsh-chunked-list";
17
18
  import { accessSync, constants, statSync } from "node:fs";
@@ -21,11 +22,18 @@ import { accessSync, constants, statSync } from "node:fs";
21
22
  *
22
23
  * @module @deepseek-ai/dsh-subagent
23
24
  */
24
- /** Typed failure for the subagent seam. */
25
+ /** Typed failure for the subagent seam; `code` is one {@link SubagentErrorCode}. */
25
26
  var SubagentError = class extends HarnessError {
27
+ code;
28
+ /**
29
+ * @param message - reason and next step for the caller.
30
+ * @param code - failure class.
31
+ * @param options - standard `cause` chaining.
32
+ */
26
33
  constructor(message, code, options) {
27
34
  super(message, code, options);
28
35
  this.name = "SubagentError";
36
+ this.code = code;
29
37
  }
30
38
  };
31
39
  //#endregion
@@ -101,11 +109,11 @@ function isCancellation(error, signal) {
101
109
  * let it delegate as if it were top-level.
102
110
  * @param agent - the agent whose header and options carry the depth.
103
111
  * @returns its non-negative safe-integer depth.
104
- * @throws if the runtime `AgentOptions.subagentDepth` is not a non-negative safe integer.
112
+ * @throws {SubagentError} `INVALID_DEPTH` if the runtime `AgentOptions.subagentDepth` is not a non-negative safe integer.
105
113
  */
106
114
  function delegationDepthOf(agent) {
107
115
  const runtime = agent.options.subagentDepth;
108
- if (runtime !== void 0 && (!Number.isSafeInteger(runtime) || runtime < 0 || Object.is(runtime, -0))) throw new TypeError("agent subagentDepth must be a non-negative safe integer");
116
+ if (runtime !== void 0 && (!Number.isSafeInteger(runtime) || runtime < 0 || Object.is(runtime, -0))) throw new SubagentError("agent subagentDepth must be a non-negative safe integer", "INVALID_DEPTH");
109
117
  return Math.max(agent.session.header.delegationDepth ?? 0, runtime ?? 0);
110
118
  }
111
119
  /**
@@ -201,12 +209,12 @@ function renderThrown(value) {
201
209
  *
202
210
  * @module @deepseek-ai/dsh-subagent/child-agent
203
211
  */
204
- /** Thrown when starting a child would exceed the requested depth cap. */
205
- var SubagentDepthError = class extends Error {
212
+ /** Thrown when starting a child would exceed the requested depth cap; `code` is `DEPTH_EXCEEDED`. */
213
+ var SubagentDepthError = class extends SubagentError {
206
214
  attemptedDepth;
207
215
  maxDepth;
208
216
  constructor(attemptedDepth, maxDepth) {
209
- super(`subagent depth ${attemptedDepth} exceeds maxDepth ${maxDepth}`);
217
+ super(`subagent depth ${attemptedDepth} exceeds maxDepth ${maxDepth}`, "DEPTH_EXCEEDED");
210
218
  this.attemptedDepth = attemptedDepth;
211
219
  this.maxDepth = maxDepth;
212
220
  this.name = "SubagentDepthError";
@@ -220,11 +228,11 @@ var SubagentDepthError = class extends Error {
220
228
  * @param maxDepth - optional absolute cap the resolved depth must not exceed.
221
229
  * @returns the child's non-negative safe-integer depth.
222
230
  * @throws {SubagentDepthError} when the resolved depth exceeds `maxDepth`.
223
- * @throws {RangeError} when the resolved depth leaves the safe-integer range.
231
+ * @throws {SubagentError} `INVALID_DEPTH` when the resolved depth leaves the safe-integer range.
224
232
  */
225
233
  function resolveChildDepth(parent, maxDepth) {
226
234
  const childDepth = delegationDepthOf(parent) + 1;
227
- if (!Number.isSafeInteger(childDepth)) throw new RangeError("subagent child depth exceeds the safe-integer range");
235
+ if (!Number.isSafeInteger(childDepth)) throw new SubagentError("subagent child depth exceeds the safe-integer range", "INVALID_DEPTH");
228
236
  if (maxDepth !== void 0 && childDepth > maxDepth) throw new SubagentDepthError(childDepth, maxDepth);
229
237
  return childDepth;
230
238
  }
@@ -302,11 +310,11 @@ function childSessionMeta(parent, childDepth, isSeeded, selectedPreset) {
302
310
  };
303
311
  }
304
312
  /**
305
- * Model-facing delegation-scope statement for every in-process child. A
313
+ * Model-facing delegation-scope and message-authorship statement for every in-process child. A
306
314
  * runtime-context contribution rather than a system-prompt section, so the
307
315
  * deployment's system prompt stays uniform across parents and children.
308
316
  */
309
- const SUBAGENT_DELEGATION_CONTEXT = "You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.";
317
+ const SUBAGENT_DELEGATION_CONTEXT = "You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it. Messages from other agents begin with \"Agent <name> sent a message:\". Other user messages come from the human user, who reads this conversation directly. You can still message other agents to coordinate, but answer the human user in your reply.";
310
318
  /**
311
319
  * Compose a child before publication and restore historical descriptor overrides.
312
320
  * Explicit selection mounts the named preset. Omission joins a supplied creator's
@@ -316,6 +324,9 @@ const SUBAGENT_DELEGATION_CONTEXT = "You are a delegated subagent: your permissi
316
324
  * @param parent - creator for fresh delegation; absent during target-only restoration.
317
325
  * @param composition - independent preset and any overrides read from a historical descriptor.
318
326
  * @returns A promise when mounting an independent preset; otherwise completes synchronously.
327
+ * @throws {SubagentError} `PRESET_UNAVAILABLE` when a preset is selected but the preset
328
+ * service is absent. An unknown or unloadable selected preset rejects with the registry's
329
+ * `RemoteError` code.
319
330
  */
320
331
  function applyChildComposition(childCtx, parent, composition) {
321
332
  if (composition.agentPreset !== void 0) {
@@ -335,7 +346,7 @@ function applyChildOverrides(childCtx, composition) {
335
346
  text: SUBAGENT_DELEGATION_CONTEXT
336
347
  });
337
348
  if (composition.persona !== void 0) childCtx.systemPrompt.section({
338
- name: "deployment:persona-prefix",
349
+ name: PERSONA_PREFIX_SECTION,
339
350
  order: childCtx.systemPrompt.getSectionOrder("DEPLOYMENT_PERSONA_PREFIX"),
340
351
  text: composition.persona
341
352
  });
@@ -969,24 +980,6 @@ function catalogNames(entries) {
969
980
  return names;
970
981
  }
971
982
  //#endregion
972
- //#region lib/types/types.js
973
- /**
974
- * The seam's consumer-facing contracts: request, result, and capability types
975
- * for {@link SubagentProvider}, plus the `subagent/start` and `subagent/end`
976
- * payloads that plugins and hosts observe. Internal control interfaces, such
977
- * as the manager host, belong with their implementation.
978
- *
979
- * @module @deepseek-ai/dsh-subagent/types
980
- */
981
- /**
982
- * Brand a string as a {@link SubagentRunId}.
983
- * @param id - the raw run id.
984
- * @returns the same string, branded.
985
- */
986
- function SubagentRunId(id) {
987
- return id;
988
- }
989
- //#endregion
990
983
  //#region lib/types/structured.js
991
984
  /**
992
985
  * Child-scoped structured-output tool, prompt instruction, terminal guard, and authoritative
@@ -1055,7 +1048,7 @@ function attachStructuredRuntime(childCtx, schema, canComplete) {
1055
1048
  execute(args, exec) {
1056
1049
  const violations = validateJsonSchemaValue(schema, args);
1057
1050
  if (violations.length > 0) throw new ToolArgsError(violations);
1058
- if (!canComplete()) throw new Error("Process pending messages before submitting structured output.");
1051
+ if (!canComplete()) throw new SubagentError("Process pending messages before submitting structured output.", "STRUCTURED_OUTPUT_PENDING_INPUT");
1059
1052
  staged.set(exec, { value: args });
1060
1053
  exec.concludeTurn();
1061
1054
  return Promise.resolve({ recorded: true });
@@ -1168,6 +1161,10 @@ function finalAssistantOutput(events) {
1168
1161
  /** Process-local capacity shared by every member of a subagent tree. */
1169
1162
  var ActivationPool = class {
1170
1163
  slots = /* @__PURE__ */ new Set();
1164
+ /** Slots reserved by starting, resident, or stopping children. */
1165
+ get size() {
1166
+ return this.slots.size;
1167
+ }
1171
1168
  /**
1172
1169
  * Reserve before reconstruction; release also tolerates unpublished rollback.
1173
1170
  * @param capacity - the maximum simultaneous activations in this pool.
@@ -1554,8 +1551,9 @@ var SubagentManager = class {
1554
1551
  });
1555
1552
  established = activation;
1556
1553
  const childHeader = requireLocalActivation(activation).handle.agent.session.header;
1557
- return await this.submitMaterialized(activation, spec.delivery !== "caller" ? withResultDeliveryGuidance(spec.prompt) : spec.prompt, {
1558
- source: { kind: "user" },
1554
+ const task = createAgentMessage(parent, agentAddress(this.pathOf(parent, ancestry.root), parent.id), spec.prompt);
1555
+ return await this.submitMaterialized(activation, spec.delivery !== "caller" ? withResultDeliveryGuidance([...task.content]) : [...task.content], {
1556
+ source: task.source,
1559
1557
  signal,
1560
1558
  delivery: "queue",
1561
1559
  authorize: () => {
@@ -1900,6 +1898,17 @@ var SubagentManager = class {
1900
1898
  const root = this.rootOf(agent);
1901
1899
  return this.closingRoots.has(root) ? root : void 0;
1902
1900
  }
1901
+ /**
1902
+ * Observe the shared capacity of a live tree member.
1903
+ * @param caller - exact live root or resident child selecting the tree.
1904
+ * @returns occupied slots and the current configured limit, without reserving capacity.
1905
+ */
1906
+ capacityOf(caller) {
1907
+ return {
1908
+ running: this.rootPools.get(this.rootOf(caller))?.size ?? 0,
1909
+ limit: this.maxActiveSubagents()
1910
+ };
1911
+ }
1903
1912
  /** Share one capacity pool across every instance in a subagent tree. */
1904
1913
  rootPool(parent) {
1905
1914
  let pool = this.rootPools.get(parent);
@@ -1947,7 +1956,7 @@ var SubagentManager = class {
1947
1956
  child.session.append("subagent/descriptor", create.descriptor);
1948
1957
  appendDelegatedPolicyOverrides(child.session, create.delegatedPolicies);
1949
1958
  const workingDirectory = childCtx.get("workingDirectory");
1950
- if (workingDirectory === void 0) throw new Error("local subagents require the working-directory service");
1959
+ if (workingDirectory === void 0) throw new SubagentError("local subagents require the working-directory service", "WORKING_DIRECTORY_UNAVAILABLE");
1951
1960
  await workingDirectory.set(child, create.cwd, inputs.signal);
1952
1961
  }
1953
1962
  if (inputs.composition.agentPreset === void 0) await applyChildComposition(childCtx, create?.parent, inputs.composition);
@@ -1961,7 +1970,13 @@ var SubagentManager = class {
1961
1970
  }) : await this.ownerCtx.agents.create({
1962
1971
  sessionId: childId,
1963
1972
  meta: create.meta,
1964
- ...create.seed === void 0 ? {} : { seed: create.seed },
1973
+ ...create.seed === void 0 ? {} : {
1974
+ seed: create.seed,
1975
+ parentSource: {
1976
+ sessionId: create.parent.id,
1977
+ endSeq: SessionLogOffset(create.seed.length)
1978
+ }
1979
+ },
1965
1980
  inheritedEventCount: create.inheritedEventCount,
1966
1981
  agentOptions: inputs.agentOptions,
1967
1982
  signal: inputs.signal,
@@ -1981,7 +1996,7 @@ var SubagentManager = class {
1981
1996
  const activation = {
1982
1997
  releaseSlot,
1983
1998
  childId,
1984
- runId: SubagentRunId(randomUUID()),
1999
+ runId: brandString(randomUUID()),
1985
2000
  provider,
1986
2001
  ...resource,
1987
2002
  root,
@@ -2267,7 +2282,13 @@ var SubagentManager = class {
2267
2282
  try {
2268
2283
  const source = __addDisposableResource$1(env_3, await this.observeContinuation(childId, signal), false);
2269
2284
  this.assertAdmitting(root);
2270
- const descriptor = foldSubagentDescriptor(source.events.slice(source.inheritedEventCount));
2285
+ const ownEvents = source.events.slice(source.inheritedEventCount);
2286
+ let descriptor;
2287
+ try {
2288
+ descriptor = foldSubagentDescriptor(ownEvents);
2289
+ } catch (error) {
2290
+ throw new SubagentError(`subagent "${childId}" has a corrupt continuation descriptor and cannot be resumed; choose a different target`, "NOT_RESUMABLE", { cause: error });
2291
+ }
2271
2292
  if (descriptor === void 0 || descriptor.mode !== "continuable") throw new SubagentError(`subagent "${childId}" has no supported continuation state and cannot be resumed; choose a different target`, "NOT_RESUMABLE");
2272
2293
  const { ancestors, path } = await this.resolveCreationAncestry(source, signal, root);
2273
2294
  let activation;
@@ -2285,7 +2306,7 @@ var SubagentManager = class {
2285
2306
  agentOptions: {
2286
2307
  ...descriptor.agentProvider !== void 0 ? { provider: descriptor.agentProvider } : {},
2287
2308
  ...descriptor.agentModel !== void 0 ? { model: descriptor.agentModel } : {},
2288
- ...descriptor.agentReasoningEffort !== void 0 ? { reasoningEffort: ReasoningEffortId(descriptor.agentReasoningEffort) } : {}
2309
+ ...descriptor.agentReasoningEffort !== void 0 ? { reasoningEffort: brandString(descriptor.agentReasoningEffort) } : {}
2289
2310
  },
2290
2311
  composition: {
2291
2312
  agentPreset: agentPreset ?? void 0,
@@ -2803,10 +2824,11 @@ function isEnterableDirectory(path) {
2803
2824
  * @param label - which source supplied the value, for the diagnostic.
2804
2825
  * @param cwd - the candidate working directory.
2805
2826
  * @returns `cwd`, validated.
2827
+ * @throws {SubagentError} `INVALID_CWD` when `cwd` is relative or not an enterable directory.
2806
2828
  */
2807
2829
  function assertUsableCwd(prefix, label, cwd) {
2808
- if (!isAbsolute(cwd)) throw new Error(`${prefix}: ${label} must be an absolute path: ${cwd}`);
2809
- if (!isEnterableDirectory(cwd)) throw new Error(`${prefix}: ${label} is not an accessible directory: ${cwd}`);
2830
+ if (!isAbsolute(cwd)) throw new SubagentError(`${prefix}: ${label} must be an absolute path: ${cwd}`, "INVALID_CWD");
2831
+ if (!isEnterableDirectory(cwd)) throw new SubagentError(`${prefix}: ${label} is not an accessible directory: ${cwd}`, "INVALID_CWD");
2810
2832
  return cwd;
2811
2833
  }
2812
2834
  /** Normalize an unknown thrown value to an Error (the catch binding is `unknown`). */
@@ -2838,7 +2860,7 @@ async function settleRunResult(parts) {
2838
2860
  };
2839
2861
  try {
2840
2862
  parts.onError?.(toError(error), "error");
2841
- } catch {}
2863
+ } catch (_diagnosticSinkFailed) {}
2842
2864
  const collected = parts.collectDiagnostic?.();
2843
2865
  const diagnostic = collected === void 0 ? void 0 : limitSubagentDiagnostic(collected);
2844
2866
  return {
@@ -2873,6 +2895,24 @@ function subprocessRunHandle(parts) {
2873
2895
  };
2874
2896
  }
2875
2897
  //#endregion
2898
+ //#region lib/types/types.js
2899
+ /**
2900
+ * The seam's consumer-facing contracts: request, result, and capability types
2901
+ * for {@link SubagentProvider}, plus the `subagent/start` and `subagent/end`
2902
+ * payloads that plugins and hosts observe. Internal control interfaces, such
2903
+ * as the manager host, belong with their implementation.
2904
+ *
2905
+ * @module @deepseek-ai/dsh-subagent/types
2906
+ */
2907
+ /**
2908
+ * Brand a string as a {@link SubagentRunId}.
2909
+ * @param id - the raw run id.
2910
+ * @returns the same string, branded.
2911
+ */
2912
+ function SubagentRunId(id) {
2913
+ return id;
2914
+ }
2915
+ //#endregion
2876
2916
  //#region lib/types/index.js
2877
2917
  var __runInitializers = function(thisArg, initializers, value) {
2878
2918
  var useValue = arguments.length > 2;
@@ -2988,7 +3028,7 @@ let SubagentRuntime = (() => {
2988
3028
  identityOf: (session) => identityProjection.stateOf(session).identity,
2989
3029
  catalogOf: (session) => subagentCatalogProjectionDefinition.wire.view(catalogProjection.stateOf(session)),
2990
3030
  emitLifecycle: this.emitLifecycle
2991
- }, () => this.config.maxActiveSubagents.get());
3031
+ }, () => this.maxActiveSubagents);
2992
3032
  this.manager = manager;
2993
3033
  childCtx.effect(() => () => {
2994
3034
  /* v8 ignore else -- one injected binding owns the slot until its fiber disposes. */
@@ -2996,6 +3036,10 @@ let SubagentRuntime = (() => {
2996
3036
  }, "subagents.managerBinding()");
2997
3037
  });
2998
3038
  }
3039
+ /** Current concurrency limit shared by all descendants in each subagent tree. */
3040
+ get maxActiveSubagents() {
3041
+ return this.config.maxActiveSubagents.get();
3042
+ }
2999
3043
  /**
3000
3044
  * Resolve a delegation tool's depth policy against the current user setting.
3001
3045
  * @param configured - Explicit tool limit, or provider-managed for external delegation.
@@ -3044,6 +3088,14 @@ let SubagentRuntime = (() => {
3044
3088
  return this.requireManager().rootOf(caller);
3045
3089
  }
3046
3090
  /**
3091
+ * Observe the shared concurrency capacity of the caller's subagent tree.
3092
+ * @param caller - exact live root or resident tree member.
3093
+ * @returns occupied slots and the current limit; this observation reserves no capacity.
3094
+ */
3095
+ capacityOf(caller) {
3096
+ return this.requireManager().capacityOf(caller);
3097
+ }
3098
+ /**
3047
3099
  * Report the model-facing names of a live tree member and its direct creator.
3048
3100
  * The root is `lead`; a descendant is the slash-separated path of names from
3049
3101
  * the root, or its Session id when it or a creator below the root has no name.