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

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.15 · 插件 → 添加插件
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.15`,从 `v0.9.0-toolbridge.14` 派生,使用 `host-toolbridge` 发布渠道。员工安装由连接组件提供的「AI 写作工作台(含工具桥)」总包 `@ai-workbench/workbench-toolbridge@0.1.12`,与不含工具桥的版本二选一。
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.js CHANGED
@@ -641,11 +641,18 @@ export class AcpSession {
641
641
  this.turnToken = Symbol('turn');
642
642
  let rejectAbort;
643
643
  const interrupted = new Promise((_resolve, reject) => { rejectAbort = reject; });
644
+ const requestAbort = new AbortController();
644
645
  const cancel = () => {
646
+ if (signal?.reason?.kind === 'disposed') {
647
+ this.close({ layer: 'acp', initiator: 'acp.owner-disposed', reason: 'SESSION_DETACHED', action: 'detach' });
648
+ rejectAbort?.(new NeedError('ABORTED', '客户端已退出,主机原轮保留,未发送取消', '原轮冷恢复'));
649
+ return;
650
+ }
645
651
  if (this.closeRequested) {
646
652
  rejectAbort?.(new NeedError('ABORTED', '客户端已分离,未重发或取消主机原轮', '原轮恢复状态'));
647
653
  return;
648
654
  }
655
+ requestAbort.abort(signal?.reason);
649
656
  this.closeDiagnostics.record({ layer: 'acp', initiator: 'acp.prompt-cancel', reason: 'ABORTED', operation: 'session/prompt', action: 'abort' });
650
657
  rejectAbort?.(new NeedError('ABORTED', '已请求取消本轮,远端状态需确认', '确认主机取消状态'));
651
658
  void this.connection.agent.notify(acp.methods.agent.session.cancel, { sessionId: this.sessionId }).catch(() => {
@@ -657,7 +664,7 @@ export class AcpSession {
657
664
  this.flushBridgeStartupNotice();
658
665
  const result = await this.stage('acp-prompt', () => {
659
666
  this.promptPermissions.set(params, { current, native });
660
- const request = this.connection.agent.request(acp.methods.agent.session.prompt, params, { cancellationSignal: signal });
667
+ const request = this.connection.agent.request(acp.methods.agent.session.prompt, params, { cancellationSignal: requestAbort.signal });
661
668
  return signal ? Promise.race([request, interrupted]) : request;
662
669
  });
663
670
  signal?.throwIfAborted();
@@ -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,34 @@ 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();
41
+ if (coldStore)
42
+ 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 });
43
+ const beforeMessage = coldStore ? async (bytes, message) => {
44
+ const rpc = JSON.parse(Buffer.from(bytes).toString('utf8'));
45
+ let record = await coldStore.update(request.sessionId, agent.id, roundId, row => {
46
+ if (rpc.method && Object.hasOwn(rpc, 'id') && !row.rpcIds.includes(rpc.id))
47
+ row.rpcIds.push(rpc.id);
48
+ 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 } : {}) };
49
+ if (rpc.method === 'session/prompt') {
50
+ if (!row.meta || row.nativeId !== rpc.params?.sessionId || row.promptId)
51
+ throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '原轮归属未完成持久登记,未发送输入', '完整冷恢复快照');
52
+ row.promptId = String(rpc.id);
53
+ row.promptSha256 = message.sha256;
54
+ row.promptBytes = bytes.length;
55
+ row.phase = 'running';
56
+ }
57
+ });
58
+ if (rpc.method === 'session/prompt') {
59
+ 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)])));
60
+ if (!Number.isSafeInteger(bound.round?.outputStartSequence))
61
+ throw new NeedError('BROKER_PROTOCOL_INVALID', '原轮输出起点未确认', '原轮绑定回执');
62
+ await coldStore.update(request.sessionId, agent.id, roundId, row => { row.outputStart = bound.round.outputStartSequence; });
63
+ }
64
+ } : undefined;
65
+ 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))
66
+ row.answered.push(row.pending.rpcId); row.inputSequence = sequence; delete row.pending; }); } : undefined;
67
+ 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, 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
68
  const reconnectOff = started.inputProtocolVersion === 2 ? _get()?.onConnectionState?.(state => { if (state.phase === 'connected' && !channel.online)
41
69
  void channel.connect().catch(() => { }); }) : undefined;
42
70
  let ended = false;
@@ -76,6 +104,6 @@ export function brokerFactory(_get, _ask, configuration, provided) {
76
104
  finally {
77
105
  request.signal?.removeEventListener('abort', aborted);
78
106
  }
79
- return { identity: identity(target), cwd: project.path, closeDiagnostics: diagnostics, broker: channel, sessionOwnership, acpTransport: channel, dispose, detach: channel.supportsRecovery ? detach : dispose };
107
+ return { ...(coldStore ? { cold: { id: roundId, store: coldStore, 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
108
  };
81
109
  }
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,19 @@ export interface BrokerOptions {
12
13
  attach: (after?: number) => Promise<Attachment>;
13
14
  inputProtocolVersion?: 2;
14
15
  recoverDisconnect?: boolean;
16
+ messageInput?: boolean;
17
+ initialSequence?: number;
18
+ restoreInput?: {
19
+ sequence: number;
20
+ pending?: ColdWrite;
21
+ };
22
+ beforeMessage?: (bytes: Uint8Array, message: {
23
+ id: string;
24
+ sha256: string;
25
+ chunkBytes: number;
26
+ baseSequence: number;
27
+ }) => Promise<void>;
28
+ afterMessage?: (sequence: number) => Promise<void>;
15
29
  onNeed?: (need: Need) => void;
16
30
  }
17
31
  /** One byte stream / SDK app over one SSH attachment of a new agent. Input is never replayed. */
@@ -22,6 +36,16 @@ export declare class BrokerTransport {
22
36
  private output;
23
37
  private attachment?;
24
38
  private cursor;
39
+ get lastSequence(): number;
40
+ private receipt;
41
+ get inputReceipt(): any;
42
+ private controlWait?;
43
+ private resendControl;
44
+ private controlMessage;
45
+ completeRestoredInput(): void;
46
+ discardMessage(id: string): Promise<any>;
47
+ observeMessage(id: string): Promise<any>;
48
+ resumeMessage(write: ColdWrite): Promise<void>;
25
49
  private attachedId?;
26
50
  get attachmentId(): string | undefined;
27
51
  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,28 @@ export class BrokerTransport {
11
12
  output;
12
13
  attachment;
13
14
  cursor = 0;
15
+ get lastSequence() { return this.cursor; }
16
+ receipt;
17
+ get inputReceipt() { return this.receipt; }
18
+ controlWait;
19
+ resendControl() { const wait = this.controlWait; if (wait && this.online) {
20
+ const child = this.attachment;
21
+ child.stdin.write(JSON.stringify({ type: wait.kind === 'discard' ? 'discard-input' : 'observe-input', messageId: wait.id }) + '\n', error => { if (error)
22
+ child.kill('SIGTERM'); });
23
+ } }
24
+ async controlMessage(kind, id) { await this.waitInput(); if (this.controlWait)
25
+ throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '原输入观察尚未结束', '串行消息回执'); const ready = Promise.withResolvers(); this.controlWait = { kind, id, ready }; this.resendControl(); try {
26
+ return await ready.promise;
27
+ }
28
+ finally {
29
+ this.controlWait = undefined;
30
+ } }
31
+ completeRestoredInput() { this.options.restoreInput = undefined; }
32
+ discardMessage(id) { return this.controlMessage('discard', id); }
33
+ observeMessage(id) { return this.controlMessage('observe', id); }
34
+ async resumeMessage(write) { const bytes = Buffer.from(write.wire, 'base64'), skip = this.inputSequence - write.baseSequence; if (skip < 0 || skip > write.chunks)
35
+ throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '原输入水位越界,没有重复写入', '原输入提交回执'); if (skip === write.chunks)
36
+ return; await this.send(bytes, { id: write.id, sha256: write.sha256, chunkBytes: write.chunkBytes, offset: skip * write.chunkBytes }); }
14
37
  attachedId;
15
38
  get attachmentId() { return this.attachedId; }
16
39
  inputSequence = 0;
@@ -85,6 +108,8 @@ export class BrokerTransport {
85
108
  if (!Number.isSafeInteger(options.maxFrameBytes) || options.maxFrameBytes < 1)
86
109
  throw new NeedError('SETTINGS_REQUIRED', '我需要 brokerMaxFrameBytes', '管理员确认 brokerMaxFrameBytes');
87
110
  this.options = options;
111
+ this.cursor = options.initialSequence ?? 0;
112
+ this.inputSequence = options.restoreInput?.sequence ?? 0;
88
113
  this.inputReady = options.inputProtocolVersion !== 2;
89
114
  this.lease.abort();
90
115
  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 +140,7 @@ export class BrokerTransport {
115
140
  this.attached = false;
116
141
  this.lease.abort();
117
142
  this.pendingInput?.ack.reject(error);
143
+ this.controlWait?.ready.reject(error);
118
144
  this.notice(error.code, error.message);
119
145
  this.changed();
120
146
  this.attachment?.kill('SIGTERM');
@@ -132,6 +158,7 @@ export class BrokerTransport {
132
158
  this.attached = false;
133
159
  this.lease.abort();
134
160
  this.pendingInput?.ack.reject(new NeedError('CONNECTION_LOST', '原轮已经关闭,输入未重发', '原轮状态'));
161
+ this.controlWait?.ready.reject(new NeedError('CONNECTION_LOST', '原流已结束,控制回执未确认', '原消息终态'));
135
162
  this.changed();
136
163
  this.attachment?.kill('SIGTERM');
137
164
  try {
@@ -196,8 +223,18 @@ export class BrokerTransport {
196
223
  const receipt = f.inputReceipt;
197
224
  if (f.inputProtocolVersion !== 2 || !receipt || receipt.failed !== false)
198
225
  throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '主机不能确认原输入字节水位,未重发输入。', 'inputProtocolVersion 2的有效回执');
199
- this.acknowledge(receipt.committedSequence);
200
- if (receipt.pendingSequence !== null && receipt.pendingSequence !== this.pendingInput?.sequence)
226
+ if (this.options.messageInput && this.options.restoreInput && !this.pendingInput && this.inputSequence <= this.options.restoreInput.sequence + (this.options.restoreInput.pending?.chunks ?? 0)) {
227
+ const sequence = receipt.committedSequence, restore = this.options.restoreInput, pending = restore.pending, r = receipt;
228
+ 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)))
229
+ throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '原输入水位不属于本轮,未跳过输入', '原消息身份及提交水位');
230
+ this.inputSequence = sequence;
231
+ }
232
+ else
233
+ this.acknowledge(receipt.committedSequence);
234
+ this.receipt = receipt;
235
+ if (this.options.messageInput && f.messageInputProtocolVersion !== 1)
236
+ throw new NeedError('BROKER_PROTOCOL_INVALID', '主机缺少完整消息暂存协议', 'messageInputProtocolVersion 1');
237
+ 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
238
  throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '主机在途输入不属于本客户端', '原客户端在途输入');
202
239
  if (typeof f.attachmentId !== 'string' || !f.attachmentId)
203
240
  throw new NeedError('BROKER_PROTOCOL_INVALID', '主机缺少写者实例标识', '本次attachmentId');
@@ -212,9 +249,22 @@ export class BrokerTransport {
212
249
  this.attached = true;
213
250
  this.lease = new AbortController();
214
251
  this.changed();
252
+ this.resendControl();
215
253
  connected.resolve();
216
254
  return;
217
255
  }
256
+ if (f.type === 'input-discarded' || f.type === 'input-observed') {
257
+ const wait = this.controlWait;
258
+ if (!wait || f.messageId !== wait.id)
259
+ throw new NeedError('BROKER_PROTOCOL_INVALID', '输入控制回执不匹配', '原消息标识');
260
+ this.receipt = f.inputReceipt;
261
+ const r = f.inputReceipt;
262
+ if (!Number.isSafeInteger(r?.committedSequence) || r.committedSequence < this.inputSequence)
263
+ throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '输入控制水位倒退', '原消息终态');
264
+ this.inputSequence = r.committedSequence;
265
+ wait.ready.resolve(r);
266
+ return;
267
+ }
218
268
  if (f.type === 'input-ack') {
219
269
  if (this.options.inputProtocolVersion !== 2)
220
270
  throw new NeedError('BROKER_PROTOCOL_INVALID', '未协商输入确认', 'inputProtocolVersion 2');
@@ -224,12 +274,12 @@ export class BrokerTransport {
224
274
  if (f.type === 'replay-complete') {
225
275
  if (this.options.inputProtocolVersion !== 2 || f.sequence !== this.cursor)
226
276
  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'));
277
+ this.output.enqueue(Buffer.from(JSON.stringify({ jsonrpc: '2.0', method: '_aw/broker-replay-complete', params: { generation: this.epoch, pendingClientRequests: f.pendingClientRequests } }) + '\n'));
228
278
  return;
229
279
  }
230
280
  if (f.type === 'error') {
231
281
  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 + ');没有重放输入或代答审批', '恢复或显式结束原会话');
282
+ const error = new NeedError(code, f.reason === 'OUTPUT_JOURNAL_FAILED' ? '主机输出持久保存失败(' + String(f.systemCode) + '),原轮结果未确认,没有重放。' : '主机会话无法续接(' + code + ');没有重放输入或代答审批', '恢复或显式结束原会话');
233
283
  if (ready && code === 'ATTACH_LEASE_EXPIRED' && this.supportsRecovery) {
234
284
  attemptClosed = true;
235
285
  this.stopHeartbeat();
@@ -256,6 +306,7 @@ export class BrokerTransport {
256
306
  this.attached = false;
257
307
  this.lease.abort();
258
308
  this.pendingInput?.ack.reject(new NeedError('AGENT_EXITED', '主机进程已退出,未重发输入', '原轮结果'));
309
+ this.controlWait?.ready.reject(new NeedError('AGENT_EXITED', '主机进程已退出,输入控制回执未确认', '原消息终态'));
259
310
  this.changed();
260
311
  this.output.close();
261
312
  return;
@@ -333,7 +384,7 @@ export class BrokerTransport {
333
384
  return connected.promise.finally(off);
334
385
  }
335
386
  write(bytes) { return this.exclusive(() => this.send(bytes)); }
336
- async send(bytes) {
387
+ async send(bytes, resume) {
337
388
  if (this.supportsRecovery)
338
389
  await this.waitInput();
339
390
  if (!this.online || !this.attachment)
@@ -383,28 +434,31 @@ export class BrokerTransport {
383
434
  if (prompt && this.promptPermit === promptPermit)
384
435
  this.promptPermit = undefined;
385
436
  const chunks = [];
386
- let chunkBytes = bytes.byteLength;
437
+ let chunkBytes = resume?.chunkBytes ?? bytes.byteLength;
438
+ const message = this.options.messageInput ? resume ?? { id: randomUUID(), sha256: createHash('sha256').update(bytes).digest('hex') } : undefined;
387
439
  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;
440
+ 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
441
  if (size < 1)
390
442
  throw new NeedError('LEASE_CAPACITY_INVALID', '主机会话容量无法承载输入', '有效controlMaxBytes');
391
- chunkBytes = size;
443
+ chunkBytes = resume?.chunkBytes ?? size;
392
444
  if (this.options.inputProtocolVersion !== 2)
393
445
  for (let offset = 0; offset < bytes.byteLength; offset += size)
394
446
  chunks.push(Buffer.from(JSON.stringify({ type: 'input', data: Buffer.from(bytes.subarray(offset, offset + size)).toString('base64') }) + '\n'));
395
447
  }
396
448
  else
397
449
  chunks.push(Buffer.from(bytes));
450
+ if (message && !resume)
451
+ await this.options.beforeMessage?.(bytes, { ...message, chunkBytes, baseSequence: this.inputSequence });
398
452
  if (this.options.inputProtocolVersion === 2) {
399
453
  try {
400
- for (let offset = 0; offset < bytes.byteLength; offset += chunkBytes) {
454
+ for (let offset = resume?.offset ?? 0; offset < bytes.byteLength; offset += chunkBytes) {
401
455
  const chunk = bytes.subarray(offset, offset + chunkBytes);
402
456
  await this.waitInput();
403
457
  if (prompt)
404
458
  currentPrompt();
405
459
  const sequence = this.inputSequence + 1, ack = Promise.withResolvers();
406
460
  void ack.promise.catch(() => { });
407
- const frame = Buffer.from(JSON.stringify({ type: 'input', sequence, data: Buffer.from(chunk).toString('base64') }) + '\n');
461
+ 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
462
  const pending = { sequence, frame, ack };
409
463
  this.pendingInput = pending;
410
464
  try {
@@ -434,6 +488,8 @@ export class BrokerTransport {
434
488
  this.pendingInput = undefined;
435
489
  }
436
490
  }
491
+ if (message)
492
+ await this.options.afterMessage?.(this.inputSequence);
437
493
  return;
438
494
  }
439
495
  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,14 @@
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
+ }): AsyncGenerator<StreamChunk>;