@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.
- package/README.md +36 -7
- package/dist/acp.d.ts +23 -3
- package/dist/acp.js +106 -21
- package/dist/broker-runtime.d.ts +2 -0
- package/dist/broker-runtime.js +60 -3
- package/dist/broker.d.ts +56 -1
- package/dist/broker.js +310 -11
- 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 +399 -0
- package/dist/cold-recovery.d.ts +62 -0
- package/dist/cold-recovery.js +595 -0
- package/dist/cold-store.d.ts +99 -0
- package/dist/cold-store.js +29 -0
- package/dist/conversation-details.js +21 -8
- package/dist/employee-endpoint.js +15 -1
- package/dist/employee-mcp.js +1 -1
- package/dist/employee-native.js +7 -1
- package/dist/employee-provider.d.ts +2 -0
- package/dist/employee-provider.js +46 -11
- 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-startup.d.ts +18 -0
- package/dist/employee-startup.js +95 -0
- 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 +223 -51
- package/dist/input.js +4 -1
- package/dist/live-steering.d.ts +46 -0
- package/dist/live-steering.js +45 -0
- package/dist/mapping.d.ts +4 -24
- package/dist/mapping.js +11 -65
- 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 +16 -0
- package/dist/provider.js +66 -33
- package/dist/rpc-namespace.js +16 -2
- package/dist/session-source.d.ts +3 -1
- package/dist/session-source.js +2 -1
- package/dist/startup-timing.d.ts +14 -0
- package/dist/startup-timing.js +34 -0
- 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 +14 -5
- package/dist/toolbridge.d.ts +1 -1
- package/dist/toolbridge.js +23 -4
- package/package.json +23 -16
|
@@ -0,0 +1,399 @@
|
|
|
1
|
+
import { isKnownAcpUpdate, acpNeed } from "./acp.js";
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import * as acp from '@agentclientprotocol/sdk/unstable';
|
|
4
|
+
import { BrokerTransport, brokerCommand, controlJson } from "./broker.js";
|
|
5
|
+
import { coldNeed } from "./cold-store.js";
|
|
6
|
+
import { StreamMapper } from "./mapping.js";
|
|
7
|
+
import { LlmError } from '@deepseek-ai/dsh-llm';
|
|
8
|
+
import { NeedError } from "./remote.js";
|
|
9
|
+
/** 同一个 prompt 的可靠回执减去已写入 DSH 的部分;不是跨 prompt 的累计减法。 */
|
|
10
|
+
function remainingUsage(current, previous) {
|
|
11
|
+
const usage = { ...current };
|
|
12
|
+
for (const key of Object.keys(usage)) {
|
|
13
|
+
const actual = usage[key], paid = previous?.[key];
|
|
14
|
+
if (typeof actual === 'number' && typeof paid === 'number') {
|
|
15
|
+
if (actual < paid)
|
|
16
|
+
throw coldNeed('USAGE_BASELINE_INVALID');
|
|
17
|
+
usage[key] = actual - paid;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
return Object.values(usage).some(x => typeof x === 'number' && x !== 0) ? [{ type: 'usage', usage }] : [];
|
|
21
|
+
}
|
|
22
|
+
/** Read-only reconstruction, with block kinds and exact content checked against the durable transcript. */
|
|
23
|
+
class Prefix {
|
|
24
|
+
index = 0;
|
|
25
|
+
offset = 0;
|
|
26
|
+
blocks = [];
|
|
27
|
+
constructor(saved) { for (const block of saved.blocks) {
|
|
28
|
+
if (block.type === 'tool-call')
|
|
29
|
+
continue;
|
|
30
|
+
if (block.type !== 'text' && block.type !== 'reasoning')
|
|
31
|
+
throw coldNeed('SESSION_CONTEXT_MISMATCH');
|
|
32
|
+
if (block.text.length === 0)
|
|
33
|
+
continue;
|
|
34
|
+
const prior = this.blocks.at(-1);
|
|
35
|
+
if (prior?.type === block.type)
|
|
36
|
+
prior.text += block.text;
|
|
37
|
+
else
|
|
38
|
+
this.blocks.push({ type: block.type, text: block.text });
|
|
39
|
+
} }
|
|
40
|
+
take(type, text) { let used = 0; while (used < text.length && this.index < this.blocks.length) {
|
|
41
|
+
const b = this.blocks[this.index];
|
|
42
|
+
if (!b.text.length) {
|
|
43
|
+
this.index++;
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
if (b.type !== type)
|
|
47
|
+
throw coldNeed('SESSION_CONTEXT_MISMATCH');
|
|
48
|
+
const count = Math.min(text.length - used, b.text.length - this.offset);
|
|
49
|
+
if (text.slice(used, used + count) !== b.text.slice(this.offset, this.offset + count))
|
|
50
|
+
throw coldNeed('SESSION_CONTEXT_MISMATCH');
|
|
51
|
+
used += count;
|
|
52
|
+
this.offset += count;
|
|
53
|
+
if (this.offset === b.text.length) {
|
|
54
|
+
this.index++;
|
|
55
|
+
this.offset = 0;
|
|
56
|
+
}
|
|
57
|
+
} return text.slice(used); }
|
|
58
|
+
finish() { if (this.index !== this.blocks.length)
|
|
59
|
+
throw coldNeed('SESSION_CONTEXT_MISMATCH'); }
|
|
60
|
+
}
|
|
61
|
+
const HOST_ROUND_ENDED = '上一轮的主机会话已结束,那一轮的结果无法接回;没有重新发送那一轮的任务,可以在本会话继续。\n\n';
|
|
62
|
+
const LOGIN_ENDED = '\n上一轮因主机会话的登录已失效没有完成,已结束那一轮的主机会话;没有重新发送那一轮的任务,接下来用当前登录在本会话继续。\n\n';
|
|
63
|
+
/** The checkpoint that commits the original round and lets the next round resume its native thread. */
|
|
64
|
+
function coldPointer(record, outputAfter) {
|
|
65
|
+
const snapshot = record.meta;
|
|
66
|
+
return { ...(snapshot.hostSource ? { hostSource: snapshot.hostSource } : {}), ...(snapshot.modelConfiguration ? { modelConfiguration: snapshot.modelConfiguration } : {}), version: 2, agent: record.provider, contextSha256: snapshot.contextSha256, dshSessionId: record.sessionId, identity: snapshot.identity, cwd: snapshot.cwd, sessionId: record.nativeId, ...(snapshot.binding ? { bindingId: snapshot.binding.bindingId, workspaceId: snapshot.binding.workspaceId } : {}), coldRoundId: record.id, coldPromptId: record.promptId, coldRoundTerminal: true, coldOutputAfter: outputAfter };
|
|
67
|
+
}
|
|
68
|
+
export async function* recoverColdProtocol(record, store, prefix, options) {
|
|
69
|
+
options.signal?.throwIfAborted();
|
|
70
|
+
if (!record.meta || !record.nativeId || !record.promptId)
|
|
71
|
+
throw coldNeed();
|
|
72
|
+
const command = (args) => brokerCommand(record.target, args), owner = ['--dsh-session-id', record.sessionId, '--provider', record.brand, '--remote-session-id', record.nativeId];
|
|
73
|
+
let bound;
|
|
74
|
+
try {
|
|
75
|
+
bound = controlJson(await options.io.run(command(['bind-round', record.brokerId, '--if-instance', record.instanceId, ...owner, '--round-id', record.id, '--prompt-id', record.promptId, '--prompt-sha256', record.promptSha256, '--prompt-bytes', String(record.promptBytes)]), options.signal));
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
// The original broker is gone: S deletes a session directory only after signalling its process group (TTL reap, kill, lost broker),
|
|
79
|
+
// and a socket refusing connections has no broker behind it (host restart). Its output cannot be recovered.
|
|
80
|
+
if (!(error instanceof NeedError) || !['ENOENT', 'ECONNREFUSED'].includes(error.code))
|
|
81
|
+
throw error;
|
|
82
|
+
if (options.cancelOnly)
|
|
83
|
+
return; // Nothing is left to cancel; the next human input settles the round.
|
|
84
|
+
// Settle the round once without resending it; the next round resumes the original native session.
|
|
85
|
+
record = await store.update(record.sessionId, record.provider, record.id, row => { if (!row.terminal) {
|
|
86
|
+
row.terminal = { kind: 'error', value: { code: error.code } };
|
|
87
|
+
row.terminalAfter = row.outputStart ?? row.outputAfter;
|
|
88
|
+
} row.phase = 'terminal'; delete row.pending; }); // A terminal already recorded keeps its real result and usage.
|
|
89
|
+
const ended = new StreamMapper();
|
|
90
|
+
if (record.terminal?.kind === 'result')
|
|
91
|
+
for (const chunk of ended.acpResponse(record.terminal.value))
|
|
92
|
+
if (chunk.type === 'usage')
|
|
93
|
+
yield* remainingUsage(chunk.usage, prefix.usage);
|
|
94
|
+
yield* ended.text(HOST_ROUND_ENDED);
|
|
95
|
+
yield* ended.flush();
|
|
96
|
+
yield { type: 'finish', reason: { kind: 'stop' }, replayState: { response: coldPointer(record, record.terminalAfter ?? record.outputStart ?? record.outputAfter) } };
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
if (!Number.isSafeInteger(bound.round?.outputStartSequence))
|
|
100
|
+
throw coldNeed();
|
|
101
|
+
if (record.outputStart === undefined)
|
|
102
|
+
record = await store.update(record.sessionId, record.provider, record.id, row => { row.outputStart = bound.round.outputStartSequence; });
|
|
103
|
+
else if (bound.round.outputStartSequence !== record.outputStart)
|
|
104
|
+
throw coldNeed('SESSION_CONTEXT_MISMATCH');
|
|
105
|
+
let broker;
|
|
106
|
+
let promptConfirmed = false, localCancellation = false, nativeTerminalSeen = false, cancelHandled = false;
|
|
107
|
+
let cancellationWake = () => { };
|
|
108
|
+
let cancelNote;
|
|
109
|
+
const beforeMessage = async (bytes, m) => { const rpc = JSON.parse(Buffer.from(bytes).toString()); await store.update(record.sessionId, record.provider, record.id, row => { if (rpc.method === 'session/cancel' && rpc.params?.sessionId === row.nativeId || rpc.method === '$/cancel_request' && String(rpc.params?.requestId) === row.promptId)
|
|
110
|
+
row.cancelIntent ??= { source: 'wire' }; row.pending = { id: m.id, sha256: m.sha256, wire: Buffer.from(bytes).toString('base64'), baseSequence: m.baseSequence, chunkBytes: m.chunkBytes, chunks: Math.ceil(bytes.length / m.chunkBytes), ...(rpc.method ? { method: rpc.method } : {}), ...(Object.hasOwn(rpc, 'id') ? { rpcId: rpc.id } : {}) }; }); };
|
|
111
|
+
const afterMessage = async (sequence) => { const method = record.pending?.method; record = await store.update(record.sessionId, record.provider, record.id, row => { if (row.pending && !row.pending.method && row.pending.rpcId !== undefined && !row.answered.includes(row.pending.rpcId))
|
|
112
|
+
row.answered.push(row.pending.rpcId); if (row.pending && ['session/cancel', '$/cancel_request'].includes(row.pending.method ?? '') && row.cancelIntent)
|
|
113
|
+
row.cancelIntent.delivered = true; row.inputSequence = sequence; delete row.pending; }); if (method === 'session/prompt')
|
|
114
|
+
promptConfirmed = true; broker.completeRestoredInput(); };
|
|
115
|
+
broker = new BrokerTransport({ maxFrameBytes: options.maxFrameBytes, controlMaxBytes: record.controlMaxBytes, leased: true, inputProtocolVersion: 2, messageInput: true, recoverDisconnect: true, instanceId: record.instanceId, initialSequence: record.outputStart, restoreInput: { sequence: record.inputSequence, pending: record.pending }, beforeMessage, afterMessage, attach: (after = 0) => options.io.attach(command(['attach', record.brokerId, '--after', String(after), '--framed', '--leased', '--input-protocol', '2', '--message-input', '--if-instance', record.instanceId, '--cold-round', record.id, '--prompt-id', record.promptId, ...owner])) });
|
|
116
|
+
const raw = acp.ndJsonStream(broker.writable, broker.readable, { maxMessageBytes: options.maxMessageBytes }), reader = raw.readable.getReader(), writer = raw.writable.getWriter();
|
|
117
|
+
const mapper = new StreamMapper(), output = new StreamMapper(), trim = new Prefix(prefix);
|
|
118
|
+
let terminal = false, replayed = false, delivered = false;
|
|
119
|
+
const pendingRequests = new Map();
|
|
120
|
+
let outboundTail = Promise.resolve();
|
|
121
|
+
const enqueue = (work) => { outboundTail = outboundTail.then(work); void outboundTail.catch(error => broker.fail(error instanceof NeedError ? error : coldNeed())); };
|
|
122
|
+
const replayOff = broker.onChange(() => { if (!broker.online)
|
|
123
|
+
replayed = false; });
|
|
124
|
+
const send = async (message) => { await writer.write(message); };
|
|
125
|
+
const cancel = () => { if (options.signal?.reason?.kind !== 'user') {
|
|
126
|
+
broker.close();
|
|
127
|
+
return;
|
|
128
|
+
} cancelNote = store.update(record.sessionId, record.provider, record.id, row => { row.cancelIntent ??= { source: 'user-signal' }; }).then(row => { record = row; broker.close(); }, error => { broker.fail(error instanceof NeedError ? error : coldNeed()); throw error; }); void cancelNote.catch(() => { }); };
|
|
129
|
+
options.signal?.addEventListener('abort', cancel, { once: true });
|
|
130
|
+
const projection = function* (chunks) { for (const chunk of chunks) {
|
|
131
|
+
if (chunk.type === 'text-delta' || chunk.type === 'reasoning-delta') {
|
|
132
|
+
const type = chunk.type === 'text-delta' ? 'text' : 'reasoning';
|
|
133
|
+
yield* output.text(trim.take(type, chunk.text), type === 'reasoning');
|
|
134
|
+
}
|
|
135
|
+
else if (chunk.type === 'usage') {
|
|
136
|
+
yield* remainingUsage(chunk.usage, prefix.usage);
|
|
137
|
+
}
|
|
138
|
+
} };
|
|
139
|
+
let activePump, releasePump, terminalWaiting = false;
|
|
140
|
+
try {
|
|
141
|
+
for (;;) {
|
|
142
|
+
options.signal?.throwIfAborted();
|
|
143
|
+
try {
|
|
144
|
+
await broker.connect();
|
|
145
|
+
break;
|
|
146
|
+
}
|
|
147
|
+
catch (error) {
|
|
148
|
+
if (!(error instanceof NeedError) || !['ATTACH_BUSY', 'BROKER_ATTACH_FAILED'].includes(error.code))
|
|
149
|
+
throw error;
|
|
150
|
+
await new Promise((resolve, reject) => { const timer = setTimeout(resolve, record.heartbeatIntervalMs); const abort = () => { clearTimeout(timer); reject(options.signal?.reason); }; options.signal?.addEventListener('abort', abort, { once: true }); });
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
const saved = record.pending;
|
|
154
|
+
let pendingAction = false;
|
|
155
|
+
const settleOrphans = async () => { for (const [key, m] of pendingRequests) {
|
|
156
|
+
if (localCancellation) {
|
|
157
|
+
pendingRequests.clear();
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
if (record.answered.some(id => JSON.stringify(id) === key)) {
|
|
161
|
+
pendingRequests.delete(key);
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
await send(m.method === 'session/request_permission' ? { jsonrpc: '2.0', id: m.id, result: { outcome: { outcome: 'cancelled' } } } : { jsonrpc: '2.0', id: m.id, error: { code: -32603, message: 'EMPLOYEE_EXEC_UNKNOWN' } });
|
|
165
|
+
pendingRequests.delete(key);
|
|
166
|
+
} };
|
|
167
|
+
const restorePending = async () => {
|
|
168
|
+
if (!saved)
|
|
169
|
+
return;
|
|
170
|
+
const final = saved.baseSequence + saved.chunks;
|
|
171
|
+
let receipt = broker.inputReceipt;
|
|
172
|
+
if (receipt.pendingSequence === final) {
|
|
173
|
+
receipt = await broker.observeMessage(saved.id);
|
|
174
|
+
}
|
|
175
|
+
if (receipt.committedSequence === final && receipt.deliveredSequence >= final && receipt.lastMessage?.id === saved.id && receipt.lastMessage?.sha256 === saved.sha256 && receipt.lastMessage?.state === 'delivered') {
|
|
176
|
+
await afterMessage(final);
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
const rpc = JSON.parse(Buffer.from(saved.wire, 'base64').toString());
|
|
180
|
+
const permittedCancel = saved.method === 'session/cancel' && rpc.params?.sessionId === record.nativeId || saved.method === '$/cancel_request' && String(rpc.params?.requestId) === record.promptId;
|
|
181
|
+
if (saved.method === 'session/prompt') {
|
|
182
|
+
record = (await store.read(record.sessionId, record.provider));
|
|
183
|
+
if (record.cancelIntent) {
|
|
184
|
+
if (receipt.stagedMessageId === saved.id || receipt.lastMessage?.id === saved.id && receipt.lastMessage?.state === 'discarded')
|
|
185
|
+
receipt = await broker.discardMessage(saved.id);
|
|
186
|
+
else if (receipt.committedSequence !== saved.baseSequence || receipt.pendingSequence !== null || receipt.stagedMessageId)
|
|
187
|
+
throw coldNeed();
|
|
188
|
+
record = await store.update(record.sessionId, record.provider, record.id, row => { row.inputSequence = receipt.committedSequence; delete row.pending; row.cancelCheckpoint = { inputNotDelivered: true, receipt }; row.terminal = { kind: 'local-cancel', value: { inputNotDelivered: true } }; row.phase = 'terminal'; });
|
|
189
|
+
broker.completeRestoredInput();
|
|
190
|
+
localCancellation = true;
|
|
191
|
+
cancellationWake();
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
broker.authorizePrompt(() => !options.signal?.aborted && !record.cancelIntent);
|
|
195
|
+
await broker.resumeMessage(saved);
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
if (permittedCancel) {
|
|
199
|
+
record = await store.update(record.sessionId, record.provider, record.id, row => { row.cancelIntent ??= { source: 'wire' }; });
|
|
200
|
+
await broker.resumeMessage(saved);
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
// Old approvals/executions are never replayed. Only their unsent staging may be discarded.
|
|
204
|
+
if (receipt.stagedMessageId === saved.id || receipt.lastMessage?.id === saved.id && receipt.lastMessage?.state === 'discarded')
|
|
205
|
+
receipt = await broker.discardMessage(saved.id);
|
|
206
|
+
else if (receipt.committedSequence !== saved.baseSequence)
|
|
207
|
+
throw coldNeed();
|
|
208
|
+
record = await store.update(record.sessionId, record.provider, record.id, row => { row.inputSequence = receipt.committedSequence; delete row.pending; });
|
|
209
|
+
broker.completeRestoredInput();
|
|
210
|
+
};
|
|
211
|
+
const cancelOriginal = async () => { record = (await store.read(record.sessionId, record.provider)); if (record.cancelCheckpoint?.inputNotDelivered) {
|
|
212
|
+
localCancellation = true;
|
|
213
|
+
cancellationWake();
|
|
214
|
+
return;
|
|
215
|
+
} if (!record.cancelIntent || record.cancelIntent.delivered || nativeTerminalSeen)
|
|
216
|
+
return; if (!promptConfirmed && broker.promptDelivered !== true)
|
|
217
|
+
throw coldNeed(); await send({ jsonrpc: '2.0', method: 'session/cancel', params: { sessionId: record.nativeId } }); };
|
|
218
|
+
const incoming = [];
|
|
219
|
+
let readDone = false, readFailure, wake;
|
|
220
|
+
const notify = () => { wake?.(); wake = undefined; };
|
|
221
|
+
cancellationWake = notify;
|
|
222
|
+
const pump = (async () => {
|
|
223
|
+
try {
|
|
224
|
+
for (;;) {
|
|
225
|
+
const item = await reader.read();
|
|
226
|
+
if (item.done)
|
|
227
|
+
break;
|
|
228
|
+
const batch = Array.isArray(item.value) ? item.value : [item.value];
|
|
229
|
+
for (const m of batch) {
|
|
230
|
+
if (m.method === '_aw/broker-replay-complete') {
|
|
231
|
+
broker.confirmReplay(m.params?.generation);
|
|
232
|
+
replayed = true;
|
|
233
|
+
notify();
|
|
234
|
+
if (Array.isArray(m.params?.pendingClientRequests)) {
|
|
235
|
+
const ids = new Set(m.params.pendingClientRequests.map((r) => JSON.stringify(r.id)));
|
|
236
|
+
for (const key of pendingRequests.keys())
|
|
237
|
+
if (!ids.has(key))
|
|
238
|
+
pendingRequests.delete(key);
|
|
239
|
+
}
|
|
240
|
+
if (!pendingAction) {
|
|
241
|
+
pendingAction = true;
|
|
242
|
+
enqueue(async () => { await restorePending(); await cancelOriginal(); cancelHandled = true; notify(); });
|
|
243
|
+
}
|
|
244
|
+
enqueue(settleOrphans);
|
|
245
|
+
continue;
|
|
246
|
+
}
|
|
247
|
+
if (m.method && Object.hasOwn(m, 'id')) {
|
|
248
|
+
pendingRequests.set(JSON.stringify(m.id), m);
|
|
249
|
+
if (replayed)
|
|
250
|
+
enqueue(settleOrphans);
|
|
251
|
+
continue;
|
|
252
|
+
}
|
|
253
|
+
if (!m.method && Object.hasOwn(m, 'id') && String(m.id) === record.promptId)
|
|
254
|
+
nativeTerminalSeen = true;
|
|
255
|
+
if (terminalWaiting)
|
|
256
|
+
continue;
|
|
257
|
+
const consumed = Promise.withResolvers();
|
|
258
|
+
releasePump = consumed.resolve;
|
|
259
|
+
incoming.push(m);
|
|
260
|
+
notify();
|
|
261
|
+
await consumed.promise;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
catch (error) {
|
|
266
|
+
readFailure = error;
|
|
267
|
+
}
|
|
268
|
+
finally {
|
|
269
|
+
readDone = true;
|
|
270
|
+
notify();
|
|
271
|
+
}
|
|
272
|
+
})();
|
|
273
|
+
// Keep the reader alive independently while outgoing controls await a new replay barrier.
|
|
274
|
+
activePump = pump;
|
|
275
|
+
for await (const chunk of projection(mapper.text(record.meta.prelude ?? '')))
|
|
276
|
+
yield chunk;
|
|
277
|
+
mapper.flush();
|
|
278
|
+
let nativeUpdates = 0, noticeIndex = 0;
|
|
279
|
+
const notices = function* () { while (record.localNotices?.[noticeIndex]?.beforeUpdate === nativeUpdates) {
|
|
280
|
+
const notice = record.localNotices[noticeIndex++];
|
|
281
|
+
yield* projection(mapper.text(notice.text, notice.kind === 'reasoning'));
|
|
282
|
+
} };
|
|
283
|
+
yield* notices();
|
|
284
|
+
for (;;) {
|
|
285
|
+
options.signal?.throwIfAborted();
|
|
286
|
+
if (options.cancelOnly && cancelHandled)
|
|
287
|
+
return;
|
|
288
|
+
if (localCancellation) {
|
|
289
|
+
yield* output.flush();
|
|
290
|
+
if (!options.markerId)
|
|
291
|
+
throw new NeedError('ABORTED', '原轮在送达前已取消,未执行', '原消息未派发回执');
|
|
292
|
+
yield* recoverLocalCancellation(record, store, options.markerId);
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
if (!incoming.length) {
|
|
296
|
+
if (readFailure)
|
|
297
|
+
throw readFailure;
|
|
298
|
+
if (readDone)
|
|
299
|
+
break;
|
|
300
|
+
await new Promise(resolve => { wake = resolve; });
|
|
301
|
+
continue;
|
|
302
|
+
}
|
|
303
|
+
const m = incoming.shift();
|
|
304
|
+
releasePump?.();
|
|
305
|
+
releasePump = undefined;
|
|
306
|
+
if (m.method === 'session/update') {
|
|
307
|
+
if (m.params?.sessionId !== record.nativeId)
|
|
308
|
+
throw coldNeed('SESSION_CONTEXT_MISMATCH');
|
|
309
|
+
if (!isKnownAcpUpdate(m.params.update))
|
|
310
|
+
continue;
|
|
311
|
+
yield* projection(mapper.acp(m.params.update));
|
|
312
|
+
nativeUpdates++;
|
|
313
|
+
yield* notices();
|
|
314
|
+
continue;
|
|
315
|
+
}
|
|
316
|
+
if (!m.method && Object.hasOwn(m, 'id')) {
|
|
317
|
+
if (String(m.id) !== record.promptId) {
|
|
318
|
+
if (!record.rpcIds.includes(m.id))
|
|
319
|
+
throw coldNeed('ACP_FOREIGN_RESPONSE');
|
|
320
|
+
continue;
|
|
321
|
+
}
|
|
322
|
+
terminalWaiting = true;
|
|
323
|
+
while (!replayed && !readDone)
|
|
324
|
+
await new Promise(resolve => { wake = resolve; });
|
|
325
|
+
if (!replayed)
|
|
326
|
+
throw readFailure ?? coldNeed();
|
|
327
|
+
await outboundTail;
|
|
328
|
+
if (readFailure)
|
|
329
|
+
throw readFailure;
|
|
330
|
+
if (options.cancelOnly)
|
|
331
|
+
return;
|
|
332
|
+
terminal = true;
|
|
333
|
+
await store.update(record.sessionId, record.provider, record.id, row => { row.terminal = { kind: m.error ? 'error' : 'result', value: m.error ?? m.result }; row.phase = 'terminal'; row.terminalAfter = broker.lastSequence; });
|
|
334
|
+
if (m.error) {
|
|
335
|
+
trim.finish();
|
|
336
|
+
// The original agent failed authentication (same judgment as a live round): its login is no longer valid. End it first, so the next round
|
|
337
|
+
// resumes the original native session with the current login (Codex holds one writer per thread); then settle without resending the task.
|
|
338
|
+
if (options.markerId && acpNeed(new acp.RequestError(m.error.code, m.error.message, m.error.data)).code === 'LOGIN_REQUIRED') {
|
|
339
|
+
await options.io.run(command(['kill', record.brokerId, '--if-instance', record.instanceId]), options.signal).catch(() => { options.signal?.throwIfAborted(); console.warn('[remote-agent] 旧主机会话暂未清理,将由主机自动回收'); });
|
|
340
|
+
yield* output.flush();
|
|
341
|
+
yield* output.text(LOGIN_ENDED);
|
|
342
|
+
yield* output.flush();
|
|
343
|
+
yield { type: 'finish', reason: { kind: 'stop' }, replayState: { response: coldPointer(record, broker.lastSequence) } };
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
if (!options.markerId)
|
|
347
|
+
throw new NeedError('ACP_FAILED', '原轮返回错误,没有另开模型轮或重放输入', '原RPC错误码 ' + String(m.error.code));
|
|
348
|
+
const token = randomUUID(), message = '原轮返回错误(' + String(m.error.code) + '),没有重新发送原任务;恢复回执 ' + token;
|
|
349
|
+
await store.update(record.sessionId, record.provider, record.id, row => { row.errorDelivery = { markerId: options.markerId, promptId: record.promptId, code: 'ACP_FAILED', token, message }; });
|
|
350
|
+
throw new LlmError(message, 'ACP_FAILED', { cause: m.error });
|
|
351
|
+
}
|
|
352
|
+
if (!m.result || typeof m.result.stopReason !== 'string')
|
|
353
|
+
throw coldNeed();
|
|
354
|
+
yield* projection(mapper.acpResponse(m.result));
|
|
355
|
+
if (m.result.stopReason === 'cancelled') {
|
|
356
|
+
trim.finish();
|
|
357
|
+
if (!options.markerId)
|
|
358
|
+
throw new NeedError('ABORTED', '原模型轮已取消,没有另开轮次', '原会话取消结果');
|
|
359
|
+
const token = randomUUID(), message = '原模型轮已取消,没有另开轮次;恢复回执 ' + token;
|
|
360
|
+
await store.update(record.sessionId, record.provider, record.id, row => { row.errorDelivery = { markerId: options.markerId, promptId: record.promptId, code: 'ABORTED', token, message }; });
|
|
361
|
+
throw new LlmError(message, 'ABORTED');
|
|
362
|
+
}
|
|
363
|
+
if (m.result.stopReason === 'refusal')
|
|
364
|
+
yield* projection(mapper.text('\n[远端拒绝] 此请求未执行。\n'));
|
|
365
|
+
trim.finish();
|
|
366
|
+
yield* output.flush();
|
|
367
|
+
delivered = true;
|
|
368
|
+
yield { type: 'finish', reason: { kind: ['max_tokens', 'max_turn_requests'].includes(m.result.stopReason) ? 'max-tokens' : 'stop' }, replayState: { response: coldPointer(record, broker.lastSequence) } };
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
if (!terminal)
|
|
373
|
+
throw coldNeed('CONNECTION_LOST');
|
|
374
|
+
}
|
|
375
|
+
finally {
|
|
376
|
+
options.signal?.removeEventListener('abort', cancel);
|
|
377
|
+
replayOff();
|
|
378
|
+
if (options.signal?.aborted && options.signal.reason?.kind !== 'disposed')
|
|
379
|
+
await outboundTail.catch(() => { });
|
|
380
|
+
broker.close({ layer: 'broker', initiator: 'cold.detach', reason: 'SESSION_DETACHED', action: 'detach' });
|
|
381
|
+
releasePump?.();
|
|
382
|
+
await outboundTail.catch(() => { });
|
|
383
|
+
await activePump;
|
|
384
|
+
await cancelNote?.catch(() => { });
|
|
385
|
+
reader.releaseLock();
|
|
386
|
+
writer.releaseLock();
|
|
387
|
+
// The recovered result is delivered: end its host agent so the next round can own the native thread.
|
|
388
|
+
if (delivered && !options.signal?.aborted)
|
|
389
|
+
void options.io.run(command(['kill', record.brokerId, '--if-instance', record.instanceId])).catch(() => console.warn('[remote-agent] 旧主机会话暂未清理,将由主机自动回收'));
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
/** 本地未派发取消的证明来自写前记录或S消息回执,不伪造原生RPC终态。 */
|
|
393
|
+
export async function* recoverLocalCancellation(record, store, markerId) {
|
|
394
|
+
if (!record.cancelIntent || !record.cancelCheckpoint?.inputNotDelivered || record.terminal?.kind !== 'local-cancel')
|
|
395
|
+
throw coldNeed();
|
|
396
|
+
const token = randomUUID(), message = '原轮已在送达前取消,没有执行或重新发送原任务;恢复回执 ' + token;
|
|
397
|
+
await store.update(record.sessionId, record.provider, record.id, row => { row.errorDelivery = { markerId, promptId: record.promptId, code: 'ABORTED', token, message }; });
|
|
398
|
+
throw new LlmError(message, 'ABORTED');
|
|
399
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { Context } from '@deepseek-ai/cordis';
|
|
2
|
+
import { type SessionEvent, type SessionHeader } from '@deepseek-ai/dsh-session';
|
|
3
|
+
import { type LlmResolvedModelInfo, type GenerateOptions, type StreamChunk } from '@deepseek-ai/dsh-llm';
|
|
4
|
+
import { type ColdRound, type ColdStore } from './cold-store.ts';
|
|
5
|
+
import { type Runtime, type ConnectApi } from './provider.ts';
|
|
6
|
+
import { type BrokerIo, type SshArgv } from './broker.ts';
|
|
7
|
+
declare module '@deepseek-ai/dsh-llm' {
|
|
8
|
+
interface MessageSourceMap {
|
|
9
|
+
'ai-workbench-cold-recovery': {
|
|
10
|
+
kind: 'ai-workbench-cold-recovery';
|
|
11
|
+
roundId: string;
|
|
12
|
+
form: 'notice';
|
|
13
|
+
summary: string;
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
export declare const recoveryMarker: (message: any) => string | undefined;
|
|
18
|
+
export declare class ColdRecovery {
|
|
19
|
+
private ctx;
|
|
20
|
+
private getConnect;
|
|
21
|
+
private config;
|
|
22
|
+
private provided?;
|
|
23
|
+
readonly store: ColdStore;
|
|
24
|
+
private queues;
|
|
25
|
+
private scheduled;
|
|
26
|
+
private live;
|
|
27
|
+
private lifetime;
|
|
28
|
+
private cancellationWatches;
|
|
29
|
+
private steps;
|
|
30
|
+
constructor(ctx: Context, getConnect: () => ConnectApi | undefined, config: () => {
|
|
31
|
+
acpMaxMessageBytes?: number;
|
|
32
|
+
brokerMaxFrameBytes?: number;
|
|
33
|
+
brokerControlMaxBytes?: number;
|
|
34
|
+
}, provided?: {
|
|
35
|
+
store?: ColdStore;
|
|
36
|
+
readSource?: (id: string) => Promise<unknown>;
|
|
37
|
+
io?: (r: ColdRound) => BrokerIo;
|
|
38
|
+
argv?: SshArgv;
|
|
39
|
+
} | undefined);
|
|
40
|
+
dispose(): void;
|
|
41
|
+
events(sessionId: string, header?: SessionHeader): Promise<readonly SessionEvent[]>;
|
|
42
|
+
capture(runtime: Runtime, options: GenerateOptions, nativeId: string | undefined, meta: Omit<NonNullable<ColdRound['meta']>, 'header' | 'inputDigests'>): Promise<void>;
|
|
43
|
+
recordUserCancellation(runtime: Runtime, options: GenerateOptions, nativeId: string | undefined, fallback: Omit<NonNullable<ColdRound['meta']>, 'header' | 'inputDigests'>): Promise<void>;
|
|
44
|
+
private adoptUserCancellation;
|
|
45
|
+
private reconcile;
|
|
46
|
+
private queueSnapshot;
|
|
47
|
+
private schedule;
|
|
48
|
+
private settleUserCancellation;
|
|
49
|
+
private watchCancellation;
|
|
50
|
+
install(): void;
|
|
51
|
+
/** Official user cancellation is an input disposition even before a remote runtime exists. */
|
|
52
|
+
projectCancelledInputs(options: GenerateOptions): Promise<GenerateOptions>;
|
|
53
|
+
previousPointer(options: GenerateOptions): Promise<any>;
|
|
54
|
+
release(sessionId: string, id: string): void;
|
|
55
|
+
/** This handle only replays an existing round. Its envelope follows this
|
|
56
|
+
* step's choice; it neither selects nor advertises capabilities for a new model. */
|
|
57
|
+
recoveryModel(provider: string, model: string, signal?: AbortSignal): LlmResolvedModelInfo | undefined;
|
|
58
|
+
canRecover(options: GenerateOptions): boolean;
|
|
59
|
+
private connection;
|
|
60
|
+
stream(options: GenerateOptions, lifetime?: AbortSignal): AsyncGenerator<StreamChunk>;
|
|
61
|
+
private streamRound;
|
|
62
|
+
}
|