@ai-workbench/remote-agent 0.9.0-toolbridge.3 → 0.9.0-toolbridge.30
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 +32 -7
- package/dist/acp.d.ts +23 -3
- package/dist/acp.js +106 -21
- package/dist/broker-runtime.d.ts +2 -0
- package/dist/broker-runtime.js +60 -3
- package/dist/broker.d.ts +56 -1
- package/dist/broker.js +310 -11
- package/dist/claude-local.js +26 -5
- package/dist/client.js +1 -1
- package/dist/close-diagnostics.d.ts +1 -1
- package/dist/close-diagnostics.js +1 -1
- package/dist/cold-protocol.d.ts +17 -0
- package/dist/cold-protocol.js +399 -0
- package/dist/cold-recovery.d.ts +62 -0
- package/dist/cold-recovery.js +595 -0
- package/dist/cold-store.d.ts +99 -0
- package/dist/cold-store.js +29 -0
- package/dist/conversation-details.js +21 -8
- package/dist/employee-endpoint.js +15 -1
- package/dist/employee-mcp.js +1 -1
- package/dist/employee-native.js +7 -1
- package/dist/employee-provider.js +46 -11
- package/dist/employee-relay.js +148 -1
- package/dist/employee-shell.d.ts +2 -0
- package/dist/employee-shell.js +22 -19
- package/dist/employee-tools.js +2 -2
- package/dist/employee-workspace.d.ts +20 -4
- package/dist/employee-workspace.js +26 -5
- package/dist/index.d.ts +12 -3
- package/dist/index.js +221 -51
- package/dist/input.js +4 -1
- package/dist/live-steering.d.ts +46 -0
- package/dist/live-steering.js +45 -0
- package/dist/mapping.d.ts +4 -24
- package/dist/mapping.js +11 -65
- package/dist/model-catalog.d.ts +2 -0
- package/dist/model-catalog.js +5 -1
- package/dist/preflight-diagnostic.js +1 -1
- package/dist/presentation.js +1 -0
- package/dist/provider.d.ts +15 -0
- package/dist/provider.js +3 -2
- package/dist/rpc-namespace.js +16 -2
- package/dist/session-source.d.ts +3 -1
- package/dist/session-source.js +2 -1
- package/dist/startup-timing.d.ts +14 -0
- package/dist/startup-timing.js +34 -0
- package/dist/toolbridge-loop.d.ts +3 -2
- package/dist/toolbridge-loop.js +4 -2
- package/dist/toolbridge-table.d.ts +4 -3
- package/dist/toolbridge-table.js +14 -5
- package/dist/toolbridge.d.ts +1 -1
- package/dist/toolbridge.js +4 -4
- package/package.json +23 -16
package/dist/index.js
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import { StartupTiming } from "./startup-timing.js";
|
|
2
|
+
import { ColdRecovery } from "./cold-recovery.js";
|
|
3
|
+
import { createSteeringReceipts, installLiveSteering, steeringMessageDigest } from "./live-steering.js";
|
|
1
4
|
import { ToolBridgeLoop } from "./toolbridge-loop.js";
|
|
2
5
|
import { openToolBridgeMcp, TOOLBRIDGE_NOTICE } from "./toolbridge.js";
|
|
3
6
|
import { connectNeedMessage } from "./connect-need.js";
|
|
@@ -7,7 +10,7 @@ import { SessionId } from '@deepseek-ai/dsh-session';
|
|
|
7
10
|
import { createAssistantMessage } from '@deepseek-ai/dsh-llm';
|
|
8
11
|
import Schema from '@deepseek-ai/schemastery';
|
|
9
12
|
import { LlmAdapter, LlmError } from '@deepseek-ai/dsh-llm';
|
|
10
|
-
import { createHash } from 'node:crypto';
|
|
13
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
11
14
|
import * as unstable from '@agentclientprotocol/sdk/unstable';
|
|
12
15
|
import * as acp from '@agentclientprotocol/sdk';
|
|
13
16
|
import { AcpSession } from "./acp.js";
|
|
@@ -39,9 +42,9 @@ export const settingsNamespace = 'ai-workbench-codex';
|
|
|
39
42
|
// L can be installed/enabled after X; keeping X mounted lets it explain the prerequisite.
|
|
40
43
|
export const inject = ['llm'];
|
|
41
44
|
/** Owner-approved defaults; administrators may override through the existing settings. */
|
|
42
|
-
export const DEFAULT_CONFIG = Object.freeze({ acpMaxMessageBytes:
|
|
45
|
+
export const DEFAULT_CONFIG = Object.freeze({ acpMaxMessageBytes: 512000000, brokerMaxFrameBytes: 2097152, brokerControlMaxBytes: 1048576, employeeShellKillGraceMs: 1000 });
|
|
43
46
|
export const Config = Schema.object({
|
|
44
|
-
acpMaxMessageBytes: Schema.number().min(1).step(1).i18n({ en: 'Session message limit; default
|
|
47
|
+
acpMaxMessageBytes: Schema.number().min(1).step(1).i18n({ en: 'Session message limit; default 512 MB, adjustable by administrators', zh: '会话消息容量;默认512 MB,管理员可调整' }).default(DEFAULT_CONFIG.acpMaxMessageBytes).volatile(),
|
|
45
48
|
brokerMaxFrameBytes: Schema.number().min(1).step(1).i18n({ en: 'Host output chunk limit; default 2 MiB, adjustable by administrators', zh: '主机回传单段容量;默认2 MiB,管理员可调整' }).default(DEFAULT_CONFIG.brokerMaxFrameBytes).volatile(),
|
|
46
49
|
brokerControlMaxBytes: Schema.number().min(1).step(1).i18n({ en: 'Host session control reply limit; default 1 MiB, adjustable by administrators', zh: '主机会话管理回复容量;默认1 MiB,管理员可调整' }).default(DEFAULT_CONFIG.brokerControlMaxBytes).volatile(),
|
|
47
50
|
employeeShellKillGraceMs: Schema.number().min(0).max(2147483647).step(1).i18n({ en: 'Local command SSH cleanup grace in milliseconds; cancellation keeps the remote result unknown', zh: '本机命令SSH取消后的清理宽限毫秒;默认1000,取消仍保留员工端结果未知' }).default(DEFAULT_CONFIG.employeeShellKillGraceMs).volatile(),
|
|
@@ -94,9 +97,12 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
94
97
|
directory;
|
|
95
98
|
preflightDiagnostics;
|
|
96
99
|
permissions;
|
|
100
|
+
steeringReceipts;
|
|
101
|
+
coldRecovery;
|
|
97
102
|
bridgeLoop;
|
|
98
103
|
config;
|
|
99
104
|
sessions = new Map();
|
|
105
|
+
injectedInputs = new Map();
|
|
100
106
|
turns = new Map();
|
|
101
107
|
lifetime = new AbortController();
|
|
102
108
|
shuttingDown = false;
|
|
@@ -104,7 +110,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
104
110
|
modelPresentation = new ModelPresentation();
|
|
105
111
|
employeeNoticeSessions = new Set();
|
|
106
112
|
pendingEmployeeNotices = new Set();
|
|
107
|
-
constructor(config, resolveRuntime, approve, providerName = () => CODEX_AGENT.name.zh, agent = CODEX_AGENT, readImage, reportLoginFailure, directory, preflightDiagnostics, permissions, bridgeStopped) {
|
|
113
|
+
constructor(config, resolveRuntime, approve, providerName = () => CODEX_AGENT.name.zh, agent = CODEX_AGENT, readImage, reportLoginFailure, directory, preflightDiagnostics, permissions, bridgeStopped, steeringReceipts, coldRecovery) {
|
|
108
114
|
super();
|
|
109
115
|
this.resolveRuntime = resolveRuntime;
|
|
110
116
|
this.approve = approve;
|
|
@@ -115,10 +121,79 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
115
121
|
this.directory = directory;
|
|
116
122
|
this.preflightDiagnostics = preflightDiagnostics;
|
|
117
123
|
this.permissions = permissions;
|
|
118
|
-
this.
|
|
124
|
+
this.steeringReceipts = steeringReceipts;
|
|
125
|
+
this.coldRecovery = coldRecovery;
|
|
126
|
+
this.bridgeLoop = new ToolBridgeLoop(readImage, bridgeStopped, (id, message) => this.injectedInputs.get(id)?.get(message.id) === steeringMessageDigest(message));
|
|
119
127
|
this.config = typeof config === 'function' ? config : () => config;
|
|
120
128
|
}
|
|
121
129
|
providerInfo(provider) { return { id: provider, name: this.providerName() }; }
|
|
130
|
+
canSteer(sessionId) { const live = this.sessions.get(sessionId); return !!this.steeringReceipts && !!live?.acceptingSteer && live.session.canSteer; }
|
|
131
|
+
steer(sessionId, message, isCurrent) {
|
|
132
|
+
const live = this.sessions.get(sessionId);
|
|
133
|
+
if (!live || !this.canSteer(sessionId))
|
|
134
|
+
return Promise.resolve();
|
|
135
|
+
const digest = steeringMessageDigest(message), valid = () => !isCurrent || isCurrent();
|
|
136
|
+
if (live.steerIds.get(message.id) === digest)
|
|
137
|
+
return live.steerTail;
|
|
138
|
+
live.steerIds.set(message.id, digest);
|
|
139
|
+
const work = live.steerTail.catch(() => { }).then(async () => {
|
|
140
|
+
if (!live.acceptingSteer || this.sessions.get(sessionId) !== live || !live.session.canSteer || !valid())
|
|
141
|
+
return;
|
|
142
|
+
const store = this.steeringReceipts, provider = live.options.provider, nativeSessionId = live.session.id;
|
|
143
|
+
const old = (await store.read(sessionId, provider, [message.id])).get(message.id);
|
|
144
|
+
if (!valid())
|
|
145
|
+
return;
|
|
146
|
+
if (old && old.messageSha256 !== digest && old.outcome !== 'deferred') {
|
|
147
|
+
live.notice?.('这条消息的旧版本已发送或送达未确认,不能撤回;编辑后的内容保留在队列,按下一步骤交付。');
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
if (old && old.outcome !== 'deferred') {
|
|
151
|
+
if (old.outcome !== 'injected' || old.nativeSessionId !== nativeSessionId) {
|
|
152
|
+
const error = new NeedError('INPUT_DELIVERY_UNCONFIRMED', '这条中途消息已有未确认的送达记录,没有再次发送。', '原轮中途消息回执');
|
|
153
|
+
throw error;
|
|
154
|
+
}
|
|
155
|
+
(this.injectedInputs.get(sessionId) ?? this.injectedInputs.set(sessionId, new Map()).get(sessionId)).set(message.id, digest);
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
const prepared = await prepareInput({ ...live.options, messages: [message] }, this.readImage);
|
|
159
|
+
if (!valid())
|
|
160
|
+
return;
|
|
161
|
+
const params = { sessionId: nativeSessionId, prompt: prepared.prompt, _meta: { steering: { idleBehavior: 'promptRequired' } } };
|
|
162
|
+
if (Buffer.byteLength(JSON.stringify({ jsonrpc: '2.0', id: 'steering', method: '_session/steering', params })) + 1 > live.maxBytes)
|
|
163
|
+
throw new NeedError('ACP_MESSAGE_TOO_LARGE', '中途消息超过已设置的会话消息容量,仍在官方队列中,未发送。', '管理员调整acpMaxMessageBytes');
|
|
164
|
+
const receipt = { sessionId, provider, messageId: message.id, nativeSessionId, turnId: live.turnId, messageSha256: digest, outcome: 'prepared' };
|
|
165
|
+
await store.put(receipt);
|
|
166
|
+
const before = live.session.steerDispatchCount;
|
|
167
|
+
if (!valid()) {
|
|
168
|
+
await store.put({ ...receipt, outcome: 'deferred' });
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
try {
|
|
172
|
+
const outcome = await live.session.steer(prepared.prompt, live.options.signal, valid, live.maxBytes);
|
|
173
|
+
await store.put({ ...receipt, outcome: outcome === 'injected' ? 'injected' : 'deferred' });
|
|
174
|
+
if (outcome === 'injected')
|
|
175
|
+
(this.injectedInputs.get(sessionId) ?? this.injectedInputs.set(sessionId, new Map()).get(sessionId)).set(message.id, digest);
|
|
176
|
+
}
|
|
177
|
+
catch (error) {
|
|
178
|
+
const dispatched = live.session.steerDispatchCount !== before;
|
|
179
|
+
await store.put({ ...receipt, outcome: dispatched ? 'unknown' : 'deferred' });
|
|
180
|
+
if (dispatched) {
|
|
181
|
+
const failure = new NeedError('INPUT_DELIVERY_UNCONFIRMED', '中途消息可能已交给原轮,送达结果未知,没有自动重复发送。', '原轮中途消息回执');
|
|
182
|
+
throw failure;
|
|
183
|
+
}
|
|
184
|
+
live.runtime.details?.record({ kind: 'need', severity: 'warning', code: error instanceof NeedError ? error.code : 'INPUT_DELIVERY_UNCONFIRMED', summary: '中途消息未发出,仍由官方队列后续处理。' });
|
|
185
|
+
}
|
|
186
|
+
});
|
|
187
|
+
const observed = work.catch(error => {
|
|
188
|
+
live.runtime.details?.record({ kind: 'need', severity: 'warning', code: error instanceof NeedError ? error.code : 'INPUT_DELIVERY_UNCONFIRMED', summary: '中途消息未确认,原消息没有丢弃或自动重发。' });
|
|
189
|
+
// A steering receipt describes this input, not the running prompt's result.
|
|
190
|
+
// Keep its uncertainty durable; the official next step records the input
|
|
191
|
+
// and explains why it was not sent again without failing the original turn.
|
|
192
|
+
});
|
|
193
|
+
live.steerTail = observed;
|
|
194
|
+
void observed.catch(() => { });
|
|
195
|
+
return observed;
|
|
196
|
+
}
|
|
122
197
|
catalog(signal) { if (!this.directory)
|
|
123
198
|
throw new LlmError('无法获取模型列表:缺少可信主机目录能力', 'MODEL_CATALOG_UNAVAILABLE'); return this.directory.read(this.agent, signal); }
|
|
124
199
|
async listModels(provider) { const catalog = await this.catalog(this.lifetime.signal); try {
|
|
@@ -130,6 +205,9 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
130
205
|
catalog.release();
|
|
131
206
|
} }
|
|
132
207
|
async resolveModel(provider, id, signal) {
|
|
208
|
+
const recovered = this.coldRecovery?.recoveryModel(provider, id, signal);
|
|
209
|
+
if (recovered)
|
|
210
|
+
return recovered;
|
|
133
211
|
const displayed = this.modelPresentation.resolve(provider, id);
|
|
134
212
|
if (displayed)
|
|
135
213
|
return displayed;
|
|
@@ -175,10 +253,12 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
175
253
|
await this.cleanupRuntime(current.runtime);
|
|
176
254
|
}
|
|
177
255
|
async detachSession(sessionId) {
|
|
178
|
-
await this.bridgeLoop.cancel(sessionId);
|
|
179
256
|
const current = this.sessions.get(sessionId), turn = this.turns.get(sessionId);
|
|
180
257
|
if (!current && !turn)
|
|
181
258
|
return;
|
|
259
|
+
if (current?.runtime.broker?.supportsRecovery)
|
|
260
|
+
current.session.close({ layer: 'adapter', initiator: 'adapter.detach-sdk', reason: 'SESSION_DETACHED', action: 'detach' });
|
|
261
|
+
await this.bridgeLoop.cancel(sessionId);
|
|
182
262
|
current?.runtime.closeDiagnostics?.record({ layer: 'adapter', initiator: 'adapter.detach-session', reason: 'SESSION_DETACHED', action: 'detach', changes: [{ field: 'adapter.detached', before: this.detached.has(sessionId), after: true }] });
|
|
183
263
|
this.detached.add(sessionId);
|
|
184
264
|
if (current) {
|
|
@@ -198,17 +278,32 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
198
278
|
for (const live of this.sessions.values())
|
|
199
279
|
live.runtime.closeDiagnostics?.record({ layer: 'adapter', initiator: 'adapter.dispose', reason: 'PLUGIN_DISPOSED', action: 'dispose', changes: [{ field: 'adapter.shutting-down', before: this.shuttingDown, after: true }] });
|
|
200
280
|
this.shuttingDown = true;
|
|
201
|
-
|
|
281
|
+
this.coldRecovery?.dispose?.();
|
|
202
282
|
this.modelPresentation.clear();
|
|
203
283
|
this.employeeNoticeSessions.clear();
|
|
204
284
|
this.pendingEmployeeNotices.clear();
|
|
205
285
|
const results = await Promise.allSettled([...new Set([...this.sessions.keys(), ...this.turns.keys()])].map(id => this.detachSession(id)));
|
|
206
|
-
this.
|
|
286
|
+
await this.bridgeLoop.dispose();
|
|
287
|
+
this.lifetime.abort(Object.assign(new DOMException('远程模型插件已关闭', 'AbortError'), { kind: 'disposed' }));
|
|
207
288
|
const failure = results.find(result => result.status === 'rejected');
|
|
208
289
|
if (failure?.status === 'rejected')
|
|
209
290
|
throw failure.reason;
|
|
210
291
|
}
|
|
211
292
|
async *stream(options) {
|
|
293
|
+
if (this.coldRecovery?.canRecover(options)) {
|
|
294
|
+
try {
|
|
295
|
+
yield* this.coldRecovery.stream(options, this.lifetime.signal);
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
catch (error) {
|
|
299
|
+
if (error instanceof NeedError)
|
|
300
|
+
throw new LlmError(error.message, error.code, { cause: error });
|
|
301
|
+
throw error;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
// Before the tool bridge: a parked turn must not take a background request for its own continuation.
|
|
305
|
+
if (options.purpose)
|
|
306
|
+
throw new LlmError(employeeFailure('PURPOSE_UNSUPPORTED', this.agent.loginProvider, false), 'PURPOSE_UNSUPPORTED');
|
|
212
307
|
let promptDispatched = !!options.sessionId && (this.sessions.get(options.sessionId)?.session.promptDispatchCount ?? 0) > 0;
|
|
213
308
|
try {
|
|
214
309
|
for await (const chunk of this.bridgeLoop.stream(options, (o, b) => this.generate(o, () => { promptDispatched = true; }, b))) {
|
|
@@ -247,8 +342,6 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
247
342
|
}
|
|
248
343
|
}
|
|
249
344
|
async *generate(original, onPromptDispatched, bridge) {
|
|
250
|
-
if (original.purpose)
|
|
251
|
-
throw new NeedError('PURPOSE_UNSUPPORTED', '此远程模型不处理后台标题或上下文整理请求,未发送模型请求', '独立的后台请求能力');
|
|
252
345
|
if (this.lifetime.signal.aborted)
|
|
253
346
|
throw new NeedError('DISPOSED', '远程模型插件已关闭', '启用远程模型插件');
|
|
254
347
|
const key = original.sessionId;
|
|
@@ -258,7 +351,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
258
351
|
if (key)
|
|
259
352
|
this.turns.set(key, turn);
|
|
260
353
|
const signal = AbortSignal.any([this.lifetime.signal, turn.signal, ...(original.signal ? [original.signal] : [])]);
|
|
261
|
-
|
|
354
|
+
let options = { ...original, signal };
|
|
262
355
|
const abortOffs = [];
|
|
263
356
|
let bridgeMcp;
|
|
264
357
|
let request;
|
|
@@ -270,11 +363,11 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
270
363
|
let remoteAttempted = false;
|
|
271
364
|
let promptBaseline = 0;
|
|
272
365
|
let failureCode;
|
|
273
|
-
let preserveRecoveredRuntime = false;
|
|
274
366
|
let activeMapper;
|
|
275
367
|
let selected;
|
|
276
368
|
let modelConfiguration;
|
|
277
369
|
let turnFailure;
|
|
370
|
+
let coldPrelude = '';
|
|
278
371
|
let employeeNoticeShown = false;
|
|
279
372
|
let permissionOff;
|
|
280
373
|
let permissionEpoch = new AbortController();
|
|
@@ -284,7 +377,8 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
284
377
|
runtime.details.record(entry); };
|
|
285
378
|
const config = this.config();
|
|
286
379
|
const mode = 'session';
|
|
287
|
-
|
|
380
|
+
const startupTiming = new StartupTiming(this.preflightDiagnostics ? event => { void this.preflightDiagnostics.record(request, this.agent.loginProvider, event); } : undefined), endStartup = startupTiming.start('startup');
|
|
381
|
+
request = { sessionId: options.sessionId, mode: mode ?? 'session', signal, toolBridge: bridge, startupTiming };
|
|
288
382
|
const observeAbort = (source, initiator, reason) => { if (!source)
|
|
289
383
|
return; const record = () => { (request?.closeDiagnostics ?? runtime?.closeDiagnostics)?.record({ layer: 'adapter', initiator, reason, action: 'abort', changes: [{ field: 'adapter.turn-aborted', before: false, after: source.aborted }] }); }; source.addEventListener('abort', record, { once: true }); abortOffs.push(() => source.removeEventListener('abort', record)); };
|
|
290
384
|
observeAbort(original.signal, 'signal.caller', 'CALLER_ABORTED');
|
|
@@ -296,7 +390,12 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
296
390
|
try {
|
|
297
391
|
if (!Number.isSafeInteger(config.acpMaxMessageBytes) || config.acpMaxMessageBytes < 1)
|
|
298
392
|
throw new NeedError('SETTINGS_REQUIRED', '远程模型连接设置无效,请联系管理员检查', '有效的acpMaxMessageBytes');
|
|
299
|
-
const
|
|
393
|
+
const standardCheckpoint = readPointer(options, this.agent), recoveredCheckpoint = await this.coldRecovery?.previousPointer(options);
|
|
394
|
+
const checkpoint = recoveredCheckpoint && (!standardCheckpoint || recoveredCheckpoint.index > standardCheckpoint.index) ? recoveredCheckpoint : standardCheckpoint, previous = checkpoint?.pointer ?? (checkpoint === recoveredCheckpoint ? standardCheckpoint?.pointer : undefined);
|
|
395
|
+
const usedColdCheckpoint = !!recoveredCheckpoint && checkpoint === recoveredCheckpoint;
|
|
396
|
+
let checkpointIndex = usedColdCheckpoint ? -1 : checkpoint?.index ?? -1;
|
|
397
|
+
if (usedColdCheckpoint)
|
|
398
|
+
options = { ...options, messages: options.messages.filter((m, index) => index > checkpoint.index || m.role === 'system' || m.role === 'developer') };
|
|
300
399
|
employeeNoticeShown = !!key && this.employeeNoticeSessions.has(key) || false;
|
|
301
400
|
if (employeeNoticeShown && key)
|
|
302
401
|
this.employeeNoticeSessions.add(key);
|
|
@@ -318,9 +417,34 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
318
417
|
request.userInputIds = Object.freeze(humanIds);
|
|
319
418
|
request.userMessageIds = request.userInputIds;
|
|
320
419
|
earlyStage = 'source-context';
|
|
321
|
-
await this.resolveRuntime.preflight?.(request);
|
|
420
|
+
await startupTiming.run('source-admission', async () => this.resolveRuntime.preflight?.(request));
|
|
421
|
+
options = { ...await this.coldRecovery?.projectCancelledInputs?.(options) ?? options, signal };
|
|
422
|
+
if (!usedColdCheckpoint)
|
|
423
|
+
checkpointIndex = readPointer(options, this.agent)?.index ?? -1;
|
|
424
|
+
const receipts = this.steeringReceipts && options.sessionId ? await this.steeringReceipts.read(options.sessionId, options.provider, humanIds) : new Map();
|
|
425
|
+
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));
|
|
426
|
+
const uncertain = new Set(matching.filter(r => r.outcome === 'prepared' || r.outcome === 'unknown').map(r => {
|
|
427
|
+
if (!previous || r.nativeSessionId !== previous.sessionId)
|
|
428
|
+
throw new NeedError('SESSION_CONTEXT_MISMATCH', '中途消息属于另一原生轮,未重复提交。', '原会话的中途消息回执与检查点');
|
|
429
|
+
return r.messageId;
|
|
430
|
+
}));
|
|
431
|
+
const receiptNotice = uncertain.size ? '\n中途消息送达未确认,已保留记录,没有重复发送。原轮结果已保留;请核对原轮输出,之后可在原会话继续。\n' : undefined;
|
|
432
|
+
const injected = new Set(matching.filter(r => r.outcome === 'injected').map(r => { if (!previous || r.nativeSessionId !== previous.sessionId)
|
|
433
|
+
throw new NeedError('SESSION_CONTEXT_MISMATCH', '中途消息属于另一原生轮,未重复提交。', '原会话的注入回执与检查点'); return r.messageId; }));
|
|
434
|
+
const withheld = new Set([...injected, ...uncertain]);
|
|
435
|
+
if (humanIds.length && humanIds.every(id => withheld.has(id))) {
|
|
436
|
+
if (receiptNotice) {
|
|
437
|
+
const notice = new StreamMapper();
|
|
438
|
+
yield* notice.text(receiptNotice);
|
|
439
|
+
yield* notice.flush();
|
|
440
|
+
}
|
|
441
|
+
yield { type: 'finish', reason: { kind: 'stop' }, replayState: { response: previous } };
|
|
442
|
+
succeeded = true;
|
|
443
|
+
return;
|
|
444
|
+
}
|
|
445
|
+
const projected = { ...options, messages: options.messages.filter((m, index) => index <= checkpointIndex || !('id' in m) || typeof m.id !== 'string' || !withheld.has(m.id)) };
|
|
322
446
|
earlyStage = 'input-prepare';
|
|
323
|
-
let input = await prepareInput(
|
|
447
|
+
let input = await startupTiming.run('input-prepare', () => prepareInput(projected, this.readImage));
|
|
324
448
|
const contextSha256 = createHash('sha256').update(input.systemPrompt ?? '').digest('hex');
|
|
325
449
|
request.contextSha256 = contextSha256;
|
|
326
450
|
const codex = this.agent.loginProvider === 'codex';
|
|
@@ -336,7 +460,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
336
460
|
options.signal = modelSignal;
|
|
337
461
|
request.signal = modelSignal;
|
|
338
462
|
earlyStage = 'runtime-resolve';
|
|
339
|
-
runtime = await this.resolveRuntime(request);
|
|
463
|
+
runtime = await startupTiming.run('runtime-resolve', () => this.resolveRuntime(request));
|
|
340
464
|
const closeSink = runtime.details;
|
|
341
465
|
runtime.closeDiagnostics ??= new CloseDiagnostics(event => closeSink?.record(event));
|
|
342
466
|
signal.throwIfAborted();
|
|
@@ -348,13 +472,14 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
348
472
|
}
|
|
349
473
|
if (previous && !runtime.hostSource && (previous.identity !== runtime.identity || previous.cwd !== runtime.cwd || previous.bindingId && previous.bindingId !== runtime.binding?.bindingId || previous.workspaceId && previous.workspaceId !== runtime.binding?.workspaceId))
|
|
350
474
|
throw new NeedError('SESSION_CONTEXT_MISMATCH', '原会话的员工主机或工作区已改变,请新建会话', '原会话的可信目标和工作区');
|
|
351
|
-
input = await prepareContinuation({ ...options, messages:
|
|
475
|
+
input = await prepareContinuation({ ...options, messages: projected.messages.slice(checkpointIndex + 1) }, input, this.readImage, { maxBytes: config.acpMaxMessageBytes, host: runtime.hostWorkspace });
|
|
352
476
|
if (runtime.hostWorkspace && mode === 'session' && Buffer.byteLength(JSON.stringify({ prompt: input.prompt, systemPrompt: input.systemPrompt }), 'utf8') > config.acpMaxMessageBytes)
|
|
353
477
|
throw new NeedError('ACP_MESSAGE_TOO_LARGE', '本轮输入超过已设置的会话消息容量,未截断或发送', '管理员调整acpMaxMessageBytes');
|
|
354
478
|
const details = runtime.details ?? await createRemoteDetails({ warn: line => console.warn(line) }).open({ sessionId: options.sessionId ?? 'unscoped', provider: this.agent.loginProvider, identity: runtime.identity, connection: runtime.connection });
|
|
479
|
+
startupTiming.bind(event => details.record(event));
|
|
355
480
|
if (bridge && runtime.employeeExecutionMeta && !runtime.hostWorkspace && bridge.table.size) {
|
|
356
481
|
bridge.enable(event => details.record(event));
|
|
357
|
-
bridgeMcp = await openToolBridgeMcp(bridge, config.acpMaxMessageBytes);
|
|
482
|
+
bridgeMcp = await startupTiming.run('bridge-open', () => openToolBridgeMcp(bridge, config.acpMaxMessageBytes));
|
|
358
483
|
}
|
|
359
484
|
recordInformation();
|
|
360
485
|
request.recordEarlyFailure = undefined;
|
|
@@ -362,18 +487,19 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
362
487
|
details.record({ kind: 'session', severity: input.historyTransfer.omittedRounds ? 'warning' : 'info', code: input.historyTransfer.omittedRounds ? 'HISTORY_TRANSFER_TRIMMED' : 'HISTORY_TRANSFER', summary: input.historyTransfer.omittedRounds ? `可见历史超过既有会话消息容量,保留最近${input.historyTransfer.retainedRounds}轮,省略较早${input.historyTransfer.omittedRounds}轮;当前输入完整保留。` : '已补充当前远端会话尚未见过的可见对话,未重放工具或审批。', payload: input.historyTransfer });
|
|
363
488
|
if (runtime.hostWorkspace)
|
|
364
489
|
details.record({ kind: 'session', severity: 'info', code: 'HOST_WORKSPACE_CONTEXT', summary: '本轮模型工作区上下文及审批会话目录使用已确认的主机目录。', payload: { source: 'host', cwd: runtime.hostWorkspace.cwd } });
|
|
365
|
-
const mapper = new StreamMapper(
|
|
490
|
+
const mapper = new StreamMapper(observation => details.record(observation));
|
|
366
491
|
activeMapper = mapper;
|
|
367
492
|
let id;
|
|
368
493
|
let stop;
|
|
369
494
|
const pointerRuntime = runtime;
|
|
370
|
-
const makePointer = (nativeId) => ({ ...(pointerRuntime.hostSource ? { hostSource: pointerRuntime.hostSource } : {}), ...(modelConfiguration ? { modelConfiguration } : {}), version: 2, agent: this.agent.id, contextSha256, ...(
|
|
495
|
+
const makePointer = (nativeId) => ({ ...(pointerRuntime.cold ? { coldRoundId: pointerRuntime.cold.id } : {}), ...(pointerRuntime.hostSource ? { hostSource: pointerRuntime.hostSource } : {}), ...(modelConfiguration ? { modelConfiguration } : {}), version: 2, agent: this.agent.id, contextSha256, ...(options.sessionId ? { dshSessionId: options.sessionId } : {}), identity: pointerRuntime.identity, cwd: pointerRuntime.cwd, sessionId: nativeId, ...(pointerRuntime.binding ? { bindingId: pointerRuntime.binding.bindingId, workspaceId: pointerRuntime.binding.workspaceId } : {}) });
|
|
371
496
|
if (runtime.employeePresentation)
|
|
372
497
|
details.record({ kind: 'session', severity: 'warning', code: 'EMPLOYEE_EXECUTION_SCOPE', summary: runtime.employeePresentation, payload: { source: 'local' } });
|
|
373
498
|
if (runtime.execution)
|
|
374
499
|
details.record({ kind: 'session', severity: 'warning', code: 'CLAUDE_EMPLOYEE_SCOPE', summary: runtime.execution.notice, payload: runtime.execution.scope });
|
|
375
500
|
if ((runtime.employeePresentation || runtime.execution) && !employeeNoticeShown) {
|
|
376
|
-
|
|
501
|
+
coldPrelude = EMPLOYEE_EXECUTION_NOTICE + (bridge?.enabled ? '\n\n' + TOOLBRIDGE_NOTICE : '') + '\n\n';
|
|
502
|
+
for (const chunk of mapper.text(coldPrelude)) {
|
|
377
503
|
if (chunk.type === 'text-delta') {
|
|
378
504
|
employeeNoticeShown = true;
|
|
379
505
|
if (key) {
|
|
@@ -395,9 +521,16 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
395
521
|
let done = false;
|
|
396
522
|
let failure;
|
|
397
523
|
const push = (chunks) => { queue.push(...chunks); wake?.(); wake = undefined; };
|
|
524
|
+
let renderTail = Promise.resolve(), nativeUpdates = 0, coldPromptStarted = false;
|
|
525
|
+
const render = (work) => { renderTail = renderTail.then(work); void renderTail.catch(error => { failure ??= error; session?.close({ layer: 'adapter', initiator: 'adapter.render-failure', reason: closeCode(error, 'MAPPING_FAILED'), action: 'close' }); wake?.(); }); };
|
|
526
|
+
const renderNotice = (text) => render(async () => { if (runtime.cold)
|
|
527
|
+
await runtime.cold.store.update(options.sessionId, options.provider, runtime.cold.id, row => { (row.localNotices ??= []).push({ beforeUpdate: nativeUpdates, text }); }); push(mapper.text(text)); });
|
|
528
|
+
if (receiptNotice)
|
|
529
|
+
renderNotice(receiptNotice);
|
|
398
530
|
let promptPermit;
|
|
399
531
|
let confirmedNativeMode;
|
|
400
|
-
|
|
532
|
+
let endDispatch = () => { };
|
|
533
|
+
const hooks = { closeDiagnostics: runtime.closeDiagnostics, broker: runtime.broker, sessionOwnership: runtime.sessionOwnership, employeeExecution: runtime.employeeExecution, startupTiming, onPromptDispatched: () => { endDispatch(); endStartup(); }, ...this.permissions ? { promptGuard: () => {
|
|
401
534
|
if (!promptPermit)
|
|
402
535
|
throw new NeedError('PERMISSION_POLICY_CHANGED', '当前权限没有保持确认,本次没有继续派发。', '当前权限代次和同值回执');
|
|
403
536
|
return promptPermit;
|
|
@@ -419,25 +552,36 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
419
552
|
}
|
|
420
553
|
}
|
|
421
554
|
if (execution) {
|
|
422
|
-
if (toolName && ['
|
|
555
|
+
if (toolName && ['Read', 'Write', 'Edit', 'Glob', 'Grep', 'Bash'].includes(toolName)) {
|
|
423
556
|
details.record({ kind: 'need', severity: 'warning', code: 'CLAUDE_HOST_TOOL_UNSUPPORTED', summary: '这类原生调用没有经过员工端别名,本机来源不支持;本次审批已取消', payload: { operation: toolName } });
|
|
424
|
-
|
|
557
|
+
renderNotice('\n这类操作尚不支持在本机执行,已取消本次审批,没有在主机代跑。\n');
|
|
425
558
|
return 'cancelled';
|
|
426
559
|
}
|
|
427
560
|
}
|
|
428
561
|
const answer = await this.approve?.(permission, approvalSignal, options, execution && toolName?.startsWith('mcp__employee__') ? 'employee-local' : undefined, runtime.hostWorkspace) ?? 'unavailable';
|
|
429
562
|
return answer;
|
|
430
|
-
}, onEmployeeNotice: notice =>
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
563
|
+
}, onEmployeeNotice: notice => renderNotice(notice + '\n\n'), onUpdate: (notification, originSequence) => { const fromPrompt = coldPromptStarted; render(async () => { let inRound = fromPrompt; if (fromPrompt && runtime.cold) {
|
|
564
|
+
const start = await runtime.cold.bound;
|
|
565
|
+
if (!Number.isSafeInteger(originSequence))
|
|
566
|
+
throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '原输出通知的来源未确认', '原broker输出序号');
|
|
567
|
+
inRound = originSequence > start;
|
|
568
|
+
if (!inRound) {
|
|
569
|
+
const update = notification.update;
|
|
570
|
+
if ((update.sessionUpdate === 'agent_message_chunk' || update.sessionUpdate === 'agent_thought_chunk') && update.content.type === 'text' && update.content.text) {
|
|
571
|
+
const text = update.content.text, kind = update.sessionUpdate === 'agent_thought_chunk' ? 'reasoning' : 'text';
|
|
572
|
+
await runtime.cold.store.update(options.sessionId, options.provider, runtime.cold.id, row => { (row.localNotices ??= []).push({ beforeUpdate: nativeUpdates, text, kind }); });
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
} bridge?.observe(notification.update); push(mapper.acp(notification.update)); if (inRound)
|
|
576
|
+
nativeUpdates++; }); }, onResponse: response => render(async () => {
|
|
577
|
+
// 可靠回执先持久化,再向DSH投影;退出后即使原broker被回收也能补记同轮未落盘用量。
|
|
578
|
+
if (runtime.cold)
|
|
579
|
+
await runtime.cold.store.update(options.sessionId, options.provider, runtime.cold.id, row => { row.terminal = { kind: 'result', value: response }; row.phase = 'terminal'; row.terminalAfter = runtime.broker?.lastSequence; });
|
|
580
|
+
push(mapper.acpResponse(response));
|
|
581
|
+
}), onDetail: detail => details.record(detail) };
|
|
438
582
|
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 });
|
|
439
583
|
session = new AcpSession(transport, hooks);
|
|
440
|
-
live = { session, runtime, configuration, contextSha256,
|
|
584
|
+
live = { session, runtime, configuration, contextSha256, options, acceptingSteer: true, turnId: randomUUID(), steerIds: new Map(), steerTail: Promise.resolve(), maxBytes: config.acpMaxMessageBytes, notice: renderNotice };
|
|
441
585
|
if (key)
|
|
442
586
|
this.sessions.set(key, live);
|
|
443
587
|
promptBaseline = session.promptDispatchCount;
|
|
@@ -457,12 +601,13 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
457
601
|
return;
|
|
458
602
|
const remoteMode = permissionMode(this.agent.loginProvider, policy);
|
|
459
603
|
details.record({ kind: 'session', severity: 'info', code: 'DSH_PERMISSION_POLICY', summary: '按DSH当前会话权限同步远程工具;不会把关闭审批提示解释为自动批准。', payload: { ...policy, remoteMode } });
|
|
460
|
-
await session.selectPermissionMode(remoteMode, modelSignal, this.agent.loginProvider);
|
|
604
|
+
await startupTiming.run('permission-confirm', () => session.selectPermissionMode(remoteMode, modelSignal, this.agent.loginProvider));
|
|
461
605
|
confirmedNativeMode = remoteMode;
|
|
462
606
|
permissionKey = next;
|
|
463
607
|
});
|
|
464
608
|
};
|
|
465
609
|
const dispatchPrompt = async () => {
|
|
610
|
+
endDispatch = startupTiming.start('prompt-dispatch');
|
|
466
611
|
if (!this.permissions)
|
|
467
612
|
return session.prompt(input.prompt, modelSignal);
|
|
468
613
|
// New official policy events can append work while an ACK is awaited.
|
|
@@ -484,14 +629,14 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
484
629
|
const task = (async () => {
|
|
485
630
|
remoteAttempted = true;
|
|
486
631
|
try {
|
|
487
|
-
await session.start(runtime.execution?.hostCwd ?? runtime.cwd, previous?.sessionId, modelSignal, { systemPrompt: input.systemPrompt, ...(bridgeMcp ? { toolBridgeServers: bridgeMcp.mcpServers } : {}), ...(runtime.execution ? { employeeRouting: runtime.execution.routing } : {}), ...(codex ? { codexNewSessionOnly: true } : {}), ...(runtime.employeeExecutionMeta ? { employeeExecution: runtime.employeeExecutionMeta } : {}) }, input.prompt);
|
|
632
|
+
await session.start(runtime.execution?.hostCwd ?? runtime.cwd, previous?.sessionId, modelSignal, { systemPrompt: input.systemPrompt, systemPromptChanged: contextChanged, ...(bridgeMcp ? { toolBridgeServers: bridgeMcp.mcpServers } : {}), ...(runtime.execution ? { employeeRouting: runtime.execution.routing } : {}), ...(codex ? { codexNewSessionOnly: true, initialModel: selected.value } : {}), ...(runtime.employeeExecutionMeta ? { employeeExecution: runtime.employeeExecutionMeta } : {}) }, input.prompt);
|
|
488
633
|
}
|
|
489
634
|
catch (error) {
|
|
490
635
|
details.record({ kind: 'session', severity: 'action-required', code: 'SESSION_START_FAILED', summary: '远端会话建立或恢复失败,本轮用户输入未发送。', payload: { operation: previous ? 'resume-or-load' : 'new', reason: closeCode(error, 'ACP_FAILED'), promptDispatched: false } });
|
|
491
636
|
throw error;
|
|
492
637
|
}
|
|
493
638
|
try {
|
|
494
|
-
const actual = await session.selectModel(selected.value, options.reasoningEffort, modelSignal);
|
|
639
|
+
const actual = await startupTiming.run('model-confirm', () => session.selectModel(selected.value, options.reasoningEffort, modelSignal));
|
|
495
640
|
// This lease is tied to the trusted host-user and instance/epoch.
|
|
496
641
|
// Its mapping and this turn's exact setter ACK are different facts.
|
|
497
642
|
modelConfiguration = { selected: { ...selected, ...(options.reasoningEffort === undefined ? {} : { effort: options.reasoningEffort }) }, configured: actual, resolvedModel: selected.resolvedModel ?? selected.value, status: 'remote-configured', ...(this.agent.loginProvider === 'claude' ? { resolvedModelSource: 'host-user-catalog', sessionModelReported: false } : {}) };
|
|
@@ -534,6 +679,10 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
534
679
|
}
|
|
535
680
|
recordInformation();
|
|
536
681
|
details.beginTurn(runtime.detailContext?.() ?? { turn: null, step: null });
|
|
682
|
+
await renderTail;
|
|
683
|
+
if (runtime.cold && this.coldRecovery)
|
|
684
|
+
await this.coldRecovery.capture(runtime, options, session.id, { identity: runtime.identity, cwd: runtime.cwd, binding: runtime.binding, hostSource: runtime.hostSource, contextSha256, modelConfiguration, model: options.model, prelude: coldPrelude, localDirectory: runtime.localDirectory });
|
|
685
|
+
coldPromptStarted = true;
|
|
537
686
|
await runtime.execution?.beginTurn(modelSignal);
|
|
538
687
|
if (bridge?.enabled)
|
|
539
688
|
bridge.replayState = { response: makePointer(session.id) };
|
|
@@ -541,6 +690,8 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
541
690
|
id = session.id;
|
|
542
691
|
try {
|
|
543
692
|
const result = await dispatchPrompt();
|
|
693
|
+
live.acceptingSteer = false;
|
|
694
|
+
await live.steerTail;
|
|
544
695
|
if (bridge?.unsettled)
|
|
545
696
|
bridge.abandon('HOST_PROMPT_ENDED_WITH_PENDING_CALL');
|
|
546
697
|
permissionOff?.();
|
|
@@ -548,7 +699,13 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
548
699
|
await permissionTail;
|
|
549
700
|
return result;
|
|
550
701
|
}
|
|
702
|
+
catch (error) {
|
|
703
|
+
endDispatch('failed');
|
|
704
|
+
throw error;
|
|
705
|
+
}
|
|
551
706
|
finally {
|
|
707
|
+
live.acceptingSteer = false;
|
|
708
|
+
await live.steerTail;
|
|
552
709
|
permissionOff?.();
|
|
553
710
|
permissionOff = undefined;
|
|
554
711
|
bridge?.end();
|
|
@@ -556,7 +713,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
556
713
|
details.endTurn();
|
|
557
714
|
}
|
|
558
715
|
})();
|
|
559
|
-
void task.then(value => { stop = value; }, error => { failure ??= runtime.broker?.error ?? error; }).finally(() => { done = true; wake?.(); wake = undefined; });
|
|
716
|
+
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; });
|
|
560
717
|
while (!done || queue.length) {
|
|
561
718
|
if (queue.length)
|
|
562
719
|
yield queue.shift();
|
|
@@ -576,8 +733,6 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
576
733
|
details.endTurn();
|
|
577
734
|
if (!id)
|
|
578
735
|
throw new NeedError('SESSION_ID_MISSING', '远端没有返回会话标识', '有效的远端会话标识');
|
|
579
|
-
if (live)
|
|
580
|
-
live.usageSnapshot = mapper.usageSnapshot;
|
|
581
736
|
if (modelConfiguration) {
|
|
582
737
|
const actual = session.modelConfiguration;
|
|
583
738
|
const changed = !actual?.confirmed || actual.model !== modelConfiguration.configured.model || actual.effort !== modelConfiguration.configured.effort;
|
|
@@ -586,11 +741,14 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
586
741
|
}
|
|
587
742
|
}
|
|
588
743
|
yield* mapper.flush();
|
|
589
|
-
const
|
|
744
|
+
const finalCold = runtime.cold ? await runtime.cold.store.update(options.sessionId, options.provider, runtime.cold.id, row => { row.terminal ??= { kind: 'result', value: { stopReason: stop } }; row.phase = 'terminal'; row.terminalAfter = runtime.broker?.lastSequence; }) : undefined;
|
|
745
|
+
const pointer = { ...makePointer(id), ...(finalCold ? { coldRoundTerminal: true, coldPromptId: finalCold.promptId, coldOutputAfter: runtime.broker?.lastSequence } : {}) };
|
|
590
746
|
succeeded = true;
|
|
591
747
|
yield { type: 'finish', reason: { kind: stop === 'max_tokens' || stop === 'max_turn_requests' ? 'max-tokens' : 'stop' }, replayState: { response: pointer } };
|
|
592
748
|
}
|
|
593
749
|
catch (error) {
|
|
750
|
+
if (original.signal?.reason?.kind === 'user' && runtime?.cold && this.coldRecovery)
|
|
751
|
+
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 ?? '', modelConfiguration: modelConfiguration ?? { selected }, model: options.model, prelude: coldPrelude, localDirectory: runtime.localDirectory });
|
|
594
752
|
if (session && session.promptDispatchCount > promptBaseline)
|
|
595
753
|
onPromptDispatched();
|
|
596
754
|
if (bridge?.unsettled && !signal.aborted)
|
|
@@ -599,6 +757,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
599
757
|
runtime?.closeDiagnostics?.record({ layer: 'adapter', initiator: 'adapter.turn-failure', reason: closeCode(error, signal.aborted ? 'ABORTED' : 'TURN_FAILED'), action: 'failure' });
|
|
600
758
|
recordInformation();
|
|
601
759
|
failureCode = error instanceof NeedError || error instanceof ModelConfigurationError ? error.code : error instanceof LlmError ? error.code : 'TURN_PREPARATION_FAILED';
|
|
760
|
+
endStartup('failed');
|
|
602
761
|
withRemoteFailureEvidence(error, runtime?.employeeRemoteCloseReason?.(), failureCode);
|
|
603
762
|
activeMapper?.flushMetadata();
|
|
604
763
|
if (request?.recordEarlyFailure)
|
|
@@ -617,23 +776,29 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
617
776
|
if (bridgeMcp)
|
|
618
777
|
await bridgeMcp.close();
|
|
619
778
|
if (runtime) {
|
|
779
|
+
if (runtime.cold && key)
|
|
780
|
+
this.coldRecovery?.release(key, runtime.cold.id);
|
|
620
781
|
session?.close({ layer: 'adapter', initiator: 'adapter.turn-finally', reason: succeeded ? 'TURN_FINISHED' : 'TURN_FAILED', action: 'close' });
|
|
621
782
|
if (key && this.sessions.get(key) === live)
|
|
622
783
|
this.sessions.delete(key);
|
|
623
|
-
|
|
784
|
+
if (session && session.promptDispatchCount > promptBaseline && (runtime.cold && !succeeded && !bridge?.concludeAcknowledged || this.shuttingDown || key && this.detached.has(key) || original.signal?.reason?.kind === 'disposed'))
|
|
785
|
+
void runtime.detach?.({ layer: 'adapter', initiator: 'adapter.preserve-original', reason: 'SESSION_DETACHED', action: 'detach' });
|
|
786
|
+
else
|
|
787
|
+
void this.cleanupRuntime(runtime);
|
|
624
788
|
}
|
|
625
789
|
if (key && this.turns.get(key) === turn)
|
|
626
790
|
this.turns.delete(key);
|
|
627
|
-
if (key)
|
|
791
|
+
if (key) {
|
|
628
792
|
this.detached.delete(key);
|
|
793
|
+
}
|
|
629
794
|
}
|
|
630
795
|
}
|
|
631
796
|
}
|
|
632
797
|
/** One official registration owns both routes, preserving opaque replay ownership. */
|
|
633
798
|
export class RemoteAgentsAdapter extends LlmAdapter {
|
|
634
799
|
adapters = new Map();
|
|
635
|
-
constructor(config, makeRuntime, approve, nameFor, readImage, reportLoginFailure, directory, preflightDiagnostics, permissions, bridgeStopped) { super(); for (const agent of AGENTS)
|
|
636
|
-
this.adapters.set(agent.id, new CodexRemoteAdapter(config, makeRuntime(agent), approve, () => nameFor(agent), agent, readImage, reportLoginFailure, directory, preflightDiagnostics, permissions, bridgeStopped)); }
|
|
800
|
+
constructor(config, makeRuntime, approve, nameFor, readImage, reportLoginFailure, directory, preflightDiagnostics, permissions, bridgeStopped, steeringReceipts, coldRecovery) { super(); for (const agent of AGENTS)
|
|
801
|
+
this.adapters.set(agent.id, new CodexRemoteAdapter(config, makeRuntime(agent), approve, () => nameFor(agent), agent, readImage, reportLoginFailure, directory, preflightDiagnostics, permissions, bridgeStopped, steeringReceipts, coldRecovery)); }
|
|
637
802
|
adapter(provider) { const adapter = this.adapters.get(provider); if (!adapter)
|
|
638
803
|
throw new LlmError('远程模型未注册', 'PROVIDER_NOT_FOUND'); return adapter; }
|
|
639
804
|
providerInfo(provider) { return this.adapter(provider).providerInfo(provider); }
|
|
@@ -642,7 +807,7 @@ export class RemoteAgentsAdapter extends LlmAdapter {
|
|
|
642
807
|
async prepareCall(provider, model, signal) { const prepared = await this.adapter(provider).prepareCall(provider, model, signal); return { ...prepared, stream: (options) => this.stream(options) }; }
|
|
643
808
|
providerRetryPolicy() { return { mode: 'normal', maxRetries: 0, retryableCodes: [], initialDelayMs: 0, maxDelayMs: 0, jitterRatio: 0 }; }
|
|
644
809
|
stream(options) {
|
|
645
|
-
if (options.sessionId)
|
|
810
|
+
if (options.sessionId && !options.purpose)
|
|
646
811
|
for (const [provider, adapter] of this.adapters)
|
|
647
812
|
if (provider !== options.provider && adapter.hasBridgeSession(options.sessionId)) {
|
|
648
813
|
void adapter.disposeSession(options.sessionId);
|
|
@@ -650,6 +815,8 @@ export class RemoteAgentsAdapter extends LlmAdapter {
|
|
|
650
815
|
}
|
|
651
816
|
return this.adapter(options.provider).stream(options);
|
|
652
817
|
}
|
|
818
|
+
canSteer(provider, sessionId) { return this.adapters.get(provider)?.canSteer(sessionId) ?? false; }
|
|
819
|
+
steer(provider, sessionId, message, isCurrent) { return this.adapter(provider).steer(sessionId, message, isCurrent); }
|
|
653
820
|
async completeDshTurn(sessionId, messages) { await Promise.all([...this.adapters.values()].map(adapter => adapter.completeDshTurn(sessionId, messages))); }
|
|
654
821
|
async disposeSession(sessionId) { await Promise.all([...this.adapters.values()].map(adapter => adapter.disposeSession(sessionId))); }
|
|
655
822
|
async detachSession(sessionId) { await Promise.all([...this.adapters.values()].map(adapter => adapter.detachSession(sessionId))); }
|
|
@@ -665,7 +832,9 @@ export function apply(ctx, live) {
|
|
|
665
832
|
throw new NeedError('ATTACHMENT_REQUIRED', '我需要官方附件组件读取这张图片', '官方attachments.readImage');
|
|
666
833
|
return attachments.readImage(ref, signal);
|
|
667
834
|
};
|
|
668
|
-
const
|
|
835
|
+
const sessionSources = createSessionSources(ctx, get);
|
|
836
|
+
const coldRecovery = new ColdRecovery(ctx, get, config, { readSource: sessionSources.read });
|
|
837
|
+
const openByAgent = new Map(AGENTS.map(agent => [agent.id, brokerFactory(get, undefined, config, { coldStore: coldRecovery.store })]));
|
|
669
838
|
const detailManagers = new Map();
|
|
670
839
|
const managerForProfile = () => {
|
|
671
840
|
const profile = ctx.get('profileContext');
|
|
@@ -678,7 +847,6 @@ export function apply(ctx, live) {
|
|
|
678
847
|
return manager;
|
|
679
848
|
};
|
|
680
849
|
ctx.provide('aiWorkbenchRemoteDiagnostics', { read: (query) => managerForProfile().read(query) });
|
|
681
|
-
const sessionSources = createSessionSources(ctx, get);
|
|
682
850
|
const preflightDiagnostics = createPreflightDiagnostics({ ctx, getApi: get, manager: managerForProfile });
|
|
683
851
|
const diagnostics = new Map();
|
|
684
852
|
const diagnostic = (scope, provider, message) => {
|
|
@@ -697,6 +865,7 @@ export function apply(ctx, live) {
|
|
|
697
865
|
// Public Loader Entry.options.id; optional when mounted without Loader.
|
|
698
866
|
const actualSettingsNamespace = ctx.fiber.entry?.options.id;
|
|
699
867
|
const modelDirectory = new ModelCatalog(get, () => config().acpMaxMessageBytes, undefined, (provider, error) => managerForProfile().recordCatalogFailure(provider, error));
|
|
868
|
+
const steeringReceipts = createSteeringReceipts(ctx);
|
|
700
869
|
const adapter = new RemoteAgentsAdapter(config, agent => {
|
|
701
870
|
const details = async (request, api, connection, target) => {
|
|
702
871
|
return managerForProfile().open({ sessionId: request.sessionId, provider: agent.loginProvider, identity: `${target.username}@${target.host}:${target.port}`, connection });
|
|
@@ -728,8 +897,7 @@ export function apply(ctx, live) {
|
|
|
728
897
|
const workspace = async (request) => {
|
|
729
898
|
const services = ctx;
|
|
730
899
|
const registry = services.get('workspaceRegistry');
|
|
731
|
-
|
|
732
|
-
return officialEmployeeWorkspace(request.sessionId, registry, sessions?.get(request.sessionId)?.header);
|
|
900
|
+
return officialEmployeeWorkspace(request.sessionId, registry, services.get('sessions'));
|
|
733
901
|
};
|
|
734
902
|
const provider = connectProvider(get, { agent, workspace, source: sessionSources, ...(agent.loginProvider === 'codex' ? { employee: {
|
|
735
903
|
getNetwork: () => ctx.get('aiWorkbenchNetwork'),
|
|
@@ -776,7 +944,9 @@ export function apply(ctx, live) {
|
|
|
776
944
|
if (turn !== null && step !== null)
|
|
777
945
|
agent.session.append('assistant/message', { turn, step, message: createAssistantMessage({ content: [{ type: 'text', text: notice }], source: { provider: 'ai-workbench-toolbridge', model: 'notice' } }), stream: [] }, { surfaceOp: 'append' });
|
|
778
946
|
agent.cancel({ kind: 'hook', reason: 'DSH_BRIDGE_CALL_ABANDONED_BY_HOST' }, { keepInbox: true });
|
|
779
|
-
});
|
|
947
|
+
}, steeringReceipts, coldRecovery);
|
|
948
|
+
coldRecovery.install();
|
|
949
|
+
installLiveSteering(ctx, adapter);
|
|
780
950
|
ctx.on('session/event', (session, event) => { if (event.type === 'turn/end') {
|
|
781
951
|
const operation = event.data.reason.kind === 'completed' ? adapter.completeDshTurn(session.id, session.deriveMessages()) : adapter.disposeSession(session.id);
|
|
782
952
|
void operation.catch(() => ctx.logger('remote-agent').warn('TOOLBRIDGE_RESULT_DELIVERY_UNCONFIRMED'));
|
package/dist/input.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { NeedError } from "./remote.js";
|
|
2
|
+
import { dshSkillCatalog } from "./toolbridge-table.js";
|
|
2
3
|
function runtimeSections(message) {
|
|
3
4
|
const source = message.source;
|
|
4
5
|
if (message.role !== 'user' || source?.kind !== 'runtime-context' || source.form !== 'snapshot' || !Array.isArray(source.sections) || message.content.length !== 1 || message.content[0].type !== 'text')
|
|
@@ -138,7 +139,9 @@ export async function prepareInput(options, readImage) {
|
|
|
138
139
|
const before = prompt.length;
|
|
139
140
|
const sections = runtimeSections(message);
|
|
140
141
|
for (const block of message.content) {
|
|
141
|
-
|
|
142
|
+
let prepared = await publicBlock(block, options, readImage);
|
|
143
|
+
if (prepared.type === 'text' && dshSkillCatalog([message]) !== undefined)
|
|
144
|
+
prepared = { ...prepared, text: '以下是DSH的技能目录,供DSH工具skill使用;主机Claude/Codex原生技能按各自原生指令加载。加载后请按<skill_resources>给出的资源基址读取资源。\n' + prepared.text };
|
|
142
145
|
prompt.push(prepared);
|
|
143
146
|
if (sections)
|
|
144
147
|
runtimeSnapshots.set(prepared, sections);
|