@ai-workbench/remote-agent 0.9.0-toolbridge.15 → 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 +2 -2
- package/dist/acp.d.ts +2 -1
- package/dist/acp.js +15 -11
- package/dist/broker-runtime.js +32 -20
- package/dist/broker.d.ts +17 -0
- package/dist/broker.js +68 -1
- package/dist/cold-protocol.d.ts +3 -0
- package/dist/cold-protocol.js +103 -34
- package/dist/cold-recovery.d.ts +12 -2
- package/dist/cold-recovery.js +214 -43
- package/dist/cold-store.d.ts +11 -2
- package/dist/index.js +24 -6
- package/dist/provider.d.ts +3 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
# AI Workbench 远程助手 · @ai-workbench/remote-agent@0.9.0-toolbridge.
|
|
1
|
+
# AI Workbench 远程助手 · @ai-workbench/remote-agent@0.9.0-toolbridge.16 · 插件 → 添加插件
|
|
2
2
|
|
|
3
3
|
## 含工具桥预发布线
|
|
4
4
|
|
|
5
|
-
本包为 `0.9.0-toolbridge.
|
|
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
|
|
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:
|
|
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
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
if (raw?.method === acp.methods.client.session.update && typeof update?.sessionUpdate === 'string' && !knownUpdates.has(update.sessionUpdate)) {
|
|
496
|
-
this.
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
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
|
}
|
|
@@ -742,3 +745,4 @@ export function acpNeed(error) {
|
|
|
742
745
|
function record(value) { return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : undefined; }
|
|
743
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']);
|
|
744
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);
|
package/dist/broker-runtime.js
CHANGED
|
@@ -37,34 +37,46 @@ export function brokerFactory(_get, _ask, configuration, provided) {
|
|
|
37
37
|
throw new NeedError(started.code, '主机的环境配置会覆盖本机执行位置,本轮已停止;请由管理员移开该配置后在原会话重试。', '主机 CODEX_HOME/environments.toml 不存在');
|
|
38
38
|
if (started.protocolVersion !== 1 || started.id !== id || !started.instanceId)
|
|
39
39
|
throw new NeedError('BROKER_PROTOCOL_INVALID', '主机会话未能启动,请恢复连接后再试。', '有效的主机会话启动回应');
|
|
40
|
-
const coldStore = started.messageInputProtocolVersion === 1 ? provided?.coldStore : undefined, roundId = newColdId();
|
|
40
|
+
const coldStore = started.messageInputProtocolVersion === 1 ? provided?.coldStore : undefined, roundId = newColdId(), boundOrigin = Promise.withResolvers();
|
|
41
|
+
void boundOrigin.promise.catch(() => { });
|
|
41
42
|
if (coldStore)
|
|
42
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 });
|
|
43
44
|
const beforeMessage = coldStore ? async (bytes, message) => {
|
|
44
45
|
const rpc = JSON.parse(Buffer.from(bytes).toString('utf8'));
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
row.rpcIds.
|
|
48
|
-
|
|
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
|
+
});
|
|
49
62
|
if (rpc.method === 'session/prompt') {
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
row.
|
|
54
|
-
|
|
55
|
-
row.phase = 'running';
|
|
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);
|
|
56
68
|
}
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
await coldStore.update(request.sessionId, agent.id, roundId, row => { row.outputStart = bound.round.outputStartSequence; });
|
|
69
|
+
}
|
|
70
|
+
catch (error) {
|
|
71
|
+
if (rpc.method === 'session/prompt')
|
|
72
|
+
boundOrigin.reject(error);
|
|
73
|
+
throw error;
|
|
63
74
|
}
|
|
64
75
|
} : undefined;
|
|
65
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))
|
|
66
|
-
row.answered.push(row.pending.rpcId); row.
|
|
67
|
-
|
|
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])) });
|
|
68
80
|
const reconnectOff = started.inputProtocolVersion === 2 ? _get()?.onConnectionState?.(state => { if (state.phase === 'connected' && !channel.online)
|
|
69
81
|
void channel.connect().catch(() => { }); }) : undefined;
|
|
70
82
|
let ended = false;
|
|
@@ -104,6 +116,6 @@ export function brokerFactory(_get, _ask, configuration, provided) {
|
|
|
104
116
|
finally {
|
|
105
117
|
request.signal?.removeEventListener('abort', aborted);
|
|
106
118
|
}
|
|
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 };
|
|
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 };
|
|
108
120
|
};
|
|
109
121
|
}
|
package/dist/broker.d.ts
CHANGED
|
@@ -14,6 +14,7 @@ export interface BrokerOptions {
|
|
|
14
14
|
inputProtocolVersion?: 2;
|
|
15
15
|
recoverDisconnect?: boolean;
|
|
16
16
|
messageInput?: boolean;
|
|
17
|
+
outputOrigins?: boolean;
|
|
17
18
|
initialSequence?: number;
|
|
18
19
|
restoreInput?: {
|
|
19
20
|
sequence: number;
|
|
@@ -37,6 +38,22 @@ export declare class BrokerTransport {
|
|
|
37
38
|
private attachment?;
|
|
38
39
|
private cursor;
|
|
39
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;
|
|
40
57
|
private receipt;
|
|
41
58
|
get inputReceipt(): any;
|
|
42
59
|
private controlWait?;
|
package/dist/broker.js
CHANGED
|
@@ -13,6 +13,64 @@ export class BrokerTransport {
|
|
|
13
13
|
attachment;
|
|
14
14
|
cursor = 0;
|
|
15
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; }
|
|
16
74
|
receipt;
|
|
17
75
|
get inputReceipt() { return this.receipt; }
|
|
18
76
|
controlWait;
|
|
@@ -232,6 +290,8 @@ export class BrokerTransport {
|
|
|
232
290
|
else
|
|
233
291
|
this.acknowledge(receipt.committedSequence);
|
|
234
292
|
this.receipt = receipt;
|
|
293
|
+
if (typeof f.promptDelivered === 'boolean')
|
|
294
|
+
this.promptReceipt = f.promptDelivered;
|
|
235
295
|
if (this.options.messageInput && f.messageInputProtocolVersion !== 1)
|
|
236
296
|
throw new NeedError('BROKER_PROTOCOL_INVALID', '主机缺少完整消息暂存协议', 'messageInputProtocolVersion 1');
|
|
237
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))
|
|
@@ -275,6 +335,8 @@ export class BrokerTransport {
|
|
|
275
335
|
if (this.options.inputProtocolVersion !== 2 || f.sequence !== this.cursor)
|
|
276
336
|
throw new NeedError('REPLAY_GAP', '原轮回放水位未连续', '完整原轮回放');
|
|
277
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));
|
|
278
340
|
return;
|
|
279
341
|
}
|
|
280
342
|
if (f.type === 'error') {
|
|
@@ -301,6 +363,11 @@ export class BrokerTransport {
|
|
|
301
363
|
throw error;
|
|
302
364
|
}
|
|
303
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
|
+
}
|
|
304
371
|
this.stopHeartbeat();
|
|
305
372
|
this.ended = true;
|
|
306
373
|
this.attached = false;
|
|
@@ -324,7 +391,7 @@ export class BrokerTransport {
|
|
|
324
391
|
if (seq !== this.cursor + 1)
|
|
325
392
|
throw new NeedError('REPLAY_GAP', '主机输出存在缺口,不能安全继续审批', '显式结束或恢复原会话');
|
|
326
393
|
if (f.channel === 'stdout') {
|
|
327
|
-
this.
|
|
394
|
+
this.stdout(Buffer.from(f.data, 'base64'), seq);
|
|
328
395
|
}
|
|
329
396
|
this.cursor = seq;
|
|
330
397
|
this.changed();
|
package/dist/cold-protocol.d.ts
CHANGED
|
@@ -11,4 +11,7 @@ export declare function recoverColdProtocol(record: ColdRound, store: ColdStore,
|
|
|
11
11
|
maxMessageBytes: number;
|
|
12
12
|
signal?: AbortSignal;
|
|
13
13
|
markerId?: string;
|
|
14
|
+
cancelOnly?: boolean;
|
|
14
15
|
}): AsyncGenerator<StreamChunk>;
|
|
16
|
+
/** 本地未派发取消的证明来自写前记录或S消息回执,不伪造原生RPC终态。 */
|
|
17
|
+
export declare function recoverLocalCancellation(record: ColdRound, store: ColdStore, markerId: string): AsyncGenerator<StreamChunk>;
|
package/dist/cold-protocol.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isKnownAcpUpdate } from "./acp.js";
|
|
1
2
|
import { randomUUID } from 'node:crypto';
|
|
2
3
|
import * as acp from '@agentclientprotocol/sdk/unstable';
|
|
3
4
|
import { BrokerTransport, brokerCommand, controlJson } from "./broker.js";
|
|
@@ -57,9 +58,15 @@ export async function* recoverColdProtocol(record, store, prefix, options) {
|
|
|
57
58
|
else if (bound.round.outputStartSequence !== record.outputStart)
|
|
58
59
|
throw coldNeed('SESSION_CONTEXT_MISMATCH');
|
|
59
60
|
let broker;
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
61
|
+
let promptConfirmed = false, localCancellation = false, nativeTerminalSeen = false, cancelHandled = false;
|
|
62
|
+
let cancellationWake = () => { };
|
|
63
|
+
let cancelNote;
|
|
64
|
+
const beforeMessage = async (bytes, m) => { const rpc = JSON.parse(Buffer.from(bytes).toString()); await store.update(record.sessionId, record.provider, record.id, row => { if (rpc.method === 'session/cancel' && rpc.params?.sessionId === row.nativeId || rpc.method === '$/cancel_request' && String(rpc.params?.requestId) === row.promptId)
|
|
65
|
+
row.cancelIntent ??= { source: 'wire' }; row.pending = { id: m.id, sha256: m.sha256, wire: Buffer.from(bytes).toString('base64'), baseSequence: m.baseSequence, chunkBytes: m.chunkBytes, chunks: Math.ceil(bytes.length / m.chunkBytes), ...(rpc.method ? { method: rpc.method } : {}), ...(Object.hasOwn(rpc, 'id') ? { rpcId: rpc.id } : {}) }; }); };
|
|
66
|
+
const afterMessage = async (sequence) => { const method = record.pending?.method; record = await store.update(record.sessionId, record.provider, record.id, row => { if (row.pending && !row.pending.method && row.pending.rpcId !== undefined && !row.answered.includes(row.pending.rpcId))
|
|
67
|
+
row.answered.push(row.pending.rpcId); if (row.pending && ['session/cancel', '$/cancel_request'].includes(row.pending.method ?? '') && row.cancelIntent)
|
|
68
|
+
row.cancelIntent.delivered = true; row.inputSequence = sequence; delete row.pending; }); if (method === 'session/prompt')
|
|
69
|
+
promptConfirmed = true; broker.completeRestoredInput(); };
|
|
63
70
|
broker = new BrokerTransport({ maxFrameBytes: options.maxFrameBytes, controlMaxBytes: record.controlMaxBytes, leased: true, inputProtocolVersion: 2, messageInput: true, recoverDisconnect: true, instanceId: record.instanceId, initialSequence: record.outputStart, restoreInput: { sequence: record.inputSequence, pending: record.pending }, beforeMessage, afterMessage, attach: (after = 0) => options.io.attach(command(['attach', record.brokerId, '--after', String(after), '--framed', '--leased', '--input-protocol', '2', '--message-input', '--if-instance', record.instanceId, '--cold-round', record.id, '--prompt-id', record.promptId, ...owner])) });
|
|
64
71
|
const raw = acp.ndJsonStream(broker.writable, broker.readable, { maxMessageBytes: options.maxMessageBytes }), reader = raw.readable.getReader(), writer = raw.writable.getWriter();
|
|
65
72
|
const mapper = new StreamMapper(record.meta.baseline), output = new StreamMapper(), trim = new Prefix(prefix);
|
|
@@ -70,10 +77,10 @@ export async function* recoverColdProtocol(record, store, prefix, options) {
|
|
|
70
77
|
const replayOff = broker.onChange(() => { if (!broker.online)
|
|
71
78
|
replayed = false; });
|
|
72
79
|
const send = async (message) => { await writer.write(message); };
|
|
73
|
-
const cancel = () => { if (options.signal?.reason?.kind
|
|
80
|
+
const cancel = () => { if (options.signal?.reason?.kind !== 'user') {
|
|
74
81
|
broker.close();
|
|
75
82
|
return;
|
|
76
|
-
}
|
|
83
|
+
} cancelNote = store.update(record.sessionId, record.provider, record.id, row => { row.cancelIntent ??= { source: 'user-signal' }; }).then(row => { record = row; broker.close(); }, error => { broker.fail(error instanceof NeedError ? error : coldNeed()); throw error; }); void cancelNote.catch(() => { }); };
|
|
77
84
|
options.signal?.addEventListener('abort', cancel, { once: true });
|
|
78
85
|
const projection = function* (chunks) { for (const chunk of chunks) {
|
|
79
86
|
if (chunk.type === 'text-delta' || chunk.type === 'reasoning-delta') {
|
|
@@ -111,6 +118,10 @@ export async function* recoverColdProtocol(record, store, prefix, options) {
|
|
|
111
118
|
const saved = record.pending;
|
|
112
119
|
let pendingAction = false;
|
|
113
120
|
const settleOrphans = async () => { for (const [key, m] of pendingRequests) {
|
|
121
|
+
if (localCancellation) {
|
|
122
|
+
pendingRequests.clear();
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
114
125
|
if (record.answered.some(id => JSON.stringify(id) === key)) {
|
|
115
126
|
pendingRequests.delete(key);
|
|
116
127
|
continue;
|
|
@@ -132,7 +143,25 @@ export async function* recoverColdProtocol(record, store, prefix, options) {
|
|
|
132
143
|
}
|
|
133
144
|
const rpc = JSON.parse(Buffer.from(saved.wire, 'base64').toString());
|
|
134
145
|
const permittedCancel = saved.method === 'session/cancel' && rpc.params?.sessionId === record.nativeId || saved.method === '$/cancel_request' && String(rpc.params?.requestId) === record.promptId;
|
|
135
|
-
if (saved.method === 'session/prompt'
|
|
146
|
+
if (saved.method === 'session/prompt') {
|
|
147
|
+
record = (await store.read(record.sessionId, record.provider));
|
|
148
|
+
if (record.cancelIntent) {
|
|
149
|
+
if (receipt.stagedMessageId === saved.id || receipt.lastMessage?.id === saved.id && receipt.lastMessage?.state === 'discarded')
|
|
150
|
+
receipt = await broker.discardMessage(saved.id);
|
|
151
|
+
else if (receipt.committedSequence !== saved.baseSequence || receipt.pendingSequence !== null || receipt.stagedMessageId)
|
|
152
|
+
throw coldNeed();
|
|
153
|
+
record = await store.update(record.sessionId, record.provider, record.id, row => { row.inputSequence = receipt.committedSequence; delete row.pending; row.cancelCheckpoint = { inputNotDelivered: true, receipt }; row.terminal = { kind: 'local-cancel', value: { inputNotDelivered: true } }; row.phase = 'terminal'; row.finalUsage = row.meta.baseline; });
|
|
154
|
+
broker.completeRestoredInput();
|
|
155
|
+
localCancellation = true;
|
|
156
|
+
cancellationWake();
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
broker.authorizePrompt(() => !options.signal?.aborted && !record.cancelIntent);
|
|
160
|
+
await broker.resumeMessage(saved);
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
if (permittedCancel) {
|
|
164
|
+
record = await store.update(record.sessionId, record.provider, record.id, row => { row.cancelIntent ??= { source: 'wire' }; });
|
|
136
165
|
await broker.resumeMessage(saved);
|
|
137
166
|
return;
|
|
138
167
|
}
|
|
@@ -144,45 +173,58 @@ export async function* recoverColdProtocol(record, store, prefix, options) {
|
|
|
144
173
|
record = await store.update(record.sessionId, record.provider, record.id, row => { row.inputSequence = receipt.committedSequence; delete row.pending; });
|
|
145
174
|
broker.completeRestoredInput();
|
|
146
175
|
};
|
|
176
|
+
const cancelOriginal = async () => { record = (await store.read(record.sessionId, record.provider)); if (record.cancelCheckpoint?.inputNotDelivered) {
|
|
177
|
+
localCancellation = true;
|
|
178
|
+
cancellationWake();
|
|
179
|
+
return;
|
|
180
|
+
} if (!record.cancelIntent || record.cancelIntent.delivered || nativeTerminalSeen)
|
|
181
|
+
return; if (!promptConfirmed && broker.promptDelivered !== true)
|
|
182
|
+
throw coldNeed(); await send({ jsonrpc: '2.0', method: 'session/cancel', params: { sessionId: record.nativeId } }); };
|
|
147
183
|
const incoming = [];
|
|
148
184
|
let readDone = false, readFailure, wake;
|
|
149
185
|
const notify = () => { wake?.(); wake = undefined; };
|
|
186
|
+
cancellationWake = notify;
|
|
150
187
|
const pump = (async () => {
|
|
151
188
|
try {
|
|
152
189
|
for (;;) {
|
|
153
190
|
const item = await reader.read();
|
|
154
191
|
if (item.done)
|
|
155
192
|
break;
|
|
156
|
-
const
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
193
|
+
const batch = Array.isArray(item.value) ? item.value : [item.value];
|
|
194
|
+
for (const m of batch) {
|
|
195
|
+
if (m.method === '_aw/broker-replay-complete') {
|
|
196
|
+
broker.confirmReplay(m.params?.generation);
|
|
197
|
+
replayed = true;
|
|
198
|
+
notify();
|
|
199
|
+
if (Array.isArray(m.params?.pendingClientRequests)) {
|
|
200
|
+
const ids = new Set(m.params.pendingClientRequests.map((r) => JSON.stringify(r.id)));
|
|
201
|
+
for (const key of pendingRequests.keys())
|
|
202
|
+
if (!ids.has(key))
|
|
203
|
+
pendingRequests.delete(key);
|
|
204
|
+
}
|
|
205
|
+
if (!pendingAction) {
|
|
206
|
+
pendingAction = true;
|
|
207
|
+
enqueue(async () => { await restorePending(); await cancelOriginal(); cancelHandled = true; notify(); });
|
|
208
|
+
}
|
|
209
|
+
enqueue(settleOrphans);
|
|
210
|
+
continue;
|
|
165
211
|
}
|
|
166
|
-
if (
|
|
167
|
-
|
|
168
|
-
|
|
212
|
+
if (m.method && Object.hasOwn(m, 'id')) {
|
|
213
|
+
pendingRequests.set(JSON.stringify(m.id), m);
|
|
214
|
+
if (replayed)
|
|
215
|
+
enqueue(settleOrphans);
|
|
216
|
+
continue;
|
|
169
217
|
}
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
218
|
+
if (!m.method && Object.hasOwn(m, 'id') && String(m.id) === record.promptId)
|
|
219
|
+
nativeTerminalSeen = true;
|
|
220
|
+
if (terminalWaiting)
|
|
221
|
+
continue;
|
|
222
|
+
const consumed = Promise.withResolvers();
|
|
223
|
+
releasePump = consumed.resolve;
|
|
224
|
+
incoming.push(m);
|
|
225
|
+
notify();
|
|
226
|
+
await consumed.promise;
|
|
178
227
|
}
|
|
179
|
-
if (terminalWaiting)
|
|
180
|
-
continue;
|
|
181
|
-
const consumed = Promise.withResolvers();
|
|
182
|
-
releasePump = consumed.resolve;
|
|
183
|
-
incoming.push(m);
|
|
184
|
-
notify();
|
|
185
|
-
await consumed.promise;
|
|
186
228
|
}
|
|
187
229
|
}
|
|
188
230
|
catch (error) {
|
|
@@ -200,11 +242,21 @@ export async function* recoverColdProtocol(record, store, prefix, options) {
|
|
|
200
242
|
mapper.flush();
|
|
201
243
|
let nativeUpdates = 0, noticeIndex = 0;
|
|
202
244
|
const notices = function* () { while (record.localNotices?.[noticeIndex]?.beforeUpdate === nativeUpdates) {
|
|
203
|
-
|
|
245
|
+
const notice = record.localNotices[noticeIndex++];
|
|
246
|
+
yield* projection(mapper.text(notice.text, notice.kind === 'reasoning'));
|
|
204
247
|
} };
|
|
205
248
|
yield* notices();
|
|
206
249
|
for (;;) {
|
|
207
250
|
options.signal?.throwIfAborted();
|
|
251
|
+
if (options.cancelOnly && cancelHandled)
|
|
252
|
+
return;
|
|
253
|
+
if (localCancellation) {
|
|
254
|
+
yield* output.flush();
|
|
255
|
+
if (!options.markerId)
|
|
256
|
+
throw new NeedError('ABORTED', '原轮在送达前已取消,未执行', '原消息未派发回执');
|
|
257
|
+
yield* recoverLocalCancellation(record, store, options.markerId);
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
208
260
|
if (!incoming.length) {
|
|
209
261
|
if (readFailure)
|
|
210
262
|
throw readFailure;
|
|
@@ -219,6 +271,8 @@ export async function* recoverColdProtocol(record, store, prefix, options) {
|
|
|
219
271
|
if (m.method === 'session/update') {
|
|
220
272
|
if (m.params?.sessionId !== record.nativeId)
|
|
221
273
|
throw coldNeed('SESSION_CONTEXT_MISMATCH');
|
|
274
|
+
if (!isKnownAcpUpdate(m.params.update))
|
|
275
|
+
continue;
|
|
222
276
|
yield* projection(mapper.acp(m.params.update));
|
|
223
277
|
nativeUpdates++;
|
|
224
278
|
yield* notices();
|
|
@@ -231,9 +285,15 @@ export async function* recoverColdProtocol(record, store, prefix, options) {
|
|
|
231
285
|
continue;
|
|
232
286
|
}
|
|
233
287
|
terminalWaiting = true;
|
|
288
|
+
while (!replayed && !readDone)
|
|
289
|
+
await new Promise(resolve => { wake = resolve; });
|
|
290
|
+
if (!replayed)
|
|
291
|
+
throw readFailure ?? coldNeed();
|
|
234
292
|
await outboundTail;
|
|
235
293
|
if (readFailure)
|
|
236
294
|
throw readFailure;
|
|
295
|
+
if (options.cancelOnly)
|
|
296
|
+
return;
|
|
237
297
|
terminal = true;
|
|
238
298
|
await store.update(record.sessionId, record.provider, record.id, row => { row.terminal = { kind: m.error ? 'error' : 'result', value: m.error ?? m.result }; row.phase = 'terminal'; row.terminalAfter = broker.lastSequence; });
|
|
239
299
|
if (m.error) {
|
|
@@ -279,7 +339,16 @@ export async function* recoverColdProtocol(record, store, prefix, options) {
|
|
|
279
339
|
releasePump?.();
|
|
280
340
|
await outboundTail.catch(() => { });
|
|
281
341
|
await activePump;
|
|
342
|
+
await cancelNote?.catch(() => { });
|
|
282
343
|
reader.releaseLock();
|
|
283
344
|
writer.releaseLock();
|
|
284
345
|
}
|
|
285
346
|
}
|
|
347
|
+
/** 本地未派发取消的证明来自写前记录或S消息回执,不伪造原生RPC终态。 */
|
|
348
|
+
export async function* recoverLocalCancellation(record, store, markerId) {
|
|
349
|
+
if (!record.cancelIntent || !record.cancelCheckpoint?.inputNotDelivered || record.terminal?.kind !== 'local-cancel')
|
|
350
|
+
throw coldNeed();
|
|
351
|
+
const token = randomUUID(), message = '原轮已在送达前取消,没有执行或重新发送原任务;恢复回执 ' + token;
|
|
352
|
+
await store.update(record.sessionId, record.provider, record.id, row => { row.finalUsage = row.meta?.baseline ?? null; row.errorDelivery = { markerId, promptId: record.promptId, code: 'ABORTED', token, message }; });
|
|
353
|
+
throw new LlmError(message, 'ABORTED');
|
|
354
|
+
}
|
package/dist/cold-recovery.d.ts
CHANGED
|
@@ -25,6 +25,8 @@ export declare class ColdRecovery {
|
|
|
25
25
|
private queues;
|
|
26
26
|
private scheduled;
|
|
27
27
|
private live;
|
|
28
|
+
private lifetime;
|
|
29
|
+
private cancellationWatches;
|
|
28
30
|
private steps;
|
|
29
31
|
constructor(ctx: Context, getConnect: () => ConnectApi | undefined, config: () => {
|
|
30
32
|
acpMaxMessageBytes?: number;
|
|
@@ -36,12 +38,19 @@ export declare class ColdRecovery {
|
|
|
36
38
|
io?: (r: ColdRound) => BrokerIo;
|
|
37
39
|
argv?: SshArgv;
|
|
38
40
|
} | undefined);
|
|
41
|
+
dispose(): void;
|
|
39
42
|
events(sessionId: string, header?: SessionHeader): Promise<readonly SessionEvent[]>;
|
|
40
|
-
capture(runtime: Runtime, options: GenerateOptions, nativeId: string, meta: Omit<NonNullable<ColdRound['meta']>, 'header' | 'inputDigests'>): Promise<void>;
|
|
43
|
+
capture(runtime: Runtime, options: GenerateOptions, nativeId: string | undefined, meta: Omit<NonNullable<ColdRound['meta']>, 'header' | 'inputDigests'>): Promise<void>;
|
|
44
|
+
recordUserCancellation(runtime: Runtime, options: GenerateOptions, nativeId: string | undefined, fallback: Omit<NonNullable<ColdRound['meta']>, 'header' | 'inputDigests'>): Promise<void>;
|
|
45
|
+
private adoptUserCancellation;
|
|
41
46
|
private reconcile;
|
|
42
47
|
private queueSnapshot;
|
|
43
48
|
private schedule;
|
|
49
|
+
private settleUserCancellation;
|
|
50
|
+
private watchCancellation;
|
|
44
51
|
install(): void;
|
|
52
|
+
/** Official user cancellation is an input disposition even before a remote runtime exists. */
|
|
53
|
+
projectCancelledInputs(options: GenerateOptions): Promise<GenerateOptions>;
|
|
45
54
|
previousPointer(options: GenerateOptions): Promise<any>;
|
|
46
55
|
release(sessionId: string, id: string): void;
|
|
47
56
|
recoveryModel(provider: string, model: string, signal?: AbortSignal): (import("@deepseek-ai/dsh-llm").LlmResolvedModelInfo & {
|
|
@@ -49,5 +58,6 @@ export declare class ColdRecovery {
|
|
|
49
58
|
}) | undefined;
|
|
50
59
|
canRecover(options: GenerateOptions): boolean;
|
|
51
60
|
private connection;
|
|
52
|
-
stream(options: GenerateOptions): AsyncGenerator<StreamChunk>;
|
|
61
|
+
stream(options: GenerateOptions, lifetime?: AbortSignal): AsyncGenerator<StreamChunk>;
|
|
62
|
+
private streamRound;
|
|
53
63
|
}
|
package/dist/cold-recovery.js
CHANGED
|
@@ -7,12 +7,37 @@ import { expandAssistantStream, createUserMessage } from '@deepseek-ai/dsh-llm';
|
|
|
7
7
|
import { isDeepStrictEqual } from 'node:util';
|
|
8
8
|
import { createHash } from 'node:crypto';
|
|
9
9
|
import { createColdStore, coldNeed } from "./cold-store.js";
|
|
10
|
-
import { recoverColdProtocol } from "./cold-protocol.js";
|
|
10
|
+
import { recoverColdProtocol, recoverLocalCancellation } from "./cold-protocol.js";
|
|
11
11
|
import { sameStoredSessionHeader } from "./session-header.js";
|
|
12
12
|
import { awaitL, identity, unwrap } from "./provider.js";
|
|
13
13
|
import { sshIo } from "./broker.js";
|
|
14
14
|
const sourceKind = 'ai-workbench-cold-recovery';
|
|
15
15
|
export const recoveryMarker = (message) => message?.role === 'user' && message.source?.kind === sourceKind && typeof message.source?.roundId === 'string' ? message.source.roundId : undefined;
|
|
16
|
+
// Reconstruct only official, exact claims. A turn may stop after inbox.claim
|
|
17
|
+
// and before either step/start or user/message has been appended.
|
|
18
|
+
function inputClaims(events) {
|
|
19
|
+
const queues = { 'next-step': [], 'next-turn': [] }, claims = new Map();
|
|
20
|
+
let turn;
|
|
21
|
+
const add = (owner, message) => { const items = claims.get(owner) ?? new Map(); items.set(message.id, message); claims.set(owner, items); };
|
|
22
|
+
for (const event of events) {
|
|
23
|
+
if (event.type === 'turn/start')
|
|
24
|
+
turn = event.data.turn;
|
|
25
|
+
else if (event.type === 'turn/end')
|
|
26
|
+
turn = undefined;
|
|
27
|
+
else if (event.type === 'user/message' && turn !== undefined)
|
|
28
|
+
add(turn, event.data);
|
|
29
|
+
else if (event.type === 'agent/inbox/spliced') {
|
|
30
|
+
const { target, start, removedCount = 0, inserted, outcome } = event.data, queue = queues[target];
|
|
31
|
+
if (!queue || !Number.isSafeInteger(start) || start < 0 || start > queue.length || !Number.isSafeInteger(removedCount) || removedCount < 0 || start + removedCount > queue.length)
|
|
32
|
+
throw coldNeed('SESSION_CONTEXT_MISMATCH');
|
|
33
|
+
const removed = queue.splice(start, removedCount, ...inserted);
|
|
34
|
+
if (turn !== undefined && outcome !== 'canceled')
|
|
35
|
+
for (const message of removed)
|
|
36
|
+
add(turn, message);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return claims;
|
|
40
|
+
}
|
|
16
41
|
const digest = (message) => createHash('sha256').update(JSON.stringify(message)).digest('hex');
|
|
17
42
|
export class ColdRecovery {
|
|
18
43
|
ctx;
|
|
@@ -23,6 +48,8 @@ export class ColdRecovery {
|
|
|
23
48
|
queues = new WeakMap();
|
|
24
49
|
scheduled = new WeakMap();
|
|
25
50
|
live = new Map();
|
|
51
|
+
lifetime = new AbortController();
|
|
52
|
+
cancellationWatches = new Map();
|
|
26
53
|
steps = new Map();
|
|
27
54
|
constructor(ctx, getConnect, config, provided) {
|
|
28
55
|
this.ctx = ctx;
|
|
@@ -30,7 +57,10 @@ export class ColdRecovery {
|
|
|
30
57
|
this.config = config;
|
|
31
58
|
this.provided = provided;
|
|
32
59
|
this.store = provided?.store ?? createColdStore(ctx);
|
|
60
|
+
ctx.effect?.(() => () => this.dispose());
|
|
33
61
|
}
|
|
62
|
+
dispose() { this.lifetime.abort(Object.assign(new DOMException('原轮恢复已分离', 'AbortError'), { kind: 'disposed' })); for (const watch of this.cancellationWatches.values())
|
|
63
|
+
watch.off(); this.cancellationWatches.clear(); }
|
|
34
64
|
async events(sessionId, header) {
|
|
35
65
|
const sessions = this.ctx.get('sessions'), session = sessions?.get(SessionId(sessionId)), persistence = this.ctx.get('sessionPersistence');
|
|
36
66
|
if (!session || !persistence?.identity || !await sessions.flush(session))
|
|
@@ -89,13 +119,46 @@ export class ColdRecovery {
|
|
|
89
119
|
await this.store.update(options.sessionId, options.provider, runtime.cold.id, row => { row.originTurn = turn; row.originStep = step; });
|
|
90
120
|
this.live.set(options.sessionId, runtime.cold.id);
|
|
91
121
|
}
|
|
122
|
+
async recordUserCancellation(runtime, options, nativeId, fallback) {
|
|
123
|
+
if (!runtime.cold || !options.sessionId)
|
|
124
|
+
return;
|
|
125
|
+
const before = await this.store.read(options.sessionId, options.provider);
|
|
126
|
+
if (!before || before.id !== runtime.cold.id)
|
|
127
|
+
return;
|
|
128
|
+
if (!before.meta)
|
|
129
|
+
await this.capture(runtime, options, nativeId, fallback);
|
|
130
|
+
await this.store.update(options.sessionId, options.provider, runtime.cold.id, row => { row.cancelIntent ??= { source: 'user-signal' }; if (!row.promptId) {
|
|
131
|
+
row.cancelCheckpoint = { inputNotDelivered: true, receipt: { kind: 'no-prompt-wire' } };
|
|
132
|
+
row.terminal = { kind: 'local-cancel', value: { inputNotDelivered: true } };
|
|
133
|
+
row.finalUsage = row.meta.baseline;
|
|
134
|
+
row.phase = 'terminal';
|
|
135
|
+
} });
|
|
136
|
+
}
|
|
137
|
+
async adoptUserCancellation(row, events) {
|
|
138
|
+
if (row.cancelIntent || row.phase === 'committed')
|
|
139
|
+
return row;
|
|
140
|
+
const turns = new Set();
|
|
141
|
+
if (row.originTurn !== undefined)
|
|
142
|
+
turns.add(row.originTurn);
|
|
143
|
+
for (const [turn, messages] of inputClaims(events))
|
|
144
|
+
if ([...messages.values()].some(message => recoveryMarker(message) === row.id))
|
|
145
|
+
turns.add(turn);
|
|
146
|
+
if (!events.some(event => event.type === 'turn/end' && turns.has(event.data.turn) && event.data.reason.kind === 'aborted' && event.data.reason.reason.kind === 'user'))
|
|
147
|
+
return row;
|
|
148
|
+
return this.store.update(row.sessionId, row.provider, row.id, r => { r.cancelIntent = { source: 'official-user' }; if (!r.promptId) {
|
|
149
|
+
r.cancelCheckpoint = { inputNotDelivered: true, receipt: { kind: 'no-prompt-wire' } };
|
|
150
|
+
r.terminal = { kind: 'local-cancel', value: { inputNotDelivered: true } };
|
|
151
|
+
r.finalUsage = r.meta.baseline;
|
|
152
|
+
r.phase = 'terminal';
|
|
153
|
+
} });
|
|
154
|
+
}
|
|
92
155
|
async reconcile(row, events) {
|
|
93
156
|
const owns = (pointer) => pointer?.coldRoundId === row.id && pointer.coldRoundTerminal === true && pointer.sessionId === row.nativeId && pointer.dshSessionId === row.sessionId && pointer.agent === row.provider && pointer.coldPromptId === row.promptId;
|
|
94
157
|
let settled = events.find(e => e.type === 'assistant/message' && e.data.message.source.provider === row.provider && owns(e.data.message.source.replayState?.response));
|
|
95
158
|
if (!settled)
|
|
96
159
|
settled = events.find(e => e.type === 'assistant/attempt' && expandAssistantStream(e.data.stream).some(item => { const chunk = item.chunk; if (chunk.type !== 'finish' || !['stop', 'max-tokens'].includes(chunk.reason.kind))
|
|
97
160
|
return false; const response = chunk.replayState?.response; return owns(response); }));
|
|
98
|
-
if (!settled && (row.terminal?.kind === 'error' || row.terminal?.kind === 'result' && row.terminal.value?.stopReason === 'cancelled') && row.errorDelivery && row.errorDelivery.promptId === row.promptId) {
|
|
161
|
+
if (!settled && (row.terminal?.kind === 'local-cancel' && row.cancelCheckpoint?.inputNotDelivered && row.cancelIntent || row.terminal?.kind === 'error' || row.terminal?.kind === 'result' && row.terminal.value?.stopReason === 'cancelled') && row.errorDelivery && row.errorDelivery.promptId === row.promptId) {
|
|
99
162
|
const delivery = row.errorDelivery;
|
|
100
163
|
let turn, step, ours = false;
|
|
101
164
|
for (const e of events) {
|
|
@@ -125,12 +188,14 @@ export class ColdRecovery {
|
|
|
125
188
|
const provider = agent.options.provider;
|
|
126
189
|
if (typeof provider !== 'string')
|
|
127
190
|
return;
|
|
128
|
-
|
|
129
|
-
if (!row || !['running', 'terminal'].includes(row.phase) || !row.promptId || this.live.get(row.sessionId) === row.id || this.scheduled.get(agent) === row.id)
|
|
191
|
+
let row = await this.store.read(agent.session.id, provider);
|
|
192
|
+
if (!row || !['running', 'terminal'].includes(row.phase) || !row.promptId && row.terminal?.kind !== 'local-cancel' || this.live.get(row.sessionId) === row.id || this.scheduled.get(agent) === row.id)
|
|
130
193
|
return;
|
|
131
194
|
if (!row.meta || !sameStoredSessionHeader(row.meta.header, agent.session.header))
|
|
132
195
|
throw coldNeed('SESSION_CONTEXT_MISMATCH');
|
|
133
|
-
|
|
196
|
+
const events = await this.events(row.sessionId, row.meta.header);
|
|
197
|
+
row = await this.adoptUserCancellation(row, events);
|
|
198
|
+
if (await this.reconcile(row, events))
|
|
134
199
|
return;
|
|
135
200
|
this.queueSnapshot(agent);
|
|
136
201
|
this.scheduled.set(agent, row.id);
|
|
@@ -143,50 +208,105 @@ export class ColdRecovery {
|
|
|
143
208
|
}
|
|
144
209
|
agent.send(existing ?? createUserMessage({ source: { kind: sourceKind, roundId: row.id, form: 'notice', summary: '接回退出前原轮结果' }, content: [{ type: 'text', text: '正在接回退出前的原轮结果;没有重新发送原任务。' }] }), 'next-step', true);
|
|
145
210
|
}
|
|
211
|
+
async settleUserCancellation(row, parentLifetime) {
|
|
212
|
+
const lifetime = parentLifetime ? AbortSignal.any([this.lifetime.signal, parentLifetime]) : this.lifetime.signal;
|
|
213
|
+
if (lifetime.aborted || row.phase === 'committed' || !row.promptId || !row.meta || row.cancelIntent?.delivered || row.cancelCheckpoint?.inputNotDelivered)
|
|
214
|
+
return;
|
|
215
|
+
const api = this.getConnect(), connection = api?.getConnectionState?.();
|
|
216
|
+
if (!api || connection && connection.phase !== 'connected')
|
|
217
|
+
return;
|
|
218
|
+
const target = unwrap(await awaitL(() => api.getSshTarget(), lifetime));
|
|
219
|
+
if (identity(target) !== row.meta.identity || !isDeepStrictEqual(target, row.target))
|
|
220
|
+
throw coldNeed('SESSION_CONTEXT_MISMATCH');
|
|
221
|
+
const io = this.provided?.io?.(row) ?? sshIo(target, this.provided?.argv ?? (await import('@ai-workbench/connect')).sshArgs, this.config().brokerControlMaxBytes);
|
|
222
|
+
for await (const _chunk of recoverColdProtocol(row, this.store, { blocks: [] }, { io, maxFrameBytes: this.config().brokerMaxFrameBytes, maxMessageBytes: this.config().acpMaxMessageBytes, signal: lifetime, cancelOnly: true })) { }
|
|
223
|
+
}
|
|
224
|
+
watchCancellation(payload) {
|
|
225
|
+
const { agent, turn, step, signal } = payload, provider = String(agent.options.provider);
|
|
226
|
+
if (!['codex-remote', 'claude-code-workbench'].includes(provider) || !this.provided?.store && !this.ctx.get('storageDomain'))
|
|
227
|
+
return;
|
|
228
|
+
this.cancellationWatches.get(agent)?.off();
|
|
229
|
+
// Take the snapshot before pre-step/prepareCall can create a new runtime.
|
|
230
|
+
// A live normal producer already owns its own adapter cancellation listener.
|
|
231
|
+
const snapshot = this.store.read(agent.session.id, provider).then(row => ({ row, live: row && this.live.get(row.sessionId) === row.id }));
|
|
232
|
+
void snapshot.catch(() => { });
|
|
233
|
+
const watch = { turn, step, signal, started: false, pending: undefined, off: () => signal.removeEventListener('abort', note) };
|
|
234
|
+
const note = () => { if (signal.reason?.kind !== 'user')
|
|
235
|
+
return; watch.pending = (async () => { const { row, live } = await snapshot; if (!row || live || !['running', 'terminal'].includes(row.phase))
|
|
236
|
+
return; if (!row.meta || !sameStoredSessionHeader(row.meta.header, agent.session.header))
|
|
237
|
+
throw coldNeed('SESSION_CONTEXT_MISMATCH'); const cancelled = await this.store.update(row.sessionId, row.provider, row.id, r => { r.cancelIntent ??= { source: 'user-signal' }; }); if (!watch.started)
|
|
238
|
+
await this.settleUserCancellation(cancelled); })(); void watch.pending.catch(() => { }); };
|
|
239
|
+
this.cancellationWatches.set(agent, watch);
|
|
240
|
+
signal.addEventListener('abort', note, { once: true });
|
|
241
|
+
if (signal.aborted)
|
|
242
|
+
note();
|
|
243
|
+
return watch;
|
|
244
|
+
}
|
|
146
245
|
install() {
|
|
147
246
|
this.ctx.on('agent/created', async ({ agent, source }) => { if (source === 'resume')
|
|
148
247
|
await this.schedule(agent); });
|
|
149
248
|
this.ctx.on('agent/inbox/inserted', ({ agent }) => { this.queueSnapshot(agent); });
|
|
150
249
|
this.ctx.on('agent/pre-step', async (payload, next) => {
|
|
151
|
-
const
|
|
152
|
-
if (decision.kind !== 'enter')
|
|
153
|
-
return decision;
|
|
154
|
-
this.steps.delete(payload.agent);
|
|
155
|
-
let markers = decision.messages.filter(m => recoveryMarker(m));
|
|
156
|
-
if (!markers.length && !this.scheduled.has(payload.agent))
|
|
157
|
-
return decision;
|
|
158
|
-
const claimed = new Set(payload.messages.map(m => m.id)), q = this.queues.get(payload.agent);
|
|
159
|
-
let restored = false;
|
|
160
|
-
const restoreHumans = () => { if (restored)
|
|
161
|
-
return; restored = true; for (const target of ['next-step', 'next-turn']) {
|
|
162
|
-
const messages = decision.messages.filter(m => claimed.has(m.id) && !recoveryMarker(m) && (q?.get(m.id) ?? 'next-step') === target);
|
|
163
|
-
if (messages.length)
|
|
164
|
-
payload.agent.inbox.splice(target, 0, 0, messages);
|
|
165
|
-
} };
|
|
250
|
+
const cancellation = this.watchCancellation(payload);
|
|
166
251
|
try {
|
|
167
|
-
const
|
|
168
|
-
if (
|
|
169
|
-
|
|
252
|
+
const decision = await next();
|
|
253
|
+
if (decision.kind !== 'enter')
|
|
254
|
+
return decision;
|
|
255
|
+
this.steps.delete(payload.agent);
|
|
256
|
+
let markers = decision.messages.filter(m => recoveryMarker(m));
|
|
257
|
+
if (!markers.length && !this.scheduled.has(payload.agent) && (!['codex-remote', 'claude-code-workbench'].includes(String(payload.agent.options.provider)) || !this.provided?.store && !this.ctx.get('storageDomain')))
|
|
258
|
+
return decision;
|
|
259
|
+
const claimed = new Set(payload.messages.map(m => m.id)), q = this.queues.get(payload.agent);
|
|
260
|
+
let restored = false;
|
|
261
|
+
const restoreHumans = () => { if (restored)
|
|
262
|
+
return; restored = true; for (const target of ['next-step', 'next-turn']) {
|
|
263
|
+
const messages = decision.messages.filter(m => claimed.has(m.id) && !recoveryMarker(m) && (q?.get(m.id) ?? 'next-step') === target);
|
|
264
|
+
if (messages.length)
|
|
265
|
+
payload.agent.inbox.splice(target, 0, 0, messages);
|
|
266
|
+
} };
|
|
267
|
+
try {
|
|
268
|
+
let row = await this.store.read(payload.agent.session.id, String(payload.agent.options.provider));
|
|
269
|
+
if (row?.meta)
|
|
270
|
+
row = await this.adoptUserCancellation(row, await this.events(row.sessionId, row.meta.header));
|
|
271
|
+
if (!markers.length && row && ['running', 'terminal'].includes(row.phase) && (row.promptId || row.terminal?.kind === 'local-cancel') && this.live.get(row.sessionId) !== row.id) {
|
|
272
|
+
if (await this.reconcile(row, await this.events(row.sessionId, row.meta?.header)))
|
|
273
|
+
return decision;
|
|
274
|
+
markers = [createUserMessage({ source: { kind: sourceKind, roundId: row.id, form: 'notice', summary: '接回退出前原轮结果' }, content: [{ type: 'text', text: '正在接回退出前的原轮结果;没有重新发送原任务。' }] })];
|
|
275
|
+
}
|
|
276
|
+
if (!markers.length)
|
|
170
277
|
return decision;
|
|
171
|
-
|
|
278
|
+
if (!row || markers.some(m => recoveryMarker(m) !== row.id) || !['running', 'terminal'].includes(row.phase))
|
|
279
|
+
throw coldNeed('SESSION_CONTEXT_MISMATCH');
|
|
280
|
+
restoreHumans();
|
|
281
|
+
this.steps.set(payload.agent, { turn: payload.turn, step: payload.step, signal: payload.signal, row, markerId: markers[0].id });
|
|
282
|
+
return { ...decision, messages: [...markers, ...decision.messages.filter(m => !claimed.has(m.id) && !recoveryMarker(m))] };
|
|
283
|
+
}
|
|
284
|
+
catch (error) {
|
|
285
|
+
restoreHumans();
|
|
286
|
+
throw error;
|
|
172
287
|
}
|
|
173
|
-
if (!markers.length)
|
|
174
|
-
return decision;
|
|
175
|
-
if (!row || markers.some(m => recoveryMarker(m) !== row.id) || !['running', 'terminal'].includes(row.phase))
|
|
176
|
-
throw coldNeed('SESSION_CONTEXT_MISMATCH');
|
|
177
|
-
restoreHumans();
|
|
178
|
-
this.steps.set(payload.agent, { turn: payload.turn, step: payload.step, signal: payload.signal, row, markerId: markers[0].id });
|
|
179
|
-
return { ...decision, messages: [...markers, ...decision.messages.filter(m => !claimed.has(m.id) && !recoveryMarker(m))] };
|
|
180
288
|
}
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
throw error;
|
|
289
|
+
finally {
|
|
290
|
+
await cancellation?.pending;
|
|
184
291
|
}
|
|
185
292
|
});
|
|
186
|
-
this.ctx.on('agent/request', async (payload, next) => {
|
|
187
|
-
|
|
188
|
-
|
|
293
|
+
this.ctx.on('agent/request', async (payload, next) => { try {
|
|
294
|
+
const config = await next(), step = this.steps.get(payload.agent);
|
|
295
|
+
if (step && step.turn === payload.turn && step.step === payload.step && step.signal === payload.signal)
|
|
296
|
+
return structuredClone(step.row.meta.callConfig ?? { provider: step.row.provider, model: step.row.meta.model, reasoningEffort: step.row.meta.modelConfiguration?.selected?.effort });
|
|
297
|
+
return config;
|
|
298
|
+
}
|
|
299
|
+
finally {
|
|
300
|
+
await this.cancellationWatches.get(payload.agent)?.pending;
|
|
301
|
+
} });
|
|
302
|
+
this.ctx.on('agent/disposed', ({ agent }) => { this.cancellationWatches.get(agent)?.off(); this.cancellationWatches.delete(agent); this.steps.delete(agent); this.scheduled.delete(agent); this.live.delete(agent.session.id); });
|
|
189
303
|
this.ctx.on('session/event', (session, event) => { if (event.type === 'step/end' || event.type === 'turn/end') {
|
|
304
|
+
for (const [agent, watch] of this.cancellationWatches) {
|
|
305
|
+
if (agent.session.id === session.id && watch.turn === event.data.turn && (event.type === 'turn/end' || watch.step === event.data.step)) {
|
|
306
|
+
watch.off();
|
|
307
|
+
this.cancellationWatches.delete(agent);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
190
310
|
for (const [agent, step] of this.steps)
|
|
191
311
|
if (agent.session.id === session.id && step.turn === event.data.turn && (event.type === 'turn/end' || step.step === event.data.step))
|
|
192
312
|
this.steps.delete(agent);
|
|
@@ -206,11 +326,22 @@ export class ColdRecovery {
|
|
|
206
326
|
void (async () => { await agent.whenIdle(); if (this.ctx.get('agents')?.get(agent.session.id) !== agent)
|
|
207
327
|
return; await agent.runMaintenance(async () => { await this.schedule(agent); }); })().catch(() => this.ctx.logger('remote-agent').warn('INPUT_DELIVERY_UNCONFIRMED:冷恢复初始化未确认'));
|
|
208
328
|
}
|
|
329
|
+
/** Official user cancellation is an input disposition even before a remote runtime exists. */
|
|
330
|
+
async projectCancelledInputs(options) {
|
|
331
|
+
if (!options.sessionId || !this.ctx.get('sessions')?.get(SessionId(options.sessionId)))
|
|
332
|
+
return options;
|
|
333
|
+
const events = await this.events(options.sessionId), claims = inputClaims(events), cancelled = new Set();
|
|
334
|
+
for (const event of events)
|
|
335
|
+
if (event.type === 'turn/end' && event.data.reason.kind === 'aborted' && event.data.reason.reason.kind === 'user')
|
|
336
|
+
for (const id of claims.get(event.data.turn)?.keys() ?? [])
|
|
337
|
+
cancelled.add(id);
|
|
338
|
+
return cancelled.size ? { ...options, messages: options.messages.filter(message => message.role !== 'user' || (!message.id || !cancelled.has(message.id))) } : options;
|
|
339
|
+
}
|
|
209
340
|
async previousPointer(options) {
|
|
210
341
|
if (!options.sessionId || !this.provided?.store && !this.ctx.get('storageDomain'))
|
|
211
342
|
return;
|
|
212
343
|
let row = await this.store.read(options.sessionId, options.provider);
|
|
213
|
-
if (!row || !row.meta || !row.
|
|
344
|
+
if (!row || !row.meta || !row.terminal)
|
|
214
345
|
return;
|
|
215
346
|
if (row.phase !== 'committed') {
|
|
216
347
|
if (!await this.reconcile(row, await this.events(row.sessionId, row.meta.header)))
|
|
@@ -222,6 +353,8 @@ export class ColdRecovery {
|
|
|
222
353
|
return;
|
|
223
354
|
await this.events(row.sessionId, row.meta.header);
|
|
224
355
|
const m = row.meta, usage = row.finalUsage ?? null;
|
|
356
|
+
if (!row.nativeId)
|
|
357
|
+
return { index, pointer: undefined };
|
|
225
358
|
return { index, pointer: { version: 2, agent: row.provider, dshSessionId: row.sessionId, identity: m.identity, cwd: m.cwd, sessionId: row.nativeId, contextSha256: m.contextSha256, usageSnapshot: usage, ...(m.binding ? { bindingId: m.binding.bindingId, workspaceId: m.binding.workspaceId } : {}), ...(m.hostSource ? { hostSource: m.hostSource } : {}), ...(m.modelConfiguration ? { modelConfiguration: m.modelConfiguration } : {}) } };
|
|
226
359
|
}
|
|
227
360
|
release(sessionId, id) { if (this.live.get(sessionId) === id)
|
|
@@ -234,7 +367,7 @@ export class ColdRecovery {
|
|
|
234
367
|
return modelInfo(provider, selected);
|
|
235
368
|
}
|
|
236
369
|
} }
|
|
237
|
-
canRecover(options) { return !options.purpose && [...this.steps].some(([agent, step]) => agent.session.id === options.sessionId && step.row.provider === options.provider && step.row.meta?.model === options.model && step.signal === options.signal && !step.signal.aborted && options.messages.some(m => m.id === step.markerId && recoveryMarker(m) === step.row.id)); }
|
|
370
|
+
canRecover(options) { return !options.purpose && [...this.steps].some(([agent, step]) => agent.session.id === options.sessionId && step.row.provider === options.provider && step.row.meta?.model === options.model && step.signal === options.signal && (!step.signal.aborted || step.signal.reason?.kind === 'user') && options.messages.some(m => m.id === step.markerId && recoveryMarker(m) === step.row.id)); }
|
|
238
371
|
async connection(signal, binding) {
|
|
239
372
|
for (;;) {
|
|
240
373
|
signal?.throwIfAborted();
|
|
@@ -268,13 +401,46 @@ export class ColdRecovery {
|
|
|
268
401
|
wake(); });
|
|
269
402
|
}
|
|
270
403
|
}
|
|
271
|
-
async *stream(options) {
|
|
404
|
+
async *stream(options, lifetime) {
|
|
405
|
+
if (!this.canRecover(options) || !options.sessionId)
|
|
406
|
+
throw coldNeed();
|
|
407
|
+
const selected = [...this.steps.values()].find(step => step.signal === options.signal && step.row.sessionId === options.sessionId && step.row.provider === options.provider);
|
|
408
|
+
let inheritedCancellation;
|
|
409
|
+
for (const [agent, step] of this.steps)
|
|
410
|
+
if (step === selected) {
|
|
411
|
+
const watch = this.cancellationWatches.get(agent);
|
|
412
|
+
if (watch) {
|
|
413
|
+
watch.started = true;
|
|
414
|
+
inheritedCancellation = watch.pending;
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
let cancellation;
|
|
418
|
+
const note = () => { if (options.signal?.reason?.kind === 'user')
|
|
419
|
+
cancellation = this.store.update(selected.row.sessionId, selected.row.provider, selected.row.id, row => { row.cancelIntent ??= { source: 'user-signal' }; }); void cancellation?.catch(() => { }); };
|
|
420
|
+
options.signal?.addEventListener('abort', note, { once: true });
|
|
421
|
+
if (options.signal?.aborted)
|
|
422
|
+
note();
|
|
423
|
+
try {
|
|
424
|
+
await inheritedCancellation;
|
|
425
|
+
yield* this.streamRound(options, lifetime);
|
|
426
|
+
}
|
|
427
|
+
finally {
|
|
428
|
+
options.signal?.removeEventListener('abort', note);
|
|
429
|
+
await cancellation;
|
|
430
|
+
if (cancellation && !lifetime?.aborted) {
|
|
431
|
+
const row = await this.store.read(selected.row.sessionId, selected.row.provider);
|
|
432
|
+
if (row && row.id === selected.row.id)
|
|
433
|
+
await this.settleUserCancellation(row, lifetime);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
async *streamRound(options, lifetime) {
|
|
272
438
|
if (!this.canRecover(options) || !options.sessionId)
|
|
273
439
|
throw coldNeed();
|
|
274
440
|
const markers = options.messages.filter(m => recoveryMarker(m)), id = recoveryMarker(markers.at(-1));
|
|
275
441
|
const selected = [...this.steps.values()].find(step => step.signal === options.signal && step.row.id === id);
|
|
276
442
|
const row = await this.store.read(options.sessionId, options.provider);
|
|
277
|
-
if (!selected || !row || row.id !== id || !row.meta || !row.nativeId || !['running', 'terminal'].includes(row.phase))
|
|
443
|
+
if (!selected || !row || row.id !== id || !row.meta || !row.nativeId && row.terminal?.kind !== 'local-cancel' || !['running', 'terminal'].includes(row.phase))
|
|
278
444
|
throw coldNeed();
|
|
279
445
|
const events = await this.events(row.sessionId, row.meta.header);
|
|
280
446
|
if (this.provided?.readSource && !isDeepStrictEqual(row.meta.hostSource ?? { source: 'local' }, await this.provided.readSource(row.sessionId)))
|
|
@@ -284,7 +450,12 @@ export class ColdRecovery {
|
|
|
284
450
|
if (!e || digest(e.data) !== expected)
|
|
285
451
|
throw coldNeed('SESSION_CONTEXT_MISMATCH');
|
|
286
452
|
}
|
|
287
|
-
|
|
453
|
+
if (row.terminal?.kind === 'local-cancel') {
|
|
454
|
+
yield* recoverLocalCancellation(row, this.store, selected.markerId);
|
|
455
|
+
return;
|
|
456
|
+
}
|
|
457
|
+
const operationSignal = lifetime ? AbortSignal.any([lifetime, ...options.signal ? [options.signal] : []]) : options.signal;
|
|
458
|
+
const { api, target, connection: initialConnection } = await this.connection(operationSignal, row.meta);
|
|
288
459
|
if (identity(target) !== row.meta.identity || !isDeepStrictEqual(target, row.target))
|
|
289
460
|
throw coldNeed('SESSION_CONTEXT_MISMATCH');
|
|
290
461
|
if (row.meta.binding) {
|
|
@@ -400,7 +571,7 @@ export class ColdRecovery {
|
|
|
400
571
|
await check();
|
|
401
572
|
}
|
|
402
573
|
checkLocation();
|
|
403
|
-
const signal = AbortSignal.any([guard.signal, ...
|
|
574
|
+
const signal = AbortSignal.any([guard.signal, ...operationSignal ? [operationSignal] : []]);
|
|
404
575
|
if (!isDeepStrictEqual(api.getConnectionState?.(), initialConnection)) {
|
|
405
576
|
const checked = await this.connection(signal, row.meta);
|
|
406
577
|
if (checked.api !== api || !isDeepStrictEqual(checked.target, row.target))
|
package/dist/cold-store.d.ts
CHANGED
|
@@ -60,12 +60,21 @@ export interface ColdRound {
|
|
|
60
60
|
localNotices?: {
|
|
61
61
|
beforeUpdate: number;
|
|
62
62
|
text: string;
|
|
63
|
+
kind?: 'text' | 'reasoning';
|
|
63
64
|
}[];
|
|
65
|
+
cancelIntent?: {
|
|
66
|
+
source: 'user-signal' | 'official-user' | 'wire';
|
|
67
|
+
delivered?: boolean;
|
|
68
|
+
};
|
|
69
|
+
cancelCheckpoint?: {
|
|
70
|
+
inputNotDelivered: true;
|
|
71
|
+
receipt: unknown;
|
|
72
|
+
};
|
|
64
73
|
finalUsage?: UsageSnapshot | null;
|
|
65
74
|
errorDelivery?: {
|
|
66
75
|
markerId: string;
|
|
67
76
|
code: string;
|
|
68
|
-
promptId
|
|
77
|
+
promptId?: string;
|
|
69
78
|
token: string;
|
|
70
79
|
message: string;
|
|
71
80
|
};
|
|
@@ -74,7 +83,7 @@ export interface ColdRound {
|
|
|
74
83
|
outputAfter: number;
|
|
75
84
|
officialSeq?: number;
|
|
76
85
|
terminal?: {
|
|
77
|
-
kind: 'result' | 'error';
|
|
86
|
+
kind: 'result' | 'error' | 'local-cancel';
|
|
78
87
|
value: unknown;
|
|
79
88
|
};
|
|
80
89
|
failure?: string;
|
package/dist/index.js
CHANGED
|
@@ -280,12 +280,13 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
280
280
|
for (const live of this.sessions.values())
|
|
281
281
|
live.runtime.closeDiagnostics?.record({ layer: 'adapter', initiator: 'adapter.dispose', reason: 'PLUGIN_DISPOSED', action: 'dispose', changes: [{ field: 'adapter.shutting-down', before: this.shuttingDown, after: true }] });
|
|
282
282
|
this.shuttingDown = true;
|
|
283
|
+
this.coldRecovery?.dispose?.();
|
|
283
284
|
this.modelPresentation.clear();
|
|
284
285
|
this.employeeNoticeSessions.clear();
|
|
285
286
|
this.pendingEmployeeNotices.clear();
|
|
286
287
|
const results = await Promise.allSettled([...new Set([...this.sessions.keys(), ...this.turns.keys()])].map(id => this.detachSession(id)));
|
|
287
288
|
await this.bridgeLoop.dispose();
|
|
288
|
-
this.lifetime.abort();
|
|
289
|
+
this.lifetime.abort(Object.assign(new DOMException('远程模型插件已关闭', 'AbortError'), { kind: 'disposed' }));
|
|
289
290
|
const failure = results.find(result => result.status === 'rejected');
|
|
290
291
|
if (failure?.status === 'rejected')
|
|
291
292
|
throw failure.reason;
|
|
@@ -293,7 +294,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
293
294
|
async *stream(options) {
|
|
294
295
|
if (this.coldRecovery?.canRecover(options)) {
|
|
295
296
|
try {
|
|
296
|
-
yield* this.coldRecovery.stream(options);
|
|
297
|
+
yield* this.coldRecovery.stream(options, this.lifetime.signal);
|
|
297
298
|
return;
|
|
298
299
|
}
|
|
299
300
|
catch (error) {
|
|
@@ -392,9 +393,9 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
392
393
|
if (!Number.isSafeInteger(config.acpMaxMessageBytes) || config.acpMaxMessageBytes < 1)
|
|
393
394
|
throw new NeedError('SETTINGS_REQUIRED', '远程模型连接设置无效,请联系管理员检查', '有效的acpMaxMessageBytes');
|
|
394
395
|
const standardCheckpoint = readPointer(options, this.agent), recoveredCheckpoint = await this.coldRecovery?.previousPointer(options);
|
|
395
|
-
const checkpoint = recoveredCheckpoint && (!standardCheckpoint || recoveredCheckpoint.index > standardCheckpoint.index) ? recoveredCheckpoint : standardCheckpoint, previous = checkpoint?.pointer;
|
|
396
|
+
const checkpoint = recoveredCheckpoint && (!standardCheckpoint || recoveredCheckpoint.index > standardCheckpoint.index) ? recoveredCheckpoint : standardCheckpoint, previous = checkpoint?.pointer ?? (checkpoint === recoveredCheckpoint ? standardCheckpoint?.pointer : undefined);
|
|
396
397
|
const usedColdCheckpoint = !!recoveredCheckpoint && checkpoint === recoveredCheckpoint;
|
|
397
|
-
|
|
398
|
+
let checkpointIndex = usedColdCheckpoint ? -1 : checkpoint?.index ?? -1;
|
|
398
399
|
if (usedColdCheckpoint)
|
|
399
400
|
options = { ...options, messages: options.messages.filter((m, index) => index > checkpoint.index || m.role === 'system' || m.role === 'developer') };
|
|
400
401
|
employeeNoticeShown = !!key && this.employeeNoticeSessions.has(key) || false;
|
|
@@ -419,6 +420,9 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
419
420
|
request.userMessageIds = request.userInputIds;
|
|
420
421
|
earlyStage = 'source-context';
|
|
421
422
|
await this.resolveRuntime.preflight?.(request);
|
|
423
|
+
options = { ...await this.coldRecovery?.projectCancelledInputs?.(options) ?? options, signal };
|
|
424
|
+
if (!usedColdCheckpoint)
|
|
425
|
+
checkpointIndex = readPointer(options, this.agent)?.index ?? -1;
|
|
422
426
|
const receipts = this.steeringReceipts && options.sessionId ? await this.steeringReceipts.read(options.sessionId, options.provider, humanIds) : new Map();
|
|
423
427
|
const matching = [...receipts.values()].filter(r => tail.some(m => m.role === 'user' && 'source' in m && m.source?.kind === 'user' && m.id === r.messageId && steeringMessageDigest(m) === r.messageSha256));
|
|
424
428
|
for (const receipt of matching)
|
|
@@ -545,7 +549,19 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
545
549
|
}
|
|
546
550
|
const answer = await this.approve?.(permission, approvalSignal, options, execution && toolName?.startsWith('mcp__employee__') ? 'employee-local' : undefined, runtime.hostWorkspace) ?? 'unavailable';
|
|
547
551
|
return answer;
|
|
548
|
-
}, onEmployeeNotice: notice => renderNotice(notice + '\n\n'), onUpdate: notification => { const fromPrompt = coldPromptStarted; render(() => {
|
|
552
|
+
}, onEmployeeNotice: notice => renderNotice(notice + '\n\n'), onUpdate: (notification, originSequence) => { const fromPrompt = coldPromptStarted; render(async () => { let inRound = fromPrompt; if (fromPrompt && runtime.cold) {
|
|
553
|
+
const start = await runtime.cold.bound;
|
|
554
|
+
if (!Number.isSafeInteger(originSequence))
|
|
555
|
+
throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '原输出通知的来源未确认', '原broker输出序号');
|
|
556
|
+
inRound = originSequence > start;
|
|
557
|
+
if (!inRound) {
|
|
558
|
+
const update = notification.update;
|
|
559
|
+
if ((update.sessionUpdate === 'agent_message_chunk' || update.sessionUpdate === 'agent_thought_chunk') && update.content.type === 'text' && update.content.text) {
|
|
560
|
+
const text = update.content.text, kind = update.sessionUpdate === 'agent_thought_chunk' ? 'reasoning' : 'text';
|
|
561
|
+
await runtime.cold.store.update(options.sessionId, options.provider, runtime.cold.id, row => { (row.localNotices ??= []).push({ beforeUpdate: nativeUpdates, text, kind }); });
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
} bridge?.observe(notification.update); push(mapper.acp(notification.update)); if (inRound)
|
|
549
565
|
nativeUpdates++; }); }, onResponse: response => render(() => { push(mapper.acpResponse(response)); }), onDetail: detail => details.record(detail) };
|
|
550
566
|
const transport = runtime.acpTransport instanceof acp.AgentApp || runtime.acpTransport instanceof unstable.AgentApp ? runtime.acpTransport : acp.ndJsonStream(runtime.acpTransport.writable, runtime.acpTransport.readable, { maxMessageBytes: config.acpMaxMessageBytes });
|
|
551
567
|
session = new AcpSession(transport, hooks);
|
|
@@ -692,7 +708,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
692
708
|
details.endTurn();
|
|
693
709
|
}
|
|
694
710
|
})();
|
|
695
|
-
void task.then(value => { stop = value; }, error => { failure ??= runtime.broker?.error ?? error; }).then(async () => { await renderTail; }, error => { failure ??= error; }).catch(error => { failure ??= error; }).finally(() => { done = true; wake?.(); wake = undefined; });
|
|
711
|
+
void task.then(value => { stop = value; }, error => { runtime.cold?.failBinding(error); failure ??= runtime.broker?.error ?? error; }).then(async () => { await renderTail; }, error => { failure ??= error; }).catch(error => { failure ??= error; }).finally(() => { done = true; wake?.(); wake = undefined; });
|
|
696
712
|
while (!done || queue.length) {
|
|
697
713
|
if (queue.length)
|
|
698
714
|
yield queue.shift();
|
|
@@ -728,6 +744,8 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
728
744
|
yield { type: 'finish', reason: { kind: stop === 'max_tokens' || stop === 'max_turn_requests' ? 'max-tokens' : 'stop' }, replayState: { response: pointer } };
|
|
729
745
|
}
|
|
730
746
|
catch (error) {
|
|
747
|
+
if (original.signal?.reason?.kind === 'user' && runtime?.cold && this.coldRecovery)
|
|
748
|
+
await this.coldRecovery.recordUserCancellation(runtime, options, session?.id ?? request?.resumeSessionId, { identity: runtime.identity, cwd: runtime.cwd, binding: runtime.binding, hostSource: runtime.hostSource, contextSha256: request?.contextSha256 ?? '', baseline: activeMapper?.usageSnapshot ?? null, modelConfiguration: modelConfiguration ?? { selected }, model: options.model, prelude: coldPrelude, localDirectory: runtime.localDirectory });
|
|
731
749
|
if (session && session.promptDispatchCount > promptBaseline)
|
|
732
750
|
onPromptDispatched();
|
|
733
751
|
if (bridge?.unsettled && !signal.aborted)
|
package/dist/provider.d.ts
CHANGED
|
@@ -36,7 +36,9 @@ export interface Runtime {
|
|
|
36
36
|
cold?: {
|
|
37
37
|
id: string;
|
|
38
38
|
store: ColdStore;
|
|
39
|
-
|
|
39
|
+
bound: Promise<number>;
|
|
40
|
+
failBinding: (error: unknown) => void;
|
|
41
|
+
prepare: (nativeId: string | undefined, meta: NonNullable<ColdRound['meta']>) => Promise<void>;
|
|
40
42
|
};
|
|
41
43
|
identity: string;
|
|
42
44
|
cwd: string;
|