@ai-workbench/remote-agent 0.9.0-toolbridge.2 → 0.9.0-toolbridge.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +23 -8
  2. package/dist/acp.d.ts +23 -1
  3. package/dist/acp.js +127 -17
  4. package/dist/broker-runtime.d.ts +2 -0
  5. package/dist/broker-runtime.js +52 -3
  6. package/dist/broker.d.ts +56 -1
  7. package/dist/broker.js +300 -10
  8. package/dist/claude-local.js +26 -5
  9. package/dist/client.js +1 -1
  10. package/dist/close-diagnostics.d.ts +1 -1
  11. package/dist/close-diagnostics.js +1 -1
  12. package/dist/cold-protocol.d.ts +17 -0
  13. package/dist/cold-protocol.js +358 -0
  14. package/dist/cold-recovery.d.ts +63 -0
  15. package/dist/cold-recovery.js +598 -0
  16. package/dist/cold-store.d.ts +100 -0
  17. package/dist/cold-store.js +29 -0
  18. package/dist/employee-endpoint.js +15 -1
  19. package/dist/employee-mcp.js +1 -1
  20. package/dist/employee-provider.js +26 -6
  21. package/dist/employee-relay.js +148 -1
  22. package/dist/employee-shell.d.ts +2 -0
  23. package/dist/employee-shell.js +22 -19
  24. package/dist/employee-tools.js +2 -2
  25. package/dist/employee-workspace.d.ts +20 -4
  26. package/dist/employee-workspace.js +26 -5
  27. package/dist/index.d.ts +12 -3
  28. package/dist/index.js +205 -40
  29. package/dist/input.js +4 -1
  30. package/dist/live-steering.d.ts +46 -0
  31. package/dist/live-steering.js +45 -0
  32. package/dist/model-catalog.d.ts +2 -0
  33. package/dist/model-catalog.js +5 -1
  34. package/dist/preflight-diagnostic.js +1 -1
  35. package/dist/presentation.js +1 -0
  36. package/dist/provider.d.ts +13 -0
  37. package/dist/rpc-namespace.js +16 -2
  38. package/dist/session-source.d.ts +3 -1
  39. package/dist/session-source.js +2 -1
  40. package/dist/toolbridge-loop.d.ts +3 -2
  41. package/dist/toolbridge-loop.js +4 -2
  42. package/dist/toolbridge-table.d.ts +4 -3
  43. package/dist/toolbridge-table.js +15 -5
  44. package/dist/toolbridge.d.ts +1 -1
  45. package/dist/toolbridge.js +4 -4
  46. package/package.json +23 -16
package/dist/index.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { ColdRecovery } from './cold-recovery.ts';
2
+ import { type SteeringReceipts } from './live-steering.ts';
1
3
  import type { Context } from '@deepseek-ai/cordis';
2
4
  import Schema from '@deepseek-ai/schemastery';
3
5
  import { LlmAdapter, type GenerateOptions, type StreamChunk, type LlmResolvedModelInfo } from '@deepseek-ai/dsh-llm';
@@ -15,7 +17,7 @@ export declare const settingsNamespace = "ai-workbench-codex";
15
17
  export declare const inject: string[];
16
18
  /** Owner-approved defaults; administrators may override through the existing settings. */
17
19
  export declare const DEFAULT_CONFIG: Readonly<{
18
- readonly acpMaxMessageBytes: 4194304;
20
+ readonly acpMaxMessageBytes: 512000000;
19
21
  readonly brokerMaxFrameBytes: 2097152;
20
22
  readonly brokerControlMaxBytes: 1048576;
21
23
  readonly employeeShellKillGraceMs: 1000;
@@ -57,9 +59,12 @@ export declare class CodexRemoteAdapter extends LlmAdapter {
57
59
  private readonly directory?;
58
60
  private readonly preflightDiagnostics?;
59
61
  private readonly permissions?;
62
+ private readonly steeringReceipts?;
63
+ private readonly coldRecovery?;
60
64
  private bridgeLoop;
61
65
  private config;
62
66
  private sessions;
67
+ private injectedInputs;
63
68
  private turns;
64
69
  private lifetime;
65
70
  private shuttingDown;
@@ -67,11 +72,13 @@ export declare class CodexRemoteAdapter extends LlmAdapter {
67
72
  private modelPresentation;
68
73
  private employeeNoticeSessions;
69
74
  private pendingEmployeeNotices;
70
- 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);
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);
71
76
  providerInfo(provider: string): {
72
77
  id: string;
73
78
  name: string;
74
79
  };
80
+ canSteer(sessionId: string): boolean;
81
+ steer(sessionId: string, message: import('@deepseek-ai/dsh-llm').UserMessage, isCurrent?: () => boolean): Promise<void>;
75
82
  private catalog;
76
83
  listModels(provider: string): Promise<(LlmResolvedModelInfo & {
77
84
  catalog: HostModel;
@@ -101,7 +108,7 @@ export declare class CodexRemoteAdapter extends LlmAdapter {
101
108
  /** One official registration owns both routes, preserving opaque replay ownership. */
102
109
  export declare class RemoteAgentsAdapter extends LlmAdapter {
103
110
  private adapters;
104
- 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);
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);
105
112
  private adapter;
106
113
  providerInfo(provider: string): {
107
114
  id: string;
@@ -124,6 +131,8 @@ export declare class RemoteAgentsAdapter extends LlmAdapter {
124
131
  jitterRatio: number;
125
132
  };
126
133
  stream(options: GenerateOptions): AsyncGenerator<StreamChunk, any, any>;
134
+ canSteer(provider: string, sessionId: string): boolean;
135
+ steer(provider: string, sessionId: string, message: import('@deepseek-ai/dsh-llm').UserMessage, isCurrent?: () => boolean): Promise<void>;
127
136
  completeDshTurn(sessionId: string, messages: GenerateOptions['messages']): Promise<void>;
128
137
  disposeSession(sessionId: string): Promise<void>;
129
138
  detachSession(sessionId: string): Promise<void>;
package/dist/index.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { ColdRecovery } from "./cold-recovery.js";
2
+ import { createSteeringReceipts, installLiveSteering, steeringMessageDigest } from "./live-steering.js";
1
3
  import { ToolBridgeLoop } from "./toolbridge-loop.js";
2
4
  import { openToolBridgeMcp, TOOLBRIDGE_NOTICE } from "./toolbridge.js";
3
5
  import { connectNeedMessage } from "./connect-need.js";
@@ -7,7 +9,7 @@ import { SessionId } from '@deepseek-ai/dsh-session';
7
9
  import { createAssistantMessage } from '@deepseek-ai/dsh-llm';
8
10
  import Schema from '@deepseek-ai/schemastery';
9
11
  import { LlmAdapter, LlmError } from '@deepseek-ai/dsh-llm';
10
- import { createHash } from 'node:crypto';
12
+ import { createHash, randomUUID } from 'node:crypto';
11
13
  import * as unstable from '@agentclientprotocol/sdk/unstable';
12
14
  import * as acp from '@agentclientprotocol/sdk';
13
15
  import { AcpSession } from "./acp.js";
@@ -39,9 +41,9 @@ export const settingsNamespace = 'ai-workbench-codex';
39
41
  // L can be installed/enabled after X; keeping X mounted lets it explain the prerequisite.
40
42
  export const inject = ['llm'];
41
43
  /** Owner-approved defaults; administrators may override through the existing settings. */
42
- export const DEFAULT_CONFIG = Object.freeze({ acpMaxMessageBytes: 4194304, brokerMaxFrameBytes: 2097152, brokerControlMaxBytes: 1048576, employeeShellKillGraceMs: 1000 });
44
+ export const DEFAULT_CONFIG = Object.freeze({ acpMaxMessageBytes: 512000000, brokerMaxFrameBytes: 2097152, brokerControlMaxBytes: 1048576, employeeShellKillGraceMs: 1000 });
43
45
  export const Config = Schema.object({
44
- acpMaxMessageBytes: Schema.number().min(1).step(1).i18n({ en: 'Session message limit; default 4 MiB, adjustable by administrators', zh: '会话消息容量;默认4 MiB,管理员可调整' }).default(DEFAULT_CONFIG.acpMaxMessageBytes).volatile(),
46
+ acpMaxMessageBytes: Schema.number().min(1).step(1).i18n({ en: 'Session message limit; default 512 MB, adjustable by administrators', zh: '会话消息容量;默认512 MB,管理员可调整' }).default(DEFAULT_CONFIG.acpMaxMessageBytes).volatile(),
45
47
  brokerMaxFrameBytes: Schema.number().min(1).step(1).i18n({ en: 'Host output chunk limit; default 2 MiB, adjustable by administrators', zh: '主机回传单段容量;默认2 MiB,管理员可调整' }).default(DEFAULT_CONFIG.brokerMaxFrameBytes).volatile(),
46
48
  brokerControlMaxBytes: Schema.number().min(1).step(1).i18n({ en: 'Host session control reply limit; default 1 MiB, adjustable by administrators', zh: '主机会话管理回复容量;默认1 MiB,管理员可调整' }).default(DEFAULT_CONFIG.brokerControlMaxBytes).volatile(),
47
49
  employeeShellKillGraceMs: Schema.number().min(0).max(2147483647).step(1).i18n({ en: 'Local command SSH cleanup grace in milliseconds; cancellation keeps the remote result unknown', zh: '本机命令SSH取消后的清理宽限毫秒;默认1000,取消仍保留员工端结果未知' }).default(DEFAULT_CONFIG.employeeShellKillGraceMs).volatile(),
@@ -94,9 +96,12 @@ export class CodexRemoteAdapter extends LlmAdapter {
94
96
  directory;
95
97
  preflightDiagnostics;
96
98
  permissions;
99
+ steeringReceipts;
100
+ coldRecovery;
97
101
  bridgeLoop;
98
102
  config;
99
103
  sessions = new Map();
104
+ injectedInputs = new Map();
100
105
  turns = new Map();
101
106
  lifetime = new AbortController();
102
107
  shuttingDown = false;
@@ -104,7 +109,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
104
109
  modelPresentation = new ModelPresentation();
105
110
  employeeNoticeSessions = new Set();
106
111
  pendingEmployeeNotices = new Set();
107
- constructor(config, resolveRuntime, approve, providerName = () => CODEX_AGENT.name.zh, agent = CODEX_AGENT, readImage, reportLoginFailure, directory, preflightDiagnostics, permissions, bridgeStopped) {
112
+ constructor(config, resolveRuntime, approve, providerName = () => CODEX_AGENT.name.zh, agent = CODEX_AGENT, readImage, reportLoginFailure, directory, preflightDiagnostics, permissions, bridgeStopped, steeringReceipts, coldRecovery) {
108
113
  super();
109
114
  this.resolveRuntime = resolveRuntime;
110
115
  this.approve = approve;
@@ -115,10 +120,82 @@ export class CodexRemoteAdapter extends LlmAdapter {
115
120
  this.directory = directory;
116
121
  this.preflightDiagnostics = preflightDiagnostics;
117
122
  this.permissions = permissions;
118
- this.bridgeLoop = new ToolBridgeLoop(readImage, bridgeStopped);
123
+ this.steeringReceipts = steeringReceipts;
124
+ this.coldRecovery = coldRecovery;
125
+ this.bridgeLoop = new ToolBridgeLoop(readImage, bridgeStopped, (id, message) => this.injectedInputs.get(id)?.get(message.id) === steeringMessageDigest(message));
119
126
  this.config = typeof config === 'function' ? config : () => config;
120
127
  }
121
128
  providerInfo(provider) { return { id: provider, name: this.providerName() }; }
129
+ canSteer(sessionId) { const live = this.sessions.get(sessionId); return !!this.steeringReceipts && !!live?.acceptingSteer && live.session.canSteer; }
130
+ steer(sessionId, message, isCurrent) {
131
+ const live = this.sessions.get(sessionId);
132
+ if (!live || !this.canSteer(sessionId))
133
+ return Promise.resolve();
134
+ const digest = steeringMessageDigest(message), valid = () => !isCurrent || isCurrent();
135
+ if (live.steerIds.get(message.id) === digest)
136
+ return live.steerTail;
137
+ live.steerIds.set(message.id, digest);
138
+ const work = live.steerTail.catch(() => { }).then(async () => {
139
+ if (!live.acceptingSteer || this.sessions.get(sessionId) !== live || !live.session.canSteer || !valid())
140
+ return;
141
+ const store = this.steeringReceipts, provider = live.options.provider, nativeSessionId = live.session.id;
142
+ const old = (await store.read(sessionId, provider, [message.id])).get(message.id);
143
+ if (!valid())
144
+ return;
145
+ if (old && old.messageSha256 !== digest && old.outcome !== 'deferred') {
146
+ live.notice?.('这条消息的旧版本已发送或送达未确认,不能撤回;编辑后的内容保留在队列,按下一步骤交付。');
147
+ return;
148
+ }
149
+ if (old && old.outcome !== 'deferred') {
150
+ if (old.outcome !== 'injected' || old.nativeSessionId !== nativeSessionId) {
151
+ const error = new NeedError('INPUT_DELIVERY_UNCONFIRMED', '这条中途消息已有未确认的送达记录,没有再次发送。', '原轮中途消息回执');
152
+ live.steerFailure ??= error;
153
+ throw error;
154
+ }
155
+ (this.injectedInputs.get(sessionId) ?? this.injectedInputs.set(sessionId, new Map()).get(sessionId)).set(message.id, digest);
156
+ return;
157
+ }
158
+ const prepared = await prepareInput({ ...live.options, messages: [message] }, this.readImage);
159
+ if (!valid())
160
+ return;
161
+ const params = { sessionId: nativeSessionId, prompt: prepared.prompt, _meta: { steering: { idleBehavior: 'promptRequired' } } };
162
+ if (Buffer.byteLength(JSON.stringify({ jsonrpc: '2.0', id: 'steering', method: '_session/steering', params })) + 1 > live.maxBytes)
163
+ throw new NeedError('ACP_MESSAGE_TOO_LARGE', '中途消息超过已设置的会话消息容量,仍在官方队列中,未发送。', '管理员调整acpMaxMessageBytes');
164
+ const receipt = { sessionId, provider, messageId: message.id, nativeSessionId, turnId: live.turnId, messageSha256: digest, outcome: 'prepared' };
165
+ await store.put(receipt);
166
+ const before = live.session.steerDispatchCount;
167
+ if (!valid()) {
168
+ await store.put({ ...receipt, outcome: 'deferred' });
169
+ return;
170
+ }
171
+ try {
172
+ const outcome = await live.session.steer(prepared.prompt, live.options.signal, valid, live.maxBytes);
173
+ await store.put({ ...receipt, outcome: outcome === 'injected' ? 'injected' : 'deferred' });
174
+ if (outcome === 'injected')
175
+ (this.injectedInputs.get(sessionId) ?? this.injectedInputs.set(sessionId, new Map()).get(sessionId)).set(message.id, digest);
176
+ }
177
+ catch (error) {
178
+ const dispatched = live.session.steerDispatchCount !== before;
179
+ await store.put({ ...receipt, outcome: dispatched ? 'unknown' : 'deferred' });
180
+ if (dispatched) {
181
+ const failure = new NeedError('INPUT_DELIVERY_UNCONFIRMED', '中途消息可能已交给原轮,送达结果未知,没有自动重复发送。', '原轮中途消息回执');
182
+ live.steerFailure ??= failure;
183
+ throw failure;
184
+ }
185
+ live.runtime.details?.record({ kind: 'need', severity: 'warning', code: error instanceof NeedError ? error.code : 'INPUT_DELIVERY_UNCONFIRMED', summary: '中途消息未发出,仍由官方队列后续处理。' });
186
+ }
187
+ });
188
+ const observed = work.catch(error => {
189
+ live.runtime.details?.record({ kind: 'need', severity: 'warning', code: error instanceof NeedError ? error.code : 'INPUT_DELIVERY_UNCONFIRMED', summary: '中途消息未确认,原消息没有丢弃或自动重发。' });
190
+ // Preserve uncertainty for this round, but known pre-dispatch failures do
191
+ // not poison later safe steering requests or unrelated future turns.
192
+ if (live.steerFailure === error)
193
+ throw error;
194
+ });
195
+ live.steerTail = observed;
196
+ void observed.catch(() => { });
197
+ return observed;
198
+ }
122
199
  catalog(signal) { if (!this.directory)
123
200
  throw new LlmError('无法获取模型列表:缺少可信主机目录能力', 'MODEL_CATALOG_UNAVAILABLE'); return this.directory.read(this.agent, signal); }
124
201
  async listModels(provider) { const catalog = await this.catalog(this.lifetime.signal); try {
@@ -130,6 +207,9 @@ export class CodexRemoteAdapter extends LlmAdapter {
130
207
  catalog.release();
131
208
  } }
132
209
  async resolveModel(provider, id, signal) {
210
+ const recovered = this.coldRecovery?.recoveryModel(provider, id, signal);
211
+ if (recovered)
212
+ return recovered;
133
213
  const displayed = this.modelPresentation.resolve(provider, id);
134
214
  if (displayed)
135
215
  return displayed;
@@ -175,10 +255,12 @@ export class CodexRemoteAdapter extends LlmAdapter {
175
255
  await this.cleanupRuntime(current.runtime);
176
256
  }
177
257
  async detachSession(sessionId) {
178
- await this.bridgeLoop.cancel(sessionId);
179
258
  const current = this.sessions.get(sessionId), turn = this.turns.get(sessionId);
180
259
  if (!current && !turn)
181
260
  return;
261
+ if (current?.runtime.broker?.supportsRecovery)
262
+ current.session.close({ layer: 'adapter', initiator: 'adapter.detach-sdk', reason: 'SESSION_DETACHED', action: 'detach' });
263
+ await this.bridgeLoop.cancel(sessionId);
182
264
  current?.runtime.closeDiagnostics?.record({ layer: 'adapter', initiator: 'adapter.detach-session', reason: 'SESSION_DETACHED', action: 'detach', changes: [{ field: 'adapter.detached', before: this.detached.has(sessionId), after: true }] });
183
265
  this.detached.add(sessionId);
184
266
  if (current) {
@@ -198,17 +280,32 @@ export class CodexRemoteAdapter extends LlmAdapter {
198
280
  for (const live of this.sessions.values())
199
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 }] });
200
282
  this.shuttingDown = true;
201
- await this.bridgeLoop.dispose();
283
+ this.coldRecovery?.dispose?.();
202
284
  this.modelPresentation.clear();
203
285
  this.employeeNoticeSessions.clear();
204
286
  this.pendingEmployeeNotices.clear();
205
287
  const results = await Promise.allSettled([...new Set([...this.sessions.keys(), ...this.turns.keys()])].map(id => this.detachSession(id)));
206
- this.lifetime.abort();
288
+ await this.bridgeLoop.dispose();
289
+ this.lifetime.abort(Object.assign(new DOMException('远程模型插件已关闭', 'AbortError'), { kind: 'disposed' }));
207
290
  const failure = results.find(result => result.status === 'rejected');
208
291
  if (failure?.status === 'rejected')
209
292
  throw failure.reason;
210
293
  }
211
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
+ }
306
+ // Before the tool bridge: a parked turn must not take a background request for its own continuation.
307
+ if (options.purpose)
308
+ throw new LlmError(employeeFailure('PURPOSE_UNSUPPORTED', this.agent.loginProvider, false), 'PURPOSE_UNSUPPORTED');
212
309
  let promptDispatched = !!options.sessionId && (this.sessions.get(options.sessionId)?.session.promptDispatchCount ?? 0) > 0;
213
310
  try {
214
311
  for await (const chunk of this.bridgeLoop.stream(options, (o, b) => this.generate(o, () => { promptDispatched = true; }, b))) {
@@ -247,8 +344,6 @@ export class CodexRemoteAdapter extends LlmAdapter {
247
344
  }
248
345
  }
249
346
  async *generate(original, onPromptDispatched, bridge) {
250
- if (original.purpose)
251
- throw new NeedError('PURPOSE_UNSUPPORTED', '此远程模型不处理后台标题或上下文整理请求,未发送模型请求', '独立的后台请求能力');
252
347
  if (this.lifetime.signal.aborted)
253
348
  throw new NeedError('DISPOSED', '远程模型插件已关闭', '启用远程模型插件');
254
349
  const key = original.sessionId;
@@ -258,7 +353,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
258
353
  if (key)
259
354
  this.turns.set(key, turn);
260
355
  const signal = AbortSignal.any([this.lifetime.signal, turn.signal, ...(original.signal ? [original.signal] : [])]);
261
- const options = { ...original, signal };
356
+ let options = { ...original, signal };
262
357
  const abortOffs = [];
263
358
  let bridgeMcp;
264
359
  let request;
@@ -270,11 +365,11 @@ export class CodexRemoteAdapter extends LlmAdapter {
270
365
  let remoteAttempted = false;
271
366
  let promptBaseline = 0;
272
367
  let failureCode;
273
- let preserveRecoveredRuntime = false;
274
368
  let activeMapper;
275
369
  let selected;
276
370
  let modelConfiguration;
277
371
  let turnFailure;
372
+ let coldPrelude = '';
278
373
  let employeeNoticeShown = false;
279
374
  let permissionOff;
280
375
  let permissionEpoch = new AbortController();
@@ -296,7 +391,12 @@ export class CodexRemoteAdapter extends LlmAdapter {
296
391
  try {
297
392
  if (!Number.isSafeInteger(config.acpMaxMessageBytes) || config.acpMaxMessageBytes < 1)
298
393
  throw new NeedError('SETTINGS_REQUIRED', '远程模型连接设置无效,请联系管理员检查', '有效的acpMaxMessageBytes');
299
- const checkpoint = readPointer(options, this.agent), previous = checkpoint?.pointer;
394
+ const standardCheckpoint = readPointer(options, this.agent), recoveredCheckpoint = await this.coldRecovery?.previousPointer(options);
395
+ const checkpoint = recoveredCheckpoint && (!standardCheckpoint || recoveredCheckpoint.index > standardCheckpoint.index) ? recoveredCheckpoint : standardCheckpoint, previous = checkpoint?.pointer ?? (checkpoint === recoveredCheckpoint ? standardCheckpoint?.pointer : undefined);
396
+ const usedColdCheckpoint = !!recoveredCheckpoint && checkpoint === recoveredCheckpoint;
397
+ let checkpointIndex = usedColdCheckpoint ? -1 : checkpoint?.index ?? -1;
398
+ if (usedColdCheckpoint)
399
+ options = { ...options, messages: options.messages.filter((m, index) => index > checkpoint.index || m.role === 'system' || m.role === 'developer') };
300
400
  employeeNoticeShown = !!key && this.employeeNoticeSessions.has(key) || false;
301
401
  if (employeeNoticeShown && key)
302
402
  this.employeeNoticeSessions.add(key);
@@ -319,8 +419,24 @@ export class CodexRemoteAdapter extends LlmAdapter {
319
419
  request.userMessageIds = request.userInputIds;
320
420
  earlyStage = 'source-context';
321
421
  await this.resolveRuntime.preflight?.(request);
422
+ options = { ...await this.coldRecovery?.projectCancelledInputs?.(options) ?? options, signal };
423
+ if (!usedColdCheckpoint)
424
+ checkpointIndex = readPointer(options, this.agent)?.index ?? -1;
425
+ const receipts = this.steeringReceipts && options.sessionId ? await this.steeringReceipts.read(options.sessionId, options.provider, humanIds) : new Map();
426
+ 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));
427
+ for (const receipt of matching)
428
+ if (receipt.outcome === 'prepared' || receipt.outcome === 'unknown')
429
+ throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '中途消息送达结果未知,没有在下一步骤重复提交;请核对原轮状态。', '原生注入回执');
430
+ const injected = new Set(matching.filter(r => r.outcome === 'injected').map(r => { if (!previous || r.nativeSessionId !== previous.sessionId)
431
+ throw new NeedError('SESSION_CONTEXT_MISMATCH', '中途消息属于另一原生轮,未重复提交。', '原会话的注入回执与检查点'); return r.messageId; }));
432
+ if (humanIds.length && humanIds.every(id => injected.has(id))) {
433
+ yield { type: 'finish', reason: { kind: 'stop' }, replayState: { response: previous } };
434
+ succeeded = true;
435
+ return;
436
+ }
437
+ const projected = { ...options, messages: options.messages.filter((m, index) => index <= checkpointIndex || !('id' in m) || typeof m.id !== 'string' || !injected.has(m.id)) };
322
438
  earlyStage = 'input-prepare';
323
- let input = await prepareInput(options, this.readImage);
439
+ let input = await prepareInput(projected, this.readImage);
324
440
  const contextSha256 = createHash('sha256').update(input.systemPrompt ?? '').digest('hex');
325
441
  request.contextSha256 = contextSha256;
326
442
  const codex = this.agent.loginProvider === 'codex';
@@ -348,7 +464,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
348
464
  }
349
465
  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))
350
466
  throw new NeedError('SESSION_CONTEXT_MISMATCH', '原会话的员工主机或工作区已改变,请新建会话', '原会话的可信目标和工作区');
351
- input = await prepareContinuation({ ...options, messages: options.messages.slice((checkpoint?.index ?? -1) + 1) }, input, this.readImage, { maxBytes: config.acpMaxMessageBytes, host: runtime.hostWorkspace });
467
+ input = await prepareContinuation({ ...options, messages: projected.messages.slice(checkpointIndex + 1) }, input, this.readImage, { maxBytes: config.acpMaxMessageBytes, host: runtime.hostWorkspace });
352
468
  if (runtime.hostWorkspace && mode === 'session' && Buffer.byteLength(JSON.stringify({ prompt: input.prompt, systemPrompt: input.systemPrompt }), 'utf8') > config.acpMaxMessageBytes)
353
469
  throw new NeedError('ACP_MESSAGE_TOO_LARGE', '本轮输入超过已设置的会话消息容量,未截断或发送', '管理员调整acpMaxMessageBytes');
354
470
  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 });
@@ -367,13 +483,14 @@ export class CodexRemoteAdapter extends LlmAdapter {
367
483
  let id;
368
484
  let stop;
369
485
  const pointerRuntime = runtime;
370
- 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 } : {}) });
486
+ 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 } : {}) });
371
487
  if (runtime.employeePresentation)
372
488
  details.record({ kind: 'session', severity: 'warning', code: 'EMPLOYEE_EXECUTION_SCOPE', summary: runtime.employeePresentation, payload: { source: 'local' } });
373
489
  if (runtime.execution)
374
490
  details.record({ kind: 'session', severity: 'warning', code: 'CLAUDE_EMPLOYEE_SCOPE', summary: runtime.execution.notice, payload: runtime.execution.scope });
375
491
  if ((runtime.employeePresentation || runtime.execution) && !employeeNoticeShown) {
376
- for (const chunk of mapper.text(EMPLOYEE_EXECUTION_NOTICE + (bridge?.enabled ? '\n\n' + TOOLBRIDGE_NOTICE : '') + '\n\n')) {
492
+ coldPrelude = EMPLOYEE_EXECUTION_NOTICE + (bridge?.enabled ? '\n\n' + TOOLBRIDGE_NOTICE : '') + '\n\n';
493
+ for (const chunk of mapper.text(coldPrelude)) {
377
494
  if (chunk.type === 'text-delta') {
378
495
  employeeNoticeShown = true;
379
496
  if (key) {
@@ -395,6 +512,10 @@ export class CodexRemoteAdapter extends LlmAdapter {
395
512
  let done = false;
396
513
  let failure;
397
514
  const push = (chunks) => { queue.push(...chunks); wake?.(); wake = undefined; };
515
+ let renderTail = Promise.resolve(), nativeUpdates = 0, coldPromptStarted = false;
516
+ 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?.(); }); };
517
+ const renderNotice = (text) => render(async () => { if (runtime.cold)
518
+ await runtime.cold.store.update(options.sessionId, options.provider, runtime.cold.id, row => { (row.localNotices ??= []).push({ beforeUpdate: nativeUpdates, text }); }); push(mapper.text(text)); });
398
519
  let promptPermit;
399
520
  let confirmedNativeMode;
400
521
  const hooks = { closeDiagnostics: runtime.closeDiagnostics, broker: runtime.broker, sessionOwnership: runtime.sessionOwnership, employeeExecution: runtime.employeeExecution, ...this.permissions ? { promptGuard: () => {
@@ -419,25 +540,31 @@ export class CodexRemoteAdapter extends LlmAdapter {
419
540
  }
420
541
  }
421
542
  if (execution) {
422
- if (toolName && ['Agent', 'Task', 'TaskOutput', 'TaskStop', 'Read', 'Write', 'Edit', 'Glob', 'Grep', 'Bash'].includes(toolName)) {
543
+ if (toolName && ['Read', 'Write', 'Edit', 'Glob', 'Grep', 'Bash'].includes(toolName)) {
423
544
  details.record({ kind: 'need', severity: 'warning', code: 'CLAUDE_HOST_TOOL_UNSUPPORTED', summary: '这类原生调用没有经过员工端别名,本机来源不支持;本次审批已取消', payload: { operation: toolName } });
424
- push(mapper.text('\n这类操作尚不支持在本机执行,已取消本次审批,没有在主机代跑。\n'));
545
+ renderNotice('\n这类操作尚不支持在本机执行,已取消本次审批,没有在主机代跑。\n');
425
546
  return 'cancelled';
426
547
  }
427
548
  }
428
549
  const answer = await this.approve?.(permission, approvalSignal, options, execution && toolName?.startsWith('mcp__employee__') ? 'employee-local' : undefined, runtime.hostWorkspace) ?? 'unavailable';
429
550
  return answer;
430
- }, onEmployeeNotice: notice => push(mapper.text(notice + '\n\n')), onUpdate: notification => { try {
431
- bridge?.observe(notification.update);
432
- push(mapper.acp(notification.update));
433
- }
434
- catch (error) {
435
- failure = error;
436
- session?.close({ layer: 'adapter', initiator: 'adapter.mapper-failure', reason: closeCode(error, 'MAPPING_FAILED'), action: 'close' });
437
- } }, onResponse: response => push(mapper.acpResponse(response)), onDetail: detail => details.record(detail) };
551
+ }, onEmployeeNotice: notice => renderNotice(notice + '\n\n'), onUpdate: (notification, originSequence) => { const fromPrompt = coldPromptStarted; render(async () => { let inRound = fromPrompt; if (fromPrompt && runtime.cold) {
552
+ const start = await runtime.cold.bound;
553
+ if (!Number.isSafeInteger(originSequence))
554
+ throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '原输出通知的来源未确认', '原broker输出序号');
555
+ inRound = originSequence > start;
556
+ if (!inRound) {
557
+ const update = notification.update;
558
+ if ((update.sessionUpdate === 'agent_message_chunk' || update.sessionUpdate === 'agent_thought_chunk') && update.content.type === 'text' && update.content.text) {
559
+ const text = update.content.text, kind = update.sessionUpdate === 'agent_thought_chunk' ? 'reasoning' : 'text';
560
+ await runtime.cold.store.update(options.sessionId, options.provider, runtime.cold.id, row => { (row.localNotices ??= []).push({ beforeUpdate: nativeUpdates, text, kind }); });
561
+ }
562
+ }
563
+ } bridge?.observe(notification.update); push(mapper.acp(notification.update)); if (inRound)
564
+ nativeUpdates++; }); }, onResponse: response => render(() => { push(mapper.acpResponse(response)); }), onDetail: detail => details.record(detail) };
438
565
  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 });
439
566
  session = new AcpSession(transport, hooks);
440
- live = { session, runtime, configuration, contextSha256, usageSnapshot: mapper.usageSnapshot };
567
+ live = { session, runtime, configuration, contextSha256, usageSnapshot: mapper.usageSnapshot, options, acceptingSteer: true, turnId: randomUUID(), steerIds: new Map(), steerTail: Promise.resolve(), maxBytes: config.acpMaxMessageBytes, notice: renderNotice };
441
568
  if (key)
442
569
  this.sessions.set(key, live);
443
570
  promptBaseline = session.promptDispatchCount;
@@ -534,13 +661,22 @@ export class CodexRemoteAdapter extends LlmAdapter {
534
661
  }
535
662
  recordInformation();
536
663
  details.beginTurn(runtime.detailContext?.() ?? { turn: null, step: null });
664
+ await renderTail;
665
+ if (runtime.cold && this.coldRecovery)
666
+ 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 });
667
+ coldPromptStarted = true;
537
668
  await runtime.execution?.beginTurn(modelSignal);
538
669
  if (bridge?.enabled)
539
670
  bridge.replayState = { response: makePointer(session.id) };
540
671
  bridge?.begin(modelSignal);
541
672
  id = session.id;
673
+ let promptFailed = false;
542
674
  try {
543
675
  const result = await dispatchPrompt();
676
+ live.acceptingSteer = false;
677
+ await live.steerTail;
678
+ if (live.steerFailure)
679
+ throw live.steerFailure;
544
680
  if (bridge?.unsettled)
545
681
  bridge.abandon('HOST_PROMPT_ENDED_WITH_PENDING_CALL');
546
682
  permissionOff?.();
@@ -548,7 +684,22 @@ export class CodexRemoteAdapter extends LlmAdapter {
548
684
  await permissionTail;
549
685
  return result;
550
686
  }
687
+ catch (error) {
688
+ promptFailed = true;
689
+ throw error;
690
+ }
551
691
  finally {
692
+ live.acceptingSteer = false;
693
+ try {
694
+ await live.steerTail;
695
+ if (live.steerFailure)
696
+ throw live.steerFailure;
697
+ }
698
+ catch (error) {
699
+ if (!promptFailed)
700
+ throw error;
701
+ details.record({ kind: 'need', severity: 'warning', code: 'INPUT_DELIVERY_UNCONFIRMED', summary: '原轮失败且有中途消息未获送达确认,没有重发。' });
702
+ }
552
703
  permissionOff?.();
553
704
  permissionOff = undefined;
554
705
  bridge?.end();
@@ -556,7 +707,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
556
707
  details.endTurn();
557
708
  }
558
709
  })();
559
- void task.then(value => { stop = value; }, error => { failure ??= runtime.broker?.error ?? error; }).finally(() => { done = true; wake?.(); wake = undefined; });
710
+ 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; });
560
711
  while (!done || queue.length) {
561
712
  if (queue.length)
562
713
  yield queue.shift();
@@ -586,11 +737,14 @@ export class CodexRemoteAdapter extends LlmAdapter {
586
737
  }
587
738
  }
588
739
  yield* mapper.flush();
589
- const pointer = makePointer(id);
740
+ 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;
741
+ const pointer = { ...makePointer(id), ...(finalCold ? { coldRoundTerminal: true, coldPromptId: finalCold.promptId, coldOutputAfter: runtime.broker?.lastSequence } : {}) };
590
742
  succeeded = true;
591
743
  yield { type: 'finish', reason: { kind: stop === 'max_tokens' || stop === 'max_turn_requests' ? 'max-tokens' : 'stop' }, replayState: { response: pointer } };
592
744
  }
593
745
  catch (error) {
746
+ if (original.signal?.reason?.kind === 'user' && runtime?.cold && this.coldRecovery)
747
+ 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 });
594
748
  if (session && session.promptDispatchCount > promptBaseline)
595
749
  onPromptDispatched();
596
750
  if (bridge?.unsettled && !signal.aborted)
@@ -617,23 +771,29 @@ export class CodexRemoteAdapter extends LlmAdapter {
617
771
  if (bridgeMcp)
618
772
  await bridgeMcp.close();
619
773
  if (runtime) {
774
+ if (runtime.cold && key)
775
+ this.coldRecovery?.release(key, runtime.cold.id);
620
776
  session?.close({ layer: 'adapter', initiator: 'adapter.turn-finally', reason: succeeded ? 'TURN_FINISHED' : 'TURN_FAILED', action: 'close' });
621
777
  if (key && this.sessions.get(key) === live)
622
778
  this.sessions.delete(key);
623
- void this.cleanupRuntime(runtime);
779
+ if (session && session.promptDispatchCount > promptBaseline && (runtime.cold && !succeeded && !bridge?.concludeAcknowledged || this.shuttingDown || key && this.detached.has(key) || original.signal?.reason?.kind === 'disposed'))
780
+ void runtime.detach?.({ layer: 'adapter', initiator: 'adapter.preserve-original', reason: 'SESSION_DETACHED', action: 'detach' });
781
+ else
782
+ void this.cleanupRuntime(runtime);
624
783
  }
625
784
  if (key && this.turns.get(key) === turn)
626
785
  this.turns.delete(key);
627
- if (key)
786
+ if (key) {
628
787
  this.detached.delete(key);
788
+ }
629
789
  }
630
790
  }
631
791
  }
632
792
  /** One official registration owns both routes, preserving opaque replay ownership. */
633
793
  export class RemoteAgentsAdapter extends LlmAdapter {
634
794
  adapters = new Map();
635
- constructor(config, makeRuntime, approve, nameFor, readImage, reportLoginFailure, directory, preflightDiagnostics, permissions, bridgeStopped) { super(); for (const agent of AGENTS)
636
- this.adapters.set(agent.id, new CodexRemoteAdapter(config, makeRuntime(agent), approve, () => nameFor(agent), agent, readImage, reportLoginFailure, directory, preflightDiagnostics, permissions, bridgeStopped)); }
795
+ constructor(config, makeRuntime, approve, nameFor, readImage, reportLoginFailure, directory, preflightDiagnostics, permissions, bridgeStopped, steeringReceipts, coldRecovery) { super(); for (const agent of AGENTS)
796
+ this.adapters.set(agent.id, new CodexRemoteAdapter(config, makeRuntime(agent), approve, () => nameFor(agent), agent, readImage, reportLoginFailure, directory, preflightDiagnostics, permissions, bridgeStopped, steeringReceipts, coldRecovery)); }
637
797
  adapter(provider) { const adapter = this.adapters.get(provider); if (!adapter)
638
798
  throw new LlmError('远程模型未注册', 'PROVIDER_NOT_FOUND'); return adapter; }
639
799
  providerInfo(provider) { return this.adapter(provider).providerInfo(provider); }
@@ -642,7 +802,7 @@ export class RemoteAgentsAdapter extends LlmAdapter {
642
802
  async prepareCall(provider, model, signal) { const prepared = await this.adapter(provider).prepareCall(provider, model, signal); return { ...prepared, stream: (options) => this.stream(options) }; }
643
803
  providerRetryPolicy() { return { mode: 'normal', maxRetries: 0, retryableCodes: [], initialDelayMs: 0, maxDelayMs: 0, jitterRatio: 0 }; }
644
804
  stream(options) {
645
- if (options.sessionId)
805
+ if (options.sessionId && !options.purpose)
646
806
  for (const [provider, adapter] of this.adapters)
647
807
  if (provider !== options.provider && adapter.hasBridgeSession(options.sessionId)) {
648
808
  void adapter.disposeSession(options.sessionId);
@@ -650,6 +810,8 @@ export class RemoteAgentsAdapter extends LlmAdapter {
650
810
  }
651
811
  return this.adapter(options.provider).stream(options);
652
812
  }
813
+ canSteer(provider, sessionId) { return this.adapters.get(provider)?.canSteer(sessionId) ?? false; }
814
+ steer(provider, sessionId, message, isCurrent) { return this.adapter(provider).steer(sessionId, message, isCurrent); }
653
815
  async completeDshTurn(sessionId, messages) { await Promise.all([...this.adapters.values()].map(adapter => adapter.completeDshTurn(sessionId, messages))); }
654
816
  async disposeSession(sessionId) { await Promise.all([...this.adapters.values()].map(adapter => adapter.disposeSession(sessionId))); }
655
817
  async detachSession(sessionId) { await Promise.all([...this.adapters.values()].map(adapter => adapter.detachSession(sessionId))); }
@@ -665,7 +827,9 @@ export function apply(ctx, live) {
665
827
  throw new NeedError('ATTACHMENT_REQUIRED', '我需要官方附件组件读取这张图片', '官方attachments.readImage');
666
828
  return attachments.readImage(ref, signal);
667
829
  };
668
- const openByAgent = new Map(AGENTS.map(agent => [agent.id, brokerFactory(get, undefined, config)]));
830
+ const sessionSources = createSessionSources(ctx, get);
831
+ const coldRecovery = new ColdRecovery(ctx, get, config, { readSource: sessionSources.read });
832
+ const openByAgent = new Map(AGENTS.map(agent => [agent.id, brokerFactory(get, undefined, config, { coldStore: coldRecovery.store })]));
669
833
  const detailManagers = new Map();
670
834
  const managerForProfile = () => {
671
835
  const profile = ctx.get('profileContext');
@@ -678,7 +842,6 @@ export function apply(ctx, live) {
678
842
  return manager;
679
843
  };
680
844
  ctx.provide('aiWorkbenchRemoteDiagnostics', { read: (query) => managerForProfile().read(query) });
681
- const sessionSources = createSessionSources(ctx, get);
682
845
  const preflightDiagnostics = createPreflightDiagnostics({ ctx, getApi: get, manager: managerForProfile });
683
846
  const diagnostics = new Map();
684
847
  const diagnostic = (scope, provider, message) => {
@@ -697,6 +860,7 @@ export function apply(ctx, live) {
697
860
  // Public Loader Entry.options.id; optional when mounted without Loader.
698
861
  const actualSettingsNamespace = ctx.fiber.entry?.options.id;
699
862
  const modelDirectory = new ModelCatalog(get, () => config().acpMaxMessageBytes, undefined, (provider, error) => managerForProfile().recordCatalogFailure(provider, error));
863
+ const steeringReceipts = createSteeringReceipts(ctx);
700
864
  const adapter = new RemoteAgentsAdapter(config, agent => {
701
865
  const details = async (request, api, connection, target) => {
702
866
  return managerForProfile().open({ sessionId: request.sessionId, provider: agent.loginProvider, identity: `${target.username}@${target.host}:${target.port}`, connection });
@@ -728,8 +892,7 @@ export function apply(ctx, live) {
728
892
  const workspace = async (request) => {
729
893
  const services = ctx;
730
894
  const registry = services.get('workspaceRegistry');
731
- const sessions = services.get('sessions');
732
- return officialEmployeeWorkspace(request.sessionId, registry, sessions?.get(request.sessionId)?.header);
895
+ return officialEmployeeWorkspace(request.sessionId, registry, services.get('sessions'));
733
896
  };
734
897
  const provider = connectProvider(get, { agent, workspace, source: sessionSources, ...(agent.loginProvider === 'codex' ? { employee: {
735
898
  getNetwork: () => ctx.get('aiWorkbenchNetwork'),
@@ -776,7 +939,9 @@ export function apply(ctx, live) {
776
939
  if (turn !== null && step !== null)
777
940
  agent.session.append('assistant/message', { turn, step, message: createAssistantMessage({ content: [{ type: 'text', text: notice }], source: { provider: 'ai-workbench-toolbridge', model: 'notice' } }), stream: [] }, { surfaceOp: 'append' });
778
941
  agent.cancel({ kind: 'hook', reason: 'DSH_BRIDGE_CALL_ABANDONED_BY_HOST' }, { keepInbox: true });
779
- });
942
+ }, steeringReceipts, coldRecovery);
943
+ coldRecovery.install();
944
+ installLiveSteering(ctx, adapter);
780
945
  ctx.on('session/event', (session, event) => { if (event.type === 'turn/end') {
781
946
  const operation = event.data.reason.kind === 'completed' ? adapter.completeDshTurn(session.id, session.deriveMessages()) : adapter.disposeSession(session.id);
782
947
  void operation.catch(() => ctx.logger('remote-agent').warn('TOOLBRIDGE_RESULT_DELIVERY_UNCONFIRMED'));
package/dist/input.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { NeedError } from "./remote.js";
2
+ import { dshSkillCatalog } from "./toolbridge-table.js";
2
3
  function runtimeSections(message) {
3
4
  const source = message.source;
4
5
  if (message.role !== 'user' || source?.kind !== 'runtime-context' || source.form !== 'snapshot' || !Array.isArray(source.sections) || message.content.length !== 1 || message.content[0].type !== 'text')
@@ -138,7 +139,9 @@ export async function prepareInput(options, readImage) {
138
139
  const before = prompt.length;
139
140
  const sections = runtimeSections(message);
140
141
  for (const block of message.content) {
141
- const prepared = await publicBlock(block, options, readImage);
142
+ let prepared = await publicBlock(block, options, readImage);
143
+ if (prepared.type === 'text' && dshSkillCatalog([message]) !== undefined)
144
+ prepared = { ...prepared, text: '以下是DSH的技能目录,供DSH工具skill使用;主机Claude/Codex原生技能按各自原生指令加载。加载后请按<skill_resources>给出的资源基址读取资源。\n' + prepared.text };
142
145
  prompt.push(prepared);
143
146
  if (sections)
144
147
  runtimeSnapshots.set(prepared, sections);