@ai-workbench/remote-agent 0.9.0-toolbridge.12 → 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.12 · 插件 → 添加插件
1
+ # AI Workbench 远程助手 · @ai-workbench/remote-agent@0.9.0-toolbridge.14 · 插件 → 添加插件
2
2
 
3
3
  ## 含工具桥预发布线
4
4
 
5
- 本包为 `0.9.0-toolbridge.12`,从 `v0.9.0-toolbridge.11` 派生,使用 `host-toolbridge` 发布渠道。员工安装由连接组件提供的「AI 写作工作台(含工具桥)」总包 `@ai-workbench/workbench-toolbridge@0.1.9`,与不含工具桥的版本二选一。
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
 
@@ -16,7 +21,11 @@ Codex 需要 S 后续安装的独立受保护命令 `/usr/local/aw-host/bin/code
16
21
 
17
22
  需要远程主机连接组件 0.7.37 或更新的 0.7.x、联网助手 0.4.9,以及支持公开会话归属接口的主机组件 S0.4.26。主机来源保存于官方 storage.domain 的会话元数据表,每轮仅由连接组件检查一次主机目录,不检查本机占位目录。
18
23
 
19
- Claude 本机 Bash 会单独消费员工桥代理的控制诊断,不把它交给模型当作命令输出;真实传输中断仍提示结果未知。命令自身的标准输出、标准错误与退出码照常返回。
24
+ Claude 员工MCP的stdio通道保持在当前原生客户端上。底层员工SSH/Unix流断开时,在途工具只返回结果未知,不重放;连接恢复后下一次新工具调用串行重新连接并初始化。同一DSH会话无需新建;若连接/绑定已撤销或DSH桥工具在途结束本轮,网络恢复后在原会话发新消息,沿原生编号续接。只使用原已核验的设备/账户/绑定,不跨代偷接。
25
+
26
+ DSH技能工具仅使用DSH公布的目录,主机原生技能按各自原生指令加载;工具描述标明目录快照与返回的资源基址。
27
+
28
+ Claude 本机 Bash 会单独消费员工桥代理的控制诊断,不把它交给模型当作命令输出;真实传输中断仍提示结果未知。命令自身的标准输出、标准错误与退出码照常返回。非UTF-8流不拒绝,按原始字节base64返回并增加对应stdoutEncoding/stderrEncoding标记;有效UTF-8格式不变。没有新增原始字节上限,编码后的消息沿既有512MB容量核验。
20
29
 
21
30
  模型列表读取会随连接状态或连接代际变化取消,连接恢复时通过官方机制刷新。目录失败原因写入当前 profile 的 `ai-workbench-remote-agent/logs/model-catalog.jsonl`(脱敏);未增加单次读取时限或重试。
22
31
 
@@ -56,7 +65,7 @@ Codex 员工端只使用随包提供的原生组件,通道等待本次组件
56
65
 
57
66
  ## 技术详情与交付
58
67
 
59
- 技术详情只写官方 profile 下本地私有日志,并由既有技术详情界面展开显示。写入失败不覆盖原始错误、不等待远端投递回执。每个运行环境只记录首次关闭原因;首先观察到的原因不自动等同跨层根因。
68
+ 技术详情只写官方 profile 下本地私有日志,并由既有技术详情界面展开显示。写入失败不覆盖原始错误、不等待远端投递回执。连接与独立工具操作分别保留首次关闭原因,普通工具退出不再占用连接首因;首先观察到的原因不自动等同跨层根因。
60
69
 
61
70
  工程验证和独立审查见 `docs/evidence/2026-10-25-X-host-source-v2/`;AUTH profile 夹具补齐与最终 main 全套复验见其中的 `auth-profile-return.md`。固定包摘要及真实设备验收状态以项目 X 回执为准。插件不修改 DSH 核心,不添加启动器或自定义 profile。
62
71
 
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');
@@ -31,7 +31,7 @@ export declare class CloseDiagnostics {
31
31
  get first(): Readonly<Record<string, unknown>> | undefined;
32
32
  bind(sink: (detail: DetailObservation) => void): void;
33
33
  capture(): CloseObserver;
34
- child(sink?: (detail: DetailObservation) => void): CloseDiagnostics;
34
+ child(sink?: (detail: DetailObservation) => void, independent?: boolean): CloseDiagnostics;
35
35
  record(cause: CloseCause): void;
36
36
  private recordUsing;
37
37
  }
@@ -13,7 +13,7 @@ export class CloseDiagnostics {
13
13
  get first() { return this.state.first; }
14
14
  bind(sink) { this.sink = sink; }
15
15
  capture() { const sink = this.sink; return cause => this.recordUsing(sink, cause); }
16
- child(sink = this.sink) { return new CloseDiagnostics(sink, this.state); }
16
+ child(sink = this.sink, independent = false) { return new CloseDiagnostics(sink, independent ? {} : this.state); }
17
17
  record(cause) { this.recordUsing(this.sink, cause); }
18
18
  recordUsing(sink, cause) {
19
19
  if (this.state.first)
@@ -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();
@@ -8,7 +8,7 @@ import { createEmployeeTools } from "./employee-tools.js";
8
8
  import { employeeRouting } from "./employee-relay.js";
9
9
  import { NeedError } from "./remote.js";
10
10
  const string = { type: 'string' }, integer = { type: 'integer' }, boolean = { type: 'boolean' };
11
- function schema(name, properties, required) { return { name, description: '在员工电脑所选工作区执行' + name + ';不在主机回退。', inputSchema: { type: 'object', properties, required, additionalProperties: false } }; }
11
+ function schema(name, properties, required) { return { name, description: '在员工电脑所选工作区执行' + name + ';不在主机回退。' + (name === 'Bash' ? '输出原样保留:若stdoutEncoding或stderrEncoding为base64,对应字符串为原始字节的base64编码,按标明编码处理;退出状态独立保留。' : ''), inputSchema: { type: 'object', properties, required, additionalProperties: false } }; }
12
12
  export const EMPLOYEE_MCP_TOOLS = [
13
13
  schema('Read', { file_path: string, offset: integer, limit: integer, pages: string }, ['file_path']),
14
14
  schema('Write', { file_path: string, content: string }, ['file_path', 'content']),