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
@@ -7,95 +7,184 @@
7
7
  * 这里只负责**把会话建起来**,不负责"建完之后要一直活着还是顺便开个控制面"—— 那是命令层的事。
8
8
  */
9
9
  import { hostname } from 'node:os';
10
+ import { join } from 'node:path';
10
11
  import { version } from '../cli/meta.js';
11
- import { boolFlag, posFlag, strFlag } from '../cli/flags.js';
12
+ import { boolFlag, numFlagMin, posFlag, strFlag } from '../cli/flags.js';
12
13
  import { createSession } from './session.js';
13
- import { AuthError, authorizeWithBrowser, authorizeWithDeviceCode } from '../infra/auth.js';
14
- import { configPath, loadConfig, resolveDiffMaxBytes, resolveMaxQueued, resolveMaxTasks, saveConfig, tokenTail, } from '../infra/config.js';
15
- import { resolveDeviceId } from '../transport/bridge-client.js';
14
+ import { TaskRegistry } from './task-registry.js';
15
+ import { AuthError, authorizeWithBrowser, authorizeWithDeviceCode, refreshDeviceToken, } from '../infra/auth.js';
16
+ import { configPath, loadConfig, resolveDiffMaxBytes, resolveExternalSandbox, resolveInteractionEnabled, resolveInteractionTimeoutMs, resolveMaxInteractionsPerTask, resolveEventRetentionMaxEvents, resolveFeedBudgets, resolveApprovalLedgerEnabled, resolveApprovalTtlMs, resolveMaxQueued, resolveMaxTasks, resolvePermissionPolicy, resolveSessionIdleMs, saveConfig, stateDbPath, stateDir, tokenTail, } from '../infra/config.js';
17
+ import { SessionStore } from '../core/session-store.js';
18
+ import { ensureDeviceIdentity } from '../infra/device-identity-store.js';
19
+ import { withProfileLock } from '../infra/profile-lock.js';
16
20
  export async function startBridge(flags, log) {
17
- const platformUrl = posFlag(flags, 1);
18
- if (!platformUrl) {
21
+ const platformArg = posFlag(flags, 1);
22
+ if (!platformArg) {
19
23
  log('error', '用法:agent-bridge connect <platformUrl> [--token=xxx] [--no-browser]');
20
24
  process.exit(2);
21
25
  }
22
- const saved = loadConfig();
23
- let deviceToken = strFlag(flags, 'token');
24
- // 只在授权/复用配置时被赋值;--token 模式下由下面的 resolveDeviceId 解析
25
- let deviceId = '';
26
- let boundUrl = saved?.platformUrl ?? '';
27
- if (!deviceToken) {
28
- if (saved?.platformUrl === platformUrl.replace(/\/+$/, '') && saved.deviceToken) {
29
- deviceToken = saved.deviceToken;
30
- deviceId = saved.deviceId;
31
- boundUrl = saved.platformUrl;
26
+ const targetUrl = platformArg.replace(/\/+$/, '');
27
+ const explicitToken = strFlag(flags, 'token');
28
+ // 身份、授权和凭证写在同一 profile 锁内;WS 会话不持锁。
29
+ const prepared = await withProfileLock(stateDir(), async () => {
30
+ const saved = loadConfig();
31
+ const reusable = !explicitToken && saved?.platformUrl === targetUrl && saved.deviceToken;
32
+ const identity = await ensureDeviceIdentity({
33
+ identityPath: join(stateDir(), 'identity.toml'),
34
+ legacyDeviceId: saved?.deviceId,
35
+ explicitDeviceId: strFlag(flags, 'device-id'),
36
+ envDeviceId: process.env['AGENT_BRIDGE_DEVICE_ID'],
37
+ allowCreate: !explicitToken && !reusable,
38
+ hasReusableCredential: Boolean(explicitToken || reusable),
39
+ });
40
+ const deviceId = identity.deviceId;
41
+ log('info', `[agent-bridge] 设备身份 ${identity.source}(${deviceId})`);
42
+ if (explicitToken) {
43
+ const config = {
44
+ ...saved,
45
+ platformUrl: targetUrl,
46
+ deviceId,
47
+ deviceToken: explicitToken,
48
+ };
49
+ // 显式 token 不继承旧凭证的刷新令牌或绑定时间,也不写入磁盘。
50
+ delete config.refreshToken;
51
+ delete config.boundAt;
52
+ return { deviceId, deviceToken: explicitToken, config };
53
+ }
54
+ if (reusable) {
55
+ if (!saved?.deviceToken)
56
+ throw new Error('可复用配置缺少设备凭证,请重新授权。');
57
+ const deviceToken = saved.deviceToken;
32
58
  log('info', `复用已保存的设备凭证(${deviceId},token ${tokenTail(deviceToken)})`);
59
+ return { deviceId, deviceToken, config: saved };
33
60
  }
34
- else {
35
- log('info', '[agent-bridge] 开始设备授权…');
36
- const useBrowser = !boolFlag(flags, 'no-browser');
37
- try {
38
- const res = useBrowser
39
- ? await authorizeWithBrowser(platformUrl, {
40
- onPrompt: (url) => log('info', `[agent-bridge] 已打开浏览器,若无反应请手动访问:\n ${url}`),
41
- })
42
- : await authorizeWithDeviceCode(platformUrl, {
43
- onPrompt: (uri, code) => log('info', `[agent-bridge] 请在浏览器打开 ${uri} 并输入验证码:${code}`),
44
- });
45
- deviceToken = res.deviceToken;
46
- deviceId = res.deviceId;
47
- boundUrl = res.platformUrl;
48
- saveConfig({
49
- platformUrl: res.platformUrl,
50
- deviceId: res.deviceId,
51
- deviceToken: res.deviceToken,
52
- refreshToken: res.refreshToken,
53
- label: strFlag(flags, 'label') ?? hostname(),
54
- boundAt: new Date().toISOString(),
61
+ log('info', '[agent-bridge] 开始设备授权…');
62
+ const context = {
63
+ platformUrl: targetUrl,
64
+ deviceId,
65
+ hostname: hostname(),
66
+ platform: process.platform,
67
+ cliVersion: version(),
68
+ };
69
+ try {
70
+ const res = !boolFlag(flags, 'no-browser')
71
+ ? await authorizeWithBrowser(context, {
72
+ onPrompt: (url) => log('info', `[agent-bridge] 已打开浏览器,若无反应请手动访问:\n ${url}`),
73
+ })
74
+ : await authorizeWithDeviceCode(context, {
75
+ onPrompt: (uri, code) => log('info', `[agent-bridge] 请在浏览器打开 ${uri} 并输入验证码:${code}`),
55
76
  });
56
- log('info', `✅ 设备绑定成功(${res.deviceId}),配置已写入 ${configPath()}`);
57
- }
58
- catch (e) {
59
- if (e instanceof AuthError) {
60
- log('error', `❌ 授权失败:${e.message}`);
61
- process.exit(1);
62
- }
63
- throw e;
64
- }
77
+ const config = {
78
+ ...saved,
79
+ platformUrl: targetUrl,
80
+ deviceId,
81
+ deviceToken: res.deviceToken,
82
+ refreshToken: res.refreshToken,
83
+ label: strFlag(flags, 'label') ?? saved?.label ?? hostname(),
84
+ boundAt: new Date().toISOString(),
85
+ };
86
+ await saveConfig(config);
87
+ log('info', `✅ 设备绑定成功(${deviceId}),配置已写入 ${configPath()}`);
88
+ return { deviceId, deviceToken: res.deviceToken, config };
89
+ }
90
+ catch (e) {
91
+ if (e instanceof AuthError)
92
+ log('error', `❌ 授权失败:${e.message}`);
93
+ // 不在锁内退出进程;cli.ts 顶层捕获后退出,finally 始终释放锁。
94
+ throw e;
65
95
  }
66
- }
67
- // deviceId 解析优先级:授权响应 > --device-id > AGENT_BRIDGE_DEVICE_ID > 已保存配置(同平台)
68
- const targetUrl = (boundUrl || platformUrl).replace(/\/+$/, '');
69
- const savedId = saved && saved.platformUrl === targetUrl ? saved.deviceId : '';
70
- deviceId = resolveDeviceId({
71
- fromAuth: deviceId,
72
- flag: strFlag(flags, 'device-id') ?? '',
73
- env: process.env['AGENT_BRIDGE_DEVICE_ID'] ?? '',
74
- saved: savedId,
75
96
  });
76
- if (!deviceId) {
77
- log('warn', '[agent-bridge] 未提供 deviceId(--device-id / AGENT_BRIDGE_DEVICE_ID):' +
78
- '连接将不带 deviceId 参数,平台需按 Bearer token 反查设备');
79
- }
80
- if (saved?.allowedCwd?.length) {
97
+ const { config: saved, deviceId, deviceToken } = prepared;
98
+ if (saved.allowedCwd?.length) {
81
99
  log('info', `[agent-bridge] 目录白名单已启用(${saved.allowedCwd.length} 个条目),越界任务将被拒绝`);
82
100
  }
83
- if (saved?.requireServiceToken) {
101
+ if (saved.requireServiceToken) {
84
102
  log('info', '[agent-bridge] 已开启 require_service_token:无有效服务令牌的任务将被拒绝');
85
103
  }
86
- const session = createSession({
87
- platformUrl: boundUrl || platformUrl,
88
- deviceToken,
89
- deviceId,
90
- cliVersion: version(),
91
- hostname: hostname(),
92
- allowedCwd: saved?.allowedCwd,
93
- maxConcurrent: resolveMaxTasks(saved?.maxTasks),
94
- maxQueued: resolveMaxQueued(saved?.maxQueued),
95
- diffMaxBytes: resolveDiffMaxBytes(saved?.diffMaxBytes),
96
- captureDiffByDefault: saved?.diffDefault === true,
97
- requireServiceToken: saved?.requireServiceToken === true,
98
- log,
104
+ // 启动参数优先级最高:--max-tasks / --max-queue > 环境变量 > config.toml > 默认(30 / 60)
105
+ const maxTasksOverride = numFlagMin(flags, 'max-tasks', 1);
106
+ const maxQueueOverride = numFlagMin(flags, 'max-queue', 0);
107
+ // 权限策略:非法值由 resolvePermissionPolicy 回落到 default(失败关闭)
108
+ const permissionPolicyOverride = strFlag(flags, 'permission-policy');
109
+ const externalSandboxOverride = boolFlag(flags, 'external-sandbox') || undefined;
110
+ // 交互开关与额度:缺省全关(不发交互请求),显式 --interaction-enabled 才开
111
+ const interactionEnabledOverride = boolFlag(flags, 'interaction-enabled') || undefined;
112
+ const interactionTimeoutOverride = numFlagMin(flags, 'interaction-timeout-ms', 1000);
113
+ const maxInteractionsOverride = numFlagMin(flags, 'max-interactions-per-task', 1);
114
+ const approvalLedgerOverride = boolFlag(flags, 'approval-ledger') || undefined;
115
+ const approvalTtlOverride = numFlagMin(flags, 'approval-ttl-ms', 60_000);
116
+ // 事件保留:0 是合法值(= 不裁剪),所以下限用 0 而不是 1
117
+ const eventRetentionOverride = numFlagMin(flags, 'event-retention-max-events', 0);
118
+ const store = new SessionStore(stateDbPath(), {
119
+ retentionMaxEvents: resolveEventRetentionMaxEvents(saved?.eventRetentionMaxEvents, eventRetentionOverride),
120
+ // 有界 feed(2.9/3.9):默认 200/200/50 + 4MiB/64MiB,[feed] 段逐维覆盖(0 = 关闭该维)
121
+ feedBudgets: resolveFeedBudgets(saved?.feed),
99
122
  });
123
+ const recovered = store.recoverInterrupted();
124
+ if (recovered > 0) {
125
+ log('info', `[agent-bridge] 已恢复 ${recovered} 个上次中断的会话(未自动重放副作用)`);
126
+ }
127
+ let session;
128
+ let refreshToken = saved?.refreshToken;
129
+ const refresh = refreshToken
130
+ ? () => refreshDeviceToken({
131
+ platformUrl: targetUrl,
132
+ deviceId,
133
+ hostname: hostname(),
134
+ platform: process.platform,
135
+ cliVersion: version(),
136
+ }, refreshToken)
137
+ : undefined;
138
+ try {
139
+ session = createSession({
140
+ platformUrl: targetUrl,
141
+ deviceToken,
142
+ deviceId,
143
+ refresh,
144
+ onTokenRefreshed: (tokens) => {
145
+ refreshToken = tokens.refreshToken ?? refreshToken;
146
+ if (!saved)
147
+ return;
148
+ saved.deviceToken = tokens.deviceToken;
149
+ if (refreshToken)
150
+ saved.refreshToken = refreshToken;
151
+ const bound = {
152
+ ...saved,
153
+ platformUrl: saved.platformUrl ?? targetUrl,
154
+ deviceId: saved.deviceId ?? deviceId,
155
+ deviceToken: tokens.deviceToken,
156
+ ...(refreshToken ? { refreshToken } : {}),
157
+ };
158
+ void saveConfig(bound);
159
+ },
160
+ cliVersion: version(),
161
+ hostname: hostname(),
162
+ allowedCwd: saved.allowedCwd,
163
+ maxConcurrent: resolveMaxTasks(saved.maxTasks, maxTasksOverride),
164
+ maxQueued: resolveMaxQueued(saved.maxQueued, maxQueueOverride),
165
+ diffMaxBytes: resolveDiffMaxBytes(saved.diffMaxBytes),
166
+ captureDiffByDefault: saved.diffDefault === true,
167
+ requireServiceToken: saved.requireServiceToken === true,
168
+ permissionPolicy: resolvePermissionPolicy(saved.permissionPolicy, permissionPolicyOverride),
169
+ externalSandbox: resolveExternalSandbox(saved.externalSandbox, externalSandboxOverride),
170
+ interactionEnabled: resolveInteractionEnabled(saved.interactionEnabled, interactionEnabledOverride),
171
+ interactionTimeoutMs: resolveInteractionTimeoutMs(saved.interactionTimeoutMs, interactionTimeoutOverride),
172
+ maxInteractionsPerTask: resolveMaxInteractionsPerTask(saved.maxInteractionsPerTask, maxInteractionsOverride),
173
+ approvalLedgerEnabled: resolveApprovalLedgerEnabled(saved.approvalLedgerEnabled, approvalLedgerOverride),
174
+ approvalTtlMs: resolveApprovalTtlMs(saved.approvalTtlMs, approvalTtlOverride),
175
+ sessionIdleMs: resolveSessionIdleMs(saved.sessionIdleMs),
176
+ registry: new TaskRegistry(),
177
+ store,
178
+ artifactRootDir: join(stateDir(), 'artifacts'),
179
+ log,
180
+ });
181
+ }
182
+ catch (error) {
183
+ store.close();
184
+ throw error;
185
+ }
186
+ const resumed = session.recoverQueuedTasks?.() ?? 0;
187
+ if (resumed > 0)
188
+ log('info', `[agent-bridge] 已恢复 ${resumed} 个 queued Turn`);
100
189
  return { session, config: saved };
101
190
  }
@@ -0,0 +1,204 @@
1
+ /**
2
+ * 常驻 Claude stream-json 会话;Qoder 使用 headless + 原生 --resume。
3
+ *
4
+ * 每个 conversation session 一个进程:Turn 结束(result)只结算 Turn,不退出进程;
5
+ * 下一条 send_message 继续写 user 帧。这样省掉每轮 CLI 冷启动,并保留原生 session。
6
+ *
7
+ * 注意:CLI 会把 active Turn 期间的第二个 user 帧排队,因此这里不声明 same-turn steer。
8
+ */
9
+ import { createInterface } from 'node:readline';
10
+ import { killCliProcess, spawnCliProcess } from '../adapters/agent-adapters.js';
11
+ import { claudeResultError } from '../adapters/claude-stream.js';
12
+ export function claudeResidentArgs(nativeSessionId) {
13
+ const args = [
14
+ '-p',
15
+ '--input-format',
16
+ 'stream-json',
17
+ '--output-format',
18
+ 'stream-json',
19
+ '--verbose',
20
+ '--permission-mode',
21
+ 'acceptEdits',
22
+ ];
23
+ if (nativeSessionId)
24
+ args.push('--resume', nativeSessionId);
25
+ return args;
26
+ }
27
+ function textOf(message) {
28
+ if (!message || typeof message !== 'object')
29
+ return '';
30
+ const content = message.content;
31
+ if (!Array.isArray(content))
32
+ return '';
33
+ return content
34
+ .filter((block) => Boolean(block && typeof block === 'object'))
35
+ .filter((block) => block.type === 'text' && typeof block.text === 'string')
36
+ .map((block) => block.text ?? '')
37
+ .join('');
38
+ }
39
+ export class ClaudeResident {
40
+ options;
41
+ child;
42
+ rl;
43
+ active;
44
+ stepSeq = 0;
45
+ stepRefs = new Map();
46
+ sessionId = '';
47
+ closed = false;
48
+ idleTimer;
49
+ generation = 0;
50
+ constructor(options) {
51
+ this.options = options;
52
+ }
53
+ get nativeSessionId() {
54
+ return this.sessionId;
55
+ }
56
+ get isRunning() {
57
+ return Boolean(this.child && !this.closed);
58
+ }
59
+ ensureStarted() {
60
+ if (this.child && !this.closed)
61
+ return this.child;
62
+ const args = this.options.args ?? claudeResidentArgs(this.sessionId || this.options.nativeSessionId);
63
+ const child = spawnCliProcess(this.options.command, args, {
64
+ cwd: this.options.cwd,
65
+ env: process.env,
66
+ });
67
+ const generation = ++this.generation;
68
+ this.child = child;
69
+ this.closed = false;
70
+ this.rl = createInterface({ input: child.stdout });
71
+ this.rl.on('line', (line) => {
72
+ if (this.generation === generation)
73
+ this.onLine(line);
74
+ });
75
+ child.on('error', (error) => {
76
+ if (this.generation === generation)
77
+ this.fail(error);
78
+ });
79
+ child.on('close', () => {
80
+ // 旧进程的 close 可能晚于新进程启动;generation 不匹配时不能污染新进程状态。
81
+ if (this.generation !== generation)
82
+ return;
83
+ this.closed = true;
84
+ this.fail(new Error('Claude 常驻进程已退出'));
85
+ });
86
+ return child;
87
+ }
88
+ send(prompt, hooks, timeoutMs = 10 * 60_000) {
89
+ if (this.active)
90
+ return Promise.reject(new Error('Claude 会话正忙'));
91
+ if (this.idleTimer) {
92
+ clearTimeout(this.idleTimer);
93
+ this.idleTimer = undefined;
94
+ }
95
+ const child = this.ensureStarted();
96
+ if (!child.stdin.writable)
97
+ return Promise.reject(new Error('Claude 会话 stdin 不可写'));
98
+ this.stepSeq = 0;
99
+ this.stepRefs.clear();
100
+ return new Promise((resolve, reject) => {
101
+ const timer = setTimeout(() => {
102
+ this.fail(new Error('Claude 常驻会话超时'));
103
+ }, timeoutMs);
104
+ this.active = { hooks, text: '', timer, resolve, reject };
105
+ child.stdin.write(`${JSON.stringify({
106
+ type: 'user',
107
+ message: { role: 'user', content: [{ type: 'text', text: prompt }] },
108
+ })}\n`);
109
+ });
110
+ }
111
+ close() {
112
+ if (this.idleTimer) {
113
+ clearTimeout(this.idleTimer);
114
+ this.idleTimer = undefined;
115
+ }
116
+ this.closed = true;
117
+ this.rl?.close();
118
+ if (this.child)
119
+ killCliProcess(this.child, this.options.command);
120
+ this.child?.stdin.destroy();
121
+ this.child?.stdout.destroy();
122
+ this.child?.stderr.destroy();
123
+ this.child?.unref();
124
+ this.active?.reject(new Error('Claude 常驻会话已关闭'));
125
+ this.active = undefined;
126
+ }
127
+ onLine(line) {
128
+ const trimmed = line.trim();
129
+ if (!trimmed)
130
+ return;
131
+ let event;
132
+ try {
133
+ event = JSON.parse(trimmed);
134
+ }
135
+ catch {
136
+ return;
137
+ }
138
+ const turn = this.active;
139
+ if (event['type'] === 'system' && typeof event['session_id'] === 'string') {
140
+ this.sessionId = event['session_id'];
141
+ turn?.hooks.onSession?.(this.sessionId);
142
+ return;
143
+ }
144
+ if (!turn)
145
+ return;
146
+ if (event['type'] === 'assistant') {
147
+ const message = event['message'];
148
+ const text = textOf(message);
149
+ if (text) {
150
+ turn.text += text;
151
+ turn.hooks.onLog('stdout', text);
152
+ }
153
+ const blocks = Array.isArray(message?.content) ? message.content : [];
154
+ for (const block of blocks) {
155
+ if (!block || typeof block !== 'object')
156
+ continue;
157
+ const item = block;
158
+ if (item['type'] !== 'tool_use' || typeof item['name'] !== 'string')
159
+ continue;
160
+ this.stepSeq += 1;
161
+ const ref = typeof item['id'] === 'string' ? item['id'] : undefined;
162
+ if (ref)
163
+ this.stepRefs.set(ref, this.stepSeq);
164
+ turn.hooks.onStep?.({
165
+ action: item['name'],
166
+ label: typeof item['input'] === 'object' ? JSON.stringify(item['input']).slice(0, 200) : undefined,
167
+ state: 'started',
168
+ ref,
169
+ seq: this.stepSeq,
170
+ });
171
+ }
172
+ return;
173
+ }
174
+ if (event['type'] === 'result') {
175
+ if (typeof event['session_id'] === 'string')
176
+ this.sessionId = event['session_id'];
177
+ const result = typeof event['result'] === 'string' ? event['result'] : turn.text;
178
+ clearTimeout(turn.timer);
179
+ this.active = undefined;
180
+ const resultError = claudeResultError(event);
181
+ if (resultError) {
182
+ turn.reject(resultError);
183
+ return;
184
+ }
185
+ turn.resolve({ exitCode: 0, result });
186
+ const idleMs = this.options.idleMs ?? 10 * 60_000;
187
+ if (idleMs > 0) {
188
+ this.idleTimer = setTimeout(() => {
189
+ this.idleTimer = undefined;
190
+ this.close();
191
+ }, idleMs);
192
+ this.idleTimer.unref?.();
193
+ }
194
+ }
195
+ }
196
+ fail(error) {
197
+ const turn = this.active;
198
+ this.active = undefined;
199
+ if (turn) {
200
+ clearTimeout(turn.timer);
201
+ turn.reject(error);
202
+ }
203
+ }
204
+ }