agent-bridge-service 0.2.2 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/CHANGELOG.md +112 -140
  2. package/README.md +508 -35
  3. package/README.zh-CN.md +443 -33
  4. package/assets/agent-icons/agy.svg +27 -0
  5. package/dist/adapters/acp-auth.js +51 -0
  6. package/dist/adapters/acp-codebuddy.js +507 -0
  7. package/dist/adapters/agent-adapters.js +466 -46
  8. package/dist/adapters/claude-stream.js +159 -0
  9. package/dist/adapters/codex-app-server.js +310 -0
  10. package/dist/adapters/host-env.js +48 -0
  11. package/dist/adapters/mcp-elicitation.js +148 -0
  12. package/dist/adapters/mcp-host.js +70 -0
  13. package/dist/adapters/step-parsers.js +583 -0
  14. package/dist/app/bootstrap.js +163 -74
  15. package/dist/app/claude-resident.js +204 -0
  16. package/dist/app/conversation.js +639 -0
  17. package/dist/app/service-gate.js +1 -1
  18. package/dist/app/session.js +425 -14
  19. package/dist/app/task-dispatch.js +883 -7
  20. package/dist/app/task-registry.js +168 -0
  21. package/dist/cli/dispatch.js +4 -0
  22. package/dist/cli/flags.js +11 -0
  23. package/dist/cli/help.js +25 -7
  24. package/dist/cli/panel.js +334 -0
  25. package/dist/cli/render.js +2 -0
  26. package/dist/commands/approvals.js +80 -0
  27. package/dist/commands/connect.js +122 -4
  28. package/dist/commands/daemon-service.js +81 -0
  29. package/dist/commands/daemon.js +269 -6
  30. package/dist/commands/logout.js +13 -10
  31. package/dist/commands/serve.js +98 -12
  32. package/dist/commands/sessions.js +106 -0
  33. package/dist/core/ansi.js +5 -0
  34. package/dist/core/artifact-extract.js +158 -0
  35. package/dist/core/artifact-transfer.js +583 -0
  36. package/dist/core/device-identity.js +22 -0
  37. package/dist/core/emitter.js +50 -8
  38. package/dist/core/errors.js +43 -0
  39. package/dist/core/form-schema.js +72 -0
  40. package/dist/core/interaction-broker.js +440 -0
  41. package/dist/core/interaction-url.js +63 -0
  42. package/dist/core/partial-messages.js +99 -0
  43. package/dist/core/permission-ledger.js +146 -0
  44. package/dist/core/permission-policy.js +88 -0
  45. package/dist/core/port-fallback.js +22 -0
  46. package/dist/core/redact.js +13 -0
  47. package/dist/core/scan.js +12 -7
  48. package/dist/core/session-store.js +1632 -0
  49. package/dist/core/task-supervisor.js +955 -30
  50. package/dist/infra/atomic-file.js +111 -0
  51. package/dist/infra/audit.js +7 -0
  52. package/dist/infra/auth.js +167 -42
  53. package/dist/infra/config.js +511 -72
  54. package/dist/infra/device-identity-store.js +87 -0
  55. package/dist/infra/jwt.js +149 -0
  56. package/dist/infra/profile-lock.js +295 -0
  57. package/dist/infra/proxy-env.js +60 -0
  58. package/dist/infra/service-token.js +25 -4
  59. package/dist/protocol.js +298 -2
  60. package/dist/transport/a2a-mapping.js +206 -0
  61. package/dist/transport/acp-gateway-mapping.js +186 -0
  62. package/dist/transport/bridge-client.js +31 -22
  63. package/dist/transport/control-plane-page.js +820 -0
  64. package/dist/transport/control-plane-sessions-page.js +90 -0
  65. package/dist/transport/control-plane.js +923 -71
  66. package/dist/transport/gateway.js +1005 -0
  67. package/dist/transport/office-preview.js +154 -0
  68. package/package.json +6 -3
  69. package/assets/agent-icons/gemini.svg +0 -1
@@ -0,0 +1,70 @@
1
+ /**
2
+ * 本机 MCP server 宿主:按 config.toml 的 [mcp.servers.*] 启动 stdio server,
3
+ * 复用 McpElicitationClient 完成 tools/list、tools/call 与 elicitation。
4
+ *
5
+ * 这是“配置入口 + 宿主”,不是平台 Form 的完整链路;平台交互仍由调用方注入 handler。
6
+ */
7
+ import { McpElicitationClient } from './mcp-elicitation.js';
8
+ export class McpHost {
9
+ servers;
10
+ clients = new Map();
11
+ constructor(servers) {
12
+ this.servers = servers;
13
+ }
14
+ names() {
15
+ return Object.keys(this.servers).sort();
16
+ }
17
+ client(name) {
18
+ const spec = this.servers[name];
19
+ if (!spec)
20
+ throw new Error(`未配置 MCP server:${name}`);
21
+ const cached = this.clients.get(name);
22
+ if (cached)
23
+ return cached;
24
+ const client = new McpElicitationClient({
25
+ spec: {
26
+ command: spec.command,
27
+ args: spec.args ?? [],
28
+ cwd: spec.cwd ?? process.cwd(),
29
+ env: { ...process.env, ...(spec.env ?? {}) },
30
+ },
31
+ });
32
+ this.clients.set(name, client);
33
+ return client;
34
+ }
35
+ async listTools(name) {
36
+ return this.client(name).listTools();
37
+ }
38
+ async callTool(name, tool, args = {}, onElicitation) {
39
+ if (!this.servers[name])
40
+ throw new Error(`未配置 MCP server:${name}`);
41
+ if (onElicitation) {
42
+ const existing = this.clients.get(name);
43
+ if (existing) {
44
+ existing.close();
45
+ this.clients.delete(name);
46
+ }
47
+ return this.createWithHandler(name, onElicitation).callTool(tool, args);
48
+ }
49
+ return this.client(name).callTool(tool, args);
50
+ }
51
+ createWithHandler(name, onElicitation) {
52
+ const spec = this.servers[name];
53
+ const client = new McpElicitationClient({
54
+ spec: {
55
+ command: spec.command,
56
+ args: spec.args ?? [],
57
+ cwd: spec.cwd ?? process.cwd(),
58
+ env: { ...process.env, ...(spec.env ?? {}) },
59
+ },
60
+ ...(onElicitation ? { onElicitation } : {}),
61
+ });
62
+ this.clients.set(name, client);
63
+ return client;
64
+ }
65
+ close() {
66
+ for (const client of this.clients.values())
67
+ client.close();
68
+ this.clients.clear();
69
+ }
70
+ }
@@ -0,0 +1,583 @@
1
+ /**
2
+ * 步骤流解析器(B 批次:L1/L2 结构化事件 → task_step)
3
+ *
4
+ * 数据源格式(2026-10-24 本机实测,样例落档 openspec/changes/add-multi-task-visibility/research/):
5
+ * - `claude-json`:claude / codebuddy 的 `-p --output-format stream-json --verbose`
6
+ * assistant.message.content[].tool_use → started(action=name,label 取 input 摘要)
7
+ * user.message.content[].tool_result → finished(ref=tool_use_id,ok=!is_error)
8
+ * - `codex-json`:`codex exec --json`
9
+ * item.started / item.completed 成对(item.id 配对);只收动作类 item
10
+ * (command_execution / file_change / mcp_tool_call / web_search),reasoning / agent_message 跳过
11
+ * - `opencode-json`:`opencode run --format json`(⛔ 不是 `--json`,那是无效参数)
12
+ * tool_use 事件一次带齐 part.state.status → 直接发 finished
13
+ *
14
+ * 解析器是纯函数状态机:feed() 内部维持行缓冲,只处理完整行;非 JSON 行快速跳过。
15
+ */
16
+ /** 单个 content 块的字符上限(design「有界 text/diff/terminal」;超限截断,不扫描全文) */
17
+ const TOOL_CONTENT_MAX = 16_384;
18
+ /** 从 TodoWrite 类工具的 input 提取计划(存在才返回;工具名含 todo 且带 todos 数组才认) */
19
+ function planOfInput(toolName, input) {
20
+ if (!/todo/i.test(toolName))
21
+ return undefined;
22
+ if (typeof input !== 'object' || input === null)
23
+ return undefined;
24
+ const todos = input['todos'];
25
+ if (!Array.isArray(todos))
26
+ return undefined;
27
+ const items = [];
28
+ for (const t of todos) {
29
+ if (typeof t !== 'object' || t === null)
30
+ continue;
31
+ const text = String(t['content'] ?? t['text'] ?? '');
32
+ if (!text)
33
+ continue;
34
+ const raw = String(t['status'] ?? 'pending');
35
+ const state = raw === 'completed' ? 'completed' : raw === 'in_progress' ? 'in_progress' : 'pending';
36
+ items.push({ text, state });
37
+ }
38
+ return items.length > 0 ? items : undefined;
39
+ }
40
+ /** 从 tool_use.input 里挑一个最有信息量的摘要字段 */
41
+ function labelOfInput(input) {
42
+ if (!input || typeof input !== 'object')
43
+ return undefined;
44
+ const o = input;
45
+ for (const k of ['command', 'file_path', 'path', 'pattern', 'url', 'query', 'description']) {
46
+ const v = o[k];
47
+ if (typeof v === 'string' && v.trim())
48
+ return v;
49
+ }
50
+ return undefined;
51
+ }
52
+ function forEachJsonLine(buffer, chunk, onLine) {
53
+ const text = buffer.rest + chunk;
54
+ const lines = text.split('\n');
55
+ buffer.rest = lines.pop() ?? '';
56
+ for (const line of lines) {
57
+ const t = line.trim();
58
+ if (!t.startsWith('{'))
59
+ continue;
60
+ try {
61
+ onLine(JSON.parse(t));
62
+ }
63
+ catch {
64
+ /* 半行/非 JSON:跳过 */
65
+ }
66
+ }
67
+ }
68
+ // ---------- claude / codebuddy:stream-json ----------
69
+ /** claude 工具名 → ACP kind(4.8 富 toolCall;未列出的工具归 other,不猜) */
70
+ const CLAUDE_TOOL_KINDS = {
71
+ Read: 'read',
72
+ Edit: 'edit',
73
+ Write: 'edit',
74
+ NotebookEdit: 'edit',
75
+ MultiEdit: 'edit',
76
+ Delete: 'delete',
77
+ Move: 'move',
78
+ Glob: 'search',
79
+ Grep: 'search',
80
+ Bash: 'execute',
81
+ Think: 'think',
82
+ WebFetch: 'fetch',
83
+ WebSearch: 'fetch',
84
+ };
85
+ /** tool_use.input 里的路径字段 → locations 包装(file_path 优先,与 labelOfInput 同源字段;无命中给空对象) */
86
+ function locationsOfInput(input) {
87
+ if (!input || typeof input !== 'object')
88
+ return {};
89
+ const o = input;
90
+ for (const k of ['file_path', 'path', 'notebook_path']) {
91
+ const v = o[k];
92
+ if (typeof v === 'string' && v)
93
+ return { locations: [{ path: v }] };
94
+ }
95
+ return {};
96
+ }
97
+ /**
98
+ * claude 系 tool_use → 富 toolCall(supervisor 的常驻 stream 通道复用同一映射;
99
+ * headless 解析器内部直接内联同款构造)。
100
+ */
101
+ export function claudeToolCallOf(name, id, input) {
102
+ return {
103
+ ...(typeof id === 'string' && id ? { toolCallId: id } : {}),
104
+ name,
105
+ kind: CLAUDE_TOOL_KINDS[name] ?? 'other',
106
+ status: 'pending',
107
+ ...locationsOfInput(input),
108
+ };
109
+ }
110
+ /** tool_result.content → 有界块(Bash 类输出映射 terminal;其余 text)。字符串/块数组都收。 */
111
+ function toolResultContent(raw) {
112
+ const pieces = [];
113
+ if (typeof raw === 'string')
114
+ pieces.push(raw);
115
+ else if (Array.isArray(raw)) {
116
+ for (const item of raw) {
117
+ if (typeof item === 'string')
118
+ pieces.push(item);
119
+ else if (item && typeof item === 'object' && typeof item['text'] === 'string') {
120
+ pieces.push(item['text']);
121
+ }
122
+ }
123
+ }
124
+ const text = pieces.join('\n');
125
+ if (!text)
126
+ return undefined;
127
+ return [{ kind: 'terminal', text: text.length > TOOL_CONTENT_MAX ? `${text.slice(0, TOOL_CONTENT_MAX - 1)}…` : text }];
128
+ }
129
+ function createClaudeParser() {
130
+ const buffer = { rest: '' };
131
+ // 最终回答:result 事件的 result 字段优先;兜底最后一条 assistant text 块
132
+ let lastText;
133
+ // 待办计划:TodoWrite 的 input.todos 快照(每次调用覆盖)
134
+ let plan;
135
+ let outcome;
136
+ // 中间 agent 消息(4.7):按 assistant 消息聚合 text 块,drain 即清空
137
+ const pendingMessages = [];
138
+ return {
139
+ feed(chunk) {
140
+ const out = [];
141
+ forEachJsonLine(buffer, chunk, (o) => {
142
+ const message = o['message'];
143
+ const content = message?.['content'];
144
+ if (o['type'] === 'result') {
145
+ const resultText = typeof o['result'] === 'string' ? o['result'] : undefined;
146
+ if (resultText !== undefined)
147
+ lastText = resultText;
148
+ const subtype = typeof o['subtype'] === 'string' ? o['subtype'] : undefined;
149
+ const failed = o['is_error'] === true || (subtype !== undefined && subtype !== 'success');
150
+ const detail = (typeof o['error'] === 'string' && o['error']) || resultText || subtype || '未知终态错误';
151
+ outcome = {
152
+ ok: !failed,
153
+ ...(failed ? { error: `CLI result${subtype ? ` ${subtype}` : ''}:${detail}` } : {}),
154
+ ...(resultText ? { result: resultText } : {}),
155
+ };
156
+ }
157
+ if (!Array.isArray(content))
158
+ return;
159
+ if (o['type'] === 'assistant') {
160
+ const nativeId = typeof message?.['id'] === 'string' ? message?.['id'] : undefined;
161
+ let textParts = [];
162
+ for (const b of content) {
163
+ if (b?.type === 'tool_use' && typeof b.name === 'string') {
164
+ plan = planOfInput(b.name, b.input) ?? plan;
165
+ out.push({
166
+ action: b.name,
167
+ label: labelOfInput(b.input),
168
+ state: 'started',
169
+ ref: typeof b.id === 'string' ? b.id : undefined,
170
+ toolCall: {
171
+ ...(typeof b.id === 'string' ? { toolCallId: b.id } : {}),
172
+ name: b.name,
173
+ kind: CLAUDE_TOOL_KINDS[b.name] ?? 'other',
174
+ ...(typeof b.title === 'string' ? { title: b.title } : {}),
175
+ status: 'pending',
176
+ ...locationsOfInput(b.input),
177
+ // rawInput 不上行:只有上面的 locations 路径与 label 摘要
178
+ },
179
+ });
180
+ }
181
+ else if (b?.type === 'text' && typeof b.text === 'string' && b.text.trim()) {
182
+ lastText = b.text;
183
+ textParts.push(b.text);
184
+ }
185
+ }
186
+ // 同一条 assistant 消息的多个 text 块聚合为一条中间消息(CLI 原生 id 作幂等键)
187
+ if (textParts.length > 0) {
188
+ pendingMessages.push({
189
+ ...(nativeId ? { messageId: nativeId } : {}),
190
+ text: textParts.join('\n\n'),
191
+ });
192
+ }
193
+ }
194
+ else if (o['type'] === 'user') {
195
+ for (const b of content) {
196
+ if (b?.type === 'tool_result') {
197
+ const ref = typeof b['tool_use_id'] === 'string' ? b['tool_use_id'] : undefined;
198
+ const resultContent = toolResultContent(b['content']);
199
+ out.push({
200
+ action: 'tool_result',
201
+ state: 'finished',
202
+ ok: b['is_error'] !== true,
203
+ ref,
204
+ toolCall: {
205
+ ...(ref ? { toolCallId: ref } : {}),
206
+ name: 'tool_result',
207
+ status: b['is_error'] === true ? 'failed' : 'completed',
208
+ ...(resultContent ? { content: resultContent } : {}),
209
+ },
210
+ });
211
+ }
212
+ }
213
+ }
214
+ });
215
+ return out;
216
+ },
217
+ finalText: () => lastText,
218
+ drainMessages: () => pendingMessages.splice(0),
219
+ finalOutcome: () => outcome,
220
+ plan: () => plan,
221
+ };
222
+ }
223
+ // ---------- codex:exec --json ----------
224
+ /** 动作类 item:只有它们值得成为步骤(reasoning / agent_message 是思考与回复,不算) */
225
+ const CODEX_ACTION_ITEMS = new Set(['command_execution', 'file_change', 'mcp_tool_call', 'web_search']);
226
+ function codexLabel(item) {
227
+ if (typeof item['command'] === 'string')
228
+ return item['command'];
229
+ const changes = item['changes'];
230
+ if (Array.isArray(changes) && changes.length > 0) {
231
+ const p = changes[0]?.['path'];
232
+ if (typeof p === 'string')
233
+ return p;
234
+ }
235
+ return typeof item['path'] === 'string' ? item['path'] : undefined;
236
+ }
237
+ function createCodexParser() {
238
+ const buffer = { rest: '' };
239
+ // 最终回答:最后一条 agent_message 的 text
240
+ let lastText;
241
+ // 计划:codex 的 plan/update_plan item(item.plan = [{step,status}])
242
+ let plan;
243
+ return {
244
+ feed(chunk) {
245
+ const out = [];
246
+ forEachJsonLine(buffer, chunk, (o) => {
247
+ const type = o['type'];
248
+ if (type !== 'item.started' && type !== 'item.completed' && type !== 'item.updated')
249
+ return;
250
+ const item = o['item'];
251
+ if (!item || typeof item['type'] !== 'string')
252
+ return;
253
+ if ((item['type'] === 'plan' || item['type'] === 'update_plan') && Array.isArray(item['plan'])) {
254
+ const items = [];
255
+ for (const p of item['plan']) {
256
+ const text = String(p?.['step'] ?? p?.['text'] ?? '');
257
+ if (!text)
258
+ continue;
259
+ const raw = String(p?.['status'] ?? 'pending');
260
+ items.push({
261
+ text,
262
+ state: raw === 'completed' ? 'completed' : raw === 'in_progress' ? 'in_progress' : 'pending',
263
+ });
264
+ }
265
+ if (items.length > 0)
266
+ plan = items;
267
+ }
268
+ if (type === 'item.completed' && item['type'] === 'agent_message' && typeof item['text'] === 'string') {
269
+ lastText = item['text'];
270
+ }
271
+ if (type === 'item.updated')
272
+ return;
273
+ if (!CODEX_ACTION_ITEMS.has(item['type']))
274
+ return;
275
+ const started = type === 'item.started';
276
+ out.push({
277
+ action: item['type'],
278
+ label: codexLabel(item),
279
+ state: started ? 'started' : 'finished',
280
+ ok: started ? undefined : item['type'] !== 'error' && (item['exit_code'] === undefined || item['exit_code'] === 0),
281
+ ref: typeof item['id'] === 'string' ? item['id'] : undefined,
282
+ });
283
+ });
284
+ return out;
285
+ },
286
+ finalText: () => lastText,
287
+ plan: () => plan,
288
+ };
289
+ }
290
+ // ---------- opencode:run --format json ----------
291
+ function createOpencodeParser() {
292
+ const buffer = { rest: '' };
293
+ // 最终回答:最后一条 text 事件的 part.text
294
+ let lastText;
295
+ let plan;
296
+ return {
297
+ feed(chunk) {
298
+ const out = [];
299
+ forEachJsonLine(buffer, chunk, (o) => {
300
+ if (o['type'] === 'text') {
301
+ const part = o['part'];
302
+ if (typeof part?.['text'] === 'string' && part['text'].trim())
303
+ lastText = part['text'];
304
+ return;
305
+ }
306
+ if (o['type'] !== 'tool_use')
307
+ return;
308
+ const part = o['part'];
309
+ if (!part || part['type'] !== 'tool' || typeof part['tool'] !== 'string')
310
+ return;
311
+ const state = part['state'];
312
+ plan = planOfInput(part['tool'], state?.['input']) ?? plan;
313
+ out.push({
314
+ action: part['tool'],
315
+ label: labelOfInput(state?.['input']),
316
+ state: 'finished',
317
+ ok: state?.['status'] === 'completed',
318
+ ref: typeof part['callID'] === 'string' ? part['callID'] : undefined,
319
+ });
320
+ });
321
+ return out;
322
+ },
323
+ finalText: () => lastText,
324
+ plan: () => plan,
325
+ };
326
+ }
327
+ // ---------- agy(Antigravity CLI):-p --output-format stream-json ----------
328
+ // 官方 headless 文档 + 1.4.10 本机实测信封一致:{"event":"init"|"step_update"|"result",…同名负载}。
329
+ // tool 步骤两态(ACTIVE/DONE)按 step_index 配对;result.status 枚举里只有 SUCCESS 算完成 ——
330
+ // 退出码 0 也可能是 --print-timeout 的优雅部分完成,finalOutcome 负责推翻假成功。
331
+ // init 的 conversation_id 在信封顶层,supervisor 既有 onSession 正则直接命中,无需新机制。
332
+ /** agy 参数对象的摘要键(`CommandLine` 是 agy 特有大小写,通用 labelOfInput 不含) */
333
+ function agyLabelOfParameters(parameters) {
334
+ if (!parameters || typeof parameters !== 'object')
335
+ return labelOfInput(parameters);
336
+ const o = parameters;
337
+ const cl = o['CommandLine'];
338
+ if (typeof cl === 'string' && cl.trim())
339
+ return cl;
340
+ return labelOfInput(parameters);
341
+ }
342
+ function createAgyParser() {
343
+ const buffer = { rest: '' };
344
+ // 最终回答:result.response 优先;agent_response 的 text_delta 增量拼接兜底
345
+ let deltaText;
346
+ let finalResponse;
347
+ // 终态裁决:见过 result 事件才有发言权(没见过 = 该流没有 status 语义,不推翻退出码)
348
+ let outcome;
349
+ return {
350
+ feed(chunk) {
351
+ const out = [];
352
+ forEachJsonLine(buffer, chunk, (o) => {
353
+ const event = o['event'];
354
+ if (event === 'step_update') {
355
+ const p = o['step_update'];
356
+ if (!p || p['step_type'] !== 'tool') {
357
+ if (p?.['step_type'] === 'agent_response' && typeof p['text_delta'] === 'string') {
358
+ deltaText = (deltaText ?? '') + p['text_delta'];
359
+ }
360
+ return;
361
+ }
362
+ const state = p['state'];
363
+ if (state !== 'ACTIVE' && state !== 'DONE')
364
+ return;
365
+ const done = state === 'DONE';
366
+ // ACTIVE 就带 parameters(官方实样):started 步骤立即显示命令行,不必等 DONE
367
+ const toolInfo = p['tool_info'];
368
+ out.push({
369
+ action: typeof p['tool_name'] === 'string' ? p['tool_name'] : 'tool',
370
+ label: agyLabelOfParameters(toolInfo?.['parameters']),
371
+ state: done ? 'finished' : 'started',
372
+ ...(done ? { ok: toolInfo?.['error'] == null } : {}),
373
+ ref: p['step_index'] === undefined ? undefined : String(p['step_index']),
374
+ });
375
+ }
376
+ else if (event === 'result') {
377
+ const r = o['result'];
378
+ if (!r)
379
+ return;
380
+ const response = typeof r['response'] === 'string' ? r['response'] : undefined;
381
+ if (response && response.trim())
382
+ finalResponse = response;
383
+ const status = String(r['status'] ?? '');
384
+ const errMsg = typeof r['error'] === 'string' && r['error'] ? r['error'] : undefined;
385
+ outcome = {
386
+ ok: status === 'SUCCESS',
387
+ ...(status !== 'SUCCESS'
388
+ ? { error: `Antigravity CLI status=${status || 'unknown'}${errMsg ? `:${errMsg}` : ''}` }
389
+ : {}),
390
+ ...(finalResponse ? { result: finalResponse } : {}),
391
+ };
392
+ }
393
+ });
394
+ return out;
395
+ },
396
+ finalText: () => finalResponse ?? deltaText,
397
+ finalOutcome: () => outcome,
398
+ };
399
+ }
400
+ // ---------- kimi:OpenAI 风格 tool_calls ----------
401
+ // 实测(kimi -p … --output-format stream-json):assistant.tool_calls[] → role:tool。
402
+ // function.arguments 是 JSON 字符串(OpenAI 惯例),抠出内部摘要字段做 label。
403
+ function createKimiParser() {
404
+ const buffer = { rest: '' };
405
+ // 最终回答:最后一条 role:assistant 的 content 字符串
406
+ let lastText;
407
+ let plan;
408
+ return {
409
+ feed(chunk) {
410
+ const out = [];
411
+ forEachJsonLine(buffer, chunk, (o) => {
412
+ if (o['role'] === 'assistant' && Array.isArray(o['tool_calls'])) {
413
+ if (typeof o['content'] === 'string' && o['content'].trim())
414
+ lastText = o['content'];
415
+ for (const call of o['tool_calls']) {
416
+ const fn = call?.['function'];
417
+ if (typeof fn?.['name'] !== 'string')
418
+ continue;
419
+ let label;
420
+ let input;
421
+ if (typeof fn['arguments'] === 'string') {
422
+ try {
423
+ input = JSON.parse(fn['arguments']);
424
+ label = labelOfInput(input);
425
+ }
426
+ catch {
427
+ label = fn['arguments'];
428
+ }
429
+ }
430
+ else {
431
+ input = fn['arguments'];
432
+ label = labelOfInput(input);
433
+ }
434
+ plan = planOfInput(fn['name'], input) ?? plan;
435
+ out.push({
436
+ action: fn['name'],
437
+ label,
438
+ state: 'started',
439
+ ref: typeof call['id'] === 'string' ? call['id'] : undefined,
440
+ });
441
+ }
442
+ }
443
+ else if (o['role'] === 'assistant' && typeof o['content'] === 'string' && o['content'].trim()) {
444
+ lastText = o['content'];
445
+ }
446
+ else if (o['role'] === 'tool') {
447
+ out.push({
448
+ action: 'tool_result',
449
+ state: 'finished',
450
+ ok: true,
451
+ ref: typeof o['tool_call_id'] === 'string' ? o['tool_call_id'] : undefined,
452
+ });
453
+ }
454
+ });
455
+ return out;
456
+ },
457
+ finalText: () => lastText,
458
+ plan: () => plan,
459
+ };
460
+ }
461
+ // ---------- dsh(DeepSeek Harness):--profile headless --json ----------
462
+ // 官方文档口径(本机缺 key 未取得 tool_call 实测):session / status / text / thinking /
463
+ // tool_call / tool_result / final / error;tool_result.callId 与 tool_call.callId 配对。
464
+ function createDshParser() {
465
+ const buffer = { rest: '' };
466
+ // 最终回答:final 事件的 text
467
+ let lastText;
468
+ let plan;
469
+ let outcome;
470
+ return {
471
+ feed(chunk) {
472
+ const out = [];
473
+ forEachJsonLine(buffer, chunk, (o) => {
474
+ const type = o['type'];
475
+ if (type === 'status' && o['phase'] === 'turn_end') {
476
+ const reason = o['reason'];
477
+ if (reason?.['kind'] === 'error') {
478
+ const error = reason['error'];
479
+ const code = typeof error?.['code'] === 'string' ? `${error['code']}: ` : '';
480
+ const message = typeof error?.['message'] === 'string' ? error['message'] : 'DSH 回合失败';
481
+ outcome = { ok: false, error: `DSH ${code}${message}` };
482
+ }
483
+ }
484
+ if (type === 'final' && typeof o['text'] === 'string')
485
+ lastText = o['text'];
486
+ if (type === 'tool_call') {
487
+ const action = (o['name'] ?? o['tool']);
488
+ if (typeof action !== 'string')
489
+ return;
490
+ plan = planOfInput(action, o['arguments'] ?? o['input'] ?? o['args']) ?? plan;
491
+ out.push({
492
+ action,
493
+ label: labelOfInput(o['arguments'] ?? o['input'] ?? o['args']),
494
+ state: 'started',
495
+ ref: typeof o['callId'] === 'string' ? o['callId'] : undefined,
496
+ });
497
+ }
498
+ else if (type === 'tool_result') {
499
+ out.push({
500
+ action: 'tool_result',
501
+ state: 'finished',
502
+ ok: o['isError'] !== true && o['is_error'] !== true,
503
+ ref: typeof o['callId'] === 'string' ? o['callId'] : undefined,
504
+ });
505
+ }
506
+ });
507
+ return out;
508
+ },
509
+ finalText: () => lastText,
510
+ finalOutcome: () => outcome,
511
+ plan: () => plan,
512
+ };
513
+ }
514
+ // ---------- minimax-code(mcode):exec --output-format stream-json ----------
515
+ // 实测(0.6.13):exec/session/turn 生命周期 + item.started|updated|completed。
516
+ // 动作在 item.type === 'tool_call'(toolCall{id,name,input,status});reasoning / agent_message 跳过;
517
+ // item.updated 是增量噪音,同样跳过。status 是数字枚举(成功观测值为 2),不猜语义:
518
+ // ok 仅在显式 error 字段存在时判 false。
519
+ function createMcodeParser() {
520
+ const buffer = { rest: '' };
521
+ // 最终回答:exec.completed 的 result.output/answer;兜底最后一条 agent_message content
522
+ let lastText;
523
+ let plan;
524
+ return {
525
+ feed(chunk) {
526
+ const out = [];
527
+ forEachJsonLine(buffer, chunk, (o) => {
528
+ const type = o['type'];
529
+ if (type === 'exec.completed') {
530
+ const result = o['result'];
531
+ const text = (result?.['output'] ?? result?.['answer']);
532
+ if (typeof text === 'string' && text.trim())
533
+ lastText = text;
534
+ return;
535
+ }
536
+ if (type !== 'item.started' && type !== 'item.completed')
537
+ return;
538
+ const item = o['item'];
539
+ if (!item)
540
+ return;
541
+ if (type === 'item.completed' &&
542
+ item['type'] === 'agent_message' &&
543
+ typeof item['content'] === 'string' &&
544
+ item['content'].trim()) {
545
+ lastText = item['content'];
546
+ }
547
+ if (item['type'] !== 'tool_call')
548
+ return;
549
+ const call = item['toolCall'];
550
+ if (!call || typeof call['name'] !== 'string')
551
+ return;
552
+ plan = planOfInput(call['name'], call['input']) ?? plan;
553
+ const started = type === 'item.started';
554
+ out.push({
555
+ action: call['name'],
556
+ label: labelOfInput(call['input']),
557
+ state: started ? 'started' : 'finished',
558
+ ok: started ? undefined : call['error'] == null,
559
+ ref: typeof call['id'] === 'string' ? call['id'] : undefined,
560
+ });
561
+ });
562
+ return out;
563
+ },
564
+ finalText: () => lastText,
565
+ plan: () => plan,
566
+ };
567
+ }
568
+ /** 按格式名造解析器(格式由适配器声明,解析器与 CLI 输出一一对应) */
569
+ export function createStepParser(format) {
570
+ if (format === 'claude-json')
571
+ return createClaudeParser();
572
+ if (format === 'codex-json')
573
+ return createCodexParser();
574
+ if (format === 'agy-json')
575
+ return createAgyParser();
576
+ if (format === 'kimi-json')
577
+ return createKimiParser();
578
+ if (format === 'dsh-json')
579
+ return createDshParser();
580
+ if (format === 'mcode-json')
581
+ return createMcodeParser();
582
+ return createOpencodeParser();
583
+ }