@ai-workbench/remote-agent 0.9.0-toolbridge.3 → 0.9.0-toolbridge.31

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 (56) hide show
  1. package/README.md +36 -7
  2. package/dist/acp.d.ts +23 -3
  3. package/dist/acp.js +106 -21
  4. package/dist/broker-runtime.d.ts +2 -0
  5. package/dist/broker-runtime.js +60 -3
  6. package/dist/broker.d.ts +56 -1
  7. package/dist/broker.js +310 -11
  8. package/dist/claude-local.js +26 -5
  9. package/dist/client.js +1 -1
  10. package/dist/close-diagnostics.d.ts +1 -1
  11. package/dist/close-diagnostics.js +1 -1
  12. package/dist/cold-protocol.d.ts +17 -0
  13. package/dist/cold-protocol.js +399 -0
  14. package/dist/cold-recovery.d.ts +62 -0
  15. package/dist/cold-recovery.js +595 -0
  16. package/dist/cold-store.d.ts +99 -0
  17. package/dist/cold-store.js +29 -0
  18. package/dist/conversation-details.js +21 -8
  19. package/dist/employee-endpoint.js +15 -1
  20. package/dist/employee-mcp.js +1 -1
  21. package/dist/employee-native.js +7 -1
  22. package/dist/employee-provider.d.ts +2 -0
  23. package/dist/employee-provider.js +46 -11
  24. package/dist/employee-relay.js +148 -1
  25. package/dist/employee-shell.d.ts +2 -0
  26. package/dist/employee-shell.js +22 -19
  27. package/dist/employee-startup.d.ts +18 -0
  28. package/dist/employee-startup.js +95 -0
  29. package/dist/employee-tools.js +2 -2
  30. package/dist/employee-workspace.d.ts +20 -4
  31. package/dist/employee-workspace.js +26 -5
  32. package/dist/index.d.ts +12 -3
  33. package/dist/index.js +223 -51
  34. package/dist/input.js +4 -1
  35. package/dist/live-steering.d.ts +46 -0
  36. package/dist/live-steering.js +45 -0
  37. package/dist/mapping.d.ts +4 -24
  38. package/dist/mapping.js +11 -65
  39. package/dist/model-catalog.d.ts +2 -0
  40. package/dist/model-catalog.js +5 -1
  41. package/dist/preflight-diagnostic.js +1 -1
  42. package/dist/presentation.js +1 -0
  43. package/dist/provider.d.ts +16 -0
  44. package/dist/provider.js +66 -33
  45. package/dist/rpc-namespace.js +16 -2
  46. package/dist/session-source.d.ts +3 -1
  47. package/dist/session-source.js +2 -1
  48. package/dist/startup-timing.d.ts +14 -0
  49. package/dist/startup-timing.js +34 -0
  50. package/dist/toolbridge-loop.d.ts +3 -2
  51. package/dist/toolbridge-loop.js +4 -2
  52. package/dist/toolbridge-table.d.ts +4 -3
  53. package/dist/toolbridge-table.js +14 -5
  54. package/dist/toolbridge.d.ts +1 -1
  55. package/dist/toolbridge.js +23 -4
  56. package/package.json +23 -16
package/dist/broker.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { ColdWrite } from './cold-store.ts';
1
2
  import { type CloseCause, type CloseObserver } from './close-diagnostics.ts';
2
3
  import { type ChildProcessWithoutNullStreams } from 'node:child_process';
3
4
  import { NeedError, type Need } from './remote.ts';
@@ -9,7 +10,23 @@ export interface BrokerOptions {
9
10
  instanceId?: string;
10
11
  leased?: boolean;
11
12
  controlMaxBytes?: number;
12
- attach: () => Promise<Attachment>;
13
+ attach: (after?: number) => Promise<Attachment>;
14
+ inputProtocolVersion?: 2;
15
+ recoverDisconnect?: boolean;
16
+ messageInput?: boolean;
17
+ outputOrigins?: boolean;
18
+ initialSequence?: number;
19
+ restoreInput?: {
20
+ sequence: number;
21
+ pending?: ColdWrite;
22
+ };
23
+ beforeMessage?: (bytes: Uint8Array, message: {
24
+ id: string;
25
+ sha256: string;
26
+ chunkBytes: number;
27
+ baseSequence: number;
28
+ }) => Promise<void>;
29
+ afterMessage?: (sequence: number) => Promise<void>;
13
30
  onNeed?: (need: Need) => void;
14
31
  }
15
32
  /** One byte stream / SDK app over one SSH attachment of a new agent. Input is never replayed. */
@@ -20,6 +37,44 @@ export declare class BrokerTransport {
20
37
  private output;
21
38
  private attachment?;
22
39
  private cursor;
40
+ get lastSequence(): number;
41
+ private originKey;
42
+ private originNonce;
43
+ private originPartial;
44
+ private originFinalSequence;
45
+ private originMarker;
46
+ private stdout;
47
+ withOutputOrigins<T extends {
48
+ readable: ReadableStream<any>;
49
+ writable: WritableStream<any>;
50
+ }>(stream: T): T;
51
+ stripOutputOrigin<T>(notification: T): {
52
+ notification: T;
53
+ sequence?: number;
54
+ };
55
+ private promptReceipt?;
56
+ get promptDelivered(): boolean | undefined;
57
+ private receipt;
58
+ get inputReceipt(): any;
59
+ private controlWait?;
60
+ private resendControl;
61
+ private controlMessage;
62
+ completeRestoredInput(): void;
63
+ discardMessage(id: string): Promise<any>;
64
+ observeMessage(id: string): Promise<any>;
65
+ resumeMessage(write: ColdWrite): Promise<void>;
66
+ private inputSequence;
67
+ private inputReady;
68
+ private pendingInput?;
69
+ private recoveryTimer?;
70
+ private recoveryIntervalMs?;
71
+ private everReady;
72
+ get recovering(): boolean;
73
+ get supportsRecovery(): boolean;
74
+ confirmReplay(generation: unknown): void;
75
+ private recover;
76
+ private waitInput;
77
+ private acknowledge;
23
78
  private epoch;
24
79
  private attached;
25
80
  private ended;
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,142 @@ export class BrokerTransport {
11
12
  output;
12
13
  attachment;
13
14
  cursor = 0;
15
+ get lastSequence() { return this.cursor; }
16
+ originKey = 'ai-workbench/output-origin/' + randomUUID();
17
+ originNonce = randomUUID();
18
+ originPartial = false;
19
+ originFinalSequence = 0;
20
+ originMarker(sequence) { return Buffer.from(JSON.stringify(['aw-origin', sequence, this.originNonce]) + '\n'); }
21
+ stdout(bytes, sequence) {
22
+ if (!this.options.outputOrigins) {
23
+ this.output.enqueue(bytes);
24
+ return;
25
+ }
26
+ this.originFinalSequence = sequence;
27
+ let start = 0, newline;
28
+ while ((newline = bytes.indexOf(10, start)) >= 0) {
29
+ const part = bytes.subarray(start, newline + 1);
30
+ if (part.some(byte => ![9, 10, 13, 32].includes(byte)))
31
+ this.originPartial = true;
32
+ this.output.enqueue(part);
33
+ if (this.originPartial)
34
+ this.output.enqueue(this.originMarker(sequence));
35
+ this.originPartial = false;
36
+ start = newline + 1;
37
+ }
38
+ if (start < bytes.length) {
39
+ const part = bytes.subarray(start);
40
+ if (part.some(byte => ![9, 13, 32].includes(byte)))
41
+ this.originPartial = true;
42
+ this.output.enqueue(part);
43
+ }
44
+ }
45
+ withOutputOrigins(stream) {
46
+ if (!this.options.outputOrigins)
47
+ return stream;
48
+ let pending;
49
+ return { ...stream, readable: stream.readable.pipeThrough(new TransformStream({ transform: (message, controller) => {
50
+ if (Array.isArray(message) && message[0] === 'aw-origin' && message[2] === this.originNonce) {
51
+ if (pending === undefined)
52
+ throw new NeedError('BROKER_PROTOCOL_INVALID', '输出消息来源边界不完整', '原broker输出序号');
53
+ const sequence = message[1];
54
+ const annotate = (value) => Array.isArray(value) ? value.map(annotate) : sequence !== null && value?.method === 'session/update' && value.params && typeof value.params === 'object' ? { ...value, params: { ...value.params, _meta: { ...value.params._meta, [this.originKey]: sequence } } } : value;
55
+ pending = annotate(pending);
56
+ controller.enqueue(pending);
57
+ pending = undefined;
58
+ return;
59
+ }
60
+ if (pending !== undefined)
61
+ throw new NeedError('BROKER_PROTOCOL_INVALID', '输出消息缺少来源边界', '原broker输出序号');
62
+ pending = message;
63
+ }, flush: () => { if (pending !== undefined)
64
+ throw new NeedError('BROKER_PROTOCOL_INVALID', '输出消息来源未确认', '原broker输出序号'); } })) };
65
+ }
66
+ stripOutputOrigin(notification) { const raw = notification, meta = raw?._meta, sequence = meta?.[this.originKey]; if (sequence === undefined)
67
+ return { notification }; if (!Number.isSafeInteger(sequence) || sequence < 1)
68
+ throw new NeedError('BROKER_PROTOCOL_INVALID', '输出序号无效', '原broker输出序号'); const clean = { ...meta }; delete clean[this.originKey]; const copy = { ...raw }; if (Object.keys(clean).length)
69
+ copy._meta = clean;
70
+ else
71
+ delete copy._meta; return { notification: copy, sequence }; }
72
+ promptReceipt;
73
+ get promptDelivered() { return this.promptReceipt; }
74
+ receipt;
75
+ get inputReceipt() { return this.receipt; }
76
+ controlWait;
77
+ resendControl() { const wait = this.controlWait; if (wait && this.online) {
78
+ const child = this.attachment;
79
+ child.stdin.write(JSON.stringify({ type: wait.kind === 'discard' ? 'discard-input' : 'observe-input', messageId: wait.id }) + '\n', error => { if (error)
80
+ child.kill('SIGTERM'); });
81
+ } }
82
+ async controlMessage(kind, id) { await this.waitInput(); if (this.controlWait)
83
+ throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '原输入观察尚未结束', '串行消息回执'); const ready = Promise.withResolvers(); this.controlWait = { kind, id, ready }; this.resendControl(); try {
84
+ return await ready.promise;
85
+ }
86
+ finally {
87
+ this.controlWait = undefined;
88
+ } }
89
+ completeRestoredInput() { this.options.restoreInput = undefined; }
90
+ discardMessage(id) { return this.controlMessage('discard', id); }
91
+ observeMessage(id) { return this.controlMessage('observe', id); }
92
+ async resumeMessage(write) { const bytes = Buffer.from(write.wire, 'base64'), skip = this.inputSequence - write.baseSequence; if (skip < 0 || skip > write.chunks)
93
+ throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '原输入水位越界,没有重复写入', '原输入提交回执'); if (skip === write.chunks)
94
+ return; await this.send(bytes, { id: write.id, sha256: write.sha256, chunkBytes: write.chunkBytes, offset: skip * write.chunkBytes }); }
95
+ inputSequence = 0;
96
+ inputReady = true;
97
+ pendingInput;
98
+ recoveryTimer;
99
+ recoveryIntervalMs;
100
+ everReady = false;
101
+ get recovering() { return !!this.options.recoverDisconnect && !this.ended && !this.attached; }
102
+ get supportsRecovery() { return !!this.options.recoverDisconnect && this.options.inputProtocolVersion === 2; }
103
+ confirmReplay(generation) { if (this.options.inputProtocolVersion === 2 && generation === this.epoch && this.online) {
104
+ this.inputReady = true;
105
+ this.changed();
106
+ } }
107
+ recover() {
108
+ if (!this.supportsRecovery || this.ended || this.online)
109
+ return;
110
+ void (async () => {
111
+ try {
112
+ await this.joining?.catch(() => { });
113
+ if (!this.ended && !this.online)
114
+ await this.connect();
115
+ }
116
+ catch (error) {
117
+ if (this.ended)
118
+ return;
119
+ this.notice(error instanceof NeedError ? error.code : 'CONNECTION_LOST', '主机原轮暂未重新附着,等待原租约或连接恢复,没有重发输入。');
120
+ if (this.recoveryIntervalMs !== undefined && this.recoveryTimer === undefined) {
121
+ this.recoveryTimer = setTimeout(() => { this.recoveryTimer = undefined; this.recover(); }, this.recoveryIntervalMs);
122
+ this.recoveryTimer.unref();
123
+ }
124
+ }
125
+ })();
126
+ }
127
+ waitInput() {
128
+ if (this.online && this.inputReady)
129
+ return Promise.resolve();
130
+ if (this.ended)
131
+ return Promise.reject(this.failure ?? new NeedError('CONNECTION_LOST', '原执行流已结束', '原轮状态'));
132
+ return new Promise((resolve, reject) => { const off = this.onChange(() => { if (this.ended) {
133
+ off();
134
+ reject(this.failure ?? new NeedError('CONNECTION_LOST', '原执行流已结束', '原轮状态'));
135
+ }
136
+ else if (this.online && this.inputReady) {
137
+ off();
138
+ resolve();
139
+ } }); });
140
+ }
141
+ acknowledge(sequence) {
142
+ if (!Number.isSafeInteger(sequence) || sequence < 0)
143
+ throw new NeedError('BROKER_PROTOCOL_INVALID', '主机输入确认序号无效', '原broker输入水位');
144
+ if (sequence === this.inputSequence)
145
+ return;
146
+ if (!this.pendingInput || sequence !== this.pendingInput.sequence)
147
+ throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '主机输入水位不属于本客户端,未跳过或重发输入。', '原客户端唯一在途输入');
148
+ this.inputSequence = sequence;
149
+ this.pendingInput.ack.resolve();
150
+ }
14
151
  epoch = 0;
15
152
  attached = false;
16
153
  ended = false;
@@ -27,6 +164,9 @@ export class BrokerTransport {
27
164
  if (!Number.isSafeInteger(options.maxFrameBytes) || options.maxFrameBytes < 1)
28
165
  throw new NeedError('SETTINGS_REQUIRED', '我需要 brokerMaxFrameBytes', '管理员确认 brokerMaxFrameBytes');
29
166
  this.options = options;
167
+ this.cursor = options.initialSequence ?? 0;
168
+ this.inputSequence = options.restoreInput?.sequence ?? 0;
169
+ this.inputReady = options.inputProtocolVersion !== 2;
30
170
  this.lease.abort();
31
171
  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
172
  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 +175,10 @@ export class BrokerTransport {
35
175
  get generation() { return this.epoch; }
36
176
  get signal() { return this.lease.signal; }
37
177
  get error() { return this.failure; }
38
- stopHeartbeat() { if (this.heartbeat !== undefined)
178
+ stopHeartbeat() { if (this.recoveryTimer !== undefined) {
179
+ clearTimeout(this.recoveryTimer);
180
+ this.recoveryTimer = undefined;
181
+ } if (this.heartbeat !== undefined)
39
182
  clearInterval(this.heartbeat); this.heartbeat = undefined; }
40
183
  authorizeResponse(id, generation, valid) { this.permits.set(JSON.stringify(id), { generation, valid }); }
41
184
  authorizePrompt(valid) { this.promptPermit = valid; }
@@ -52,6 +195,8 @@ export class BrokerTransport {
52
195
  this.ended = true;
53
196
  this.attached = false;
54
197
  this.lease.abort();
198
+ this.pendingInput?.ack.reject(error);
199
+ this.controlWait?.ready.reject(error);
55
200
  this.notice(error.code, error.message);
56
201
  this.changed();
57
202
  this.attachment?.kill('SIGTERM');
@@ -68,6 +213,8 @@ export class BrokerTransport {
68
213
  this.ended = true;
69
214
  this.attached = false;
70
215
  this.lease.abort();
216
+ this.pendingInput?.ack.reject(new NeedError('CONNECTION_LOST', '原轮已经关闭,输入未重发', '原轮状态'));
217
+ this.controlWait?.ready.reject(new NeedError('CONNECTION_LOST', '原流已结束,控制回执未确认', '原消息终态'));
71
218
  this.changed();
72
219
  this.attachment?.kill('SIGTERM');
73
220
  try {
@@ -86,7 +233,7 @@ export class BrokerTransport {
86
233
  return this.joining;
87
234
  }
88
235
  async attach() {
89
- const child = await this.options.attach();
236
+ const child = await this.options.attach(this.cursor);
90
237
  if (this.ended) {
91
238
  this.options.observeClose?.({ layer: 'broker', initiator: 'broker.late-attachment', reason: 'SESSION_ENDED', action: 'terminate' });
92
239
  child.kill('SIGTERM');
@@ -95,7 +242,10 @@ export class BrokerTransport {
95
242
  this.attachment = child;
96
243
  this.epoch++;
97
244
  const generation = this.epoch;
98
- child.stderr.resume();
245
+ // Before ready, S reports a vanished broker as one JSON line on stderr; nothing else is read from it.
246
+ let diagnostics = Buffer.alloc(0);
247
+ child.stderr.on('data', (b) => { if (!ready && diagnostics.length <= (this.options.controlMaxBytes ?? 4096))
248
+ diagnostics = Buffer.concat([diagnostics, b]); });
99
249
  child.stdin.on('error', () => { });
100
250
  let partial = Buffer.alloc(0);
101
251
  let ready = false;
@@ -128,16 +278,79 @@ export class BrokerTransport {
128
278
  this.heartbeat.unref?.();
129
279
  }
130
280
  }
281
+ if (this.options.inputProtocolVersion === 2) {
282
+ const receipt = f.inputReceipt;
283
+ if (f.inputProtocolVersion !== 2 || !receipt || receipt.failed !== false)
284
+ throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '主机不能确认原输入字节水位,未重发输入。', 'inputProtocolVersion 2的有效回执');
285
+ if (this.options.messageInput && this.options.restoreInput && !this.pendingInput && this.inputSequence <= this.options.restoreInput.sequence + (this.options.restoreInput.pending?.chunks ?? 0)) {
286
+ const sequence = receipt.committedSequence, restore = this.options.restoreInput, pending = restore.pending, r = receipt;
287
+ 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)))
288
+ throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '原输入水位不属于本轮,未跳过输入', '原消息身份及提交水位');
289
+ this.inputSequence = sequence;
290
+ }
291
+ else
292
+ this.acknowledge(receipt.committedSequence);
293
+ this.receipt = receipt;
294
+ if (typeof f.promptDelivered === 'boolean')
295
+ this.promptReceipt = f.promptDelivered;
296
+ if (this.options.messageInput && f.messageInputProtocolVersion !== 1)
297
+ throw new NeedError('BROKER_PROTOCOL_INVALID', '主机缺少完整消息暂存协议', 'messageInputProtocolVersion 1');
298
+ 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))
299
+ throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '主机在途输入不属于本客户端', '原客户端在途输入');
300
+ this.inputReady = false;
301
+ }
302
+ const lifecycle = f.lifecycle;
303
+ if (this.supportsRecovery && Number.isSafeInteger(lifecycle?.heartbeatIntervalMs) && lifecycle.heartbeatIntervalMs > 0)
304
+ this.recoveryIntervalMs = lifecycle.heartbeatIntervalMs;
131
305
  ready = true;
306
+ this.everReady = true;
132
307
  this.attached = true;
133
308
  this.lease = new AbortController();
134
309
  this.changed();
310
+ this.resendControl();
135
311
  connected.resolve();
136
312
  return;
137
313
  }
314
+ if (f.type === 'input-discarded' || f.type === 'input-observed') {
315
+ const wait = this.controlWait;
316
+ if (!wait || f.messageId !== wait.id)
317
+ throw new NeedError('BROKER_PROTOCOL_INVALID', '输入控制回执不匹配', '原消息标识');
318
+ this.receipt = f.inputReceipt;
319
+ const r = f.inputReceipt;
320
+ if (!Number.isSafeInteger(r?.committedSequence) || r.committedSequence < this.inputSequence)
321
+ throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '输入控制水位倒退', '原消息终态');
322
+ this.inputSequence = r.committedSequence;
323
+ wait.ready.resolve(r);
324
+ return;
325
+ }
326
+ if (f.type === 'input-ack') {
327
+ if (this.options.inputProtocolVersion !== 2)
328
+ throw new NeedError('BROKER_PROTOCOL_INVALID', '未协商输入确认', 'inputProtocolVersion 2');
329
+ this.acknowledge(f.sequence);
330
+ return;
331
+ }
332
+ if (f.type === 'replay-complete') {
333
+ if (this.options.inputProtocolVersion !== 2 || f.sequence !== this.cursor)
334
+ throw new NeedError('REPLAY_GAP', '原轮回放水位未连续', '完整原轮回放');
335
+ this.output.enqueue(Buffer.from(JSON.stringify({ jsonrpc: '2.0', method: '_aw/broker-replay-complete', params: { generation: this.epoch, pendingClientRequests: f.pendingClientRequests } }) + '\n'));
336
+ if (this.options.outputOrigins)
337
+ this.output.enqueue(this.originMarker(null));
338
+ return;
339
+ }
138
340
  if (f.type === 'error') {
139
341
  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 + ');没有重放输入或代答审批', '恢复或显式结束原会话');
342
+ const error = new NeedError(code, f.reason === 'OUTPUT_JOURNAL_FAILED' ? '主机输出持久保存失败(' + String(f.systemCode) + '),原轮结果未确认,没有重放。' : '主机会话无法续接(' + code + ');没有重放输入或代答审批', '恢复或显式结束原会话');
343
+ if (ready && code === 'ATTACH_LEASE_EXPIRED' && this.supportsRecovery) {
344
+ attemptClosed = true;
345
+ this.stopHeartbeat();
346
+ this.attached = false;
347
+ this.inputReady = false;
348
+ this.lease.abort();
349
+ this.changed();
350
+ child.kill('SIGTERM');
351
+ this.recover();
352
+ return;
353
+ }
141
354
  if (!ready && f.code === 'ATTACH_BUSY') {
142
355
  this.options.observeClose?.({ layer: 'broker', initiator: 'broker.attach-busy', reason: error.code, action: 'terminate' });
143
356
  attemptClosed = true;
@@ -147,6 +360,22 @@ export class BrokerTransport {
147
360
  }
148
361
  throw error;
149
362
  }
363
+ if (f.type === 'exit' && this.supportsRecovery) {
364
+ if (this.options.outputOrigins && this.originPartial) {
365
+ this.output.enqueue(Buffer.from('\n'));
366
+ this.output.enqueue(this.originMarker(this.originFinalSequence));
367
+ this.originPartial = false;
368
+ }
369
+ this.stopHeartbeat();
370
+ this.ended = true;
371
+ this.attached = false;
372
+ this.lease.abort();
373
+ this.pendingInput?.ack.reject(new NeedError('AGENT_EXITED', '主机进程已退出,未重发输入', '原轮结果'));
374
+ this.controlWait?.ready.reject(new NeedError('AGENT_EXITED', '主机进程已退出,输入控制回执未确认', '原消息终态'));
375
+ this.changed();
376
+ this.output.close();
377
+ return;
378
+ }
150
379
  if (f.type === 'exit') {
151
380
  connected.reject(new NeedError('AGENT_EXITED', '主机 agent 已退出', '重新建立会话'));
152
381
  this.fail(new NeedError('AGENT_EXITED', '主机 agent 已退出,退出状态不代表本轮完成', '确认主机状态'));
@@ -160,7 +389,7 @@ export class BrokerTransport {
160
389
  if (seq !== this.cursor + 1)
161
390
  throw new NeedError('REPLAY_GAP', '主机输出存在缺口,不能安全继续审批', '显式结束或恢复原会话');
162
391
  if (f.channel === 'stdout') {
163
- this.output.enqueue(Buffer.from(f.data, 'base64'));
392
+ this.stdout(Buffer.from(f.data, 'base64'), seq);
164
393
  }
165
394
  this.cursor = seq;
166
395
  this.changed();
@@ -201,11 +430,24 @@ export class BrokerTransport {
201
430
  this.attached = false;
202
431
  this.lease.abort();
203
432
  this.changed();
433
+ this.inputReady = this.options.inputProtocolVersion !== 2;
434
+ // The original broker is gone (reaped, crashed, host restarted): waiting cannot bring it back, so end this round and let the next input settle it.
435
+ const gone = ready ? undefined : controlNeed(diagnostics.toString('utf8'));
436
+ if (gone && ['ENOENT', 'ECONNREFUSED'].includes(gone.code)) {
437
+ fatal(gone);
438
+ return;
439
+ }
440
+ if (this.supportsRecovery && this.everReady) {
441
+ if (!ready)
442
+ connected.reject(new NeedError('BROKER_ATTACH_FAILED', '原轮暂未重新附着,继续等待原租约或连接', '原主机连接'));
443
+ else
444
+ this.recover();
445
+ return;
446
+ }
204
447
  if (!ready) {
205
448
  fatal(new NeedError('BROKER_ATTACH_FAILED', '主机会话附着失败;根因未查明', '有效的原员工 SSH/broker 连接'));
206
449
  return;
207
450
  }
208
- // A real disconnect ends this turn; the next turn starts a new agent.
209
451
  fatal(new NeedError('CONNECTION_LOST', '主机会话连接已中断,恢复后可在原会话继续。', '当前主机连接'));
210
452
  };
211
453
  child.once('error', () => detached({ layer: 'broker', initiator: 'broker.attachment-error', reason: 'BROKER_ATTACHMENT_ERROR', action: 'failure' }));
@@ -213,7 +455,9 @@ export class BrokerTransport {
213
455
  return connected.promise.finally(off);
214
456
  }
215
457
  write(bytes) { return this.exclusive(() => this.send(bytes)); }
216
- async send(bytes) {
458
+ async send(bytes, resume) {
459
+ if (this.supportsRecovery)
460
+ await this.waitInput();
217
461
  if (!this.online || !this.attachment)
218
462
  throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '连接不在线,输入没有排队或重放', '恢复连接并确认原会话状态');
219
463
  let response;
@@ -224,7 +468,7 @@ export class BrokerTransport {
224
468
  throw new NeedError('ACP_INPUT_INVALID', 'ACP 输出不是一条完整 JSON 消息', '有效的 ACP SDK 字节输出');
225
469
  }
226
470
  const selected = response.result?.outcome?.outcome === 'selected';
227
- const prompt = response.method === 'session/prompt', promptPermit = prompt ? this.promptPermit : undefined;
471
+ const prompt = response.method === 'session/prompt' || response.method === '_session/steering', promptPermit = prompt ? this.promptPermit : undefined;
228
472
  const generation = this.epoch;
229
473
  const child = this.attachment;
230
474
  const permit = this.permits.get(JSON.stringify(response.id));
@@ -261,15 +505,70 @@ export class BrokerTransport {
261
505
  if (prompt && this.promptPermit === promptPermit)
262
506
  this.promptPermit = undefined;
263
507
  const chunks = [];
508
+ let chunkBytes = resume?.chunkBytes ?? bytes.byteLength;
509
+ const message = this.options.messageInput ? resume ?? { id: randomUUID(), sha256: createHash('sha256').update(bytes).digest('hex') } : undefined;
264
510
  if (this.options.leased) {
265
- const size = Math.floor((this.options.controlMaxBytes - Buffer.byteLength(JSON.stringify({ type: 'input', data: '' }))) / 4) * 3;
511
+ 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
512
  if (size < 1)
267
513
  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'));
514
+ chunkBytes = resume?.chunkBytes ?? size;
515
+ if (this.options.inputProtocolVersion !== 2)
516
+ for (let offset = 0; offset < bytes.byteLength; offset += size)
517
+ chunks.push(Buffer.from(JSON.stringify({ type: 'input', data: Buffer.from(bytes.subarray(offset, offset + size)).toString('base64') }) + '\n'));
270
518
  }
271
519
  else
272
520
  chunks.push(Buffer.from(bytes));
521
+ if (message && !resume)
522
+ await this.options.beforeMessage?.(bytes, { ...message, chunkBytes, baseSequence: this.inputSequence });
523
+ if (this.options.inputProtocolVersion === 2) {
524
+ try {
525
+ for (let offset = resume?.offset ?? 0; offset < bytes.byteLength; offset += chunkBytes) {
526
+ const chunk = bytes.subarray(offset, offset + chunkBytes);
527
+ await this.waitInput();
528
+ if (prompt)
529
+ currentPrompt();
530
+ const sequence = this.inputSequence + 1, ack = Promise.withResolvers();
531
+ void ack.promise.catch(() => { });
532
+ 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');
533
+ const pending = { sequence, frame, ack };
534
+ this.pendingInput = pending;
535
+ try {
536
+ while (this.inputSequence < sequence) {
537
+ await this.waitInput();
538
+ if (this.inputSequence >= sequence)
539
+ break;
540
+ if (prompt)
541
+ currentPrompt();
542
+ if (selected && (generation !== this.epoch || !policyCurrent()))
543
+ throw new NeedError('APPROVAL_STALE', '断线后原批准不再重发,原轮结果可能未知。', '当前代次的审批许可');
544
+ const current = this.attachment, epoch = this.epoch, detached = Promise.withResolvers();
545
+ const off = this.onChange(() => { if (this.epoch !== epoch || !this.online)
546
+ detached.resolve(); });
547
+ try {
548
+ current.stdin.write(frame, error => { if (error)
549
+ current.kill('SIGTERM'); });
550
+ await Promise.race([ack.promise, detached.promise]);
551
+ }
552
+ finally {
553
+ off();
554
+ }
555
+ }
556
+ }
557
+ finally {
558
+ if (this.pendingInput === pending)
559
+ this.pendingInput = undefined;
560
+ }
561
+ }
562
+ if (message)
563
+ await this.options.afterMessage?.(this.inputSequence);
564
+ return;
565
+ }
566
+ catch (error) {
567
+ const known = error instanceof NeedError ? error : new NeedError('INPUT_DELIVERY_UNCONFIRMED', '原输入结果未知,没有重发', '原轮输入确认');
568
+ this.fail(known);
569
+ throw known;
570
+ }
571
+ }
273
572
  for (const chunk of chunks) {
274
573
  if (!this.online || this.attachment !== child || this.epoch !== generation)
275
574
  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: ['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');
package/dist/client.js CHANGED
@@ -1,6 +1,6 @@
1
1
  window.__ModuleLoader__.load({id:'@ai-workbench/remote-agent',factory(require){
2
2
  const messages={"en":{"administratorNote":"Settings → Built-in plugins → 远程助手参数. Eight named settings with defaults, scope and effects.","providerName":"Codex (Remote Host)"},"zh":{"administratorNote":"管理员:设置 → 内置插件 → 远程助手参数。八项设置含默认值、范围、生效和后果说明。","providerName":"Codex(远程主机)"}};
3
- const settingsFields=[{"key":"acpMaxMessageBytes","name":"完整消息与工具输出容量(字节)","kind":"number","min":1,"max":9007199254740991,"range":"1~9007199254740991 的整数;0不能关闭上限","scope":"两位远程助手的完整会话消息;也用于模型目录、本机 MCP、员工执行 RPC 和工具输出容量。","when":"当轮快照不变;下一次独立目录查询读取新值;已有会话需新建后使用。","consequence":"调大可接收更大消息、占用更多内存;调小更早拒绝超限。超限明确停止,不截断、不自动重试;不能用0取消完整消息保护。","defaultValue":4194304},{"key":"brokerMaxFrameBytes","name":"主机会话回传单段容量(字节)","kind":"number","min":1,"max":9007199254740991,"range":"1~9007199254740991 的整数;0不能关闭上限","scope":"本插件接收主机会话单段输出的容量;不会替主机修改它自己的输出策略。","when":"当轮快照不变;更改后已有会话需新建。","consequence":"调大允许更大回传段、占用更多内存;调小可能拒绝主机合法输出。超限停止,不截断;不能关闭协议帧核验。","defaultValue":2097152},{"key":"brokerControlMaxBytes","name":"主机会话管理回复容量(字节)","kind":"number","min":1,"max":9007199254740991,"range":"1~9007199254740991 的整数;0不能关闭上限","scope":"主机会话管理命令的标准输出、标准错误各自容量;也用于本机执行桥的管理回复。","when":"当轮快照不变;更改后已有会话需新建。","consequence":"调大允许更长管理回复、占用更多内存;调小可能无法核实状态。超限明确停止,不能把不完整回复当成功;0不表示无限。","defaultValue":1048576},{"key":"employeeShellKillGraceMs","name":"本机命令外层连接清理宽限(毫秒)","kind":"number","min":0,"max":2147483647,"range":"0~2147483647 的整数","scope":"仅 Claude 本机 Bash 取消后,本插件自己的外层 SSH 进程清理;不控制员工命令或 Codex 执行器。","when":"当轮快照不变;更改后已有会话需新建。","consequence":"大于0时先请求外层连接退出,再等待所设毫秒后强制清理;0表示不留宽限、立即强制清理外层连接,不是关闭取消。没有员工端退出确认时结果仍未知,不能据此自动重放或声称命令已停止。","defaultValue":1000}];
3
+ const settingsFields=[{"key":"acpMaxMessageBytes","name":"完整消息与工具输出容量(字节)","kind":"number","min":1,"max":9007199254740991,"range":"1~9007199254740991 的整数;0不能关闭上限","scope":"两位远程助手的完整会话消息;默认512 MB(512000000字节)。也用于模型目录、本机 MCP、员工执行 RPC 和工具输出容量。","when":"当轮快照不变;下一次独立调用或目录查询读取新值。","consequence":"调大可接收更大消息、占用更多内存;调小更早拒绝超限。超限明确停止,不截断、不自动重试;不能用0取消完整消息保护。","defaultValue":512000000},{"key":"brokerMaxFrameBytes","name":"主机会话回传单段容量(字节)","kind":"number","min":1,"max":9007199254740991,"range":"1~9007199254740991 的整数;0不能关闭上限","scope":"本插件接收主机会话单段输出的容量;不会替主机修改它自己的输出策略。","when":"当轮快照不变;更改后已有会话需新建。","consequence":"调大允许更大回传段、占用更多内存;调小可能拒绝主机合法输出。超限停止,不截断;不能关闭协议帧核验。","defaultValue":2097152},{"key":"brokerControlMaxBytes","name":"主机会话管理回复容量(字节)","kind":"number","min":1,"max":9007199254740991,"range":"1~9007199254740991 的整数;0不能关闭上限","scope":"主机会话管理命令的标准输出、标准错误各自容量;也用于本机执行桥的管理回复。","when":"当轮快照不变;更改后已有会话需新建。","consequence":"调大允许更长管理回复、占用更多内存;调小可能无法核实状态。超限明确停止,不能把不完整回复当成功;0不表示无限。","defaultValue":1048576},{"key":"employeeShellKillGraceMs","name":"本机命令外层连接清理宽限(毫秒)","kind":"number","min":0,"max":2147483647,"range":"0~2147483647 的整数","scope":"仅 Claude 本机 Bash 取消后,本插件自己的外层 SSH 进程清理;不控制员工命令或 Codex 执行器。","when":"当轮快照不变;更改后已有会话需新建。","consequence":"大于0时先请求外层连接退出,再等待所设毫秒后强制清理;0表示不留宽限、立即强制清理外层连接,不是关闭取消。没有员工端退出确认时结果仍未知,不能据此自动重放或声称命令已停止。","defaultValue":1000}];
4
4
  /* Public settings.plugins.tab + shared ConfigForms. No private client services. */
5
5
  function mountRuntimeSettings(ctx,React,fields){
6
6
  const h=React.createElement;
@@ -31,7 +31,7 @@ export declare class CloseDiagnostics {
31
31
  get first(): Readonly<Record<string, unknown>> | undefined;
32
32
  bind(sink: (detail: DetailObservation) => void): void;
33
33
  capture(): CloseObserver;
34
- child(sink?: (detail: DetailObservation) => void): CloseDiagnostics;
34
+ child(sink?: (detail: DetailObservation) => void, independent?: boolean): CloseDiagnostics;
35
35
  record(cause: CloseCause): void;
36
36
  private recordUsing;
37
37
  }
@@ -13,7 +13,7 @@ export class CloseDiagnostics {
13
13
  get first() { return this.state.first; }
14
14
  bind(sink) { this.sink = sink; }
15
15
  capture() { const sink = this.sink; return cause => this.recordUsing(sink, cause); }
16
- child(sink = this.sink) { return new CloseDiagnostics(sink, this.state); }
16
+ child(sink = this.sink, independent = false) { return new CloseDiagnostics(sink, independent ? {} : this.state); }
17
17
  record(cause) { this.recordUsing(this.sink, cause); }
18
18
  recordUsing(sink, cause) {
19
19
  if (this.state.first)
@@ -0,0 +1,17 @@
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
+ cancelOnly?: boolean;
15
+ }): AsyncGenerator<StreamChunk>;
16
+ /** 本地未派发取消的证明来自写前记录或S消息回执,不伪造原生RPC终态。 */
17
+ export declare function recoverLocalCancellation(record: ColdRound, store: ColdStore, markerId: string): AsyncGenerator<StreamChunk>;