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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,8 +1,13 @@
1
- # AI Workbench 远程助手 · @ai-workbench/remote-agent@0.9.0-toolbridge.13 · 插件 → 添加插件
1
+ # AI Workbench 远程助手 · @ai-workbench/remote-agent@0.9.0-toolbridge.14 · 插件 → 添加插件
2
2
 
3
3
  ## 含工具桥预发布线
4
4
 
5
- 本包为 `0.9.0-toolbridge.13`,从 `v0.9.0-toolbridge.12` 派生,使用 `host-toolbridge` 发布渠道。员工安装由连接组件提供的「AI 写作工作台(含工具桥)」总包 `@ai-workbench/workbench-toolbridge@0.1.10`,与不含工具桥的版本二选一。
5
+ 本包为 `0.9.0-toolbridge.14`,从 `v0.9.0-toolbridge.13` 派生,使用 `host-toolbridge` 发布渠道。员工安装由连接组件提供的「AI 写作工作台(含工具桥)」总包 `@ai-workbench/workbench-toolbridge@0.1.11`,与不含工具桥的版本二选一。
6
+
7
+ 本轮增加两家运行中插话(DSH 原生 nextStep),保留官方队列和原话;明确 followup 仍排下一轮。Codex 含桥组件需 `2.2.2-aw.12`,Claude 仍为官方 `0.94.0`。插件确定消息未发出时保留排队资格;送达未确认时明确报错且不重放。已注入旧正文不能撤回,编辑版下一步骤交付。
8
+
9
+ host `0.8.9` 的新 broker 支持同一客户端/SDK 在切网后按输出游标和输入 ACK 水位接回原 prompt、结果及用量,不重新发送原 prompt;旧本机执行端失效仍为 UNKNOWN,不用新进程替换或重放旧操作。客户端退出/重开后的冷恢复尚未完成;旧运行 broker 不会被安装自动追改。无新增设置;512,000,000 字节默认保留,实际协议头计入同一容量。
10
+
6
11
 
7
12
  选择本机文件夹后,Claude 和 Codex 可以把 DSH 已启用的 MCP、web、skill、ask_user、todo/present/goal 等工具交给 DSH 原生执行和审批。内置文件/命令、子代理/agent-team、run_code 不在桥接表;原有文件和命令执行方式保留。plan 不自动放行桥接权限;default 下 Claude 的桥接原生权限由插件单次应答,员工只在 DSH 审批实际工具。主机文件夹不开放工具桥。
8
13
 
package/dist/acp.d.ts CHANGED
@@ -53,6 +53,10 @@ export declare class AcpSession {
53
53
  private turnSignal?;
54
54
  private turnToken?;
55
55
  private busy;
56
+ private steeringSupported;
57
+ private dispatchedSteers;
58
+ get canSteer(): boolean;
59
+ get steerDispatchCount(): number;
56
60
  private startAttempted;
57
61
  private negotiated;
58
62
  private method?;
@@ -118,6 +122,7 @@ export declare class AcpSession {
118
122
  start(cwd: string, resumeId?: string, signal?: AbortSignal, context?: AcpStartContext, prompt?: acp.ContentBlock[]): Promise<string>;
119
123
  /** Codex context is immutable after creation; keep the old remote session intact. */
120
124
  prompt(input: string | acp.ContentBlock[], signal?: AbortSignal): Promise<acp.StopReason>;
125
+ steer(prompt: acp.ContentBlock[], signal?: AbortSignal, isCurrent?: () => boolean, maxBytes?: number): Promise<'injected' | 'promptRequired'>;
121
126
  close(cause?: CloseCause, error?: Error): void;
122
127
  }
123
128
  export declare function acpNeed(error: unknown): NeedError;
package/dist/acp.js CHANGED
@@ -18,6 +18,10 @@ export class AcpSession {
18
18
  turnSignal;
19
19
  turnToken;
20
20
  busy = false;
21
+ steeringSupported = false;
22
+ dispatchedSteers = 0;
23
+ get canSteer() { return this.steeringSupported && this.busy && !this.closeRequested; }
24
+ get steerDispatchCount() { return this.dispatchedSteers; }
21
25
  startAttempted = false;
22
26
  negotiated = {};
23
27
  method;
@@ -430,6 +434,10 @@ export class AcpSession {
430
434
  throw new acp.RequestError(-32601, '不支持此扩展交互');
431
435
  })
432
436
  .onNotification('*', ({ method, params }) => {
437
+ if (method === '_aw/broker-replay-complete') {
438
+ this.hooks.broker?.confirmReplay(record(params)?.generation);
439
+ return;
440
+ }
433
441
  this.detail({ kind: 'extension', severity: 'warning', code: 'ACP_UNKNOWN_NOTIFICATION', summary: '收到未知远端扩展通知,已保留技术记录', method, payload: params });
434
442
  });
435
443
  if ('readable' in transport && 'writable' in transport)
@@ -449,7 +457,8 @@ export class AcpSession {
449
457
  /** A rejected request on an already-closed SDK never reaches this write.
450
458
  * Once a transport write starts, failure remains delivery-unknown. */
451
459
  observeDispatch(message) {
452
- if (record(message)?.method !== 'session/prompt' || !Object.hasOwn(message, 'id'))
460
+ const method = record(message)?.method;
461
+ if (!['session/prompt', '_session/steering'].includes(String(method)) || !Object.hasOwn(message, 'id'))
453
462
  return;
454
463
  const params = record(record(message)?.params), current = params ? this.promptPermissions.get(params) : undefined;
455
464
  if (params)
@@ -458,6 +467,8 @@ export class AcpSession {
458
467
  this.closeDiagnostics.record({ layer: 'acp', initiator: 'acp.permission-dispatch-gate', reason: 'PERMISSION_POLICY_CHANGED', operation: 'session/prompt', action: 'failure' });
459
468
  throw new NeedError('PERMISSION_POLICY_CHANGED', '当前权限已变化或无法核对,这次派发已停止;原输入没有重放。', '当前权限代次与远端同值回执');
460
469
  }
470
+ if (current.maxBytes !== undefined && Buffer.byteLength(JSON.stringify(message)) + 1 > current.maxBytes)
471
+ throw new NeedError('ACP_MESSAGE_TOO_LARGE', '中途消息超过已设置的会话消息容量,未发送。', '管理员调整acpMaxMessageBytes');
461
472
  current.native();
462
473
  this.hooks.broker?.authorizePrompt(() => { try {
463
474
  if (!current.current())
@@ -468,7 +479,10 @@ export class AcpSession {
468
479
  catch {
469
480
  return false;
470
481
  } });
471
- this.dispatchedPrompts++;
482
+ if (method === 'session/prompt')
483
+ this.dispatchedPrompts++;
484
+ else
485
+ this.dispatchedSteers++;
472
486
  }
473
487
  observe(stream) {
474
488
  // Observe already-parsed public Stream messages: no NDJSON parsing, second
@@ -520,6 +534,8 @@ export class AcpSession {
520
534
  if (hello.protocolVersion !== acp.PROTOCOL_VERSION)
521
535
  throw new NeedError('ACP_VERSION_MISMATCH', 'ACP 协议版本不兼容', '支持 ACP v1 的远端 agent');
522
536
  this.negotiated = hello.agentCapabilities ?? {};
537
+ const steering = record(hello._meta?.steering);
538
+ this.steeringSupported = steering?.supported === true && (!context?.codexNewSessionOnly || steering.idleBehavior === 'promptRequired');
523
539
  if (this.employeeMeta) {
524
540
  const policy = record(hello._meta?.awEmployeeExecution);
525
541
  if (!this.hooks.employeeExecution || !policy || Object.keys(policy).length !== (context?.toolBridgeServers ? 6 : 5) || context?.toolBridgeServers && policy.mcpBridge !== 1 || policy.version !== 1 || policy.nativeCliVersion !== '0.160.1' || policy.native !== true || policy.perRpcGate !== true || policy.noHostFallback !== true)
@@ -626,6 +642,10 @@ export class AcpSession {
626
642
  let rejectAbort;
627
643
  const interrupted = new Promise((_resolve, reject) => { rejectAbort = reject; });
628
644
  const cancel = () => {
645
+ if (this.closeRequested) {
646
+ rejectAbort?.(new NeedError('ABORTED', '客户端已分离,未重发或取消主机原轮', '原轮恢复状态'));
647
+ return;
648
+ }
629
649
  this.closeDiagnostics.record({ layer: 'acp', initiator: 'acp.prompt-cancel', reason: 'ABORTED', operation: 'session/prompt', action: 'abort' });
630
650
  rejectAbort?.(new NeedError('ABORTED', '已请求取消本轮,远端状态需确认', '确认主机取消状态'));
631
651
  void this.connection.agent.notify(acp.methods.agent.session.cancel, { sessionId: this.sessionId }).catch(() => {
@@ -656,12 +676,34 @@ export class AcpSession {
656
676
  this.turnToken = undefined;
657
677
  }
658
678
  }
679
+ async steer(prompt, signal, isCurrent, maxBytes) {
680
+ if (!this.canSteer || !this.sessionId || isCurrent && !isCurrent())
681
+ return 'promptRequired';
682
+ this.validatePrompt(prompt);
683
+ signal?.throwIfAborted();
684
+ const token = this.turnToken, permit = this.hooks.promptGuard?.(), expected = this.selectedPermission, reported = new Set();
685
+ const current = () => this.canSteer && (!isCurrent || isCurrent()) && this.turnToken === token && !signal?.aborted && (!permit || !permit.signal.aborted && permit.isCurrent());
686
+ const params = { sessionId: this.sessionId, prompt, _meta: { steering: { idleBehavior: 'promptRequired' } } };
687
+ this.promptPermissions.set(params, { current, native: () => this.validateNativePermission(expected, reported), maxBytes });
688
+ try {
689
+ const result = await this.connection.agent.request('_session/steering', params, { cancellationSignal: signal });
690
+ if (result.outcome === 'injected' || result.outcome === 'promptRequired')
691
+ return result.outcome;
692
+ throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '中途消息未获得同一轮的注入回执,没有重复提交。', '原轮injected或promptRequired回执');
693
+ }
694
+ catch (error) {
695
+ throw acpNeed(error);
696
+ }
697
+ }
659
698
  close(cause = { layer: 'acp', initiator: 'acp.close', reason: 'ACP_CLOSE_REQUESTED', action: 'close' }, error) { this.closeDiagnostics.record({ ...cause, changes: cause.changes ?? [{ field: 'acp.close-requested', before: this.closeRequested, after: true }] }); this.closeRequested = true; this.connection?.close(error); }
660
699
  }
661
700
  export function acpNeed(error) {
662
701
  if (error instanceof NeedError)
663
702
  return error;
664
703
  if (error instanceof acp.RequestError) {
704
+ const localCode = record(error.data)?.localDispatchCode;
705
+ if (error.message === 'ACP_LOCAL_REQUEST_REJECTED' && (localCode === 'ACP_MESSAGE_TOO_LARGE' || localCode === 'PERMISSION_POLICY_CHANGED'))
706
+ return new NeedError(localCode, '中途消息在实际派发前被拒绝,仍在官方队列中,未发送。', '当前消息、权限与acpMaxMessageBytes');
665
707
  if (record(error.data)?.reason === 'thread_active_writer')
666
708
  return new NeedError('REMOTE_SESSION_BUSY', employeeFailure('REMOTE_SESSION_BUSY'), '原远端线程仍被占用;需要按同一DSH会话和远端线程定位已断开的旧broker并确认释放;RPC 错误码 ' + error.code);
667
709
  // Host SDK1.9 uses Internal error + data.details for thrown adapter errors.
@@ -36,14 +36,29 @@ export function brokerFactory(_get, _ask, configuration, provided) {
36
36
  throw new NeedError(started.code, '主机的环境配置会覆盖本机执行位置,本轮已停止;请由管理员移开该配置后在原会话重试。', '主机 CODEX_HOME/environments.toml 不存在');
37
37
  if (started.protocolVersion !== 1 || started.id !== id || !started.instanceId)
38
38
  throw new NeedError('BROKER_PROTOCOL_INVALID', '主机会话未能启动,请恢复连接后再试。', '有效的主机会话启动回应');
39
- const channel = new BrokerTransport({ observeClose: diagnostics.capture(), maxFrameBytes: settings.brokerMaxFrameBytes, instanceId: started.instanceId, leased: true, controlMaxBytes: started.controlMaxBytes, attach: () => io.attach(command(['attach', id, '--after', '0', '--framed', '--leased', '--if-instance', started.instanceId])) });
39
+ const channel = new BrokerTransport({ observeClose: diagnostics.capture(), maxFrameBytes: settings.brokerMaxFrameBytes, instanceId: started.instanceId, leased: true, controlMaxBytes: started.controlMaxBytes, ...(started.inputProtocolVersion === 2 ? { inputProtocolVersion: 2, recoverDisconnect: true } : {}), attach: (after = 0) => io.attach(command(['attach', id, '--after', String(after), '--framed', '--leased', ...(started.inputProtocolVersion === 2 ? ['--input-protocol', '2'] : []), '--if-instance', started.instanceId])) });
40
+ const reconnectOff = started.inputProtocolVersion === 2 ? _get()?.onConnectionState?.(state => { if (state.phase === 'connected' && !channel.online)
41
+ void channel.connect().catch(() => { }); }) : undefined;
40
42
  let ended = false;
41
- const dispose = async (cause = { layer: 'broker', initiator: 'broker.dispose', reason: 'BROKER_DISPOSE', action: 'dispose' }) => {
43
+ const detach = async (cause = { layer: 'broker', initiator: 'broker.detach', reason: 'SESSION_DETACHED', action: 'detach' }) => {
42
44
  if (ended)
43
45
  return;
44
46
  ended = true;
47
+ reconnectOff?.();
45
48
  diagnostics.record(cause);
46
49
  channel.close(cause);
50
+ };
51
+ const dispose = async (cause = { layer: 'broker', initiator: 'broker.dispose', reason: 'BROKER_DISPOSE', action: 'dispose' }) => {
52
+ if (ended)
53
+ return;
54
+ if (channel.supportsRecovery) {
55
+ const attachmentId = channel.attachmentId;
56
+ await detach(cause);
57
+ if (attachmentId)
58
+ void io.run(command(['kill', id, '--if-instance', started.instanceId, '--if-attachment', attachmentId])).catch(() => console.warn('[remote-agent] 原写者已分离或更换,主机按既有生命周期保留原轮'));
59
+ return;
60
+ }
61
+ await detach(cause);
47
62
  void io.run(command(['kill', id, '--if-instance', started.instanceId])).catch(() => console.warn('[remote-agent] 旧主机会话暂未清理,将由主机自动回收'));
48
63
  };
49
64
  const aborted = () => channel.fail(new NeedError('ABORTED', '本轮已取消。', '确认主机状态'), { layer: 'broker', initiator: 'broker.open-signal', reason: 'ABORTED', action: 'abort' });
@@ -61,6 +76,6 @@ export function brokerFactory(_get, _ask, configuration, provided) {
61
76
  finally {
62
77
  request.signal?.removeEventListener('abort', aborted);
63
78
  }
64
- return { identity: identity(target), cwd: project.path, closeDiagnostics: diagnostics, broker: channel, sessionOwnership, acpTransport: channel, dispose, detach: dispose };
79
+ return { identity: identity(target), cwd: project.path, closeDiagnostics: diagnostics, broker: channel, sessionOwnership, acpTransport: channel, dispose, detach: channel.supportsRecovery ? detach : dispose };
65
80
  };
66
81
  }
package/dist/broker.d.ts CHANGED
@@ -9,7 +9,9 @@ export interface BrokerOptions {
9
9
  instanceId?: string;
10
10
  leased?: boolean;
11
11
  controlMaxBytes?: number;
12
- attach: () => Promise<Attachment>;
12
+ attach: (after?: number) => Promise<Attachment>;
13
+ inputProtocolVersion?: 2;
14
+ recoverDisconnect?: boolean;
13
15
  onNeed?: (need: Need) => void;
14
16
  }
15
17
  /** One byte stream / SDK app over one SSH attachment of a new agent. Input is never replayed. */
@@ -20,6 +22,20 @@ export declare class BrokerTransport {
20
22
  private output;
21
23
  private attachment?;
22
24
  private cursor;
25
+ private attachedId?;
26
+ get attachmentId(): string | undefined;
27
+ private inputSequence;
28
+ private inputReady;
29
+ private pendingInput?;
30
+ private recoveryTimer?;
31
+ private recoveryIntervalMs?;
32
+ private everReady;
33
+ get recovering(): boolean;
34
+ get supportsRecovery(): boolean;
35
+ confirmReplay(generation: unknown): void;
36
+ private recover;
37
+ private waitInput;
38
+ private acknowledge;
23
39
  private epoch;
24
40
  private attached;
25
41
  private ended;
package/dist/broker.js CHANGED
@@ -11,6 +11,64 @@ export class BrokerTransport {
11
11
  output;
12
12
  attachment;
13
13
  cursor = 0;
14
+ attachedId;
15
+ get attachmentId() { return this.attachedId; }
16
+ inputSequence = 0;
17
+ inputReady = true;
18
+ pendingInput;
19
+ recoveryTimer;
20
+ recoveryIntervalMs;
21
+ everReady = false;
22
+ get recovering() { return !!this.options.recoverDisconnect && !this.ended && !this.attached; }
23
+ get supportsRecovery() { return !!this.options.recoverDisconnect && this.options.inputProtocolVersion === 2; }
24
+ confirmReplay(generation) { if (this.options.inputProtocolVersion === 2 && generation === this.epoch && this.online) {
25
+ this.inputReady = true;
26
+ this.changed();
27
+ } }
28
+ recover() {
29
+ if (!this.supportsRecovery || this.ended || this.online)
30
+ return;
31
+ void (async () => {
32
+ try {
33
+ await this.joining?.catch(() => { });
34
+ if (!this.ended && !this.online)
35
+ await this.connect();
36
+ }
37
+ catch (error) {
38
+ if (this.ended)
39
+ return;
40
+ this.notice(error instanceof NeedError ? error.code : 'CONNECTION_LOST', '主机原轮暂未重新附着,等待原租约或连接恢复,没有重发输入。');
41
+ if (this.recoveryIntervalMs !== undefined && this.recoveryTimer === undefined) {
42
+ this.recoveryTimer = setTimeout(() => { this.recoveryTimer = undefined; this.recover(); }, this.recoveryIntervalMs);
43
+ this.recoveryTimer.unref();
44
+ }
45
+ }
46
+ })();
47
+ }
48
+ waitInput() {
49
+ if (this.online && this.inputReady)
50
+ return Promise.resolve();
51
+ if (this.ended)
52
+ return Promise.reject(this.failure ?? new NeedError('CONNECTION_LOST', '原执行流已结束', '原轮状态'));
53
+ return new Promise((resolve, reject) => { const off = this.onChange(() => { if (this.ended) {
54
+ off();
55
+ reject(this.failure ?? new NeedError('CONNECTION_LOST', '原执行流已结束', '原轮状态'));
56
+ }
57
+ else if (this.online && this.inputReady) {
58
+ off();
59
+ resolve();
60
+ } }); });
61
+ }
62
+ acknowledge(sequence) {
63
+ if (!Number.isSafeInteger(sequence) || sequence < 0)
64
+ throw new NeedError('BROKER_PROTOCOL_INVALID', '主机输入确认序号无效', '原broker输入水位');
65
+ if (sequence === this.inputSequence)
66
+ return;
67
+ if (!this.pendingInput || sequence !== this.pendingInput.sequence)
68
+ throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '主机输入水位不属于本客户端,未跳过或重发输入。', '原客户端唯一在途输入');
69
+ this.inputSequence = sequence;
70
+ this.pendingInput.ack.resolve();
71
+ }
14
72
  epoch = 0;
15
73
  attached = false;
16
74
  ended = false;
@@ -27,6 +85,7 @@ export class BrokerTransport {
27
85
  if (!Number.isSafeInteger(options.maxFrameBytes) || options.maxFrameBytes < 1)
28
86
  throw new NeedError('SETTINGS_REQUIRED', '我需要 brokerMaxFrameBytes', '管理员确认 brokerMaxFrameBytes');
29
87
  this.options = options;
88
+ this.inputReady = options.inputProtocolVersion !== 2;
30
89
  this.lease.abort();
31
90
  this.readable = new ReadableStream({ start: c => { this.output = c; }, pull: () => { this.attachment?.stdout.resume(); }, cancel: reason => { this.close({ layer: 'broker', initiator: 'broker.reader-cancel', reason: closeCode(reason, 'BROKER_READER_CANCELLED'), action: 'close' }); } });
32
91
  this.writable = new WritableStream({ write: bytes => this.write(bytes), close: () => this.close({ layer: 'broker', initiator: 'broker.writer-close', reason: 'BROKER_WRITER_CLOSED', action: 'close' }), abort: reason => this.close({ layer: 'broker', initiator: 'broker.writer-abort', reason: closeCode(reason, 'BROKER_WRITER_ABORTED'), action: 'abort' }) });
@@ -35,7 +94,10 @@ export class BrokerTransport {
35
94
  get generation() { return this.epoch; }
36
95
  get signal() { return this.lease.signal; }
37
96
  get error() { return this.failure; }
38
- stopHeartbeat() { if (this.heartbeat !== undefined)
97
+ stopHeartbeat() { if (this.recoveryTimer !== undefined) {
98
+ clearTimeout(this.recoveryTimer);
99
+ this.recoveryTimer = undefined;
100
+ } if (this.heartbeat !== undefined)
39
101
  clearInterval(this.heartbeat); this.heartbeat = undefined; }
40
102
  authorizeResponse(id, generation, valid) { this.permits.set(JSON.stringify(id), { generation, valid }); }
41
103
  authorizePrompt(valid) { this.promptPermit = valid; }
@@ -52,6 +114,7 @@ export class BrokerTransport {
52
114
  this.ended = true;
53
115
  this.attached = false;
54
116
  this.lease.abort();
117
+ this.pendingInput?.ack.reject(error);
55
118
  this.notice(error.code, error.message);
56
119
  this.changed();
57
120
  this.attachment?.kill('SIGTERM');
@@ -68,6 +131,7 @@ export class BrokerTransport {
68
131
  this.ended = true;
69
132
  this.attached = false;
70
133
  this.lease.abort();
134
+ this.pendingInput?.ack.reject(new NeedError('CONNECTION_LOST', '原轮已经关闭,输入未重发', '原轮状态'));
71
135
  this.changed();
72
136
  this.attachment?.kill('SIGTERM');
73
137
  try {
@@ -86,7 +150,7 @@ export class BrokerTransport {
86
150
  return this.joining;
87
151
  }
88
152
  async attach() {
89
- const child = await this.options.attach();
153
+ const child = await this.options.attach(this.cursor);
90
154
  if (this.ended) {
91
155
  this.options.observeClose?.({ layer: 'broker', initiator: 'broker.late-attachment', reason: 'SESSION_ENDED', action: 'terminate' });
92
156
  child.kill('SIGTERM');
@@ -128,16 +192,55 @@ export class BrokerTransport {
128
192
  this.heartbeat.unref?.();
129
193
  }
130
194
  }
195
+ if (this.options.inputProtocolVersion === 2) {
196
+ const receipt = f.inputReceipt;
197
+ if (f.inputProtocolVersion !== 2 || !receipt || receipt.failed !== false)
198
+ throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '主机不能确认原输入字节水位,未重发输入。', 'inputProtocolVersion 2的有效回执');
199
+ this.acknowledge(receipt.committedSequence);
200
+ if (receipt.pendingSequence !== null && receipt.pendingSequence !== this.pendingInput?.sequence)
201
+ throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '主机在途输入不属于本客户端', '原客户端在途输入');
202
+ if (typeof f.attachmentId !== 'string' || !f.attachmentId)
203
+ throw new NeedError('BROKER_PROTOCOL_INVALID', '主机缺少写者实例标识', '本次attachmentId');
204
+ this.attachedId = f.attachmentId;
205
+ this.inputReady = false;
206
+ }
207
+ const lifecycle = f.lifecycle;
208
+ if (this.supportsRecovery && Number.isSafeInteger(lifecycle?.heartbeatIntervalMs) && lifecycle.heartbeatIntervalMs > 0)
209
+ this.recoveryIntervalMs = lifecycle.heartbeatIntervalMs;
131
210
  ready = true;
211
+ this.everReady = true;
132
212
  this.attached = true;
133
213
  this.lease = new AbortController();
134
214
  this.changed();
135
215
  connected.resolve();
136
216
  return;
137
217
  }
218
+ if (f.type === 'input-ack') {
219
+ if (this.options.inputProtocolVersion !== 2)
220
+ throw new NeedError('BROKER_PROTOCOL_INVALID', '未协商输入确认', 'inputProtocolVersion 2');
221
+ this.acknowledge(f.sequence);
222
+ return;
223
+ }
224
+ if (f.type === 'replay-complete') {
225
+ if (this.options.inputProtocolVersion !== 2 || f.sequence !== this.cursor)
226
+ throw new NeedError('REPLAY_GAP', '原轮回放水位未连续', '完整原轮回放');
227
+ this.output.enqueue(Buffer.from(JSON.stringify({ jsonrpc: '2.0', method: '_aw/broker-replay-complete', params: { generation: this.epoch } }) + '\n'));
228
+ return;
229
+ }
138
230
  if (f.type === 'error') {
139
231
  const code = typeof f.code === 'string' && /^[A-Z][A-Z0-9_]{0,63}$/.test(f.code) ? f.code : 'BROKER_PROTOCOL_INVALID';
140
232
  const error = new NeedError(code, '主机会话无法续接(' + code + ');没有重放输入或代答审批', '恢复或显式结束原会话');
233
+ if (ready && code === 'ATTACH_LEASE_EXPIRED' && this.supportsRecovery) {
234
+ attemptClosed = true;
235
+ this.stopHeartbeat();
236
+ this.attached = false;
237
+ this.inputReady = false;
238
+ this.lease.abort();
239
+ this.changed();
240
+ child.kill('SIGTERM');
241
+ this.recover();
242
+ return;
243
+ }
141
244
  if (!ready && f.code === 'ATTACH_BUSY') {
142
245
  this.options.observeClose?.({ layer: 'broker', initiator: 'broker.attach-busy', reason: error.code, action: 'terminate' });
143
246
  attemptClosed = true;
@@ -147,6 +250,16 @@ export class BrokerTransport {
147
250
  }
148
251
  throw error;
149
252
  }
253
+ if (f.type === 'exit' && this.supportsRecovery) {
254
+ this.stopHeartbeat();
255
+ this.ended = true;
256
+ this.attached = false;
257
+ this.lease.abort();
258
+ this.pendingInput?.ack.reject(new NeedError('AGENT_EXITED', '主机进程已退出,未重发输入', '原轮结果'));
259
+ this.changed();
260
+ this.output.close();
261
+ return;
262
+ }
150
263
  if (f.type === 'exit') {
151
264
  connected.reject(new NeedError('AGENT_EXITED', '主机 agent 已退出', '重新建立会话'));
152
265
  this.fail(new NeedError('AGENT_EXITED', '主机 agent 已退出,退出状态不代表本轮完成', '确认主机状态'));
@@ -201,11 +314,18 @@ export class BrokerTransport {
201
314
  this.attached = false;
202
315
  this.lease.abort();
203
316
  this.changed();
317
+ this.inputReady = this.options.inputProtocolVersion !== 2;
318
+ if (this.supportsRecovery && this.everReady) {
319
+ if (!ready)
320
+ connected.reject(new NeedError('BROKER_ATTACH_FAILED', '原轮暂未重新附着,继续等待原租约或连接', '原主机连接'));
321
+ else
322
+ this.recover();
323
+ return;
324
+ }
204
325
  if (!ready) {
205
326
  fatal(new NeedError('BROKER_ATTACH_FAILED', '主机会话附着失败;根因未查明', '有效的原员工 SSH/broker 连接'));
206
327
  return;
207
328
  }
208
- // A real disconnect ends this turn; the next turn starts a new agent.
209
329
  fatal(new NeedError('CONNECTION_LOST', '主机会话连接已中断,恢复后可在原会话继续。', '当前主机连接'));
210
330
  };
211
331
  child.once('error', () => detached({ layer: 'broker', initiator: 'broker.attachment-error', reason: 'BROKER_ATTACHMENT_ERROR', action: 'failure' }));
@@ -214,6 +334,8 @@ export class BrokerTransport {
214
334
  }
215
335
  write(bytes) { return this.exclusive(() => this.send(bytes)); }
216
336
  async send(bytes) {
337
+ if (this.supportsRecovery)
338
+ await this.waitInput();
217
339
  if (!this.online || !this.attachment)
218
340
  throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '连接不在线,输入没有排队或重放', '恢复连接并确认原会话状态');
219
341
  let response;
@@ -224,7 +346,7 @@ export class BrokerTransport {
224
346
  throw new NeedError('ACP_INPUT_INVALID', 'ACP 输出不是一条完整 JSON 消息', '有效的 ACP SDK 字节输出');
225
347
  }
226
348
  const selected = response.result?.outcome?.outcome === 'selected';
227
- const prompt = response.method === 'session/prompt', promptPermit = prompt ? this.promptPermit : undefined;
349
+ const prompt = response.method === 'session/prompt' || response.method === '_session/steering', promptPermit = prompt ? this.promptPermit : undefined;
228
350
  const generation = this.epoch;
229
351
  const child = this.attachment;
230
352
  const permit = this.permits.get(JSON.stringify(response.id));
@@ -261,15 +383,65 @@ export class BrokerTransport {
261
383
  if (prompt && this.promptPermit === promptPermit)
262
384
  this.promptPermit = undefined;
263
385
  const chunks = [];
386
+ let chunkBytes = bytes.byteLength;
264
387
  if (this.options.leased) {
265
- const size = Math.floor((this.options.controlMaxBytes - Buffer.byteLength(JSON.stringify({ type: 'input', data: '' }))) / 4) * 3;
388
+ const size = Math.floor((this.options.controlMaxBytes - Buffer.byteLength(JSON.stringify({ type: 'input', data: '', ...(this.options.inputProtocolVersion === 2 ? { sequence: Number.MAX_SAFE_INTEGER } : {}) }))) / 4) * 3;
266
389
  if (size < 1)
267
390
  throw new NeedError('LEASE_CAPACITY_INVALID', '主机会话容量无法承载输入', '有效controlMaxBytes');
268
- for (let offset = 0; offset < bytes.byteLength; offset += size)
269
- chunks.push(Buffer.from(JSON.stringify({ type: 'input', data: Buffer.from(bytes.subarray(offset, offset + size)).toString('base64') }) + '\n'));
391
+ chunkBytes = size;
392
+ if (this.options.inputProtocolVersion !== 2)
393
+ for (let offset = 0; offset < bytes.byteLength; offset += size)
394
+ chunks.push(Buffer.from(JSON.stringify({ type: 'input', data: Buffer.from(bytes.subarray(offset, offset + size)).toString('base64') }) + '\n'));
270
395
  }
271
396
  else
272
397
  chunks.push(Buffer.from(bytes));
398
+ if (this.options.inputProtocolVersion === 2) {
399
+ try {
400
+ for (let offset = 0; offset < bytes.byteLength; offset += chunkBytes) {
401
+ const chunk = bytes.subarray(offset, offset + chunkBytes);
402
+ await this.waitInput();
403
+ if (prompt)
404
+ currentPrompt();
405
+ const sequence = this.inputSequence + 1, ack = Promise.withResolvers();
406
+ void ack.promise.catch(() => { });
407
+ const frame = Buffer.from(JSON.stringify({ type: 'input', sequence, data: Buffer.from(chunk).toString('base64') }) + '\n');
408
+ const pending = { sequence, frame, ack };
409
+ this.pendingInput = pending;
410
+ try {
411
+ while (this.inputSequence < sequence) {
412
+ await this.waitInput();
413
+ if (this.inputSequence >= sequence)
414
+ break;
415
+ if (prompt)
416
+ currentPrompt();
417
+ if (selected && (generation !== this.epoch || !policyCurrent()))
418
+ throw new NeedError('APPROVAL_STALE', '断线后原批准不再重发,原轮结果可能未知。', '当前代次的审批许可');
419
+ const current = this.attachment, epoch = this.epoch, detached = Promise.withResolvers();
420
+ const off = this.onChange(() => { if (this.epoch !== epoch || !this.online)
421
+ detached.resolve(); });
422
+ try {
423
+ current.stdin.write(frame, error => { if (error)
424
+ current.kill('SIGTERM'); });
425
+ await Promise.race([ack.promise, detached.promise]);
426
+ }
427
+ finally {
428
+ off();
429
+ }
430
+ }
431
+ }
432
+ finally {
433
+ if (this.pendingInput === pending)
434
+ this.pendingInput = undefined;
435
+ }
436
+ }
437
+ return;
438
+ }
439
+ catch (error) {
440
+ const known = error instanceof NeedError ? error : new NeedError('INPUT_DELIVERY_UNCONFIRMED', '原输入结果未知,没有重发', '原轮输入确认');
441
+ this.fail(known);
442
+ throw known;
443
+ }
444
+ }
273
445
  for (const chunk of chunks) {
274
446
  if (!this.online || this.attachment !== child || this.epoch !== generation)
275
447
  throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '分块发送期间断线,未重放输入', '原主机连接');
@@ -125,6 +125,18 @@ export function createClaudeLocalProvider(options) {
125
125
  if (options.getConnect() !== api || options.getNetwork() !== network)
126
126
  throw failure('EMPLOYEE_CONTEXT_CHANGED');
127
127
  const underlying = base, endpoint = mcp;
128
+ let localClosing;
129
+ const modelLifetime = new AbortController();
130
+ const transientLease = () => underlying.broker?.supportsRecovery && lease.signal.aborted && ['CONNECTION_LOST', 'EMPLOYEE_ENDPOINT_UNAVAILABLE'].includes(closeCode(lease.signal.reason));
131
+ const closeLocal = (cause) => localClosing ??= Promise.resolve().then(async () => {
132
+ for (const operation of [() => endpoint.close(cause), () => row.lease.close(cause)])
133
+ try {
134
+ await operation();
135
+ }
136
+ catch {
137
+ console.warn('CLAUDE_CLEANUP_FAILED');
138
+ }
139
+ });
128
140
  const close = (detach, cause = { layer: 'runtime', initiator: detach ? 'claude.runtime-detach' : 'claude.runtime-dispose', reason: detach ? 'RUNTIME_DETACH' : 'RUNTIME_DISPOSE', action: detach ? 'detach' : 'dispose' }) => {
129
141
  // Unlink synchronously. A slow/failed cleanup must not hold the next round.
130
142
  if (entries.get(request.sessionId) === row)
@@ -138,16 +150,25 @@ export function createClaudeLocalProvider(options) {
138
150
  catch {
139
151
  console.warn('CLAUDE_CLEANUP_FAILED');
140
152
  } };
141
- await clean(() => endpoint.close({ layer: 'relay', initiator: 'claude.cleanup-mcp', reason: 'RUNTIME_CLEANUP', action: 'close' }));
142
- await clean(() => row.lease.close({ layer: 'endpoint', initiator: 'claude.cleanup-lease', reason: 'RUNTIME_CLEANUP', action: 'close' }));
153
+ await clean(() => closeLocal(cause));
143
154
  await clean(() => detach ? underlying.detach?.(cause) : underlying.dispose?.(cause));
144
155
  });
145
156
  };
146
- const executionSignal = AbortSignal.any([lease.signal, ...mcp.signal ? [mcp.signal] : []]);
147
- row.runtime = { ...underlying, closeDiagnostics, cwd: workspace.directory.path, details, connection: { ...connection }, binding: { bindingId: item.bindingId, workspaceId: workspace.workspaceId, revision: state.revision }, execution: { hostCwd: target.session.root, routing: mcp.routing, notice: NOTICE, signal: executionSignal, scope: { source: 'local', cwd: workspace.directory.path, hostCwd: target.session.root, uid: lease.target.endpoint.remoteUid, claudeAcpVersion: '0.94.0', sdkVersion: '0.3.303', unsupported: ['subagents', 'internal-direct-calls', 'binary-read', 'background-shell'] }, validate: async (signal) => { signal?.throwIfAborted(); executionSignal.throwIfAborted(); }, beginTurn: async (signal) => { signal?.throwIfAborted(); executionSignal.throwIfAborted(); if (row.closing || row.active)
157
+ const executionSignal = modelLifetime.signal;
158
+ row.runtime = { ...underlying, closeDiagnostics, cwd: workspace.directory.path, details, connection: { ...connection }, binding: { bindingId: item.bindingId, workspaceId: workspace.workspaceId, revision: state.revision }, execution: { hostCwd: target.session.root, routing: mcp.routing, notice: NOTICE, signal: executionSignal, scope: { source: 'local', cwd: workspace.directory.path, hostCwd: target.session.root, uid: lease.target.endpoint.remoteUid, claudeAcpVersion: '0.94.0', sdkVersion: '0.3.303', unsupported: ['subagents', 'internal-direct-calls', 'binary-read', 'background-shell'] }, validate: async (signal) => { signal?.throwIfAborted(); lease.signal.throwIfAborted(); executionSignal.throwIfAborted(); }, beginTurn: async (signal) => { signal?.throwIfAborted(); lease.signal.throwIfAborted(); executionSignal.throwIfAborted(); if (row.closing || row.active)
148
159
  throw failure('TURN_BUSY'); row.active = { signal, details: row.details }; }, endTurn: () => { row.active = undefined; } }, dispose: cause => close(false, cause), detach: cause => close(true, cause) };
149
160
  entries.set(request.sessionId, row);
150
- lease.signal.addEventListener('abort', () => { void close(false, { layer: 'endpoint', initiator: 'claude.lease-abort', reason: closeCode(lease?.signal.reason, 'EMPLOYEE_CONTEXT_CHANGED'), action: 'abort' }).catch(() => console.warn('CLAUDE_CLEANUP_FAILED')); }, { once: true });
161
+ const endpointAborted = () => {
162
+ const cause = { layer: 'endpoint', initiator: 'claude.lease-abort', reason: closeCode(lease?.signal.reason, 'EMPLOYEE_CONTEXT_CHANGED'), action: 'abort' };
163
+ if (transientLease()) {
164
+ void closeLocal(cause);
165
+ return;
166
+ }
167
+ modelLifetime.abort(lease?.signal.reason ?? mcp?.signal?.reason);
168
+ void close(false, cause).catch(() => console.warn('CLAUDE_CLEANUP_FAILED'));
169
+ };
170
+ lease.signal.addEventListener('abort', endpointAborted, { once: true });
171
+ mcp.signal?.addEventListener('abort', endpointAborted, { once: true });
151
172
  if (lease.signal.aborted) {
152
173
  await close(false, { layer: 'endpoint', initiator: 'claude.open-aborted', reason: closeCode(lease.signal.reason, 'EMPLOYEE_CONTEXT_CHANGED'), action: 'abort' });
153
174
  throw failure('EMPLOYEE_CONTEXT_CHANGED');
@@ -67,7 +67,21 @@ export async function openEmployeeLease(options, initialSignal) {
67
67
  catch {
68
68
  invalidate('EMPLOYEE_CONTEXT_CHANGED', initiator);
69
69
  } };
70
- offs.push(api.onConnectionState(() => changed('lease.connection-change')), api.onWorkspaceLocationState(() => changed('lease.workspace-change')), network.onState(event => { if (event?.kind === 'lost' || network.getState().phase !== 'online')
70
+ offs.push(api.onConnectionState(() => {
71
+ try {
72
+ current();
73
+ return;
74
+ }
75
+ catch { }
76
+ const currentState = api.getWorkspaceLocationState(), rows = currentState.items.filter(x => x.workspaceId === request.workspaceId);
77
+ if (options.getConnect() === api && options.getNetwork() === network && api.getConnectionState().instanceId === connection.instanceId && (currentState.phase !== 'ready' || rows.length === 1 && rows[0].bindingId === request.expectedBindingId && rows[0].source === 'local' && rows[0].status === 'selected'))
78
+ invalidate('CONNECTION_LOST', 'lease.connection-change');
79
+ else
80
+ changed('lease.connection-change');
81
+ }), api.onWorkspaceLocationState(() => { if (api.getWorkspaceLocationState().phase !== 'ready')
82
+ invalidate('CONNECTION_LOST', 'lease.workspace-offline');
83
+ else
84
+ changed('lease.workspace-change'); }), network.onState(event => { if (event?.kind === 'lost' || network.getState().phase !== 'online')
71
85
  invalidate('EMPLOYEE_ENDPOINT_UNAVAILABLE', 'lease.network-loss'); }));
72
86
  async function physicalDirectory(signal) {
73
87
  current();
@@ -111,6 +111,10 @@ export function createEmployeeProvider(get, options, agent) {
111
111
  const revoke = (reason, initiator, changes) => { lifetime.abort(reason); if (candidate)
112
112
  void candidate.dispose(reason, { layer: 'endpoint', initiator, reason: reason.code, action: 'invalidate', changes }).catch(() => { }); };
113
113
  disposers.push(api.onWorkspaceLocationState(next => {
114
+ if (next.phase !== 'ready') {
115
+ revoke(fail('CONNECTION_LOST'), 'endpoint.workspace-offline');
116
+ return;
117
+ }
114
118
  const matches = next.items.filter(item => item.workspaceId === context.workspaceId);
115
119
  if (get() !== api || next.phase !== 'ready' || next.instanceId !== connection.instanceId || next.epoch !== connection.epoch || matches.length !== 1 || matches[0].bindingId !== context.bindingId || matches[0].source !== 'local' || matches[0].status !== 'selected')
116
120
  revoke(fail('EMPLOYEE_CONTEXT_CHANGED'), 'endpoint.workspace-change', [{ field: 'workspace.binding-id', before: context.bindingId, after: matches[0]?.bindingId ?? null }, { field: 'workspace.source', before: 'local', after: matches[0]?.source ?? null }, { field: 'workspace.status', before: 'selected', after: matches[0]?.status ?? null }, { field: 'workspace.match-count', before: 1, after: matches.length }]);
@@ -175,10 +179,24 @@ export function createEmployeeProvider(get, options, agent) {
175
179
  const execution = new EmployeeExecution({ closeDiagnostics, bindingId: admitted.bindingId, acpMaxMessageBytes: request.acpMaxMessageBytes, transport: signal => createEmployeeSshTransport(ssh, signal) });
176
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 };
177
181
  runtime.employeeRemoteCloseReason = () => execution.remoteClose?.reason;
182
+ let hostFinalized = false;
183
+ const finishHost = (reason, cause) => {
184
+ if (hostFinalized)
185
+ return;
186
+ hostFinalized = true;
187
+ const detach = cause.action === 'detach' && host.broker?.supportsRecovery;
188
+ if (!detach)
189
+ host.broker?.fail(reason ?? fail('EMPLOYEE_EXEC_CLOSED'));
190
+ void Promise.resolve(detach ? host.detach?.(cause) : host.dispose?.(cause)).catch(() => console.warn('[remote-agent] 原主机资源暂未确认清理,将由主机生命周期回收'));
191
+ };
178
192
  entry = { scope, runtime, current: input, details, execution, network, ended: false, dispose: (reason, cause = { layer: 'runtime', initiator: 'provider.dispose', reason: reason?.code ?? 'EMPLOYEE_EXEC_CLOSED', action: 'dispose' }) => {
179
193
  closeDiagnostics.record({ ...cause, changes: cause.changes ?? [{ field: 'provider.ended', before: entry.ended, after: true }] });
180
- if (entry.ended)
194
+ const preserve = !!host.broker?.supportsRecovery && !!reason && ['CONNECTION_LOST', 'EMPLOYEE_EXEC_UNKNOWN'].includes(reason.code);
195
+ if (entry.ended) {
196
+ if (!preserve)
197
+ finishHost(reason, cause);
181
198
  return Promise.resolve();
199
+ }
182
200
  entry.ended = true;
183
201
  entry.reason = reason;
184
202
  if (live.get(sessionId) === entry)
@@ -186,9 +204,11 @@ export function createEmployeeProvider(get, options, agent) {
186
204
  execution.invalidate(reason ?? fail('EMPLOYEE_EXEC_CLOSED'), { layer: 'executor', initiator: 'provider.invalidate-executor', reason: reason?.code ?? 'EMPLOYEE_EXEC_CLOSED', action: 'invalidate' });
187
205
  for (const off of disposers)
188
206
  off();
189
- host.broker?.fail(reason ?? fail('EMPLOYEE_EXEC_CLOSED'));
190
- void Promise.allSettled([execution.dispose({ layer: 'executor', initiator: 'provider.cleanup-executor', reason: 'RUNTIME_CLEANUP', action: 'dispose' }), host.dispose?.({ layer: 'broker', initiator: 'provider.cleanup-host', reason: 'RUNTIME_CLEANUP', action: 'dispose' })]).then(results => { if (results.some(result => result.status === 'rejected'))
191
- console.warn('[remote-agent] 员工执行通道的旧资源将由主机回收'); });
207
+ // Keep the model's original prompt and SDK alive through transport loss.
208
+ // The old employee execution stays UNKNOWN, never swapped for a fresh process.
209
+ if (!preserve)
210
+ finishHost(reason, cause);
211
+ void execution.dispose({ layer: 'executor', initiator: 'provider.cleanup-executor', reason: 'RUNTIME_CLEANUP', action: 'dispose' }).catch(() => console.warn('[remote-agent] 员工执行端旧资源将由主机回收'));
192
212
  return Promise.resolve();
193
213
  } };
194
214
  candidate = entry;
@@ -209,7 +229,7 @@ export function createEmployeeProvider(get, options, agent) {
209
229
  runtime.dispose = cause => entry.dispose(undefined, cause ?? { layer: 'runtime', initiator: 'runtime.dispose', reason: 'RUNTIME_DISPOSE', action: 'dispose' });
210
230
  runtime.detach = cause => entry.dispose(undefined, cause ?? { layer: 'runtime', initiator: 'runtime.detach', reason: 'RUNTIME_DETACH', action: 'detach' });
211
231
  if (host.broker)
212
- disposers.push(host.broker.onChange(() => { if (!host.broker.online)
232
+ disposers.push(host.broker.onChange(() => { if (!host.broker.online && !host.broker.recovering)
213
233
  revoke(fail('EMPLOYEE_EXEC_UNKNOWN'), 'endpoint.broker-offline'); }));
214
234
  live.set(sessionId, entry);
215
235
  return runtime;
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { type SteeringReceipts } from './live-steering.ts';
1
2
  import type { Context } from '@deepseek-ai/cordis';
2
3
  import Schema from '@deepseek-ai/schemastery';
3
4
  import { LlmAdapter, type GenerateOptions, type StreamChunk, type LlmResolvedModelInfo } from '@deepseek-ai/dsh-llm';
@@ -57,9 +58,11 @@ export declare class CodexRemoteAdapter extends LlmAdapter {
57
58
  private readonly directory?;
58
59
  private readonly preflightDiagnostics?;
59
60
  private readonly permissions?;
61
+ private readonly steeringReceipts?;
60
62
  private bridgeLoop;
61
63
  private config;
62
64
  private sessions;
65
+ private injectedInputs;
63
66
  private turns;
64
67
  private lifetime;
65
68
  private shuttingDown;
@@ -67,11 +70,13 @@ export declare class CodexRemoteAdapter extends LlmAdapter {
67
70
  private modelPresentation;
68
71
  private employeeNoticeSessions;
69
72
  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);
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);
71
74
  providerInfo(provider: string): {
72
75
  id: string;
73
76
  name: string;
74
77
  };
78
+ canSteer(sessionId: string): boolean;
79
+ steer(sessionId: string, message: import('@deepseek-ai/dsh-llm').UserMessage, isCurrent?: () => boolean): Promise<void>;
75
80
  private catalog;
76
81
  listModels(provider: string): Promise<(LlmResolvedModelInfo & {
77
82
  catalog: HostModel;
@@ -101,7 +106,7 @@ export declare class CodexRemoteAdapter extends LlmAdapter {
101
106
  /** One official registration owns both routes, preserving opaque replay ownership. */
102
107
  export declare class RemoteAgentsAdapter extends LlmAdapter {
103
108
  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);
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);
105
110
  private adapter;
106
111
  providerInfo(provider: string): {
107
112
  id: string;
@@ -124,6 +129,8 @@ export declare class RemoteAgentsAdapter extends LlmAdapter {
124
129
  jitterRatio: number;
125
130
  };
126
131
  stream(options: GenerateOptions): AsyncGenerator<StreamChunk, any, any>;
132
+ canSteer(provider: string, sessionId: string): boolean;
133
+ steer(provider: string, sessionId: string, message: import('@deepseek-ai/dsh-llm').UserMessage, isCurrent?: () => boolean): Promise<void>;
127
134
  completeDshTurn(sessionId: string, messages: GenerateOptions['messages']): Promise<void>;
128
135
  disposeSession(sessionId: string): Promise<void>;
129
136
  detachSession(sessionId: string): Promise<void>;
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { createSteeringReceipts, installLiveSteering, steeringMessageDigest } from "./live-steering.js";
1
2
  import { ToolBridgeLoop } from "./toolbridge-loop.js";
2
3
  import { openToolBridgeMcp, TOOLBRIDGE_NOTICE } from "./toolbridge.js";
3
4
  import { connectNeedMessage } from "./connect-need.js";
@@ -7,7 +8,7 @@ import { SessionId } from '@deepseek-ai/dsh-session';
7
8
  import { createAssistantMessage } from '@deepseek-ai/dsh-llm';
8
9
  import Schema from '@deepseek-ai/schemastery';
9
10
  import { LlmAdapter, LlmError } from '@deepseek-ai/dsh-llm';
10
- import { createHash } from 'node:crypto';
11
+ import { createHash, randomUUID } from 'node:crypto';
11
12
  import * as unstable from '@agentclientprotocol/sdk/unstable';
12
13
  import * as acp from '@agentclientprotocol/sdk';
13
14
  import { AcpSession } from "./acp.js";
@@ -94,9 +95,11 @@ export class CodexRemoteAdapter extends LlmAdapter {
94
95
  directory;
95
96
  preflightDiagnostics;
96
97
  permissions;
98
+ steeringReceipts;
97
99
  bridgeLoop;
98
100
  config;
99
101
  sessions = new Map();
102
+ injectedInputs = new Map();
100
103
  turns = new Map();
101
104
  lifetime = new AbortController();
102
105
  shuttingDown = false;
@@ -104,7 +107,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
104
107
  modelPresentation = new ModelPresentation();
105
108
  employeeNoticeSessions = new Set();
106
109
  pendingEmployeeNotices = new Set();
107
- constructor(config, resolveRuntime, approve, providerName = () => CODEX_AGENT.name.zh, agent = CODEX_AGENT, readImage, reportLoginFailure, directory, preflightDiagnostics, permissions, bridgeStopped) {
110
+ constructor(config, resolveRuntime, approve, providerName = () => CODEX_AGENT.name.zh, agent = CODEX_AGENT, readImage, reportLoginFailure, directory, preflightDiagnostics, permissions, bridgeStopped, steeringReceipts) {
108
111
  super();
109
112
  this.resolveRuntime = resolveRuntime;
110
113
  this.approve = approve;
@@ -115,10 +118,81 @@ export class CodexRemoteAdapter extends LlmAdapter {
115
118
  this.directory = directory;
116
119
  this.preflightDiagnostics = preflightDiagnostics;
117
120
  this.permissions = permissions;
118
- this.bridgeLoop = new ToolBridgeLoop(readImage, bridgeStopped);
121
+ this.steeringReceipts = steeringReceipts;
122
+ this.bridgeLoop = new ToolBridgeLoop(readImage, bridgeStopped, (id, message) => this.injectedInputs.get(id)?.get(message.id) === steeringMessageDigest(message));
119
123
  this.config = typeof config === 'function' ? config : () => config;
120
124
  }
121
125
  providerInfo(provider) { return { id: provider, name: this.providerName() }; }
126
+ canSteer(sessionId) { const live = this.sessions.get(sessionId); return !!this.steeringReceipts && !!live?.acceptingSteer && live.session.canSteer; }
127
+ steer(sessionId, message, isCurrent) {
128
+ const live = this.sessions.get(sessionId);
129
+ if (!live || !this.canSteer(sessionId))
130
+ return Promise.resolve();
131
+ const digest = steeringMessageDigest(message), valid = () => !isCurrent || isCurrent();
132
+ if (live.steerIds.get(message.id) === digest)
133
+ return live.steerTail;
134
+ live.steerIds.set(message.id, digest);
135
+ const work = live.steerTail.catch(() => { }).then(async () => {
136
+ if (!live.acceptingSteer || this.sessions.get(sessionId) !== live || !live.session.canSteer || !valid())
137
+ return;
138
+ const store = this.steeringReceipts, provider = live.options.provider, nativeSessionId = live.session.id;
139
+ const old = (await store.read(sessionId, provider, [message.id])).get(message.id);
140
+ if (!valid())
141
+ return;
142
+ if (old && old.messageSha256 !== digest && old.outcome !== 'deferred') {
143
+ live.notice?.('这条消息的旧版本已发送或送达未确认,不能撤回;编辑后的内容保留在队列,按下一步骤交付。');
144
+ return;
145
+ }
146
+ if (old && old.outcome !== 'deferred') {
147
+ if (old.outcome !== 'injected' || old.nativeSessionId !== nativeSessionId) {
148
+ const error = new NeedError('INPUT_DELIVERY_UNCONFIRMED', '这条中途消息已有未确认的送达记录,没有再次发送。', '原轮中途消息回执');
149
+ live.steerFailure ??= error;
150
+ throw error;
151
+ }
152
+ (this.injectedInputs.get(sessionId) ?? this.injectedInputs.set(sessionId, new Map()).get(sessionId)).set(message.id, digest);
153
+ return;
154
+ }
155
+ const prepared = await prepareInput({ ...live.options, messages: [message] }, this.readImage);
156
+ if (!valid())
157
+ return;
158
+ const params = { sessionId: nativeSessionId, prompt: prepared.prompt, _meta: { steering: { idleBehavior: 'promptRequired' } } };
159
+ if (Buffer.byteLength(JSON.stringify({ jsonrpc: '2.0', id: 'steering', method: '_session/steering', params })) + 1 > live.maxBytes)
160
+ throw new NeedError('ACP_MESSAGE_TOO_LARGE', '中途消息超过已设置的会话消息容量,仍在官方队列中,未发送。', '管理员调整acpMaxMessageBytes');
161
+ const receipt = { sessionId, provider, messageId: message.id, nativeSessionId, turnId: live.turnId, messageSha256: digest, outcome: 'prepared' };
162
+ await store.put(receipt);
163
+ const before = live.session.steerDispatchCount;
164
+ if (!valid()) {
165
+ await store.put({ ...receipt, outcome: 'deferred' });
166
+ return;
167
+ }
168
+ try {
169
+ const outcome = await live.session.steer(prepared.prompt, live.options.signal, valid, live.maxBytes);
170
+ await store.put({ ...receipt, outcome: outcome === 'injected' ? 'injected' : 'deferred' });
171
+ if (outcome === 'injected')
172
+ (this.injectedInputs.get(sessionId) ?? this.injectedInputs.set(sessionId, new Map()).get(sessionId)).set(message.id, digest);
173
+ }
174
+ catch (error) {
175
+ const dispatched = live.session.steerDispatchCount !== before;
176
+ await store.put({ ...receipt, outcome: dispatched ? 'unknown' : 'deferred' });
177
+ if (dispatched) {
178
+ const failure = new NeedError('INPUT_DELIVERY_UNCONFIRMED', '中途消息可能已交给原轮,送达结果未知,没有自动重复发送。', '原轮中途消息回执');
179
+ live.steerFailure ??= failure;
180
+ throw failure;
181
+ }
182
+ live.runtime.details?.record({ kind: 'need', severity: 'warning', code: error instanceof NeedError ? error.code : 'INPUT_DELIVERY_UNCONFIRMED', summary: '中途消息未发出,仍由官方队列后续处理。' });
183
+ }
184
+ });
185
+ const observed = work.catch(error => {
186
+ live.runtime.details?.record({ kind: 'need', severity: 'warning', code: error instanceof NeedError ? error.code : 'INPUT_DELIVERY_UNCONFIRMED', summary: '中途消息未确认,原消息没有丢弃或自动重发。' });
187
+ // Preserve uncertainty for this round, but known pre-dispatch failures do
188
+ // not poison later safe steering requests or unrelated future turns.
189
+ if (live.steerFailure === error)
190
+ throw error;
191
+ });
192
+ live.steerTail = observed;
193
+ void observed.catch(() => { });
194
+ return observed;
195
+ }
122
196
  catalog(signal) { if (!this.directory)
123
197
  throw new LlmError('无法获取模型列表:缺少可信主机目录能力', 'MODEL_CATALOG_UNAVAILABLE'); return this.directory.read(this.agent, signal); }
124
198
  async listModels(provider) { const catalog = await this.catalog(this.lifetime.signal); try {
@@ -175,10 +249,12 @@ export class CodexRemoteAdapter extends LlmAdapter {
175
249
  await this.cleanupRuntime(current.runtime);
176
250
  }
177
251
  async detachSession(sessionId) {
178
- await this.bridgeLoop.cancel(sessionId);
179
252
  const current = this.sessions.get(sessionId), turn = this.turns.get(sessionId);
180
253
  if (!current && !turn)
181
254
  return;
255
+ if (current?.runtime.broker?.supportsRecovery)
256
+ current.session.close({ layer: 'adapter', initiator: 'adapter.detach-sdk', reason: 'SESSION_DETACHED', action: 'detach' });
257
+ await this.bridgeLoop.cancel(sessionId);
182
258
  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
259
  this.detached.add(sessionId);
184
260
  if (current) {
@@ -198,11 +274,11 @@ export class CodexRemoteAdapter extends LlmAdapter {
198
274
  for (const live of this.sessions.values())
199
275
  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
276
  this.shuttingDown = true;
201
- await this.bridgeLoop.dispose();
202
277
  this.modelPresentation.clear();
203
278
  this.employeeNoticeSessions.clear();
204
279
  this.pendingEmployeeNotices.clear();
205
280
  const results = await Promise.allSettled([...new Set([...this.sessions.keys(), ...this.turns.keys()])].map(id => this.detachSession(id)));
281
+ await this.bridgeLoop.dispose();
206
282
  this.lifetime.abort();
207
283
  const failure = results.find(result => result.status === 'rejected');
208
284
  if (failure?.status === 'rejected')
@@ -320,8 +396,21 @@ export class CodexRemoteAdapter extends LlmAdapter {
320
396
  request.userMessageIds = request.userInputIds;
321
397
  earlyStage = 'source-context';
322
398
  await this.resolveRuntime.preflight?.(request);
399
+ const receipts = this.steeringReceipts && options.sessionId ? await this.steeringReceipts.read(options.sessionId, options.provider, humanIds) : new Map();
400
+ 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
+ for (const receipt of matching)
402
+ if (receipt.outcome === 'prepared' || receipt.outcome === 'unknown')
403
+ throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '中途消息送达结果未知,没有在下一步骤重复提交;请核对原轮状态。', '原生注入回执');
404
+ const injected = new Set(matching.filter(r => r.outcome === 'injected').map(r => { if (!previous || r.nativeSessionId !== previous.sessionId)
405
+ throw new NeedError('SESSION_CONTEXT_MISMATCH', '中途消息属于另一原生轮,未重复提交。', '原会话的注入回执与检查点'); return r.messageId; }));
406
+ if (humanIds.length && humanIds.every(id => injected.has(id))) {
407
+ yield { type: 'finish', reason: { kind: 'stop' }, replayState: { response: previous } };
408
+ succeeded = true;
409
+ return;
410
+ }
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)) };
323
412
  earlyStage = 'input-prepare';
324
- let input = await prepareInput(options, this.readImage);
413
+ let input = await prepareInput(projected, this.readImage);
325
414
  const contextSha256 = createHash('sha256').update(input.systemPrompt ?? '').digest('hex');
326
415
  request.contextSha256 = contextSha256;
327
416
  const codex = this.agent.loginProvider === 'codex';
@@ -349,7 +438,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
349
438
  }
350
439
  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))
351
440
  throw new NeedError('SESSION_CONTEXT_MISMATCH', '原会话的员工主机或工作区已改变,请新建会话', '原会话的可信目标和工作区');
352
- input = await prepareContinuation({ ...options, messages: options.messages.slice((checkpoint?.index ?? -1) + 1) }, input, this.readImage, { maxBytes: config.acpMaxMessageBytes, host: runtime.hostWorkspace });
441
+ input = await prepareContinuation({ ...options, messages: projected.messages.slice((checkpoint?.index ?? -1) + 1) }, input, this.readImage, { maxBytes: config.acpMaxMessageBytes, host: runtime.hostWorkspace });
353
442
  if (runtime.hostWorkspace && mode === 'session' && Buffer.byteLength(JSON.stringify({ prompt: input.prompt, systemPrompt: input.systemPrompt }), 'utf8') > config.acpMaxMessageBytes)
354
443
  throw new NeedError('ACP_MESSAGE_TOO_LARGE', '本轮输入超过已设置的会话消息容量,未截断或发送', '管理员调整acpMaxMessageBytes');
355
444
  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 });
@@ -438,7 +527,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
438
527
  } }, onResponse: response => push(mapper.acpResponse(response)), onDetail: detail => details.record(detail) };
439
528
  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 });
440
529
  session = new AcpSession(transport, hooks);
441
- live = { session, runtime, configuration, contextSha256, usageSnapshot: mapper.usageSnapshot };
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)) };
442
531
  if (key)
443
532
  this.sessions.set(key, live);
444
533
  promptBaseline = session.promptDispatchCount;
@@ -540,8 +629,13 @@ export class CodexRemoteAdapter extends LlmAdapter {
540
629
  bridge.replayState = { response: makePointer(session.id) };
541
630
  bridge?.begin(modelSignal);
542
631
  id = session.id;
632
+ let promptFailed = false;
543
633
  try {
544
634
  const result = await dispatchPrompt();
635
+ live.acceptingSteer = false;
636
+ await live.steerTail;
637
+ if (live.steerFailure)
638
+ throw live.steerFailure;
545
639
  if (bridge?.unsettled)
546
640
  bridge.abandon('HOST_PROMPT_ENDED_WITH_PENDING_CALL');
547
641
  permissionOff?.();
@@ -549,7 +643,22 @@ export class CodexRemoteAdapter extends LlmAdapter {
549
643
  await permissionTail;
550
644
  return result;
551
645
  }
646
+ catch (error) {
647
+ promptFailed = true;
648
+ throw error;
649
+ }
552
650
  finally {
651
+ live.acceptingSteer = false;
652
+ try {
653
+ await live.steerTail;
654
+ if (live.steerFailure)
655
+ throw live.steerFailure;
656
+ }
657
+ catch (error) {
658
+ if (!promptFailed)
659
+ throw error;
660
+ details.record({ kind: 'need', severity: 'warning', code: 'INPUT_DELIVERY_UNCONFIRMED', summary: '原轮失败且有中途消息未获送达确认,没有重发。' });
661
+ }
553
662
  permissionOff?.();
554
663
  permissionOff = undefined;
555
664
  bridge?.end();
@@ -625,16 +734,17 @@ export class CodexRemoteAdapter extends LlmAdapter {
625
734
  }
626
735
  if (key && this.turns.get(key) === turn)
627
736
  this.turns.delete(key);
628
- if (key)
737
+ if (key) {
629
738
  this.detached.delete(key);
739
+ }
630
740
  }
631
741
  }
632
742
  }
633
743
  /** One official registration owns both routes, preserving opaque replay ownership. */
634
744
  export class RemoteAgentsAdapter extends LlmAdapter {
635
745
  adapters = new Map();
636
- constructor(config, makeRuntime, approve, nameFor, readImage, reportLoginFailure, directory, preflightDiagnostics, permissions, bridgeStopped) { super(); for (const agent of AGENTS)
637
- this.adapters.set(agent.id, new CodexRemoteAdapter(config, makeRuntime(agent), approve, () => nameFor(agent), agent, readImage, reportLoginFailure, directory, preflightDiagnostics, permissions, bridgeStopped)); }
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)); }
638
748
  adapter(provider) { const adapter = this.adapters.get(provider); if (!adapter)
639
749
  throw new LlmError('远程模型未注册', 'PROVIDER_NOT_FOUND'); return adapter; }
640
750
  providerInfo(provider) { return this.adapter(provider).providerInfo(provider); }
@@ -651,6 +761,8 @@ export class RemoteAgentsAdapter extends LlmAdapter {
651
761
  }
652
762
  return this.adapter(options.provider).stream(options);
653
763
  }
764
+ canSteer(provider, sessionId) { return this.adapters.get(provider)?.canSteer(sessionId) ?? false; }
765
+ steer(provider, sessionId, message, isCurrent) { return this.adapter(provider).steer(sessionId, message, isCurrent); }
654
766
  async completeDshTurn(sessionId, messages) { await Promise.all([...this.adapters.values()].map(adapter => adapter.completeDshTurn(sessionId, messages))); }
655
767
  async disposeSession(sessionId) { await Promise.all([...this.adapters.values()].map(adapter => adapter.disposeSession(sessionId))); }
656
768
  async detachSession(sessionId) { await Promise.all([...this.adapters.values()].map(adapter => adapter.detachSession(sessionId))); }
@@ -698,6 +810,7 @@ export function apply(ctx, live) {
698
810
  // Public Loader Entry.options.id; optional when mounted without Loader.
699
811
  const actualSettingsNamespace = ctx.fiber.entry?.options.id;
700
812
  const modelDirectory = new ModelCatalog(get, () => config().acpMaxMessageBytes, undefined, (provider, error) => managerForProfile().recordCatalogFailure(provider, error));
813
+ const steeringReceipts = createSteeringReceipts(ctx);
701
814
  const adapter = new RemoteAgentsAdapter(config, agent => {
702
815
  const details = async (request, api, connection, target) => {
703
816
  return managerForProfile().open({ sessionId: request.sessionId, provider: agent.loginProvider, identity: `${target.username}@${target.host}:${target.port}`, connection });
@@ -777,7 +890,8 @@ export function apply(ctx, live) {
777
890
  if (turn !== null && step !== null)
778
891
  agent.session.append('assistant/message', { turn, step, message: createAssistantMessage({ content: [{ type: 'text', text: notice }], source: { provider: 'ai-workbench-toolbridge', model: 'notice' } }), stream: [] }, { surfaceOp: 'append' });
779
892
  agent.cancel({ kind: 'hook', reason: 'DSH_BRIDGE_CALL_ABANDONED_BY_HOST' }, { keepInbox: true });
780
- });
893
+ }, steeringReceipts);
894
+ installLiveSteering(ctx, adapter);
781
895
  ctx.on('session/event', (session, event) => { if (event.type === 'turn/end') {
782
896
  const operation = event.data.reason.kind === 'completed' ? adapter.completeDshTurn(session.id, session.deriveMessages()) : adapter.disposeSession(session.id);
783
897
  void operation.catch(() => ctx.logger('remote-agent').warn('TOOLBRIDGE_RESULT_DELIVERY_UNCONFIRMED'));
@@ -0,0 +1,46 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import type { UserMessage } from '@deepseek-ai/dsh-llm';
3
+ import { z } from 'zod';
4
+ declare const receiptSchema: z.ZodObject<{
5
+ sessionId: z.ZodString;
6
+ provider: z.ZodString;
7
+ messageId: z.ZodString;
8
+ nativeSessionId: z.ZodString;
9
+ turnId: z.ZodString;
10
+ messageSha256: z.ZodString;
11
+ outcome: z.ZodEnum<{
12
+ unknown: "unknown";
13
+ injected: "injected";
14
+ prepared: "prepared";
15
+ deferred: "deferred";
16
+ }>;
17
+ }, z.core.$strict>;
18
+ export type SteeringReceipt = z.infer<typeof receiptSchema>;
19
+ export declare const steeringMessageDigest: (message: UserMessage) => string;
20
+ export interface SteeringReceipts {
21
+ read(sessionId: string, provider: string, ids: readonly string[]): Promise<ReadonlyMap<string, SteeringReceipt>>;
22
+ put(receipt: SteeringReceipt): Promise<void>;
23
+ }
24
+ export declare const liveSteeringSpec: {
25
+ name: string;
26
+ version: number;
27
+ tables: {
28
+ receipts: import("@deepseek-ai/dsh-storage-domain").DomainTableSpec<string, {
29
+ sessionId: string;
30
+ provider: string;
31
+ messageId: string;
32
+ nativeSessionId: string;
33
+ turnId: string;
34
+ messageSha256: string;
35
+ outcome: "unknown" | "injected" | "prepared" | "deferred";
36
+ }>;
37
+ };
38
+ };
39
+ export declare function createSteeringReceipts(ctx: Context): SteeringReceipts;
40
+ export interface LiveSteeringTarget {
41
+ canSteer(provider: string, sessionId: string): boolean;
42
+ steer(provider: string, sessionId: string, message: UserMessage, isCurrent?: () => boolean): Promise<unknown>;
43
+ }
44
+ /** Observe the public inbox; the official driver still claims and records every input. */
45
+ export declare function installLiveSteering(ctx: Context, target: LiveSteeringTarget): void;
46
+ export {};
@@ -0,0 +1,45 @@
1
+ import { 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 receiptSchema = z.object({ sessionId: z.string().min(1), provider: z.string().min(1), messageId: z.string().min(1), nativeSessionId: z.string().min(1), turnId: z.string().min(1), messageSha256: z.string().regex(/^[a-f0-9]{64}$/), outcome: z.enum(['prepared', 'injected', 'deferred', 'unknown']) }).strict();
6
+ export const steeringMessageDigest = (message) => createHash('sha256').update(JSON.stringify({ source: message.source, content: message.content })).digest('hex');
7
+ export const liveSteeringSpec = defineDomain({ name: 'ai_workbench_live_steering', version: 1, tables: { receipts: domainTable(receiptSchema) } });
8
+ const key = (sessionId, provider, messageId) => JSON.stringify([sessionId, provider, messageId]);
9
+ const storageFailure = () => new NeedError('INPUT_DELIVERY_UNCONFIRMED', '中途消息的送达登记未能确认;没有自动重复发送,请核对原轮状态。', '官方storageDomain中途消息回执');
10
+ export function createSteeringReceipts(ctx) {
11
+ let domain;
12
+ const open = () => { if (!domain) {
13
+ const facility = ctx.get('storageDomain');
14
+ if (!facility)
15
+ throw storageFailure();
16
+ domain = facility.open(liveSteeringSpec).catch(error => { domain = undefined; throw error; });
17
+ } return domain; };
18
+ ctx.effect(() => async () => { if (domain)
19
+ await (await domain).close(); });
20
+ return {
21
+ async read(sessionId, provider, ids) { try {
22
+ const table = (await open()).table('receipts');
23
+ return new Map(ids.flatMap(id => { const row = table.get(key(sessionId, provider, id)); return row ? [[id, receiptSchema.parse(row)]] : []; }));
24
+ }
25
+ catch (error) {
26
+ throw Object.assign(storageFailure(), { cause: error });
27
+ } },
28
+ async put(receipt) { try {
29
+ await (await open()).table('receipts').put(key(receipt.sessionId, receipt.provider, receipt.messageId), receiptSchema.parse(receipt));
30
+ }
31
+ catch (error) {
32
+ throw Object.assign(storageFailure(), { cause: error });
33
+ } },
34
+ };
35
+ }
36
+ /** Observe the public inbox; the official driver still claims and records every input. */
37
+ export function installLiveSteering(ctx, target) {
38
+ ctx.on('agent/inbox/inserted', ({ agent, message }) => {
39
+ const provider = agent.options.provider, id = agent.session.id;
40
+ if (typeof provider !== 'string' || message.source.kind !== 'user' || !agent.inbox.nextStep.some(item => item.id === message.id) || !target.canSteer(provider, id))
41
+ return;
42
+ const digest = steeringMessageDigest(message);
43
+ void target.steer(provider, id, message, () => agent.options.provider === provider && agent.inbox.nextStep.some(item => item.id === message.id && steeringMessageDigest(item) === digest)).catch(() => ctx.logger('remote-agent').warn('INPUT_DELIVERY_UNCONFIRMED:中途消息回执未确认,没有自动重复发送'));
44
+ });
45
+ }
@@ -4,7 +4,8 @@ import { NeedError } from "./remote.js";
4
4
  export function isolateRpcIds(stream, onWrite) {
5
5
  const prefix = randomUUID() + '/';
6
6
  const pending = new Map();
7
- const readable = stream.readable.pipeThrough(new TransformStream({ transform(message, controller) {
7
+ let incoming;
8
+ const readable = stream.readable.pipeThrough(new TransformStream({ start(controller) { incoming = controller; }, transform(message, controller) {
8
9
  const raw = message;
9
10
  if (!raw.method && Object.hasOwn(raw, 'id')) {
10
11
  if (typeof raw.id !== 'string' || !pending.has(raw.id))
@@ -28,9 +29,22 @@ export function isolateRpcIds(stream, onWrite) {
28
29
  const params = raw.params;
29
30
  outgoing = { ...raw, params: { ...params, requestId: prefix + JSON.stringify(params.requestId) } };
30
31
  }
31
- const writer = stream.writable.getWriter();
32
+ // A known pre-dispatch steering rejection belongs to one request. Throwing
33
+ // from WritableStream.write would permanently poison the shared SDK channel.
34
+ // Deliver an explicit local RPC error on the public Stream instead. No native
35
+ // write or dispatch count occurs, and the namespaced pending entry is removed.
32
36
  try {
33
37
  onWrite?.(outgoing);
38
+ }
39
+ catch (error) {
40
+ if (raw.method !== '_session/steering' || !Object.hasOwn(raw, 'id') || !(error instanceof NeedError) || !['ACP_MESSAGE_TOO_LARGE', 'PERMISSION_POLICY_CHANGED'].includes(error.code))
41
+ throw error;
42
+ pending.delete(String(outgoing.id));
43
+ incoming.enqueue({ jsonrpc: '2.0', id: raw.id, error: { code: -32603, message: 'ACP_LOCAL_REQUEST_REJECTED', data: { localDispatchCode: error.code } } });
44
+ return;
45
+ }
46
+ const writer = stream.writable.getWriter();
47
+ try {
34
48
  await writer.write(outgoing);
35
49
  }
36
50
  finally {
@@ -1,4 +1,4 @@
1
- import { type GenerateOptions, type StreamChunk } from '@deepseek-ai/dsh-llm';
1
+ import { type GenerateOptions, type StreamChunk, type UserMessage } from '@deepseek-ai/dsh-llm';
2
2
  import { ToolBridge } from './toolbridge.ts';
3
3
  import type { ImageReader } from './input.ts';
4
4
  type Producer = (options: GenerateOptions, bridge: ToolBridge) => AsyncGenerator<StreamChunk>;
@@ -6,9 +6,10 @@ type Producer = (options: GenerateOptions, bridge: ToolBridge) => AsyncGenerator
6
6
  export declare class ToolBridgeLoop {
7
7
  private readImage?;
8
8
  private stopped?;
9
+ private isInjected?;
9
10
  private runs;
10
11
  private concluding;
11
- constructor(readImage?: ImageReader | undefined, stopped?: ((sessionId: string, notice: string) => void) | undefined);
12
+ constructor(readImage?: ImageReader | undefined, stopped?: ((sessionId: string, notice: string) => void) | undefined, isInjected?: ((sessionId: string, message: UserMessage) => boolean) | undefined);
12
13
  private launch;
13
14
  conclude(id: string, messages: GenerateOptions['messages']): Promise<void>;
14
15
  active(id: string): boolean;
@@ -44,11 +44,13 @@ class Projection {
44
44
  export class ToolBridgeLoop {
45
45
  readImage;
46
46
  stopped;
47
+ isInjected;
47
48
  runs = new Map();
48
49
  concluding = new Map();
49
- constructor(readImage, stopped) {
50
+ constructor(readImage, stopped, isInjected) {
50
51
  this.readImage = readImage;
51
52
  this.stopped = stopped;
53
+ this.isInjected = isInjected;
52
54
  }
53
55
  launch(options, producer) {
54
56
  const controller = new AbortController(), bridge = new ToolBridge(options, this.readImage);
@@ -181,7 +183,7 @@ export class ToolBridgeLoop {
181
183
  throw new NeedError('ABORTED', '本轮已取消,工具结果没有重放。', '确认主机取消状态');
182
184
  if (run.latest !== options) {
183
185
  for (const m of options.messages)
184
- if (m.role === 'user' && 'source' in m && m.source?.kind === 'user' && 'id' in m && typeof m.id === 'string' && !run.seen.has(m.id)) {
186
+ if (m.role === 'user' && 'source' in m && m.source?.kind === 'user' && 'id' in m && typeof m.id === 'string' && !run.seen.has(m.id) && !this.isInjected?.(key, m)) {
185
187
  run.seen.add(m.id);
186
188
  run.deferred.push(m);
187
189
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-workbench/remote-agent",
3
- "version": "0.9.0-toolbridge.13",
3
+ "version": "0.9.0-toolbridge.14",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",