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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,427 @@
1
+ import { watch } from 'node:fs';
2
+ import { dirname } from 'node:path';
3
+ import { lstat, realpath } from 'node:fs/promises';
4
+ import { modelInfo } from "./model-catalog.js";
5
+ import { SessionId } from '@deepseek-ai/dsh-session';
6
+ import { expandAssistantStream, createUserMessage } from '@deepseek-ai/dsh-llm';
7
+ import { isDeepStrictEqual } from 'node:util';
8
+ import { createHash } from 'node:crypto';
9
+ import { createColdStore, coldNeed } from "./cold-store.js";
10
+ import { recoverColdProtocol } from "./cold-protocol.js";
11
+ import { sameStoredSessionHeader } from "./session-header.js";
12
+ import { awaitL, identity, unwrap } from "./provider.js";
13
+ import { sshIo } from "./broker.js";
14
+ const sourceKind = 'ai-workbench-cold-recovery';
15
+ export const recoveryMarker = (message) => message?.role === 'user' && message.source?.kind === sourceKind && typeof message.source?.roundId === 'string' ? message.source.roundId : undefined;
16
+ const digest = (message) => createHash('sha256').update(JSON.stringify(message)).digest('hex');
17
+ export class ColdRecovery {
18
+ ctx;
19
+ getConnect;
20
+ config;
21
+ provided;
22
+ store;
23
+ queues = new WeakMap();
24
+ scheduled = new WeakMap();
25
+ live = new Map();
26
+ steps = new Map();
27
+ constructor(ctx, getConnect, config, provided) {
28
+ this.ctx = ctx;
29
+ this.getConnect = getConnect;
30
+ this.config = config;
31
+ this.provided = provided;
32
+ this.store = provided?.store ?? createColdStore(ctx);
33
+ }
34
+ async events(sessionId, header) {
35
+ const sessions = this.ctx.get('sessions'), session = sessions?.get(SessionId(sessionId)), persistence = this.ctx.get('sessionPersistence');
36
+ if (!session || !persistence?.identity || !await sessions.flush(session))
37
+ throw coldNeed();
38
+ const handle = await persistence.open(session.id, 'read');
39
+ try {
40
+ if (handle.id !== session.id || handle.access !== 'read' || !sameStoredSessionHeader(handle.header, session.header) || header && !sameStoredSessionHeader(handle.header, header))
41
+ throw coldNeed('SESSION_CONTEXT_MISMATCH');
42
+ const result = await handle.read();
43
+ return result.events;
44
+ }
45
+ finally {
46
+ await handle.close();
47
+ }
48
+ }
49
+ async capture(runtime, options, nativeId, meta) {
50
+ if (!runtime.cold || !options.sessionId)
51
+ return;
52
+ const session = this.ctx.get('sessions')?.get(SessionId(options.sessionId));
53
+ if (!session)
54
+ throw coldNeed();
55
+ if (this.provided?.readSource && !isDeepStrictEqual(meta.hostSource ?? { source: 'local' }, await this.provided.readSource(options.sessionId)))
56
+ throw coldNeed('SESSION_CONTEXT_MISMATCH');
57
+ const events = await this.events(options.sessionId), header = structuredClone(session.header);
58
+ let turn, step;
59
+ for (const e of events) {
60
+ if (e.type === 'turn/start') {
61
+ turn = e.data.turn;
62
+ step = undefined;
63
+ }
64
+ else if (e.type === 'step/start') {
65
+ step = e.data.step;
66
+ }
67
+ else if (e.type === 'turn/end') {
68
+ turn = undefined;
69
+ step = undefined;
70
+ }
71
+ }
72
+ if (turn === undefined || step === undefined)
73
+ throw coldNeed();
74
+ let t, s;
75
+ const inputs = [];
76
+ for (const e of events) {
77
+ if (e.type === 'turn/start')
78
+ t = e.data.turn;
79
+ else if (e.type === 'step/start')
80
+ s = e.data.step;
81
+ else if (e.type === 'user/message' && t === turn && s === step)
82
+ inputs.push(e.data);
83
+ }
84
+ const inputDigests = Object.fromEntries(inputs.map(m => [m.id, digest(m)]));
85
+ if (!inputs.length)
86
+ throw coldNeed();
87
+ const { provider, model, reasoningEffort, temperature, maxTokens, stop } = options;
88
+ await runtime.cold.prepare(nativeId, { ...meta, header, inputDigests, callConfig: { provider, model, reasoningEffort, temperature, maxTokens, stop } });
89
+ await this.store.update(options.sessionId, options.provider, runtime.cold.id, row => { row.originTurn = turn; row.originStep = step; });
90
+ this.live.set(options.sessionId, runtime.cold.id);
91
+ }
92
+ async reconcile(row, events) {
93
+ const owns = (pointer) => pointer?.coldRoundId === row.id && pointer.coldRoundTerminal === true && pointer.sessionId === row.nativeId && pointer.dshSessionId === row.sessionId && pointer.agent === row.provider && pointer.coldPromptId === row.promptId;
94
+ let settled = events.find(e => e.type === 'assistant/message' && e.data.message.source.provider === row.provider && owns(e.data.message.source.replayState?.response));
95
+ if (!settled)
96
+ settled = events.find(e => e.type === 'assistant/attempt' && expandAssistantStream(e.data.stream).some(item => { const chunk = item.chunk; if (chunk.type !== 'finish' || !['stop', 'max-tokens'].includes(chunk.reason.kind))
97
+ return false; const response = chunk.replayState?.response; return owns(response); }));
98
+ if (!settled && (row.terminal?.kind === 'error' || row.terminal?.kind === 'result' && row.terminal.value?.stopReason === 'cancelled') && row.errorDelivery && row.errorDelivery.promptId === row.promptId) {
99
+ const delivery = row.errorDelivery;
100
+ let turn, step, ours = false;
101
+ for (const e of events) {
102
+ if (e.type === 'turn/start') {
103
+ turn = e.data.turn;
104
+ ours = false;
105
+ }
106
+ else if (e.type === 'step/start') {
107
+ step = e.data.step;
108
+ ours = false;
109
+ }
110
+ else if (e.type === 'user/message' && e.data.id === delivery.markerId && recoveryMarker(e.data) === row.id)
111
+ ours = true;
112
+ else if (e.type === 'assistant/attempt' && ours && e.data.turn === turn && e.data.step === step && expandAssistantStream(e.data.stream).some(item => item.chunk.type === 'finish' && (item.chunk.reason.kind === 'error' || item.chunk.reason.kind === 'aborted') && item.chunk.reason.failure?.code === delivery.code && item.chunk.reason.failure?.message === delivery.message))
113
+ settled = e;
114
+ }
115
+ }
116
+ if (!settled)
117
+ return false;
118
+ await this.store.update(row.sessionId, row.provider, row.id, r => { r.phase = 'committed'; r.officialSeq = settled.seq; r.outputAfter = (settled.type === 'assistant/message' ? settled.data.message.source.replayState?.response?.coldOutputAfter : undefined) ?? r.terminalAfter ?? 0; delete r.pending; });
119
+ return true;
120
+ }
121
+ queueSnapshot(agent) { const q = this.queues.get(agent) ?? new Map(); for (const m of agent.inbox.nextStep)
122
+ q.set(m.id, 'next-step'); for (const m of agent.inbox.nextTurn)
123
+ q.set(m.id, 'next-turn'); this.queues.set(agent, q); return q; }
124
+ async schedule(agent) {
125
+ const provider = agent.options.provider;
126
+ if (typeof provider !== 'string')
127
+ return;
128
+ const row = await this.store.read(agent.session.id, provider);
129
+ if (!row || !['running', 'terminal'].includes(row.phase) || !row.promptId || this.live.get(row.sessionId) === row.id || this.scheduled.get(agent) === row.id)
130
+ return;
131
+ if (!row.meta || !sameStoredSessionHeader(row.meta.header, agent.session.header))
132
+ throw coldNeed('SESSION_CONTEXT_MISMATCH');
133
+ if (await this.reconcile(row, await this.events(row.sessionId, row.meta.header)))
134
+ return;
135
+ this.queueSnapshot(agent);
136
+ this.scheduled.set(agent, row.id);
137
+ const existing = [...agent.inbox.nextStep, ...agent.inbox.nextTurn].find(m => recoveryMarker(m) === row.id);
138
+ for (const target of ['next-step', 'next-turn']) {
139
+ const queue = target === 'next-step' ? agent.inbox.nextStep : agent.inbox.nextTurn;
140
+ for (let index = queue.length - 1; index >= 0; index--)
141
+ if (recoveryMarker(queue[index]) === row.id)
142
+ agent.inbox.splice(target, index, 1, []);
143
+ }
144
+ agent.send(existing ?? createUserMessage({ source: { kind: sourceKind, roundId: row.id, form: 'notice', summary: '接回退出前原轮结果' }, content: [{ type: 'text', text: '正在接回退出前的原轮结果;没有重新发送原任务。' }] }), 'next-step', true);
145
+ }
146
+ install() {
147
+ this.ctx.on('agent/created', async ({ agent, source }) => { if (source === 'resume')
148
+ await this.schedule(agent); });
149
+ this.ctx.on('agent/inbox/inserted', ({ agent }) => { this.queueSnapshot(agent); });
150
+ this.ctx.on('agent/pre-step', async (payload, next) => {
151
+ const decision = await next();
152
+ if (decision.kind !== 'enter')
153
+ return decision;
154
+ this.steps.delete(payload.agent);
155
+ let markers = decision.messages.filter(m => recoveryMarker(m));
156
+ if (!markers.length && !this.scheduled.has(payload.agent))
157
+ return decision;
158
+ const claimed = new Set(payload.messages.map(m => m.id)), q = this.queues.get(payload.agent);
159
+ let restored = false;
160
+ const restoreHumans = () => { if (restored)
161
+ return; restored = true; for (const target of ['next-step', 'next-turn']) {
162
+ const messages = decision.messages.filter(m => claimed.has(m.id) && !recoveryMarker(m) && (q?.get(m.id) ?? 'next-step') === target);
163
+ if (messages.length)
164
+ payload.agent.inbox.splice(target, 0, 0, messages);
165
+ } };
166
+ try {
167
+ const row = await this.store.read(payload.agent.session.id, String(payload.agent.options.provider));
168
+ if (!markers.length && row && ['running', 'terminal'].includes(row.phase) && row.promptId && this.live.get(row.sessionId) !== row.id) {
169
+ if (await this.reconcile(row, await this.events(row.sessionId, row.meta?.header)))
170
+ return decision;
171
+ markers = [createUserMessage({ source: { kind: sourceKind, roundId: row.id, form: 'notice', summary: '接回退出前原轮结果' }, content: [{ type: 'text', text: '正在接回退出前的原轮结果;没有重新发送原任务。' }] })];
172
+ }
173
+ if (!markers.length)
174
+ return decision;
175
+ if (!row || markers.some(m => recoveryMarker(m) !== row.id) || !['running', 'terminal'].includes(row.phase))
176
+ throw coldNeed('SESSION_CONTEXT_MISMATCH');
177
+ restoreHumans();
178
+ this.steps.set(payload.agent, { turn: payload.turn, step: payload.step, signal: payload.signal, row, markerId: markers[0].id });
179
+ return { ...decision, messages: [...markers, ...decision.messages.filter(m => !claimed.has(m.id) && !recoveryMarker(m))] };
180
+ }
181
+ catch (error) {
182
+ restoreHumans();
183
+ throw error;
184
+ }
185
+ });
186
+ this.ctx.on('agent/request', async (payload, next) => { const config = await next(), step = this.steps.get(payload.agent); if (step && step.turn === payload.turn && step.step === payload.step && step.signal === payload.signal)
187
+ return structuredClone(step.row.meta.callConfig ?? { provider: step.row.provider, model: step.row.meta.model, reasoningEffort: step.row.meta.modelConfiguration?.selected?.effort }); return config; });
188
+ this.ctx.on('agent/disposed', ({ agent }) => { this.steps.delete(agent); this.scheduled.delete(agent); this.live.delete(agent.session.id); });
189
+ this.ctx.on('session/event', (session, event) => { if (event.type === 'step/end' || event.type === 'turn/end') {
190
+ for (const [agent, step] of this.steps)
191
+ if (agent.session.id === session.id && step.turn === event.data.turn && (event.type === 'turn/end' || step.step === event.data.step))
192
+ this.steps.delete(agent);
193
+ } if (event.type === 'turn/end') {
194
+ void (async () => { for (const provider of ['codex-remote', 'claude-code-workbench']) {
195
+ const row = await this.store.read(session.id, provider);
196
+ if (row?.terminal && row.phase !== 'committed')
197
+ await this.reconcile(row, await this.events(session.id, row.meta?.header));
198
+ } })().catch(() => this.ctx.logger('remote-agent').warn('INPUT_DELIVERY_UNCONFIRMED:原轮终态落盘未确认'));
199
+ } if (event.type === 'assistant/message') {
200
+ const pointer = event.data.message.source.replayState?.response;
201
+ if (pointer?.coldRoundTerminal && pointer?.coldRoundId)
202
+ void (async () => { const row = await this.store.read(session.id, event.data.message.source.provider); if (row && row.id === pointer.coldRoundId)
203
+ await this.reconcile(row, await this.events(session.id, row.meta?.header)); })().catch(() => this.ctx.logger('remote-agent').warn('INPUT_DELIVERY_UNCONFIRMED:原轮结果已返回,持久提交暂未确认'));
204
+ } });
205
+ for (const agent of this.ctx.get('agents')?.list?.() ?? [])
206
+ void (async () => { await agent.whenIdle(); if (this.ctx.get('agents')?.get(agent.session.id) !== agent)
207
+ return; await agent.runMaintenance(async () => { await this.schedule(agent); }); })().catch(() => this.ctx.logger('remote-agent').warn('INPUT_DELIVERY_UNCONFIRMED:冷恢复初始化未确认'));
208
+ }
209
+ async previousPointer(options) {
210
+ if (!options.sessionId || !this.provided?.store && !this.ctx.get('storageDomain'))
211
+ return;
212
+ let row = await this.store.read(options.sessionId, options.provider);
213
+ if (!row || !row.meta || !row.nativeId || !row.terminal)
214
+ return;
215
+ if (row.phase !== 'committed') {
216
+ if (!await this.reconcile(row, await this.events(row.sessionId, row.meta.header)))
217
+ throw coldNeed();
218
+ row = (await this.store.read(options.sessionId, options.provider));
219
+ }
220
+ const index = options.messages.findLastIndex(m => recoveryMarker(m) === row.id);
221
+ if (index < 0)
222
+ return;
223
+ await this.events(row.sessionId, row.meta.header);
224
+ const m = row.meta, usage = row.finalUsage ?? null;
225
+ return { index, pointer: { version: 2, agent: row.provider, dshSessionId: row.sessionId, identity: m.identity, cwd: m.cwd, sessionId: row.nativeId, contextSha256: m.contextSha256, usageSnapshot: usage, ...(m.binding ? { bindingId: m.binding.bindingId, workspaceId: m.binding.workspaceId } : {}), ...(m.hostSource ? { hostSource: m.hostSource } : {}), ...(m.modelConfiguration ? { modelConfiguration: m.modelConfiguration } : {}) } };
226
+ }
227
+ release(sessionId, id) { if (this.live.get(sessionId) === id)
228
+ this.live.delete(sessionId); }
229
+ recoveryModel(provider, model, signal) { for (const step of this.steps.values()) {
230
+ if (step.signal === signal && step.row.provider === provider && step.row.meta?.model === model) {
231
+ const selected = step.row.meta.modelConfiguration?.selected;
232
+ if (!selected)
233
+ throw coldNeed();
234
+ return modelInfo(provider, selected);
235
+ }
236
+ } }
237
+ canRecover(options) { return !options.purpose && [...this.steps].some(([agent, step]) => agent.session.id === options.sessionId && step.row.provider === options.provider && step.row.meta?.model === options.model && step.signal === options.signal && !step.signal.aborted && options.messages.some(m => m.id === step.markerId && recoveryMarker(m) === step.row.id)); }
238
+ async connection(signal, binding) {
239
+ for (;;) {
240
+ signal?.throwIfAborted();
241
+ const api = this.getConnect(), stamp = api ? JSON.stringify([api.getConnectionState?.(), binding?.binding ? api.getWorkspaceLocationState?.() : undefined]) : '';
242
+ if (api) {
243
+ if (binding?.binding && (!api.getWorkspaceLocationState || !api.onWorkspaceLocationState || !api.onConnectionState))
244
+ throw coldNeed('DEPENDENCY_REQUIRED');
245
+ const location = binding?.binding ? api.getWorkspaceLocationState?.() : undefined;
246
+ if (binding?.binding && (location?.phase === 'disposed' || location?.phase === 'failed' && location.need && !['HOST_OFFLINE', 'SSH_FAILED', 'CONNECTION_LOST'].includes(location.need.code)))
247
+ throw coldNeed(location?.need?.code ?? 'SESSION_CONTEXT_MISMATCH');
248
+ const state = api.getConnectionState?.();
249
+ if (!state || state.phase === 'connected') {
250
+ const result = await awaitL(() => api.getSshTarget(), signal);
251
+ if (result.ok) {
252
+ if (!binding?.binding || api.getWorkspaceLocationState?.().phase === 'ready')
253
+ return { api, target: result.value, connection: state };
254
+ }
255
+ else if (!['HOST_OFFLINE', 'SSH_FAILED', 'CONNECTION_LOST'].includes(result.error.code))
256
+ unwrap(result);
257
+ }
258
+ else if (state.phase === 'disposed' || state.need && !['HOST_OFFLINE', 'SSH_FAILED', 'CONNECTION_LOST'].includes(state.need.code))
259
+ throw coldNeed(state.need?.code ?? 'CONNECTION_REQUIRED');
260
+ }
261
+ await new Promise((resolve, reject) => { const offs = []; const clear = () => { for (const off of offs)
262
+ off(); signal?.removeEventListener('abort', abort); }; const wake = () => { clear(); resolve(); }; const abort = () => { clear(); reject(signal?.reason); }; offs.push(this.ctx.on('internal/service', name => { if (name === 'aiWorkbenchConnect')
263
+ wake(); })); if (api?.onConnectionState)
264
+ offs.push(api.onConnectionState(wake)); if (api?.onWorkspaceLocationState)
265
+ offs.push(api.onWorkspaceLocationState(wake)); signal?.addEventListener('abort', abort, { once: true }); if (signal?.aborted)
266
+ abort();
267
+ else if (this.getConnect() !== api || api && JSON.stringify([api.getConnectionState?.(), binding?.binding ? api.getWorkspaceLocationState?.() : undefined]) !== stamp)
268
+ wake(); });
269
+ }
270
+ }
271
+ async *stream(options) {
272
+ if (!this.canRecover(options) || !options.sessionId)
273
+ throw coldNeed();
274
+ const markers = options.messages.filter(m => recoveryMarker(m)), id = recoveryMarker(markers.at(-1));
275
+ const selected = [...this.steps.values()].find(step => step.signal === options.signal && step.row.id === id);
276
+ const row = await this.store.read(options.sessionId, options.provider);
277
+ if (!selected || !row || row.id !== id || !row.meta || !row.nativeId || !['running', 'terminal'].includes(row.phase))
278
+ throw coldNeed();
279
+ const events = await this.events(row.sessionId, row.meta.header);
280
+ if (this.provided?.readSource && !isDeepStrictEqual(row.meta.hostSource ?? { source: 'local' }, await this.provided.readSource(row.sessionId)))
281
+ throw coldNeed('SESSION_CONTEXT_MISMATCH');
282
+ for (const [inputId, expected] of Object.entries(row.meta.inputDigests ?? {})) {
283
+ const e = events.find(e => e.type === 'user/message' && e.data.id === inputId);
284
+ if (!e || digest(e.data) !== expected)
285
+ throw coldNeed('SESSION_CONTEXT_MISMATCH');
286
+ }
287
+ const { api, target, connection: initialConnection } = await this.connection(options.signal, row.meta);
288
+ if (identity(target) !== row.meta.identity || !isDeepStrictEqual(target, row.target))
289
+ throw coldNeed('SESSION_CONTEXT_MISMATCH');
290
+ if (row.meta.binding) {
291
+ if (typeof api.onWorkspaceLocationState !== 'function' || typeof api.onConnectionState !== 'function')
292
+ throw coldNeed('DEPENDENCY_REQUIRED');
293
+ const state = api.getWorkspaceLocationState?.(), matches = state?.items.filter(x => x.workspaceId === row.meta.binding.workspaceId);
294
+ if (state?.phase !== 'ready' || matches?.length !== 1 || matches[0].bindingId !== row.meta.binding.bindingId || matches[0].status !== 'selected' || matches[0].source !== (row.meta.hostSource ? 'host' : 'local'))
295
+ throw coldNeed('SESSION_CONTEXT_MISMATCH');
296
+ }
297
+ if (row.meta.localDirectory) {
298
+ try {
299
+ const expected = row.meta.localDirectory, current = await lstat(expected.path), canonical = await realpath(expected.path);
300
+ if (!current.isDirectory() || current.isSymbolicLink() || canonical !== expected.path || current.dev !== expected.device || current.ino !== expected.inode)
301
+ throw coldNeed('EMPLOYEE_CONTEXT_CHANGED');
302
+ }
303
+ catch {
304
+ throw coldNeed('EMPLOYEE_CONTEXT_CHANGED');
305
+ }
306
+ }
307
+ const attempts = new Set([JSON.stringify([row.originTurn, row.originStep])]);
308
+ let turn, step;
309
+ for (const e of events) {
310
+ if (e.type === 'turn/start')
311
+ turn = e.data.turn;
312
+ else if (e.type === 'step/start')
313
+ step = e.data.step;
314
+ else if (e.type === 'user/message' && recoveryMarker(e.data) === row.id)
315
+ attempts.add(JSON.stringify([turn, step]));
316
+ }
317
+ const blocks = [], usage = { inputTokens: 0, outputTokens: 0 };
318
+ for (const e of events) {
319
+ if (!['assistant/message', 'assistant/attempt'].includes(e.type))
320
+ continue;
321
+ const d = e.data;
322
+ const pointer = d.message?.source?.replayState?.response;
323
+ if (!attempts.has(JSON.stringify([d.turn, d.step])) && pointer?.coldRoundId !== row.id && !(d.turn === row.originTurn && d.step >= row.originStep))
324
+ continue;
325
+ if (e.type === 'assistant/message' && d.message.source.provider !== row.provider)
326
+ continue;
327
+ const data = e.data;
328
+ if (e.type === 'assistant/message')
329
+ blocks.push(...data.message.content);
330
+ else {
331
+ const llm = await import('@deepseek-ai/dsh-llm');
332
+ const assembler = new llm.BlockAssembler();
333
+ for (const item of llm.expandAssistantStream(data.stream ?? [])) {
334
+ assembler.push(item.chunk);
335
+ if (item.chunk.type === 'usage')
336
+ for (const [key, value] of Object.entries(item.chunk.usage))
337
+ if (typeof value === 'number')
338
+ usage[key] = (usage[key] ?? 0) + value;
339
+ }
340
+ blocks.push(...assembler.blocks());
341
+ }
342
+ for (const [key, value] of Object.entries(data.usage ?? {}))
343
+ if (typeof value === 'number')
344
+ usage[key] = (usage[key] ?? 0) + value;
345
+ }
346
+ let io = this.provided?.io?.(row);
347
+ if (!io) {
348
+ const argv = this.provided?.argv ?? (await import('@ai-workbench/connect')).sshArgs;
349
+ io = sshIo(target, argv, this.config().brokerControlMaxBytes);
350
+ }
351
+ const guard = new AbortController(), disposers = [];
352
+ let revoked;
353
+ const revoke = (code = 'SESSION_CONTEXT_MISMATCH') => { revoked = coldNeed(code); guard.abort({ kind: 'disposed' }); };
354
+ const connection = initialConnection;
355
+ const checkLocation = () => { if (this.getConnect() !== api) {
356
+ revoke();
357
+ return;
358
+ } if (!row.meta.binding)
359
+ return; const state = api.getWorkspaceLocationState?.(); if (!state) {
360
+ revoke();
361
+ return;
362
+ } if (state.phase !== 'ready') {
363
+ if (state.phase === 'disposed' || state.phase === 'failed' && (!state.need || !['HOST_OFFLINE', 'SSH_FAILED', 'CONNECTION_LOST'].includes(state.need.code)))
364
+ revoke();
365
+ return;
366
+ } const matches = state.items.filter(x => x.workspaceId === row.meta.binding.workspaceId); if (matches.length !== 1 || matches[0].bindingId !== row.meta.binding.bindingId || matches[0].source !== (row.meta.hostSource ? 'host' : 'local') || matches[0].status !== 'selected')
367
+ revoke(); };
368
+ try {
369
+ disposers.push(this.ctx.on('domain/changed', event => { if (event.domain === 'ai_workbench_remote_sources' && event.table === 'sessions' && event.key === row.sessionId && (event.operation === 'deleted' || !isDeepStrictEqual(event.value, row.meta.hostSource ?? { source: 'local' })))
370
+ revoke(); }));
371
+ disposers.push(this.ctx.on('internal/service', name => { if (name === 'aiWorkbenchConnect' && this.getConnect() !== api)
372
+ revoke(); }));
373
+ if (api.onWorkspaceLocationState)
374
+ disposers.push(api.onWorkspaceLocationState(checkLocation));
375
+ if (api.onConnectionState)
376
+ disposers.push(api.onConnectionState(next => { if (this.getConnect() !== api || next.instanceId !== connection?.instanceId || next.phase === 'disposed' || next.phase === 'unavailable' && (!next.need || !['HOST_OFFLINE', 'SSH_FAILED', 'CONNECTION_LOST'].includes(next.need.code)))
377
+ revoke();
378
+ else if (next.phase === 'connected') {
379
+ void api.getSshTarget().then(result => { if (result.ok) {
380
+ if (identity(result.value) !== row.meta.identity || !isDeepStrictEqual(result.value, row.target))
381
+ revoke();
382
+ }
383
+ else if (!['HOST_OFFLINE', 'SSH_FAILED', 'CONNECTION_LOST'].includes(result.error.code))
384
+ revoke(); }, () => revoke());
385
+ checkLocation();
386
+ } }));
387
+ if (row.meta.localDirectory) {
388
+ const expected = row.meta.localDirectory;
389
+ const check = async () => { try {
390
+ const stat = await lstat(expected.path);
391
+ if (!stat.isDirectory() || stat.isSymbolicLink() || await realpath(expected.path) !== expected.path || stat.dev !== expected.device || stat.ino !== expected.inode)
392
+ revoke('EMPLOYEE_CONTEXT_CHANGED');
393
+ }
394
+ catch {
395
+ revoke('EMPLOYEE_CONTEXT_CHANGED');
396
+ } };
397
+ const watcher = watch(dirname(expected.path), () => { void check(); });
398
+ watcher.on('error', () => revoke('EMPLOYEE_CONTEXT_CHANGED'));
399
+ disposers.push(() => watcher.close());
400
+ await check();
401
+ }
402
+ checkLocation();
403
+ const signal = AbortSignal.any([guard.signal, ...options.signal ? [options.signal] : []]);
404
+ if (!isDeepStrictEqual(api.getConnectionState?.(), initialConnection)) {
405
+ const checked = await this.connection(signal, row.meta);
406
+ if (checked.api !== api || !isDeepStrictEqual(checked.target, row.target))
407
+ revoke();
408
+ }
409
+ if (this.provided?.readSource && !isDeepStrictEqual(row.meta.hostSource ?? { source: 'local' }, await this.provided.readSource(row.sessionId)))
410
+ revoke();
411
+ signal.throwIfAborted();
412
+ this.live.set(row.sessionId, row.id);
413
+ yield* recoverColdProtocol(row, this.store, { blocks, usage }, { io, maxFrameBytes: this.config().brokerMaxFrameBytes, maxMessageBytes: this.config().acpMaxMessageBytes, signal, markerId: selected.markerId });
414
+ if (revoked)
415
+ throw revoked;
416
+ }
417
+ catch (error) {
418
+ throw revoked ?? error;
419
+ }
420
+ finally {
421
+ for (const off of disposers)
422
+ off();
423
+ if (this.live.get(row.sessionId) === row.id)
424
+ this.live.delete(row.sessionId);
425
+ }
426
+ }
427
+ }
@@ -0,0 +1,91 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import { NeedError } from './remote.ts';
3
+ import type { ConnectTarget } from './provider.ts';
4
+ import type { UsageSnapshot } from './mapping.ts';
5
+ export interface ColdWrite {
6
+ id: string;
7
+ sha256: string;
8
+ wire: string;
9
+ baseSequence: number;
10
+ chunkBytes: number;
11
+ chunks: number;
12
+ method?: string;
13
+ rpcId?: string | number | null;
14
+ }
15
+ export interface ColdRound {
16
+ version: 1;
17
+ id: string;
18
+ sessionId: string;
19
+ provider: string;
20
+ brand: 'codex' | 'claude';
21
+ phase: 'opening' | 'running' | 'terminal' | 'committed';
22
+ target: ConnectTarget;
23
+ brokerId: string;
24
+ instanceId: string;
25
+ controlMaxBytes: number;
26
+ heartbeatIntervalMs: number;
27
+ nativeId?: string;
28
+ promptId?: string;
29
+ promptSha256?: string;
30
+ promptBytes?: number;
31
+ originTurn?: number;
32
+ originStep?: number;
33
+ rpcIds: (string | number | null)[];
34
+ answered: (string | number | null)[];
35
+ inputSequence: number;
36
+ pending?: ColdWrite;
37
+ meta?: {
38
+ identity: string;
39
+ cwd: string;
40
+ binding?: {
41
+ bindingId: string;
42
+ workspaceId: string;
43
+ revision: number;
44
+ };
45
+ hostSource?: unknown;
46
+ contextSha256: string;
47
+ baseline: UsageSnapshot | null;
48
+ modelConfiguration?: unknown;
49
+ header: unknown;
50
+ model: string;
51
+ callConfig?: import('@deepseek-ai/dsh-llm').LlmCallConfig;
52
+ prelude?: string;
53
+ inputDigests?: Record<string, string>;
54
+ localDirectory?: {
55
+ path: string;
56
+ device: number;
57
+ inode: number;
58
+ };
59
+ };
60
+ localNotices?: {
61
+ beforeUpdate: number;
62
+ text: string;
63
+ }[];
64
+ finalUsage?: UsageSnapshot | null;
65
+ errorDelivery?: {
66
+ markerId: string;
67
+ code: string;
68
+ promptId: string;
69
+ token: string;
70
+ message: string;
71
+ };
72
+ terminalAfter?: number;
73
+ outputStart?: number;
74
+ outputAfter: number;
75
+ officialSeq?: number;
76
+ terminal?: {
77
+ kind: 'result' | 'error';
78
+ value: unknown;
79
+ };
80
+ failure?: string;
81
+ }
82
+ export interface ColdStore {
83
+ read(sessionId: string, provider: string): Promise<ColdRound | undefined>;
84
+ put(round: ColdRound): Promise<void>;
85
+ update(sessionId: string, provider: string, id: string, change: (round: ColdRound) => void): Promise<ColdRound>;
86
+ }
87
+ export declare const coldKey: (sessionId: string, provider: string) => string;
88
+ export declare function coldNeed(code?: string): NeedError;
89
+ export declare function createColdStore(ctx: Context): ColdStore;
90
+ export declare const wireDigest: (bytes: Uint8Array) => string;
91
+ export declare function newColdId(): `${string}-${string}-${string}-${string}-${string}`;
@@ -0,0 +1,29 @@
1
+ import { randomUUID, createHash } from 'node:crypto';
2
+ import { defineDomain, domainTable } from '@deepseek-ai/dsh-storage-domain';
3
+ import { z } from 'zod';
4
+ import { NeedError } from "./remote.js";
5
+ const spec = defineDomain({ name: 'ai_workbench_cold_rounds', version: 1, tables: { rounds: domainTable(z.object({ sessionId: z.string(), provider: z.string(), payload: z.unknown() }).strict()) } });
6
+ export const coldKey = (sessionId, provider) => JSON.stringify([sessionId, provider]);
7
+ export function coldNeed(code = 'INPUT_DELIVERY_UNCONFIRMED') { return new NeedError(code, '原轮恢复状态未能确认,没有另开模型轮或重复发送输入。', '原会话持久归属、输入确认和官方日志落盘证据'); }
8
+ export function createColdStore(ctx) {
9
+ let domain;
10
+ let tail = Promise.resolve();
11
+ const open = () => { if (!domain) {
12
+ const service = ctx.get('storageDomain');
13
+ if (!service)
14
+ throw coldNeed();
15
+ domain = service.open(spec).catch(e => { domain = undefined; throw e; });
16
+ } return domain; };
17
+ ctx.effect(() => async () => { await tail; if (domain)
18
+ await (await domain).close(); });
19
+ const rawRead = async (sessionId, provider) => { const row = (await open()).table('rounds').get(coldKey(sessionId, provider)); if (!row)
20
+ return; const record = structuredClone(row.payload); if (record.version !== 1 || record.sessionId !== sessionId || record.provider !== provider || !record.id || !Array.isArray(record.rpcIds) || !Array.isArray(record.answered))
21
+ throw coldNeed(); return record; };
22
+ const rawPut = async (round) => { await (await open()).table('rounds').put(coldKey(round.sessionId, round.provider), { sessionId: round.sessionId, provider: round.provider, payload: structuredClone(round) }); };
23
+ const enqueue = (work) => { const result = tail.then(work); tail = result.then(() => { }, () => { }); return result; };
24
+ const store = { async read(sessionId, provider) { await tail; return rawRead(sessionId, provider); }, put(round) { const copy = structuredClone(round); return enqueue(() => rawPut(copy)); }, update(sessionId, provider, id, change) { return enqueue(async () => { const row = await rawRead(sessionId, provider); if (!row || row.id !== id)
25
+ throw coldNeed('SESSION_CONTEXT_MISMATCH'); change(row); await rawPut(row); return row; }); } };
26
+ return store;
27
+ }
28
+ export const wireDigest = (bytes) => createHash('sha256').update(bytes).digest('hex');
29
+ export function newColdId() { return randomUUID(); }
@@ -177,7 +177,7 @@ export function createEmployeeProvider(get, options, agent) {
177
177
  if (get() !== api || employee.getNetwork() !== network)
178
178
  throw fail('EMPLOYEE_CONTEXT_CHANGED');
179
179
  const execution = new EmployeeExecution({ closeDiagnostics, bindingId: admitted.bindingId, acpMaxMessageBytes: request.acpMaxMessageBytes, transport: signal => createEmployeeSshTransport(ssh, signal) });
180
- const runtime = { ...host, closeDiagnostics, cwd: admitted.cwd, details, connection: { ...connection }, binding: { bindingId: admitted.bindingId, workspaceId: admitted.workspaceId, revision: state.revision }, employeeExecutionMeta: { version: 1, bindingId: admitted.bindingId, workspaceId: admitted.workspaceId, cwd: admitted.cwd, acpMaxMessageBytes: request.acpMaxMessageBytes }, employeePresentation: EMPLOYEE_EXECUTION_NOTICE };
180
+ const runtime = { ...host, localDirectory: { ...context.directory }, closeDiagnostics, cwd: admitted.cwd, details, connection: { ...connection }, binding: { bindingId: admitted.bindingId, workspaceId: admitted.workspaceId, revision: state.revision }, employeeExecutionMeta: { version: 1, bindingId: admitted.bindingId, workspaceId: admitted.workspaceId, cwd: admitted.cwd, acpMaxMessageBytes: request.acpMaxMessageBytes }, employeePresentation: EMPLOYEE_EXECUTION_NOTICE };
181
181
  runtime.employeeRemoteCloseReason = () => execution.remoteClose?.reason;
182
182
  let hostFinalized = false;
183
183
  const finishHost = (reason, cause) => {
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { ColdRecovery } from './cold-recovery.ts';
1
2
  import { type SteeringReceipts } from './live-steering.ts';
2
3
  import type { Context } from '@deepseek-ai/cordis';
3
4
  import Schema from '@deepseek-ai/schemastery';
@@ -59,6 +60,7 @@ export declare class CodexRemoteAdapter extends LlmAdapter {
59
60
  private readonly preflightDiagnostics?;
60
61
  private readonly permissions?;
61
62
  private readonly steeringReceipts?;
63
+ private readonly coldRecovery?;
62
64
  private bridgeLoop;
63
65
  private config;
64
66
  private sessions;
@@ -70,7 +72,7 @@ export declare class CodexRemoteAdapter extends LlmAdapter {
70
72
  private modelPresentation;
71
73
  private employeeNoticeSessions;
72
74
  private pendingEmployeeNotices;
73
- constructor(config: PluginConfig | (() => PluginConfig), resolveRuntime: RuntimeProvider, approve?: InvocationApproval | undefined, providerName?: () => string, agent?: AgentDefinition, readImage?: ImageReader | undefined, reportLoginFailure?: LoginFailureReporter | undefined, directory?: ModelDirectory | undefined, preflightDiagnostics?: PreflightDiagnostics | undefined, permissions?: PermissionSource | undefined, bridgeStopped?: (sessionId: string, notice: string) => void, steeringReceipts?: SteeringReceipts | undefined);
75
+ constructor(config: PluginConfig | (() => PluginConfig), resolveRuntime: RuntimeProvider, approve?: InvocationApproval | undefined, providerName?: () => string, agent?: AgentDefinition, readImage?: ImageReader | undefined, reportLoginFailure?: LoginFailureReporter | undefined, directory?: ModelDirectory | undefined, preflightDiagnostics?: PreflightDiagnostics | undefined, permissions?: PermissionSource | undefined, bridgeStopped?: (sessionId: string, notice: string) => void, steeringReceipts?: SteeringReceipts | undefined, coldRecovery?: ColdRecovery | undefined);
74
76
  providerInfo(provider: string): {
75
77
  id: string;
76
78
  name: string;
@@ -106,7 +108,7 @@ export declare class CodexRemoteAdapter extends LlmAdapter {
106
108
  /** One official registration owns both routes, preserving opaque replay ownership. */
107
109
  export declare class RemoteAgentsAdapter extends LlmAdapter {
108
110
  private adapters;
109
- constructor(config: () => PluginConfig, makeRuntime: (agent: AgentDefinition) => RuntimeProvider, approve: InvocationApproval, nameFor: (agent: AgentDefinition) => string, readImage?: ImageReader, reportLoginFailure?: LoginFailureReporter, directory?: ModelDirectory, preflightDiagnostics?: PreflightDiagnostics, permissions?: PermissionSource, bridgeStopped?: (sessionId: string, notice: string) => void, steeringReceipts?: SteeringReceipts);
111
+ constructor(config: () => PluginConfig, makeRuntime: (agent: AgentDefinition) => RuntimeProvider, approve: InvocationApproval, nameFor: (agent: AgentDefinition) => string, readImage?: ImageReader, reportLoginFailure?: LoginFailureReporter, directory?: ModelDirectory, preflightDiagnostics?: PreflightDiagnostics, permissions?: PermissionSource, bridgeStopped?: (sessionId: string, notice: string) => void, steeringReceipts?: SteeringReceipts, coldRecovery?: ColdRecovery);
110
112
  private adapter;
111
113
  providerInfo(provider: string): {
112
114
  id: string;