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

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/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { createSteeringReceipts, installLiveSteering, steeringMessageDigest } from "./live-steering.js";
1
2
  import { ToolBridgeLoop } from "./toolbridge-loop.js";
2
3
  import { openToolBridgeMcp, TOOLBRIDGE_NOTICE } from "./toolbridge.js";
3
4
  import { connectNeedMessage } from "./connect-need.js";
@@ -7,7 +8,7 @@ import { SessionId } from '@deepseek-ai/dsh-session';
7
8
  import { createAssistantMessage } from '@deepseek-ai/dsh-llm';
8
9
  import Schema from '@deepseek-ai/schemastery';
9
10
  import { LlmAdapter, LlmError } from '@deepseek-ai/dsh-llm';
10
- import { createHash } from 'node:crypto';
11
+ import { createHash, randomUUID } from 'node:crypto';
11
12
  import * as unstable from '@agentclientprotocol/sdk/unstable';
12
13
  import * as acp from '@agentclientprotocol/sdk';
13
14
  import { AcpSession } from "./acp.js";
@@ -94,9 +95,11 @@ export class CodexRemoteAdapter extends LlmAdapter {
94
95
  directory;
95
96
  preflightDiagnostics;
96
97
  permissions;
98
+ steeringReceipts;
97
99
  bridgeLoop;
98
100
  config;
99
101
  sessions = new Map();
102
+ injectedInputs = new Map();
100
103
  turns = new Map();
101
104
  lifetime = new AbortController();
102
105
  shuttingDown = false;
@@ -104,7 +107,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
104
107
  modelPresentation = new ModelPresentation();
105
108
  employeeNoticeSessions = new Set();
106
109
  pendingEmployeeNotices = new Set();
107
- constructor(config, resolveRuntime, approve, providerName = () => CODEX_AGENT.name.zh, agent = CODEX_AGENT, readImage, reportLoginFailure, directory, preflightDiagnostics, permissions, bridgeStopped) {
110
+ constructor(config, resolveRuntime, approve, providerName = () => CODEX_AGENT.name.zh, agent = CODEX_AGENT, readImage, reportLoginFailure, directory, preflightDiagnostics, permissions, bridgeStopped, steeringReceipts) {
108
111
  super();
109
112
  this.resolveRuntime = resolveRuntime;
110
113
  this.approve = approve;
@@ -115,10 +118,81 @@ export class CodexRemoteAdapter extends LlmAdapter {
115
118
  this.directory = directory;
116
119
  this.preflightDiagnostics = preflightDiagnostics;
117
120
  this.permissions = permissions;
118
- this.bridgeLoop = new ToolBridgeLoop(readImage, bridgeStopped);
121
+ this.steeringReceipts = steeringReceipts;
122
+ this.bridgeLoop = new ToolBridgeLoop(readImage, bridgeStopped, (id, message) => this.injectedInputs.get(id)?.get(message.id) === steeringMessageDigest(message));
119
123
  this.config = typeof config === 'function' ? config : () => config;
120
124
  }
121
125
  providerInfo(provider) { return { id: provider, name: this.providerName() }; }
126
+ canSteer(sessionId) { const live = this.sessions.get(sessionId); return !!this.steeringReceipts && !!live?.acceptingSteer && live.session.canSteer; }
127
+ steer(sessionId, message, isCurrent) {
128
+ const live = this.sessions.get(sessionId);
129
+ if (!live || !this.canSteer(sessionId))
130
+ return Promise.resolve();
131
+ const digest = steeringMessageDigest(message), valid = () => !isCurrent || isCurrent();
132
+ if (live.steerIds.get(message.id) === digest)
133
+ return live.steerTail;
134
+ live.steerIds.set(message.id, digest);
135
+ const work = live.steerTail.catch(() => { }).then(async () => {
136
+ if (!live.acceptingSteer || this.sessions.get(sessionId) !== live || !live.session.canSteer || !valid())
137
+ return;
138
+ const store = this.steeringReceipts, provider = live.options.provider, nativeSessionId = live.session.id;
139
+ const old = (await store.read(sessionId, provider, [message.id])).get(message.id);
140
+ if (!valid())
141
+ return;
142
+ if (old && old.messageSha256 !== digest && old.outcome !== 'deferred') {
143
+ live.notice?.('这条消息的旧版本已发送或送达未确认,不能撤回;编辑后的内容保留在队列,按下一步骤交付。');
144
+ return;
145
+ }
146
+ if (old && old.outcome !== 'deferred') {
147
+ if (old.outcome !== 'injected' || old.nativeSessionId !== nativeSessionId) {
148
+ const error = new NeedError('INPUT_DELIVERY_UNCONFIRMED', '这条中途消息已有未确认的送达记录,没有再次发送。', '原轮中途消息回执');
149
+ live.steerFailure ??= error;
150
+ throw error;
151
+ }
152
+ (this.injectedInputs.get(sessionId) ?? this.injectedInputs.set(sessionId, new Map()).get(sessionId)).set(message.id, digest);
153
+ return;
154
+ }
155
+ const prepared = await prepareInput({ ...live.options, messages: [message] }, this.readImage);
156
+ if (!valid())
157
+ return;
158
+ const params = { sessionId: nativeSessionId, prompt: prepared.prompt, _meta: { steering: { idleBehavior: 'promptRequired' } } };
159
+ if (Buffer.byteLength(JSON.stringify({ jsonrpc: '2.0', id: 'steering', method: '_session/steering', params })) + 1 > live.maxBytes)
160
+ throw new NeedError('ACP_MESSAGE_TOO_LARGE', '中途消息超过已设置的会话消息容量,仍在官方队列中,未发送。', '管理员调整acpMaxMessageBytes');
161
+ const receipt = { sessionId, provider, messageId: message.id, nativeSessionId, turnId: live.turnId, messageSha256: digest, outcome: 'prepared' };
162
+ await store.put(receipt);
163
+ const before = live.session.steerDispatchCount;
164
+ if (!valid()) {
165
+ await store.put({ ...receipt, outcome: 'deferred' });
166
+ return;
167
+ }
168
+ try {
169
+ const outcome = await live.session.steer(prepared.prompt, live.options.signal, valid, live.maxBytes);
170
+ await store.put({ ...receipt, outcome: outcome === 'injected' ? 'injected' : 'deferred' });
171
+ if (outcome === 'injected')
172
+ (this.injectedInputs.get(sessionId) ?? this.injectedInputs.set(sessionId, new Map()).get(sessionId)).set(message.id, digest);
173
+ }
174
+ catch (error) {
175
+ const dispatched = live.session.steerDispatchCount !== before;
176
+ await store.put({ ...receipt, outcome: dispatched ? 'unknown' : 'deferred' });
177
+ if (dispatched) {
178
+ const failure = new NeedError('INPUT_DELIVERY_UNCONFIRMED', '中途消息可能已交给原轮,送达结果未知,没有自动重复发送。', '原轮中途消息回执');
179
+ live.steerFailure ??= failure;
180
+ throw failure;
181
+ }
182
+ live.runtime.details?.record({ kind: 'need', severity: 'warning', code: error instanceof NeedError ? error.code : 'INPUT_DELIVERY_UNCONFIRMED', summary: '中途消息未发出,仍由官方队列后续处理。' });
183
+ }
184
+ });
185
+ const observed = work.catch(error => {
186
+ live.runtime.details?.record({ kind: 'need', severity: 'warning', code: error instanceof NeedError ? error.code : 'INPUT_DELIVERY_UNCONFIRMED', summary: '中途消息未确认,原消息没有丢弃或自动重发。' });
187
+ // Preserve uncertainty for this round, but known pre-dispatch failures do
188
+ // not poison later safe steering requests or unrelated future turns.
189
+ if (live.steerFailure === error)
190
+ throw error;
191
+ });
192
+ live.steerTail = observed;
193
+ void observed.catch(() => { });
194
+ return observed;
195
+ }
122
196
  catalog(signal) { if (!this.directory)
123
197
  throw new LlmError('无法获取模型列表:缺少可信主机目录能力', 'MODEL_CATALOG_UNAVAILABLE'); return this.directory.read(this.agent, signal); }
124
198
  async listModels(provider) { const catalog = await this.catalog(this.lifetime.signal); try {
@@ -175,10 +249,12 @@ export class CodexRemoteAdapter extends LlmAdapter {
175
249
  await this.cleanupRuntime(current.runtime);
176
250
  }
177
251
  async detachSession(sessionId) {
178
- await this.bridgeLoop.cancel(sessionId);
179
252
  const current = this.sessions.get(sessionId), turn = this.turns.get(sessionId);
180
253
  if (!current && !turn)
181
254
  return;
255
+ if (current?.runtime.broker?.supportsRecovery)
256
+ current.session.close({ layer: 'adapter', initiator: 'adapter.detach-sdk', reason: 'SESSION_DETACHED', action: 'detach' });
257
+ await this.bridgeLoop.cancel(sessionId);
182
258
  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
259
  this.detached.add(sessionId);
184
260
  if (current) {
@@ -198,11 +274,11 @@ export class CodexRemoteAdapter extends LlmAdapter {
198
274
  for (const live of this.sessions.values())
199
275
  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
276
  this.shuttingDown = true;
201
- await this.bridgeLoop.dispose();
202
277
  this.modelPresentation.clear();
203
278
  this.employeeNoticeSessions.clear();
204
279
  this.pendingEmployeeNotices.clear();
205
280
  const results = await Promise.allSettled([...new Set([...this.sessions.keys(), ...this.turns.keys()])].map(id => this.detachSession(id)));
281
+ await this.bridgeLoop.dispose();
206
282
  this.lifetime.abort();
207
283
  const failure = results.find(result => result.status === 'rejected');
208
284
  if (failure?.status === 'rejected')
@@ -320,8 +396,21 @@ export class CodexRemoteAdapter extends LlmAdapter {
320
396
  request.userMessageIds = request.userInputIds;
321
397
  earlyStage = 'source-context';
322
398
  await this.resolveRuntime.preflight?.(request);
399
+ const receipts = this.steeringReceipts && options.sessionId ? await this.steeringReceipts.read(options.sessionId, options.provider, humanIds) : new Map();
400
+ 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));
401
+ for (const receipt of matching)
402
+ if (receipt.outcome === 'prepared' || receipt.outcome === 'unknown')
403
+ throw new NeedError('INPUT_DELIVERY_UNCONFIRMED', '中途消息送达结果未知,没有在下一步骤重复提交;请核对原轮状态。', '原生注入回执');
404
+ const injected = new Set(matching.filter(r => r.outcome === 'injected').map(r => { if (!previous || r.nativeSessionId !== previous.sessionId)
405
+ throw new NeedError('SESSION_CONTEXT_MISMATCH', '中途消息属于另一原生轮,未重复提交。', '原会话的注入回执与检查点'); return r.messageId; }));
406
+ if (humanIds.length && humanIds.every(id => injected.has(id))) {
407
+ yield { type: 'finish', reason: { kind: 'stop' }, replayState: { response: previous } };
408
+ succeeded = true;
409
+ return;
410
+ }
411
+ const projected = { ...options, messages: options.messages.filter((m, index) => index <= (checkpoint?.index ?? -1) || !('id' in m) || typeof m.id !== 'string' || !injected.has(m.id)) };
323
412
  earlyStage = 'input-prepare';
324
- let input = await prepareInput(options, this.readImage);
413
+ let input = await prepareInput(projected, this.readImage);
325
414
  const contextSha256 = createHash('sha256').update(input.systemPrompt ?? '').digest('hex');
326
415
  request.contextSha256 = contextSha256;
327
416
  const codex = this.agent.loginProvider === 'codex';
@@ -349,7 +438,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
349
438
  }
350
439
  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
440
  throw new NeedError('SESSION_CONTEXT_MISMATCH', '原会话的员工主机或工作区已改变,请新建会话', '原会话的可信目标和工作区');
352
- input = await prepareContinuation({ ...options, messages: options.messages.slice((checkpoint?.index ?? -1) + 1) }, input, this.readImage, { maxBytes: config.acpMaxMessageBytes, host: runtime.hostWorkspace });
441
+ input = await prepareContinuation({ ...options, messages: projected.messages.slice((checkpoint?.index ?? -1) + 1) }, input, this.readImage, { maxBytes: config.acpMaxMessageBytes, host: runtime.hostWorkspace });
353
442
  if (runtime.hostWorkspace && mode === 'session' && Buffer.byteLength(JSON.stringify({ prompt: input.prompt, systemPrompt: input.systemPrompt }), 'utf8') > config.acpMaxMessageBytes)
354
443
  throw new NeedError('ACP_MESSAGE_TOO_LARGE', '本轮输入超过已设置的会话消息容量,未截断或发送', '管理员调整acpMaxMessageBytes');
355
444
  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 });
@@ -438,7 +527,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
438
527
  } }, onResponse: response => push(mapper.acpResponse(response)), onDetail: detail => details.record(detail) };
439
528
  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
529
  session = new AcpSession(transport, hooks);
441
- live = { session, runtime, configuration, contextSha256, usageSnapshot: mapper.usageSnapshot };
530
+ live = { session, runtime, configuration, contextSha256, usageSnapshot: mapper.usageSnapshot, options, acceptingSteer: true, turnId: randomUUID(), steerIds: new Map(), steerTail: Promise.resolve(), maxBytes: config.acpMaxMessageBytes, notice: text => push(mapper.text(text)) };
442
531
  if (key)
443
532
  this.sessions.set(key, live);
444
533
  promptBaseline = session.promptDispatchCount;
@@ -540,8 +629,13 @@ export class CodexRemoteAdapter extends LlmAdapter {
540
629
  bridge.replayState = { response: makePointer(session.id) };
541
630
  bridge?.begin(modelSignal);
542
631
  id = session.id;
632
+ let promptFailed = false;
543
633
  try {
544
634
  const result = await dispatchPrompt();
635
+ live.acceptingSteer = false;
636
+ await live.steerTail;
637
+ if (live.steerFailure)
638
+ throw live.steerFailure;
545
639
  if (bridge?.unsettled)
546
640
  bridge.abandon('HOST_PROMPT_ENDED_WITH_PENDING_CALL');
547
641
  permissionOff?.();
@@ -549,7 +643,22 @@ export class CodexRemoteAdapter extends LlmAdapter {
549
643
  await permissionTail;
550
644
  return result;
551
645
  }
646
+ catch (error) {
647
+ promptFailed = true;
648
+ throw error;
649
+ }
552
650
  finally {
651
+ live.acceptingSteer = false;
652
+ try {
653
+ await live.steerTail;
654
+ if (live.steerFailure)
655
+ throw live.steerFailure;
656
+ }
657
+ catch (error) {
658
+ if (!promptFailed)
659
+ throw error;
660
+ details.record({ kind: 'need', severity: 'warning', code: 'INPUT_DELIVERY_UNCONFIRMED', summary: '原轮失败且有中途消息未获送达确认,没有重发。' });
661
+ }
553
662
  permissionOff?.();
554
663
  permissionOff = undefined;
555
664
  bridge?.end();
@@ -625,16 +734,17 @@ export class CodexRemoteAdapter extends LlmAdapter {
625
734
  }
626
735
  if (key && this.turns.get(key) === turn)
627
736
  this.turns.delete(key);
628
- if (key)
737
+ if (key) {
629
738
  this.detached.delete(key);
739
+ }
630
740
  }
631
741
  }
632
742
  }
633
743
  /** One official registration owns both routes, preserving opaque replay ownership. */
634
744
  export class RemoteAgentsAdapter extends LlmAdapter {
635
745
  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)); }
746
+ constructor(config, makeRuntime, approve, nameFor, readImage, reportLoginFailure, directory, preflightDiagnostics, permissions, bridgeStopped, steeringReceipts) { super(); for (const agent of AGENTS)
747
+ this.adapters.set(agent.id, new CodexRemoteAdapter(config, makeRuntime(agent), approve, () => nameFor(agent), agent, readImage, reportLoginFailure, directory, preflightDiagnostics, permissions, bridgeStopped, steeringReceipts)); }
638
748
  adapter(provider) { const adapter = this.adapters.get(provider); if (!adapter)
639
749
  throw new LlmError('远程模型未注册', 'PROVIDER_NOT_FOUND'); return adapter; }
640
750
  providerInfo(provider) { return this.adapter(provider).providerInfo(provider); }
@@ -651,6 +761,8 @@ export class RemoteAgentsAdapter extends LlmAdapter {
651
761
  }
652
762
  return this.adapter(options.provider).stream(options);
653
763
  }
764
+ canSteer(provider, sessionId) { return this.adapters.get(provider)?.canSteer(sessionId) ?? false; }
765
+ steer(provider, sessionId, message, isCurrent) { return this.adapter(provider).steer(sessionId, message, isCurrent); }
654
766
  async completeDshTurn(sessionId, messages) { await Promise.all([...this.adapters.values()].map(adapter => adapter.completeDshTurn(sessionId, messages))); }
655
767
  async disposeSession(sessionId) { await Promise.all([...this.adapters.values()].map(adapter => adapter.disposeSession(sessionId))); }
656
768
  async detachSession(sessionId) { await Promise.all([...this.adapters.values()].map(adapter => adapter.detachSession(sessionId))); }
@@ -698,6 +810,7 @@ export function apply(ctx, live) {
698
810
  // Public Loader Entry.options.id; optional when mounted without Loader.
699
811
  const actualSettingsNamespace = ctx.fiber.entry?.options.id;
700
812
  const modelDirectory = new ModelCatalog(get, () => config().acpMaxMessageBytes, undefined, (provider, error) => managerForProfile().recordCatalogFailure(provider, error));
813
+ const steeringReceipts = createSteeringReceipts(ctx);
701
814
  const adapter = new RemoteAgentsAdapter(config, agent => {
702
815
  const details = async (request, api, connection, target) => {
703
816
  return managerForProfile().open({ sessionId: request.sessionId, provider: agent.loginProvider, identity: `${target.username}@${target.host}:${target.port}`, connection });
@@ -777,7 +890,8 @@ export function apply(ctx, live) {
777
890
  if (turn !== null && step !== null)
778
891
  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
892
  agent.cancel({ kind: 'hook', reason: 'DSH_BRIDGE_CALL_ABANDONED_BY_HOST' }, { keepInbox: true });
780
- });
893
+ }, steeringReceipts);
894
+ installLiveSteering(ctx, adapter);
781
895
  ctx.on('session/event', (session, event) => { if (event.type === 'turn/end') {
782
896
  const operation = event.data.reason.kind === 'completed' ? adapter.completeDshTurn(session.id, session.deriveMessages()) : adapter.disposeSession(session.id);
783
897
  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
- const prepared = await publicBlock(block, options, readImage);
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);
@@ -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
+ }
@@ -4,7 +4,8 @@ import { NeedError } from "./remote.js";
4
4
  export function isolateRpcIds(stream, onWrite) {
5
5
  const prefix = randomUUID() + '/';
6
6
  const pending = new Map();
7
- const readable = stream.readable.pipeThrough(new TransformStream({ transform(message, controller) {
7
+ let incoming;
8
+ const readable = stream.readable.pipeThrough(new TransformStream({ start(controller) { incoming = controller; }, transform(message, controller) {
8
9
  const raw = message;
9
10
  if (!raw.method && Object.hasOwn(raw, 'id')) {
10
11
  if (typeof raw.id !== 'string' || !pending.has(raw.id))
@@ -28,9 +29,22 @@ export function isolateRpcIds(stream, onWrite) {
28
29
  const params = raw.params;
29
30
  outgoing = { ...raw, params: { ...params, requestId: prefix + JSON.stringify(params.requestId) } };
30
31
  }
31
- const writer = stream.writable.getWriter();
32
+ // A known pre-dispatch steering rejection belongs to one request. Throwing
33
+ // from WritableStream.write would permanently poison the shared SDK channel.
34
+ // Deliver an explicit local RPC error on the public Stream instead. No native
35
+ // write or dispatch count occurs, and the namespaced pending entry is removed.
32
36
  try {
33
37
  onWrite?.(outgoing);
38
+ }
39
+ catch (error) {
40
+ if (raw.method !== '_session/steering' || !Object.hasOwn(raw, 'id') || !(error instanceof NeedError) || !['ACP_MESSAGE_TOO_LARGE', 'PERMISSION_POLICY_CHANGED'].includes(error.code))
41
+ throw error;
42
+ pending.delete(String(outgoing.id));
43
+ incoming.enqueue({ jsonrpc: '2.0', id: raw.id, error: { code: -32603, message: 'ACP_LOCAL_REQUEST_REJECTED', data: { localDispatchCode: error.code } } });
44
+ return;
45
+ }
46
+ const writer = stream.writable.getWriter();
47
+ try {
34
48
  await writer.write(outgoing);
35
49
  }
36
50
  finally {
@@ -1,4 +1,4 @@
1
- import { type GenerateOptions, type StreamChunk } from '@deepseek-ai/dsh-llm';
1
+ import { type GenerateOptions, type StreamChunk, type UserMessage } from '@deepseek-ai/dsh-llm';
2
2
  import { ToolBridge } from './toolbridge.ts';
3
3
  import type { ImageReader } from './input.ts';
4
4
  type Producer = (options: GenerateOptions, bridge: ToolBridge) => AsyncGenerator<StreamChunk>;
@@ -6,9 +6,10 @@ type Producer = (options: GenerateOptions, bridge: ToolBridge) => AsyncGenerator
6
6
  export declare class ToolBridgeLoop {
7
7
  private readImage?;
8
8
  private stopped?;
9
+ private isInjected?;
9
10
  private runs;
10
11
  private concluding;
11
- constructor(readImage?: ImageReader | undefined, stopped?: ((sessionId: string, notice: string) => void) | undefined);
12
+ constructor(readImage?: ImageReader | undefined, stopped?: ((sessionId: string, notice: string) => void) | undefined, isInjected?: ((sessionId: string, message: UserMessage) => boolean) | undefined);
12
13
  private launch;
13
14
  conclude(id: string, messages: GenerateOptions['messages']): Promise<void>;
14
15
  active(id: string): boolean;
@@ -44,11 +44,13 @@ class Projection {
44
44
  export class ToolBridgeLoop {
45
45
  readImage;
46
46
  stopped;
47
+ isInjected;
47
48
  runs = new Map();
48
49
  concluding = new Map();
49
- constructor(readImage, stopped) {
50
+ constructor(readImage, stopped, isInjected) {
50
51
  this.readImage = readImage;
51
52
  this.stopped = stopped;
53
+ this.isInjected = isInjected;
52
54
  }
53
55
  launch(options, producer) {
54
56
  const controller = new AbortController(), bridge = new ToolBridge(options, this.readImage);
@@ -181,7 +183,7 @@ export class ToolBridgeLoop {
181
183
  throw new NeedError('ABORTED', '本轮已取消,工具结果没有重放。', '确认主机取消状态');
182
184
  if (run.latest !== options) {
183
185
  for (const m of options.messages)
184
- if (m.role === 'user' && 'source' in m && m.source?.kind === 'user' && 'id' in m && typeof m.id === 'string' && !run.seen.has(m.id)) {
186
+ if (m.role === 'user' && 'source' in m && m.source?.kind === 'user' && 'id' in m && typeof m.id === 'string' && !run.seen.has(m.id) && !this.isInjected?.(key, m)) {
185
187
  run.seen.add(m.id);
186
188
  run.deferred.push(m);
187
189
  }
@@ -1,4 +1,4 @@
1
- import type { ToolSchema } from '@deepseek-ai/dsh-llm';
1
+ import type { ToolSchema, GenerateOptions } from '@deepseek-ai/dsh-llm';
2
2
  import type { Tool } from '@modelcontextprotocol/sdk/types.js';
3
3
  /** Fixed official tool names; no description heuristics or plugin-name branches. */
4
4
  export declare const TOOLBRIDGE_EXCLUDED: readonly ["read", "write", "edit", "read_image", "glob", "grep", "bash", "pwsh", "str_replace_editor", "job_output", "job_list", "job_kill", "load_workspace_dependencies", "terminal_open", "terminal_send", "terminal_read", "terminal_signal", "terminal_close", "terminal_list", "subagent", "list_subagent_models", "send_message", "interrupt_agent", "spawn_teammate", "list_agents", "wait_agent", "team_task_create", "team_task_list", "team_task_get", "team_task_update", "run_code"];
@@ -7,4 +7,5 @@ export interface BridgeTool {
7
7
  schema: ToolSchema;
8
8
  wire: Tool;
9
9
  }
10
- export declare function bridgeTable(tools?: readonly ToolSchema[]): ReadonlyMap<string, BridgeTool>;
10
+ export declare function dshSkillCatalog(messages?: GenerateOptions['messages']): readonly string[] | undefined;
11
+ export declare function bridgeTable(tools?: readonly ToolSchema[], catalog?: readonly string[]): ReadonlyMap<string, BridgeTool>;
@@ -9,7 +9,17 @@ export const TOOLBRIDGE_EXCLUDED = Object.freeze([
9
9
  'team_task_create', 'team_task_list', 'team_task_get', 'team_task_update', 'run_code',
10
10
  ]);
11
11
  const excluded = new Set(TOOLBRIDGE_EXCLUDED);
12
- export function bridgeTable(tools = []) {
12
+ export function dshSkillCatalog(messages = []) {
13
+ for (const message of messages.toReversed()) {
14
+ const source = message.source;
15
+ if (message.role !== 'user' || source?.kind !== 'skill-catalog' || source.form !== 'catalog' || !Array.isArray(source.entries))
16
+ continue;
17
+ if (!source.entries.every(entry => entry && typeof entry.name === 'string' && typeof entry.description === 'string'))
18
+ continue;
19
+ return source.entries.map(entry => entry.name);
20
+ }
21
+ }
22
+ export function bridgeTable(tools = [], catalog) {
13
23
  const table = new Map(), names = new Set();
14
24
  for (const tool of tools) {
15
25
  if (excluded.has(tool.name))
@@ -21,7 +31,8 @@ export function bridgeTable(tools = []) {
21
31
  if (table.has(alias))
22
32
  throw new NeedError('TOOLBRIDGE_NAME_COLLISION', '工具桥名称冲突,未执行。', '唯一工具桥名称');
23
33
  const schema = structuredClone(tool);
24
- table.set(alias, { alias, schema, wire: { name: alias, description: 'DSH工具 ' + schema.name + ':' + schema.description, inputSchema: structuredClone(schema.parameters) } });
34
+ const skill = schema.name === 'skill' ? ' 这是DSH技能加载器,名字取自DSH的<available_skills>目录;主机Claude/Codex的原生技能按各自原生技能指令加载。' + (catalog === undefined ? '请以当前DSH技能目录为准。' : '本次DSH公布的目录快照:' + JSON.stringify(catalog) + ';实际可用性由DSH调用时确认。') + '技能资源按返回的<skill_resources>基址读取。' : '';
35
+ table.set(alias, { alias, schema, wire: { name: alias, description: 'DSH工具 ' + schema.name + ':' + schema.description + skill, inputSchema: structuredClone(schema.parameters) } });
25
36
  }
26
37
  return table;
27
38
  }
@@ -4,7 +4,7 @@ import { mkdtemp, lstat, rm } from 'node:fs/promises';
4
4
  import { Server } from '@modelcontextprotocol/sdk/server/index.js';
5
5
  import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
6
6
  import { EmployeeSocketTransport } from "./employee-mcp.js";
7
- import { bridgeTable } from "./toolbridge-table.js";
7
+ import { bridgeTable, dshSkillCatalog } from "./toolbridge-table.js";
8
8
  import { NeedError } from "./remote.js";
9
9
  export const TOOLBRIDGE_TIMEOUT_SECONDS = 1800;
10
10
  export const TOOLBRIDGE_NOTICE = '含工具桥:本机文件夹的扩展工具由DSH执行并按当前权限审批;文件和命令保持原执行方式。工具表在新一轮主机连接时更新。';
@@ -16,7 +16,7 @@ export class ToolBridge {
16
16
  readImage;
17
17
  controller = new AbortController();
18
18
  snapshot;
19
- get table() { return this.snapshot ??= bridgeTable(this.options.tools); }
19
+ get table() { return this.snapshot ??= bridgeTable(this.options.tools, dshSkillCatalog(this.options.messages)); }
20
20
  calls = new Map();
21
21
  enabled = false;
22
22
  ended = false;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-workbench/remote-agent",
3
- "version": "0.9.0-toolbridge.12",
3
+ "version": "0.9.0-toolbridge.14",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -112,7 +112,7 @@
112
112
  "publishConfig": {
113
113
  "access": "public",
114
114
  "registry": "https://registry.npmjs.org/",
115
- "tag": "toolbridge"
115
+ "tag": "host-toolbridge"
116
116
  },
117
117
  "keywords": [
118
118
  "dsh",