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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,12 +1,12 @@
1
- # AI Workbench 远程助手 · @ai-workbench/remote-agent@0.9.0-toolbridge.14 · 插件 → 添加插件
1
+ # AI Workbench 远程助手 · @ai-workbench/remote-agent@0.9.0-toolbridge.16 · 插件 → 添加插件
2
2
 
3
3
  ## 含工具桥预发布线
4
4
 
5
- 本包为 `0.9.0-toolbridge.14`,从 `v0.9.0-toolbridge.13` 派生,使用 `host-toolbridge` 发布渠道。员工安装由连接组件提供的「AI 写作工作台(含工具桥)」总包 `@ai-workbench/workbench-toolbridge@0.1.11`,与不含工具桥的版本二选一。
5
+ 本包为 `0.9.0-toolbridge.16`,从 `v0.9.0-toolbridge.14` 派生,使用 `host-toolbridge` 发布渠道。员工安装由连接组件提供的「AI 写作工作台(含工具桥)」总包 `@ai-workbench/workbench-toolbridge@0.1.13`,与不含工具桥的版本二选一。
6
6
 
7
7
  本轮增加两家运行中插话(DSH 原生 nextStep),保留官方队列和原话;明确 followup 仍排下一轮。Codex 含桥组件需 `2.2.2-aw.12`,Claude 仍为官方 `0.94.0`。插件确定消息未发出时保留排队资格;送达未确认时明确报错且不重放。已注入旧正文不能撤回,编辑版下一步骤交付。
8
8
 
9
- host `0.8.9` 的新 broker 支持同一客户端/SDK 在切网后按输出游标和输入 ACK 水位接回原 prompt、结果及用量,不重新发送原 prompt;旧本机执行端失效仍为 UNKNOWN,不用新进程替换或重放旧操作。客户端退出/重开后的冷恢复尚未完成;旧运行 broker 不会被安装自动追改。无新增设置;512,000,000 字节默认保留,实际协议头计入同一容量。
9
+ host `0.8.10` 的新 broker 支持同一客户端/SDK 在切网后按输出游标和输入 ACK 水位接回原 prompt、结果及用量,不重新发送原 prompt;旧本机执行端失效仍为 UNKNOWN,不用新进程替换或重放旧操作。客户端完全退出、崩溃后,重新打开同一 DSH 会话会自动接回已持久登记的原 prompt,显示未落盘输出并取回原结果、增量用量。原 prompt 只执行一次;旧审批仅取消,不复活未知本机执行。旧运行 broker 和 X.14 在途轮不会被安装自动补造冷恢复记录。无新增设置;512,000,000 字节默认保留,实际协议头计入同一容量。
10
10
 
11
11
 
12
12
  选择本机文件夹后,Claude 和 Codex 可以把 DSH 已启用的 MCP、web、skill、ask_user、todo/present/goal 等工具交给 DSH 原生执行和审批。内置文件/命令、子代理/agent-team、run_code 不在桥接表;原有文件和命令执行方式保留。plan 不自动放行桥接权限;default 下 Claude 的桥接原生权限由插件单次应答,员工只在 DSH 审批实际工具。主机文件夹不开放工具桥。
@@ -31,7 +31,7 @@ Claude 本机 Bash 会单独消费员工桥代理的控制诊断,不把它交
31
31
 
32
32
  ## 会话行为
33
33
 
34
- 每轮启动一个新助手进程,按原生会话编号恢复上下文;不接回旧进程或重放上一轮输入。主机会话始终使用创建时保存的主机和目录;工作区之后的选择只影响新会话。
34
+ 新的用户轮启动一个新助手进程,按原生会话编号恢复上下文;退出前尚未结算的原轮则附着原进程,仅取回该轮输出、结果和用量,不重发原输入。主机会话始终使用创建时保存的主机和目录;工作区之后的选择只影响新会话。
35
35
 
36
36
  同一 DSH 会话切换 Claude/Codex 时,切回会接本品牌最近的远端会话,并补充它尚未见过的可见对话;首次使用某品牌则带入全部可见历史。工具内部状态、推理和技术详情不转交。历史超出既有 `acpMaxMessageBytes` 容量时,只带能容纳的最近完整轮,并在技术详情说明省略数量;当前输入保持完整,超限仍明确失败。没有新增设置、重试或时限。
37
37
 
package/dist/acp.d.ts CHANGED
@@ -10,7 +10,7 @@ import type { SessionOwnership } from './broker-ownership.ts';
10
10
  export type ApprovalOutcome = 'allowed-once' | 'rejected' | 'cancelled' | 'unavailable';
11
11
  export interface AcpHooks {
12
12
  closeDiagnostics?: CloseDiagnostics;
13
- onUpdate?: (notification: acp.SessionNotification) => void;
13
+ onUpdate?: (notification: acp.SessionNotification, originSequence?: number) => void;
14
14
  onResponse?: (response: acp.PromptResponse) => void;
15
15
  approve?: (request: acp.RequestPermissionRequest, signal?: AbortSignal) => Promise<ApprovalOutcome>;
16
16
  /** A grant belongs to the exact official permission generation that asked it. */
@@ -126,3 +126,4 @@ export declare class AcpSession {
126
126
  close(cause?: CloseCause, error?: Error): void;
127
127
  }
128
128
  export declare function acpNeed(error: unknown): NeedError;
129
+ export declare const isKnownAcpUpdate: (update: unknown) => boolean;
package/dist/acp.js CHANGED
@@ -277,7 +277,8 @@ export class AcpSession {
277
277
  this.hooks = hooks;
278
278
  this.closeDiagnostics = hooks.closeDiagnostics ?? new CloseDiagnostics(event => this.detail(event));
279
279
  const app = acp.client({ name: '@ai-workbench/remote-agent' })
280
- .onNotification(acp.methods.client.session.update, ({ params: notification }) => {
280
+ .onNotification(acp.methods.client.session.update, ({ params: incoming }) => {
281
+ const { notification, sequence } = this.hooks.broker?.stripOutputOrigin(incoming) ?? { notification: incoming, sequence: undefined };
281
282
  if (this.creatingReplacement) {
282
283
  if (notification.sessionId !== this.sessionId && notification.update.sessionUpdate === 'config_option_update')
283
284
  this.pendingConfiguration(notification.sessionId, notification.update.configOptions);
@@ -319,7 +320,7 @@ export class AcpSession {
319
320
  if (meta && Object.keys(meta).length)
320
321
  this.detail({ kind: 'extension', severity: 'info', code: 'ACP_NOTIFICATION_META', summary: '远端通知扩展', method: 'session/update', payload: notification._meta });
321
322
  if (this.busy) {
322
- this.hooks.onUpdate?.(notification);
323
+ this.hooks.onUpdate?.(notification, sequence);
323
324
  }
324
325
  else
325
326
  this.detail({ kind: notification.update.sessionUpdate === 'available_commands_update' ? 'commands' : 'session', severity: 'info', code: 'ACP_IDLE_UPDATE', summary: '远端会话建立、恢复或空闲时的轨迹', method: 'session/update', payload: notification });
@@ -441,7 +442,7 @@ export class AcpSession {
441
442
  this.detail({ kind: 'extension', severity: 'warning', code: 'ACP_UNKNOWN_NOTIFICATION', summary: '收到未知远端扩展通知,已保留技术记录', method, payload: params });
442
443
  });
443
444
  if ('readable' in transport && 'writable' in transport)
444
- this.connection = app.connect(isolateRpcIds(this.observe(transport), message => this.observeDispatch(message)));
445
+ this.connection = app.connect(isolateRpcIds(this.observe(this.hooks.broker?.withOutputOrigins(transport) ?? transport), message => this.observeDispatch(message)));
445
446
  else {
446
447
  // Stable and unstable apps use distinct private symbols. Bridge only their
447
448
  // public stream interfaces so either SDK entry point remains supported.
@@ -489,14 +490,16 @@ export class AcpSession {
489
490
  // byte buffer, message-size policy, or transport fallback is introduced.
490
491
  const observe = this.closeDiagnostics.capture();
491
492
  const readable = stream.readable.pipeThrough(new TransformStream({ transform: (message, controller) => {
492
- const raw = record(message);
493
- const params = record(raw?.params);
494
- const update = record(params?.update);
495
- if (raw?.method === acp.methods.client.session.update && typeof update?.sessionUpdate === 'string' && !knownUpdates.has(update.sessionUpdate)) {
496
- this.detail({ kind: 'extension', severity: 'warning', code: 'ACP_UNKNOWN_UPDATE', summary: '收到未知远端会话事件,已保留结构', method: 'session/update', payload: params });
497
- return;
498
- }
499
- controller.enqueue(message);
493
+ const inspect = (value) => { if (Array.isArray(value)) {
494
+ const members = value.flatMap(item => inspect(item));
495
+ return members.length ? [members] : [];
496
+ } const raw = record(value), params = record(raw?.params), update = record(params?.update); if (raw?.method === acp.methods.client.session.update && typeof update?.sessionUpdate === 'string' && !knownUpdates.has(update.sessionUpdate)) {
497
+ const notification = this.hooks.broker?.stripOutputOrigin(params).notification ?? params;
498
+ this.detail({ kind: 'extension', severity: 'warning', code: 'ACP_UNKNOWN_UPDATE', summary: '收到未知远端会话事件,已保留结构', method: 'session/update', payload: notification });
499
+ return [];
500
+ } return [value]; };
501
+ for (const value of inspect(message))
502
+ controller.enqueue(value);
500
503
  }, flush: () => observe({ layer: 'acp', initiator: 'acp.read-eof', reason: 'ACP_STREAM_EOF', action: 'eof' }) }));
501
504
  return { readable, writable: stream.writable };
502
505
  }
@@ -641,11 +644,18 @@ export class AcpSession {
641
644
  this.turnToken = Symbol('turn');
642
645
  let rejectAbort;
643
646
  const interrupted = new Promise((_resolve, reject) => { rejectAbort = reject; });
647
+ const requestAbort = new AbortController();
644
648
  const cancel = () => {
649
+ if (signal?.reason?.kind === 'disposed') {
650
+ this.close({ layer: 'acp', initiator: 'acp.owner-disposed', reason: 'SESSION_DETACHED', action: 'detach' });
651
+ rejectAbort?.(new NeedError('ABORTED', '客户端已退出,主机原轮保留,未发送取消', '原轮冷恢复'));
652
+ return;
653
+ }
645
654
  if (this.closeRequested) {
646
655
  rejectAbort?.(new NeedError('ABORTED', '客户端已分离,未重发或取消主机原轮', '原轮恢复状态'));
647
656
  return;
648
657
  }
658
+ requestAbort.abort(signal?.reason);
649
659
  this.closeDiagnostics.record({ layer: 'acp', initiator: 'acp.prompt-cancel', reason: 'ABORTED', operation: 'session/prompt', action: 'abort' });
650
660
  rejectAbort?.(new NeedError('ABORTED', '已请求取消本轮,远端状态需确认', '确认主机取消状态'));
651
661
  void this.connection.agent.notify(acp.methods.agent.session.cancel, { sessionId: this.sessionId }).catch(() => {
@@ -657,7 +667,7 @@ export class AcpSession {
657
667
  this.flushBridgeStartupNotice();
658
668
  const result = await this.stage('acp-prompt', () => {
659
669
  this.promptPermissions.set(params, { current, native });
660
- const request = this.connection.agent.request(acp.methods.agent.session.prompt, params, { cancellationSignal: signal });
670
+ const request = this.connection.agent.request(acp.methods.agent.session.prompt, params, { cancellationSignal: requestAbort.signal });
661
671
  return signal ? Promise.race([request, interrupted]) : request;
662
672
  });
663
673
  signal?.throwIfAborted();
@@ -735,3 +745,4 @@ export function acpNeed(error) {
735
745
  function record(value) { return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : undefined; }
736
746
  const knownUpdates = new Set(['user_message_chunk', 'agent_message_chunk', 'agent_thought_chunk', 'tool_call', 'tool_call_update', 'plan', 'plan_update', 'plan_removed', 'available_commands_update', 'current_mode_update', 'config_option_update', 'session_info_update', 'usage_update', 'notice', 'compaction_update', 'compaction_summary_chunk', 'subagent_update', 'session_message', 'session_message_chunk']);
737
747
  function safeLabel(value) { return value.replaceAll(/[\r\n\x00-\x1f\x7f]/g, ' '); }
748
+ export const isKnownAcpUpdate = (update) => !!update && typeof update === 'object' && knownUpdates.has(update.sessionUpdate);
@@ -1,3 +1,4 @@
1
+ import { type ColdStore } from './cold-store.ts';
1
2
  import { type SshArgv, type BrokerIo, type BrokerSettings } from './broker.ts';
2
3
  import { type ConnectApi, type ConnectTarget, type Project, type Runtime, type RuntimeRequest } from './provider.ts';
3
4
  import type { Interaction } from './interaction.ts';
@@ -5,4 +6,5 @@ import type { Interaction } from './interaction.ts';
5
6
  export declare function brokerFactory(_get: () => ConnectApi | undefined, _ask: Interaction | undefined, configuration: BrokerSettings | (() => BrokerSettings), provided?: {
6
7
  argv?: SshArgv;
7
8
  io?: (target: ConnectTarget) => BrokerIo;
9
+ coldStore?: ColdStore;
8
10
  }): (target: ConnectTarget, project: Project, request: RuntimeRequest) => Promise<Runtime>;
@@ -6,6 +6,7 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
6
6
  }
7
7
  return path;
8
8
  };
9
+ import { newColdId } from "./cold-store.js";
9
10
  import { randomUUID } from 'node:crypto';
10
11
  import { CloseDiagnostics } from "./close-diagnostics.js";
11
12
  import { BrokerTransport, brokerCommand, brokerId, sshIo, controlJson } from "./broker.js";
@@ -36,7 +37,46 @@ export function brokerFactory(_get, _ask, configuration, provided) {
36
37
  throw new NeedError(started.code, '主机的环境配置会覆盖本机执行位置,本轮已停止;请由管理员移开该配置后在原会话重试。', '主机 CODEX_HOME/environments.toml 不存在');
37
38
  if (started.protocolVersion !== 1 || started.id !== id || !started.instanceId)
38
39
  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, ...(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 coldStore = started.messageInputProtocolVersion === 1 ? provided?.coldStore : undefined, roundId = newColdId(), boundOrigin = Promise.withResolvers();
41
+ void boundOrigin.promise.catch(() => { });
42
+ if (coldStore)
43
+ await coldStore.put({ version: 1, id: roundId, sessionId: request.sessionId, provider: agent.id, brand: agent.loginProvider, phase: 'opening', target: structuredClone(target), brokerId: id, instanceId: started.instanceId, controlMaxBytes: started.controlMaxBytes, heartbeatIntervalMs: started.lifecycle.heartbeatIntervalMs, rpcIds: [], answered: [], inputSequence: 0, outputAfter: 0 });
44
+ const beforeMessage = coldStore ? async (bytes, message) => {
45
+ const rpc = JSON.parse(Buffer.from(bytes).toString('utf8'));
46
+ try {
47
+ let record = await coldStore.update(request.sessionId, agent.id, roundId, row => {
48
+ if (rpc.method && Object.hasOwn(rpc, 'id') && !row.rpcIds.includes(rpc.id))
49
+ row.rpcIds.push(rpc.id);
50
+ if (rpc.method === 'session/cancel' && rpc.params?.sessionId === row.nativeId || rpc.method === '$/cancel_request' && String(rpc.params?.requestId) === row.promptId)
51
+ row.cancelIntent ??= { source: 'wire' };
52
+ row.pending = { id: message.id, sha256: message.sha256, wire: Buffer.from(bytes).toString('base64'), baseSequence: message.baseSequence, chunkBytes: message.chunkBytes, chunks: Math.ceil(bytes.length / message.chunkBytes), ...(rpc.method ? { method: rpc.method } : {}), ...(Object.hasOwn(rpc, 'id') ? { rpcId: rpc.id } : {}) };
53
+ if (rpc.method === 'session/prompt') {
54
+ if (!row.meta || row.nativeId !== rpc.params?.sessionId || row.promptId)
55
+ throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '原轮归属未完成持久登记,未发送输入', '完整冷恢复快照');
56
+ row.promptId = String(rpc.id);
57
+ row.promptSha256 = message.sha256;
58
+ row.promptBytes = bytes.length;
59
+ row.phase = 'running';
60
+ }
61
+ });
62
+ if (rpc.method === 'session/prompt') {
63
+ const bound = controlJson(await io.run(command(['bind-round', id, '--if-instance', started.instanceId, '--dsh-session-id', request.sessionId, '--provider', agent.loginProvider, '--remote-session-id', record.nativeId, '--round-id', roundId, '--prompt-id', record.promptId, '--prompt-sha256', record.promptSha256, '--prompt-bytes', String(record.promptBytes)]), request.signal));
64
+ if (!Number.isSafeInteger(bound.round?.outputStartSequence))
65
+ throw new NeedError('BROKER_PROTOCOL_INVALID', '原轮输出起点未确认', '原轮绑定回执');
66
+ await coldStore.update(request.sessionId, agent.id, roundId, row => { row.outputStart = bound.round.outputStartSequence; });
67
+ boundOrigin.resolve(bound.round.outputStartSequence);
68
+ }
69
+ }
70
+ catch (error) {
71
+ if (rpc.method === 'session/prompt')
72
+ boundOrigin.reject(error);
73
+ throw error;
74
+ }
75
+ } : undefined;
76
+ const afterMessage = coldStore ? async (sequence) => { await coldStore.update(request.sessionId, agent.id, roundId, row => { if (row.pending && !row.pending.method && row.pending.rpcId !== undefined && !row.answered.includes(row.pending.rpcId))
77
+ row.answered.push(row.pending.rpcId); if (row.pending && ['session/cancel', '$/cancel_request'].includes(row.pending.method ?? '') && row.cancelIntent)
78
+ row.cancelIntent.delivered = true; row.inputSequence = sequence; delete row.pending; }); } : undefined;
79
+ 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 } : {}), ...(coldStore ? { messageInput: true, outputOrigins: true, beforeMessage, afterMessage } : {}), attach: (after = 0) => io.attach(command(['attach', id, '--after', String(after), '--framed', '--leased', ...(started.inputProtocolVersion === 2 ? ['--input-protocol', '2'] : []), ...(coldStore ? ['--message-input'] : []), '--if-instance', started.instanceId])) });
40
80
  const reconnectOff = started.inputProtocolVersion === 2 ? _get()?.onConnectionState?.(state => { if (state.phase === 'connected' && !channel.online)
41
81
  void channel.connect().catch(() => { }); }) : undefined;
42
82
  let ended = false;
@@ -76,6 +116,6 @@ export function brokerFactory(_get, _ask, configuration, provided) {
76
116
  finally {
77
117
  request.signal?.removeEventListener('abort', aborted);
78
118
  }
79
- return { identity: identity(target), cwd: project.path, closeDiagnostics: diagnostics, broker: channel, sessionOwnership, acpTransport: channel, dispose, detach: channel.supportsRecovery ? detach : dispose };
119
+ return { ...(coldStore ? { cold: { id: roundId, store: coldStore, bound: boundOrigin.promise, failBinding: error => boundOrigin.reject(error), prepare: async (nativeId, meta) => { await coldStore.update(request.sessionId, agent.id, roundId, row => { row.nativeId = nativeId; row.meta = structuredClone(meta); }); } } } : {}), identity: identity(target), cwd: project.path, closeDiagnostics: diagnostics, broker: channel, sessionOwnership, acpTransport: channel, dispose, detach: channel.supportsRecovery ? detach : dispose };
80
120
  };
81
121
  }
package/dist/broker.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { ColdWrite } from './cold-store.ts';
1
2
  import { type CloseCause, type CloseObserver } from './close-diagnostics.ts';
2
3
  import { type ChildProcessWithoutNullStreams } from 'node:child_process';
3
4
  import { NeedError, type Need } from './remote.ts';
@@ -12,6 +13,20 @@ export interface BrokerOptions {
12
13
  attach: (after?: number) => Promise<Attachment>;
13
14
  inputProtocolVersion?: 2;
14
15
  recoverDisconnect?: boolean;
16
+ messageInput?: boolean;
17
+ outputOrigins?: boolean;
18
+ initialSequence?: number;
19
+ restoreInput?: {
20
+ sequence: number;
21
+ pending?: ColdWrite;
22
+ };
23
+ beforeMessage?: (bytes: Uint8Array, message: {
24
+ id: string;
25
+ sha256: string;
26
+ chunkBytes: number;
27
+ baseSequence: number;
28
+ }) => Promise<void>;
29
+ afterMessage?: (sequence: number) => Promise<void>;
15
30
  onNeed?: (need: Need) => void;
16
31
  }
17
32
  /** One byte stream / SDK app over one SSH attachment of a new agent. Input is never replayed. */
@@ -22,6 +37,32 @@ export declare class BrokerTransport {
22
37
  private output;
23
38
  private attachment?;
24
39
  private cursor;
40
+ get lastSequence(): number;
41
+ private originKey;
42
+ private originNonce;
43
+ private originPartial;
44
+ private originFinalSequence;
45
+ private originMarker;
46
+ private stdout;
47
+ withOutputOrigins<T extends {
48
+ readable: ReadableStream<any>;
49
+ writable: WritableStream<any>;
50
+ }>(stream: T): T;
51
+ stripOutputOrigin<T>(notification: T): {
52
+ notification: T;
53
+ sequence?: number;
54
+ };
55
+ private promptReceipt?;
56
+ get promptDelivered(): boolean | undefined;
57
+ private receipt;
58
+ get inputReceipt(): any;
59
+ private controlWait?;
60
+ private resendControl;
61
+ private controlMessage;
62
+ completeRestoredInput(): void;
63
+ discardMessage(id: string): Promise<any>;
64
+ observeMessage(id: string): Promise<any>;
65
+ resumeMessage(write: ColdWrite): Promise<void>;
25
66
  private attachedId?;
26
67
  get attachmentId(): string | undefined;
27
68
  private inputSequence;
package/dist/broker.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { randomUUID } from 'node:crypto';
1
2
  import { closeCode } from "./close-diagnostics.js";
2
3
  import { spawn } from 'node:child_process';
3
4
  import { createHash } from 'node:crypto';
@@ -11,6 +12,86 @@ export class BrokerTransport {
11
12
  output;
12
13
  attachment;
13
14
  cursor = 0;
15
+ get lastSequence() { return this.cursor; }
16
+ originKey = 'ai-workbench/output-origin/' + randomUUID();
17
+ originNonce = randomUUID();
18
+ originPartial = false;
19
+ originFinalSequence = 0;
20
+ originMarker(sequence) { return Buffer.from(JSON.stringify(['aw-origin', sequence, this.originNonce]) + '\n'); }
21
+ stdout(bytes, sequence) {
22
+ if (!this.options.outputOrigins) {
23
+ this.output.enqueue(bytes);
24
+ return;
25
+ }
26
+ this.originFinalSequence = sequence;
27
+ let start = 0, newline;
28
+ while ((newline = bytes.indexOf(10, start)) >= 0) {
29
+ const part = bytes.subarray(start, newline + 1);
30
+ if (part.some(byte => ![9, 10, 13, 32].includes(byte)))
31
+ this.originPartial = true;
32
+ this.output.enqueue(part);
33
+ if (this.originPartial)
34
+ this.output.enqueue(this.originMarker(sequence));
35
+ this.originPartial = false;
36
+ start = newline + 1;
37
+ }
38
+ if (start < bytes.length) {
39
+ const part = bytes.subarray(start);
40
+ if (part.some(byte => ![9, 13, 32].includes(byte)))
41
+ this.originPartial = true;
42
+ this.output.enqueue(part);
43
+ }
44
+ }
45
+ withOutputOrigins(stream) {
46
+ if (!this.options.outputOrigins)
47
+ return stream;
48
+ let pending;
49
+ return { ...stream, readable: stream.readable.pipeThrough(new TransformStream({ transform: (message, controller) => {
50
+ if (Array.isArray(message) && message[0] === 'aw-origin' && message[2] === this.originNonce) {
51
+ if (pending === undefined)
52
+ throw new NeedError('BROKER_PROTOCOL_INVALID', '输出消息来源边界不完整', '原broker输出序号');
53
+ const sequence = message[1];
54
+ const annotate = (value) => Array.isArray(value) ? value.map(annotate) : sequence !== null && value?.method === 'session/update' && value.params && typeof value.params === 'object' ? { ...value, params: { ...value.params, _meta: { ...value.params._meta, [this.originKey]: sequence } } } : value;
55
+ pending = annotate(pending);
56
+ controller.enqueue(pending);
57
+ pending = undefined;
58
+ return;
59
+ }
60
+ if (pending !== undefined)
61
+ throw new NeedError('BROKER_PROTOCOL_INVALID', '输出消息缺少来源边界', '原broker输出序号');
62
+ pending = message;
63
+ }, flush: () => { if (pending !== undefined)
64
+ throw new NeedError('BROKER_PROTOCOL_INVALID', '输出消息来源未确认', '原broker输出序号'); } })) };
65
+ }
66
+ stripOutputOrigin(notification) { const raw = notification, meta = raw?._meta, sequence = meta?.[this.originKey]; if (sequence === undefined)
67
+ return { notification }; if (!Number.isSafeInteger(sequence) || sequence < 1)
68
+ throw new NeedError('BROKER_PROTOCOL_INVALID', '输出序号无效', '原broker输出序号'); const clean = { ...meta }; delete clean[this.originKey]; const copy = { ...raw }; if (Object.keys(clean).length)
69
+ copy._meta = clean;
70
+ else
71
+ delete copy._meta; return { notification: copy, sequence }; }
72
+ promptReceipt;
73
+ get promptDelivered() { return this.promptReceipt; }
74
+ receipt;
75
+ get inputReceipt() { return this.receipt; }
76
+ controlWait;
77
+ resendControl() { const wait = this.controlWait; if (wait && this.online) {
78
+ const child = this.attachment;
79
+ child.stdin.write(JSON.stringify({ type: wait.kind === 'discard' ? 'discard-input' : 'observe-input', messageId: wait.id }) + '\n', error => { if (error)
80
+ child.kill('SIGTERM'); });
81
+ } }
82
+ async controlMessage(kind, id) { await this.waitInput(); if (this.controlWait)
83
+ throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '原输入观察尚未结束', '串行消息回执'); const ready = Promise.withResolvers(); this.controlWait = { kind, id, ready }; this.resendControl(); try {
84
+ return await ready.promise;
85
+ }
86
+ finally {
87
+ this.controlWait = undefined;
88
+ } }
89
+ completeRestoredInput() { this.options.restoreInput = undefined; }
90
+ discardMessage(id) { return this.controlMessage('discard', id); }
91
+ observeMessage(id) { return this.controlMessage('observe', id); }
92
+ async resumeMessage(write) { const bytes = Buffer.from(write.wire, 'base64'), skip = this.inputSequence - write.baseSequence; if (skip < 0 || skip > write.chunks)
93
+ throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '原输入水位越界,没有重复写入', '原输入提交回执'); if (skip === write.chunks)
94
+ return; await this.send(bytes, { id: write.id, sha256: write.sha256, chunkBytes: write.chunkBytes, offset: skip * write.chunkBytes }); }
14
95
  attachedId;
15
96
  get attachmentId() { return this.attachedId; }
16
97
  inputSequence = 0;
@@ -85,6 +166,8 @@ export class BrokerTransport {
85
166
  if (!Number.isSafeInteger(options.maxFrameBytes) || options.maxFrameBytes < 1)
86
167
  throw new NeedError('SETTINGS_REQUIRED', '我需要 brokerMaxFrameBytes', '管理员确认 brokerMaxFrameBytes');
87
168
  this.options = options;
169
+ this.cursor = options.initialSequence ?? 0;
170
+ this.inputSequence = options.restoreInput?.sequence ?? 0;
88
171
  this.inputReady = options.inputProtocolVersion !== 2;
89
172
  this.lease.abort();
90
173
  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' }); } });
@@ -115,6 +198,7 @@ export class BrokerTransport {
115
198
  this.attached = false;
116
199
  this.lease.abort();
117
200
  this.pendingInput?.ack.reject(error);
201
+ this.controlWait?.ready.reject(error);
118
202
  this.notice(error.code, error.message);
119
203
  this.changed();
120
204
  this.attachment?.kill('SIGTERM');
@@ -132,6 +216,7 @@ export class BrokerTransport {
132
216
  this.attached = false;
133
217
  this.lease.abort();
134
218
  this.pendingInput?.ack.reject(new NeedError('CONNECTION_LOST', '原轮已经关闭,输入未重发', '原轮状态'));
219
+ this.controlWait?.ready.reject(new NeedError('CONNECTION_LOST', '原流已结束,控制回执未确认', '原消息终态'));
135
220
  this.changed();
136
221
  this.attachment?.kill('SIGTERM');
137
222
  try {
@@ -196,8 +281,20 @@ export class BrokerTransport {
196
281
  const receipt = f.inputReceipt;
197
282
  if (f.inputProtocolVersion !== 2 || !receipt || receipt.failed !== false)
198
283
  throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '主机不能确认原输入字节水位,未重发输入。', 'inputProtocolVersion 2的有效回执');
199
- this.acknowledge(receipt.committedSequence);
200
- if (receipt.pendingSequence !== null && receipt.pendingSequence !== this.pendingInput?.sequence)
284
+ if (this.options.messageInput && this.options.restoreInput && !this.pendingInput && this.inputSequence <= this.options.restoreInput.sequence + (this.options.restoreInput.pending?.chunks ?? 0)) {
285
+ const sequence = receipt.committedSequence, restore = this.options.restoreInput, pending = restore.pending, r = receipt;
286
+ if (!Number.isSafeInteger(sequence) || sequence < restore.sequence || sequence > restore.sequence + (pending?.chunks ?? 0) || sequence !== restore.sequence && (!pending || r.stagedMessageId !== pending.id && !(r.lastMessage?.id === pending.id && r.lastMessage?.sha256 === pending.sha256)))
287
+ throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '原输入水位不属于本轮,未跳过输入', '原消息身份及提交水位');
288
+ this.inputSequence = sequence;
289
+ }
290
+ else
291
+ this.acknowledge(receipt.committedSequence);
292
+ this.receipt = receipt;
293
+ if (typeof f.promptDelivered === 'boolean')
294
+ this.promptReceipt = f.promptDelivered;
295
+ if (this.options.messageInput && f.messageInputProtocolVersion !== 1)
296
+ throw new NeedError('BROKER_PROTOCOL_INVALID', '主机缺少完整消息暂存协议', 'messageInputProtocolVersion 1');
297
+ if (receipt.pendingSequence !== null && receipt.pendingSequence !== this.pendingInput?.sequence && !(this.options.restoreInput?.pending && receipt.pendingSequence === this.options.restoreInput.pending.baseSequence + this.options.restoreInput.pending.chunks && receipt.stagedMessageId === this.options.restoreInput.pending.id && receipt.stagedSha256 === this.options.restoreInput.pending.sha256))
201
298
  throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '主机在途输入不属于本客户端', '原客户端在途输入');
202
299
  if (typeof f.attachmentId !== 'string' || !f.attachmentId)
203
300
  throw new NeedError('BROKER_PROTOCOL_INVALID', '主机缺少写者实例标识', '本次attachmentId');
@@ -212,9 +309,22 @@ export class BrokerTransport {
212
309
  this.attached = true;
213
310
  this.lease = new AbortController();
214
311
  this.changed();
312
+ this.resendControl();
215
313
  connected.resolve();
216
314
  return;
217
315
  }
316
+ if (f.type === 'input-discarded' || f.type === 'input-observed') {
317
+ const wait = this.controlWait;
318
+ if (!wait || f.messageId !== wait.id)
319
+ throw new NeedError('BROKER_PROTOCOL_INVALID', '输入控制回执不匹配', '原消息标识');
320
+ this.receipt = f.inputReceipt;
321
+ const r = f.inputReceipt;
322
+ if (!Number.isSafeInteger(r?.committedSequence) || r.committedSequence < this.inputSequence)
323
+ throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '输入控制水位倒退', '原消息终态');
324
+ this.inputSequence = r.committedSequence;
325
+ wait.ready.resolve(r);
326
+ return;
327
+ }
218
328
  if (f.type === 'input-ack') {
219
329
  if (this.options.inputProtocolVersion !== 2)
220
330
  throw new NeedError('BROKER_PROTOCOL_INVALID', '未协商输入确认', 'inputProtocolVersion 2');
@@ -224,12 +334,14 @@ export class BrokerTransport {
224
334
  if (f.type === 'replay-complete') {
225
335
  if (this.options.inputProtocolVersion !== 2 || f.sequence !== this.cursor)
226
336
  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'));
337
+ this.output.enqueue(Buffer.from(JSON.stringify({ jsonrpc: '2.0', method: '_aw/broker-replay-complete', params: { generation: this.epoch, pendingClientRequests: f.pendingClientRequests } }) + '\n'));
338
+ if (this.options.outputOrigins)
339
+ this.output.enqueue(this.originMarker(null));
228
340
  return;
229
341
  }
230
342
  if (f.type === 'error') {
231
343
  const code = typeof f.code === 'string' && /^[A-Z][A-Z0-9_]{0,63}$/.test(f.code) ? f.code : 'BROKER_PROTOCOL_INVALID';
232
- const error = new NeedError(code, '主机会话无法续接(' + code + ');没有重放输入或代答审批', '恢复或显式结束原会话');
344
+ const error = new NeedError(code, f.reason === 'OUTPUT_JOURNAL_FAILED' ? '主机输出持久保存失败(' + String(f.systemCode) + '),原轮结果未确认,没有重放。' : '主机会话无法续接(' + code + ');没有重放输入或代答审批', '恢复或显式结束原会话');
233
345
  if (ready && code === 'ATTACH_LEASE_EXPIRED' && this.supportsRecovery) {
234
346
  attemptClosed = true;
235
347
  this.stopHeartbeat();
@@ -251,11 +363,17 @@ export class BrokerTransport {
251
363
  throw error;
252
364
  }
253
365
  if (f.type === 'exit' && this.supportsRecovery) {
366
+ if (this.options.outputOrigins && this.originPartial) {
367
+ this.output.enqueue(Buffer.from('\n'));
368
+ this.output.enqueue(this.originMarker(this.originFinalSequence));
369
+ this.originPartial = false;
370
+ }
254
371
  this.stopHeartbeat();
255
372
  this.ended = true;
256
373
  this.attached = false;
257
374
  this.lease.abort();
258
375
  this.pendingInput?.ack.reject(new NeedError('AGENT_EXITED', '主机进程已退出,未重发输入', '原轮结果'));
376
+ this.controlWait?.ready.reject(new NeedError('AGENT_EXITED', '主机进程已退出,输入控制回执未确认', '原消息终态'));
259
377
  this.changed();
260
378
  this.output.close();
261
379
  return;
@@ -273,7 +391,7 @@ export class BrokerTransport {
273
391
  if (seq !== this.cursor + 1)
274
392
  throw new NeedError('REPLAY_GAP', '主机输出存在缺口,不能安全继续审批', '显式结束或恢复原会话');
275
393
  if (f.channel === 'stdout') {
276
- this.output.enqueue(Buffer.from(f.data, 'base64'));
394
+ this.stdout(Buffer.from(f.data, 'base64'), seq);
277
395
  }
278
396
  this.cursor = seq;
279
397
  this.changed();
@@ -333,7 +451,7 @@ export class BrokerTransport {
333
451
  return connected.promise.finally(off);
334
452
  }
335
453
  write(bytes) { return this.exclusive(() => this.send(bytes)); }
336
- async send(bytes) {
454
+ async send(bytes, resume) {
337
455
  if (this.supportsRecovery)
338
456
  await this.waitInput();
339
457
  if (!this.online || !this.attachment)
@@ -383,28 +501,31 @@ export class BrokerTransport {
383
501
  if (prompt && this.promptPermit === promptPermit)
384
502
  this.promptPermit = undefined;
385
503
  const chunks = [];
386
- let chunkBytes = bytes.byteLength;
504
+ let chunkBytes = resume?.chunkBytes ?? bytes.byteLength;
505
+ const message = this.options.messageInput ? resume ?? { id: randomUUID(), sha256: createHash('sha256').update(bytes).digest('hex') } : undefined;
387
506
  if (this.options.leased) {
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;
507
+ const size = Math.floor((this.options.controlMaxBytes - Buffer.byteLength(JSON.stringify({ type: 'input', data: '', ...(this.options.inputProtocolVersion === 2 ? { sequence: Number.MAX_SAFE_INTEGER } : {}), ...(message ? { messageId: message.id, final: false, sha256: message.sha256 } : {}) }))) / 4) * 3;
389
508
  if (size < 1)
390
509
  throw new NeedError('LEASE_CAPACITY_INVALID', '主机会话容量无法承载输入', '有效controlMaxBytes');
391
- chunkBytes = size;
510
+ chunkBytes = resume?.chunkBytes ?? size;
392
511
  if (this.options.inputProtocolVersion !== 2)
393
512
  for (let offset = 0; offset < bytes.byteLength; offset += size)
394
513
  chunks.push(Buffer.from(JSON.stringify({ type: 'input', data: Buffer.from(bytes.subarray(offset, offset + size)).toString('base64') }) + '\n'));
395
514
  }
396
515
  else
397
516
  chunks.push(Buffer.from(bytes));
517
+ if (message && !resume)
518
+ await this.options.beforeMessage?.(bytes, { ...message, chunkBytes, baseSequence: this.inputSequence });
398
519
  if (this.options.inputProtocolVersion === 2) {
399
520
  try {
400
- for (let offset = 0; offset < bytes.byteLength; offset += chunkBytes) {
521
+ for (let offset = resume?.offset ?? 0; offset < bytes.byteLength; offset += chunkBytes) {
401
522
  const chunk = bytes.subarray(offset, offset + chunkBytes);
402
523
  await this.waitInput();
403
524
  if (prompt)
404
525
  currentPrompt();
405
526
  const sequence = this.inputSequence + 1, ack = Promise.withResolvers();
406
527
  void ack.promise.catch(() => { });
407
- const frame = Buffer.from(JSON.stringify({ type: 'input', sequence, data: Buffer.from(chunk).toString('base64') }) + '\n');
528
+ const frame = Buffer.from(JSON.stringify({ type: 'input', sequence, data: Buffer.from(chunk).toString('base64'), ...(message ? { messageId: message.id, sha256: message.sha256, final: offset + chunkBytes >= bytes.byteLength } : {}) }) + '\n');
408
529
  const pending = { sequence, frame, ack };
409
530
  this.pendingInput = pending;
410
531
  try {
@@ -434,6 +555,8 @@ export class BrokerTransport {
434
555
  this.pendingInput = undefined;
435
556
  }
436
557
  }
558
+ if (message)
559
+ await this.options.afterMessage?.(this.inputSequence);
437
560
  return;
438
561
  }
439
562
  catch (error) {
@@ -155,7 +155,7 @@ export function createClaudeLocalProvider(options) {
155
155
  });
156
156
  };
157
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)
158
+ row.runtime = { ...underlying, localDirectory: { ...workspace.directory }, 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)
159
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) };
160
160
  entries.set(request.sessionId, row);
161
161
  const endpointAborted = () => {
@@ -0,0 +1,17 @@
1
+ import { type BrokerIo } from './broker.ts';
2
+ import { type ColdRound, type ColdStore } from './cold-store.ts';
3
+ import { type StreamChunk, type ContentBlock, type TokenUsage } from '@deepseek-ai/dsh-llm';
4
+ export interface ColdPrefix {
5
+ blocks: readonly ContentBlock[];
6
+ usage?: TokenUsage;
7
+ }
8
+ export declare function recoverColdProtocol(record: ColdRound, store: ColdStore, prefix: ColdPrefix, options: {
9
+ io: BrokerIo;
10
+ maxFrameBytes: number;
11
+ maxMessageBytes: number;
12
+ signal?: AbortSignal;
13
+ markerId?: string;
14
+ cancelOnly?: boolean;
15
+ }): AsyncGenerator<StreamChunk>;
16
+ /** 本地未派发取消的证明来自写前记录或S消息回执,不伪造原生RPC终态。 */
17
+ export declare function recoverLocalCancellation(record: ColdRound, store: ColdStore, markerId: string): AsyncGenerator<StreamChunk>;