@oh-my-dsh/dsh-better-subagent 0.5.3 → 0.5.5-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -4
- package/docs/DEVELOPMENT.md +19 -15
- package/lib/child-exit-guard.d.ts +45 -0
- package/lib/child-exit-guard.js +96 -0
- package/lib/child-exit-guard.js.map +1 -0
- package/lib/cli/claude.d.ts +49 -0
- package/lib/cli/claude.js +177 -0
- package/lib/cli/claude.js.map +1 -0
- package/lib/cli/codex.d.ts +46 -0
- package/lib/cli/codex.js +174 -0
- package/lib/cli/codex.js.map +1 -0
- package/lib/cli/jsonl.d.ts +72 -0
- package/lib/cli/jsonl.js +211 -0
- package/lib/cli/jsonl.js.map +1 -0
- package/lib/cli/types.d.ts +44 -0
- package/lib/cli/types.js +2 -0
- package/lib/cli/types.js.map +1 -0
- package/lib/cli/version.d.ts +56 -0
- package/lib/cli/version.js +95 -0
- package/lib/cli/version.js.map +1 -0
- package/lib/cli-adapter.d.ts +42 -0
- package/lib/cli-adapter.js +226 -0
- package/lib/cli-adapter.js.map +1 -0
- package/lib/cli-sessions.d.ts +28 -0
- package/lib/cli-sessions.js +79 -0
- package/lib/cli-sessions.js.map +1 -0
- package/lib/client.js +1911 -0
- package/lib/config.d.ts +278 -0
- package/lib/config.js +340 -0
- package/lib/config.js.map +1 -0
- package/lib/index.d.ts +26 -0
- package/{src → lib}/index.js +15 -18
- package/lib/index.js.map +1 -0
- package/lib/panel.d.ts +275 -0
- package/lib/panel.js +839 -0
- package/lib/panel.js.map +1 -0
- package/lib/prompt.d.ts +58 -0
- package/{src → lib}/prompt.js +110 -109
- package/lib/prompt.js.map +1 -0
- package/lib/ptc-exemption.d.ts +10 -0
- package/lib/ptc-exemption.js +13 -0
- package/lib/ptc-exemption.js.map +1 -0
- package/{src/settings.js → lib/settings.d.ts} +5 -17
- package/lib/settings.js +47 -0
- package/lib/settings.js.map +1 -0
- package/lib/subagents.d.ts +37 -0
- package/lib/subagents.js +276 -0
- package/lib/subagents.js.map +1 -0
- package/lib/wait-subagent.d.ts +49 -0
- package/lib/wait-subagent.js +401 -0
- package/lib/wait-subagent.js.map +1 -0
- package/package.json +56 -25
- package/src/child-exit-guard.js +0 -96
- package/src/cli/claude.js +0 -166
- package/src/cli/codex.js +0 -164
- package/src/cli/jsonl.js +0 -216
- package/src/cli/version.js +0 -98
- package/src/cli-adapter.js +0 -208
- package/src/cli-sessions.js +0 -82
- package/src/client.js +0 -1553
- package/src/config.js +0 -346
- package/src/panel.js +0 -803
- package/src/ptc-exemption.js +0 -18
- package/src/subagents.js +0 -235
- package/src/wait-subagent.js +0 -378
package/README.md
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
<p align="center">
|
|
13
13
|
<a href="https://www.npmjs.com/package/@oh-my-dsh/dsh-better-subagent"><img src="https://img.shields.io/npm/v/%40oh-my-dsh%2Fdsh-better-subagent.svg" alt="npm 版本"></a>
|
|
14
14
|
<a href="LICENSE"><img alt="Apache-2.0" src="https://img.shields.io/github/license/omdsh-dev/dsh-better-subagent?color=blue"></a>
|
|
15
|
-
<a href="package.json"><img alt="DSH 0.2.
|
|
15
|
+
<a href="package.json"><img alt="DSH 0.2.3-alpha.2" src="https://img.shields.io/badge/DSH-0.2.3--alpha.2-4B32C3"></a>
|
|
16
16
|
<a href="https://github.com/omdsh-dev/dsh-better-dsh"><img alt="Part of Better DSH" src="https://img.shields.io/badge/part%20of-dsh--better--dsh-2F80B7"></a>
|
|
17
17
|
</p>
|
|
18
18
|
|
|
@@ -42,10 +42,10 @@
|
|
|
42
42
|
|
|
43
43
|
```sh
|
|
44
44
|
# 只安装这个插件
|
|
45
|
-
dsh plugin --profile <profile> add @oh-my-dsh/dsh-better-subagent@0.5.
|
|
45
|
+
dsh plugin --profile <profile> add @oh-my-dsh/dsh-better-subagent@0.5.5-alpha.1
|
|
46
46
|
|
|
47
47
|
# 或安装 Better DSH(会自动带上所有独立插件)
|
|
48
|
-
dsh plugin --profile <profile> add dsh-better-dsh@0.
|
|
48
|
+
dsh plugin --profile <profile> add dsh-better-dsh@0.11.7
|
|
49
49
|
```
|
|
50
50
|
|
|
51
51
|
> 安装 / 升级 / 换包后必须重启对应 profile;只刷新网页不够。
|
|
@@ -57,7 +57,7 @@ dsh plugin --profile <profile> add dsh-better-dsh@0.10.1
|
|
|
57
57
|
| 稳定行 id | `dsh-better-subagent` |
|
|
58
58
|
| 入口 / 工具 | `wait_subagent` · `/better-subagent/api/*` · 子代理设置页 |
|
|
59
59
|
| 设置 | `childExitGuard`、`delegation.prompt`、`tiers.*`、两个 CLI 后端、`trustedHosts` |
|
|
60
|
-
| npm 包 | `@oh-my-dsh/dsh-better-subagent@0.5.
|
|
60
|
+
| npm 包 | `@oh-my-dsh/dsh-better-subagent@0.5.5-alpha.1` |
|
|
61
61
|
| 仓库 | https://github.com/omdsh-dev/dsh-better-subagent |
|
|
62
62
|
|
|
63
63
|
## 设置
|
package/docs/DEVELOPMENT.md
CHANGED
|
@@ -4,10 +4,10 @@
|
|
|
4
4
|
|
|
5
5
|
## 1. 包形态
|
|
6
6
|
|
|
7
|
-
-
|
|
7
|
+
- 宿主源码使用严格 TypeScript(`src/index.ts`),构建为纯 ESM `lib/index.js` 与 `.d.ts`;浏览器源码 `src/client/index.ts` 经 esbuild 编译后包装为宿主加载的 `lib/client.js` closure。
|
|
8
8
|
- `package.json` 的 `dsh.bundle.patch` 指向 `cordis.patch.yml`;`dsh.client.platform = "web"`。
|
|
9
|
-
- `files` 白名单:`
|
|
10
|
-
- 依赖:运行时只直接 import `@deepseek-ai/schemastery`;其余 DSH
|
|
9
|
+
- `files` 白名单:`lib`、`docs`、`cordis.patch.yml`、`README.md`、`LICENSE`、`third-party`。测试、脚本、设计 Spec、凭据、临时 profile 都不进发布包。
|
|
10
|
+
- 依赖:运行时只直接 import `@deepseek-ai/schemastery`;其余 DSH 包是 peer 范围(`>=0.2.3-alpha.2 <0.3.0`),由宿主运行环境提供,服务全部经 `ctx` 获取。
|
|
11
11
|
- 浏览器半边只 `require('react')`,不 import 任何 DSH client 包;样式全部使用宿主主题 token(`--dsw-alias-*`),不写 DOM。
|
|
12
12
|
|
|
13
13
|
## 2. 宿主行与配置
|
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
|
|
23
23
|
- 行 `name` 必须是 scoped npm 名:Loader 把它当模块 specifier 解析,`dsh-client-modules` 还要求 manifest 的 `name` 与行完全一致才能发现 `./client`。
|
|
24
24
|
- 不允许再插入 agent preset 行;本插件不提供 preset。
|
|
25
|
-
- 行 `Config` 在 `src/config.
|
|
25
|
+
- 行 `Config` 在 `src/config.ts`,由 `src/index.ts` 重新导出。全部字段 volatile:`childExitGuard`、`delegation.prompt`、`tiers.fast/quality`、`subagents.eng/global`、`subagents.codex.*`、`subagents.claude.*`、`trustedHosts`(信任边界按请求重读活配置,保存即生效不重挂)。
|
|
26
26
|
- `delegation.prompt`(默认 `true`)只决定 `better-subagent:delegation` 提示词段是否渲染,**对所有预设生效**;`subagents.eng/global` 只管 CLI 后端路由与 CLI 目录段。两者互不影响:把 CLI 范围全关掉,委派纪律照样渲染。
|
|
27
27
|
- `normalizeConfig` 会把任意来源(volatile 引用、旧 JSON、残缺对象)规整成精确默认形状;非法值回退默认、绝不抛错。`currentConfig(ctx, fallback)` 经 `configEditor` 找**活**行配置;找不到时回退 `fallback`。
|
|
28
28
|
- **命名**:S1 Spec 的 unscoped 名 `dsh-better-subagent` 已被他人占用,现使用 scoped 包名 `@oh-my-dsh/dsh-better-subagent`;行 id 仍是 `dsh-better-subagent`,行 name 与 client closure id 必须是 scoped 包名,短键 `dsh-better-subagent#dsh-better-subagent` 只作兼容别名保留。旧 `@menghuan1918/dsh-better-subagent` 作为 legacy 键保留。
|
|
@@ -36,7 +36,7 @@
|
|
|
36
36
|
|
|
37
37
|
## 3. 装配
|
|
38
38
|
|
|
39
|
-
`src/index.
|
|
39
|
+
`src/index.ts` 的 `apply(ctx, config)` 依次调用:
|
|
40
40
|
|
|
41
41
|
| 模块 | 装配内容 | 需要的服务 |
|
|
42
42
|
|---|---|---|
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
|
|
49
49
|
所有 `ctx.inject` 都是延迟的:headless 组合缺少 `webServer` 时只有设置路由跳过,其余照常工作;缺少 CLI 所需服务时只有 CLI 桥不挂载。
|
|
50
50
|
|
|
51
|
-
## 4. CLI 桥(`src/subagents.
|
|
51
|
+
## 4. CLI 桥(`src/subagents.ts` + `src/cli-adapter.ts` + `src/cli/*`)
|
|
52
52
|
|
|
53
53
|
- 不注册第二个 spawn/fork registry;CLI 子代理仍是原生 `subagents.startActivation({provider:'spawn', childId, parent, prompt, ...})`,只是 `agentOptions.provider` 是内部 synthetic route。rc.2 的 spec 是扁平对象,返回 `{childId, name}`;工具结果只回传 `{kind:'activation', name}`。
|
|
54
54
|
- 内部 route 历史固定为 `apollo-cli-codex` / `apollo-cli-claude`;不要为新包名重命名,否则旧会话不可续接。
|
|
@@ -56,12 +56,12 @@
|
|
|
56
56
|
- `ctx.tools.guard`:内部 route 保留、禁用范围明确拒绝、fork 拒绝;
|
|
57
57
|
- `ctx.tools.execute`:`subagent` + `provider=codex|claude` 短路创建;`list_subagent_models` 合并 CLI 目录;
|
|
58
58
|
- `ctx.on('tools/result')`:未被调用方接受的 child 回收(drain + 删 KV)。
|
|
59
|
-
- 创建流程:模型/effort 白名单校验 → 父当前目录解析(`workingDirectory.ensure`)→ `resolveExecutable` 预检 → `<executable> --version` 版本预检(`src/cli/version.
|
|
59
|
+
- 创建流程:模型/effort 白名单校验 → 父当前目录解析(`workingDirectory.ensure`)→ `resolveExecutable` 预检 → `<executable> --version` 版本预检(`src/cli/version.ts`:Codex 基线 `0.162.1`,Claude 基线 `2.1.300`;无法执行/无法识别/过旧都给出点名可执行文件与安装/升级方式的可操作错误)→ 先落 KV 再 `startActivation` → 已发布 activation 在失败/取消时 `dispose()`,再删记录;预发布失败由 rc.2 manager 回滚。`ctx.cliVersionProbe` 是测试 seam;真实运行时用 `execFile`,无 shell。
|
|
60
60
|
- 每个 adapter:一轮一个子进程;`delivered` 在 spawn 前落 KV;`remoteId` 第一行事件即落盘;`parse` 失败/非零退出/缺完成标志都抛错且不自动重试;`dispose()` 等待进程句柄退出。没有 `subprocess` 服务或 spawn 未发布时回滚 `started/delivered`。
|
|
61
|
-
- 身份 KV(`src/cli-sessions.
|
|
61
|
+
- 身份 KV(`src/cli-sessions.ts`):命名空间前缀 `apollo_cli_` + `sha256(profile.dir)[:16]`,version 1,`sessions` 表,`per-record`。**包名变化不重命名/复制/清空**。
|
|
62
62
|
- 权限/模型/effort 与父子归属在启动前失败;缺 CLI 或版本不兼容给可操作诊断,不回退到另一后端。
|
|
63
63
|
|
|
64
|
-
## 5. wait_subagent 的跨回合判定(`src/wait-subagent.
|
|
64
|
+
## 5. wait_subagent 的跨回合判定(`src/wait-subagent.ts`)
|
|
65
65
|
|
|
66
66
|
旧实现的缺陷:`settled` 只按 childId 缓存 `subagent/end`,当同一 child 被续接(新 activation 或 resident 新回合)时会把旧 end 当成本轮完成。
|
|
67
67
|
|
|
@@ -84,7 +84,7 @@
|
|
|
84
84
|
|
|
85
85
|
回归测试:`tests/wait-subagent.test.mjs` 构造「旧 end → 新 start + 排队 idle → running → 新 end」与「同一 run 内 turn 结束后又有 splice」;另通过真实 `installWaitTool` 注册 seam 的 deferred `observeSession`,覆盖读取挂起期间的新 activation / 无新 start 的 resident running + claim,以及 start/end 换代后 idle 的旧日志快照。
|
|
86
86
|
|
|
87
|
-
## 6. 子代理退出守卫(`src/child-exit-guard.
|
|
87
|
+
## 6. 子代理退出守卫(`src/child-exit-guard.ts`)
|
|
88
88
|
|
|
89
89
|
- 只由 volatile `childExitGuard`(默认 false)控制;
|
|
90
90
|
- 只听 `agent/turn-stopping`,只收集 `subagents.listDescendants(agent.id)` 中 `depth === 1` 且 **live status === running** 的直接子代理;
|
|
@@ -92,7 +92,7 @@
|
|
|
92
92
|
- 查询/注入异常 → 告警并放行(fail open);`payload.signal.aborted` 直接返回;
|
|
93
93
|
- 不看 jobs、不 import Apollo、不扩大权限。
|
|
94
94
|
|
|
95
|
-
## 7. 提示词(`src/prompt.
|
|
95
|
+
## 7. 提示词(`src/prompt.ts`)
|
|
96
96
|
|
|
97
97
|
在 `agent/created` 时向该 Agent 的 `agent.ctx.systemPrompt` 注册(effect 随 Agent 释放):
|
|
98
98
|
|
|
@@ -104,7 +104,7 @@
|
|
|
104
104
|
|
|
105
105
|
preset 解析优先 `agentPresets.composedPreset(agent.ctx)`,回退 `sessionProjections`/session header;文本是函数,按活配置每次请求渲染。Apollo 的 PRINCIPLES、工作流 skills、job/general guard 文本不在此处。
|
|
106
106
|
|
|
107
|
-
## 8. 只读 API(`src/panel.
|
|
107
|
+
## 8. 只读 API(`src/panel.ts` + `src/settings.ts`)
|
|
108
108
|
|
|
109
109
|
- `registerCapabilitiesRoute` 一次注册两个 prefix:`/better-subagent/api` 与 `/apollo/api`,共享同一 handler;`settings.js` 只注册一次。
|
|
110
110
|
- 路由:`/capabilities`、`/models?cli=codex|claude`、`/routes`;GET only;未知路径 404;非 GET 405;不读请求体。
|
|
@@ -112,7 +112,7 @@ preset 解析优先 `agentPresets.composedPreset(agent.ctx)`,回退 `sessionPr
|
|
|
112
112
|
- 能力探针:30s 有界缓存 + 并发去重。发现:Codex `codex debug models`(失败回退 `--bundled`);Claude 读 `ANTHROPIC_BASE_URL`/凭据并请求 `/v1/models`。发现只在显式调用时触发(不做后台缓存/重探);响应不回凭据,只回可执行文件路径/版本、profile 名、模型 id/effort。
|
|
113
113
|
- `trustedHosts` 只约束本插件的读接口,不改变宿主设置镜像的可写性。
|
|
114
114
|
|
|
115
|
-
## 9. 客户端设置页(`src/client.
|
|
115
|
+
## 9. 客户端设置页(`src/client/index.ts`)
|
|
116
116
|
|
|
117
117
|
- `window.__ModuleLoader__.load({id:'@oh-my-dsh/dsh-better-subagent', factory})`;只 require React。
|
|
118
118
|
- 使用 `form.state`(`{status, value, revision, writable, mode}`)与 `form.mutate(ops, revision)`;只在保存时提交与宿主快照的差异 `set` ops。
|
|
@@ -127,7 +127,11 @@ preset 解析优先 `agentPresets.composedPreset(agent.ctx)`,回退 `sessionPr
|
|
|
127
127
|
```sh
|
|
128
128
|
cd /path/to/dsh-better-subagent
|
|
129
129
|
npm install
|
|
130
|
-
npm
|
|
130
|
+
npm run typecheck
|
|
131
|
+
npm test # pretest 自动构建 lib/;全部测试加载生成的 lib/*.js
|
|
132
|
+
|
|
133
|
+
# 仅构建;smoke 暂存并加载 lib/,直接运行前需先完成构建
|
|
134
|
+
npm run build
|
|
131
135
|
|
|
132
136
|
# 真实宿主(headless,无需 CLI 凭据):原生 subagent create→wait→continue→wait→interrupt→wait
|
|
133
137
|
DSH_PACKAGE_ROOT="/path/to/dependencies/dsh/node_modules/@deepseek-ai/dsh" npm run smoke
|
|
@@ -179,6 +183,6 @@ CLI smoke 会把 DSH profile 放在临时目录,但不会改 Claude/Codex 的
|
|
|
179
183
|
|
|
180
184
|
## 12. 发布
|
|
181
185
|
|
|
182
|
-
- `.github/workflows/release.yml`:GitHub Release `published` 触发;校验 tag `v<version>` 与 `package.json` 版本一致;`npm ci` → `npm test` → `npm publish --provenance --access public`。
|
|
186
|
+
- `.github/workflows/release.yml`:GitHub Release `published` 触发;校验 tag `v<version>` 与 `package.json` 版本一致;`npm ci` → `npm test` → `npm publish --provenance --access public --tag alpha`。
|
|
183
187
|
- 使用 npm trusted publishing(OIDC),仓库与 workflow 中不保存 npm token;npmjs.com 的 trusted publisher 需指向本仓库与 `release.yml`。
|
|
184
188
|
- 发布前检查:`npm pack --dry-run --json` 的文件列表只含白名单(无 tests/scripts/docs 之外的内部 Spec、无 `.env`/`.npmrc`/凭据/临时 profile)。
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Child exit guard — host-plane plugin that intercepts turn end while the
|
|
3
|
+
* Agent still has RUNNING direct children.
|
|
4
|
+
*
|
|
5
|
+
* Scope is deliberately narrow:
|
|
6
|
+
* - gated by the volatile `childExitGuard` row setting (default false);
|
|
7
|
+
* - only direct children whose live Agent status is `running` are intercepted;
|
|
8
|
+
* background bash jobs and Apollo's general guard remain Apollo's business;
|
|
9
|
+
* - the only action is a concise `agent.steer()` notice. Query/inject failures
|
|
10
|
+
* fail open (warn and let the turn end) so a broken query cannot wedge a
|
|
11
|
+
* session; the user interrupt signal always passes through.
|
|
12
|
+
*
|
|
13
|
+
* The notice wording is the single runtime source for this plugin's child-guard
|
|
14
|
+
* prompt contract as well (see `src/prompt.js`).
|
|
15
|
+
*/
|
|
16
|
+
import type { Context } from '@deepseek-ai/cordis';
|
|
17
|
+
import type { Agent } from '@deepseek-ai/dsh-agent';
|
|
18
|
+
import type { UserMessage } from '@deepseek-ai/dsh-session';
|
|
19
|
+
import type { SubagentDescendantListEntry } from '@deepseek-ai/dsh-subagent';
|
|
20
|
+
export declare const name = "better-subagent-child-exit-guard";
|
|
21
|
+
export declare const inject: string[];
|
|
22
|
+
type GuardChild = {
|
|
23
|
+
id: string;
|
|
24
|
+
label?: string;
|
|
25
|
+
meta?: {
|
|
26
|
+
label?: string;
|
|
27
|
+
};
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* Construct the steer notice (model-visible, enters the session log).
|
|
31
|
+
* @param children - running direct-child listChildren entries.
|
|
32
|
+
* @returns one user-role plugin notice message.
|
|
33
|
+
*/
|
|
34
|
+
export declare function buildChildGuardMessage(children: readonly GuardChild[]): UserMessage;
|
|
35
|
+
/**
|
|
36
|
+
* Collect this Agent's running direct children.
|
|
37
|
+
* @param ctx - runtime context (subagents/agents injected).
|
|
38
|
+
* @param agent - the Agent whose turn is stopping.
|
|
39
|
+
* @returns running direct-child entries; query failures propagate to the caller.
|
|
40
|
+
*/
|
|
41
|
+
export declare function collectRunningChildren(ctx: Context, agent: Agent): Promise<SubagentDescendantListEntry[]>;
|
|
42
|
+
/** Install the turn-stopping listener on a context that already has the services. */
|
|
43
|
+
export declare function installChildExitGuard(ctx: Context, config: unknown): () => boolean;
|
|
44
|
+
export declare function mountChildExitGuard(ctx: Context, config: unknown): void;
|
|
45
|
+
export {};
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Child exit guard — host-plane plugin that intercepts turn end while the
|
|
3
|
+
* Agent still has RUNNING direct children.
|
|
4
|
+
*
|
|
5
|
+
* Scope is deliberately narrow:
|
|
6
|
+
* - gated by the volatile `childExitGuard` row setting (default false);
|
|
7
|
+
* - only direct children whose live Agent status is `running` are intercepted;
|
|
8
|
+
* background bash jobs and Apollo's general guard remain Apollo's business;
|
|
9
|
+
* - the only action is a concise `agent.steer()` notice. Query/inject failures
|
|
10
|
+
* fail open (warn and let the turn end) so a broken query cannot wedge a
|
|
11
|
+
* session; the user interrupt signal always passes through.
|
|
12
|
+
*
|
|
13
|
+
* The notice wording is the single runtime source for this plugin's child-guard
|
|
14
|
+
* prompt contract as well (see `src/prompt.js`).
|
|
15
|
+
*/
|
|
16
|
+
import { currentConfig } from './config.js';
|
|
17
|
+
export const name = 'better-subagent-child-exit-guard';
|
|
18
|
+
export const inject = ['subagents', 'agents'];
|
|
19
|
+
/** Render one running-child line. */
|
|
20
|
+
function lineOf(child) {
|
|
21
|
+
// 0.1.1-rc.2 entries are meta:{mode,label}; 0.1.2+ promote them to top level.
|
|
22
|
+
const label = child.label ?? child.meta?.label;
|
|
23
|
+
return ` - subagent ${child.id}${label === undefined || label === '' ? '' : ` (${label})`}`;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Construct the steer notice (model-visible, enters the session log).
|
|
27
|
+
* @param children - running direct-child listChildren entries.
|
|
28
|
+
* @returns one user-role plugin notice message.
|
|
29
|
+
*/
|
|
30
|
+
export function buildChildGuardMessage(children) {
|
|
31
|
+
const text = [
|
|
32
|
+
'Direct subagent work is still running, so the turn cannot end yet:',
|
|
33
|
+
...children.map(lineOf),
|
|
34
|
+
'',
|
|
35
|
+
'Wait for running subagents with wait_subagent (use send_message only to give one new information or a correction). '
|
|
36
|
+
+ 'Finish only after every running child is handled, or wait for the user to interrupt.',
|
|
37
|
+
].join('\n');
|
|
38
|
+
return {
|
|
39
|
+
role: 'user',
|
|
40
|
+
content: [{ type: 'text', text }],
|
|
41
|
+
// Producer-owned source kind: native session format v4 refuses the retired
|
|
42
|
+
// `{kind:'plugin', plugin}` wrapper shape for newly appended messages.
|
|
43
|
+
source: {
|
|
44
|
+
kind: name,
|
|
45
|
+
form: 'notice',
|
|
46
|
+
summary: `运行中的子代理阻止回合结束(${children.length})`,
|
|
47
|
+
},
|
|
48
|
+
id: crypto.randomUUID(),
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Collect this Agent's running direct children.
|
|
53
|
+
* @param ctx - runtime context (subagents/agents injected).
|
|
54
|
+
* @param agent - the Agent whose turn is stopping.
|
|
55
|
+
* @returns running direct-child entries; query failures propagate to the caller.
|
|
56
|
+
*/
|
|
57
|
+
export async function collectRunningChildren(ctx, agent) {
|
|
58
|
+
const running = [];
|
|
59
|
+
// rc.2 removed listChildren; depth-one descendants are this Agent's direct
|
|
60
|
+
// children in the same stable catalog order.
|
|
61
|
+
for (const entry of (await ctx.subagents.listDescendants(agent.id)).filter((candidate) => candidate.depth === 1)) {
|
|
62
|
+
if (ctx.agents.get(entry.id)?.status === 'running')
|
|
63
|
+
running.push(entry);
|
|
64
|
+
}
|
|
65
|
+
return running;
|
|
66
|
+
}
|
|
67
|
+
/** Install the turn-stopping listener on a context that already has the services. */
|
|
68
|
+
export function installChildExitGuard(ctx, config) {
|
|
69
|
+
return ctx.on('agent/turn-stopping', async (payload) => {
|
|
70
|
+
const agent = payload?.agent;
|
|
71
|
+
if (agent === undefined || payload?.signal?.aborted)
|
|
72
|
+
return;
|
|
73
|
+
try {
|
|
74
|
+
if (!currentConfig(ctx, config).childExitGuard)
|
|
75
|
+
return;
|
|
76
|
+
const children = await collectRunningChildren(ctx, agent);
|
|
77
|
+
if (children.length === 0)
|
|
78
|
+
return;
|
|
79
|
+
if (payload.signal?.aborted)
|
|
80
|
+
return;
|
|
81
|
+
agent.steer(buildChildGuardMessage(children));
|
|
82
|
+
}
|
|
83
|
+
catch (error) {
|
|
84
|
+
// Fail open: a broken query or injection must release this turn.
|
|
85
|
+
ctx.logger?.warn?.(`better-subagent child exit guard skipped: ${error instanceof Error ? error.message : String(error)}`);
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
export function mountChildExitGuard(ctx, config) {
|
|
90
|
+
ctx.inject(inject, (runtime) => {
|
|
91
|
+
const dispose = installChildExitGuard(runtime, config);
|
|
92
|
+
if (typeof runtime.effect === 'function')
|
|
93
|
+
runtime.effect(() => dispose, 'better-subagent: child exit guard');
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
//# sourceMappingURL=child-exit-guard.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"child-exit-guard.js","sourceRoot":"","sources":["../src/child-exit-guard.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAOH,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAE3C,MAAM,CAAC,MAAM,IAAI,GAAG,kCAAkC,CAAA;AAEtD,MAAM,CAAC,MAAM,MAAM,GAAG,CAAC,WAAW,EAAE,QAAQ,CAAC,CAAA;AAI7C,qCAAqC;AACrC,SAAS,MAAM,CAAC,KAAiB;IAC/B,8EAA8E;IAC9E,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,IAAI,KAAK,CAAC,IAAI,EAAE,KAAK,CAAA;IAC9C,OAAO,gBAAgB,KAAK,CAAC,EAAE,GAAG,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,KAAK,GAAG,EAAE,CAAA;AAC9F,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,s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EAAE,KAAK,CAAA;QAC5B,IAAI,KAAK,KAAK,SAAS,IAAI,OAAO,EAAE,MAAM,EAAE,OAAO;YAAE,OAAM;QAC3D,IAAI,CAAC;YACH,IAAI,CAAC,aAAa,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC,cAAc;gBAAE,OAAM;YACtD,MAAM,QAAQ,GAAG,MAAM,sBAAsB,CAAC,GAAG,EAAE,KAAK,CAAC,CAAA;YACzD,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC;gBAAE,OAAM;YACjC,IAAI,OAAO,CAAC,MAAM,EAAE,OAAO;gBAAE,OAAM;YACnC,KAAK,CAAC,KAAK,CAAC,sBAAsB,CAAC,QAAQ,CAAC,CAAC,CAAA;QAC/C,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,iEAAiE;YACjE,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,6CAA6C,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAA;QAC3H,CAAC;IACH,CAAC,CAAC,CAAA;AACJ,CAAC;AAED,MAAM,UAAU,mBAAmB,CAAC,GAAY,EAAE,MAAe;IAC/D,GAAG,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,OAAO,EAAE,EAAE;QAC7B,MAAM,OAAO,GAAG,qBAAqB,CAAC,OAAO,EAAE,MAAM,CAAC,CAAA;QACtD,IAAI,OAAO,OAAO,CAAC,MAAM,KAAK,UAAU;YAAE,OAAO,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC,OAAO,EAAE,mCAAmC,CAAC,CAAA;IAC9G,CAAC,CAAC,CAAA;AACJ,CAAC","sourcesContent":["/**\n * Child exit guard — host-plane plugin that intercepts turn end while the\n * Agent still has RUNNING direct children.\n *\n * Scope is deliberately narrow:\n * - gated by the volatile `childExitGuard` row setting (default false);\n * - only direct children whose live Agent status is `running` are intercepted;\n * background bash jobs and Apollo's general guard remain Apollo's business;\n * - the only action is a concise `agent.steer()` notice. Query/inject failures\n * fail open (warn and let the turn end) so a broken query cannot wedge a\n * session; the user interrupt signal always passes through.\n *\n * The notice wording is the single runtime source for this plugin's child-guard\n * prompt contract as well (see `src/prompt.js`).\n */\n\nimport type { Context } from '@deepseek-ai/cordis'\nimport type { Agent } from '@deepseek-ai/dsh-agent'\nimport type { UserMessage } from '@deepseek-ai/dsh-session'\nimport type { SubagentDescendantListEntry } from '@deepseek-ai/dsh-subagent'\n\nimport { currentConfig } from './config.js'\n\nexport const name = 'better-subagent-child-exit-guard'\n\nexport const inject = ['subagents', 'agents']\n\ntype GuardChild = { id: string; label?: string; meta?: { label?: string } }\n\n/** Render one running-child line. */\nfunction lineOf(child: GuardChild) {\n // 0.1.1-rc.2 entries are meta:{mode,label}; 0.1.2+ promote them to top level.\n const label = child.label ?? child.meta?.label\n return ` - subagent ${child.id}${label === undefined || label === '' ? '' : ` (${label})`}`\n}\n\n/**\n * Construct the steer notice (model-visible, enters the session log).\n * @param children - running direct-child listChildren entries.\n * @returns one user-role plugin notice message.\n */\nexport function buildChildGuardMessage(children: readonly GuardChild[]): UserMessage {\n const text = [\n 'Direct subagent work is still running, so the turn cannot end yet:',\n ...children.map(lineOf),\n '',\n 'Wait for running subagents with wait_subagent (use send_message only to give one new information or a correction). '\n + 'Finish only after every running child is handled, or wait for the user to interrupt.',\n ].join('\\n')\n return {\n role: 'user',\n content: [{ type: 'text', text }],\n // Producer-owned source kind: native session format v4 refuses the retired\n // `{kind:'plugin', plugin}` wrapper shape for newly appended messages.\n source: {\n kind: name,\n form: 'notice',\n summary: `运行中的子代理阻止回合结束(${children.length})`,\n },\n id: crypto.randomUUID() as UserMessage['id'],\n }\n}\n\n/**\n * Collect this Agent's running direct children.\n * @param ctx - runtime context (subagents/agents injected).\n * @param agent - the Agent whose turn is stopping.\n * @returns running direct-child entries; query failures propagate to the caller.\n */\nexport async function collectRunningChildren(ctx: Context, agent: Agent) {\n const running: SubagentDescendantListEntry[] = []\n // rc.2 removed listChildren; depth-one descendants are this Agent's direct\n // children in the same stable catalog order.\n for (const entry of (await ctx.subagents.listDescendants(agent.id)).filter((candidate) => candidate.depth === 1)) {\n if (ctx.agents.get(entry.id)?.status === 'running') running.push(entry)\n }\n return running\n}\n\n/** Install the turn-stopping listener on a context that already has the services. */\nexport function installChildExitGuard(ctx: Context, config: unknown) {\n return ctx.on('agent/turn-stopping', async (payload) => {\n const agent = payload?.agent\n if (agent === undefined || payload?.signal?.aborted) return\n try {\n if (!currentConfig(ctx, config).childExitGuard) return\n const children = await collectRunningChildren(ctx, agent)\n if (children.length === 0) return\n if (payload.signal?.aborted) return\n agent.steer(buildChildGuardMessage(children))\n } catch (error) {\n // Fail open: a broken query or injection must release this turn.\n ctx.logger?.warn?.(`better-subagent child exit guard skipped: ${error instanceof Error ? error.message : String(error)}`)\n }\n })\n}\n\nexport function mountChildExitGuard(ctx: Context, config: unknown) {\n ctx.inject(inject, (runtime) => {\n const dispose = installChildExitGuard(runtime, config)\n if (typeof runtime.effect === 'function') runtime.effect(() => dispose, 'better-subagent: child exit guard')\n })\n}\n"]}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Claude Code CLI 适配:纯命令构造 + `--print --output-format stream-json` 事件流解析。
|
|
3
|
+
* 只产出 argv 与 stdin 正文并翻译事件;spawn/管道/stderr/中断由父 adapter 的
|
|
4
|
+
* `ctx.subprocess` 掌握(stdin 取 `{data: input}`)。不 import 任何 DSH 包。
|
|
5
|
+
*
|
|
6
|
+
* 实测依据(Claude Code 2.1.300,新建 + `--resume` 各一轮真实跑通):
|
|
7
|
+
* - `--print` 不给位置参数 prompt 时正文从 stdin 读,所以 argv 里没有 prompt;
|
|
8
|
+
* - `stream-json` 必须配 `--verbose` 才是完整事件流;
|
|
9
|
+
* - `--permission-prompts none` = 没人回答权限提问、会被提问的一律自动拒绝,
|
|
10
|
+
* 正是无人值守管道要的语义(`--permission-mode` 仍决定其余判定);
|
|
11
|
+
* - 续接用 `--resume <SESSION_ID>`;**不传** `--no-session-persistence`,否则会话
|
|
12
|
+
* 不落盘、下一轮无法续接;
|
|
13
|
+
* - claude **没有** cwd 选项(`--add-dir` 只是追加可写目录),工作目录由进程 cwd
|
|
14
|
+
* 决定,故本模块接受并忽略 `cwd`,交给父 adapter 的 spawn `cwd`;`profile` 是
|
|
15
|
+
* codex 专属概念,同样忽略。
|
|
16
|
+
*
|
|
17
|
+
* 事件语义:
|
|
18
|
+
* - `system`(hook_started / hook_response / init)都带 `session_id`,且前两者出现在
|
|
19
|
+
* `init` **之前**——故 remoteId 在「第一个带 session_id 的 system 事件」就回报;
|
|
20
|
+
* - `assistant` → `message.content[]` 里 `type === 'text'` 的块拼成正文;`tool_use` /
|
|
21
|
+
* `thinking` 块**绝不**当作正文;带 `parent_tool_use_id` 的是子代理消息,也不计入;
|
|
22
|
+
* - `result` → 唯一权威收尾:`subtype === 'success' && is_error !== true` 才算成功;
|
|
23
|
+
* `result` 字段是最终答复文本(覆盖累积值),`usage` 是整轮用量。
|
|
24
|
+
*/
|
|
25
|
+
import type { CliCommandSpec, CliParser } from './types.js';
|
|
26
|
+
/**
|
|
27
|
+
* 构造一轮 `claude --print` 调用。
|
|
28
|
+
*
|
|
29
|
+
* @param {object} spec
|
|
30
|
+
* @param {string} [spec.executable='claude'] - 可执行名或绝对路径。
|
|
31
|
+
* @param {string} [spec.cwd] - 接受但忽略:claude 无 cwd 选项,请用 spawn 的 cwd。
|
|
32
|
+
* @param {string} [spec.model] - `--model`,别名(sonnet/opus…)或全名。
|
|
33
|
+
* @param {string} [spec.effort] - `--effort`,实测取值 low/medium/high/xhigh/max。
|
|
34
|
+
* @param {string} [spec.profile] - 接受但忽略:codex 专属概念。
|
|
35
|
+
* @param {string} [spec.permissionMode] - `--permission-mode`。
|
|
36
|
+
* @param {string} [spec.remoteId] - 已有 session id 时走 `--resume <id>`。
|
|
37
|
+
* @param {string} spec.prompt - 正文,经 stdin 送入。
|
|
38
|
+
* @returns {{argv: string[], input: string}}
|
|
39
|
+
*/
|
|
40
|
+
export declare function buildCommand({ executable, model, effort, permissionMode, remoteId, prompt }?: CliCommandSpec): {
|
|
41
|
+
argv: string[];
|
|
42
|
+
input: string;
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* 创建一个有状态的 claude 事件解析器(一轮子进程一个)。
|
|
46
|
+
*
|
|
47
|
+
* @returns {{push: (event: unknown) => ({remoteId?: string, text?: string, usage?: object, completed?: boolean, error?: string}|undefined), finish: () => {text: string, remoteId?: string, usage?: object}}}
|
|
48
|
+
*/
|
|
49
|
+
export declare function createParser(): CliParser;
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Claude Code CLI 适配:纯命令构造 + `--print --output-format stream-json` 事件流解析。
|
|
3
|
+
* 只产出 argv 与 stdin 正文并翻译事件;spawn/管道/stderr/中断由父 adapter 的
|
|
4
|
+
* `ctx.subprocess` 掌握(stdin 取 `{data: input}`)。不 import 任何 DSH 包。
|
|
5
|
+
*
|
|
6
|
+
* 实测依据(Claude Code 2.1.300,新建 + `--resume` 各一轮真实跑通):
|
|
7
|
+
* - `--print` 不给位置参数 prompt 时正文从 stdin 读,所以 argv 里没有 prompt;
|
|
8
|
+
* - `stream-json` 必须配 `--verbose` 才是完整事件流;
|
|
9
|
+
* - `--permission-prompts none` = 没人回答权限提问、会被提问的一律自动拒绝,
|
|
10
|
+
* 正是无人值守管道要的语义(`--permission-mode` 仍决定其余判定);
|
|
11
|
+
* - 续接用 `--resume <SESSION_ID>`;**不传** `--no-session-persistence`,否则会话
|
|
12
|
+
* 不落盘、下一轮无法续接;
|
|
13
|
+
* - claude **没有** cwd 选项(`--add-dir` 只是追加可写目录),工作目录由进程 cwd
|
|
14
|
+
* 决定,故本模块接受并忽略 `cwd`,交给父 adapter 的 spawn `cwd`;`profile` 是
|
|
15
|
+
* codex 专属概念,同样忽略。
|
|
16
|
+
*
|
|
17
|
+
* 事件语义:
|
|
18
|
+
* - `system`(hook_started / hook_response / init)都带 `session_id`,且前两者出现在
|
|
19
|
+
* `init` **之前**——故 remoteId 在「第一个带 session_id 的 system 事件」就回报;
|
|
20
|
+
* - `assistant` → `message.content[]` 里 `type === 'text'` 的块拼成正文;`tool_use` /
|
|
21
|
+
* `thinking` 块**绝不**当作正文;带 `parent_tool_use_id` 的是子代理消息,也不计入;
|
|
22
|
+
* - `result` → 唯一权威收尾:`subtype === 'success' && is_error !== true` 才算成功;
|
|
23
|
+
* `result` 字段是最终答复文本(覆盖累积值),`usage` 是整轮用量。
|
|
24
|
+
*/
|
|
25
|
+
import { normalizeUsage, requireEnum, requireEffort, requireId, requirePrompt, requireText, sanitizeError } from './jsonl.js';
|
|
26
|
+
/** `claude --permission-mode` 的实测取值(`claude --help`)。 */
|
|
27
|
+
const PERMISSION_MODES = ['acceptEdits', 'auto', 'bypassPermissions', 'manual', 'dontAsk', 'plan'];
|
|
28
|
+
/**
|
|
29
|
+
* 构造一轮 `claude --print` 调用。
|
|
30
|
+
*
|
|
31
|
+
* @param {object} spec
|
|
32
|
+
* @param {string} [spec.executable='claude'] - 可执行名或绝对路径。
|
|
33
|
+
* @param {string} [spec.cwd] - 接受但忽略:claude 无 cwd 选项,请用 spawn 的 cwd。
|
|
34
|
+
* @param {string} [spec.model] - `--model`,别名(sonnet/opus…)或全名。
|
|
35
|
+
* @param {string} [spec.effort] - `--effort`,实测取值 low/medium/high/xhigh/max。
|
|
36
|
+
* @param {string} [spec.profile] - 接受但忽略:codex 专属概念。
|
|
37
|
+
* @param {string} [spec.permissionMode] - `--permission-mode`。
|
|
38
|
+
* @param {string} [spec.remoteId] - 已有 session id 时走 `--resume <id>`。
|
|
39
|
+
* @param {string} spec.prompt - 正文,经 stdin 送入。
|
|
40
|
+
* @returns {{argv: string[], input: string}}
|
|
41
|
+
*/
|
|
42
|
+
export function buildCommand({ executable = 'claude', model, effort, permissionMode, remoteId, prompt } = {}) {
|
|
43
|
+
const argv = [requireText(executable, 'executable'), '--print', '--output-format', 'stream-json', '--verbose'];
|
|
44
|
+
if (model !== undefined)
|
|
45
|
+
argv.push('--model', requireText(model, 'model'));
|
|
46
|
+
if (effort !== undefined)
|
|
47
|
+
argv.push('--effort', requireEffort(effort));
|
|
48
|
+
if (permissionMode !== undefined)
|
|
49
|
+
argv.push('--permission-mode', requireEnum(permissionMode, PERMISSION_MODES, 'permissionMode'));
|
|
50
|
+
// 无人值守:任何权限提问都自动拒绝,而不是挂起等一个永远不会来的回答。
|
|
51
|
+
argv.push('--permission-prompts', 'none');
|
|
52
|
+
if (remoteId !== undefined)
|
|
53
|
+
argv.push('--resume', requireId(remoteId, 'remoteId'));
|
|
54
|
+
// 正文走 stdin(`--print` 无位置参数时读 stdin),argv 里不出现 prompt。
|
|
55
|
+
return { argv, input: requirePrompt(prompt) };
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* 创建一个有状态的 claude 事件解析器(一轮子进程一个)。
|
|
59
|
+
*
|
|
60
|
+
* @returns {{push: (event: unknown) => ({remoteId?: string, text?: string, usage?: object, completed?: boolean, error?: string}|undefined), finish: () => {text: string, remoteId?: string, usage?: object}}}
|
|
61
|
+
*/
|
|
62
|
+
export function createParser() {
|
|
63
|
+
let remoteId;
|
|
64
|
+
let text = '';
|
|
65
|
+
let usage;
|
|
66
|
+
let completed = false;
|
|
67
|
+
let failure;
|
|
68
|
+
/** 失败时优先用 provider 给的错误正文,否则退化成 subtype/api_error_status。 */
|
|
69
|
+
function describeResultFailure(event) {
|
|
70
|
+
const label = typeof event.subtype === 'string' && event.subtype !== '' ? event.subtype : 'error';
|
|
71
|
+
const detail = typeof event.result === 'string' && event.result !== '' ? event.result
|
|
72
|
+
: Array.isArray(event.errors) ? event.errors.filter((item) => typeof item === 'string').slice(0, 3).join('; ') : '';
|
|
73
|
+
const status = event.api_error_status === undefined ? '' : ` (api_error_status=${event.api_error_status})`;
|
|
74
|
+
return sanitizeError(detail === '' ? `claude result ${label}${status}` : `claude result ${label}${status}: ${detail}`);
|
|
75
|
+
}
|
|
76
|
+
return {
|
|
77
|
+
/**
|
|
78
|
+
* 投喂一个已解析的事件。
|
|
79
|
+
* @param {unknown} event - `readJsonLines` 产出的单个事件。
|
|
80
|
+
* @returns {{remoteId?: string, text?: string, usage?: object, completed?: boolean, error?: string}|undefined}
|
|
81
|
+
* 本次事件产生的动作;无动作返回 undefined。
|
|
82
|
+
* `error` 是**信息性**的:只有 `finish()` 抛错才代表这一轮失败。
|
|
83
|
+
*/
|
|
84
|
+
push(value) {
|
|
85
|
+
const event = value;
|
|
86
|
+
if (event === null || typeof event !== 'object')
|
|
87
|
+
return undefined;
|
|
88
|
+
switch (event.type) {
|
|
89
|
+
case 'system': {
|
|
90
|
+
if (typeof event.session_id !== 'string' || event.session_id === '')
|
|
91
|
+
return undefined;
|
|
92
|
+
// 只回报一次;实测 hook_started 早于 init,因此这里通常是最早的时机。
|
|
93
|
+
if (remoteId !== undefined)
|
|
94
|
+
return undefined;
|
|
95
|
+
remoteId = event.session_id;
|
|
96
|
+
return { remoteId };
|
|
97
|
+
}
|
|
98
|
+
case 'assistant': {
|
|
99
|
+
// 子代理(Task 工具)的消息带 parent_tool_use_id,不能混进主答复。
|
|
100
|
+
if (typeof event.parent_tool_use_id === 'string' && event.parent_tool_use_id !== '')
|
|
101
|
+
return undefined;
|
|
102
|
+
const message = event.message;
|
|
103
|
+
if (message === null || typeof message !== 'object' || !Array.isArray(message.content))
|
|
104
|
+
return undefined;
|
|
105
|
+
const chunk = message.content
|
|
106
|
+
.filter((block) => block !== null && typeof block === 'object' && block.type === 'text' && typeof block.text === 'string')
|
|
107
|
+
.map((block) => block.text)
|
|
108
|
+
.join('');
|
|
109
|
+
if (chunk === '')
|
|
110
|
+
return undefined;
|
|
111
|
+
// 覆盖式:一条 assistant 事件就是一条完整消息,最后一条才是最终答复。
|
|
112
|
+
text = chunk;
|
|
113
|
+
return { text };
|
|
114
|
+
}
|
|
115
|
+
case 'result': {
|
|
116
|
+
const mapped = mapClaudeUsage(event.usage);
|
|
117
|
+
if (mapped !== undefined)
|
|
118
|
+
usage = mapped;
|
|
119
|
+
const succeeded = event.subtype === 'success' && event.is_error !== true;
|
|
120
|
+
if (succeeded) {
|
|
121
|
+
completed = true;
|
|
122
|
+
if (typeof event.result === 'string' && event.result !== '')
|
|
123
|
+
text = event.result;
|
|
124
|
+
}
|
|
125
|
+
else {
|
|
126
|
+
failure ??= describeResultFailure(event);
|
|
127
|
+
}
|
|
128
|
+
return {
|
|
129
|
+
...(mapped === undefined ? {} : { usage: mapped }),
|
|
130
|
+
...(succeeded ? { completed: true } : { error: failure }),
|
|
131
|
+
...(succeeded && typeof event.result === 'string' && event.result !== '' ? { text: event.result } : {}),
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
default:
|
|
135
|
+
// user(工具结果)/ stream_event / 未来新增事件:无语义动作。
|
|
136
|
+
return undefined;
|
|
137
|
+
}
|
|
138
|
+
},
|
|
139
|
+
/**
|
|
140
|
+
* 收流。失败或缺少 `result` 都抛错——「流结束了」不等于「回合成功了」。
|
|
141
|
+
* 幂等:可重复调用,不改变状态。
|
|
142
|
+
* @returns {{text: string, remoteId?: string, usage?: object}}
|
|
143
|
+
*/
|
|
144
|
+
finish() {
|
|
145
|
+
if (failure !== undefined)
|
|
146
|
+
throw new Error(`claude 回合失败:${failure}`);
|
|
147
|
+
if (!completed)
|
|
148
|
+
throw new Error('claude 流在收到成功的 result 事件之前结束');
|
|
149
|
+
return {
|
|
150
|
+
text,
|
|
151
|
+
...(remoteId === undefined ? {} : { remoteId }),
|
|
152
|
+
...(usage === undefined ? {} : { usage }),
|
|
153
|
+
};
|
|
154
|
+
},
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* 把 claude 的整轮用量映射成 DSH TokenUsage。
|
|
159
|
+
*
|
|
160
|
+
* Anthropic 的 `input_tokens` 本来就**不含**缓存(另给 `cache_read_input_tokens` /
|
|
161
|
+
* `cache_creation_input_tokens`),与 DSH 约定一致,无需扣减;
|
|
162
|
+
* `output_tokens_details.thinking_tokens` 映射为 reasoning。
|
|
163
|
+
*/
|
|
164
|
+
function mapClaudeUsage(value) {
|
|
165
|
+
const raw = value;
|
|
166
|
+
if (raw === null || typeof raw !== 'object')
|
|
167
|
+
return undefined;
|
|
168
|
+
const details = raw.output_tokens_details;
|
|
169
|
+
return normalizeUsage({
|
|
170
|
+
inputTokens: raw.input_tokens,
|
|
171
|
+
outputTokens: raw.output_tokens,
|
|
172
|
+
cacheReadTokens: raw.cache_read_input_tokens,
|
|
173
|
+
cacheWriteTokens: raw.cache_creation_input_tokens,
|
|
174
|
+
reasoningTokens: details !== null && typeof details === 'object' ? details.thinking_tokens : undefined,
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
//# sourceMappingURL=claude.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"claude.js","sourceRoot":"","sources":["../../src/cli/claude.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,OAAO,EAAE,cAAc,EAAE,WAAW,EAAE,aAAa,EAAE,SAAS,EAAE,aAAa,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAI7H,yDAAyD;AACzD,MAAM,gBAAgB,GAAG,CAAC,aAAa,EAAE,MAAM,EAAE,mBAAmB,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,CAAC,CAAA;AAElG;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,YAAY,CAAC,EAAE,UAAU,GAAG,QAAQ,EAAE,KAAK,EAAE,MAAM,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,KAAqB,EAAE;IAC1H,MAAM,IAAI,GAAG,CAAC,WAAW,CAAC,UAAU,EAAE,YAAY,CAAC,EAAE,SAAS,EAAE,iBAAiB,EAAE,aAAa,EAAE,WAAW,CAAC,CAAA;I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AAQ;QAAE,OAAO,SAAS,CAAA;IAC7D,MAAM,OAAO,GAAG,GAAG,CAAC,qBAAuD,CAAA;IAC3E,OAAO,cAAc,CAAC;QACpB,WAAW,EAAE,GAAG,CAAC,YAAY;QAC7B,YAAY,EAAE,GAAG,CAAC,aAAa;QAC/B,eAAe,EAAE,GAAG,CAAC,uBAAuB;QAC5C,gBAAgB,EAAE,GAAG,CAAC,2BAA2B;QACjD,eAAe,EAAE,OAAO,KAAK,IAAI,IAAI,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC,CAAC,SAAS;KACvG,CAAC,CAAA;AACJ,CAAC","sourcesContent":["/**\n * Claude Code CLI 适配:纯命令构造 + `--print --output-format stream-json` 事件流解析。\n * 只产出 argv 与 stdin 正文并翻译事件;spawn/管道/stderr/中断由父 adapter 的\n * `ctx.subprocess` 掌握(stdin 取 `{data: input}`)。不 import 任何 DSH 包。\n *\n * 实测依据(Claude Code 2.1.300,新建 + `--resume` 各一轮真实跑通):\n * - `--print` 不给位置参数 prompt 时正文从 stdin 读,所以 argv 里没有 prompt;\n * - `stream-json` 必须配 `--verbose` 才是完整事件流;\n * - `--permission-prompts none` = 没人回答权限提问、会被提问的一律自动拒绝,\n * 正是无人值守管道要的语义(`--permission-mode` 仍决定其余判定);\n * - 续接用 `--resume <SESSION_ID>`;**不传** `--no-session-persistence`,否则会话\n * 不落盘、下一轮无法续接;\n * - claude **没有** cwd 选项(`--add-dir` 只是追加可写目录),工作目录由进程 cwd\n * 决定,故本模块接受并忽略 `cwd`,交给父 adapter 的 spawn `cwd`;`profile` 是\n * codex 专属概念,同样忽略。\n *\n * 事件语义:\n * - `system`(hook_started / hook_response / init)都带 `session_id`,且前两者出现在\n * `init` **之前**——故 remoteId 在「第一个带 session_id 的 system 事件」就回报;\n * - `assistant` → `message.content[]` 里 `type === 'text'` 的块拼成正文;`tool_use` /\n * `thinking` 块**绝不**当作正文;带 `parent_tool_use_id` 的是子代理消息,也不计入;\n * - `result` → 唯一权威收尾:`subtype === 'success' && is_error !== true` 才算成功;\n * `result` 字段是最终答复文本(覆盖累积值),`usage` 是整轮用量。\n */\n\nimport { normalizeUsage, requireEnum, requireEffort, requireId, requirePrompt, requireText, sanitizeError } from './jsonl.js'\nimport type { TokenUsage } from '@deepseek-ai/dsh-llm'\nimport type { CliCommandSpec, CliParser } from './types.js'\n\n/** `claude --permission-mode` 的实测取值(`claude --help`)。 */\nconst PERMISSION_MODES = ['acceptEdits', 'auto', 'bypassPermissions', 'manual', 'dontAsk', 'plan']\n\n/**\n * 构造一轮 `claude --print` 调用。\n *\n * @param {object} spec\n * @param {string} [spec.executable='claude'] - 可执行名或绝对路径。\n * @param {string} [spec.cwd] - 接受但忽略:claude 无 cwd 选项,请用 spawn 的 cwd。\n * @param {string} [spec.model] - `--model`,别名(sonnet/opus…)或全名。\n * @param {string} [spec.effort] - `--effort`,实测取值 low/medium/high/xhigh/max。\n * @param {string} [spec.profile] - 接受但忽略:codex 专属概念。\n * @param {string} [spec.permissionMode] - `--permission-mode`。\n * @param {string} [spec.remoteId] - 已有 session id 时走 `--resume <id>`。\n * @param {string} spec.prompt - 正文,经 stdin 送入。\n * @returns {{argv: string[], input: string}}\n */\nexport function buildCommand({ executable = 'claude', model, effort, permissionMode, remoteId, prompt }: CliCommandSpec = {}) {\n const argv = [requireText(executable, 'executable'), '--print', '--output-format', 'stream-json', '--verbose']\n if (model !== undefined) argv.push('--model', requireText(model, 'model'))\n if (effort !== undefined) argv.push('--effort', requireEffort(effort))\n if (permissionMode !== undefined) argv.push('--permission-mode', requireEnum(permissionMode, PERMISSION_MODES, 'permissionMode'))\n // 无人值守:任何权限提问都自动拒绝,而不是挂起等一个永远不会来的回答。\n argv.push('--permission-prompts', 'none')\n if (remoteId !== undefined) argv.push('--resume', requireId(remoteId, 'remoteId'))\n // 正文走 stdin(`--print` 无位置参数时读 stdin),argv 里不出现 prompt。\n return { argv, input: requirePrompt(prompt) }\n}\n\n/**\n * 创建一个有状态的 claude 事件解析器(一轮子进程一个)。\n *\n * @returns {{push: (event: unknown) => ({remoteId?: string, text?: string, usage?: object, completed?: boolean, error?: string}|undefined), finish: () => {text: string, remoteId?: string, usage?: object}}}\n */\nexport function createParser(): CliParser {\n let remoteId: string | undefined\n let text = ''\n let usage: TokenUsage | undefined\n let completed = false\n let failure: string | undefined\n\n /** 失败时优先用 provider 给的错误正文,否则退化成 subtype/api_error_status。 */\n function describeResultFailure(event: Record<string, unknown>): string {\n const label = typeof event.subtype === 'string' && event.subtype !== '' ? event.subtype : 'error'\n const detail = typeof event.result === 'string' && event.result !== '' ? event.result\n : Array.isArray(event.errors) ? event.errors.filter((item) => typeof item === 'string').slice(0, 3).join('; ') : ''\n const status = event.api_error_status === undefined ? '' : ` (api_error_status=${event.api_error_status})`\n return sanitizeError(detail === '' ? `claude result ${label}${status}` : `claude result ${label}${status}: ${detail}`)\n }\n\n return {\n /**\n * 投喂一个已解析的事件。\n * @param {unknown} event - `readJsonLines` 产出的单个事件。\n * @returns {{remoteId?: string, text?: string, usage?: object, completed?: boolean, error?: string}|undefined}\n * 本次事件产生的动作;无动作返回 undefined。\n * `error` 是**信息性**的:只有 `finish()` 抛错才代表这一轮失败。\n */\n push(value: unknown) {\n const event = value as Record<string, unknown> | null\n if (event === null || typeof event !== 'object') return undefined\n switch (event.type) {\n case 'system': {\n if (typeof event.session_id !== 'string' || event.session_id === '') return undefined\n // 只回报一次;实测 hook_started 早于 init,因此这里通常是最早的时机。\n if (remoteId !== undefined) return undefined\n remoteId = event.session_id\n return { remoteId }\n }\n case 'assistant': {\n // 子代理(Task 工具)的消息带 parent_tool_use_id,不能混进主答复。\n if (typeof event.parent_tool_use_id === 'string' && event.parent_tool_use_id !== '') return undefined\n const message = event.message as Record<string, unknown> | null\n if (message === null || typeof message !== 'object' || !Array.isArray(message.content)) return undefined\n const chunk = (message.content as unknown[])\n .filter((block): block is { type: 'text'; text: string } => block !== null && typeof block === 'object' && (block as Record<string, unknown>).type === 'text' && typeof (block as Record<string, unknown>).text === 'string')\n .map((block) => block.text)\n .join('')\n if (chunk === '') return undefined\n // 覆盖式:一条 assistant 事件就是一条完整消息,最后一条才是最终答复。\n text = chunk\n return { text }\n }\n case 'result': {\n const mapped = mapClaudeUsage(event.usage)\n if (mapped !== undefined) usage = mapped\n const succeeded = event.subtype === 'success' && event.is_error !== true\n if (succeeded) {\n completed = true\n if (typeof event.result === 'string' && event.result !== '') text = event.result\n } else {\n failure ??= describeResultFailure(event)\n }\n return {\n ...(mapped === undefined ? {} : { usage: mapped }),\n ...(succeeded ? { completed: true } : { error: failure }),\n ...(succeeded && typeof event.result === 'string' && event.result !== '' ? { text: event.result } : {}),\n }\n }\n default:\n // user(工具结果)/ stream_event / 未来新增事件:无语义动作。\n return undefined\n }\n },\n\n /**\n * 收流。失败或缺少 `result` 都抛错——「流结束了」不等于「回合成功了」。\n * 幂等:可重复调用,不改变状态。\n * @returns {{text: string, remoteId?: string, usage?: object}}\n */\n finish() {\n if (failure !== undefined) throw new Error(`claude 回合失败:${failure}`)\n if (!completed) throw new Error('claude 流在收到成功的 result 事件之前结束')\n return {\n text,\n ...(remoteId === undefined ? {} : { remoteId }),\n ...(usage === undefined ? {} : { usage }),\n }\n },\n }\n}\n\n/**\n * 把 claude 的整轮用量映射成 DSH TokenUsage。\n *\n * Anthropic 的 `input_tokens` 本来就**不含**缓存(另给 `cache_read_input_tokens` /\n * `cache_creation_input_tokens`),与 DSH 约定一致,无需扣减;\n * `output_tokens_details.thinking_tokens` 映射为 reasoning。\n */\nfunction mapClaudeUsage(value: unknown): TokenUsage | undefined {\n const raw = value as Record<string, unknown> | null\n if (raw === null || typeof raw !== 'object') return undefined\n const details = raw.output_tokens_details as Record<string, unknown> | null\n return normalizeUsage({\n inputTokens: raw.input_tokens,\n outputTokens: raw.output_tokens,\n cacheReadTokens: raw.cache_read_input_tokens,\n cacheWriteTokens: raw.cache_creation_input_tokens,\n reasoningTokens: details !== null && typeof details === 'object' ? details.thinking_tokens : undefined,\n })\n}\n"]}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Codex CLI 适配:纯命令构造 + `codex exec --json` 事件流解析。
|
|
3
|
+
* 只产出 argv 与 stdin 正文并翻译事件;spawn/管道/stderr/中断由父 adapter 的
|
|
4
|
+
* `ctx.subprocess` 掌握(stdin 取 `{data: input}`)。不 import 任何 DSH 包。
|
|
5
|
+
*
|
|
6
|
+
* 实测依据(codex-cli 0.162.1,新建 + 续接各一轮真实跑通):
|
|
7
|
+
* - 根选项 `-p/-s/-a/-C` 必须在 `exec` **之前**:`codex exec resume` 自己不接受
|
|
8
|
+
* 这四项,续接时只有根位置能让权限与 cwd 生效。
|
|
9
|
+
* - `resume <SESSION_ID>` 紧跟 `exec`,其余选项随后(clap 允许选项交错)。
|
|
10
|
+
* - 正文走 stdin:末尾 `-` 表示从 stdin 读;argv 不经 shell 解释,所以
|
|
11
|
+
* `-c model_reasoning_effort="high"` 里的双引号是**字面量**。
|
|
12
|
+
*
|
|
13
|
+
* 事件语义:
|
|
14
|
+
* - `thread.started` 的 `thread_id` 即 remoteId,立刻回报给父落 KV;
|
|
15
|
+
* - `item.completed` 且 `item.type === 'agent_message'` → 最终助手文本(覆盖式);
|
|
16
|
+
* - `item.type === 'reasoning'` / 工具类 item → **绝不**当作正文;
|
|
17
|
+
* - `item.type === 'error'` → 实测是配置告警("ignoring N unrecognized configuration
|
|
18
|
+
* settings"),**非致命**,只作信息回报;
|
|
19
|
+
* - `turn.completed` → 唯一成功完成标志,带 turn 用量;
|
|
20
|
+
* - `turn.failed` / 顶层 `error` → 致命,`finish()` 抛错。
|
|
21
|
+
*/
|
|
22
|
+
import type { CliCommandSpec, CliParser } from './types.js';
|
|
23
|
+
/**
|
|
24
|
+
* 构造一轮 `codex exec` 调用。
|
|
25
|
+
*
|
|
26
|
+
* @param {object} spec
|
|
27
|
+
* @param {string} [spec.executable='codex'] - 可执行名或绝对路径。
|
|
28
|
+
* @param {string} [spec.cwd] - 工作根,落到根选项 `-C`。
|
|
29
|
+
* @param {string} [spec.model] - `-m` 模型 id。
|
|
30
|
+
* @param {string} [spec.effort] - 拼进 `-c model_reasoning_effort="…"`。
|
|
31
|
+
* @param {string} [spec.profile] - 根选项 `-p`;留空请传 undefined。
|
|
32
|
+
* @param {string} [spec.permissionMode] - 根选项 `-s`,只接受三种 sandbox 模式。
|
|
33
|
+
* @param {string} [spec.remoteId] - 已有 thread id 时走 `exec resume <id>`。
|
|
34
|
+
* @param {string} spec.prompt - 正文,经 stdin 送入。
|
|
35
|
+
* @returns {{argv: string[], input: string}}
|
|
36
|
+
*/
|
|
37
|
+
export declare function buildCommand({ executable, cwd, model, effort, profile, permissionMode, remoteId, prompt }?: CliCommandSpec): {
|
|
38
|
+
argv: string[];
|
|
39
|
+
input: string;
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* 创建一个有状态的 codex 事件解析器(一轮子进程一个)。
|
|
43
|
+
*
|
|
44
|
+
* @returns {{push: (event: unknown) => ({remoteId?: string, text?: string, usage?: object, completed?: boolean, error?: string}|undefined), finish: () => {text: string, remoteId?: string, usage?: object}}}
|
|
45
|
+
*/
|
|
46
|
+
export declare function createParser(): CliParser;
|