@ai-workbench/remote-agent 0.9.0-toolbridge.2 → 0.9.0-toolbridge.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -8
- package/dist/acp.d.ts +23 -1
- package/dist/acp.js +127 -17
- package/dist/broker-runtime.d.ts +2 -0
- package/dist/broker-runtime.js +52 -3
- package/dist/broker.d.ts +56 -1
- package/dist/broker.js +300 -10
- package/dist/claude-local.js +26 -5
- package/dist/client.js +1 -1
- package/dist/close-diagnostics.d.ts +1 -1
- package/dist/close-diagnostics.js +1 -1
- package/dist/cold-protocol.d.ts +17 -0
- package/dist/cold-protocol.js +358 -0
- package/dist/cold-recovery.d.ts +63 -0
- package/dist/cold-recovery.js +598 -0
- package/dist/cold-store.d.ts +100 -0
- package/dist/cold-store.js +29 -0
- package/dist/employee-endpoint.js +15 -1
- package/dist/employee-mcp.js +1 -1
- package/dist/employee-provider.js +26 -6
- package/dist/employee-relay.js +148 -1
- package/dist/employee-shell.d.ts +2 -0
- package/dist/employee-shell.js +22 -19
- package/dist/employee-tools.js +2 -2
- package/dist/employee-workspace.d.ts +20 -4
- package/dist/employee-workspace.js +26 -5
- package/dist/index.d.ts +12 -3
- package/dist/index.js +205 -40
- package/dist/input.js +4 -1
- package/dist/live-steering.d.ts +46 -0
- package/dist/live-steering.js +45 -0
- package/dist/model-catalog.d.ts +2 -0
- package/dist/model-catalog.js +5 -1
- package/dist/preflight-diagnostic.js +1 -1
- package/dist/presentation.js +1 -0
- package/dist/provider.d.ts +13 -0
- package/dist/rpc-namespace.js +16 -2
- package/dist/session-source.d.ts +3 -1
- package/dist/session-source.js +2 -1
- package/dist/toolbridge-loop.d.ts +3 -2
- package/dist/toolbridge-loop.js +4 -2
- package/dist/toolbridge-table.d.ts +4 -3
- package/dist/toolbridge-table.js +15 -5
- package/dist/toolbridge.d.ts +1 -1
- package/dist/toolbridge.js +4 -4
- package/package.json +23 -16
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.
|
|
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');
|
|
@@ -128,16 +275,79 @@ export class BrokerTransport {
|
|
|
128
275
|
this.heartbeat.unref?.();
|
|
129
276
|
}
|
|
130
277
|
}
|
|
278
|
+
if (this.options.inputProtocolVersion === 2) {
|
|
279
|
+
const receipt = f.inputReceipt;
|
|
280
|
+
if (f.inputProtocolVersion !== 2 || !receipt || receipt.failed !== false)
|
|
281
|
+
throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '主机不能确认原输入字节水位,未重发输入。', 'inputProtocolVersion 2的有效回执');
|
|
282
|
+
if (this.options.messageInput && this.options.restoreInput && !this.pendingInput && this.inputSequence <= this.options.restoreInput.sequence + (this.options.restoreInput.pending?.chunks ?? 0)) {
|
|
283
|
+
const sequence = receipt.committedSequence, restore = this.options.restoreInput, pending = restore.pending, r = receipt;
|
|
284
|
+
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)))
|
|
285
|
+
throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '原输入水位不属于本轮,未跳过输入', '原消息身份及提交水位');
|
|
286
|
+
this.inputSequence = sequence;
|
|
287
|
+
}
|
|
288
|
+
else
|
|
289
|
+
this.acknowledge(receipt.committedSequence);
|
|
290
|
+
this.receipt = receipt;
|
|
291
|
+
if (typeof f.promptDelivered === 'boolean')
|
|
292
|
+
this.promptReceipt = f.promptDelivered;
|
|
293
|
+
if (this.options.messageInput && f.messageInputProtocolVersion !== 1)
|
|
294
|
+
throw new NeedError('BROKER_PROTOCOL_INVALID', '主机缺少完整消息暂存协议', 'messageInputProtocolVersion 1');
|
|
295
|
+
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))
|
|
296
|
+
throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '主机在途输入不属于本客户端', '原客户端在途输入');
|
|
297
|
+
this.inputReady = false;
|
|
298
|
+
}
|
|
299
|
+
const lifecycle = f.lifecycle;
|
|
300
|
+
if (this.supportsRecovery && Number.isSafeInteger(lifecycle?.heartbeatIntervalMs) && lifecycle.heartbeatIntervalMs > 0)
|
|
301
|
+
this.recoveryIntervalMs = lifecycle.heartbeatIntervalMs;
|
|
131
302
|
ready = true;
|
|
303
|
+
this.everReady = true;
|
|
132
304
|
this.attached = true;
|
|
133
305
|
this.lease = new AbortController();
|
|
134
306
|
this.changed();
|
|
307
|
+
this.resendControl();
|
|
135
308
|
connected.resolve();
|
|
136
309
|
return;
|
|
137
310
|
}
|
|
311
|
+
if (f.type === 'input-discarded' || f.type === 'input-observed') {
|
|
312
|
+
const wait = this.controlWait;
|
|
313
|
+
if (!wait || f.messageId !== wait.id)
|
|
314
|
+
throw new NeedError('BROKER_PROTOCOL_INVALID', '输入控制回执不匹配', '原消息标识');
|
|
315
|
+
this.receipt = f.inputReceipt;
|
|
316
|
+
const r = f.inputReceipt;
|
|
317
|
+
if (!Number.isSafeInteger(r?.committedSequence) || r.committedSequence < this.inputSequence)
|
|
318
|
+
throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '输入控制水位倒退', '原消息终态');
|
|
319
|
+
this.inputSequence = r.committedSequence;
|
|
320
|
+
wait.ready.resolve(r);
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
if (f.type === 'input-ack') {
|
|
324
|
+
if (this.options.inputProtocolVersion !== 2)
|
|
325
|
+
throw new NeedError('BROKER_PROTOCOL_INVALID', '未协商输入确认', 'inputProtocolVersion 2');
|
|
326
|
+
this.acknowledge(f.sequence);
|
|
327
|
+
return;
|
|
328
|
+
}
|
|
329
|
+
if (f.type === 'replay-complete') {
|
|
330
|
+
if (this.options.inputProtocolVersion !== 2 || f.sequence !== this.cursor)
|
|
331
|
+
throw new NeedError('REPLAY_GAP', '原轮回放水位未连续', '完整原轮回放');
|
|
332
|
+
this.output.enqueue(Buffer.from(JSON.stringify({ jsonrpc: '2.0', method: '_aw/broker-replay-complete', params: { generation: this.epoch, pendingClientRequests: f.pendingClientRequests } }) + '\n'));
|
|
333
|
+
if (this.options.outputOrigins)
|
|
334
|
+
this.output.enqueue(this.originMarker(null));
|
|
335
|
+
return;
|
|
336
|
+
}
|
|
138
337
|
if (f.type === 'error') {
|
|
139
338
|
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 + ');没有重放输入或代答审批', '恢复或显式结束原会话');
|
|
339
|
+
const error = new NeedError(code, f.reason === 'OUTPUT_JOURNAL_FAILED' ? '主机输出持久保存失败(' + String(f.systemCode) + '),原轮结果未确认,没有重放。' : '主机会话无法续接(' + code + ');没有重放输入或代答审批', '恢复或显式结束原会话');
|
|
340
|
+
if (ready && code === 'ATTACH_LEASE_EXPIRED' && this.supportsRecovery) {
|
|
341
|
+
attemptClosed = true;
|
|
342
|
+
this.stopHeartbeat();
|
|
343
|
+
this.attached = false;
|
|
344
|
+
this.inputReady = false;
|
|
345
|
+
this.lease.abort();
|
|
346
|
+
this.changed();
|
|
347
|
+
child.kill('SIGTERM');
|
|
348
|
+
this.recover();
|
|
349
|
+
return;
|
|
350
|
+
}
|
|
141
351
|
if (!ready && f.code === 'ATTACH_BUSY') {
|
|
142
352
|
this.options.observeClose?.({ layer: 'broker', initiator: 'broker.attach-busy', reason: error.code, action: 'terminate' });
|
|
143
353
|
attemptClosed = true;
|
|
@@ -147,6 +357,22 @@ export class BrokerTransport {
|
|
|
147
357
|
}
|
|
148
358
|
throw error;
|
|
149
359
|
}
|
|
360
|
+
if (f.type === 'exit' && this.supportsRecovery) {
|
|
361
|
+
if (this.options.outputOrigins && this.originPartial) {
|
|
362
|
+
this.output.enqueue(Buffer.from('\n'));
|
|
363
|
+
this.output.enqueue(this.originMarker(this.originFinalSequence));
|
|
364
|
+
this.originPartial = false;
|
|
365
|
+
}
|
|
366
|
+
this.stopHeartbeat();
|
|
367
|
+
this.ended = true;
|
|
368
|
+
this.attached = false;
|
|
369
|
+
this.lease.abort();
|
|
370
|
+
this.pendingInput?.ack.reject(new NeedError('AGENT_EXITED', '主机进程已退出,未重发输入', '原轮结果'));
|
|
371
|
+
this.controlWait?.ready.reject(new NeedError('AGENT_EXITED', '主机进程已退出,输入控制回执未确认', '原消息终态'));
|
|
372
|
+
this.changed();
|
|
373
|
+
this.output.close();
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
150
376
|
if (f.type === 'exit') {
|
|
151
377
|
connected.reject(new NeedError('AGENT_EXITED', '主机 agent 已退出', '重新建立会话'));
|
|
152
378
|
this.fail(new NeedError('AGENT_EXITED', '主机 agent 已退出,退出状态不代表本轮完成', '确认主机状态'));
|
|
@@ -160,7 +386,7 @@ export class BrokerTransport {
|
|
|
160
386
|
if (seq !== this.cursor + 1)
|
|
161
387
|
throw new NeedError('REPLAY_GAP', '主机输出存在缺口,不能安全继续审批', '显式结束或恢复原会话');
|
|
162
388
|
if (f.channel === 'stdout') {
|
|
163
|
-
this.
|
|
389
|
+
this.stdout(Buffer.from(f.data, 'base64'), seq);
|
|
164
390
|
}
|
|
165
391
|
this.cursor = seq;
|
|
166
392
|
this.changed();
|
|
@@ -201,11 +427,18 @@ export class BrokerTransport {
|
|
|
201
427
|
this.attached = false;
|
|
202
428
|
this.lease.abort();
|
|
203
429
|
this.changed();
|
|
430
|
+
this.inputReady = this.options.inputProtocolVersion !== 2;
|
|
431
|
+
if (this.supportsRecovery && this.everReady) {
|
|
432
|
+
if (!ready)
|
|
433
|
+
connected.reject(new NeedError('BROKER_ATTACH_FAILED', '原轮暂未重新附着,继续等待原租约或连接', '原主机连接'));
|
|
434
|
+
else
|
|
435
|
+
this.recover();
|
|
436
|
+
return;
|
|
437
|
+
}
|
|
204
438
|
if (!ready) {
|
|
205
439
|
fatal(new NeedError('BROKER_ATTACH_FAILED', '主机会话附着失败;根因未查明', '有效的原员工 SSH/broker 连接'));
|
|
206
440
|
return;
|
|
207
441
|
}
|
|
208
|
-
// A real disconnect ends this turn; the next turn starts a new agent.
|
|
209
442
|
fatal(new NeedError('CONNECTION_LOST', '主机会话连接已中断,恢复后可在原会话继续。', '当前主机连接'));
|
|
210
443
|
};
|
|
211
444
|
child.once('error', () => detached({ layer: 'broker', initiator: 'broker.attachment-error', reason: 'BROKER_ATTACHMENT_ERROR', action: 'failure' }));
|
|
@@ -213,7 +446,9 @@ export class BrokerTransport {
|
|
|
213
446
|
return connected.promise.finally(off);
|
|
214
447
|
}
|
|
215
448
|
write(bytes) { return this.exclusive(() => this.send(bytes)); }
|
|
216
|
-
async send(bytes) {
|
|
449
|
+
async send(bytes, resume) {
|
|
450
|
+
if (this.supportsRecovery)
|
|
451
|
+
await this.waitInput();
|
|
217
452
|
if (!this.online || !this.attachment)
|
|
218
453
|
throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '连接不在线,输入没有排队或重放', '恢复连接并确认原会话状态');
|
|
219
454
|
let response;
|
|
@@ -224,7 +459,7 @@ export class BrokerTransport {
|
|
|
224
459
|
throw new NeedError('ACP_INPUT_INVALID', 'ACP 输出不是一条完整 JSON 消息', '有效的 ACP SDK 字节输出');
|
|
225
460
|
}
|
|
226
461
|
const selected = response.result?.outcome?.outcome === 'selected';
|
|
227
|
-
const prompt = response.method === 'session/prompt', promptPermit = prompt ? this.promptPermit : undefined;
|
|
462
|
+
const prompt = response.method === 'session/prompt' || response.method === '_session/steering', promptPermit = prompt ? this.promptPermit : undefined;
|
|
228
463
|
const generation = this.epoch;
|
|
229
464
|
const child = this.attachment;
|
|
230
465
|
const permit = this.permits.get(JSON.stringify(response.id));
|
|
@@ -261,15 +496,70 @@ export class BrokerTransport {
|
|
|
261
496
|
if (prompt && this.promptPermit === promptPermit)
|
|
262
497
|
this.promptPermit = undefined;
|
|
263
498
|
const chunks = [];
|
|
499
|
+
let chunkBytes = resume?.chunkBytes ?? bytes.byteLength;
|
|
500
|
+
const message = this.options.messageInput ? resume ?? { id: randomUUID(), sha256: createHash('sha256').update(bytes).digest('hex') } : undefined;
|
|
264
501
|
if (this.options.leased) {
|
|
265
|
-
const size = Math.floor((this.options.controlMaxBytes - Buffer.byteLength(JSON.stringify({ type: 'input', data: '' }))) / 4) * 3;
|
|
502
|
+
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
503
|
if (size < 1)
|
|
267
504
|
throw new NeedError('LEASE_CAPACITY_INVALID', '主机会话容量无法承载输入', '有效controlMaxBytes');
|
|
268
|
-
|
|
269
|
-
|
|
505
|
+
chunkBytes = resume?.chunkBytes ?? size;
|
|
506
|
+
if (this.options.inputProtocolVersion !== 2)
|
|
507
|
+
for (let offset = 0; offset < bytes.byteLength; offset += size)
|
|
508
|
+
chunks.push(Buffer.from(JSON.stringify({ type: 'input', data: Buffer.from(bytes.subarray(offset, offset + size)).toString('base64') }) + '\n'));
|
|
270
509
|
}
|
|
271
510
|
else
|
|
272
511
|
chunks.push(Buffer.from(bytes));
|
|
512
|
+
if (message && !resume)
|
|
513
|
+
await this.options.beforeMessage?.(bytes, { ...message, chunkBytes, baseSequence: this.inputSequence });
|
|
514
|
+
if (this.options.inputProtocolVersion === 2) {
|
|
515
|
+
try {
|
|
516
|
+
for (let offset = resume?.offset ?? 0; offset < bytes.byteLength; offset += chunkBytes) {
|
|
517
|
+
const chunk = bytes.subarray(offset, offset + chunkBytes);
|
|
518
|
+
await this.waitInput();
|
|
519
|
+
if (prompt)
|
|
520
|
+
currentPrompt();
|
|
521
|
+
const sequence = this.inputSequence + 1, ack = Promise.withResolvers();
|
|
522
|
+
void ack.promise.catch(() => { });
|
|
523
|
+
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');
|
|
524
|
+
const pending = { sequence, frame, ack };
|
|
525
|
+
this.pendingInput = pending;
|
|
526
|
+
try {
|
|
527
|
+
while (this.inputSequence < sequence) {
|
|
528
|
+
await this.waitInput();
|
|
529
|
+
if (this.inputSequence >= sequence)
|
|
530
|
+
break;
|
|
531
|
+
if (prompt)
|
|
532
|
+
currentPrompt();
|
|
533
|
+
if (selected && (generation !== this.epoch || !policyCurrent()))
|
|
534
|
+
throw new NeedError('APPROVAL_STALE', '断线后原批准不再重发,原轮结果可能未知。', '当前代次的审批许可');
|
|
535
|
+
const current = this.attachment, epoch = this.epoch, detached = Promise.withResolvers();
|
|
536
|
+
const off = this.onChange(() => { if (this.epoch !== epoch || !this.online)
|
|
537
|
+
detached.resolve(); });
|
|
538
|
+
try {
|
|
539
|
+
current.stdin.write(frame, error => { if (error)
|
|
540
|
+
current.kill('SIGTERM'); });
|
|
541
|
+
await Promise.race([ack.promise, detached.promise]);
|
|
542
|
+
}
|
|
543
|
+
finally {
|
|
544
|
+
off();
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
finally {
|
|
549
|
+
if (this.pendingInput === pending)
|
|
550
|
+
this.pendingInput = undefined;
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
if (message)
|
|
554
|
+
await this.options.afterMessage?.(this.inputSequence);
|
|
555
|
+
return;
|
|
556
|
+
}
|
|
557
|
+
catch (error) {
|
|
558
|
+
const known = error instanceof NeedError ? error : new NeedError('INPUT_DELIVERY_UNCONFIRMED', '原输入结果未知,没有重发', '原轮输入确认');
|
|
559
|
+
this.fail(known);
|
|
560
|
+
throw known;
|
|
561
|
+
}
|
|
562
|
+
}
|
|
273
563
|
for (const chunk of chunks) {
|
|
274
564
|
if (!this.online || this.attachment !== child || this.epoch !== generation)
|
|
275
565
|
throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '分块发送期间断线,未重放输入', '原主机连接');
|
package/dist/claude-local.js
CHANGED
|
@@ -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(() =>
|
|
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 =
|
|
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: ['
|
|
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
|
-
|
|
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":"
|
|
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>;
|