@ai-workbench/remote-agent 0.9.0-toolbridge.13 → 0.9.0-toolbridge.15

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/dist/broker.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { randomUUID } from 'node:crypto';
1
2
  import { closeCode } from "./close-diagnostics.js";
2
3
  import { spawn } from 'node:child_process';
3
4
  import { createHash } from 'node:crypto';
@@ -11,6 +12,86 @@ export class BrokerTransport {
11
12
  output;
12
13
  attachment;
13
14
  cursor = 0;
15
+ get lastSequence() { return this.cursor; }
16
+ receipt;
17
+ get inputReceipt() { return this.receipt; }
18
+ controlWait;
19
+ resendControl() { const wait = this.controlWait; if (wait && this.online) {
20
+ const child = this.attachment;
21
+ child.stdin.write(JSON.stringify({ type: wait.kind === 'discard' ? 'discard-input' : 'observe-input', messageId: wait.id }) + '\n', error => { if (error)
22
+ child.kill('SIGTERM'); });
23
+ } }
24
+ async controlMessage(kind, id) { await this.waitInput(); if (this.controlWait)
25
+ throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '原输入观察尚未结束', '串行消息回执'); const ready = Promise.withResolvers(); this.controlWait = { kind, id, ready }; this.resendControl(); try {
26
+ return await ready.promise;
27
+ }
28
+ finally {
29
+ this.controlWait = undefined;
30
+ } }
31
+ completeRestoredInput() { this.options.restoreInput = undefined; }
32
+ discardMessage(id) { return this.controlMessage('discard', id); }
33
+ observeMessage(id) { return this.controlMessage('observe', id); }
34
+ async resumeMessage(write) { const bytes = Buffer.from(write.wire, 'base64'), skip = this.inputSequence - write.baseSequence; if (skip < 0 || skip > write.chunks)
35
+ throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '原输入水位越界,没有重复写入', '原输入提交回执'); if (skip === write.chunks)
36
+ return; await this.send(bytes, { id: write.id, sha256: write.sha256, chunkBytes: write.chunkBytes, offset: skip * write.chunkBytes }); }
37
+ attachedId;
38
+ get attachmentId() { return this.attachedId; }
39
+ inputSequence = 0;
40
+ inputReady = true;
41
+ pendingInput;
42
+ recoveryTimer;
43
+ recoveryIntervalMs;
44
+ everReady = false;
45
+ get recovering() { return !!this.options.recoverDisconnect && !this.ended && !this.attached; }
46
+ get supportsRecovery() { return !!this.options.recoverDisconnect && this.options.inputProtocolVersion === 2; }
47
+ confirmReplay(generation) { if (this.options.inputProtocolVersion === 2 && generation === this.epoch && this.online) {
48
+ this.inputReady = true;
49
+ this.changed();
50
+ } }
51
+ recover() {
52
+ if (!this.supportsRecovery || this.ended || this.online)
53
+ return;
54
+ void (async () => {
55
+ try {
56
+ await this.joining?.catch(() => { });
57
+ if (!this.ended && !this.online)
58
+ await this.connect();
59
+ }
60
+ catch (error) {
61
+ if (this.ended)
62
+ return;
63
+ this.notice(error instanceof NeedError ? error.code : 'CONNECTION_LOST', '主机原轮暂未重新附着,等待原租约或连接恢复,没有重发输入。');
64
+ if (this.recoveryIntervalMs !== undefined && this.recoveryTimer === undefined) {
65
+ this.recoveryTimer = setTimeout(() => { this.recoveryTimer = undefined; this.recover(); }, this.recoveryIntervalMs);
66
+ this.recoveryTimer.unref();
67
+ }
68
+ }
69
+ })();
70
+ }
71
+ waitInput() {
72
+ if (this.online && this.inputReady)
73
+ return Promise.resolve();
74
+ if (this.ended)
75
+ return Promise.reject(this.failure ?? new NeedError('CONNECTION_LOST', '原执行流已结束', '原轮状态'));
76
+ return new Promise((resolve, reject) => { const off = this.onChange(() => { if (this.ended) {
77
+ off();
78
+ reject(this.failure ?? new NeedError('CONNECTION_LOST', '原执行流已结束', '原轮状态'));
79
+ }
80
+ else if (this.online && this.inputReady) {
81
+ off();
82
+ resolve();
83
+ } }); });
84
+ }
85
+ acknowledge(sequence) {
86
+ if (!Number.isSafeInteger(sequence) || sequence < 0)
87
+ throw new NeedError('BROKER_PROTOCOL_INVALID', '主机输入确认序号无效', '原broker输入水位');
88
+ if (sequence === this.inputSequence)
89
+ return;
90
+ if (!this.pendingInput || sequence !== this.pendingInput.sequence)
91
+ throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '主机输入水位不属于本客户端,未跳过或重发输入。', '原客户端唯一在途输入');
92
+ this.inputSequence = sequence;
93
+ this.pendingInput.ack.resolve();
94
+ }
14
95
  epoch = 0;
15
96
  attached = false;
16
97
  ended = false;
@@ -27,6 +108,9 @@ export class BrokerTransport {
27
108
  if (!Number.isSafeInteger(options.maxFrameBytes) || options.maxFrameBytes < 1)
28
109
  throw new NeedError('SETTINGS_REQUIRED', '我需要 brokerMaxFrameBytes', '管理员确认 brokerMaxFrameBytes');
29
110
  this.options = options;
111
+ this.cursor = options.initialSequence ?? 0;
112
+ this.inputSequence = options.restoreInput?.sequence ?? 0;
113
+ this.inputReady = options.inputProtocolVersion !== 2;
30
114
  this.lease.abort();
31
115
  this.readable = new ReadableStream({ start: c => { this.output = c; }, pull: () => { this.attachment?.stdout.resume(); }, cancel: reason => { this.close({ layer: 'broker', initiator: 'broker.reader-cancel', reason: closeCode(reason, 'BROKER_READER_CANCELLED'), action: 'close' }); } });
32
116
  this.writable = new WritableStream({ write: bytes => this.write(bytes), close: () => this.close({ layer: 'broker', initiator: 'broker.writer-close', reason: 'BROKER_WRITER_CLOSED', action: 'close' }), abort: reason => this.close({ layer: 'broker', initiator: 'broker.writer-abort', reason: closeCode(reason, 'BROKER_WRITER_ABORTED'), action: 'abort' }) });
@@ -35,7 +119,10 @@ export class BrokerTransport {
35
119
  get generation() { return this.epoch; }
36
120
  get signal() { return this.lease.signal; }
37
121
  get error() { return this.failure; }
38
- stopHeartbeat() { if (this.heartbeat !== undefined)
122
+ stopHeartbeat() { if (this.recoveryTimer !== undefined) {
123
+ clearTimeout(this.recoveryTimer);
124
+ this.recoveryTimer = undefined;
125
+ } if (this.heartbeat !== undefined)
39
126
  clearInterval(this.heartbeat); this.heartbeat = undefined; }
40
127
  authorizeResponse(id, generation, valid) { this.permits.set(JSON.stringify(id), { generation, valid }); }
41
128
  authorizePrompt(valid) { this.promptPermit = valid; }
@@ -52,6 +139,8 @@ export class BrokerTransport {
52
139
  this.ended = true;
53
140
  this.attached = false;
54
141
  this.lease.abort();
142
+ this.pendingInput?.ack.reject(error);
143
+ this.controlWait?.ready.reject(error);
55
144
  this.notice(error.code, error.message);
56
145
  this.changed();
57
146
  this.attachment?.kill('SIGTERM');
@@ -68,6 +157,8 @@ export class BrokerTransport {
68
157
  this.ended = true;
69
158
  this.attached = false;
70
159
  this.lease.abort();
160
+ this.pendingInput?.ack.reject(new NeedError('CONNECTION_LOST', '原轮已经关闭,输入未重发', '原轮状态'));
161
+ this.controlWait?.ready.reject(new NeedError('CONNECTION_LOST', '原流已结束,控制回执未确认', '原消息终态'));
71
162
  this.changed();
72
163
  this.attachment?.kill('SIGTERM');
73
164
  try {
@@ -86,7 +177,7 @@ export class BrokerTransport {
86
177
  return this.joining;
87
178
  }
88
179
  async attach() {
89
- const child = await this.options.attach();
180
+ const child = await this.options.attach(this.cursor);
90
181
  if (this.ended) {
91
182
  this.options.observeClose?.({ layer: 'broker', initiator: 'broker.late-attachment', reason: 'SESSION_ENDED', action: 'terminate' });
92
183
  child.kill('SIGTERM');
@@ -128,16 +219,78 @@ export class BrokerTransport {
128
219
  this.heartbeat.unref?.();
129
220
  }
130
221
  }
222
+ if (this.options.inputProtocolVersion === 2) {
223
+ const receipt = f.inputReceipt;
224
+ if (f.inputProtocolVersion !== 2 || !receipt || receipt.failed !== false)
225
+ throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '主机不能确认原输入字节水位,未重发输入。', 'inputProtocolVersion 2的有效回执');
226
+ if (this.options.messageInput && this.options.restoreInput && !this.pendingInput && this.inputSequence <= this.options.restoreInput.sequence + (this.options.restoreInput.pending?.chunks ?? 0)) {
227
+ const sequence = receipt.committedSequence, restore = this.options.restoreInput, pending = restore.pending, r = receipt;
228
+ if (!Number.isSafeInteger(sequence) || sequence < restore.sequence || sequence > restore.sequence + (pending?.chunks ?? 0) || sequence !== restore.sequence && (!pending || r.stagedMessageId !== pending.id && !(r.lastMessage?.id === pending.id && r.lastMessage?.sha256 === pending.sha256)))
229
+ throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '原输入水位不属于本轮,未跳过输入', '原消息身份及提交水位');
230
+ this.inputSequence = sequence;
231
+ }
232
+ else
233
+ this.acknowledge(receipt.committedSequence);
234
+ this.receipt = receipt;
235
+ if (this.options.messageInput && f.messageInputProtocolVersion !== 1)
236
+ throw new NeedError('BROKER_PROTOCOL_INVALID', '主机缺少完整消息暂存协议', 'messageInputProtocolVersion 1');
237
+ if (receipt.pendingSequence !== null && receipt.pendingSequence !== this.pendingInput?.sequence && !(this.options.restoreInput?.pending && receipt.pendingSequence === this.options.restoreInput.pending.baseSequence + this.options.restoreInput.pending.chunks && receipt.stagedMessageId === this.options.restoreInput.pending.id && receipt.stagedSha256 === this.options.restoreInput.pending.sha256))
238
+ throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '主机在途输入不属于本客户端', '原客户端在途输入');
239
+ if (typeof f.attachmentId !== 'string' || !f.attachmentId)
240
+ throw new NeedError('BROKER_PROTOCOL_INVALID', '主机缺少写者实例标识', '本次attachmentId');
241
+ this.attachedId = f.attachmentId;
242
+ this.inputReady = false;
243
+ }
244
+ const lifecycle = f.lifecycle;
245
+ if (this.supportsRecovery && Number.isSafeInteger(lifecycle?.heartbeatIntervalMs) && lifecycle.heartbeatIntervalMs > 0)
246
+ this.recoveryIntervalMs = lifecycle.heartbeatIntervalMs;
131
247
  ready = true;
248
+ this.everReady = true;
132
249
  this.attached = true;
133
250
  this.lease = new AbortController();
134
251
  this.changed();
252
+ this.resendControl();
135
253
  connected.resolve();
136
254
  return;
137
255
  }
256
+ if (f.type === 'input-discarded' || f.type === 'input-observed') {
257
+ const wait = this.controlWait;
258
+ if (!wait || f.messageId !== wait.id)
259
+ throw new NeedError('BROKER_PROTOCOL_INVALID', '输入控制回执不匹配', '原消息标识');
260
+ this.receipt = f.inputReceipt;
261
+ const r = f.inputReceipt;
262
+ if (!Number.isSafeInteger(r?.committedSequence) || r.committedSequence < this.inputSequence)
263
+ throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '输入控制水位倒退', '原消息终态');
264
+ this.inputSequence = r.committedSequence;
265
+ wait.ready.resolve(r);
266
+ return;
267
+ }
268
+ if (f.type === 'input-ack') {
269
+ if (this.options.inputProtocolVersion !== 2)
270
+ throw new NeedError('BROKER_PROTOCOL_INVALID', '未协商输入确认', 'inputProtocolVersion 2');
271
+ this.acknowledge(f.sequence);
272
+ return;
273
+ }
274
+ if (f.type === 'replay-complete') {
275
+ if (this.options.inputProtocolVersion !== 2 || f.sequence !== this.cursor)
276
+ throw new NeedError('REPLAY_GAP', '原轮回放水位未连续', '完整原轮回放');
277
+ this.output.enqueue(Buffer.from(JSON.stringify({ jsonrpc: '2.0', method: '_aw/broker-replay-complete', params: { generation: this.epoch, pendingClientRequests: f.pendingClientRequests } }) + '\n'));
278
+ return;
279
+ }
138
280
  if (f.type === 'error') {
139
281
  const code = typeof f.code === 'string' && /^[A-Z][A-Z0-9_]{0,63}$/.test(f.code) ? f.code : 'BROKER_PROTOCOL_INVALID';
140
- const error = new NeedError(code, '主机会话无法续接(' + code + ');没有重放输入或代答审批', '恢复或显式结束原会话');
282
+ const error = new NeedError(code, f.reason === 'OUTPUT_JOURNAL_FAILED' ? '主机输出持久保存失败(' + String(f.systemCode) + '),原轮结果未确认,没有重放。' : '主机会话无法续接(' + code + ');没有重放输入或代答审批', '恢复或显式结束原会话');
283
+ if (ready && code === 'ATTACH_LEASE_EXPIRED' && this.supportsRecovery) {
284
+ attemptClosed = true;
285
+ this.stopHeartbeat();
286
+ this.attached = false;
287
+ this.inputReady = false;
288
+ this.lease.abort();
289
+ this.changed();
290
+ child.kill('SIGTERM');
291
+ this.recover();
292
+ return;
293
+ }
141
294
  if (!ready && f.code === 'ATTACH_BUSY') {
142
295
  this.options.observeClose?.({ layer: 'broker', initiator: 'broker.attach-busy', reason: error.code, action: 'terminate' });
143
296
  attemptClosed = true;
@@ -147,6 +300,17 @@ export class BrokerTransport {
147
300
  }
148
301
  throw error;
149
302
  }
303
+ if (f.type === 'exit' && this.supportsRecovery) {
304
+ this.stopHeartbeat();
305
+ this.ended = true;
306
+ this.attached = false;
307
+ this.lease.abort();
308
+ this.pendingInput?.ack.reject(new NeedError('AGENT_EXITED', '主机进程已退出,未重发输入', '原轮结果'));
309
+ this.controlWait?.ready.reject(new NeedError('AGENT_EXITED', '主机进程已退出,输入控制回执未确认', '原消息终态'));
310
+ this.changed();
311
+ this.output.close();
312
+ return;
313
+ }
150
314
  if (f.type === 'exit') {
151
315
  connected.reject(new NeedError('AGENT_EXITED', '主机 agent 已退出', '重新建立会话'));
152
316
  this.fail(new NeedError('AGENT_EXITED', '主机 agent 已退出,退出状态不代表本轮完成', '确认主机状态'));
@@ -201,11 +365,18 @@ export class BrokerTransport {
201
365
  this.attached = false;
202
366
  this.lease.abort();
203
367
  this.changed();
368
+ this.inputReady = this.options.inputProtocolVersion !== 2;
369
+ if (this.supportsRecovery && this.everReady) {
370
+ if (!ready)
371
+ connected.reject(new NeedError('BROKER_ATTACH_FAILED', '原轮暂未重新附着,继续等待原租约或连接', '原主机连接'));
372
+ else
373
+ this.recover();
374
+ return;
375
+ }
204
376
  if (!ready) {
205
377
  fatal(new NeedError('BROKER_ATTACH_FAILED', '主机会话附着失败;根因未查明', '有效的原员工 SSH/broker 连接'));
206
378
  return;
207
379
  }
208
- // A real disconnect ends this turn; the next turn starts a new agent.
209
380
  fatal(new NeedError('CONNECTION_LOST', '主机会话连接已中断,恢复后可在原会话继续。', '当前主机连接'));
210
381
  };
211
382
  child.once('error', () => detached({ layer: 'broker', initiator: 'broker.attachment-error', reason: 'BROKER_ATTACHMENT_ERROR', action: 'failure' }));
@@ -213,7 +384,9 @@ export class BrokerTransport {
213
384
  return connected.promise.finally(off);
214
385
  }
215
386
  write(bytes) { return this.exclusive(() => this.send(bytes)); }
216
- async send(bytes) {
387
+ async send(bytes, resume) {
388
+ if (this.supportsRecovery)
389
+ await this.waitInput();
217
390
  if (!this.online || !this.attachment)
218
391
  throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '连接不在线,输入没有排队或重放', '恢复连接并确认原会话状态');
219
392
  let response;
@@ -224,7 +397,7 @@ export class BrokerTransport {
224
397
  throw new NeedError('ACP_INPUT_INVALID', 'ACP 输出不是一条完整 JSON 消息', '有效的 ACP SDK 字节输出');
225
398
  }
226
399
  const selected = response.result?.outcome?.outcome === 'selected';
227
- const prompt = response.method === 'session/prompt', promptPermit = prompt ? this.promptPermit : undefined;
400
+ const prompt = response.method === 'session/prompt' || response.method === '_session/steering', promptPermit = prompt ? this.promptPermit : undefined;
228
401
  const generation = this.epoch;
229
402
  const child = this.attachment;
230
403
  const permit = this.permits.get(JSON.stringify(response.id));
@@ -261,15 +434,70 @@ export class BrokerTransport {
261
434
  if (prompt && this.promptPermit === promptPermit)
262
435
  this.promptPermit = undefined;
263
436
  const chunks = [];
437
+ let chunkBytes = resume?.chunkBytes ?? bytes.byteLength;
438
+ const message = this.options.messageInput ? resume ?? { id: randomUUID(), sha256: createHash('sha256').update(bytes).digest('hex') } : undefined;
264
439
  if (this.options.leased) {
265
- const size = Math.floor((this.options.controlMaxBytes - Buffer.byteLength(JSON.stringify({ type: 'input', data: '' }))) / 4) * 3;
440
+ const size = Math.floor((this.options.controlMaxBytes - Buffer.byteLength(JSON.stringify({ type: 'input', data: '', ...(this.options.inputProtocolVersion === 2 ? { sequence: Number.MAX_SAFE_INTEGER } : {}), ...(message ? { messageId: message.id, final: false, sha256: message.sha256 } : {}) }))) / 4) * 3;
266
441
  if (size < 1)
267
442
  throw new NeedError('LEASE_CAPACITY_INVALID', '主机会话容量无法承载输入', '有效controlMaxBytes');
268
- for (let offset = 0; offset < bytes.byteLength; offset += size)
269
- chunks.push(Buffer.from(JSON.stringify({ type: 'input', data: Buffer.from(bytes.subarray(offset, offset + size)).toString('base64') }) + '\n'));
443
+ chunkBytes = resume?.chunkBytes ?? size;
444
+ if (this.options.inputProtocolVersion !== 2)
445
+ for (let offset = 0; offset < bytes.byteLength; offset += size)
446
+ chunks.push(Buffer.from(JSON.stringify({ type: 'input', data: Buffer.from(bytes.subarray(offset, offset + size)).toString('base64') }) + '\n'));
270
447
  }
271
448
  else
272
449
  chunks.push(Buffer.from(bytes));
450
+ if (message && !resume)
451
+ await this.options.beforeMessage?.(bytes, { ...message, chunkBytes, baseSequence: this.inputSequence });
452
+ if (this.options.inputProtocolVersion === 2) {
453
+ try {
454
+ for (let offset = resume?.offset ?? 0; offset < bytes.byteLength; offset += chunkBytes) {
455
+ const chunk = bytes.subarray(offset, offset + chunkBytes);
456
+ await this.waitInput();
457
+ if (prompt)
458
+ currentPrompt();
459
+ const sequence = this.inputSequence + 1, ack = Promise.withResolvers();
460
+ void ack.promise.catch(() => { });
461
+ const frame = Buffer.from(JSON.stringify({ type: 'input', sequence, data: Buffer.from(chunk).toString('base64'), ...(message ? { messageId: message.id, sha256: message.sha256, final: offset + chunkBytes >= bytes.byteLength } : {}) }) + '\n');
462
+ const pending = { sequence, frame, ack };
463
+ this.pendingInput = pending;
464
+ try {
465
+ while (this.inputSequence < sequence) {
466
+ await this.waitInput();
467
+ if (this.inputSequence >= sequence)
468
+ break;
469
+ if (prompt)
470
+ currentPrompt();
471
+ if (selected && (generation !== this.epoch || !policyCurrent()))
472
+ throw new NeedError('APPROVAL_STALE', '断线后原批准不再重发,原轮结果可能未知。', '当前代次的审批许可');
473
+ const current = this.attachment, epoch = this.epoch, detached = Promise.withResolvers();
474
+ const off = this.onChange(() => { if (this.epoch !== epoch || !this.online)
475
+ detached.resolve(); });
476
+ try {
477
+ current.stdin.write(frame, error => { if (error)
478
+ current.kill('SIGTERM'); });
479
+ await Promise.race([ack.promise, detached.promise]);
480
+ }
481
+ finally {
482
+ off();
483
+ }
484
+ }
485
+ }
486
+ finally {
487
+ if (this.pendingInput === pending)
488
+ this.pendingInput = undefined;
489
+ }
490
+ }
491
+ if (message)
492
+ await this.options.afterMessage?.(this.inputSequence);
493
+ return;
494
+ }
495
+ catch (error) {
496
+ const known = error instanceof NeedError ? error : new NeedError('INPUT_DELIVERY_UNCONFIRMED', '原输入结果未知,没有重发', '原轮输入确认');
497
+ this.fail(known);
498
+ throw known;
499
+ }
500
+ }
273
501
  for (const chunk of chunks) {
274
502
  if (!this.online || this.attachment !== child || this.epoch !== generation)
275
503
  throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '分块发送期间断线,未重放输入', '原主机连接');
@@ -125,6 +125,18 @@ export function createClaudeLocalProvider(options) {
125
125
  if (options.getConnect() !== api || options.getNetwork() !== network)
126
126
  throw failure('EMPLOYEE_CONTEXT_CHANGED');
127
127
  const underlying = base, endpoint = mcp;
128
+ let localClosing;
129
+ const modelLifetime = new AbortController();
130
+ const transientLease = () => underlying.broker?.supportsRecovery && lease.signal.aborted && ['CONNECTION_LOST', 'EMPLOYEE_ENDPOINT_UNAVAILABLE'].includes(closeCode(lease.signal.reason));
131
+ const closeLocal = (cause) => localClosing ??= Promise.resolve().then(async () => {
132
+ for (const operation of [() => endpoint.close(cause), () => row.lease.close(cause)])
133
+ try {
134
+ await operation();
135
+ }
136
+ catch {
137
+ console.warn('CLAUDE_CLEANUP_FAILED');
138
+ }
139
+ });
128
140
  const close = (detach, cause = { layer: 'runtime', initiator: detach ? 'claude.runtime-detach' : 'claude.runtime-dispose', reason: detach ? 'RUNTIME_DETACH' : 'RUNTIME_DISPOSE', action: detach ? 'detach' : 'dispose' }) => {
129
141
  // Unlink synchronously. A slow/failed cleanup must not hold the next round.
130
142
  if (entries.get(request.sessionId) === row)
@@ -138,16 +150,25 @@ export function createClaudeLocalProvider(options) {
138
150
  catch {
139
151
  console.warn('CLAUDE_CLEANUP_FAILED');
140
152
  } };
141
- await clean(() => endpoint.close({ layer: 'relay', initiator: 'claude.cleanup-mcp', reason: 'RUNTIME_CLEANUP', action: 'close' }));
142
- await clean(() => row.lease.close({ layer: 'endpoint', initiator: 'claude.cleanup-lease', reason: 'RUNTIME_CLEANUP', action: 'close' }));
153
+ await clean(() => closeLocal(cause));
143
154
  await clean(() => detach ? underlying.detach?.(cause) : underlying.dispose?.(cause));
144
155
  });
145
156
  };
146
- const executionSignal = AbortSignal.any([lease.signal, ...mcp.signal ? [mcp.signal] : []]);
147
- row.runtime = { ...underlying, closeDiagnostics, cwd: workspace.directory.path, details, connection: { ...connection }, binding: { bindingId: item.bindingId, workspaceId: workspace.workspaceId, revision: state.revision }, execution: { hostCwd: target.session.root, routing: mcp.routing, notice: NOTICE, signal: executionSignal, scope: { source: 'local', cwd: workspace.directory.path, hostCwd: target.session.root, uid: lease.target.endpoint.remoteUid, claudeAcpVersion: '0.94.0', sdkVersion: '0.3.303', unsupported: ['subagents', 'internal-direct-calls', 'binary-read', 'background-shell'] }, validate: async (signal) => { signal?.throwIfAborted(); executionSignal.throwIfAborted(); }, beginTurn: async (signal) => { signal?.throwIfAborted(); executionSignal.throwIfAborted(); if (row.closing || row.active)
157
+ const executionSignal = modelLifetime.signal;
158
+ row.runtime = { ...underlying, localDirectory: { ...workspace.directory }, closeDiagnostics, cwd: workspace.directory.path, details, connection: { ...connection }, binding: { bindingId: item.bindingId, workspaceId: workspace.workspaceId, revision: state.revision }, execution: { hostCwd: target.session.root, routing: mcp.routing, notice: NOTICE, signal: executionSignal, scope: { source: 'local', cwd: workspace.directory.path, hostCwd: target.session.root, uid: lease.target.endpoint.remoteUid, claudeAcpVersion: '0.94.0', sdkVersion: '0.3.303', unsupported: ['subagents', 'internal-direct-calls', 'binary-read', 'background-shell'] }, validate: async (signal) => { signal?.throwIfAborted(); lease.signal.throwIfAborted(); executionSignal.throwIfAborted(); }, beginTurn: async (signal) => { signal?.throwIfAborted(); lease.signal.throwIfAborted(); executionSignal.throwIfAborted(); if (row.closing || row.active)
148
159
  throw failure('TURN_BUSY'); row.active = { signal, details: row.details }; }, endTurn: () => { row.active = undefined; } }, dispose: cause => close(false, cause), detach: cause => close(true, cause) };
149
160
  entries.set(request.sessionId, row);
150
- lease.signal.addEventListener('abort', () => { void close(false, { layer: 'endpoint', initiator: 'claude.lease-abort', reason: closeCode(lease?.signal.reason, 'EMPLOYEE_CONTEXT_CHANGED'), action: 'abort' }).catch(() => console.warn('CLAUDE_CLEANUP_FAILED')); }, { once: true });
161
+ const endpointAborted = () => {
162
+ const cause = { layer: 'endpoint', initiator: 'claude.lease-abort', reason: closeCode(lease?.signal.reason, 'EMPLOYEE_CONTEXT_CHANGED'), action: 'abort' };
163
+ if (transientLease()) {
164
+ void closeLocal(cause);
165
+ return;
166
+ }
167
+ modelLifetime.abort(lease?.signal.reason ?? mcp?.signal?.reason);
168
+ void close(false, cause).catch(() => console.warn('CLAUDE_CLEANUP_FAILED'));
169
+ };
170
+ lease.signal.addEventListener('abort', endpointAborted, { once: true });
171
+ mcp.signal?.addEventListener('abort', endpointAborted, { once: true });
151
172
  if (lease.signal.aborted) {
152
173
  await close(false, { layer: 'endpoint', initiator: 'claude.open-aborted', reason: closeCode(lease.signal.reason, 'EMPLOYEE_CONTEXT_CHANGED'), action: 'abort' });
153
174
  throw failure('EMPLOYEE_CONTEXT_CHANGED');
@@ -0,0 +1,14 @@
1
+ import { type BrokerIo } from './broker.ts';
2
+ import { type ColdRound, type ColdStore } from './cold-store.ts';
3
+ import { type StreamChunk, type ContentBlock, type TokenUsage } from '@deepseek-ai/dsh-llm';
4
+ export interface ColdPrefix {
5
+ blocks: readonly ContentBlock[];
6
+ usage?: TokenUsage;
7
+ }
8
+ export declare function recoverColdProtocol(record: ColdRound, store: ColdStore, prefix: ColdPrefix, options: {
9
+ io: BrokerIo;
10
+ maxFrameBytes: number;
11
+ maxMessageBytes: number;
12
+ signal?: AbortSignal;
13
+ markerId?: string;
14
+ }): AsyncGenerator<StreamChunk>;