@qilin-agent/subagent-acp 0.0.0-stage → 3.1.3

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 kkutysllb
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,85 @@
1
+ # Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading
2
+ # section, a hash of its English and Chinese blocks outside code blocks and generated regions.
3
+ # After editing either side, bring the other along and re-record with:
4
+ # pnpm run verify-translation-pairing --write packages/subagent/subagent-acp/README.md
5
+ /:
6
+ en: 86941ae0e2ae97a3
7
+ zh: ca2acb7bff6d53ab
8
+ /qilin-subagent-acp:
9
+ en: 0e6df5b89556a857
10
+ zh: 8cc05e065cf5b743
11
+ /qilin-subagent-acp/summary:
12
+ en: 39559d1c5892fed9
13
+ zh: efd0fc17460a0b14
14
+ /qilin-subagent-acp/table-of-contents:
15
+ en: d152484eb41ac6b4
16
+ zh: 09388d293f9be9cb
17
+ /qilin-subagent-acp/use-this-package:
18
+ en: 78623be74507229d
19
+ zh: b0ed9c9d0c6eb040
20
+ /qilin-subagent-acp/use-this-package/when-to-choose-it:
21
+ en: 56946ab7637bb8f9
22
+ zh: c54c4da98092dd9c
23
+ /qilin-subagent-acp/use-this-package/configuration:
24
+ en: 59a13b84e3d719ec
25
+ zh: 5fe144d3fc1814f4
26
+ /qilin-subagent-acp/use-this-package/what-you-get:
27
+ en: 0a809bd7b8cebddc
28
+ zh: e2c1edf8f485e8f8
29
+ /qilin-subagent-acp/use-this-package/failure-and-recovery:
30
+ en: 312094fb2d293247
31
+ zh: c9b48a6127532308
32
+ /qilin-subagent-acp/use-this-package/safe-diagnostics:
33
+ en: 11a38ce5f9a97e1f
34
+ zh: 617ad40f3e37f742
35
+ /qilin-subagent-acp/understand-the-implementation:
36
+ en: 663322a5de5a2112
37
+ zh: 37d0602bb7e58c0e
38
+ /qilin-subagent-acp/understand-the-implementation/design-concept:
39
+ en: c98e6bcd784bbf8a
40
+ zh: b96218f6e639755c
41
+ /qilin-subagent-acp/understand-the-implementation/start-and-ownership-flow:
42
+ en: c0f7f78468f84c3b
43
+ zh: c9cb417d84d868ce
44
+ /qilin-subagent-acp/understand-the-implementation/stop-reason-mapping:
45
+ en: 88bb2b62c6e2f114
46
+ zh: f6b720ca8ce90343
47
+ /qilin-subagent-acp/understand-the-implementation/process-boundary:
48
+ en: 7217618a1d396333
49
+ zh: c8f47e31c815bec8
50
+ /qilin-subagent-acp/further-exploration:
51
+ en: 5f8bb88ba6e3dc1a
52
+ zh: 56bf6417caa81b1e
53
+ /qilin-subagent-acp/model-experience:
54
+ en: 215e7ba838619b7b
55
+ zh: a311da3843709f90
56
+ /qilin-subagent-acp/model-experience/child-agent-request:
57
+ en: 05e6180f1498fdf9
58
+ zh: 2b05d2b97bfa67da
59
+ /qilin-subagent-acp/model-experience/child-agent-request/what-the-model-sees:
60
+ en: f7f619ca78d74c6f
61
+ zh: f642dc7b4ff69a10
62
+ /qilin-subagent-acp/model-experience/child-agent-request/token-effect:
63
+ en: c0b78d334d5d0a9c
64
+ zh: d54bf504933e132d
65
+ /qilin-subagent-acp/model-experience/child-agent-request/kv-cache-effect:
66
+ en: e9423135f647a086
67
+ zh: 6b50cc215a8b4403
68
+ /qilin-subagent-acp/model-experience/parent-tool-result-indirectly:
69
+ en: 75d061c2151624a7
70
+ zh: 71e58e020b60ff90
71
+ /qilin-subagent-acp/model-experience/parent-tool-result-indirectly/what-the-model-sees:
72
+ en: e9288ecec3f2e2c7
73
+ zh: ab7e02a64421bb14
74
+ /qilin-subagent-acp/model-experience/parent-tool-result-indirectly/token-effect:
75
+ en: 600ac97cdd163650
76
+ zh: cd26bb541f56699b
77
+ /qilin-subagent-acp/model-experience/parent-tool-result-indirectly/kv-cache-effect:
78
+ en: f5d5f97a153f7c70
79
+ zh: 3d6bc05b9eadfbc2
80
+ /qilin-subagent-acp/known-limitations-and-deferred-work:
81
+ en: 53a0e7fb49fe6e23
82
+ zh: 51096d4eb51fb4ba
83
+ /qilin-subagent-acp/known-limitations-and-deferred-work/dev-note:
84
+ en: d8323b3200db6ac9
85
+ zh: f8a5273b887b9552
package/README.md CHANGED
@@ -1,3 +1,177 @@
1
- # Temporary Holding Version
1
+ ---
2
+ description: "The out-of-process ACP subagent backend for users and maintainers choosing a delegation provider, configuring a child ACP agent command, or debugging remote child runs."
3
+ kind: "package-reference"
4
+ ---
2
5
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
6
+ # @qilin-agent/subagent-acp
7
+
8
+ English | [中文](README.zh.md)
9
+
10
+ ## Summary
11
+
12
+ Use this package to delegate a task to an ACP-compatible agent running in a fresh subprocess with its own runtime, session, model, and tools. Each run shares only the selected working directory, sends the task over ACP, and returns the child's final answer or a safe error; intermediate messages and tool traffic stay outside the parent conversation. Permission prompts are answered by configured policy without human interaction. Choose it when delegation needs process isolation or a non-Harness ACP agent, and choose an in-process backend when the child must share parent capabilities.
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
+ Mount this provider when a composition needs a fully isolated, out-of-process child that speaks the Agent Client Protocol. The common path is explicit: mount the seam, mount this provider, and give it a command that starts an ACP agent.
29
+
30
+ ### When to choose it
31
+
32
+ Choose this backend when the child must run with its own runtime, model, and tools in a separate process — for example an ACP agent from another project — or when you want delegation that cannot touch the parent harness. Choose an in-process backend when the child must share the parent's composition or honor parent-enforced capabilities: this provider advertises no optional start-time capabilities, so the seam rejects requests for `agentOptions`, structured output, depth caps, tool filters, or personas rather than silently omitting them.
33
+
34
+ ### Configuration
35
+
36
+ | Field | Default | Meaning |
37
+ |---|---|---|
38
+ | `providerName` | `acp` | Registry name on `ctx.subagents` |
39
+ | `command` | required | Executable spawned for each run (the child ACP agent) |
40
+ | `args` | `[]` | Command arguments |
41
+ | `cwd` | parent session cwd | Working-directory override for the child process and its ACP session |
42
+ | `permission` | `reject` | Auto-answer permission requests by rejecting, or choosing the first `allow_once` or `allow_always` option (`allow`) |
43
+ | `env` | `{}` | Explicit child environment layered over the credential-scrubbed parent environment |
44
+ | `disposeEofGraceMs` | `6000` | Grace after stdin EOF before platform termination |
45
+ | `disposeGraceMs` | `3000` | Bound for observing structured process facts after failure and, on POSIX, the SIGTERM-to-SIGKILL grace |
46
+
47
+ The generated [configuration catalog](../../../docs/config-catalog.md#qilin-agentsubagent-acp) is the exhaustive source for every accepted field and its JSDoc.
48
+
49
+ A QiLin child uses the product launcher and an explicit absolute `QILIN_HOME`. The isolated home prevents a nested runtime from discovering the launching person's profiles or credentials; the generic ACP provider does not impose this requirement on non-QILIN agents.
50
+
51
+ ```yaml
52
+ - id: subagent-acp
53
+ name: '@qilin-agent/subagent-acp'
54
+ config:
55
+ providerName: acp
56
+ command: qilin
57
+ args: ['--profile', 'acp', '--patch', '/absolute/path/to/acp.patch.yml']
58
+ permission: reject
59
+ env:
60
+ QILIN_HOME: /absolute/path/to/isolated-child-home
61
+ DEEPSEEK_API_KEY: !!js process.env.DEEPSEEK_API_KEY
62
+ ```
63
+
64
+ ### What you get
65
+
66
+ A successful run returns the child's final streamed assistant text as the result output. The child's session, model, and tools come from the child process itself — the parent supplies only the task and the working directory. The stop reason maps `end_turn` to `completed`, `max_tokens` to `max-tokens`, `refusal` to `refusal`, `cancelled` to `aborted`, and every other value to `error`. A failed published run preserves partial assistant text in `output` and returns safe structured detail separately in `diagnostic`.
67
+
68
+ ### Failure and recovery
69
+
70
+ A spawn, initialization, or new-session failure rejects before publication, ordinarily after the managed range is proven quiescent. If cleanup also fails, the rejection preserves ordered safe startup and teardown facts without claiming whole-range quiescence. Non-cancellation errors expose only fixed provider, stage, and category facts; the original failure stays on the internal cause chain and in Host diagnostics. After publication, a prompt, transport, or early-process failure resolves as `error` with a safe diagnostic, while local cancellation resolves as `aborted` without failure detail.
71
+
72
+ ### Safe diagnostics
73
+
74
+ A generic diagnostic uses one fixed line: `Subagent failure (provider: ACP; stage: <stage>; category: <category>; ...)`. Optional stop reason, exit code, and signal come only from closed protocol or managed-process facts. Stderr, exception text, task content, tool input, paths, environment values, credentials, and protocol payloads never enter the diagnostic; the shared result boundary limits it to 4096 UTF-8 bytes. A non-completed run that requested permission can add one fixed policy, tool-kind, and decision line. Successful runs and local cancellation omit it.
75
+
76
+ -----
77
+
78
+ <a id="understand-the-implementation"></a>
79
+ ## Understand the implementation
80
+
81
+ <details>
82
+ <summary>Implementation internals — click to expand</summary>
83
+
84
+ This section explains how the backend drives a child over ACP and where the observable behavior comes from; the full contract lives in [Use this package](#use-this-package).
85
+
86
+ ### Design concept
87
+
88
+ - **Full process isolation.** Each child runs in a fresh subprocess with its own session, model, and tools; only the resolved working directory crosses from the parent.
89
+ - **One process per run.** Every run spawns a new process; there is no process pooling.
90
+ - **The ACP wire is the serialization boundary.** Same-process subagent values are not defensively cloned; the protocol is where hostile input is validated.
91
+
92
+ ### Start and ownership flow
93
+
94
+ A start resolves the child's working directory (the configured `cwd` override, else the parent session's cwd), spawns the command through the subprocess seam, performs the ACP `initialize` and `newSession` handshake, and only then publishes the run. Fulfillment means a remote session is ready and ownership has transferred to the caller. Disposal is idempotent: it closes stdin and waits a configured grace for cooperative quiescence, then escalates through SIGTERM to SIGKILL and awaits whole-range exit. Cleanup failures remain observable as ordered safe facts and never claim quiescence.
95
+
96
+ ### Stop-reason mapping
97
+
98
+ The run outcome maps the ACP terminal into the shared stop-reason vocabulary (`completed`, `max-tokens`, `refusal`, `aborted`, or `error`) in [`src/run.ts`](src/run.ts).
99
+
100
+ ### Process boundary
101
+
102
+ The child spawns through the subprocess seam: credential-shaped ambient variables are scrubbed, then explicit `config.env` values merge after the scrub. Stderr is inherited to the parent's stream, and disposal applies this provider's EOF window before the shared termination escalation.
103
+
104
+ </details>
105
+
106
+ -----
107
+
108
+ <a id="further-exploration"></a>
109
+ ## Further Exploration
110
+
111
+ Read these pages when the package-level contract is not enough. They move from this backend to the seam it plugs into and the protocol it drives.
112
+
113
+ - [Subagent subsystem](../../../docs/subsystems/subagent.md) — the service contract, provider contract, and terminal result semantics.
114
+ - [qilin-subagent seam](../subagent/README.md) — the registry and start API this provider registers on.
115
+ - [Agent Client Protocol automation server](../../acp/acp/README.md) — the automation-only server this provider drives as a client.
116
+ - [qilin-subprocess seam](../../subprocess/subprocess/README.md) — the process-spawn and teardown machinery behind each run.
117
+ - [Generated configuration catalog](../../../docs/config-catalog.md#qilin-agentsubagent-acp) — every accepted config field and its source declaration.
118
+
119
+ -----
120
+
121
+ <a id="model-experience"></a>
122
+ ## Model Experience
123
+
124
+ ### Child-agent request
125
+
126
+ #### What the model sees
127
+
128
+ The remote child receives the standalone task content through ACP plus its own process's configured system prompt, tools, and fresh session. It receives no parent conversation. This provider advertises no optional start-time capabilities, so the local service rejects requests for `agentOptions`, persona, tool filtering, depth enforcement, or structured output instead of silently omitting them.
129
+
130
+ #### Token effect
131
+
132
+ The child pays for an independent full context and its own multi-step history. These tokens never enter the parent's context.
133
+
134
+ #### KV Cache effect
135
+
136
+ Independent of the parent request cache. Each ACP child can reuse only prefixes identical under its own provider, model, composition, and history; child steps otherwise grow append-only.
137
+
138
+ ### Parent tool result, indirectly
139
+
140
+ #### What the model sees
141
+
142
+ Through `qilin-tool-subagent`, the parent receives only the child's final streamed assistant text or that consumer's exact stop-reason error, not intermediate messages or tool traffic. Non-completed results present the safe diagnostic before separately preserved partial assistant output. A request already cancelled before publication becomes exactly `Error: subagent request was aborted before the ACP child started`; another start failure contains only the fixed `Subagent failure (...)` line.
143
+
144
+ #### Token effect
145
+
146
+ Parent input grows only by the final result or error, which is data-dependent and retained until compaction. This provider adds no parent schema itself.
147
+
148
+ #### KV Cache effect
149
+
150
+ Append-only; newly visible content follows the reusable request prefix and does not invalidate existing KV-cache entries.
151
+
152
+ ## Known Limitations and Deferred Work
153
+
154
+ <a id="known-limitations-and-deferred-work"></a>
155
+
156
+
157
+ These limits define when this backend is a poor fit or needs special operational care. They are current package constraints, not a general ACP comparison or a task backlog.
158
+
159
+ - **A fresh process per run** — there is no process pooling; each delegation pays the full spawn and ACP handshake cost.
160
+ - **Local workspaces only** — the resolved working directory is a local path handed to a child on the same machine; remote workspace mapping is not designed.
161
+ - **No optional start-time capabilities** — this provider cannot apply `agentOptions`, `outputSchema`, a depth cap, a tool filter, or a persona inside the remote process, so the seam rejects requests that require them.
162
+ - **Only committed `agent_message_chunk` text is collected** — the automation server keeps reasoning, tool activity, plans, and other trace data in the child session log rather than emitting them on ACP.
163
+ - **Permission prompts are auto-answered** (`permission: allow | reject`) — no human is surfaced a child's `session/request_permission`.
164
+
165
+ <a id="dev-note"></a>
166
+ ### Dev Note
167
+
168
+ <details>
169
+ <summary>Working context for maintainers — click to expand</summary>
170
+
171
+ This Dev Note is working context for maintainers: open questions and undecided directions. It is explicitly non-authoritative — shipped behavior and limits live in the sections above and in the package code.
172
+
173
+ - **Process pooling** — persistent-process reuse is a possible future optimization but changes the per-run isolation model.
174
+ - **Remote workspaces** — mapping a remote ACP agent's workspace would need its own backend capability.
175
+ - **Continuable ACP children** — would require persisting the remote session id and a per-child continuation advertisement.
176
+
177
+ </details>
package/README.zh.md ADDED
@@ -0,0 +1,177 @@
1
+ ---
2
+ description: "面向用户与维护者的进程外 ACP(Agent Client Protocol)subagent 后端,用于选择委派提供方、配置子 ACP agent(智能体)命令或排查远程子 agent 运行问题。"
3
+ kind: "package-reference"
4
+ ---
5
+
6
+ # @qilin-agent/subagent-acp
7
+
8
+ [English](README.md) | 中文
9
+
10
+ ## 概述
11
+
12
+ 使用本包可将任务委派给运行在全新子进程中的 ACP 兼容 agent;子 agent 拥有独立的运行时、会话、模型和工具。每次运行只共享选定的工作目录,通过 ACP 发送任务,并返回子 agent 的最终答案或安全错误;中间消息和工具流量不会进入父级对话。权限提示由配置的策略自动应答,无需人工介入。当委派需要进程隔离或需要使用非 Harness ACP agent 时选择本包;当子 agent 必须共享父级能力时,选择进程内后端。
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
+ 当组合需要一个支持 Agent Client Protocol、完全隔离且在进程外运行的子 agent 时,挂载本提供方。常用路径是显式的:挂载 seam、挂载本提供方,并给出一个启动 ACP agent 的命令。
29
+
30
+ ### 何时选择
31
+
32
+ 当子 agent 必须在独立进程中运行、拥有自己的运行时、模型和工具时选择此后端——例如来自其他项目的 ACP agent——或者你希望委派完全无法触及父 harness 时。当子 agent 必须共享父级组合或遵守父级强制执行的能力约束时,请选择进程内后端:本提供方不声明任何可选启动时能力,因此 seam 会拒绝要求 `agentOptions`、结构化输出、深度上限、工具过滤或 persona 的请求,而不是静默省略。
33
+
34
+ ### 配置
35
+
36
+ | 字段 | 默认值 | 含义 |
37
+ |---|---|---|
38
+ | `providerName` | `acp` | `ctx.subagents` 上的注册表名称 |
39
+ | `command` | 必填 | 每次运行时 spawn 的可执行文件(子 ACP agent) |
40
+ | `args` | `[]` | 命令参数 |
41
+ | `cwd` | 父会话 cwd | 子进程及其 ACP 会话的工作目录覆盖值 |
42
+ | `permission` | `reject` | 自动应答权限请求:拒绝,或选择第一个 `allow_once` 或 `allow_always` 选项(`allow`) |
43
+ | `env` | `{}` | 叠加在已清理凭据的父环境之上的显式子环境 |
44
+ | `disposeEofGraceMs` | `6000` | stdin EOF 之后、平台终止之前的宽限 |
45
+ | `disposeGraceMs` | `3000` | 失败后观察结构化进程事实的时限;在 POSIX 上也是 SIGTERM 到 SIGKILL 的宽限 |
46
+
47
+ 生成的[配置目录](../../../docs/config-catalog.zh.md#qilin-agentsubagent-acp)是每个受支持字段及其 JSDoc 的穷尽式真源。
48
+
49
+ DeepSeek Harness 子进程使用产品启动器和一个显式的绝对路径 `QILIN_HOME`。隔离的 home 可防止嵌套运行时发现启动者个人的 profile 或凭据;通用 ACP 提供方不会把这一要求强加给非 QILIN agent。
50
+
51
+ ```yaml
52
+ - id: subagent-acp
53
+ name: '@qilin-agent/subagent-acp'
54
+ config:
55
+ providerName: acp
56
+ command: qilin
57
+ args: ['--profile', 'acp', '--patch', '/absolute/path/to/acp.patch.yml']
58
+ permission: reject
59
+ env:
60
+ QILIN_HOME: /absolute/path/to/isolated-child-home
61
+ DEEPSEEK_API_KEY: !!js process.env.DEEPSEEK_API_KEY
62
+ ```
63
+
64
+ ### 你会得到什么
65
+
66
+ 成功的运行会把子 agent 最终的流式 assistant 文本作为结果输出返回。子 agent 的会话、模型与工具来自子进程自身——父级只提供任务与工作目录。停止原因把 `end_turn` 映射为 `completed`、`max_tokens` 映射为 `max-tokens`、`refusal` 映射为 `refusal`、`cancelled` 映射为 `aborted`,其余值映射为 `error`。已发布运行失败时,部分 assistant 文本保留在 `output`,安全的结构化详情则单独放在 `diagnostic`。
67
+
68
+ ### 失败与恢复
69
+
70
+ spawn、初始化或新建会话失败会在发布前拒绝,通常先证明 managed range 已经完全停稳。如果清理也失败,拒绝会保留有序、安全的启动与拆卸事实,但不会声称整个 range 已经停稳。非取消错误只暴露固定的提供方、阶段与类别事实;原始失败保留在内部 cause 链与 Host 诊断中。发布后,提示词、传输或进程提前退出会以携带安全诊断的 `error` 结算;本地取消则以不带失败详情的 `aborted` 结算。
71
+
72
+ ### 安全诊断
73
+
74
+ 通用诊断使用固定的一行:`Subagent failure (provider: ACP; stage: <stage>; category: <category>; ...)`。可选的停止原因、退出码与信号只来自封闭协议或受管进程事实。stderr、异常文本、任务内容、工具输入、路径、环境值、凭据与协议载荷绝不会进入诊断;共享结果边界把诊断限制在 4096 个 UTF-8 字节内。请求过权限且未完成的运行可以增加一行固定的策略、工具种类与决定。成功运行和本地取消不包含该行。
75
+
76
+ -----
77
+
78
+ <a id="understand-the-implementation"></a>
79
+ ## 理解实现
80
+
81
+ <details>
82
+ <summary>实现细节——点击展开</summary>
83
+
84
+ 本节解释后端如何经 ACP 驱动子 agent,以及可观察行为从何而来;完整约定见[使用本包](#use-this-package)。
85
+
86
+ ### 设计理念
87
+
88
+ - **完全进程隔离。** 每个子 agent 在全新子进程中运行,拥有自己的会话、模型与工具;只有解析后的工作目录来自父级。
89
+ - **每次运行一个进程。** 每次运行都 spawn 新进程;没有进程池。
90
+ - **ACP 协议格式(wire format)是序列化边界。** 同进程 subagent 值不会为防御目的克隆;协议才是校验不可信输入的地方。
91
+
92
+ ### 启动与所有权流程
93
+
94
+ 一次启动先解析子 agent 的工作目录(配置的 `cwd` 覆盖值,否则取父会话 cwd),经子进程 seam spawn 命令,完成 ACP `initialize` 与 `newSession` 握手,然后才发布运行。兑现意味着远程会话已就绪、所有权已转移给调用方。dispose(资源释放)是幂等的:先关闭 stdin 并按配置的宽限等待协作式完全停稳,再经 SIGTERM 升级到 SIGKILL,并等待整个 managed range 退出。清理失败会作为有序的安全事实保持可观察,且绝不声称已经完全停稳。
95
+
96
+ ### 停止原因映射
97
+
98
+ 运行结果会把 ACP 终态映射进共享的停止原因词汇(`completed`、`max-tokens`、`refusal`、`aborted` 或 `error`),实现见 [`src/run.ts`](src/run.ts)。
99
+
100
+ ### 进程边界
101
+
102
+ 子进程经子进程 seam spawn:先清除疑似凭据的环境变量,再合并显式 `config.env` 值。stderr 继承到父级流,dispose 先应用本提供方的 EOF 窗口,再执行共享的逐级终止。
103
+
104
+ </details>
105
+
106
+ -----
107
+
108
+ <a id="further-exploration"></a>
109
+ ## 进一步探索
110
+
111
+ 当包级约定不够用时阅读以下页面。它们从本后端逐步进入它接入的 seam 与它驱动的协议。
112
+
113
+ - [Subagent 子系统](../../../docs/subsystems/subagent.zh.md)——服务约定、提供方约定与终态结果语义。
114
+ - [qilin-subagent seam](../subagent/README.zh.md)——本提供方注册于其上的注册表与启动 API。
115
+ - [Agent Client Protocol 自动化服务器](../../acp/acp/README.zh.md)——本提供方作为客户端驱动的仅自动化服务器。
116
+ - [qilin-subprocess seam](../../subprocess/subprocess/README.zh.md)——每次运行背后的进程 spawn 与清理机制。
117
+ - [生成配置目录](../../../docs/config-catalog.zh.md#qilin-agentsubagent-acp)——每个受支持配置字段及其源声明。
118
+
119
+ -----
120
+
121
+ <a id="model-experience"></a>
122
+ ## 模型体验
123
+
124
+ ### 子 agent 请求
125
+
126
+ #### 模型看到什么
127
+
128
+ 远程子 agent 通过 ACP 接收独立任务内容,并使用其自身进程配置的系统提示词、工具和全新会话。它不接收父级对话。本提供方不声明可选启动时能力,因此本地服务会拒绝要求 `agentOptions`、persona、工具过滤、深度强制或结构化输出的请求,而不是静默省略。
129
+
130
+ #### Token 影响
131
+
132
+ 子 agent 为独立的完整上下文及其多步骤历史支付 token 成本。这些 token 绝不会进入父级上下文。
133
+
134
+ #### KV Cache 影响
135
+
136
+ 与父级请求缓存相互独立。每个 ACP 子 agent 只能在其自身提供方、模型、组合和历史均相同时复用前缀;其余情况下,子 agent 步骤仅追加增长。
137
+
138
+ ### 父级工具结果(间接)
139
+
140
+ #### 模型看到什么
141
+
142
+ 通过 `qilin-tool-subagent`,父级只接收子 agent 最终的流式 assistant 文本或该消费方给出的精确停止原因错误,不接收中间消息或工具流量。未完成的结果会先呈现安全诊断,再单独保留部分 assistant 输出。发布前已经取消的请求会精确变为 `Error: subagent request was aborted before the ACP child started`;其他启动失败只包含固定的 `Subagent failure (...)` 行。
143
+
144
+ #### Token 影响
145
+
146
+ 父级输入只增加最终结果或错误,其内容依赖数据,并保留到压缩(compaction)为止。本提供方自身不会添加父级 schema。
147
+
148
+ #### KV Cache 影响
149
+
150
+ 仅追加;新增可见内容位于可复用请求前缀之后,不会使现有 KV Cache 条目失效。
151
+
152
+ ## 已知限制与延期工作
153
+
154
+ <a id="known-limitations-and-deferred-work"></a>
155
+
156
+
157
+ 这些限制说明本后端何时不合适,或何时需要特别的运维注意。它们是当前包约束,不是通用 ACP 对比或任务积压。
158
+
159
+ - **每次运行使用全新进程**——没有进程池;每次委派都要付出完整的 spawn 与 ACP 握手成本。
160
+ - **仅支持本地工作区**——解析后的工作目录是交给同一台机器上子进程的本地路径;远程工作区映射尚未设计。
161
+ - **不支持可选启动时能力**——本提供方无法在远程进程内应用 `agentOptions`、`outputSchema`、深度上限、工具过滤器或 persona,因此 seam 会拒绝需要它们的请求。
162
+ - **只收集已提交的 `agent_message_chunk` 文本**——自动化服务器把推理(reasoning)、工具活动、计划和其他 trace 数据保留在子 agent 会话日志中,不通过 ACP 发出。
163
+ - **权限提示自动应答**(`permission: allow | reject`)——不会把子 agent 的 `session/request_permission` 呈现给人。
164
+
165
+ <a id="dev-note"></a>
166
+ ### 开发备注
167
+
168
+ <details>
169
+ <summary>维护者的工作上下文——点击展开</summary>
170
+
171
+ 本开发备注是维护者的工作上下文:开放问题与尚未决定的探索方向。它明确不具权威性——已交付的行为与限制以上文和包代码为准。
172
+
173
+ - **进程池**——持久进程复用是可能的未来优化,但会改变每次运行的隔离模型。
174
+ - **远程工作区**——映射远程 ACP agent 的工作区需要独立的后端能力。
175
+ - **可继续执行的 ACP 子 agent**——需要持久化远程会话 id,并为每个子 agent 声明继续执行能力。
176
+
177
+ </details>
package/lib/index.js ADDED
@@ -0,0 +1,559 @@
1
+ import { accessSync, constants, statSync } from "node:fs";
2
+ import { isAbsolute, resolve } from "node:path";
3
+ import z from "@qilin-agent/schemastery";
4
+ import { MAX_TIMER_DELAY_MS } from "@qilin-agent/timeout";
5
+ import { randomUUID } from "node:crypto";
6
+ import { Readable, Writable } from "node:stream";
7
+ import { PROTOCOL_VERSION, client, methods, ndJsonStream } from "@agentclientprotocol/sdk";
8
+ import { brandString } from "@qilin-agent/brand";
9
+ import { AssistantOutputFold, settleRunResult, subprocessRunHandle } from "@qilin-agent/subagent";
10
+ //#region lib/types/run.js
11
+ /**
12
+ * Fresh-process ACP subagent client. Drives one child session and owns cancellation and
13
+ * quiescent disposal.
14
+ *
15
+ * @module @qilin-agent/subagent-acp/run
16
+ */
17
+ /** EOF grace for child flush and nested-process teardown; wider than the signal grace below. */
18
+ const DEFAULT_DISPOSE_EOF_GRACE_MS = 6e3;
19
+ /** Default POSIX grace between SIGTERM and SIGKILL on dispose (the `disposeGraceMs` config). */
20
+ const DEFAULT_DISPOSE_GRACE_MS = 3e3;
21
+ const ACP_TOOL_KINDS = new Set([
22
+ "read",
23
+ "edit",
24
+ "delete",
25
+ "move",
26
+ "search",
27
+ "execute",
28
+ "think",
29
+ "fetch",
30
+ "switch_mode",
31
+ "other"
32
+ ]);
33
+ /** Fixed safe failure text derived only from provider-owned structured facts. */
34
+ function failureDiagnostic(facts) {
35
+ const fields = [
36
+ "provider: ACP",
37
+ `stage: ${facts.stage}`,
38
+ `category: ${facts.category}`
39
+ ];
40
+ if (facts.stopReason !== void 0) fields.push(`stop reason: ${facts.stopReason}`);
41
+ if (facts.outcome?.exitCode !== null && facts.outcome?.exitCode !== void 0) fields.push(`exit code: ${facts.outcome.exitCode}`);
42
+ /* v8 ignore next -- Windows does not report POSIX child signals in SubprocessOutcome. */
43
+ if (facts.outcome?.signal !== null && facts.outcome?.signal !== void 0) fields.push(`signal: ${facts.outcome.signal}`);
44
+ return `Subagent failure (${fields.join("; ")})`;
45
+ }
46
+ /** Fixed permission fact; ACP tool titles and option text never enter it. */
47
+ function permissionDiagnostic(permission) {
48
+ return `ACP unattended decision (policy: ${permission.policy}; request: ${permission.request}; decision: ${permission.decision})`;
49
+ }
50
+ /** Put the operation failure first, followed by the latest permission decision. */
51
+ function diagnosticText(facts, permission) {
52
+ const failure = failureDiagnostic(facts);
53
+ return permission === void 0 ? failure : `${failure}\n${permissionDiagnostic(permission)}`;
54
+ }
55
+ var AcpRunFailure = class extends Error {
56
+ constructor(facts, cause) {
57
+ super(`subagent-acp: ${failureDiagnostic(facts)}`, { cause });
58
+ this.name = "AcpRunFailure";
59
+ }
60
+ };
61
+ /**
62
+ * Hide a pre-spawn workspace/configuration failure behind fixed safe facts.
63
+ * @param cause - original Host failure retained on the Error cause chain.
64
+ * @returns an Error whose message contains only the fixed ACP failure line.
65
+ */
66
+ function acpConfigurationFailure(cause) {
67
+ return new AcpRunFailure({
68
+ stage: "initialize",
69
+ category: "configuration"
70
+ }, cause);
71
+ }
72
+ /** Keep only the closed ACP tool-kind vocabulary; future values use a fixed fallback. */
73
+ function permissionRequestKind(kind) {
74
+ const candidate = kind ?? "unknown";
75
+ return ACP_TOOL_KINDS.has(candidate) ? candidate : "unknown";
76
+ }
77
+ /** Bounded managed-range exit wait: observes the handle's range until it is empty or `ms` elapses. */
78
+ async function rangeExitsWithin(child, ms) {
79
+ const controller = new AbortController();
80
+ const timer = setTimeout(() => {
81
+ controller.abort();
82
+ }, ms);
83
+ try {
84
+ return await child.waitForExit(controller.signal);
85
+ } finally {
86
+ clearTimeout(timer);
87
+ }
88
+ }
89
+ /**
90
+ * Cooperative teardown ladder for an out-of-process agent, over the seam's
91
+ * public verbs; resolves only at whole-range quiescence: stdin EOF (the child's
92
+ * window to flush persistence and reap its own descendants), then the
93
+ * terminate() escalation (SIGTERM → spec grace → SIGKILL) and its
94
+ * whole-range exit proof.
95
+ * @param child - the spawned ACP child's handle.
96
+ * @param eofGraceMs - tier-1 window after stdin EOF.
97
+ */
98
+ async function disposeAcpChild(child, eofGraceMs) {
99
+ const failures = [];
100
+ child.stdin?.end();
101
+ let exited = false;
102
+ try {
103
+ exited = await rangeExitsWithin(child, eofGraceMs);
104
+ } catch (error) {
105
+ failures.push(toError(error));
106
+ }
107
+ if (exited) return;
108
+ child.terminate();
109
+ try {
110
+ await child.waitForExit();
111
+ } catch (error) {
112
+ failures.push(toError(error));
113
+ }
114
+ if (failures.length === 1) throw failures[0];
115
+ if (failures.length > 1) throw new AggregateError(failures, "ACP subprocess teardown failed");
116
+ }
117
+ /**
118
+ * Map an ACP {@link StopReason} to a harness {@link SubagentStopReason}.
119
+ * @param reason - the terminal reason from the child's `session/prompt` response.
120
+ * @returns the harness equivalent; `max_turn_requests` and any unknown future
121
+ * variant map to `error`, so an unclean stop is never reported as `completed`.
122
+ */
123
+ function acpStopReason(reason) {
124
+ switch (reason) {
125
+ case "end_turn": return "completed";
126
+ case "max_tokens": return "max-tokens";
127
+ case "refusal": return "refusal";
128
+ case "cancelled": return "aborted";
129
+ case "max_turn_requests": return "error";
130
+ default: return "error";
131
+ }
132
+ }
133
+ /**
134
+ * Collect the text of an ACP content block (non-text blocks contribute nothing).
135
+ * @param content - the content block off a streamed `agent_message_chunk`.
136
+ * @returns the block's text, or `''` for a non-text block.
137
+ */
138
+ function acpContentText(content) {
139
+ return content.type === "text" ? content.text : "";
140
+ }
141
+ /**
142
+ * Translate the harness prompt blocks into ACP prompt blocks (text only).
143
+ * @param prompt - the harness prompt; non-text blocks are dropped.
144
+ * @returns the ACP text blocks, in order.
145
+ */
146
+ function toAcpPrompt(prompt) {
147
+ const blocks = [];
148
+ for (const block of prompt) if (block.type === "text") blocks.push({
149
+ type: "text",
150
+ text: block.text
151
+ });
152
+ return blocks;
153
+ }
154
+ /** Normalize an unknown thrown value to an Error (the catch binding is `unknown`). */
155
+ function toError(value) {
156
+ /* v8 ignore next */
157
+ return value instanceof Error ? value : new Error(String(value));
158
+ }
159
+ /** Report an original Host failure without letting the observation sink replace it. */
160
+ function reportFailure(spec, error) {
161
+ try {
162
+ spec.onError?.(toError(error), "error");
163
+ } catch {}
164
+ }
165
+ /** Classify an unpublished failure from the active protocol operation and observed process facts. */
166
+ function startupFailure(error, stage, outcome) {
167
+ return new AcpRunFailure(
168
+ /* v8 ignore next -- Windows anonymous pipes cannot expose a live-child protocol close during startup. */
169
+ outcome === void 0 ? {
170
+ stage,
171
+ category: "transport"
172
+ } : {
173
+ stage,
174
+ category: "process-exit",
175
+ outcome
176
+ },
177
+ error
178
+ );
179
+ }
180
+ /** Map one remote terminal reason to the optional safe failure line it needs. */
181
+ function terminalFailure(reason, permission) {
182
+ switch (reason) {
183
+ case "end_turn": return;
184
+ case "max_turn_requests": return diagnosticText({
185
+ stage: "prompt",
186
+ category: "remote-limit",
187
+ stopReason: "max_turn_requests"
188
+ }, permission);
189
+ case "max_tokens":
190
+ case "refusal":
191
+ case "cancelled": return permission === void 0 ? void 0 : permissionDiagnostic(permission);
192
+ default: return diagnosticText({
193
+ stage: "prompt",
194
+ category: "unknown",
195
+ stopReason: "unknown"
196
+ }, permission);
197
+ }
198
+ }
199
+ /**
200
+ * Start and publish one ACP child after initialization and session creation.
201
+ * Child failures resolve through the run result. Startup rejects with fixed
202
+ * safe facts after provider-owned cleanup; successful cleanup proves managed
203
+ * range quiescence. Cleanup failure preserves startup plus teardown facts for an ordinary
204
+ * failure, or teardown alone after cancellation, without claiming quiescence.
205
+ * Disposal cancels, terminates, and settles the child's managed range.
206
+ * @param request - the start request; its signal is the cancellation channel.
207
+ * @param spec - the resolved spawn spec: command/args/cwd, env, permission
208
+ * policy, dispose graces, and the optional error sink.
209
+ * @returns the ready run handle for the child subprocess.
210
+ */
211
+ async function startAcpRun(request, spec) {
212
+ if (request.signal.aborted) throw new Error("subagent request was aborted before the ACP child started");
213
+ const id = brandString(randomUUID());
214
+ let child;
215
+ try {
216
+ child = spec.spawn({
217
+ argv: [spec.command, ...spec.args],
218
+ cwd: spec.cwd,
219
+ stdio: {
220
+ stdin: "pipe",
221
+ stdout: "pipe",
222
+ stderr: "inherit"
223
+ },
224
+ graceMs: spec.disposeGraceMs,
225
+ env: spec.env
226
+ });
227
+ } catch (error) {
228
+ reportFailure(spec, error);
229
+ throw new AcpRunFailure({
230
+ stage: "process",
231
+ category: "process-start"
232
+ }, error);
233
+ }
234
+ /* v8 ignore start -- 'pipe' dispositions expose both streams by the seam contract; defensive. */
235
+ if (child.stdin === void 0 || child.stdout === void 0) throw new Error("subagent-acp: subprocess implementation dropped a piped protocol stream");
236
+ /* v8 ignore stop */
237
+ let processOutcome;
238
+ let processFailure;
239
+ const processDone = child.done.then((outcome) => {
240
+ processOutcome = outcome;
241
+ return outcome;
242
+ }, (error) => {
243
+ processFailure = toError(error);
244
+ throw processFailure;
245
+ });
246
+ const processRejected = processDone.then(
247
+ /* v8 ignore next -- the success arm's never-settling executor is intentionally empty. */
248
+ () => new Promise(() => {}),
249
+ (err) => Promise.reject(toError(err))
250
+ );
251
+ processRejected.catch(() => {});
252
+ const observeProcessOutcome = async (signal) => {
253
+ if (processOutcome !== void 0) return processOutcome;
254
+ const timeout = AbortSignal.timeout(Math.ceil(spec.disposeGraceMs));
255
+ const bound = signal === void 0 ? timeout : AbortSignal.any([signal, timeout]);
256
+ const aborted = Promise.withResolvers();
257
+ /* v8 ignore next -- Windows cannot expose the live-child protocol close needed to await this abort. */
258
+ const onObservationAbort = () => {
259
+ aborted.resolve(void 0);
260
+ };
261
+ bound.addEventListener("abort", onObservationAbort, { once: true });
262
+ /* v8 ignore next -- closes the event-loop race between listener registration and the preceding derived-signal check. */
263
+ if (bound.aborted) onObservationAbort();
264
+ try {
265
+ return await Promise.race([processDone, aborted.promise]);
266
+ } catch {
267
+ return processOutcome;
268
+ } finally {
269
+ bound.removeEventListener("abort", onObservationAbort);
270
+ }
271
+ };
272
+ let processDisposal;
273
+ const disposeProcess = () => processDisposal ??= disposeAcpChild(child, spec.disposeEofGraceMs);
274
+ const fold = new AssistantOutputFold();
275
+ const flags = { cancelled: false };
276
+ let latestPermission;
277
+ const agent = client({ name: "deepseek-harness-subagent-acp" }).onNotification(methods.client.session.update, ({ params }) => {
278
+ const update = params.update;
279
+ if (update.sessionUpdate === "agent_message_chunk") fold.pushText(acpContentText(update.content));
280
+ return Promise.resolve();
281
+ }).onRequest(methods.client.session.requestPermission, ({ params }) => {
282
+ if (spec.permission === "allow") {
283
+ const allow = params.options.find((o) => o.kind === "allow_once" || o.kind === "allow_always");
284
+ if (allow !== void 0) {
285
+ latestPermission = {
286
+ policy: "allow",
287
+ request: permissionRequestKind(params.toolCall.kind),
288
+ decision: "allowed"
289
+ };
290
+ return Promise.resolve({ outcome: {
291
+ outcome: "selected",
292
+ optionId: allow.optionId
293
+ } });
294
+ }
295
+ }
296
+ latestPermission = {
297
+ policy: spec.permission,
298
+ request: permissionRequestKind(params.toolCall.kind),
299
+ decision: "denied"
300
+ };
301
+ return Promise.resolve({ outcome: { outcome: "cancelled" } });
302
+ }).connect(ndJsonStream(Writable.toWeb(child.stdin), Readable.toWeb(child.stdout))).agent;
303
+ let sessionId;
304
+ let startupStage = "initialize";
305
+ let signalCancelSettled;
306
+ const cancelSettled = new Promise((resolve) => {
307
+ signalCancelSettled = resolve;
308
+ });
309
+ const requestCancel = () => {
310
+ if (flags.cancelled) return;
311
+ flags.cancelled = true;
312
+ signalCancelSettled();
313
+ /* v8 ignore next */
314
+ if (sessionId !== void 0) agent.notify(methods.agent.session.cancel, { sessionId }).catch(() => {});
315
+ };
316
+ const onAbort = () => {
317
+ requestCancel();
318
+ };
319
+ request.signal.addEventListener("abort", onAbort, { once: true });
320
+ const collectOutput = () => fold.collect() ?? [];
321
+ try {
322
+ await Promise.race([
323
+ (async () => {
324
+ await agent.request(methods.agent.initialize, {
325
+ protocolVersion: PROTOCOL_VERSION,
326
+ clientCapabilities: {}
327
+ });
328
+ startupStage = "new-session";
329
+ const session = await agent.request(methods.agent.session.new, {
330
+ cwd: spec.cwd,
331
+ mcpServers: []
332
+ });
333
+ const returnedSessionId = Reflect.get(session, "sessionId");
334
+ if (typeof returnedSessionId !== "string") throw new AcpRunFailure({
335
+ stage: "new-session",
336
+ category: "protocol"
337
+ }, /* @__PURE__ */ new Error("ACP child published without a session id"));
338
+ sessionId = returnedSessionId;
339
+ /* v8 ignore next -- cancelSettled wins the startup race before this post-response guard can settle it. */
340
+ if (flags.cancelled) throw new Error("subagent cancelled before the ACP session started");
341
+ })(),
342
+ processRejected,
343
+ cancelSettled.then(() => {
344
+ throw new Error("subagent cancelled before the ACP session started");
345
+ })
346
+ ]);
347
+ } catch (error) {
348
+ request.signal.removeEventListener("abort", onAbort);
349
+ const cancelledBeforeCleanup = flags.cancelled;
350
+ const observedOutcome = !cancelledBeforeCleanup && !(error instanceof AcpRunFailure) ? await observeProcessOutcome() : void 0;
351
+ const startup = cancelledBeforeCleanup ? { kind: "cancelled" } : {
352
+ kind: "failed",
353
+ failure: error instanceof AcpRunFailure ? error : startupFailure(error, startupStage, observedOutcome)
354
+ };
355
+ if (startup.kind === "cancelled") {} else reportFailure(spec, error instanceof AcpRunFailure ? error.cause : processFailure ?? error);
356
+ try {
357
+ await disposeProcess();
358
+ } catch (cleanupError) {
359
+ reportFailure(spec, cleanupError);
360
+ const cleanupFailure = new AcpRunFailure({
361
+ stage: "teardown",
362
+ category: processOutcome === void 0 ? "unknown" : "process-exit",
363
+ ...processOutcome === void 0 ? {} : { outcome: processOutcome }
364
+ }, cleanupError);
365
+ if (startup.kind === "cancelled") throw new AggregateError([cleanupFailure], cleanupFailure.message);
366
+ throw new AggregateError([startup.failure, cleanupFailure], `${startup.failure.message}; ${cleanupFailure.message}`);
367
+ }
368
+ if (startup.kind === "cancelled") throw new Error("subagent request was aborted before the ACP child started");
369
+ throw startup.failure;
370
+ }
371
+ /* v8 ignore next */
372
+ if (sessionId === void 0) throw new Error("unreachable: ACP startup fulfilled without a session id");
373
+ const remoteSessionId = sessionId;
374
+ let diagnostic;
375
+ return subprocessRunHandle({
376
+ id,
377
+ result: settleRunResult({
378
+ attempt: async () => {
379
+ try {
380
+ const promptResult = await Promise.race([agent.request(methods.agent.session.prompt, {
381
+ sessionId: remoteSessionId,
382
+ prompt: toAcpPrompt(request.prompt)
383
+ }), cancelSettled.then(() => {
384
+ throw new Error("subagent cancelled while the ACP prompt was running");
385
+ })]);
386
+ const stopReason = acpStopReason(promptResult.stopReason);
387
+ diagnostic = terminalFailure(promptResult.stopReason, latestPermission);
388
+ return {
389
+ output: collectOutput(),
390
+ ...diagnostic === void 0 ? {} : { diagnostic },
391
+ stopReason
392
+ };
393
+ } catch (error) {
394
+ if (!flags.cancelled) {
395
+ const outcome = await observeProcessOutcome(request.signal);
396
+ diagnostic = diagnosticText(outcome === void 0 ? {
397
+ stage: "prompt",
398
+ category: "transport"
399
+ } : {
400
+ stage: "process",
401
+ category: "process-exit",
402
+ outcome
403
+ }, latestPermission);
404
+ }
405
+ throw processFailure ?? error;
406
+ }
407
+ },
408
+ collectOutput,
409
+ collectDiagnostic: () => diagnostic,
410
+ cancelled: () => flags.cancelled,
411
+ onError: spec.onError,
412
+ signal: request.signal,
413
+ onAbort
414
+ }),
415
+ signal: request.signal,
416
+ onAbort,
417
+ requestCancel,
418
+ teardown: async () => {
419
+ try {
420
+ await disposeProcess();
421
+ } catch (error) {
422
+ reportFailure(spec, error);
423
+ throw new AcpRunFailure({
424
+ stage: "teardown",
425
+ category: processOutcome === void 0 ? "unknown" : "process-exit",
426
+ ...processOutcome === void 0 ? {} : { outcome: processOutcome }
427
+ }, error);
428
+ }
429
+ }
430
+ });
431
+ }
432
+ //#endregion
433
+ //#region lib/types/index.js
434
+ /**
435
+ * Out-of-process ACP subagent backend. Each child has its own process, session, model, and
436
+ * tools, so it shares no Cordis context and advertises no parent-enforced start capabilities;
437
+ * the ONE thing it reads off `request.parent` is the session's workspace cwd (see
438
+ * {@link resolveCwd}). This plugin uses named exports only; a default would hide its
439
+ * loader metadata (see `docs/postmortem/0001-acp-default-export-drops-inject.md`).
440
+ * @module @qilin-agent/subagent-acp
441
+ */
442
+ const name = "subagent-acp";
443
+ const inject = ["subagents", "subprocess"];
444
+ const Config = z.object({
445
+ providerName: z.string().default("acp"),
446
+ command: z.string().required(),
447
+ args: z.array(z.string()).default([]),
448
+ cwd: z.string(),
449
+ permission: z.union(["allow", "reject"]).default("reject"),
450
+ env: z.dict(z.string()).default({}),
451
+ disposeEofGraceMs: z.number().default(DEFAULT_DISPOSE_EOF_GRACE_MS),
452
+ disposeGraceMs: z.number().default(DEFAULT_DISPOSE_GRACE_MS)
453
+ });
454
+ /** A process grace must fit every Node timer that observes or terminates the child. */
455
+ function assertPositiveFinite(name, value) {
456
+ if (!Number.isFinite(value) || value <= 0 || value > MAX_TIMER_DELAY_MS) throw new Error(`subagent-acp: ${name} must be a positive finite number no greater than ${MAX_TIMER_DELAY_MS}`);
457
+ }
458
+ /**
459
+ * Whether `path` names an existing directory the harness can ENTER. The
460
+ * search-permission probe matters: `statSync().isDirectory()` is true for a
461
+ * mode-600 directory, but a subprocess cwd needs `X_OK` or spawn fails EACCES.
462
+ */
463
+ function isDirectory(path) {
464
+ try {
465
+ if (!statSync(path).isDirectory()) return false;
466
+ accessSync(path, constants.X_OK);
467
+ return true;
468
+ } catch {
469
+ return false;
470
+ }
471
+ }
472
+ /**
473
+ * Assert `cwd` can actually host the child: absolute (it doubles as the ACP
474
+ * session workspace, and a relative path would be re-anchored to the server
475
+ * process's launch directory) and an existing directory (fail here, before the
476
+ * process boundary, instead of as an ambiguous spawn ENOENT).
477
+ * @param label - which source supplied the value, for the diagnostic.
478
+ * @param cwd - the candidate working directory.
479
+ * @returns `cwd`, validated.
480
+ */
481
+ function assertUsableCwd(label, cwd) {
482
+ if (!isAbsolute(cwd)) throw new Error(`subagent-acp: ${label} must be an absolute path: ${cwd}`);
483
+ if (!isDirectory(cwd)) throw new Error(`subagent-acp: ${label} is not an accessible directory: ${cwd}`);
484
+ return cwd;
485
+ }
486
+ /**
487
+ * Resolve the child's working directory: the deployment `cwd` override when
488
+ * configured (already validated at load), else the parent session's workspace
489
+ * cwd (validated here, its earliest resolvable point). Fails loud when neither
490
+ * exists — falling back to the harness process cwd would silently bind the
491
+ * child to the server's launch directory instead of the delegating session's
492
+ * workspace (one server process serves many sessions, each with its own cwd).
493
+ */
494
+ function resolveCwd(configured, request) {
495
+ if (configured !== void 0) return configured;
496
+ const parentCwd = request.parent.session.header.cwd;
497
+ if (parentCwd === void 0) throw new Error("subagent-acp: no working directory for the child — configure `cwd` or delegate from a parent session that has one");
498
+ return assertUsableCwd("parent session cwd", parentCwd);
499
+ }
500
+ /**
501
+ * The ACP provider. Advertises NO start-time capabilities: an out-of-process
502
+ * child cannot honor `agentOptions`/`outputSchema`/`maxDepth`/`toolFilter`/
503
+ * `persona` (the service rejects a request needing any before `start` runs).
504
+ */
505
+ var AcpProvider = class {
506
+ name;
507
+ ctx;
508
+ config;
509
+ capabilities = {
510
+ agentOptions: false,
511
+ outputSchema: false,
512
+ depthLimit: false,
513
+ toolFilter: false,
514
+ persona: false
515
+ };
516
+ inheritsParentContext = false;
517
+ constructor(name, ctx, config) {
518
+ this.name = name;
519
+ this.ctx = ctx;
520
+ this.config = config;
521
+ }
522
+ start(request) {
523
+ if (request.signal.aborted) throw new Error("subagent request was aborted before the ACP child started");
524
+ let cwd;
525
+ try {
526
+ cwd = resolveCwd(this.config.cwd, request);
527
+ } catch (error) {
528
+ const failure = acpConfigurationFailure(error);
529
+ this.ctx.logger.warn(`subagent-acp "${this.name}": child start failed: %o`, error);
530
+ throw failure;
531
+ }
532
+ return startAcpRun(request, {
533
+ command: this.config.command,
534
+ args: this.config.args,
535
+ cwd,
536
+ permission: this.config.permission,
537
+ env: this.config.env,
538
+ disposeEofGraceMs: this.config.disposeEofGraceMs,
539
+ disposeGraceMs: this.config.disposeGraceMs,
540
+ spawn: (spec) => this.ctx.subprocess.spawn(spec),
541
+ onError: (error, stopReason) => {
542
+ this.ctx.logger.warn(`subagent-acp "${this.name}": child run failed (${stopReason}): ${error.message}`);
543
+ }
544
+ });
545
+ }
546
+ };
547
+ function apply(ctx, config) {
548
+ const resolved = config;
549
+ assertPositiveFinite("disposeEofGraceMs", resolved.disposeEofGraceMs);
550
+ assertPositiveFinite("disposeGraceMs", resolved.disposeGraceMs);
551
+ if (resolved.cwd === "") throw new Error("subagent-acp: config cwd must not be empty — omit the key to inherit the parent session cwd");
552
+ const validated = resolved.cwd === void 0 ? resolved : {
553
+ ...resolved,
554
+ cwd: assertUsableCwd("config cwd", resolve(resolved.cwd))
555
+ };
556
+ ctx.subagents.registerProvider(new AcpProvider(validated.providerName, ctx, validated));
557
+ }
558
+ //#endregion
559
+ export { Config, apply, inject, name };
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Out-of-process ACP subagent backend. Each child has its own process, session, model, and
3
+ * tools, so it shares no Cordis context and advertises no parent-enforced start capabilities;
4
+ * the ONE thing it reads off `request.parent` is the session's workspace cwd (see
5
+ * {@link resolveCwd}). This plugin uses named exports only; a default would hide its
6
+ * loader metadata (see `docs/postmortem/0001-acp-default-export-drops-inject.md`).
7
+ * @module @qilin-agent/subagent-acp
8
+ */
9
+ import type { Context } from '@qilin-agent/kylin';
10
+ import z from '@qilin-agent/schemastery';
11
+ import { type PermissionPolicy } from './run.ts';
12
+ export declare const name = "subagent-acp";
13
+ export declare const inject: string[];
14
+ /** Config: how to spawn and drive the child ACP agent process. */
15
+ export interface Config {
16
+ /** Provider name on `ctx.subagents` (default `acp`). */
17
+ providerName: string;
18
+ /** The executable to spawn for each run (the child ACP agent). */
19
+ command: string;
20
+ /** Arguments passed to {@link command}. */
21
+ args: string[];
22
+ /**
23
+ * Working directory override for the child process and its ACP session.
24
+ * Must be non-empty; a relative path resolves against the harness launch
25
+ * directory at load, and the result must be an existing directory. When
26
+ * omitted, each child inherits its delegating parent session's cwd — and
27
+ * starting one from a parent session that has no cwd fails.
28
+ */
29
+ cwd?: string;
30
+ /**
31
+ * How to auto-answer the child's `session/request_permission` prompts:
32
+ * `reject` (default — decline every prompt) or `allow` (approve via the first
33
+ * `allow_once` or `allow_always` option). No prompt is surfaced to a human.
34
+ */
35
+ permission: PermissionPolicy;
36
+ /**
37
+ * Extra environment variables for the child process — e.g. the child
38
+ * harness's own `DEEPSEEK_API_KEY`. Forwarded on top of a credential-scrubbed
39
+ * copy of the parent env, so an explicit key here reaches the child while
40
+ * ambient secrets do not leak implicitly.
41
+ */
42
+ env: Record<string, string>;
43
+ /**
44
+ * Grace period (ms) for the child's EOF-driven quiesce on dispose — its
45
+ * window to flush persistence and tear down its own nested subprocesses
46
+ * before the parent escalates to a signal. Must not exceed
47
+ * `MAX_TIMER_DELAY_MS`.
48
+ */
49
+ disposeEofGraceMs?: number;
50
+ /** Failure-observation and termination-escalation grace (ms); must not exceed `MAX_TIMER_DELAY_MS`. */
51
+ disposeGraceMs?: number;
52
+ }
53
+ export declare const Config: z<Config>;
54
+ export declare function apply(ctx: Context, config: Config): void;
55
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Fresh-process ACP subagent client. Drives one child session and owns cancellation and
3
+ * quiescent disposal.
4
+ *
5
+ * @module @qilin-agent/subagent-acp/run
6
+ */
7
+ import { type ContentBlock as AcpContentBlock, type StopReason } from '@agentclientprotocol/sdk';
8
+ import type { ContentBlock } from '@qilin-agent/llm';
9
+ import type { SubagentRun, SubagentStartRequest, SubagentStopReason } from '@qilin-agent/subagent';
10
+ import type { SubprocessHandle, SubprocessSpawnSpec } from '@qilin-agent/subprocess';
11
+ /** Fixed response to child permission requests: reject by default, or select the first allow option. */
12
+ export type PermissionPolicy = 'allow' | 'reject';
13
+ /** Resolved spawn spec for an ACP child process (no defaults — see Config). */
14
+ export interface AcpRunSpec {
15
+ /** The executable to spawn (the child ACP agent). */
16
+ command: string;
17
+ /** Arguments passed to {@link command}. */
18
+ args: string[];
19
+ /**
20
+ * Absolute working directory for the child process AND its ACP session
21
+ * `cwd`. The provider resolves it before this spec exists: config override,
22
+ * else the delegating parent session's workspace.
23
+ */
24
+ cwd: string;
25
+ /** How to auto-answer the child's permission prompts. */
26
+ permission: PermissionPolicy;
27
+ /**
28
+ * Extra environment variables to ADD for the child (e.g. the child harness's
29
+ * `DEEPSEEK_API_KEY`). Merged on top of the subprocess seam's scrubbed
30
+ * parent env. A value here is forwarded even if its name matches the
31
+ * credential-scrub pattern (an explicit opt-in for the child's own creds).
32
+ * Explicit `QILIN_*` entries are deployment-owned facts for the child harness
33
+ * (e.g. `QILIN_PERMISSION_MODE`); they simply merge after the scrub that
34
+ * dropped their stale ambient namesakes.
35
+ */
36
+ env: Record<string, string>;
37
+ /**
38
+ * Grace period (ms) for the child's EOF-driven quiesce in
39
+ * {@link SubagentRun.dispose} — the window to flush persistence and tear down
40
+ * its OWN nested subprocesses before the parent escalates to a signal. The
41
+ * plugin fills this from its `disposeEofGraceMs` config.
42
+ */
43
+ disposeEofGraceMs: number;
44
+ /**
45
+ * Process-observation and termination-escalation grace (ms). Failure
46
+ * classification waits at most this long for structured exit facts; POSIX
47
+ * dispose also waits this long after `SIGTERM` before `SIGKILL`, while
48
+ * Windows force-terminates directly. The plugin fills it from
49
+ * `disposeGraceMs`.
50
+ */
51
+ disposeGraceMs: number;
52
+ /**
53
+ * Spawn function from the subprocess seam (`ctx.subprocess.spawn`), so the
54
+ * child rides the shared scrub, managed-range teardown, and service-owned
55
+ * lifetime instead of a package-local child_process path.
56
+ */
57
+ spawn: (spec: SubprocessSpawnSpec) => SubprocessHandle;
58
+ /**
59
+ * Host sink for startup, published-run, or teardown failures. Model-visible
60
+ * text uses fixed safe facts, while this callback retains the original Error
61
+ * when one exists. A throw from the sink itself is contained.
62
+ */
63
+ onError?: (error: Error, stopReason: SubagentStopReason) => void;
64
+ }
65
+ /** EOF grace for child flush and nested-process teardown; wider than the signal grace below. */
66
+ export declare const DEFAULT_DISPOSE_EOF_GRACE_MS = 6000;
67
+ /** Default POSIX grace between SIGTERM and SIGKILL on dispose (the `disposeGraceMs` config). */
68
+ export declare const DEFAULT_DISPOSE_GRACE_MS = 3000;
69
+ /**
70
+ * Hide a pre-spawn workspace/configuration failure behind fixed safe facts.
71
+ * @param cause - original Host failure retained on the Error cause chain.
72
+ * @returns an Error whose message contains only the fixed ACP failure line.
73
+ */
74
+ export declare function acpConfigurationFailure(cause: unknown): Error;
75
+ /**
76
+ * Cooperative teardown ladder for an out-of-process agent, over the seam's
77
+ * public verbs; resolves only at whole-range quiescence: stdin EOF (the child's
78
+ * window to flush persistence and reap its own descendants), then the
79
+ * terminate() escalation (SIGTERM → spec grace → SIGKILL) and its
80
+ * whole-range exit proof.
81
+ * @param child - the spawned ACP child's handle.
82
+ * @param eofGraceMs - tier-1 window after stdin EOF.
83
+ */
84
+ export declare function disposeAcpChild(child: SubprocessHandle, eofGraceMs: number): Promise<void>;
85
+ /**
86
+ * Map an ACP {@link StopReason} to a harness {@link SubagentStopReason}.
87
+ * @param reason - the terminal reason from the child's `session/prompt` response.
88
+ * @returns the harness equivalent; `max_turn_requests` and any unknown future
89
+ * variant map to `error`, so an unclean stop is never reported as `completed`.
90
+ */
91
+ export declare function acpStopReason(reason: StopReason): SubagentStopReason;
92
+ /**
93
+ * Collect the text of an ACP content block (non-text blocks contribute nothing).
94
+ * @param content - the content block off a streamed `agent_message_chunk`.
95
+ * @returns the block's text, or `''` for a non-text block.
96
+ */
97
+ export declare function acpContentText(content: AcpContentBlock): string;
98
+ /**
99
+ * Translate the harness prompt blocks into ACP prompt blocks (text only).
100
+ * @param prompt - the harness prompt; non-text blocks are dropped.
101
+ * @returns the ACP text blocks, in order.
102
+ */
103
+ export declare function toAcpPrompt(prompt: ContentBlock[]): AcpContentBlock[];
104
+ /**
105
+ * Start and publish one ACP child after initialization and session creation.
106
+ * Child failures resolve through the run result. Startup rejects with fixed
107
+ * safe facts after provider-owned cleanup; successful cleanup proves managed
108
+ * range quiescence. Cleanup failure preserves startup plus teardown facts for an ordinary
109
+ * failure, or teardown alone after cancellation, without claiming quiescence.
110
+ * Disposal cancels, terminates, and settles the child's managed range.
111
+ * @param request - the start request; its signal is the cancellation channel.
112
+ * @param spec - the resolved spawn spec: command/args/cwd, env, permission
113
+ * policy, dispose graces, and the optional error sink.
114
+ * @returns the ready run handle for the child subprocess.
115
+ */
116
+ export declare function startAcpRun(request: SubagentStartRequest, spec: AcpRunSpec): Promise<SubagentRun>;
117
+ //# sourceMappingURL=run.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,63 @@
1
1
  {
2
2
  "name": "@qilin-agent/subagent-acp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "description": "Out-of-process ACP subagent backend: drives a child agent in a spawned subprocess over the Agent Client Protocol",
4
+ "version": "3.1.3",
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/kkutysllb/QiLin.git",
11
+ "directory": "packages/subagent/subagent-acp"
12
+ },
13
+ "engines": {
14
+ "node": "^22.19.0 || >=24.0.0"
15
+ },
16
+ "type": "module",
17
+ "main": "lib/index.js",
18
+ "types": "lib/types/index.d.ts",
19
+ "exports": {
20
+ ".": {
21
+ "types": "./lib/types/index.d.ts",
22
+ "default": "./lib/index.js"
23
+ },
24
+ "./src/*": "./src/*",
25
+ "./package.json": "./package.json"
26
+ },
27
+ "files": [
28
+ "lib/index.js",
29
+ "lib/types/**/*.d.ts"
30
+ ],
31
+ "license": "MIT",
32
+ "peerDependencies": {
33
+ "@qilin-agent/kylin": "~4.0.3",
34
+ "@qilin-agent/agent": "3.1.3",
35
+ "@qilin-agent/session": "3.1.3",
36
+ "@qilin-agent/llm": "3.1.3",
37
+ "@qilin-agent/timeout": "3.1.3",
38
+ "@qilin-agent/subagent": "3.1.3",
39
+ "@qilin-agent/subprocess": "3.1.3"
40
+ },
41
+ "dependencies": {
42
+ "@agentclientprotocol/sdk": "1.4.0",
43
+ "@qilin-agent/schemastery": "~3.18.3",
44
+ "@qilin-agent/brand": "3.1.3"
45
+ },
46
+ "devDependencies": {
47
+ "@qilin-agent/kylin": "~4.0.3",
48
+ "@qilin-agent/agent": "3.1.3",
49
+ "@qilin-agent/app-boot": "3.1.3",
50
+ "@qilin-agent/kylin-plugin-loader": "~1.0.4",
51
+ "@qilin-agent/llm": "3.1.3",
52
+ "@qilin-agent/loader-smoke": "3.1.3",
53
+ "@qilin-agent/session": "3.1.3",
54
+ "@qilin-agent/session-checkpoint-policy": "3.1.3",
55
+ "@qilin-agent/subagent": "3.1.3",
56
+ "@qilin-agent/session-persistence-jsonl": "3.1.3",
57
+ "@qilin-agent/subprocess": "3.1.3",
58
+ "@qilin-agent/subprocess-local": "3.1.3",
59
+ "@qilin-agent/timeout": "3.1.3",
60
+ "@qilin-agent/tool-subagent": "3.1.3",
61
+ "@qilin-agent/session-projection": "3.1.3"
62
+ }
6
63
  }