@ktkid/kmh-subagent-team 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,39 @@
1
- # Temporary Holding Version
1
+ # @ktkid/kmh-subagent-team
2
2
 
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.
3
+ 面向所有 DeepSeek Harness(DSH)会话的外部 ACP Agent 团队插件。原生接入 `agy acp`(Antigravity)、`grok agent stdio`(Grok Build)与 `codex-acp`(Codex),支持异步派发、按次选模型与思考档位、带 `sessionId` 续聊,以及主会话审批等级透传与弹回确认。
4
+
5
+ ## 目录结构
6
+
7
+ - `src/acp/`:公共 stdio JSON-RPC ACP 客户端底座(握手、会话管理、流式事件、用量与安全审批映射)
8
+ - `src/adapters/`:成员适配器(`agy`、`grok`、`generic`)
9
+ - `src/runtime/`:父会话审批等级透传(`danger-full-access` 自动放行 / `ask` 弹回确认)与独立后台任务管理器
10
+ - `docs/spec/kmh-subagent-team/`:需求规格([spec.md](docs/spec/kmh-subagent-team/spec.md))与技术设计([tech-design.md](docs/spec/kmh-subagent-team/tech-design.md))
11
+
12
+ ## 已接入成员与基线版本
13
+
14
+ | 成员 ID | 说明 | 实测基线版本 |
15
+ |---|---|---|
16
+ | `agy-acp` | Google Antigravity 原生 `agy acp` | `agy 1.5.13` |
17
+ | `grok-acp` | xAI Grok Build 原生 `grok agent stdio` | `grok 1.0.92` |
18
+ | `codex-acp` | `@agentclientprotocol/codex-acp` + Codex CLI | `codex-acp 2.12.1` / `codex 0.171.0-alpha.13.2` |
19
+ | `workbuddy-acp` | WorkBuddy 原生 ACP(`codebuddy-lite-wb`) | 跟随本机 WorkBuddy.app 内置 CLI |
20
+ | `zcode-acp` | ZCode 大臣(复用宿主 `zcode-cli` + `subagents`) | `zcode 0.18.0`(宿主 `@kmh/zcode-cli`) |
21
+
22
+ ## 暴露工具(所有 DSH 会话可用)
23
+
24
+ | 工具 | 作用 |
25
+ |---|---|
26
+ | `acp_list_members` | 探测所有已配置 ACP 成员的就绪状态、登录指引及可用模型/模式 |
27
+ | `acp_dispatch` | 异步派发任务给指定成员,可选 `model` / `effort` / `mode` / `cwd` 或 `sessionId` 续聊 |
28
+ | `acp_status` | 查看当前会话派出的后台任务状态与待审批项 |
29
+ | `acp_approve` | 当主会话空闲挂起审批时,提交 `allow` / `reject` / `cancel` |
30
+ | `acp_cancel` | 显式中止指定后台子任务(主会话 Stop 不会误杀后台任务) |
31
+
32
+ ## 开发与验证
33
+
34
+ ```bash
35
+ pnpm install
36
+ pnpm typecheck
37
+ pnpm build
38
+ pnpm test
39
+ ```
@@ -0,0 +1,4 @@
1
+ # 挂入 kmh-subagent-team 插件;成员默认内置 agy-acp 与 grok-acp,可在主仓覆盖。
2
+ - insert:
3
+ - id: kmh-subagent-team
4
+ name: "@ktkid/kmh-subagent-team"
@@ -0,0 +1,35 @@
1
+ /** 公共 ACP 客户端底座:握手、建/续会话、发提示词、流式采集、审批转发与显式取消。 */
2
+ import type { TokenUsage } from "@deepseek-ai/dsh-llm";
3
+ import { type AcpPermissionRequest, type AcpToolRecord, type PermissionDecision } from "./protocol.ts";
4
+ import { type StdioOpener } from "./process.ts";
5
+ export interface AcpRunRequest {
6
+ readonly command: string;
7
+ readonly args: readonly string[];
8
+ readonly cwd: string;
9
+ readonly env: NodeJS.ProcessEnv;
10
+ readonly prompt: string;
11
+ /** 传入则尝试通过 session/load 或 session/resume 接续同一外部会话。 */
12
+ readonly resumeSessionId?: string;
13
+ /** 可选由适配器在握手/建会话后设置模型、模式或思考档位。 */
14
+ readonly configureSession?: (call: (method: string, params: unknown) => Promise<unknown>, sessionId: string, createdResult: unknown, initResult: unknown) => Promise<void>;
15
+ /** 读取并归一化 token 用量。 */
16
+ readonly extractUsage?: (promptResponse: unknown) => TokenUsage | undefined;
17
+ /** 审批请求回调(支持同步自动放行或异步等待父会话确认)。 */
18
+ readonly decide: (request: AcpPermissionRequest) => Promise<PermissionDecision>;
19
+ /** 仅受显式取消或插件卸载控制,不受主会话 Stop 影响。 */
20
+ readonly signal: AbortSignal;
21
+ readonly shutdownGraceMs?: number;
22
+ }
23
+ export interface AcpRunResult {
24
+ readonly ok: boolean;
25
+ readonly stage: "spawn" | "initialize" | "session" | "configure" | "prompt" | "cancelled";
26
+ readonly sessionId?: string;
27
+ readonly text: string;
28
+ readonly reasoning: string;
29
+ readonly tools: readonly AcpToolRecord[];
30
+ readonly stopReason?: string;
31
+ readonly usage?: TokenUsage;
32
+ readonly error?: string;
33
+ }
34
+ /** 驱动一次完整的 ACP 回合(新建或续聊),并返回汇总正文、过程、用量与外部 sessionId。 */
35
+ export declare function runAcpTurn(req: AcpRunRequest, open?: StdioOpener): Promise<AcpRunResult>;
@@ -0,0 +1,343 @@
1
+ import { asRecord, jsonRpcIdOf, parsePermissionRequest, parseSessionUpdate, rpcErrorMessage, selectPermissionOutcome, sessionIdOf, stopReasonOf, } from "./protocol.js";
2
+ import { disposeStdioProcess, openStdioProcess, } from "./process.js";
3
+ /** 驱动一次完整的 ACP 回合(新建或续聊),并返回汇总正文、过程、用量与外部 sessionId。 */
4
+ export async function runAcpTurn(req, open = openStdioProcess) {
5
+ if (req.signal.aborted) {
6
+ return {
7
+ ok: false,
8
+ stage: "cancelled",
9
+ text: "",
10
+ reasoning: "",
11
+ tools: [],
12
+ error: "任务在启动前已被显式取消。",
13
+ };
14
+ }
15
+ let proc;
16
+ try {
17
+ proc = open(req.command, req.args, req.env, req.cwd);
18
+ }
19
+ catch (err) {
20
+ return {
21
+ ok: false,
22
+ stage: "spawn",
23
+ text: "",
24
+ reasoning: "",
25
+ tools: [],
26
+ error: `无法启动进程 ${req.command}: ${err instanceof Error ? err.message : String(err)}`,
27
+ };
28
+ }
29
+ const stderrLines = [];
30
+ const stderrPump = (async () => {
31
+ for await (const line of proc.stderr) {
32
+ stderrLines.push(line);
33
+ if (stderrLines.length > 30)
34
+ stderrLines.shift();
35
+ }
36
+ })().catch(() => undefined);
37
+ let nextId = 1;
38
+ const waiters = new Map();
39
+ const inbox = new MessageInbox();
40
+ let activeSessionId;
41
+ const sendRaw = (payload) => {
42
+ proc.send(JSON.stringify(payload));
43
+ };
44
+ const call = (method, params) => {
45
+ const id = nextId++;
46
+ const promise = new Promise((resolve) => {
47
+ waiters.set(id, resolve);
48
+ });
49
+ sendRaw({ jsonrpc: "2.0", id, method, params });
50
+ return promise;
51
+ };
52
+ const onAbort = () => {
53
+ if (activeSessionId !== undefined) {
54
+ sendRaw({
55
+ jsonrpc: "2.0",
56
+ method: "session/cancel",
57
+ params: { sessionId: activeSessionId },
58
+ });
59
+ }
60
+ inbox.close();
61
+ for (const [pendingId, resolve] of waiters) {
62
+ waiters.delete(pendingId);
63
+ resolve(undefined);
64
+ }
65
+ proc.kill("SIGTERM");
66
+ };
67
+ req.signal.addEventListener("abort", onAbort, { once: true });
68
+ const stdoutPump = (async () => {
69
+ try {
70
+ for await (const line of proc.lines) {
71
+ let parsed;
72
+ try {
73
+ parsed = JSON.parse(line);
74
+ }
75
+ catch {
76
+ continue;
77
+ }
78
+ // 服务端发起的请求(如 session/request_permission)既带 id 又带 method,优先入 inbox。
79
+ const perm = parsePermissionRequest(parsed);
80
+ if (perm !== undefined) {
81
+ inbox.push(parsed);
82
+ continue;
83
+ }
84
+ const id = jsonRpcIdOf(parsed);
85
+ const method = asRecord(parsed)?.["method"];
86
+ if (id !== undefined && method === undefined) {
87
+ const waiter = waiters.get(id);
88
+ if (waiter !== undefined) {
89
+ waiters.delete(id);
90
+ waiter(parsed);
91
+ continue;
92
+ }
93
+ }
94
+ inbox.push(parsed);
95
+ }
96
+ }
97
+ finally {
98
+ inbox.close();
99
+ for (const [pendingId, resolve] of waiters) {
100
+ waiters.delete(pendingId);
101
+ resolve(undefined);
102
+ }
103
+ }
104
+ })();
105
+ const textParts = [];
106
+ const reasoningParts = [];
107
+ const tools = new Map();
108
+ let fallbackToolSeq = 0;
109
+ try {
110
+ const initResp = await call("initialize", {
111
+ protocolVersion: 1,
112
+ clientCapabilities: {},
113
+ clientInfo: { name: "kmh-subagent-team", version: "0.1.0" },
114
+ });
115
+ if (req.signal.aborted) {
116
+ return cancelledResult(activeSessionId, textParts, reasoningParts, tools);
117
+ }
118
+ if (initResp === undefined) {
119
+ const spawnErr = await getSpawnFailure(proc);
120
+ if (spawnErr !== undefined) {
121
+ return failResult("spawn", `无法启动进程 ${req.command}: ${spawnErr.message}`, activeSessionId, textParts, reasoningParts, tools);
122
+ }
123
+ return failResult("initialize", `ACP 握手未响应。${formatStderr(stderrLines)}`, activeSessionId, textParts, reasoningParts, tools);
124
+ }
125
+ const initErr = rpcErrorMessage(initResp);
126
+ if (initErr !== undefined) {
127
+ return failResult("initialize", `ACP 握手失败:${initErr}`, activeSessionId, textParts, reasoningParts, tools);
128
+ }
129
+ let sessionResp;
130
+ if (req.resumeSessionId !== undefined) {
131
+ sessionResp = await call("session/load", {
132
+ sessionId: req.resumeSessionId,
133
+ cwd: req.cwd,
134
+ mcpServers: [],
135
+ });
136
+ if (sessionResp === undefined ||
137
+ rpcErrorMessage(sessionResp) !== undefined) {
138
+ const resumeResp = await call("session/resume", {
139
+ sessionId: req.resumeSessionId,
140
+ cwd: req.cwd,
141
+ mcpServers: [],
142
+ });
143
+ if (resumeResp !== undefined &&
144
+ rpcErrorMessage(resumeResp) === undefined) {
145
+ sessionResp = resumeResp;
146
+ }
147
+ }
148
+ if (sessionResp === undefined) {
149
+ return failResult("session", `无法恢复会话 ${req.resumeSessionId}:子进程无响应。${formatStderr(stderrLines)}`, req.resumeSessionId, textParts, reasoningParts, tools);
150
+ }
151
+ const loadErr = rpcErrorMessage(sessionResp);
152
+ if (loadErr !== undefined) {
153
+ return failResult("session", `无法恢复会话 ${req.resumeSessionId}:${loadErr}`, req.resumeSessionId, textParts, reasoningParts, tools);
154
+ }
155
+ activeSessionId = sessionIdOf(sessionResp) ?? req.resumeSessionId;
156
+ }
157
+ else {
158
+ sessionResp = await call("session/new", {
159
+ cwd: req.cwd,
160
+ mcpServers: [],
161
+ });
162
+ if (sessionResp === undefined) {
163
+ return failResult("session", `建立 ACP 会话无响应。${formatStderr(stderrLines)}`, undefined, textParts, reasoningParts, tools);
164
+ }
165
+ const sessErr = rpcErrorMessage(sessionResp);
166
+ if (sessErr !== undefined) {
167
+ return failResult("session", `建立 ACP 会话失败:${sessErr}`, undefined, textParts, reasoningParts, tools);
168
+ }
169
+ activeSessionId = sessionIdOf(sessionResp);
170
+ if (activeSessionId === undefined) {
171
+ return failResult("session", "建立 ACP 会话失败:服务端未返回 sessionId。", undefined, textParts, reasoningParts, tools);
172
+ }
173
+ }
174
+ if (req.configureSession !== undefined) {
175
+ try {
176
+ await req.configureSession(call, activeSessionId, sessionResp, initResp);
177
+ }
178
+ catch (err) {
179
+ return failResult("configure", err instanceof Error ? err.message : String(err), activeSessionId, textParts, reasoningParts, tools);
180
+ }
181
+ }
182
+ const promptPromise = call("session/prompt", {
183
+ sessionId: activeSessionId,
184
+ prompt: [{ type: "text", text: req.prompt }],
185
+ });
186
+ inbox.follow(promptPromise);
187
+ for (;;) {
188
+ const msg = await inbox.next();
189
+ if (msg === undefined)
190
+ break;
191
+ const perm = parsePermissionRequest(msg);
192
+ if (perm !== undefined) {
193
+ const decision = await req.decide(perm);
194
+ if (req.signal.aborted)
195
+ break;
196
+ sendRaw({
197
+ jsonrpc: "2.0",
198
+ id: perm.id,
199
+ result: { outcome: selectPermissionOutcome(decision, perm.options) },
200
+ });
201
+ continue;
202
+ }
203
+ const update = parseSessionUpdate(msg);
204
+ if (update === undefined)
205
+ continue;
206
+ if (update.kind === "text") {
207
+ textParts.push(update.text);
208
+ }
209
+ else if (update.kind === "reasoning") {
210
+ reasoningParts.push(update.text);
211
+ }
212
+ else {
213
+ const key = update.tool.toolCallId ?? `anon-${String(++fallbackToolSeq)}`;
214
+ const prev = tools.get(key);
215
+ tools.set(key, prev === undefined ? update.tool : { ...prev, ...update.tool });
216
+ }
217
+ }
218
+ if (req.signal.aborted) {
219
+ return cancelledResult(activeSessionId, textParts, reasoningParts, tools);
220
+ }
221
+ const promptResp = await promptPromise;
222
+ if (promptResp === undefined) {
223
+ return failResult("prompt", `ACP 执行中断,未收到完成回执。${formatStderr(stderrLines)}`, activeSessionId, textParts, reasoningParts, tools);
224
+ }
225
+ const promptErr = rpcErrorMessage(promptResp);
226
+ if (promptErr !== undefined) {
227
+ return failResult("prompt", `ACP 执行失败:${promptErr}`, activeSessionId, textParts, reasoningParts, tools);
228
+ }
229
+ const reason = stopReasonOf(promptResp);
230
+ const usage = req.extractUsage?.(promptResp);
231
+ if (reason === "cancelled" || reason === "canceled") {
232
+ return cancelledResult(activeSessionId, textParts, reasoningParts, tools);
233
+ }
234
+ if (reason !== undefined && reason !== "end_turn" && reason !== "max_tokens") {
235
+ return {
236
+ ok: false,
237
+ stage: "prompt",
238
+ sessionId: activeSessionId,
239
+ text: textParts.join(""),
240
+ reasoning: reasoningParts.join(""),
241
+ tools: [...tools.values()],
242
+ stopReason: reason,
243
+ ...(usage === undefined ? {} : { usage }),
244
+ error: `ACP 回合未正常结束(stopReason=${reason})。`,
245
+ };
246
+ }
247
+ return {
248
+ ok: true,
249
+ stage: "prompt",
250
+ sessionId: activeSessionId,
251
+ text: textParts.join(""),
252
+ reasoning: reasoningParts.join(""),
253
+ tools: [...tools.values()],
254
+ ...(reason === undefined ? {} : { stopReason: reason }),
255
+ ...(usage === undefined ? {} : { usage }),
256
+ };
257
+ }
258
+ finally {
259
+ req.signal.removeEventListener("abort", onAbort);
260
+ await disposeStdioProcess(proc, req.shutdownGraceMs);
261
+ await stdoutPump.catch(() => undefined);
262
+ await stderrPump;
263
+ }
264
+ }
265
+ class MessageInbox {
266
+ queue = [];
267
+ waiting;
268
+ closed = false;
269
+ following = false;
270
+ follow(done) {
271
+ if (this.following)
272
+ return;
273
+ this.following = true;
274
+ void done.then(() => this.close(), () => this.close());
275
+ }
276
+ push(msg) {
277
+ if (this.closed)
278
+ return;
279
+ const w = this.waiting;
280
+ this.waiting = undefined;
281
+ if (w !== undefined) {
282
+ w(msg);
283
+ return;
284
+ }
285
+ this.queue.push(msg);
286
+ }
287
+ close() {
288
+ this.closed = true;
289
+ const w = this.waiting;
290
+ this.waiting = undefined;
291
+ w?.(undefined);
292
+ }
293
+ next() {
294
+ const queued = this.queue.shift();
295
+ if (queued !== undefined)
296
+ return Promise.resolve(queued);
297
+ if (this.closed)
298
+ return Promise.resolve(undefined);
299
+ return new Promise((resolve) => {
300
+ this.waiting = resolve;
301
+ });
302
+ }
303
+ }
304
+ function cancelledResult(sessionId, textParts, reasoningParts, tools) {
305
+ return {
306
+ ok: false,
307
+ stage: "cancelled",
308
+ ...(sessionId === undefined ? {} : { sessionId }),
309
+ text: textParts.join(""),
310
+ reasoning: reasoningParts.join(""),
311
+ tools: [...tools.values()],
312
+ stopReason: "cancelled",
313
+ error: "任务已被显式取消。",
314
+ };
315
+ }
316
+ function failResult(stage, error, sessionId, textParts, reasoningParts, tools) {
317
+ return {
318
+ ok: false,
319
+ stage,
320
+ ...(sessionId === undefined ? {} : { sessionId }),
321
+ text: textParts.join(""),
322
+ reasoning: reasoningParts.join(""),
323
+ tools: [...tools.values()],
324
+ error,
325
+ };
326
+ }
327
+ function formatStderr(lines) {
328
+ if (lines.length === 0)
329
+ return "";
330
+ return `stderr: ${lines.slice(-5).join(" | ")}`;
331
+ }
332
+ async function getSpawnFailure(proc) {
333
+ const immediate = proc.getSpawnError?.();
334
+ if (immediate !== undefined)
335
+ return immediate;
336
+ return await Promise.race([
337
+ proc.exited.then(() => undefined, (err) => (err instanceof Error ? err : new Error(String(err)))),
338
+ new Promise((resolve) => {
339
+ const timer = setTimeout(() => resolve(undefined), 50);
340
+ timer.unref?.();
341
+ }),
342
+ ]);
343
+ }
@@ -0,0 +1,22 @@
1
+ export interface StdioProcess {
2
+ send(line: string): void;
3
+ readonly lines: AsyncIterable<string>;
4
+ readonly stderr: AsyncIterable<string>;
5
+ closeStdin(): void;
6
+ kill(signal?: NodeJS.Signals): void;
7
+ readonly exited: Promise<number | null>;
8
+ /** 可选返回异步 spawn 失败原因(如 ENOENT)。 */
9
+ getSpawnError?(): Error | undefined;
10
+ }
11
+ export type StdioOpener = (command: string, args: readonly string[], env: NodeJS.ProcessEnv, cwd: string) => StdioProcess;
12
+ /**
13
+ * 为 GUI 桌面端(如 macOS Electron 仅有 /usr/bin:/bin:/usr/sbin:/sbin)补齐常见 CLI 安装目录。
14
+ * 保留已有 PATH 顺序在最前,缺失目录按兜底顺序追加在后。
15
+ */
16
+ export declare function buildAugmentedPath(currentPath: string | undefined, homeDir?: string): string;
17
+ /** 继承宿主环境并清除可能干扰本地订阅登录的密钥/配置覆盖,再叠加成员显式 env。 */
18
+ export declare function buildControlledEnv(baseEnv: NodeJS.ProcessEnv, overrides?: Readonly<Record<string, string>>): NodeJS.ProcessEnv;
19
+ /** 启动本机 stdio 子进程并返回逐行异步迭代器。 */
20
+ export declare function openStdioProcess(command: string, args: readonly string[], env: NodeJS.ProcessEnv, cwd: string): StdioProcess;
21
+ /** 优雅关闭子进程:先关闭 stdin,等待宽限时间后依次发 SIGTERM / SIGKILL。 */
22
+ export declare function disposeStdioProcess(proc: StdioProcess, graceMs?: number): Promise<void>;
@@ -0,0 +1,146 @@
1
+ /** 受控 stdio 子进程管理:清理敏感覆盖变量、按行读写 NDJSON、优雅退出与超时强杀。 */
2
+ import { spawn } from "node:child_process";
3
+ import { homedir } from "node:os";
4
+ import path from "node:path";
5
+ const SENSITIVE_ENV_KEY = /(API_KEY|_TOKEN|SECRET|PASSWORD|CREDENTIAL|AUTH_PROVIDER|OIDC_)/i;
6
+ const DROPPED_OVERRIDE_KEYS = new Set([
7
+ "GROK_CONFIG",
8
+ "GROK_CONFIG_PATH",
9
+ "GROK_AUTH_PROVIDER_COMMAND",
10
+ "GROK_AUTH_PROVIDER_LABEL",
11
+ "GROK_OIDC_ISSUER",
12
+ "GROK_OIDC_CLIENT_ID",
13
+ ]);
14
+ /**
15
+ * 为 GUI 桌面端(如 macOS Electron 仅有 /usr/bin:/bin:/usr/sbin:/sbin)补齐常见 CLI 安装目录。
16
+ * 保留已有 PATH 顺序在最前,缺失目录按兜底顺序追加在后。
17
+ */
18
+ export function buildAugmentedPath(currentPath, homeDir = homedir()) {
19
+ const existing = (currentPath ?? "")
20
+ .split(path.delimiter)
21
+ .map((s) => s.trim())
22
+ .filter((s) => s.length > 0);
23
+ if (process.platform === "win32") {
24
+ return existing.join(path.delimiter);
25
+ }
26
+ const fallbacks = [
27
+ path.join(homeDir, ".grok", "bin"),
28
+ path.join(homeDir, ".local", "bin"),
29
+ path.join(homeDir, "bin"),
30
+ "/opt/homebrew/bin",
31
+ "/opt/homebrew/sbin",
32
+ "/usr/local/bin",
33
+ "/usr/bin",
34
+ "/bin",
35
+ "/usr/sbin",
36
+ "/sbin",
37
+ ];
38
+ const seen = new Set(existing);
39
+ const merged = [...existing];
40
+ for (const dir of fallbacks) {
41
+ if (!seen.has(dir)) {
42
+ seen.add(dir);
43
+ merged.push(dir);
44
+ }
45
+ }
46
+ return merged.join(path.delimiter);
47
+ }
48
+ /** 继承宿主环境并清除可能干扰本地订阅登录的密钥/配置覆盖,再叠加成员显式 env。 */
49
+ export function buildControlledEnv(baseEnv, overrides = {}) {
50
+ const result = {};
51
+ for (const [key, value] of Object.entries(baseEnv)) {
52
+ if (value === undefined)
53
+ continue;
54
+ if (DROPPED_OVERRIDE_KEYS.has(key) || SENSITIVE_ENV_KEY.test(key))
55
+ continue;
56
+ result[key] = value;
57
+ }
58
+ result["PATH"] = buildAugmentedPath(result["PATH"], result["HOME"] ?? baseEnv["HOME"] ?? homedir());
59
+ for (const [key, value] of Object.entries(overrides)) {
60
+ result[key] = value;
61
+ }
62
+ return result;
63
+ }
64
+ /** 启动本机 stdio 子进程并返回逐行异步迭代器。 */
65
+ export function openStdioProcess(command, args, env, cwd) {
66
+ const child = spawn(command, [...args], {
67
+ cwd,
68
+ env,
69
+ stdio: ["pipe", "pipe", "pipe"],
70
+ });
71
+ let spawnError;
72
+ const exited = new Promise((resolve, reject) => {
73
+ child.once("error", (err) => {
74
+ spawnError = err;
75
+ reject(err);
76
+ });
77
+ child.once("exit", (code) => resolve(code));
78
+ });
79
+ // 防止未提前 await exited 时出现 unhandled rejection。
80
+ void exited.catch(() => undefined);
81
+ return {
82
+ send(line) {
83
+ if (!child.stdin.destroyed && !child.stdin.writableEnded) {
84
+ child.stdin.write(line.endsWith("\n") ? line : `${line}\n`);
85
+ }
86
+ },
87
+ lines: readLines(child.stdout),
88
+ stderr: readLines(child.stderr),
89
+ closeStdin() {
90
+ if (!child.stdin.destroyed && !child.stdin.writableEnded) {
91
+ child.stdin.end();
92
+ }
93
+ },
94
+ kill(signal) {
95
+ if (!child.killed) {
96
+ child.kill(signal);
97
+ }
98
+ },
99
+ exited,
100
+ getSpawnError() {
101
+ return spawnError;
102
+ },
103
+ };
104
+ }
105
+ /** 优雅关闭子进程:先关闭 stdin,等待宽限时间后依次发 SIGTERM / SIGKILL。 */
106
+ export async function disposeStdioProcess(proc, graceMs = 2_000) {
107
+ proc.closeStdin();
108
+ const done = proc.exited.catch(() => null);
109
+ const firstWait = await waitOrTimeout(done, Math.min(graceMs, 500));
110
+ if (firstWait !== "timeout")
111
+ return;
112
+ proc.kill("SIGTERM");
113
+ const secondWait = await waitOrTimeout(done, graceMs);
114
+ if (secondWait !== "timeout")
115
+ return;
116
+ proc.kill("SIGKILL");
117
+ await waitOrTimeout(done, 1_000);
118
+ }
119
+ async function waitOrTimeout(promise, ms) {
120
+ if (ms <= 0)
121
+ return "timeout";
122
+ return await Promise.race([
123
+ promise,
124
+ new Promise((resolve) => {
125
+ const timer = setTimeout(() => resolve("timeout"), ms);
126
+ timer.unref?.();
127
+ }),
128
+ ]);
129
+ }
130
+ async function* readLines(stream) {
131
+ let buffer = "";
132
+ for await (const chunk of stream) {
133
+ buffer += typeof chunk === "string" ? chunk : chunk.toString("utf8");
134
+ let nl = buffer.indexOf("\n");
135
+ while (nl >= 0) {
136
+ const line = buffer.slice(0, nl).trim();
137
+ buffer = buffer.slice(nl + 1);
138
+ nl = buffer.indexOf("\n");
139
+ if (line !== "")
140
+ yield line;
141
+ }
142
+ }
143
+ const tail = buffer.trim();
144
+ if (tail !== "")
145
+ yield tail;
146
+ }
@@ -0,0 +1,66 @@
1
+ /** 公共 ACP JSON-RPC 2.0 协议解析、权限选项安全映射与用量归一化。 */
2
+ import type { TokenUsage } from "@deepseek-ai/dsh-llm";
3
+ export type JsonRpcId = string | number;
4
+ export interface AcpOption {
5
+ readonly optionId: string;
6
+ readonly kind: string;
7
+ readonly name: string;
8
+ }
9
+ export interface AcpPermissionRequest {
10
+ readonly id: JsonRpcId;
11
+ readonly sessionId: string;
12
+ readonly toolCallId?: string;
13
+ readonly title: string;
14
+ readonly kind?: string;
15
+ readonly options: readonly AcpOption[];
16
+ }
17
+ export interface AcpToolRecord {
18
+ readonly toolCallId?: string;
19
+ readonly title: string;
20
+ readonly kind?: string;
21
+ readonly status?: string;
22
+ }
23
+ export type AcpUpdateEvent = {
24
+ readonly kind: "text";
25
+ readonly text: string;
26
+ } | {
27
+ readonly kind: "reasoning";
28
+ readonly text: string;
29
+ } | {
30
+ readonly kind: "tool";
31
+ readonly tool: AcpToolRecord;
32
+ };
33
+ export type PermissionDecision = "allow" | "reject" | "cancel";
34
+ /** 读取 JSON-RPC 消息的请求/响应 ID(同时兼容 number 与 string)。 */
35
+ export declare function jsonRpcIdOf(message: unknown): JsonRpcId | undefined;
36
+ /** 读取 JSON-RPC 错误信息。 */
37
+ export declare function rpcErrorMessage(message: unknown): string | undefined;
38
+ /** 读取 sessionId(兼容顶层 result.sessionId)。 */
39
+ export declare function sessionIdOf(message: unknown): string | undefined;
40
+ /** 读取 session/prompt 回执里的 stopReason。 */
41
+ export declare function stopReasonOf(message: unknown): string | undefined;
42
+ /** 解析 session/update 通知中的正文、思考增量与工具调用记录。 */
43
+ export declare function parseSessionUpdate(message: unknown): AcpUpdateEvent | undefined;
44
+ /** 解析子 ACP 发来的 session/request_permission 请求(支持 number/string id)。 */
45
+ export declare function parsePermissionRequest(message: unknown): AcpPermissionRequest | undefined;
46
+ /**
47
+ * 安全映射审批决策到 ACP outcome(约束 C2):
48
+ * - cancel 一律返回 cancelled;
49
+ * - allow 仅匹配 kind 含 allow 的选项(优先 allow_once),找不到则 cancelled;
50
+ * - reject 仅匹配 kind 含 reject 的选项,找不到时固定返回 cancelled,绝不兜底选 options[0]。
51
+ */
52
+ export declare function selectPermissionOutcome(decision: PermissionDecision, options: readonly AcpOption[]): {
53
+ outcome: "cancelled";
54
+ } | {
55
+ outcome: "selected";
56
+ optionId: string;
57
+ };
58
+ /**
59
+ * 从 session/prompt 回执提取并归一化 token 用量(约束 C4:不捏造估算值)。
60
+ * grok 口径下 inputTokens 已包含缓存读写,需扣减后填入 DSH 互斥输入桶。
61
+ */
62
+ export declare function extractPromptUsage(message: unknown, inputIncludesCache: boolean): TokenUsage | undefined;
63
+ /** 读取 configOptions 中指定 id 的 currentValue。 */
64
+ export declare function configCurrentValue(message: unknown, id: string): string | undefined;
65
+ export declare function asRecord(value: unknown): Record<string, unknown> | undefined;
66
+ export declare function nonEmptyString(value: unknown): string | undefined;