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

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,100 @@
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
+ kind?: 'text' | 'reasoning';
64
+ }[];
65
+ cancelIntent?: {
66
+ source: 'user-signal' | 'official-user' | 'wire';
67
+ delivered?: boolean;
68
+ };
69
+ cancelCheckpoint?: {
70
+ inputNotDelivered: true;
71
+ receipt: unknown;
72
+ };
73
+ finalUsage?: UsageSnapshot | null;
74
+ errorDelivery?: {
75
+ markerId: string;
76
+ code: string;
77
+ promptId?: string;
78
+ token: string;
79
+ message: string;
80
+ };
81
+ terminalAfter?: number;
82
+ outputStart?: number;
83
+ outputAfter: number;
84
+ officialSeq?: number;
85
+ terminal?: {
86
+ kind: 'result' | 'error' | 'local-cancel';
87
+ value: unknown;
88
+ };
89
+ failure?: string;
90
+ }
91
+ export interface ColdStore {
92
+ read(sessionId: string, provider: string): Promise<ColdRound | undefined>;
93
+ put(round: ColdRound): Promise<void>;
94
+ update(sessionId: string, provider: string, id: string, change: (round: ColdRound) => void): Promise<ColdRound>;
95
+ }
96
+ export declare const coldKey: (sessionId: string, provider: string) => string;
97
+ export declare function coldNeed(code?: string): NeedError;
98
+ export declare function createColdStore(ctx: Context): ColdStore;
99
+ export declare const wireDigest: (bytes: Uint8Array) => string;
100
+ 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;
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { ColdRecovery } from "./cold-recovery.js";
1
2
  import { createSteeringReceipts, installLiveSteering, steeringMessageDigest } from "./live-steering.js";
2
3
  import { ToolBridgeLoop } from "./toolbridge-loop.js";
3
4
  import { openToolBridgeMcp, TOOLBRIDGE_NOTICE } from "./toolbridge.js";
@@ -96,6 +97,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
96
97
  preflightDiagnostics;
97
98
  permissions;
98
99
  steeringReceipts;
100
+ coldRecovery;
99
101
  bridgeLoop;
100
102
  config;
101
103
  sessions = new Map();
@@ -107,7 +109,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
107
109
  modelPresentation = new ModelPresentation();
108
110
  employeeNoticeSessions = new Set();
109
111
  pendingEmployeeNotices = new Set();
110
- constructor(config, resolveRuntime, approve, providerName = () => CODEX_AGENT.name.zh, agent = CODEX_AGENT, readImage, reportLoginFailure, directory, preflightDiagnostics, permissions, bridgeStopped, steeringReceipts) {
112
+ constructor(config, resolveRuntime, approve, providerName = () => CODEX_AGENT.name.zh, agent = CODEX_AGENT, readImage, reportLoginFailure, directory, preflightDiagnostics, permissions, bridgeStopped, steeringReceipts, coldRecovery) {
111
113
  super();
112
114
  this.resolveRuntime = resolveRuntime;
113
115
  this.approve = approve;
@@ -119,6 +121,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
119
121
  this.preflightDiagnostics = preflightDiagnostics;
120
122
  this.permissions = permissions;
121
123
  this.steeringReceipts = steeringReceipts;
124
+ this.coldRecovery = coldRecovery;
122
125
  this.bridgeLoop = new ToolBridgeLoop(readImage, bridgeStopped, (id, message) => this.injectedInputs.get(id)?.get(message.id) === steeringMessageDigest(message));
123
126
  this.config = typeof config === 'function' ? config : () => config;
124
127
  }
@@ -204,6 +207,9 @@ export class CodexRemoteAdapter extends LlmAdapter {
204
207
  catalog.release();
205
208
  } }
206
209
  async resolveModel(provider, id, signal) {
210
+ const recovered = this.coldRecovery?.recoveryModel(provider, id, signal);
211
+ if (recovered)
212
+ return recovered;
207
213
  const displayed = this.modelPresentation.resolve(provider, id);
208
214
  if (displayed)
209
215
  return displayed;
@@ -274,17 +280,29 @@ export class CodexRemoteAdapter extends LlmAdapter {
274
280
  for (const live of this.sessions.values())
275
281
  live.runtime.closeDiagnostics?.record({ layer: 'adapter', initiator: 'adapter.dispose', reason: 'PLUGIN_DISPOSED', action: 'dispose', changes: [{ field: 'adapter.shutting-down', before: this.shuttingDown, after: true }] });
276
282
  this.shuttingDown = true;
283
+ this.coldRecovery?.dispose?.();
277
284
  this.modelPresentation.clear();
278
285
  this.employeeNoticeSessions.clear();
279
286
  this.pendingEmployeeNotices.clear();
280
287
  const results = await Promise.allSettled([...new Set([...this.sessions.keys(), ...this.turns.keys()])].map(id => this.detachSession(id)));
281
288
  await this.bridgeLoop.dispose();
282
- this.lifetime.abort();
289
+ this.lifetime.abort(Object.assign(new DOMException('远程模型插件已关闭', 'AbortError'), { kind: 'disposed' }));
283
290
  const failure = results.find(result => result.status === 'rejected');
284
291
  if (failure?.status === 'rejected')
285
292
  throw failure.reason;
286
293
  }
287
294
  async *stream(options) {
295
+ if (this.coldRecovery?.canRecover(options)) {
296
+ try {
297
+ yield* this.coldRecovery.stream(options, this.lifetime.signal);
298
+ return;
299
+ }
300
+ catch (error) {
301
+ if (error instanceof NeedError)
302
+ throw new LlmError(error.message, error.code, { cause: error });
303
+ throw error;
304
+ }
305
+ }
288
306
  // Before the tool bridge: a parked turn must not take a background request for its own continuation.
289
307
  if (options.purpose)
290
308
  throw new LlmError(employeeFailure('PURPOSE_UNSUPPORTED', this.agent.loginProvider, false), 'PURPOSE_UNSUPPORTED');
@@ -335,7 +353,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
335
353
  if (key)
336
354
  this.turns.set(key, turn);
337
355
  const signal = AbortSignal.any([this.lifetime.signal, turn.signal, ...(original.signal ? [original.signal] : [])]);
338
- const options = { ...original, signal };
356
+ let options = { ...original, signal };
339
357
  const abortOffs = [];
340
358
  let bridgeMcp;
341
359
  let request;
@@ -352,6 +370,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
352
370
  let selected;
353
371
  let modelConfiguration;
354
372
  let turnFailure;
373
+ let coldPrelude = '';
355
374
  let employeeNoticeShown = false;
356
375
  let permissionOff;
357
376
  let permissionEpoch = new AbortController();
@@ -373,7 +392,12 @@ export class CodexRemoteAdapter extends LlmAdapter {
373
392
  try {
374
393
  if (!Number.isSafeInteger(config.acpMaxMessageBytes) || config.acpMaxMessageBytes < 1)
375
394
  throw new NeedError('SETTINGS_REQUIRED', '远程模型连接设置无效,请联系管理员检查', '有效的acpMaxMessageBytes');
376
- const checkpoint = readPointer(options, this.agent), previous = checkpoint?.pointer;
395
+ const standardCheckpoint = readPointer(options, this.agent), recoveredCheckpoint = await this.coldRecovery?.previousPointer(options);
396
+ const checkpoint = recoveredCheckpoint && (!standardCheckpoint || recoveredCheckpoint.index > standardCheckpoint.index) ? recoveredCheckpoint : standardCheckpoint, previous = checkpoint?.pointer ?? (checkpoint === recoveredCheckpoint ? standardCheckpoint?.pointer : undefined);
397
+ const usedColdCheckpoint = !!recoveredCheckpoint && checkpoint === recoveredCheckpoint;
398
+ let checkpointIndex = usedColdCheckpoint ? -1 : checkpoint?.index ?? -1;
399
+ if (usedColdCheckpoint)
400
+ options = { ...options, messages: options.messages.filter((m, index) => index > checkpoint.index || m.role === 'system' || m.role === 'developer') };
377
401
  employeeNoticeShown = !!key && this.employeeNoticeSessions.has(key) || false;
378
402
  if (employeeNoticeShown && key)
379
403
  this.employeeNoticeSessions.add(key);
@@ -396,6 +420,9 @@ export class CodexRemoteAdapter extends LlmAdapter {
396
420
  request.userMessageIds = request.userInputIds;
397
421
  earlyStage = 'source-context';
398
422
  await this.resolveRuntime.preflight?.(request);
423
+ options = { ...await this.coldRecovery?.projectCancelledInputs?.(options) ?? options, signal };
424
+ if (!usedColdCheckpoint)
425
+ checkpointIndex = readPointer(options, this.agent)?.index ?? -1;
399
426
  const receipts = this.steeringReceipts && options.sessionId ? await this.steeringReceipts.read(options.sessionId, options.provider, humanIds) : new Map();
400
427
  const matching = [...receipts.values()].filter(r => tail.some(m => m.role === 'user' && 'source' in m && m.source?.kind === 'user' && m.id === r.messageId && steeringMessageDigest(m) === r.messageSha256));
401
428
  for (const receipt of matching)
@@ -408,7 +435,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
408
435
  succeeded = true;
409
436
  return;
410
437
  }
411
- const projected = { ...options, messages: options.messages.filter((m, index) => index <= (checkpoint?.index ?? -1) || !('id' in m) || typeof m.id !== 'string' || !injected.has(m.id)) };
438
+ const projected = { ...options, messages: options.messages.filter((m, index) => index <= checkpointIndex || !('id' in m) || typeof m.id !== 'string' || !injected.has(m.id)) };
412
439
  earlyStage = 'input-prepare';
413
440
  let input = await prepareInput(projected, this.readImage);
414
441
  const contextSha256 = createHash('sha256').update(input.systemPrompt ?? '').digest('hex');
@@ -438,7 +465,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
438
465
  }
439
466
  if (previous && !runtime.hostSource && (previous.identity !== runtime.identity || previous.cwd !== runtime.cwd || previous.bindingId && previous.bindingId !== runtime.binding?.bindingId || previous.workspaceId && previous.workspaceId !== runtime.binding?.workspaceId))
440
467
  throw new NeedError('SESSION_CONTEXT_MISMATCH', '原会话的员工主机或工作区已改变,请新建会话', '原会话的可信目标和工作区');
441
- input = await prepareContinuation({ ...options, messages: projected.messages.slice((checkpoint?.index ?? -1) + 1) }, input, this.readImage, { maxBytes: config.acpMaxMessageBytes, host: runtime.hostWorkspace });
468
+ input = await prepareContinuation({ ...options, messages: projected.messages.slice(checkpointIndex + 1) }, input, this.readImage, { maxBytes: config.acpMaxMessageBytes, host: runtime.hostWorkspace });
442
469
  if (runtime.hostWorkspace && mode === 'session' && Buffer.byteLength(JSON.stringify({ prompt: input.prompt, systemPrompt: input.systemPrompt }), 'utf8') > config.acpMaxMessageBytes)
443
470
  throw new NeedError('ACP_MESSAGE_TOO_LARGE', '本轮输入超过已设置的会话消息容量,未截断或发送', '管理员调整acpMaxMessageBytes');
444
471
  const details = runtime.details ?? await createRemoteDetails({ warn: line => console.warn(line) }).open({ sessionId: options.sessionId ?? 'unscoped', provider: this.agent.loginProvider, identity: runtime.identity, connection: runtime.connection });
@@ -457,13 +484,14 @@ export class CodexRemoteAdapter extends LlmAdapter {
457
484
  let id;
458
485
  let stop;
459
486
  const pointerRuntime = runtime;
460
- const makePointer = (nativeId) => ({ ...(pointerRuntime.hostSource ? { hostSource: pointerRuntime.hostSource } : {}), ...(modelConfiguration ? { modelConfiguration } : {}), version: 2, agent: this.agent.id, contextSha256, ...(mode === 'session' ? { usageSnapshot: mapper.usageSnapshot } : {}), ...(options.sessionId ? { dshSessionId: options.sessionId } : {}), identity: pointerRuntime.identity, cwd: pointerRuntime.cwd, sessionId: nativeId, ...(pointerRuntime.binding ? { bindingId: pointerRuntime.binding.bindingId, workspaceId: pointerRuntime.binding.workspaceId } : {}) });
487
+ const makePointer = (nativeId) => ({ ...(pointerRuntime.cold ? { coldRoundId: pointerRuntime.cold.id } : {}), ...(pointerRuntime.hostSource ? { hostSource: pointerRuntime.hostSource } : {}), ...(modelConfiguration ? { modelConfiguration } : {}), version: 2, agent: this.agent.id, contextSha256, ...(mode === 'session' ? { usageSnapshot: mapper.usageSnapshot } : {}), ...(options.sessionId ? { dshSessionId: options.sessionId } : {}), identity: pointerRuntime.identity, cwd: pointerRuntime.cwd, sessionId: nativeId, ...(pointerRuntime.binding ? { bindingId: pointerRuntime.binding.bindingId, workspaceId: pointerRuntime.binding.workspaceId } : {}) });
461
488
  if (runtime.employeePresentation)
462
489
  details.record({ kind: 'session', severity: 'warning', code: 'EMPLOYEE_EXECUTION_SCOPE', summary: runtime.employeePresentation, payload: { source: 'local' } });
463
490
  if (runtime.execution)
464
491
  details.record({ kind: 'session', severity: 'warning', code: 'CLAUDE_EMPLOYEE_SCOPE', summary: runtime.execution.notice, payload: runtime.execution.scope });
465
492
  if ((runtime.employeePresentation || runtime.execution) && !employeeNoticeShown) {
466
- for (const chunk of mapper.text(EMPLOYEE_EXECUTION_NOTICE + (bridge?.enabled ? '\n\n' + TOOLBRIDGE_NOTICE : '') + '\n\n')) {
493
+ coldPrelude = EMPLOYEE_EXECUTION_NOTICE + (bridge?.enabled ? '\n\n' + TOOLBRIDGE_NOTICE : '') + '\n\n';
494
+ for (const chunk of mapper.text(coldPrelude)) {
467
495
  if (chunk.type === 'text-delta') {
468
496
  employeeNoticeShown = true;
469
497
  if (key) {
@@ -485,6 +513,10 @@ export class CodexRemoteAdapter extends LlmAdapter {
485
513
  let done = false;
486
514
  let failure;
487
515
  const push = (chunks) => { queue.push(...chunks); wake?.(); wake = undefined; };
516
+ let renderTail = Promise.resolve(), nativeUpdates = 0, coldPromptStarted = false;
517
+ const render = (work) => { renderTail = renderTail.then(work); void renderTail.catch(error => { failure ??= error; session?.close({ layer: 'adapter', initiator: 'adapter.render-failure', reason: closeCode(error, 'MAPPING_FAILED'), action: 'close' }); wake?.(); }); };
518
+ const renderNotice = (text) => render(async () => { if (runtime.cold)
519
+ await runtime.cold.store.update(options.sessionId, options.provider, runtime.cold.id, row => { (row.localNotices ??= []).push({ beforeUpdate: nativeUpdates, text }); }); push(mapper.text(text)); });
488
520
  let promptPermit;
489
521
  let confirmedNativeMode;
490
522
  const hooks = { closeDiagnostics: runtime.closeDiagnostics, broker: runtime.broker, sessionOwnership: runtime.sessionOwnership, employeeExecution: runtime.employeeExecution, ...this.permissions ? { promptGuard: () => {
@@ -511,23 +543,29 @@ export class CodexRemoteAdapter extends LlmAdapter {
511
543
  if (execution) {
512
544
  if (toolName && ['Agent', 'Task', 'TaskOutput', 'TaskStop', 'Read', 'Write', 'Edit', 'Glob', 'Grep', 'Bash'].includes(toolName)) {
513
545
  details.record({ kind: 'need', severity: 'warning', code: 'CLAUDE_HOST_TOOL_UNSUPPORTED', summary: '这类原生调用没有经过员工端别名,本机来源不支持;本次审批已取消', payload: { operation: toolName } });
514
- push(mapper.text('\n这类操作尚不支持在本机执行,已取消本次审批,没有在主机代跑。\n'));
546
+ renderNotice('\n这类操作尚不支持在本机执行,已取消本次审批,没有在主机代跑。\n');
515
547
  return 'cancelled';
516
548
  }
517
549
  }
518
550
  const answer = await this.approve?.(permission, approvalSignal, options, execution && toolName?.startsWith('mcp__employee__') ? 'employee-local' : undefined, runtime.hostWorkspace) ?? 'unavailable';
519
551
  return answer;
520
- }, onEmployeeNotice: notice => push(mapper.text(notice + '\n\n')), onUpdate: notification => { try {
521
- bridge?.observe(notification.update);
522
- push(mapper.acp(notification.update));
523
- }
524
- catch (error) {
525
- failure = error;
526
- session?.close({ layer: 'adapter', initiator: 'adapter.mapper-failure', reason: closeCode(error, 'MAPPING_FAILED'), action: 'close' });
527
- } }, onResponse: response => push(mapper.acpResponse(response)), onDetail: detail => details.record(detail) };
552
+ }, onEmployeeNotice: notice => renderNotice(notice + '\n\n'), onUpdate: (notification, originSequence) => { const fromPrompt = coldPromptStarted; render(async () => { let inRound = fromPrompt; if (fromPrompt && runtime.cold) {
553
+ const start = await runtime.cold.bound;
554
+ if (!Number.isSafeInteger(originSequence))
555
+ throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '原输出通知的来源未确认', '原broker输出序号');
556
+ inRound = originSequence > start;
557
+ if (!inRound) {
558
+ const update = notification.update;
559
+ if ((update.sessionUpdate === 'agent_message_chunk' || update.sessionUpdate === 'agent_thought_chunk') && update.content.type === 'text' && update.content.text) {
560
+ const text = update.content.text, kind = update.sessionUpdate === 'agent_thought_chunk' ? 'reasoning' : 'text';
561
+ await runtime.cold.store.update(options.sessionId, options.provider, runtime.cold.id, row => { (row.localNotices ??= []).push({ beforeUpdate: nativeUpdates, text, kind }); });
562
+ }
563
+ }
564
+ } bridge?.observe(notification.update); push(mapper.acp(notification.update)); if (inRound)
565
+ nativeUpdates++; }); }, onResponse: response => render(() => { push(mapper.acpResponse(response)); }), onDetail: detail => details.record(detail) };
528
566
  const transport = runtime.acpTransport instanceof acp.AgentApp || runtime.acpTransport instanceof unstable.AgentApp ? runtime.acpTransport : acp.ndJsonStream(runtime.acpTransport.writable, runtime.acpTransport.readable, { maxMessageBytes: config.acpMaxMessageBytes });
529
567
  session = new AcpSession(transport, hooks);
530
- live = { session, runtime, configuration, contextSha256, usageSnapshot: mapper.usageSnapshot, options, acceptingSteer: true, turnId: randomUUID(), steerIds: new Map(), steerTail: Promise.resolve(), maxBytes: config.acpMaxMessageBytes, notice: text => push(mapper.text(text)) };
568
+ live = { session, runtime, configuration, contextSha256, usageSnapshot: mapper.usageSnapshot, options, acceptingSteer: true, turnId: randomUUID(), steerIds: new Map(), steerTail: Promise.resolve(), maxBytes: config.acpMaxMessageBytes, notice: renderNotice };
531
569
  if (key)
532
570
  this.sessions.set(key, live);
533
571
  promptBaseline = session.promptDispatchCount;
@@ -624,6 +662,10 @@ export class CodexRemoteAdapter extends LlmAdapter {
624
662
  }
625
663
  recordInformation();
626
664
  details.beginTurn(runtime.detailContext?.() ?? { turn: null, step: null });
665
+ await renderTail;
666
+ if (runtime.cold && this.coldRecovery)
667
+ await this.coldRecovery.capture(runtime, options, session.id, { identity: runtime.identity, cwd: runtime.cwd, binding: runtime.binding, hostSource: runtime.hostSource, contextSha256, baseline: mapper.usageSnapshot, modelConfiguration, model: options.model, prelude: coldPrelude, localDirectory: runtime.localDirectory });
668
+ coldPromptStarted = true;
627
669
  await runtime.execution?.beginTurn(modelSignal);
628
670
  if (bridge?.enabled)
629
671
  bridge.replayState = { response: makePointer(session.id) };
@@ -666,7 +708,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
666
708
  details.endTurn();
667
709
  }
668
710
  })();
669
- void task.then(value => { stop = value; }, error => { failure ??= runtime.broker?.error ?? error; }).finally(() => { done = true; wake?.(); wake = undefined; });
711
+ void task.then(value => { stop = value; }, error => { runtime.cold?.failBinding(error); failure ??= runtime.broker?.error ?? error; }).then(async () => { await renderTail; }, error => { failure ??= error; }).catch(error => { failure ??= error; }).finally(() => { done = true; wake?.(); wake = undefined; });
670
712
  while (!done || queue.length) {
671
713
  if (queue.length)
672
714
  yield queue.shift();
@@ -696,11 +738,14 @@ export class CodexRemoteAdapter extends LlmAdapter {
696
738
  }
697
739
  }
698
740
  yield* mapper.flush();
699
- const pointer = makePointer(id);
741
+ const finalCold = runtime.cold ? await runtime.cold.store.update(options.sessionId, options.provider, runtime.cold.id, row => { row.finalUsage = mapper.usageSnapshot; row.terminal = { kind: 'result', value: { stopReason: stop } }; row.phase = 'terminal'; row.terminalAfter = runtime.broker?.lastSequence; }) : undefined;
742
+ const pointer = { ...makePointer(id), ...(finalCold ? { coldRoundTerminal: true, coldPromptId: finalCold.promptId, coldOutputAfter: runtime.broker?.lastSequence } : {}) };
700
743
  succeeded = true;
701
744
  yield { type: 'finish', reason: { kind: stop === 'max_tokens' || stop === 'max_turn_requests' ? 'max-tokens' : 'stop' }, replayState: { response: pointer } };
702
745
  }
703
746
  catch (error) {
747
+ if (original.signal?.reason?.kind === 'user' && runtime?.cold && this.coldRecovery)
748
+ await this.coldRecovery.recordUserCancellation(runtime, options, session?.id ?? request?.resumeSessionId, { identity: runtime.identity, cwd: runtime.cwd, binding: runtime.binding, hostSource: runtime.hostSource, contextSha256: request?.contextSha256 ?? '', baseline: activeMapper?.usageSnapshot ?? null, modelConfiguration: modelConfiguration ?? { selected }, model: options.model, prelude: coldPrelude, localDirectory: runtime.localDirectory });
704
749
  if (session && session.promptDispatchCount > promptBaseline)
705
750
  onPromptDispatched();
706
751
  if (bridge?.unsettled && !signal.aborted)
@@ -727,10 +772,15 @@ export class CodexRemoteAdapter extends LlmAdapter {
727
772
  if (bridgeMcp)
728
773
  await bridgeMcp.close();
729
774
  if (runtime) {
775
+ if (runtime.cold && key)
776
+ this.coldRecovery?.release(key, runtime.cold.id);
730
777
  session?.close({ layer: 'adapter', initiator: 'adapter.turn-finally', reason: succeeded ? 'TURN_FINISHED' : 'TURN_FAILED', action: 'close' });
731
778
  if (key && this.sessions.get(key) === live)
732
779
  this.sessions.delete(key);
733
- void this.cleanupRuntime(runtime);
780
+ if (session && session.promptDispatchCount > promptBaseline && (runtime.cold || this.shuttingDown || key && this.detached.has(key) || original.signal?.reason?.kind === 'disposed'))
781
+ void runtime.detach?.({ layer: 'adapter', initiator: 'adapter.preserve-original', reason: 'SESSION_DETACHED', action: 'detach' });
782
+ else
783
+ void this.cleanupRuntime(runtime);
734
784
  }
735
785
  if (key && this.turns.get(key) === turn)
736
786
  this.turns.delete(key);
@@ -743,8 +793,8 @@ export class CodexRemoteAdapter extends LlmAdapter {
743
793
  /** One official registration owns both routes, preserving opaque replay ownership. */
744
794
  export class RemoteAgentsAdapter extends LlmAdapter {
745
795
  adapters = new Map();
746
- constructor(config, makeRuntime, approve, nameFor, readImage, reportLoginFailure, directory, preflightDiagnostics, permissions, bridgeStopped, steeringReceipts) { super(); for (const agent of AGENTS)
747
- this.adapters.set(agent.id, new CodexRemoteAdapter(config, makeRuntime(agent), approve, () => nameFor(agent), agent, readImage, reportLoginFailure, directory, preflightDiagnostics, permissions, bridgeStopped, steeringReceipts)); }
796
+ constructor(config, makeRuntime, approve, nameFor, readImage, reportLoginFailure, directory, preflightDiagnostics, permissions, bridgeStopped, steeringReceipts, coldRecovery) { super(); for (const agent of AGENTS)
797
+ this.adapters.set(agent.id, new CodexRemoteAdapter(config, makeRuntime(agent), approve, () => nameFor(agent), agent, readImage, reportLoginFailure, directory, preflightDiagnostics, permissions, bridgeStopped, steeringReceipts, coldRecovery)); }
748
798
  adapter(provider) { const adapter = this.adapters.get(provider); if (!adapter)
749
799
  throw new LlmError('远程模型未注册', 'PROVIDER_NOT_FOUND'); return adapter; }
750
800
  providerInfo(provider) { return this.adapter(provider).providerInfo(provider); }
@@ -778,7 +828,9 @@ export function apply(ctx, live) {
778
828
  throw new NeedError('ATTACHMENT_REQUIRED', '我需要官方附件组件读取这张图片', '官方attachments.readImage');
779
829
  return attachments.readImage(ref, signal);
780
830
  };
781
- const openByAgent = new Map(AGENTS.map(agent => [agent.id, brokerFactory(get, undefined, config)]));
831
+ const sessionSources = createSessionSources(ctx, get);
832
+ const coldRecovery = new ColdRecovery(ctx, get, config, { readSource: sessionSources.read });
833
+ const openByAgent = new Map(AGENTS.map(agent => [agent.id, brokerFactory(get, undefined, config, { coldStore: coldRecovery.store })]));
782
834
  const detailManagers = new Map();
783
835
  const managerForProfile = () => {
784
836
  const profile = ctx.get('profileContext');
@@ -791,7 +843,6 @@ export function apply(ctx, live) {
791
843
  return manager;
792
844
  };
793
845
  ctx.provide('aiWorkbenchRemoteDiagnostics', { read: (query) => managerForProfile().read(query) });
794
- const sessionSources = createSessionSources(ctx, get);
795
846
  const preflightDiagnostics = createPreflightDiagnostics({ ctx, getApi: get, manager: managerForProfile });
796
847
  const diagnostics = new Map();
797
848
  const diagnostic = (scope, provider, message) => {
@@ -890,7 +941,8 @@ export function apply(ctx, live) {
890
941
  if (turn !== null && step !== null)
891
942
  agent.session.append('assistant/message', { turn, step, message: createAssistantMessage({ content: [{ type: 'text', text: notice }], source: { provider: 'ai-workbench-toolbridge', model: 'notice' } }), stream: [] }, { surfaceOp: 'append' });
892
943
  agent.cancel({ kind: 'hook', reason: 'DSH_BRIDGE_CALL_ABANDONED_BY_HOST' }, { keepInbox: true });
893
- }, steeringReceipts);
944
+ }, steeringReceipts, coldRecovery);
945
+ coldRecovery.install();
894
946
  installLiveSteering(ctx, adapter);
895
947
  ctx.on('session/event', (session, event) => { if (event.type === 'turn/end') {
896
948
  const operation = event.data.reason.kind === 'completed' ? adapter.completeDshTurn(session.id, session.deriveMessages()) : adapter.disposeSession(session.id);
@@ -1,3 +1,4 @@
1
+ import type { ColdRound, ColdStore } from './cold-store.ts';
1
2
  import type { ToolBridge } from './toolbridge.ts';
2
3
  import { type SessionSource } from './host-workspace.ts';
3
4
  import type { CloseCause, CloseDiagnostics } from './close-diagnostics.ts';
@@ -27,6 +28,18 @@ export interface EmployeeExecution {
27
28
  validate(signal?: AbortSignal): Promise<void>;
28
29
  }
29
30
  export interface Runtime {
31
+ localDirectory?: {
32
+ path: string;
33
+ device: number;
34
+ inode: number;
35
+ };
36
+ cold?: {
37
+ id: string;
38
+ store: ColdStore;
39
+ bound: Promise<number>;
40
+ failBinding: (error: unknown) => void;
41
+ prepare: (nativeId: string | undefined, meta: NonNullable<ColdRound['meta']>) => Promise<void>;
42
+ };
30
43
  identity: string;
31
44
  cwd: string;
32
45
  hostWorkspace?: Readonly<HostWorkspacePresentation>;
@@ -15,4 +15,6 @@ export declare const sessionSourceSpec: {
15
15
  };
16
16
  };
17
17
  /** Official domain metadata, keyed by native session ID. No L files, local path probes or host identity hashes. */
18
- export declare function createSessionSources(ctx: Context, getApi: () => ConnectApi | undefined): (request: RuntimeRequest, api: ConnectApi) => Promise<SessionSource | undefined>;
18
+ export declare function createSessionSources(ctx: Context, getApi: () => ConnectApi | undefined): ((request: RuntimeRequest, api: ConnectApi) => Promise<SessionSource | undefined>) & {
19
+ read: (sessionId: string) => Promise<SessionSource | undefined>;
20
+ };
@@ -79,7 +79,7 @@ export function createSessionSources(ctx, getApi) {
79
79
  return;
80
80
  void save(session, api).catch(() => ctx.logger('remote-agent').warn('会话文件来源暂未保存;发送时将重试'));
81
81
  });
82
- return async (request, api) => {
82
+ const resolve = async (request, api) => {
83
83
  if (!request.sessionId || api.getContractInfo?.().workspaceLocations !== 1 && !request.hostSource)
84
84
  return;
85
85
  const session = ctx.get('sessions')?.get(SessionId(request.sessionId));
@@ -87,4 +87,5 @@ export function createSessionSources(ctx, getApi) {
87
87
  throw storageNeed();
88
88
  return save(session, api, request);
89
89
  };
90
+ return Object.assign(resolve, { read: async (sessionId) => { const source = (await open()).table('sessions').get(sessionId); return source ? Object.freeze({ ...source }) : undefined; } });
90
91
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-workbench/remote-agent",
3
- "version": "0.9.0-toolbridge.14",
3
+ "version": "0.9.0-toolbridge.16",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -53,8 +53,14 @@
53
53
  "@deepseek-ai/dsh-client-ui-settings": "0.2.0-rc.2",
54
54
  "@deepseek-ai/dsh-compaction-basic": "0.2.0-rc.2",
55
55
  "@deepseek-ai/dsh-llm": "0.2.0-rc.2",
56
+ "@deepseek-ai/dsh-sandbox-policy": "0.2.0-rc.2",
56
57
  "@deepseek-ai/dsh-session": "0.2.0-rc.2",
58
+ "@deepseek-ai/dsh-session-persistence-jsonl": "0.2.0-rc.2",
59
+ "@deepseek-ai/dsh-session-projection": "0.2.0-rc.2",
60
+ "@deepseek-ai/dsh-storage-domain": "0.2.0-rc.2",
61
+ "@deepseek-ai/dsh-system-prompt": "0.2.0-rc.2",
57
62
  "@deepseek-ai/dsh-token-meter": "0.2.0-rc.2",
63
+ "@deepseek-ai/dsh-tools": "0.2.0-rc.2",
58
64
  "@deepseek-ai/dsh-typert-protocol": "0.2.0-rc.2",
59
65
  "@deepseek-ai/dsh-typert-registry": "0.2.0-rc.2",
60
66
  "@deepseek-ai/dsh-user-approval": "0.2.0-rc.2",
@@ -65,12 +71,7 @@
65
71
  "react": "18.3.1",
66
72
  "react-dom": "18.3.1",
67
73
  "typescript": "5.9.3",
68
- "zustand": "4.4.7",
69
- "@deepseek-ai/dsh-sandbox-policy": "0.2.0-rc.2",
70
- "@deepseek-ai/dsh-storage-domain": "0.2.0-rc.2",
71
- "@deepseek-ai/dsh-session-projection": "0.2.0-rc.2",
72
- "@deepseek-ai/dsh-system-prompt": "0.2.0-rc.2",
73
- "@deepseek-ai/dsh-tools": "0.2.0-rc.2"
74
+ "zustand": "4.4.7"
74
75
  },
75
76
  "peerDependencies": {
76
77
  "@ai-workbench/connect": "~0.7.37",
@@ -79,12 +80,12 @@
79
80
  "@deepseek-ai/dsh-agent": ">=0.2.0-rc.2 <0.3.0-0",
80
81
  "@deepseek-ai/dsh-attachment": ">=0.2.0-rc.2 <0.3.0-0",
81
82
  "@deepseek-ai/dsh-llm": ">=0.2.0-rc.2 <0.3.0-0",
83
+ "@deepseek-ai/dsh-sandbox-policy": ">=0.2.0-rc.2 <0.3.0-0",
82
84
  "@deepseek-ai/dsh-session": ">=0.2.0-rc.2 <0.3.0-0",
85
+ "@deepseek-ai/dsh-storage-domain": ">=0.2.0-rc.2 <0.3.0-0",
83
86
  "@deepseek-ai/dsh-typert-protocol": ">=0.2.0-rc.2 <0.3.0-0",
84
87
  "@deepseek-ai/dsh-user-approval": ">=0.2.0-rc.2 <0.3.0-0",
85
- "@deepseek-ai/schemastery": "^3.18.4",
86
- "@deepseek-ai/dsh-sandbox-policy": ">=0.2.0-rc.2 <0.3.0-0",
87
- "@deepseek-ai/dsh-storage-domain": ">=0.2.0-rc.2 <0.3.0-0"
88
+ "@deepseek-ai/schemastery": "^3.18.4"
88
89
  },
89
90
  "dsh": {
90
91
  "bundle": {