@x1a0f3n9/dsh-subagent-in-process-driver 0.1.5-rc.2

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 DeepSeek
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,6 @@
1
+ # Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
2
+ # side as of the last confirmed-consistent state. Both languages carry equal authority;
3
+ # after editing either side, bring the other along and re-record with:
4
+ # pnpm run verify-translation-pairing --write packages/subagent/subagent-in-process-driver/README.md
5
+ README.md: fe9703a2bc735cfea81dbf921488edb786335f6f
6
+ README.zh.md: 5ee7447829985b71d7f2004bfaa94a98fc187ea1
package/README.md ADDED
@@ -0,0 +1,177 @@
1
+ ---
2
+ description: "Shared in-process subagent run driver for maintainers and backend authors who need to understand or extend the spawn and fork run lifecycle."
3
+ kind: "package-library"
4
+ ---
5
+
6
+ # @x1a0f3n9/dsh-subagent-in-process-driver
7
+
8
+ English | [中文](README.zh.md)
9
+
10
+ ## Summary
11
+
12
+ `dsh-subagent-in-process-driver` is the shared run driver behind the two in-process subagent backends: it creates one child agent through the host's agent factory, applies per-child customization, drives one task to completion, and returns the child's own final output with a single quiescent disposal path. Spawn calls it with no session seed; fork calls it with the parent's completed-turn prefix. It is a library, not a standalone feature: provider backends call `startInProcessRun`, and nothing in a composition configures it. Read this page to understand the run lifecycle both in-process backends share.
13
+
14
+ ## Table of Contents
15
+
16
+ - [Use this package](#use-this-package)
17
+ - [Understand the implementation](#understand-the-implementation)
18
+ - [Further Exploration](#further-exploration)
19
+ - [Model Experience](#model-experience)
20
+ - [Known Limitations and Deferred Work](#known-limitations-and-deferred-work)
21
+ - [Dev Note](#dev-note)
22
+
23
+ -----
24
+
25
+ <a id="use-this-package"></a>
26
+ ## Use this package
27
+
28
+ You reach this package through a provider backend, not a composition: `dsh-subagent-spawn-in-process` and `dsh-subagent-fork-in-process` each call `startInProcessRun(request, options)` and own everything around it. This page documents the lifecycle both share so you can read one backend's behavior and reason about the other.
29
+
30
+ ### What one run provides
31
+
32
+ One call starts and drives one one-shot child. Fulfillment means the child is already published in `ctx.agents` and the caller owns the returned run; a rejected start has already quiesced the unpublished creation, so no half-created child survives. The run exposes the child's id and live agent, a `result` promise, and a `dispose()` that stops the loop, removes the agent and session, and unwinds scoped registrations.
33
+
34
+ ### The one input
35
+
36
+ `InProcessRunOptions` is `{ seed?: SessionEvent[] }` — a fork seed of balanced parent events. Spawn omits it; fork supplies the completed-turn prefix and records its length so the result reader never mistakes seeded parent messages for child output.
37
+
38
+ ### What the child gets
39
+
40
+ The child receives the parent's working-directory/session lineage and inherits the parent provider, model, reasoning effort, and output-token cap unless `request.agentOptions` overrides them. It gets a fresh flat registration scope: parent tool restrictions and authority are not imported. A run carries the parent's explicit sandbox override and `'never'` approval pin into the child and appends a per-run descriptor inside the child's initial turn.
41
+
42
+ -----
43
+
44
+ <a id="understand-the-implementation"></a>
45
+ ## Understand the implementation
46
+
47
+ <details>
48
+ <summary>Implementation internals — click to expand</summary>
49
+
50
+ This section explains the driver's lifecycle contract and the structured-output runtime; the observable behavior is covered in [Use this package](#use-this-package).
51
+
52
+ ### Start contract
53
+
54
+ The driver follows this sequence:
55
+
56
+ 1. Validate the parent depth and optional absolute `maxDepth`, then derive child depth as parent depth plus one and persist it in the child session header.
57
+ 2. Create the child through the host agent factory with the caller's required signal threaded into the creation transaction.
58
+ 3. During that transaction's unpublished setup window, install the requested persona, tool restriction, and structured-output runtime.
59
+ 4. Publish the child, retain the returned handle, and drive one task.
60
+ 5. Read the child's own output — its last non-empty assistant message, or its accumulated assistant text when none exists — and the final durable turn reason from the complete owned run, excluding any fork seed.
61
+
62
+ ### Cancellation and ownership
63
+
64
+ The required request signal covers both startup and the live run. Before publication, the creation transaction observes it, rolls back, and rejects; the driver re-checks once after publication to close the handoff race, then installs a minimal live-run listener. After fulfillment the caller owns the run: provider unload does not revoke it, and `dispose()` removes the abort listener, records cancellation, and delegates to the handle's memoized quiescence transaction, which stops the loop, removes the agent and session, and unwinds scoped registrations. Cancellation owns every non-completed in-flight outcome and reports `aborted`; an already-completed turn remains completed.
65
+
66
+ ### Structured output
67
+
68
+ `attachStructuredRuntime(childCtx, schema)` installs the whole contract in the child's scope: a `structured_output` tool validates and stages the model's value against the requested schema; a trailing first-party order-9900 system-prompt section tells the child the tool call is the terminal answer; a `tools/result` observer commits a staged value only after the authoritative final tool result succeeds, including the enclosing `run_code` result for PTC mode sub-dispatch; and a monotonic tool guard blocks later calls after capture. A clean turn that never commits the required value reports `error`; the driver does not re-prompt. All registrations ride the child fiber and disappear with it.
69
+
70
+ ### Source map
71
+
72
+ | File | Role |
73
+ |---|---|
74
+ | [`src/index.ts`](src/index.ts) | Run driver: creation, one-turn drive, result reading, disposal |
75
+ | [`src/structured.ts`](src/structured.ts) | Structured-output runtime: capture tool, prompt section, guard, commit |
76
+ | — | No runtime invariant companion is published; this package exposes no independent event sequence or mutable data relation beyond contracts enforced at its owning seam. |
77
+
78
+ </details>
79
+
80
+ -----
81
+
82
+ <a id="further-exploration"></a>
83
+ ## Further Exploration
84
+
85
+ Read these pages when the package-level contract is not enough; they move from the shared subagent model to the backends built on this driver and the delegation-policy decision.
86
+
87
+ - [Subagent subsystem](../../../docs/subsystems/subagent.md) — start requests, results, provider contract, and in-process depth and seed.
88
+ - [dsh-subagent-spawn-in-process](../subagent-spawn-in-process/README.md) — the fresh-child backend built on this driver.
89
+ - [dsh-subagent-fork-in-process](../subagent-fork-in-process/README.md) — the seeded-child backend built on this driver.
90
+ - [Delegation-policy decision](../../../.agents/notes/implemented/feature/2026-07-25-subagent-policy-inheritance.md) — how parent sandbox and approval policy reach the child.
91
+
92
+ -----
93
+
94
+ <a id="model-experience"></a>
95
+ ## Model Experience
96
+
97
+ ### Child-agent request
98
+
99
+ #### What the model sees
100
+
101
+ The shared driver sends the task verbatim as the child's user message and, when requested, shadows the persona and restricts global tool schemas, lookup, execution, and PTC mode SDK bindings in the unpublished child's fresh scope; parent restrictions are not inherited. Tool-guidance plugins can use the assembly scope to omit unavailable guidance; arbitrary static sections are not rewritten by the driver. Spawn supplies no history; fork supplies its balanced seed.
102
+
103
+ #### Token effect
104
+
105
+ Child input is isolated from the parent and grows through the child's own steps. A persona changes repeated prompt text; filtering changes schema or generated SDK cost, and scope-aware guidance changes with the visible capabilities.
106
+
107
+ #### KV Cache effect
108
+
109
+ Independent of the parent request cache. The child's later history is append-only, while persona, tool-filter, generated-SDK, provider, or model changes establish a different child prefix.
110
+
111
+ ### Structured-output system prompt, schema, and results
112
+
113
+ #### What the model sees
114
+
115
+ A structured run adds the structured-output instruction below. It also adds a child-scoped `structured_output` definition with the requested schema and the exact description `Report your final structured result. Call this exactly once, when your answer is complete; the arguments must match this tool's parameter schema exactly.` This runtime-only definition is outside the generated shipped [tool package map](../../../docs/tool-catalog.md#tool-package-map). Its canonical acknowledgement is `{ recorded: true }`, rendered as `Structured output recorded.`; a later call becomes ``Error: structured output already recorded: the run is complete, so `<tool>` is not executed``.
116
+
117
+ ##### Structured-output instruction
118
+
119
+ ```markdown
120
+ When you have your final answer, you MUST report it by calling the `structured_output` tool with arguments matching its parameter schema exactly. Do not finish with a plain text answer: only the tool call counts as your result.
121
+ ```
122
+
123
+ #### Token effect
124
+
125
+ Fixed instruction and capability tokens are paid only by that child. Result text enters the child history, while the captured value alone becomes the parent result.
126
+
127
+ #### KV Cache effect
128
+
129
+ Prefix-stable inside the child while the structured-output instruction and schema are unchanged. Changing the schema or capability may invalidate the child's cache from that early segment; results append in child and parent histories.
130
+
131
+ ### Parent start error, indirectly
132
+
133
+ #### What the model sees
134
+
135
+ Through `dsh-tool-subagent`, invalid depth state becomes exactly `Error: agent subagentDepth must be a non-negative safe integer`, `Error: subagent child depth exceeds the safe-integer range`, or `Error: subagent depth <attempted> exceeds maxDepth <max>`. A pre-publication cancellation passes its abort reason through the registry's `Error: <message>` wrapper.
136
+
137
+ #### Token effect
138
+
139
+ Zero tokens on a successful start; only the failed parent tool call retains this text.
140
+
141
+ #### KV Cache effect
142
+
143
+ Append-only; newly visible content follows the reusable request prefix and does not invalidate existing KV-cache entries.
144
+
145
+ ### Parent result, indirectly
146
+
147
+ #### What the model sees
148
+
149
+ The driver extracts only the child's own last assistant output or captured structured value; seeded parent messages and intermediate child work do not become the result.
150
+
151
+ #### Token effect
152
+
153
+ The parent receives one data-dependent result through the consumer; all other child tokens stay in the child session.
154
+
155
+ #### KV Cache effect
156
+
157
+ Append-only; newly visible content follows the reusable request prefix and does not invalidate existing KV-cache entries.
158
+
159
+ ## Known Limitations and Deferred Work
160
+
161
+ <a id="known-limitations-and-deferred-work"></a>
162
+
163
+
164
+ These limits define what an in-process one-shot run cannot do; they are current package constraints.
165
+
166
+ - **Runs expose no `sendMessage`/`resume`** — the optional runtime capabilities are absent on in-process one-shot runs.
167
+ - **Structured capture accepts the `defineTool` schema subset only** — unsupported JSON Schema constructs fail before the child is created; a provider needing a broader schema vocabulary requires a different runtime.
168
+
169
+ <a id="dev-note"></a>
170
+ ### Dev Note
171
+
172
+ <details>
173
+ <summary>Working context for maintainers — click to expand</summary>
174
+
175
+ None.
176
+
177
+ </details>
package/README.zh.md ADDED
@@ -0,0 +1,177 @@
1
+ ---
2
+ description: "共享进程内 subagent 运行驱动器,供维护者与后端作者理解或扩展 spawn 与 fork 的运行生命周期。"
3
+ kind: "package-library"
4
+ ---
5
+
6
+ # @x1a0f3n9/dsh-subagent-in-process-driver
7
+
8
+ [English](README.md) | 中文
9
+
10
+ ## 概述
11
+
12
+ `dsh-subagent-in-process-driver` 是两个进程内 subagent 后端共用的运行驱动器:它通过宿主的 agent(智能体)工厂创建一个子 agent,应用按子 agent 的定制,把一项任务驱动到完成,并以单一完全停稳的 dispose(资源释放)路径返回子 agent 自身的最终输出。spawn 调用它时不传入会话初始内容;fork 调用它时传入父级已完成轮次的前缀。它是库而非独立功能:提供方后端调用 `startInProcessRun`,组合中没有任何东西配置它。阅读本页可理解两个进程内后端共享的运行生命周期。
13
+
14
+ ## 目录
15
+
16
+ - [使用本包](#use-this-package)
17
+ - [理解实现](#understand-the-implementation)
18
+ - [进一步探索](#further-exploration)
19
+ - [模型体验](#model-experience)
20
+ - [已知限制与延期工作](#known-limitations-and-deferred-work)
21
+ - [开发备注](#dev-note)
22
+
23
+ -----
24
+
25
+ <a id="use-this-package"></a>
26
+ ## 使用本包
27
+
28
+ 你通过提供方后端而非组合到达本包:`dsh-subagent-spawn-in-process` 与 `dsh-subagent-fork-in-process` 各自调用 `startInProcessRun(request, options)` 并拥有其外围的一切。本页记录两者共享的生命周期,使你读懂一个后端的行为后即可推断另一个。
29
+
30
+ ### 一次运行提供什么
31
+
32
+ 一次调用启动并驱动一个一次性子 agent。调用兑现意味着子 agent 已发布到 `ctx.agents`,调用方拥有返回的运行;启动被拒绝时,未发布的创建已经完全停稳,因此不会有创建到一半的子 agent 存活。运行暴露子 agent 的 id 与在线 agent、一个 `result` promise,以及一个 `dispose()`——它会停止循环、移除 agent 与会话,并撤销作用域内的注册。
33
+
34
+ ### 唯一输入
35
+
36
+ `InProcessRunOptions` 的形态为 `{ seed?: SessionEvent[] }`——fork 的已配平父级事件初始内容。spawn 省略该值;fork 提供已完成轮次前缀并记录其长度,使结果读取器不会把作为初始内容的父级消息误认为子 agent 输出。
37
+
38
+ ### 子 agent 获得什么
39
+
40
+ 子 agent 获得父级的工作目录/会话谱系,除非 `request.agentOptions` 覆盖,否则继承父级的提供方、模型、推理强度与输出 token 上限。它获得全新的扁平注册作用域:父级工具限制与权限不会被导入。一次运行会把父级显式的沙箱覆盖项与 `'never'` 审批钉定带入子 agent,并在子 agent 的初始轮次内追加一份每次运行的描述符。
41
+
42
+ -----
43
+
44
+ <a id="understand-the-implementation"></a>
45
+ ## 理解实现
46
+
47
+ <details>
48
+ <summary>实现细节——点击展开</summary>
49
+
50
+ 本节解释驱动器的生命周期约定与结构化输出运行时;可观察行为已在[使用本包](#use-this-package)中说明。
51
+
52
+ ### 启动约定
53
+
54
+ 驱动器按以下顺序运行:
55
+
56
+ 1. 校验父级深度与可选的绝对 `maxDepth`,然后把子级深度推导为父级深度加一,并持久化到子级会话 header。
57
+ 2. 通过宿主 agent 工厂创建子 agent,并把调用方必需的信号传入创建事务。
58
+ 3. 在该事务未发布的设置窗口内,安装请求的 persona、工具限制与结构化输出运行时。
59
+ 4. 发布子 agent,保留返回的句柄,并驱动一项任务。
60
+ 5. 从完整的自有运行中读取子 agent 自身的输出——最后一条非空 assistant 消息,若无则取其累积的 assistant 文本——以及最终持久化的轮次原因,并排除任何 fork 初始内容。
61
+
62
+ ### 取消与所有权
63
+
64
+ 必需的请求信号同时覆盖启动阶段与实时运行。发布前,创建事务会观察它、回滚并拒绝;驱动器在发布后再检查一次以消除交接竞态,然后安装最小化的实时运行监听器。兑现后,调用方拥有该运行:提供方插件卸载不会撤销它;`dispose()` 会移除中止监听器、记录取消,并委托给句柄经记忆化的完全停稳事务——后者停止循环、移除 agent 与会话,并撤销作用域内的注册。取消流程会接管所有尚未完成的进行中结果,并将其报告为 `aborted`;已经完成的轮次仍保持完成状态。
65
+
66
+ ### 结构化输出
67
+
68
+ `attachStructuredRuntime(childCtx, schema)` 会在子 agent 作用域中安装完整约定:`structured_output` 工具按请求的 schema 校验并暂存模型值;位于末尾、顺序为 9900 的 first-party 系统提示词段告诉子 agent 该工具调用就是终态答案;`tools/result` 观察器只在该次执行的权威最终工具结果成功后提交暂存值,包括 PTC mode 子分派外层的 `run_code` 结果;单调工具防护会在捕获后阻止后续调用。正常结束却始终未提交必需值的轮次会报告 `error`;驱动器不会重新提示。所有注册都附着于子 agent fiber,并随其一同消失。
69
+
70
+ ### 源码地图
71
+
72
+ | 文件 | 职责 |
73
+ |---|---|
74
+ | [`src/index.ts`](src/index.ts) | 运行驱动器:创建、单轮驱动、结果读取、dispose |
75
+ | [`src/structured.ts`](src/structured.ts) | 结构化输出运行时:捕获工具、提示词段、防护、提交 |
76
+ | — | 不发布运行时不变式伴生入口;本包没有独立事件序列或可变数据关系,相关约定在所属 seam 强制执行。 |
77
+
78
+ </details>
79
+
80
+ -----
81
+
82
+ <a id="further-exploration"></a>
83
+ ## 进一步探索
84
+
85
+ 当包级约定不够用时阅读以下页面;它们从共享 subagent 模型进入构建于本驱动器之上的后端,以及委派策略决策。
86
+
87
+ - [Subagent 子系统](../../../docs/subsystems/subagent.zh.md)——启动请求、结果、提供方约定与进程内深度和初始内容。
88
+ - [dsh-subagent-spawn-in-process](../subagent-spawn-in-process/README.zh.md)——构建于本驱动器之上的全新子 agent 后端。
89
+ - [dsh-subagent-fork-in-process](../subagent-fork-in-process/README.zh.md)——构建于本驱动器之上的带初始内容的子 agent 后端。
90
+ - [委派策略决策](../../../.agents/notes/implemented/feature/2026-07-25-subagent-policy-inheritance.zh.md)——父级沙箱与审批策略如何到达子 agent。
91
+
92
+ -----
93
+
94
+ <a id="model-experience"></a>
95
+ ## 模型体验
96
+
97
+ ### 子 agent 请求
98
+
99
+ #### 模型看到什么
100
+
101
+ 共享驱动器把任务逐字作为子 agent 的用户消息发送;若有请求,还会在未发布子 agent 的全新作用域中遮蔽 persona,并限制全局工具 schema、查找、执行与 PTC mode SDK 绑定。父级限制不会被继承。工具指导插件可以使用组装 scope 省略不可用工具的指导;驱动器不会改写任意静态段落。spawn 不提供历史;fork 提供其已配平的初始内容。
102
+
103
+ #### Token 影响
104
+
105
+ 子 agent 输入与父级隔离,并随子 agent 自身的步骤增长。persona 会改变重复提示词文本;过滤会改变 schema 或生成 SDK 的成本,使用 scope 的指导内容也会随可见能力变化。
106
+
107
+ #### KV Cache 影响
108
+
109
+ 与父级请求缓存相互独立。子 agent 后续历史仅追加,而 persona、工具过滤、生成 SDK、提供方或模型变化会建立不同的子 agent 前缀。
110
+
111
+ ### 结构化输出系统提示词、schema 与结果
112
+
113
+ #### 模型看到什么
114
+
115
+ 结构化运行会添加下方的结构化输出指令,并添加子 agent 作用域的 `structured_output` 定义,其参数使用请求的 schema,精确描述为 `Report your final structured result. Call this exactly once, when your answer is complete; the arguments must match this tool's parameter schema exactly.` 该仅运行时存在的定义不在已生成并随产品发布的[工具包索引](../../../docs/tool-catalog.zh.md#tool-package-map)中。其规范确认值是 `{ recorded: true }`,渲染为 `Structured output recorded.`;后续调用会变为 ``Error: structured output already recorded: the run is complete, so `<tool>` is not executed``。
116
+
117
+ ##### 结构化输出指令
118
+
119
+ ```markdown
120
+ When you have your final answer, you MUST report it by calling the `structured_output` tool with arguments matching its parameter schema exactly. Do not finish with a plain text answer: only the tool call counts as your result.
121
+ ```
122
+
123
+ #### Token 影响
124
+
125
+ 固定指令与能力产生的 token 仅由该子 agent 承担。结果文本进入子 agent 历史,而只有捕获的值会成为父级结果。
126
+
127
+ #### KV Cache 影响
128
+
129
+ 只要结构化输出指令与 schema 不变,子 agent 内部的前缀就保持稳定。更改 schema 或能力可能从该早期片段开始使子 agent 缓存失效;结果会分别追加到子 agent 与父级历史中。
130
+
131
+ ### 父级启动错误(间接)
132
+
133
+ #### 模型看到什么
134
+
135
+ 通过 `dsh-tool-subagent`,无效深度状态会精确变为 `Error: agent subagentDepth must be a non-negative safe integer`、`Error: subagent child depth exceeds the safe-integer range` 或 `Error: subagent depth <attempted> exceeds maxDepth <max>`。发布前取消的中止原因会通过注册表的 `Error: <message>` 包装传递。
136
+
137
+ #### Token 影响
138
+
139
+ 启动成功时为零 token;只有失败的父级工具调用会保留这段文本。
140
+
141
+ #### KV Cache 影响
142
+
143
+ 仅追加;新增可见内容位于可复用请求前缀之后,不会使现有 KV Cache 条目失效。
144
+
145
+ ### 父级结果(间接)
146
+
147
+ #### 模型看到什么
148
+
149
+ 驱动器只提取子 agent 自身最后的 assistant 输出或捕获的结构化值;作为初始内容的父级消息与子 agent 中间工作不会成为结果。
150
+
151
+ #### Token 影响
152
+
153
+ 父级通过消费方接收一个依赖数据的结果;其他所有子 agent token 都留在子 agent 会话中。
154
+
155
+ #### KV Cache 影响
156
+
157
+ 仅追加;新增可见内容位于可复用请求前缀之后,不会使现有 KV Cache 条目失效。
158
+
159
+ ## 已知限制与延期工作
160
+
161
+ <a id="known-limitations-and-deferred-work"></a>
162
+
163
+
164
+ 这些限制说明进程内一次性运行不能做什么;它们是当前包约束。
165
+
166
+ - **运行不公开 `sendMessage`/`resume`**——进程内一次性运行不具备这些可选运行时能力。
167
+ - **结构化捕获只接受 `defineTool` schema 子集**——不支持的 JSON Schema 构造会在子 agent 创建前失败;需要更广 schema 词汇的提供方必须采用不同的运行时。
168
+
169
+ <a id="dev-note"></a>
170
+ ### 开发备注
171
+
172
+ <details>
173
+ <summary>维护者的工作上下文——点击展开</summary>
174
+
175
+ 无。
176
+
177
+ </details>
package/lib/index.js ADDED
@@ -0,0 +1,254 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { brandString } from "@x1a0f3n9/dsh-brand";
3
+ import { foldConsumedWork } from "@x1a0f3n9/dsh-agent";
4
+ import { SessionLogOffset } from "@x1a0f3n9/dsh-session";
5
+ import { createUserMessage } from "@x1a0f3n9/dsh-llm";
6
+ import { appendDelegatedPolicyOverrides, applyChildComposition, assertSubagentMaxDepth, captureDelegatedPolicyOverrides, childSessionMeta, finalAssistantOutput, resolveChildAgentOptions, resolveChildDepth } from "@x1a0f3n9/dsh-subagent";
7
+ import { ToolArgsError, validateJsonSchemaValue } from "@x1a0f3n9/dsh-tools";
8
+ //#region lib/types/structured.js
9
+ /**
10
+ * Child-scoped structured-output tool, prompt instruction, terminal guard, and authoritative
11
+ * result capture for in-process subagents. Each child registers its real schema on its own
12
+ * scope, so concurrent runs do not interact and disposal leaves no global residue. The prompt
13
+ * contribution is ordinary reconstructed request state.
14
+ *
15
+ * Capture commits only after the authoritative `tools/result` succeeds; PTC mode capture also
16
+ * waits for the enclosing `run_code` result. The terminal result marker and monotonic tool
17
+ * guard prevent later calls from reopening a completed structured run.
18
+ * @module @x1a0f3n9/dsh-subagent-in-process-driver/structured
19
+ */
20
+ /** The model-facing tool name a structured child must call to finish. */
21
+ const STRUCTURED_OUTPUT_TOOL = "structured_output";
22
+ /**
23
+ * The instruction registered as the child's trailing scoped prompt section:
24
+ * the demand travels with the
25
+ * tool, as ordinary prompt state of exactly one agent.
26
+ */
27
+ const STRUCTURED_OUTPUT_INSTRUCTION = `When you have your final answer, you MUST report it by calling the \`${STRUCTURED_OUTPUT_TOOL}\` tool with arguments matching its parameter schema exactly. Do not finish with a plain text answer: only the tool call counts as your result.`;
28
+ /**
29
+ * Attach the scoped capture tool, instruction, and enforcement to a child during
30
+ * its creation window. Child disposal removes every registration.
31
+ * @param childCtx - the child agent's scope context (`setup`'s argument).
32
+ * @param schema - the trusted, already-asserted schema subset to enforce (see
33
+ * `assertObjectJsonSchema` in dsh-tools).
34
+ * @returns the attachment handle (read `captured()` after the child settles).
35
+ */
36
+ function attachStructuredRuntime(childCtx, schema) {
37
+ /**
38
+ * Validated values staged by the capture tool body, awaiting THEIR OWN
39
+ * authoritative `tools/result` notification. The execution object's identity
40
+ * uniquely identifies a trip through the pipeline: adapter call ids may
41
+ * repeat across steps, but another execution can never reach this WeakMap
42
+ * entry. This is distinct from the opaque `ToolExecutionToken` used to
43
+ * correlate nested transports. The final notification always deletes its own
44
+ * stage, whether the result succeeded or failed.
45
+ */
46
+ const staged = /* @__PURE__ */ new WeakMap();
47
+ /** Successful nested capture waiting for its enclosing transport to commit. */
48
+ let pending;
49
+ let captured;
50
+ const schemaEntry = {
51
+ name: STRUCTURED_OUTPUT_TOOL,
52
+ description: "Report your final structured result. Call this exactly once, when your answer is complete; the arguments must match this tool's parameter schema exactly.",
53
+ parameters: schema
54
+ };
55
+ childCtx.tools.register({
56
+ ...schemaEntry,
57
+ output: {
58
+ schema: {
59
+ type: "object",
60
+ properties: { recorded: {
61
+ type: "boolean",
62
+ const: true
63
+ } },
64
+ required: ["recorded"],
65
+ additionalProperties: false
66
+ },
67
+ render: () => [{
68
+ type: "text",
69
+ text: "Structured output recorded."
70
+ }]
71
+ },
72
+ execute(args, exec) {
73
+ const violations = validateJsonSchemaValue(schema, args);
74
+ if (violations.length > 0) throw new ToolArgsError(violations);
75
+ staged.set(exec, { value: args });
76
+ exec.concludeTurn();
77
+ return Promise.resolve({ recorded: true });
78
+ }
79
+ });
80
+ childCtx.systemPrompt.section({
81
+ name: `tool:${STRUCTURED_OUTPUT_TOOL}`,
82
+ order: childCtx.systemPrompt.getSectionOrder("STRUCTURED_OUTPUT"),
83
+ text: STRUCTURED_OUTPUT_INSTRUCTION
84
+ });
85
+ childCtx.tools.guard((exec) => captured === void 0 && pending === void 0 ? void 0 : `structured output already recorded: the run is complete, so \`${exec.name}\` is not executed`);
86
+ childCtx.on("tools/result", function(exec, result) {
87
+ if (exec.name === "structured_output") {
88
+ const entry = staged.get(exec);
89
+ if (entry === void 0) return;
90
+ staged.delete(exec);
91
+ if (result.isError) return;
92
+ if (exec.parent === void 0) {
93
+ /* v8 ignore else -- sequential agent-loop dispatch lets the guard block every later supported call */
94
+ if (captured === void 0) captured = { value: entry.value };
95
+ } else if (captured === void 0 && pending === void 0) pending = {
96
+ parent: exec.parent,
97
+ value: entry.value
98
+ };
99
+ return;
100
+ }
101
+ if (pending?.parent !== exec.token) return;
102
+ const entry = pending;
103
+ pending = void 0;
104
+ if (result.isError) return;
105
+ /* v8 ignore else -- PTC mode serializes outer executions, so the guard blocks every later supported call */
106
+ if (captured === void 0) captured = { value: entry.value };
107
+ });
108
+ return { captured: () => captured };
109
+ }
110
+ //#endregion
111
+ //#region lib/types/index.js
112
+ /**
113
+ * Shared driver for in-process ONE-SHOT subagent providers. The agent factory's
114
+ * creation transaction owns unpublished setup and rollback; after publication
115
+ * the returned AgentHandle is the one quiescent lifecycle owner held by the
116
+ * provider's caller.
117
+ *
118
+ * Continuable children never come through here: the continuation manager
119
+ * composes and drives them directly, so this driver owns exactly one turn with
120
+ * one result.
121
+ *
122
+ * @module @x1a0f3n9/dsh-subagent-in-process-driver
123
+ */
124
+ /** Map a session turn outcome to the subagent seam's terminal vocabulary. */
125
+ function toStopReason(reason) {
126
+ switch (reason?.kind) {
127
+ case "completed": return "completed";
128
+ case "max-tokens": return "max-tokens";
129
+ case "aborted": return "aborted";
130
+ case "blocked": return "refusal";
131
+ default: return "error";
132
+ }
133
+ }
134
+ /** Error used when cancellation wins before the child publication boundary. */
135
+ function prePublicationAbort() {
136
+ return /* @__PURE__ */ new Error("subagent request was aborted before child publication");
137
+ }
138
+ /** Append one one-shot descriptor inside the child's initial turn before its first request. */
139
+ function attachDescriptorAppend(childCtx, descriptor) {
140
+ let appended = false;
141
+ childCtx.on("agent/pre-step", async ({ agent }, next) => {
142
+ const decision = await next();
143
+ if (!appended && decision.kind === "enter") {
144
+ appended = true;
145
+ agent.session.append("subagent/descriptor", descriptor);
146
+ }
147
+ return decision;
148
+ });
149
+ }
150
+ /**
151
+ * Establish and drive one in-process one-shot child. Fulfillment means the agent
152
+ * is already published in the registry and transfers its turn, cancellation,
153
+ * and disposal work through the returned run. Rejection means the agent
154
+ * factory's unpublished creation transaction reached quiescence without
155
+ * publishing a child. Every start appends its resolved descriptor inside the
156
+ * child's initial turn.
157
+ * @param request - the trusted typed start request, including its required signal.
158
+ * @param options - the optional fork seed.
159
+ * @returns a published holder-owned run.
160
+ */
161
+ async function startInProcessRun(request, options) {
162
+ assertSubagentMaxDepth(request.maxDepth);
163
+ if (request.signal.aborted) throw prePublicationAbort();
164
+ const parent = request.parent;
165
+ const childDepth = resolveChildDepth(parent, request.maxDepth);
166
+ const childId = brandString(randomUUID());
167
+ const seed = options.seed;
168
+ const activationBoundary = SessionLogOffset(seed?.length ?? 0);
169
+ const inherited = captureDelegatedPolicyOverrides(parent);
170
+ let structured;
171
+ const setup = (childCtx, child) => {
172
+ appendDelegatedPolicyOverrides(child.session, inherited);
173
+ applyChildComposition(childCtx, parent, {
174
+ persona: request.persona,
175
+ toolFilter: request.toolFilter
176
+ });
177
+ if (request.outputSchema !== void 0) structured = attachStructuredRuntime(childCtx, request.outputSchema);
178
+ attachDescriptorAppend(childCtx, request.descriptor);
179
+ };
180
+ return drivePublishedRun(await parent.ctx.agents.create({
181
+ sessionId: childId,
182
+ parentAgent: parent,
183
+ meta: childSessionMeta(parent, childDepth, seed !== void 0),
184
+ ...seed !== void 0 ? { seed } : {},
185
+ ...seed === void 0 ? {} : { inheritedEventCount: activationBoundary },
186
+ agentOptions: resolveChildAgentOptions(parent, request.agentOptions, childDepth),
187
+ signal: request.signal,
188
+ setup
189
+ }), request.signal, request.prompt, childId, activationBoundary, structured);
190
+ }
191
+ /**
192
+ * Wrap a published child in the single run lifecycle that owns signal handoff,
193
+ * one turn, result settlement, and quiescent disposal.
194
+ */
195
+ function drivePublishedRun(handle, signal, prompt, childId, boundary, structured) {
196
+ const child = handle.agent;
197
+ const flags = { cancelled: false };
198
+ const onAbort = () => {
199
+ flags.cancelled = true;
200
+ child.cancel({ kind: "parent" });
201
+ };
202
+ signal.addEventListener("abort", onAbort, { once: true });
203
+ if (signal.aborted) onAbort();
204
+ const result = (async () => {
205
+ try {
206
+ if (!flags.cancelled) {
207
+ child.followup(createUserMessage({
208
+ content: prompt,
209
+ source: { kind: "user" }
210
+ }));
211
+ await child.whenIdle();
212
+ }
213
+ return readResult(child, boundary, flags.cancelled, structured ? { captured: structured.captured() } : void 0);
214
+ } finally {
215
+ signal.removeEventListener("abort", onAbort);
216
+ }
217
+ })();
218
+ return {
219
+ id: childId,
220
+ localAgent: child,
221
+ result,
222
+ async dispose() {
223
+ signal.removeEventListener("abort", onAbort);
224
+ flags.cancelled = true;
225
+ const disposal = (await Promise.allSettled([handle.dispose(), result]))[0];
226
+ if (disposal.status === "rejected") throw disposal.reason;
227
+ }
228
+ };
229
+ }
230
+ /** Read one settled child's result from events after its activation boundary. */
231
+ function readResult(child, boundary, cancelled, structured) {
232
+ const own = child.session.snapshotEvents(boundary);
233
+ const lastEnd = foldConsumedWork(own).end;
234
+ const output = finalAssistantOutput(own) ?? [];
235
+ const recorded = toStopReason(lastEnd?.data.reason);
236
+ const stopReason = cancelled && recorded !== "completed" ? "aborted" : recorded;
237
+ if (structured !== void 0) {
238
+ if (structured.captured !== void 0) return {
239
+ output,
240
+ structured: structured.captured.value,
241
+ stopReason
242
+ };
243
+ if (stopReason === "completed") return {
244
+ output,
245
+ stopReason: cancelled ? "aborted" : "error"
246
+ };
247
+ }
248
+ return {
249
+ output,
250
+ stopReason
251
+ };
252
+ }
253
+ //#endregion
254
+ export { STRUCTURED_OUTPUT_INSTRUCTION, STRUCTURED_OUTPUT_TOOL, startInProcessRun };
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Shared driver for in-process ONE-SHOT subagent providers. The agent factory's
3
+ * creation transaction owns unpublished setup and rollback; after publication
4
+ * the returned AgentHandle is the one quiescent lifecycle owner held by the
5
+ * provider's caller.
6
+ *
7
+ * Continuable children never come through here: the continuation manager
8
+ * composes and drives them directly, so this driver owns exactly one turn with
9
+ * one result.
10
+ *
11
+ * @module @x1a0f3n9/dsh-subagent-in-process-driver
12
+ */
13
+ import type { SessionEvent } from '@x1a0f3n9/dsh-session';
14
+ import type { ResolvedSubagentStartRequest, SubagentRun } from '@x1a0f3n9/dsh-subagent';
15
+ export { STRUCTURED_OUTPUT_TOOL, STRUCTURED_OUTPUT_INSTRUCTION, } from './structured.ts';
16
+ /** Extra inputs the spawn and fork providers supply to the shared driver. */
17
+ export interface InProcessRunOptions {
18
+ /** Completed-turn seed for fork, or undefined for a fresh spawn. */
19
+ readonly seed?: readonly SessionEvent[];
20
+ }
21
+ /**
22
+ * Establish and drive one in-process one-shot child. Fulfillment means the agent
23
+ * is already published in the registry and transfers its turn, cancellation,
24
+ * and disposal work through the returned run. Rejection means the agent
25
+ * factory's unpublished creation transaction reached quiescence without
26
+ * publishing a child. Every start appends its resolved descriptor inside the
27
+ * child's initial turn.
28
+ * @param request - the trusted typed start request, including its required signal.
29
+ * @param options - the optional fork seed.
30
+ * @returns a published holder-owned run.
31
+ */
32
+ export declare function startInProcessRun(request: ResolvedSubagentStartRequest, options: InProcessRunOptions): Promise<SubagentRun>;
33
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Child-scoped structured-output tool, prompt instruction, terminal guard, and authoritative
3
+ * result capture for in-process subagents. Each child registers its real schema on its own
4
+ * scope, so concurrent runs do not interact and disposal leaves no global residue. The prompt
5
+ * contribution is ordinary reconstructed request state.
6
+ *
7
+ * Capture commits only after the authoritative `tools/result` succeeds; PTC mode capture also
8
+ * waits for the enclosing `run_code` result. The terminal result marker and monotonic tool
9
+ * guard prevent later calls from reopening a completed structured run.
10
+ * @module @x1a0f3n9/dsh-subagent-in-process-driver/structured
11
+ */
12
+ import type { Context } from '@deepseek-ai/cordis';
13
+ import { type ObjectJsonSchema } from '@x1a0f3n9/dsh-tools';
14
+ /** The model-facing tool name a structured child must call to finish. */
15
+ export declare const STRUCTURED_OUTPUT_TOOL = "structured_output";
16
+ /**
17
+ * The instruction registered as the child's trailing scoped prompt section:
18
+ * the demand travels with the
19
+ * tool, as ordinary prompt state of exactly one agent.
20
+ */
21
+ export declare const STRUCTURED_OUTPUT_INSTRUCTION: string;
22
+ /** One structured run's live handle: read the captured value once the child settles. */
23
+ export interface StructuredAttachment {
24
+ /**
25
+ * The captured value, once the child called the tool with valid arguments
26
+ * and the authoritative final tool result accepted that call.
27
+ * @returns the committed value, or undefined while none was accepted.
28
+ */
29
+ captured(): {
30
+ value: unknown;
31
+ } | undefined;
32
+ }
33
+ /**
34
+ * Attach the scoped capture tool, instruction, and enforcement to a child during
35
+ * its creation window. Child disposal removes every registration.
36
+ * @param childCtx - the child agent's scope context (`setup`'s argument).
37
+ * @param schema - the trusted, already-asserted schema subset to enforce (see
38
+ * `assertObjectJsonSchema` in dsh-tools).
39
+ * @returns the attachment handle (read `captured()` after the child settles).
40
+ */
41
+ export declare function attachStructuredRuntime(childCtx: Context, schema: ObjectJsonSchema): StructuredAttachment;
42
+ //# sourceMappingURL=structured.d.ts.map
package/package.json ADDED
@@ -0,0 +1,61 @@
1
+ {
2
+ "name": "@x1a0f3n9/dsh-subagent-in-process-driver",
3
+ "description": "Shared in-process subagent run driver: drives a child agent on ctx.agents (used by the spawn and fork backends)",
4
+ "version": "0.1.5-rc.2",
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/deepseek-ai/deepseek-harness.git",
11
+ "directory": "packages/subagent/subagent-in-process-driver"
12
+ },
13
+ "type": "module",
14
+ "main": "lib/index.js",
15
+ "types": "lib/types/index.d.ts",
16
+ "exports": {
17
+ ".": {
18
+ "types": "./lib/types/index.d.ts",
19
+ "default": "./lib/index.js"
20
+ },
21
+ "./src/*": "./src/*",
22
+ "./package.json": "./package.json"
23
+ },
24
+ "files": [
25
+ "lib/index.js",
26
+ "lib/types/**/*.d.ts"
27
+ ],
28
+ "license": "MIT",
29
+ "peerDependencies": {
30
+ "@deepseek-ai/cordis": "^4.0.2",
31
+ "@x1a0f3n9/dsh-agent": "^0.1.5-rc.2",
32
+ "@x1a0f3n9/dsh-session": "^0.1.5-rc.2",
33
+ "@x1a0f3n9/dsh-llm": "^0.1.5-rc.2",
34
+ "@x1a0f3n9/dsh-subagent": "^0.1.5-rc.2",
35
+ "@x1a0f3n9/dsh-system-prompt": "^0.1.5-rc.2",
36
+ "@x1a0f3n9/dsh-tools": "^0.1.5-rc.2"
37
+ },
38
+ "devDependencies": {
39
+ "@deepseek-ai/cordis": "^4.0.2",
40
+ "@deepseek-ai/cordis-plugin-include": "^1.0.7",
41
+ "@deepseek-ai/cordis-plugin-loader": "^1.0.3",
42
+ "@x1a0f3n9/dsh-agent": "^0.1.5-rc.2",
43
+ "@x1a0f3n9/dsh-agent-loop": "^0.1.5-rc.2",
44
+ "@x1a0f3n9/dsh-agent-presets": "^0.1.5-rc.2",
45
+ "@x1a0f3n9/dsh-agent-loop-testkit": "^0.1.5-rc.2",
46
+ "@x1a0f3n9/dsh-fs-sandbox": "^0.1.5-rc.2",
47
+ "@x1a0f3n9/dsh-invariants": "^0.1.5-rc.2",
48
+ "@x1a0f3n9/dsh-llm": "^0.1.5-rc.2",
49
+ "@x1a0f3n9/dsh-sandbox-policy": "^0.1.5-rc.2",
50
+ "@x1a0f3n9/dsh-session": "^0.1.5-rc.2",
51
+ "@x1a0f3n9/dsh-session-projection": "^0.1.5-rc.2",
52
+ "@x1a0f3n9/dsh-subagent": "^0.1.5-rc.2",
53
+ "@x1a0f3n9/dsh-system-prompt": "^0.1.5-rc.2",
54
+ "@x1a0f3n9/dsh-user-approval": "^0.1.5-rc.2",
55
+ "@x1a0f3n9/dsh-tool-fs": "^0.1.5-rc.2",
56
+ "@x1a0f3n9/dsh-tools": "^0.1.5-rc.2"
57
+ },
58
+ "dependencies": {
59
+ "@x1a0f3n9/dsh-brand": "^0.1.5-rc.2"
60
+ }
61
+ }