@ai-workbench/remote-agent 0.9.0-toolbridge.13 → 0.9.0-toolbridge.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -3
- package/dist/acp.d.ts +5 -0
- package/dist/acp.js +52 -3
- package/dist/broker-runtime.d.ts +2 -0
- package/dist/broker-runtime.js +46 -3
- package/dist/broker.d.ts +41 -1
- package/dist/broker.js +237 -9
- package/dist/claude-local.js +26 -5
- package/dist/cold-protocol.d.ts +14 -0
- package/dist/cold-protocol.js +285 -0
- package/dist/cold-recovery.d.ts +53 -0
- package/dist/cold-recovery.js +427 -0
- package/dist/cold-store.d.ts +91 -0
- package/dist/cold-store.js +29 -0
- package/dist/employee-endpoint.js +15 -1
- package/dist/employee-provider.js +26 -6
- package/dist/index.d.ts +11 -2
- package/dist/index.js +178 -30
- package/dist/live-steering.d.ts +46 -0
- package/dist/live-steering.js +45 -0
- package/dist/provider.d.ts +11 -0
- package/dist/rpc-namespace.js +16 -2
- package/dist/session-source.d.ts +3 -1
- package/dist/session-source.js +2 -1
- package/dist/toolbridge-loop.d.ts +3 -2
- package/dist/toolbridge-loop.js +4 -2
- package/package.json +11 -10
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { ColdRecovery } from './cold-recovery.ts';
|
|
2
|
+
import { type SteeringReceipts } from './live-steering.ts';
|
|
1
3
|
import type { Context } from '@deepseek-ai/cordis';
|
|
2
4
|
import Schema from '@deepseek-ai/schemastery';
|
|
3
5
|
import { LlmAdapter, type GenerateOptions, type StreamChunk, type LlmResolvedModelInfo } from '@deepseek-ai/dsh-llm';
|
|
@@ -57,9 +59,12 @@ export declare class CodexRemoteAdapter extends LlmAdapter {
|
|
|
57
59
|
private readonly directory?;
|
|
58
60
|
private readonly preflightDiagnostics?;
|
|
59
61
|
private readonly permissions?;
|
|
62
|
+
private readonly steeringReceipts?;
|
|
63
|
+
private readonly coldRecovery?;
|
|
60
64
|
private bridgeLoop;
|
|
61
65
|
private config;
|
|
62
66
|
private sessions;
|
|
67
|
+
private injectedInputs;
|
|
63
68
|
private turns;
|
|
64
69
|
private lifetime;
|
|
65
70
|
private shuttingDown;
|
|
@@ -67,11 +72,13 @@ export declare class CodexRemoteAdapter extends LlmAdapter {
|
|
|
67
72
|
private modelPresentation;
|
|
68
73
|
private employeeNoticeSessions;
|
|
69
74
|
private pendingEmployeeNotices;
|
|
70
|
-
constructor(config: PluginConfig | (() => PluginConfig), resolveRuntime: RuntimeProvider, approve?: InvocationApproval | undefined, providerName?: () => string, agent?: AgentDefinition, readImage?: ImageReader | undefined, reportLoginFailure?: LoginFailureReporter | undefined, directory?: ModelDirectory | undefined, preflightDiagnostics?: PreflightDiagnostics | undefined, permissions?: PermissionSource | undefined, bridgeStopped?: (sessionId: string, notice: string) => void);
|
|
75
|
+
constructor(config: PluginConfig | (() => PluginConfig), resolveRuntime: RuntimeProvider, approve?: InvocationApproval | undefined, providerName?: () => string, agent?: AgentDefinition, readImage?: ImageReader | undefined, reportLoginFailure?: LoginFailureReporter | undefined, directory?: ModelDirectory | undefined, preflightDiagnostics?: PreflightDiagnostics | undefined, permissions?: PermissionSource | undefined, bridgeStopped?: (sessionId: string, notice: string) => void, steeringReceipts?: SteeringReceipts | undefined, coldRecovery?: ColdRecovery | undefined);
|
|
71
76
|
providerInfo(provider: string): {
|
|
72
77
|
id: string;
|
|
73
78
|
name: string;
|
|
74
79
|
};
|
|
80
|
+
canSteer(sessionId: string): boolean;
|
|
81
|
+
steer(sessionId: string, message: import('@deepseek-ai/dsh-llm').UserMessage, isCurrent?: () => boolean): Promise<void>;
|
|
75
82
|
private catalog;
|
|
76
83
|
listModels(provider: string): Promise<(LlmResolvedModelInfo & {
|
|
77
84
|
catalog: HostModel;
|
|
@@ -101,7 +108,7 @@ export declare class CodexRemoteAdapter extends LlmAdapter {
|
|
|
101
108
|
/** One official registration owns both routes, preserving opaque replay ownership. */
|
|
102
109
|
export declare class RemoteAgentsAdapter extends LlmAdapter {
|
|
103
110
|
private adapters;
|
|
104
|
-
constructor(config: () => PluginConfig, makeRuntime: (agent: AgentDefinition) => RuntimeProvider, approve: InvocationApproval, nameFor: (agent: AgentDefinition) => string, readImage?: ImageReader, reportLoginFailure?: LoginFailureReporter, directory?: ModelDirectory, preflightDiagnostics?: PreflightDiagnostics, permissions?: PermissionSource, bridgeStopped?: (sessionId: string, notice: string) => void);
|
|
111
|
+
constructor(config: () => PluginConfig, makeRuntime: (agent: AgentDefinition) => RuntimeProvider, approve: InvocationApproval, nameFor: (agent: AgentDefinition) => string, readImage?: ImageReader, reportLoginFailure?: LoginFailureReporter, directory?: ModelDirectory, preflightDiagnostics?: PreflightDiagnostics, permissions?: PermissionSource, bridgeStopped?: (sessionId: string, notice: string) => void, steeringReceipts?: SteeringReceipts, coldRecovery?: ColdRecovery);
|
|
105
112
|
private adapter;
|
|
106
113
|
providerInfo(provider: string): {
|
|
107
114
|
id: string;
|
|
@@ -124,6 +131,8 @@ export declare class RemoteAgentsAdapter extends LlmAdapter {
|
|
|
124
131
|
jitterRatio: number;
|
|
125
132
|
};
|
|
126
133
|
stream(options: GenerateOptions): AsyncGenerator<StreamChunk, any, any>;
|
|
134
|
+
canSteer(provider: string, sessionId: string): boolean;
|
|
135
|
+
steer(provider: string, sessionId: string, message: import('@deepseek-ai/dsh-llm').UserMessage, isCurrent?: () => boolean): Promise<void>;
|
|
127
136
|
completeDshTurn(sessionId: string, messages: GenerateOptions['messages']): Promise<void>;
|
|
128
137
|
disposeSession(sessionId: string): Promise<void>;
|
|
129
138
|
detachSession(sessionId: string): Promise<void>;
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { ColdRecovery } from "./cold-recovery.js";
|
|
2
|
+
import { createSteeringReceipts, installLiveSteering, steeringMessageDigest } from "./live-steering.js";
|
|
1
3
|
import { ToolBridgeLoop } from "./toolbridge-loop.js";
|
|
2
4
|
import { openToolBridgeMcp, TOOLBRIDGE_NOTICE } from "./toolbridge.js";
|
|
3
5
|
import { connectNeedMessage } from "./connect-need.js";
|
|
@@ -7,7 +9,7 @@ import { SessionId } from '@deepseek-ai/dsh-session';
|
|
|
7
9
|
import { createAssistantMessage } from '@deepseek-ai/dsh-llm';
|
|
8
10
|
import Schema from '@deepseek-ai/schemastery';
|
|
9
11
|
import { LlmAdapter, LlmError } from '@deepseek-ai/dsh-llm';
|
|
10
|
-
import { createHash } from 'node:crypto';
|
|
12
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
11
13
|
import * as unstable from '@agentclientprotocol/sdk/unstable';
|
|
12
14
|
import * as acp from '@agentclientprotocol/sdk';
|
|
13
15
|
import { AcpSession } from "./acp.js";
|
|
@@ -94,9 +96,12 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
94
96
|
directory;
|
|
95
97
|
preflightDiagnostics;
|
|
96
98
|
permissions;
|
|
99
|
+
steeringReceipts;
|
|
100
|
+
coldRecovery;
|
|
97
101
|
bridgeLoop;
|
|
98
102
|
config;
|
|
99
103
|
sessions = new Map();
|
|
104
|
+
injectedInputs = new Map();
|
|
100
105
|
turns = new Map();
|
|
101
106
|
lifetime = new AbortController();
|
|
102
107
|
shuttingDown = false;
|
|
@@ -104,7 +109,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
104
109
|
modelPresentation = new ModelPresentation();
|
|
105
110
|
employeeNoticeSessions = new Set();
|
|
106
111
|
pendingEmployeeNotices = new Set();
|
|
107
|
-
constructor(config, resolveRuntime, approve, providerName = () => CODEX_AGENT.name.zh, agent = CODEX_AGENT, readImage, reportLoginFailure, directory, preflightDiagnostics, permissions, bridgeStopped) {
|
|
112
|
+
constructor(config, resolveRuntime, approve, providerName = () => CODEX_AGENT.name.zh, agent = CODEX_AGENT, readImage, reportLoginFailure, directory, preflightDiagnostics, permissions, bridgeStopped, steeringReceipts, coldRecovery) {
|
|
108
113
|
super();
|
|
109
114
|
this.resolveRuntime = resolveRuntime;
|
|
110
115
|
this.approve = approve;
|
|
@@ -115,10 +120,82 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
115
120
|
this.directory = directory;
|
|
116
121
|
this.preflightDiagnostics = preflightDiagnostics;
|
|
117
122
|
this.permissions = permissions;
|
|
118
|
-
this.
|
|
123
|
+
this.steeringReceipts = steeringReceipts;
|
|
124
|
+
this.coldRecovery = coldRecovery;
|
|
125
|
+
this.bridgeLoop = new ToolBridgeLoop(readImage, bridgeStopped, (id, message) => this.injectedInputs.get(id)?.get(message.id) === steeringMessageDigest(message));
|
|
119
126
|
this.config = typeof config === 'function' ? config : () => config;
|
|
120
127
|
}
|
|
121
128
|
providerInfo(provider) { return { id: provider, name: this.providerName() }; }
|
|
129
|
+
canSteer(sessionId) { const live = this.sessions.get(sessionId); return !!this.steeringReceipts && !!live?.acceptingSteer && live.session.canSteer; }
|
|
130
|
+
steer(sessionId, message, isCurrent) {
|
|
131
|
+
const live = this.sessions.get(sessionId);
|
|
132
|
+
if (!live || !this.canSteer(sessionId))
|
|
133
|
+
return Promise.resolve();
|
|
134
|
+
const digest = steeringMessageDigest(message), valid = () => !isCurrent || isCurrent();
|
|
135
|
+
if (live.steerIds.get(message.id) === digest)
|
|
136
|
+
return live.steerTail;
|
|
137
|
+
live.steerIds.set(message.id, digest);
|
|
138
|
+
const work = live.steerTail.catch(() => { }).then(async () => {
|
|
139
|
+
if (!live.acceptingSteer || this.sessions.get(sessionId) !== live || !live.session.canSteer || !valid())
|
|
140
|
+
return;
|
|
141
|
+
const store = this.steeringReceipts, provider = live.options.provider, nativeSessionId = live.session.id;
|
|
142
|
+
const old = (await store.read(sessionId, provider, [message.id])).get(message.id);
|
|
143
|
+
if (!valid())
|
|
144
|
+
return;
|
|
145
|
+
if (old && old.messageSha256 !== digest && old.outcome !== 'deferred') {
|
|
146
|
+
live.notice?.('这条消息的旧版本已发送或送达未确认,不能撤回;编辑后的内容保留在队列,按下一步骤交付。');
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
if (old && old.outcome !== 'deferred') {
|
|
150
|
+
if (old.outcome !== 'injected' || old.nativeSessionId !== nativeSessionId) {
|
|
151
|
+
const error = new NeedError('INPUT_DELIVERY_UNCONFIRMED', '这条中途消息已有未确认的送达记录,没有再次发送。', '原轮中途消息回执');
|
|
152
|
+
live.steerFailure ??= error;
|
|
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
|
+
live.steerFailure ??= failure;
|
|
183
|
+
throw failure;
|
|
184
|
+
}
|
|
185
|
+
live.runtime.details?.record({ kind: 'need', severity: 'warning', code: error instanceof NeedError ? error.code : 'INPUT_DELIVERY_UNCONFIRMED', summary: '中途消息未发出,仍由官方队列后续处理。' });
|
|
186
|
+
}
|
|
187
|
+
});
|
|
188
|
+
const observed = work.catch(error => {
|
|
189
|
+
live.runtime.details?.record({ kind: 'need', severity: 'warning', code: error instanceof NeedError ? error.code : 'INPUT_DELIVERY_UNCONFIRMED', summary: '中途消息未确认,原消息没有丢弃或自动重发。' });
|
|
190
|
+
// Preserve uncertainty for this round, but known pre-dispatch failures do
|
|
191
|
+
// not poison later safe steering requests or unrelated future turns.
|
|
192
|
+
if (live.steerFailure === error)
|
|
193
|
+
throw error;
|
|
194
|
+
});
|
|
195
|
+
live.steerTail = observed;
|
|
196
|
+
void observed.catch(() => { });
|
|
197
|
+
return observed;
|
|
198
|
+
}
|
|
122
199
|
catalog(signal) { if (!this.directory)
|
|
123
200
|
throw new LlmError('无法获取模型列表:缺少可信主机目录能力', 'MODEL_CATALOG_UNAVAILABLE'); return this.directory.read(this.agent, signal); }
|
|
124
201
|
async listModels(provider) { const catalog = await this.catalog(this.lifetime.signal); try {
|
|
@@ -130,6 +207,9 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
130
207
|
catalog.release();
|
|
131
208
|
} }
|
|
132
209
|
async resolveModel(provider, id, signal) {
|
|
210
|
+
const recovered = this.coldRecovery?.recoveryModel(provider, id, signal);
|
|
211
|
+
if (recovered)
|
|
212
|
+
return recovered;
|
|
133
213
|
const displayed = this.modelPresentation.resolve(provider, id);
|
|
134
214
|
if (displayed)
|
|
135
215
|
return displayed;
|
|
@@ -175,10 +255,12 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
175
255
|
await this.cleanupRuntime(current.runtime);
|
|
176
256
|
}
|
|
177
257
|
async detachSession(sessionId) {
|
|
178
|
-
await this.bridgeLoop.cancel(sessionId);
|
|
179
258
|
const current = this.sessions.get(sessionId), turn = this.turns.get(sessionId);
|
|
180
259
|
if (!current && !turn)
|
|
181
260
|
return;
|
|
261
|
+
if (current?.runtime.broker?.supportsRecovery)
|
|
262
|
+
current.session.close({ layer: 'adapter', initiator: 'adapter.detach-sdk', reason: 'SESSION_DETACHED', action: 'detach' });
|
|
263
|
+
await this.bridgeLoop.cancel(sessionId);
|
|
182
264
|
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
265
|
this.detached.add(sessionId);
|
|
184
266
|
if (current) {
|
|
@@ -198,17 +280,28 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
198
280
|
for (const live of this.sessions.values())
|
|
199
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 }] });
|
|
200
282
|
this.shuttingDown = true;
|
|
201
|
-
await this.bridgeLoop.dispose();
|
|
202
283
|
this.modelPresentation.clear();
|
|
203
284
|
this.employeeNoticeSessions.clear();
|
|
204
285
|
this.pendingEmployeeNotices.clear();
|
|
205
286
|
const results = await Promise.allSettled([...new Set([...this.sessions.keys(), ...this.turns.keys()])].map(id => this.detachSession(id)));
|
|
287
|
+
await this.bridgeLoop.dispose();
|
|
206
288
|
this.lifetime.abort();
|
|
207
289
|
const failure = results.find(result => result.status === 'rejected');
|
|
208
290
|
if (failure?.status === 'rejected')
|
|
209
291
|
throw failure.reason;
|
|
210
292
|
}
|
|
211
293
|
async *stream(options) {
|
|
294
|
+
if (this.coldRecovery?.canRecover(options)) {
|
|
295
|
+
try {
|
|
296
|
+
yield* this.coldRecovery.stream(options);
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
299
|
+
catch (error) {
|
|
300
|
+
if (error instanceof NeedError)
|
|
301
|
+
throw new LlmError(error.message, error.code, { cause: error });
|
|
302
|
+
throw error;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
212
305
|
// Before the tool bridge: a parked turn must not take a background request for its own continuation.
|
|
213
306
|
if (options.purpose)
|
|
214
307
|
throw new LlmError(employeeFailure('PURPOSE_UNSUPPORTED', this.agent.loginProvider, false), 'PURPOSE_UNSUPPORTED');
|
|
@@ -259,7 +352,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
259
352
|
if (key)
|
|
260
353
|
this.turns.set(key, turn);
|
|
261
354
|
const signal = AbortSignal.any([this.lifetime.signal, turn.signal, ...(original.signal ? [original.signal] : [])]);
|
|
262
|
-
|
|
355
|
+
let options = { ...original, signal };
|
|
263
356
|
const abortOffs = [];
|
|
264
357
|
let bridgeMcp;
|
|
265
358
|
let request;
|
|
@@ -276,6 +369,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
276
369
|
let selected;
|
|
277
370
|
let modelConfiguration;
|
|
278
371
|
let turnFailure;
|
|
372
|
+
let coldPrelude = '';
|
|
279
373
|
let employeeNoticeShown = false;
|
|
280
374
|
let permissionOff;
|
|
281
375
|
let permissionEpoch = new AbortController();
|
|
@@ -297,7 +391,12 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
297
391
|
try {
|
|
298
392
|
if (!Number.isSafeInteger(config.acpMaxMessageBytes) || config.acpMaxMessageBytes < 1)
|
|
299
393
|
throw new NeedError('SETTINGS_REQUIRED', '远程模型连接设置无效,请联系管理员检查', '有效的acpMaxMessageBytes');
|
|
300
|
-
const
|
|
394
|
+
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 usedColdCheckpoint = !!recoveredCheckpoint && checkpoint === recoveredCheckpoint;
|
|
397
|
+
const checkpointIndex = usedColdCheckpoint ? -1 : checkpoint?.index ?? -1;
|
|
398
|
+
if (usedColdCheckpoint)
|
|
399
|
+
options = { ...options, messages: options.messages.filter((m, index) => index > checkpoint.index || m.role === 'system' || m.role === 'developer') };
|
|
301
400
|
employeeNoticeShown = !!key && this.employeeNoticeSessions.has(key) || false;
|
|
302
401
|
if (employeeNoticeShown && key)
|
|
303
402
|
this.employeeNoticeSessions.add(key);
|
|
@@ -320,8 +419,21 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
320
419
|
request.userMessageIds = request.userInputIds;
|
|
321
420
|
earlyStage = 'source-context';
|
|
322
421
|
await this.resolveRuntime.preflight?.(request);
|
|
422
|
+
const receipts = this.steeringReceipts && options.sessionId ? await this.steeringReceipts.read(options.sessionId, options.provider, humanIds) : new Map();
|
|
423
|
+
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
|
+
for (const receipt of matching)
|
|
425
|
+
if (receipt.outcome === 'prepared' || receipt.outcome === 'unknown')
|
|
426
|
+
throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '中途消息送达结果未知,没有在下一步骤重复提交;请核对原轮状态。', '原生注入回执');
|
|
427
|
+
const injected = new Set(matching.filter(r => r.outcome === 'injected').map(r => { if (!previous || r.nativeSessionId !== previous.sessionId)
|
|
428
|
+
throw new NeedError('SESSION_CONTEXT_MISMATCH', '中途消息属于另一原生轮,未重复提交。', '原会话的注入回执与检查点'); return r.messageId; }));
|
|
429
|
+
if (humanIds.length && humanIds.every(id => injected.has(id))) {
|
|
430
|
+
yield { type: 'finish', reason: { kind: 'stop' }, replayState: { response: previous } };
|
|
431
|
+
succeeded = true;
|
|
432
|
+
return;
|
|
433
|
+
}
|
|
434
|
+
const projected = { ...options, messages: options.messages.filter((m, index) => index <= checkpointIndex || !('id' in m) || typeof m.id !== 'string' || !injected.has(m.id)) };
|
|
323
435
|
earlyStage = 'input-prepare';
|
|
324
|
-
let input = await prepareInput(
|
|
436
|
+
let input = await prepareInput(projected, this.readImage);
|
|
325
437
|
const contextSha256 = createHash('sha256').update(input.systemPrompt ?? '').digest('hex');
|
|
326
438
|
request.contextSha256 = contextSha256;
|
|
327
439
|
const codex = this.agent.loginProvider === 'codex';
|
|
@@ -349,7 +461,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
349
461
|
}
|
|
350
462
|
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))
|
|
351
463
|
throw new NeedError('SESSION_CONTEXT_MISMATCH', '原会话的员工主机或工作区已改变,请新建会话', '原会话的可信目标和工作区');
|
|
352
|
-
input = await prepareContinuation({ ...options, messages:
|
|
464
|
+
input = await prepareContinuation({ ...options, messages: projected.messages.slice(checkpointIndex + 1) }, input, this.readImage, { maxBytes: config.acpMaxMessageBytes, host: runtime.hostWorkspace });
|
|
353
465
|
if (runtime.hostWorkspace && mode === 'session' && Buffer.byteLength(JSON.stringify({ prompt: input.prompt, systemPrompt: input.systemPrompt }), 'utf8') > config.acpMaxMessageBytes)
|
|
354
466
|
throw new NeedError('ACP_MESSAGE_TOO_LARGE', '本轮输入超过已设置的会话消息容量,未截断或发送', '管理员调整acpMaxMessageBytes');
|
|
355
467
|
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 });
|
|
@@ -368,13 +480,14 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
368
480
|
let id;
|
|
369
481
|
let stop;
|
|
370
482
|
const pointerRuntime = runtime;
|
|
371
|
-
const makePointer = (nativeId) => ({ ...(pointerRuntime.hostSource ? { hostSource: pointerRuntime.hostSource } : {}), ...(modelConfiguration ? { modelConfiguration } : {}), version: 2, agent: this.agent.id, contextSha256, ...(mode === 'session' ? { usageSnapshot: mapper.usageSnapshot } : {}), ...(options.sessionId ? { dshSessionId: options.sessionId } : {}), identity: pointerRuntime.identity, cwd: pointerRuntime.cwd, sessionId: nativeId, ...(pointerRuntime.binding ? { bindingId: pointerRuntime.binding.bindingId, workspaceId: pointerRuntime.binding.workspaceId } : {}) });
|
|
483
|
+
const makePointer = (nativeId) => ({ ...(pointerRuntime.cold ? { coldRoundId: pointerRuntime.cold.id } : {}), ...(pointerRuntime.hostSource ? { hostSource: pointerRuntime.hostSource } : {}), ...(modelConfiguration ? { modelConfiguration } : {}), version: 2, agent: this.agent.id, contextSha256, ...(mode === 'session' ? { usageSnapshot: mapper.usageSnapshot } : {}), ...(options.sessionId ? { dshSessionId: options.sessionId } : {}), identity: pointerRuntime.identity, cwd: pointerRuntime.cwd, sessionId: nativeId, ...(pointerRuntime.binding ? { bindingId: pointerRuntime.binding.bindingId, workspaceId: pointerRuntime.binding.workspaceId } : {}) });
|
|
372
484
|
if (runtime.employeePresentation)
|
|
373
485
|
details.record({ kind: 'session', severity: 'warning', code: 'EMPLOYEE_EXECUTION_SCOPE', summary: runtime.employeePresentation, payload: { source: 'local' } });
|
|
374
486
|
if (runtime.execution)
|
|
375
487
|
details.record({ kind: 'session', severity: 'warning', code: 'CLAUDE_EMPLOYEE_SCOPE', summary: runtime.execution.notice, payload: runtime.execution.scope });
|
|
376
488
|
if ((runtime.employeePresentation || runtime.execution) && !employeeNoticeShown) {
|
|
377
|
-
|
|
489
|
+
coldPrelude = EMPLOYEE_EXECUTION_NOTICE + (bridge?.enabled ? '\n\n' + TOOLBRIDGE_NOTICE : '') + '\n\n';
|
|
490
|
+
for (const chunk of mapper.text(coldPrelude)) {
|
|
378
491
|
if (chunk.type === 'text-delta') {
|
|
379
492
|
employeeNoticeShown = true;
|
|
380
493
|
if (key) {
|
|
@@ -396,6 +509,10 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
396
509
|
let done = false;
|
|
397
510
|
let failure;
|
|
398
511
|
const push = (chunks) => { queue.push(...chunks); wake?.(); wake = undefined; };
|
|
512
|
+
let renderTail = Promise.resolve(), nativeUpdates = 0, coldPromptStarted = false;
|
|
513
|
+
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?.(); }); };
|
|
514
|
+
const renderNotice = (text) => render(async () => { if (runtime.cold)
|
|
515
|
+
await runtime.cold.store.update(options.sessionId, options.provider, runtime.cold.id, row => { (row.localNotices ??= []).push({ beforeUpdate: nativeUpdates, text }); }); push(mapper.text(text)); });
|
|
399
516
|
let promptPermit;
|
|
400
517
|
let confirmedNativeMode;
|
|
401
518
|
const hooks = { closeDiagnostics: runtime.closeDiagnostics, broker: runtime.broker, sessionOwnership: runtime.sessionOwnership, employeeExecution: runtime.employeeExecution, ...this.permissions ? { promptGuard: () => {
|
|
@@ -422,23 +539,17 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
422
539
|
if (execution) {
|
|
423
540
|
if (toolName && ['Agent', 'Task', 'TaskOutput', 'TaskStop', 'Read', 'Write', 'Edit', 'Glob', 'Grep', 'Bash'].includes(toolName)) {
|
|
424
541
|
details.record({ kind: 'need', severity: 'warning', code: 'CLAUDE_HOST_TOOL_UNSUPPORTED', summary: '这类原生调用没有经过员工端别名,本机来源不支持;本次审批已取消', payload: { operation: toolName } });
|
|
425
|
-
|
|
542
|
+
renderNotice('\n这类操作尚不支持在本机执行,已取消本次审批,没有在主机代跑。\n');
|
|
426
543
|
return 'cancelled';
|
|
427
544
|
}
|
|
428
545
|
}
|
|
429
546
|
const answer = await this.approve?.(permission, approvalSignal, options, execution && toolName?.startsWith('mcp__employee__') ? 'employee-local' : undefined, runtime.hostWorkspace) ?? 'unavailable';
|
|
430
547
|
return answer;
|
|
431
|
-
}, onEmployeeNotice: notice =>
|
|
432
|
-
|
|
433
|
-
push(mapper.acp(notification.update));
|
|
434
|
-
}
|
|
435
|
-
catch (error) {
|
|
436
|
-
failure = error;
|
|
437
|
-
session?.close({ layer: 'adapter', initiator: 'adapter.mapper-failure', reason: closeCode(error, 'MAPPING_FAILED'), action: 'close' });
|
|
438
|
-
} }, onResponse: response => push(mapper.acpResponse(response)), onDetail: detail => details.record(detail) };
|
|
548
|
+
}, onEmployeeNotice: notice => renderNotice(notice + '\n\n'), onUpdate: notification => { const fromPrompt = coldPromptStarted; render(() => { bridge?.observe(notification.update); push(mapper.acp(notification.update)); if (fromPrompt)
|
|
549
|
+
nativeUpdates++; }); }, onResponse: response => render(() => { push(mapper.acpResponse(response)); }), onDetail: detail => details.record(detail) };
|
|
439
550
|
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 });
|
|
440
551
|
session = new AcpSession(transport, hooks);
|
|
441
|
-
live = { session, runtime, configuration, contextSha256, usageSnapshot: mapper.usageSnapshot };
|
|
552
|
+
live = { session, runtime, configuration, contextSha256, usageSnapshot: mapper.usageSnapshot, options, acceptingSteer: true, turnId: randomUUID(), steerIds: new Map(), steerTail: Promise.resolve(), maxBytes: config.acpMaxMessageBytes, notice: renderNotice };
|
|
442
553
|
if (key)
|
|
443
554
|
this.sessions.set(key, live);
|
|
444
555
|
promptBaseline = session.promptDispatchCount;
|
|
@@ -535,13 +646,22 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
535
646
|
}
|
|
536
647
|
recordInformation();
|
|
537
648
|
details.beginTurn(runtime.detailContext?.() ?? { turn: null, step: null });
|
|
649
|
+
await renderTail;
|
|
650
|
+
if (runtime.cold && this.coldRecovery)
|
|
651
|
+
await this.coldRecovery.capture(runtime, options, session.id, { identity: runtime.identity, cwd: runtime.cwd, binding: runtime.binding, hostSource: runtime.hostSource, contextSha256, baseline: mapper.usageSnapshot, modelConfiguration, model: options.model, prelude: coldPrelude, localDirectory: runtime.localDirectory });
|
|
652
|
+
coldPromptStarted = true;
|
|
538
653
|
await runtime.execution?.beginTurn(modelSignal);
|
|
539
654
|
if (bridge?.enabled)
|
|
540
655
|
bridge.replayState = { response: makePointer(session.id) };
|
|
541
656
|
bridge?.begin(modelSignal);
|
|
542
657
|
id = session.id;
|
|
658
|
+
let promptFailed = false;
|
|
543
659
|
try {
|
|
544
660
|
const result = await dispatchPrompt();
|
|
661
|
+
live.acceptingSteer = false;
|
|
662
|
+
await live.steerTail;
|
|
663
|
+
if (live.steerFailure)
|
|
664
|
+
throw live.steerFailure;
|
|
545
665
|
if (bridge?.unsettled)
|
|
546
666
|
bridge.abandon('HOST_PROMPT_ENDED_WITH_PENDING_CALL');
|
|
547
667
|
permissionOff?.();
|
|
@@ -549,7 +669,22 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
549
669
|
await permissionTail;
|
|
550
670
|
return result;
|
|
551
671
|
}
|
|
672
|
+
catch (error) {
|
|
673
|
+
promptFailed = true;
|
|
674
|
+
throw error;
|
|
675
|
+
}
|
|
552
676
|
finally {
|
|
677
|
+
live.acceptingSteer = false;
|
|
678
|
+
try {
|
|
679
|
+
await live.steerTail;
|
|
680
|
+
if (live.steerFailure)
|
|
681
|
+
throw live.steerFailure;
|
|
682
|
+
}
|
|
683
|
+
catch (error) {
|
|
684
|
+
if (!promptFailed)
|
|
685
|
+
throw error;
|
|
686
|
+
details.record({ kind: 'need', severity: 'warning', code: 'INPUT_DELIVERY_UNCONFIRMED', summary: '原轮失败且有中途消息未获送达确认,没有重发。' });
|
|
687
|
+
}
|
|
553
688
|
permissionOff?.();
|
|
554
689
|
permissionOff = undefined;
|
|
555
690
|
bridge?.end();
|
|
@@ -557,7 +692,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
557
692
|
details.endTurn();
|
|
558
693
|
}
|
|
559
694
|
})();
|
|
560
|
-
void task.then(value => { stop = value; }, error => { failure ??= runtime.broker?.error ?? error; }).finally(() => { done = true; wake?.(); wake = undefined; });
|
|
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; });
|
|
561
696
|
while (!done || queue.length) {
|
|
562
697
|
if (queue.length)
|
|
563
698
|
yield queue.shift();
|
|
@@ -587,7 +722,8 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
587
722
|
}
|
|
588
723
|
}
|
|
589
724
|
yield* mapper.flush();
|
|
590
|
-
const
|
|
725
|
+
const finalCold = runtime.cold ? await runtime.cold.store.update(options.sessionId, options.provider, runtime.cold.id, row => { row.finalUsage = mapper.usageSnapshot; row.terminal = { kind: 'result', value: { stopReason: stop } }; row.phase = 'terminal'; row.terminalAfter = runtime.broker?.lastSequence; }) : undefined;
|
|
726
|
+
const pointer = { ...makePointer(id), ...(finalCold ? { coldRoundTerminal: true, coldPromptId: finalCold.promptId, coldOutputAfter: runtime.broker?.lastSequence } : {}) };
|
|
591
727
|
succeeded = true;
|
|
592
728
|
yield { type: 'finish', reason: { kind: stop === 'max_tokens' || stop === 'max_turn_requests' ? 'max-tokens' : 'stop' }, replayState: { response: pointer } };
|
|
593
729
|
}
|
|
@@ -618,23 +754,29 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
618
754
|
if (bridgeMcp)
|
|
619
755
|
await bridgeMcp.close();
|
|
620
756
|
if (runtime) {
|
|
757
|
+
if (runtime.cold && key)
|
|
758
|
+
this.coldRecovery?.release(key, runtime.cold.id);
|
|
621
759
|
session?.close({ layer: 'adapter', initiator: 'adapter.turn-finally', reason: succeeded ? 'TURN_FINISHED' : 'TURN_FAILED', action: 'close' });
|
|
622
760
|
if (key && this.sessions.get(key) === live)
|
|
623
761
|
this.sessions.delete(key);
|
|
624
|
-
|
|
762
|
+
if (session && session.promptDispatchCount > promptBaseline && (runtime.cold || this.shuttingDown || key && this.detached.has(key) || original.signal?.reason?.kind === 'disposed'))
|
|
763
|
+
void runtime.detach?.({ layer: 'adapter', initiator: 'adapter.preserve-original', reason: 'SESSION_DETACHED', action: 'detach' });
|
|
764
|
+
else
|
|
765
|
+
void this.cleanupRuntime(runtime);
|
|
625
766
|
}
|
|
626
767
|
if (key && this.turns.get(key) === turn)
|
|
627
768
|
this.turns.delete(key);
|
|
628
|
-
if (key)
|
|
769
|
+
if (key) {
|
|
629
770
|
this.detached.delete(key);
|
|
771
|
+
}
|
|
630
772
|
}
|
|
631
773
|
}
|
|
632
774
|
}
|
|
633
775
|
/** One official registration owns both routes, preserving opaque replay ownership. */
|
|
634
776
|
export class RemoteAgentsAdapter extends LlmAdapter {
|
|
635
777
|
adapters = new Map();
|
|
636
|
-
constructor(config, makeRuntime, approve, nameFor, readImage, reportLoginFailure, directory, preflightDiagnostics, permissions, bridgeStopped) { super(); for (const agent of AGENTS)
|
|
637
|
-
this.adapters.set(agent.id, new CodexRemoteAdapter(config, makeRuntime(agent), approve, () => nameFor(agent), agent, readImage, reportLoginFailure, directory, preflightDiagnostics, permissions, bridgeStopped)); }
|
|
778
|
+
constructor(config, makeRuntime, approve, nameFor, readImage, reportLoginFailure, directory, preflightDiagnostics, permissions, bridgeStopped, steeringReceipts, coldRecovery) { super(); for (const agent of AGENTS)
|
|
779
|
+
this.adapters.set(agent.id, new CodexRemoteAdapter(config, makeRuntime(agent), approve, () => nameFor(agent), agent, readImage, reportLoginFailure, directory, preflightDiagnostics, permissions, bridgeStopped, steeringReceipts, coldRecovery)); }
|
|
638
780
|
adapter(provider) { const adapter = this.adapters.get(provider); if (!adapter)
|
|
639
781
|
throw new LlmError('远程模型未注册', 'PROVIDER_NOT_FOUND'); return adapter; }
|
|
640
782
|
providerInfo(provider) { return this.adapter(provider).providerInfo(provider); }
|
|
@@ -651,6 +793,8 @@ export class RemoteAgentsAdapter extends LlmAdapter {
|
|
|
651
793
|
}
|
|
652
794
|
return this.adapter(options.provider).stream(options);
|
|
653
795
|
}
|
|
796
|
+
canSteer(provider, sessionId) { return this.adapters.get(provider)?.canSteer(sessionId) ?? false; }
|
|
797
|
+
steer(provider, sessionId, message, isCurrent) { return this.adapter(provider).steer(sessionId, message, isCurrent); }
|
|
654
798
|
async completeDshTurn(sessionId, messages) { await Promise.all([...this.adapters.values()].map(adapter => adapter.completeDshTurn(sessionId, messages))); }
|
|
655
799
|
async disposeSession(sessionId) { await Promise.all([...this.adapters.values()].map(adapter => adapter.disposeSession(sessionId))); }
|
|
656
800
|
async detachSession(sessionId) { await Promise.all([...this.adapters.values()].map(adapter => adapter.detachSession(sessionId))); }
|
|
@@ -666,7 +810,9 @@ export function apply(ctx, live) {
|
|
|
666
810
|
throw new NeedError('ATTACHMENT_REQUIRED', '我需要官方附件组件读取这张图片', '官方attachments.readImage');
|
|
667
811
|
return attachments.readImage(ref, signal);
|
|
668
812
|
};
|
|
669
|
-
const
|
|
813
|
+
const sessionSources = createSessionSources(ctx, get);
|
|
814
|
+
const coldRecovery = new ColdRecovery(ctx, get, config, { readSource: sessionSources.read });
|
|
815
|
+
const openByAgent = new Map(AGENTS.map(agent => [agent.id, brokerFactory(get, undefined, config, { coldStore: coldRecovery.store })]));
|
|
670
816
|
const detailManagers = new Map();
|
|
671
817
|
const managerForProfile = () => {
|
|
672
818
|
const profile = ctx.get('profileContext');
|
|
@@ -679,7 +825,6 @@ export function apply(ctx, live) {
|
|
|
679
825
|
return manager;
|
|
680
826
|
};
|
|
681
827
|
ctx.provide('aiWorkbenchRemoteDiagnostics', { read: (query) => managerForProfile().read(query) });
|
|
682
|
-
const sessionSources = createSessionSources(ctx, get);
|
|
683
828
|
const preflightDiagnostics = createPreflightDiagnostics({ ctx, getApi: get, manager: managerForProfile });
|
|
684
829
|
const diagnostics = new Map();
|
|
685
830
|
const diagnostic = (scope, provider, message) => {
|
|
@@ -698,6 +843,7 @@ export function apply(ctx, live) {
|
|
|
698
843
|
// Public Loader Entry.options.id; optional when mounted without Loader.
|
|
699
844
|
const actualSettingsNamespace = ctx.fiber.entry?.options.id;
|
|
700
845
|
const modelDirectory = new ModelCatalog(get, () => config().acpMaxMessageBytes, undefined, (provider, error) => managerForProfile().recordCatalogFailure(provider, error));
|
|
846
|
+
const steeringReceipts = createSteeringReceipts(ctx);
|
|
701
847
|
const adapter = new RemoteAgentsAdapter(config, agent => {
|
|
702
848
|
const details = async (request, api, connection, target) => {
|
|
703
849
|
return managerForProfile().open({ sessionId: request.sessionId, provider: agent.loginProvider, identity: `${target.username}@${target.host}:${target.port}`, connection });
|
|
@@ -777,7 +923,9 @@ export function apply(ctx, live) {
|
|
|
777
923
|
if (turn !== null && step !== null)
|
|
778
924
|
agent.session.append('assistant/message', { turn, step, message: createAssistantMessage({ content: [{ type: 'text', text: notice }], source: { provider: 'ai-workbench-toolbridge', model: 'notice' } }), stream: [] }, { surfaceOp: 'append' });
|
|
779
925
|
agent.cancel({ kind: 'hook', reason: 'DSH_BRIDGE_CALL_ABANDONED_BY_HOST' }, { keepInbox: true });
|
|
780
|
-
});
|
|
926
|
+
}, steeringReceipts, coldRecovery);
|
|
927
|
+
coldRecovery.install();
|
|
928
|
+
installLiveSteering(ctx, adapter);
|
|
781
929
|
ctx.on('session/event', (session, event) => { if (event.type === 'turn/end') {
|
|
782
930
|
const operation = event.data.reason.kind === 'completed' ? adapter.completeDshTurn(session.id, session.deriveMessages()) : adapter.disposeSession(session.id);
|
|
783
931
|
void operation.catch(() => ctx.logger('remote-agent').warn('TOOLBRIDGE_RESULT_DELIVERY_UNCONFIRMED'));
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { Context } from '@deepseek-ai/cordis';
|
|
2
|
+
import type { UserMessage } from '@deepseek-ai/dsh-llm';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
declare const receiptSchema: z.ZodObject<{
|
|
5
|
+
sessionId: z.ZodString;
|
|
6
|
+
provider: z.ZodString;
|
|
7
|
+
messageId: z.ZodString;
|
|
8
|
+
nativeSessionId: z.ZodString;
|
|
9
|
+
turnId: z.ZodString;
|
|
10
|
+
messageSha256: z.ZodString;
|
|
11
|
+
outcome: z.ZodEnum<{
|
|
12
|
+
unknown: "unknown";
|
|
13
|
+
injected: "injected";
|
|
14
|
+
prepared: "prepared";
|
|
15
|
+
deferred: "deferred";
|
|
16
|
+
}>;
|
|
17
|
+
}, z.core.$strict>;
|
|
18
|
+
export type SteeringReceipt = z.infer<typeof receiptSchema>;
|
|
19
|
+
export declare const steeringMessageDigest: (message: UserMessage) => string;
|
|
20
|
+
export interface SteeringReceipts {
|
|
21
|
+
read(sessionId: string, provider: string, ids: readonly string[]): Promise<ReadonlyMap<string, SteeringReceipt>>;
|
|
22
|
+
put(receipt: SteeringReceipt): Promise<void>;
|
|
23
|
+
}
|
|
24
|
+
export declare const liveSteeringSpec: {
|
|
25
|
+
name: string;
|
|
26
|
+
version: number;
|
|
27
|
+
tables: {
|
|
28
|
+
receipts: import("@deepseek-ai/dsh-storage-domain").DomainTableSpec<string, {
|
|
29
|
+
sessionId: string;
|
|
30
|
+
provider: string;
|
|
31
|
+
messageId: string;
|
|
32
|
+
nativeSessionId: string;
|
|
33
|
+
turnId: string;
|
|
34
|
+
messageSha256: string;
|
|
35
|
+
outcome: "unknown" | "injected" | "prepared" | "deferred";
|
|
36
|
+
}>;
|
|
37
|
+
};
|
|
38
|
+
};
|
|
39
|
+
export declare function createSteeringReceipts(ctx: Context): SteeringReceipts;
|
|
40
|
+
export interface LiveSteeringTarget {
|
|
41
|
+
canSteer(provider: string, sessionId: string): boolean;
|
|
42
|
+
steer(provider: string, sessionId: string, message: UserMessage, isCurrent?: () => boolean): Promise<unknown>;
|
|
43
|
+
}
|
|
44
|
+
/** Observe the public inbox; the official driver still claims and records every input. */
|
|
45
|
+
export declare function installLiveSteering(ctx: Context, target: LiveSteeringTarget): void;
|
|
46
|
+
export {};
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { defineDomain, domainTable } from '@deepseek-ai/dsh-storage-domain';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { NeedError } from "./remote.js";
|
|
5
|
+
const receiptSchema = z.object({ sessionId: z.string().min(1), provider: z.string().min(1), messageId: z.string().min(1), nativeSessionId: z.string().min(1), turnId: z.string().min(1), messageSha256: z.string().regex(/^[a-f0-9]{64}$/), outcome: z.enum(['prepared', 'injected', 'deferred', 'unknown']) }).strict();
|
|
6
|
+
export const steeringMessageDigest = (message) => createHash('sha256').update(JSON.stringify({ source: message.source, content: message.content })).digest('hex');
|
|
7
|
+
export const liveSteeringSpec = defineDomain({ name: 'ai_workbench_live_steering', version: 1, tables: { receipts: domainTable(receiptSchema) } });
|
|
8
|
+
const key = (sessionId, provider, messageId) => JSON.stringify([sessionId, provider, messageId]);
|
|
9
|
+
const storageFailure = () => new NeedError('INPUT_DELIVERY_UNCONFIRMED', '中途消息的送达登记未能确认;没有自动重复发送,请核对原轮状态。', '官方storageDomain中途消息回执');
|
|
10
|
+
export function createSteeringReceipts(ctx) {
|
|
11
|
+
let domain;
|
|
12
|
+
const open = () => { if (!domain) {
|
|
13
|
+
const facility = ctx.get('storageDomain');
|
|
14
|
+
if (!facility)
|
|
15
|
+
throw storageFailure();
|
|
16
|
+
domain = facility.open(liveSteeringSpec).catch(error => { domain = undefined; throw error; });
|
|
17
|
+
} return domain; };
|
|
18
|
+
ctx.effect(() => async () => { if (domain)
|
|
19
|
+
await (await domain).close(); });
|
|
20
|
+
return {
|
|
21
|
+
async read(sessionId, provider, ids) { try {
|
|
22
|
+
const table = (await open()).table('receipts');
|
|
23
|
+
return new Map(ids.flatMap(id => { const row = table.get(key(sessionId, provider, id)); return row ? [[id, receiptSchema.parse(row)]] : []; }));
|
|
24
|
+
}
|
|
25
|
+
catch (error) {
|
|
26
|
+
throw Object.assign(storageFailure(), { cause: error });
|
|
27
|
+
} },
|
|
28
|
+
async put(receipt) { try {
|
|
29
|
+
await (await open()).table('receipts').put(key(receipt.sessionId, receipt.provider, receipt.messageId), receiptSchema.parse(receipt));
|
|
30
|
+
}
|
|
31
|
+
catch (error) {
|
|
32
|
+
throw Object.assign(storageFailure(), { cause: error });
|
|
33
|
+
} },
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
/** Observe the public inbox; the official driver still claims and records every input. */
|
|
37
|
+
export function installLiveSteering(ctx, target) {
|
|
38
|
+
ctx.on('agent/inbox/inserted', ({ agent, message }) => {
|
|
39
|
+
const provider = agent.options.provider, id = agent.session.id;
|
|
40
|
+
if (typeof provider !== 'string' || message.source.kind !== 'user' || !agent.inbox.nextStep.some(item => item.id === message.id) || !target.canSteer(provider, id))
|
|
41
|
+
return;
|
|
42
|
+
const digest = steeringMessageDigest(message);
|
|
43
|
+
void target.steer(provider, id, message, () => agent.options.provider === provider && agent.inbox.nextStep.some(item => item.id === message.id && steeringMessageDigest(item) === digest)).catch(() => ctx.logger('remote-agent').warn('INPUT_DELIVERY_UNCONFIRMED:中途消息回执未确认,没有自动重复发送'));
|
|
44
|
+
});
|
|
45
|
+
}
|
package/dist/provider.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { ColdRound, ColdStore } from './cold-store.ts';
|
|
1
2
|
import type { ToolBridge } from './toolbridge.ts';
|
|
2
3
|
import { type SessionSource } from './host-workspace.ts';
|
|
3
4
|
import type { CloseCause, CloseDiagnostics } from './close-diagnostics.ts';
|
|
@@ -27,6 +28,16 @@ export interface EmployeeExecution {
|
|
|
27
28
|
validate(signal?: AbortSignal): Promise<void>;
|
|
28
29
|
}
|
|
29
30
|
export interface Runtime {
|
|
31
|
+
localDirectory?: {
|
|
32
|
+
path: string;
|
|
33
|
+
device: number;
|
|
34
|
+
inode: number;
|
|
35
|
+
};
|
|
36
|
+
cold?: {
|
|
37
|
+
id: string;
|
|
38
|
+
store: ColdStore;
|
|
39
|
+
prepare: (nativeId: string, meta: NonNullable<ColdRound['meta']>) => Promise<void>;
|
|
40
|
+
};
|
|
30
41
|
identity: string;
|
|
31
42
|
cwd: string;
|
|
32
43
|
hostWorkspace?: Readonly<HostWorkspacePresentation>;
|