@ai-workbench/remote-agent 0.9.0-toolbridge.27 → 0.9.0-toolbridge.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # AI Workbench 远程助手 · @ai-workbench/remote-agent@0.9.0-toolbridge.27 · 插件 → 添加插件
1
+ # AI Workbench 远程助手 · @ai-workbench/remote-agent@0.9.0-toolbridge.29 · 插件 → 添加插件
2
2
 
3
3
  ## 办公依赖与开工计时(O1,2026-11-15)
4
4
 
@@ -87,4 +87,6 @@ Codex 员工端只使用随包提供的原生组件,通道等待本次组件
87
87
 
88
88
  模型目录在官方启动读取时获取,并在连接变为 connected 时经官方注册刷新;官方菜单打开或重试读取缓存是 DSH 官方限制,本插件不改官方菜单或核心。真正不支持的推理档位由 DSH 预检,其英文提示保留为观察项。
89
89
 
90
- I3(0.9.0-toolbridge.27):同一 DSH 对话的系统规则更新后,续接原 Codex native 线程并在实际模型请求应用新版规则;需要主机含桥 Codex ACP aw.15。规则未变不重复追加历史;每次恢复仍带当前配置以支持压缩重建。同 native ID 的可信累计用量基线持续保留,输入、缓存、输出仅结算增量。Claude 的规则传递及累计差额路径保持。无新增设置、限制或错误码。
90
+ I3(0.9.0-toolbridge.27):同一 DSH 对话的系统规则更新后,续接原 Codex native 线程并在实际模型请求应用新版规则;需要主机含桥 Codex ACP aw.15。规则未变不重复追加历史;每次恢复仍带当前配置以支持压缩重建。用量说明已由 U1(0.9.0-toolbridge.28)更正:Codex aw.15 和 Claude 0.94.0 的 ACP 回执均按本次 prompt 统计,逐轮全额结算一次,不减历史基线;旧累计快照不再参与计算。冷接回只减同一 prompt 已在 DSH 落盘的部分,可靠终态先持久化,原 broker 回收后仍可补记其未落盘用量。订阅额度卡仍读取官方额度窗口,不能由 token 数推算百分比。Claude 的规则传递保持。无新增设置、限制或错误码。
91
+
92
+ T3(0.9.0-toolbridge.29):在已连接、当前员工目录已接纳的 Codex 路径,同轮登录核验与端点准备重叠;两项均成功并再次核对目标、连接代次与物理目录后才开工,每轮核验与正常完成后结束 broker 的做法保留。当前输入已完整列出同一技能目录时,skill 工具省去重复名字数组;目录不完整或只有历史目录时保留原快照。未改变首轮工具可见性,没有新增设置、限制或错误码。本机受控时延与工具字节测量不代表远机实测速率或实际 API token 节省;DSH 原生本轮因缺独立登录未测。
@@ -6,6 +6,19 @@ import { coldNeed } from "./cold-store.js";
6
6
  import { StreamMapper } from "./mapping.js";
7
7
  import { LlmError } from '@deepseek-ai/dsh-llm';
8
8
  import { NeedError } from "./remote.js";
9
+ /** 同一个 prompt 的可靠回执减去已写入 DSH 的部分;不是跨 prompt 的累计减法。 */
10
+ function remainingUsage(current, previous) {
11
+ const usage = { ...current };
12
+ for (const key of Object.keys(usage)) {
13
+ const actual = usage[key], paid = previous?.[key];
14
+ if (typeof actual === 'number' && typeof paid === 'number') {
15
+ if (actual < paid)
16
+ throw coldNeed('USAGE_BASELINE_INVALID');
17
+ usage[key] = actual - paid;
18
+ }
19
+ }
20
+ return Object.values(usage).some(x => typeof x === 'number' && x !== 0) ? [{ type: 'usage', usage }] : [];
21
+ }
9
22
  /** Read-only reconstruction, with block kinds and exact content checked against the durable transcript. */
10
23
  class Prefix {
11
24
  index = 0;
@@ -48,9 +61,9 @@ class Prefix {
48
61
  const HOST_ROUND_ENDED = '上一轮的主机会话已结束,那一轮的结果无法接回;没有重新发送那一轮的任务,可以在本会话继续。\n\n';
49
62
  const LOGIN_ENDED = '\n上一轮因主机会话的登录已失效没有完成,已结束那一轮的主机会话;没有重新发送那一轮的任务,接下来用当前登录在本会话继续。\n\n';
50
63
  /** The checkpoint that commits the original round and lets the next round resume its native thread. */
51
- function coldPointer(record, usageSnapshot, outputAfter) {
64
+ function coldPointer(record, outputAfter) {
52
65
  const snapshot = record.meta;
53
- return { ...(snapshot.hostSource ? { hostSource: snapshot.hostSource } : {}), ...(snapshot.modelConfiguration ? { modelConfiguration: snapshot.modelConfiguration } : {}), version: 2, agent: record.provider, contextSha256: snapshot.contextSha256, usageSnapshot, dshSessionId: record.sessionId, identity: snapshot.identity, cwd: snapshot.cwd, sessionId: record.nativeId, ...(snapshot.binding ? { bindingId: snapshot.binding.bindingId, workspaceId: snapshot.binding.workspaceId } : {}), coldRoundId: record.id, coldPromptId: record.promptId, coldRoundTerminal: true, coldOutputAfter: outputAfter };
66
+ return { ...(snapshot.hostSource ? { hostSource: snapshot.hostSource } : {}), ...(snapshot.modelConfiguration ? { modelConfiguration: snapshot.modelConfiguration } : {}), version: 2, agent: record.provider, contextSha256: snapshot.contextSha256, dshSessionId: record.sessionId, identity: snapshot.identity, cwd: snapshot.cwd, sessionId: record.nativeId, ...(snapshot.binding ? { bindingId: snapshot.binding.bindingId, workspaceId: snapshot.binding.workspaceId } : {}), coldRoundId: record.id, coldPromptId: record.promptId, coldRoundTerminal: true, coldOutputAfter: outputAfter };
54
67
  }
55
68
  export async function* recoverColdProtocol(record, store, prefix, options) {
56
69
  options.signal?.throwIfAborted();
@@ -69,14 +82,18 @@ export async function* recoverColdProtocol(record, store, prefix, options) {
69
82
  if (options.cancelOnly)
70
83
  return; // Nothing is left to cancel; the next human input settles the round.
71
84
  // Settle the round once without resending it; the next round resumes the original native session.
72
- const baseline = record.meta.baseline, usage = baseline?.kind === 'cumulative' ? { ...baseline, gap: true } : null;
73
85
  record = await store.update(record.sessionId, record.provider, record.id, row => { if (!row.terminal) {
74
86
  row.terminal = { kind: 'error', value: { code: error.code } };
75
- row.finalUsage = usage;
76
87
  row.terminalAfter = row.outputStart ?? row.outputAfter;
77
88
  } row.phase = 'terminal'; delete row.pending; }); // A terminal already recorded keeps its real result and usage.
78
- yield* new StreamMapper().text(HOST_ROUND_ENDED);
79
- yield { type: 'finish', reason: { kind: 'stop' }, replayState: { response: coldPointer(record, record.finalUsage ?? null, record.terminalAfter ?? record.outputStart ?? record.outputAfter) } };
89
+ const ended = new StreamMapper();
90
+ if (record.terminal?.kind === 'result')
91
+ for (const chunk of ended.acpResponse(record.terminal.value))
92
+ if (chunk.type === 'usage')
93
+ yield* remainingUsage(chunk.usage, prefix.usage);
94
+ yield* ended.text(HOST_ROUND_ENDED);
95
+ yield* ended.flush();
96
+ yield { type: 'finish', reason: { kind: 'stop' }, replayState: { response: coldPointer(record, record.terminalAfter ?? record.outputStart ?? record.outputAfter) } };
80
97
  return;
81
98
  }
82
99
  if (!Number.isSafeInteger(bound.round?.outputStartSequence))
@@ -97,7 +114,7 @@ export async function* recoverColdProtocol(record, store, prefix, options) {
97
114
  promptConfirmed = true; broker.completeRestoredInput(); };
98
115
  broker = new BrokerTransport({ maxFrameBytes: options.maxFrameBytes, controlMaxBytes: record.controlMaxBytes, leased: true, inputProtocolVersion: 2, messageInput: true, recoverDisconnect: true, instanceId: record.instanceId, initialSequence: record.outputStart, restoreInput: { sequence: record.inputSequence, pending: record.pending }, beforeMessage, afterMessage, attach: (after = 0) => options.io.attach(command(['attach', record.brokerId, '--after', String(after), '--framed', '--leased', '--input-protocol', '2', '--message-input', '--if-instance', record.instanceId, '--cold-round', record.id, '--prompt-id', record.promptId, ...owner])) });
99
116
  const raw = acp.ndJsonStream(broker.writable, broker.readable, { maxMessageBytes: options.maxMessageBytes }), reader = raw.readable.getReader(), writer = raw.writable.getWriter();
100
- const mapper = new StreamMapper(record.meta.baseline), output = new StreamMapper(), trim = new Prefix(prefix);
117
+ const mapper = new StreamMapper(), output = new StreamMapper(), trim = new Prefix(prefix);
101
118
  let terminal = false, replayed = false, delivered = false;
102
119
  const pendingRequests = new Map();
103
120
  let outboundTail = Promise.resolve();
@@ -116,17 +133,7 @@ export async function* recoverColdProtocol(record, store, prefix, options) {
116
133
  yield* output.text(trim.take(type, chunk.text), type === 'reasoning');
117
134
  }
118
135
  else if (chunk.type === 'usage') {
119
- const usage = { ...chunk.usage };
120
- for (const key of Object.keys(usage)) {
121
- const actual = usage[key], previous = prefix.usage?.[key];
122
- if (typeof actual === 'number' && typeof previous === 'number') {
123
- if (actual < previous)
124
- throw coldNeed('USAGE_BASELINE_INVALID');
125
- usage[key] = actual - previous;
126
- }
127
- }
128
- if (Object.values(usage).some(x => typeof x === 'number' && x !== 0))
129
- yield { type: 'usage', usage };
136
+ yield* remainingUsage(chunk.usage, prefix.usage);
130
137
  }
131
138
  } };
132
139
  let activePump, releasePump, terminalWaiting = false;
@@ -178,7 +185,7 @@ export async function* recoverColdProtocol(record, store, prefix, options) {
178
185
  receipt = await broker.discardMessage(saved.id);
179
186
  else if (receipt.committedSequence !== saved.baseSequence || receipt.pendingSequence !== null || receipt.stagedMessageId)
180
187
  throw coldNeed();
181
- record = await store.update(record.sessionId, record.provider, record.id, row => { row.inputSequence = receipt.committedSequence; delete row.pending; row.cancelCheckpoint = { inputNotDelivered: true, receipt }; row.terminal = { kind: 'local-cancel', value: { inputNotDelivered: true } }; row.phase = 'terminal'; row.finalUsage = row.meta.baseline; });
188
+ record = await store.update(record.sessionId, record.provider, record.id, row => { row.inputSequence = receipt.committedSequence; delete row.pending; row.cancelCheckpoint = { inputNotDelivered: true, receipt }; row.terminal = { kind: 'local-cancel', value: { inputNotDelivered: true } }; row.phase = 'terminal'; });
182
189
  broker.completeRestoredInput();
183
190
  localCancellation = true;
184
191
  cancellationWake();
@@ -326,7 +333,6 @@ export async function* recoverColdProtocol(record, store, prefix, options) {
326
333
  await store.update(record.sessionId, record.provider, record.id, row => { row.terminal = { kind: m.error ? 'error' : 'result', value: m.error ?? m.result }; row.phase = 'terminal'; row.terminalAfter = broker.lastSequence; });
327
334
  if (m.error) {
328
335
  trim.finish();
329
- record = await store.update(record.sessionId, record.provider, record.id, row => { row.finalUsage = mapper.usageSnapshot?.kind === 'cumulative' ? { ...mapper.usageSnapshot, gap: true } : null; });
330
336
  // The original agent failed authentication (same judgment as a live round): its login is no longer valid. End it first, so the next round
331
337
  // resumes the original native session with the current login (Codex holds one writer per thread); then settle without resending the task.
332
338
  if (options.markerId && acpNeed(new acp.RequestError(m.error.code, m.error.message, m.error.data)).code === 'LOGIN_REQUIRED') {
@@ -334,7 +340,7 @@ export async function* recoverColdProtocol(record, store, prefix, options) {
334
340
  yield* output.flush();
335
341
  yield* output.text(LOGIN_ENDED);
336
342
  yield* output.flush();
337
- yield { type: 'finish', reason: { kind: 'stop' }, replayState: { response: coldPointer(record, record.finalUsage ?? null, broker.lastSequence) } };
343
+ yield { type: 'finish', reason: { kind: 'stop' }, replayState: { response: coldPointer(record, broker.lastSequence) } };
338
344
  return;
339
345
  }
340
346
  if (!options.markerId)
@@ -346,7 +352,6 @@ export async function* recoverColdProtocol(record, store, prefix, options) {
346
352
  if (!m.result || typeof m.result.stopReason !== 'string')
347
353
  throw coldNeed();
348
354
  yield* projection(mapper.acpResponse(m.result));
349
- await store.update(record.sessionId, record.provider, record.id, row => { row.finalUsage = mapper.usageSnapshot; });
350
355
  if (m.result.stopReason === 'cancelled') {
351
356
  trim.finish();
352
357
  if (!options.markerId)
@@ -360,7 +365,7 @@ export async function* recoverColdProtocol(record, store, prefix, options) {
360
365
  trim.finish();
361
366
  yield* output.flush();
362
367
  delivered = true;
363
- yield { type: 'finish', reason: { kind: ['max_tokens', 'max_turn_requests'].includes(m.result.stopReason) ? 'max-tokens' : 'stop' }, replayState: { response: coldPointer(record, mapper.usageSnapshot, broker.lastSequence) } };
368
+ yield { type: 'finish', reason: { kind: ['max_tokens', 'max_turn_requests'].includes(m.result.stopReason) ? 'max-tokens' : 'stop' }, replayState: { response: coldPointer(record, broker.lastSequence) } };
364
369
  return;
365
370
  }
366
371
  }
@@ -389,6 +394,6 @@ export async function* recoverLocalCancellation(record, store, markerId) {
389
394
  if (!record.cancelIntent || !record.cancelCheckpoint?.inputNotDelivered || record.terminal?.kind !== 'local-cancel')
390
395
  throw coldNeed();
391
396
  const token = randomUUID(), message = '原轮已在送达前取消,没有执行或重新发送原任务;恢复回执 ' + token;
392
- await store.update(record.sessionId, record.provider, record.id, row => { row.finalUsage = row.meta?.baseline ?? null; row.errorDelivery = { markerId, promptId: record.promptId, code: 'ABORTED', token, message }; });
397
+ await store.update(record.sessionId, record.provider, record.id, row => { row.errorDelivery = { markerId, promptId: record.promptId, code: 'ABORTED', token, message }; });
393
398
  throw new LlmError(message, 'ABORTED');
394
399
  }
@@ -130,7 +130,6 @@ export class ColdRecovery {
130
130
  await this.store.update(options.sessionId, options.provider, runtime.cold.id, row => { row.cancelIntent ??= { source: 'user-signal' }; if (!row.promptId) {
131
131
  row.cancelCheckpoint = { inputNotDelivered: true, receipt: { kind: 'no-prompt-wire' } };
132
132
  row.terminal = { kind: 'local-cancel', value: { inputNotDelivered: true } };
133
- row.finalUsage = row.meta.baseline;
134
133
  row.phase = 'terminal';
135
134
  } });
136
135
  }
@@ -148,7 +147,6 @@ export class ColdRecovery {
148
147
  return this.store.update(row.sessionId, row.provider, row.id, r => { r.cancelIntent = { source: 'official-user' }; if (!r.promptId) {
149
148
  r.cancelCheckpoint = { inputNotDelivered: true, receipt: { kind: 'no-prompt-wire' } };
150
149
  r.terminal = { kind: 'local-cancel', value: { inputNotDelivered: true } };
151
- r.finalUsage = r.meta.baseline;
152
150
  r.phase = 'terminal';
153
151
  } });
154
152
  }
@@ -352,10 +350,10 @@ export class ColdRecovery {
352
350
  if (index < 0)
353
351
  return;
354
352
  await this.events(row.sessionId, row.meta.header);
355
- const m = row.meta, usage = row.finalUsage ?? null;
353
+ const m = row.meta;
356
354
  if (!row.nativeId)
357
355
  return { index, pointer: undefined };
358
- return { index, pointer: { version: 2, agent: row.provider, dshSessionId: row.sessionId, identity: m.identity, cwd: m.cwd, sessionId: row.nativeId, contextSha256: m.contextSha256, usageSnapshot: usage, ...(m.binding ? { bindingId: m.binding.bindingId, workspaceId: m.binding.workspaceId } : {}), ...(m.hostSource ? { hostSource: m.hostSource } : {}), ...(m.modelConfiguration ? { modelConfiguration: m.modelConfiguration } : {}) } };
356
+ return { index, pointer: { version: 2, agent: row.provider, dshSessionId: row.sessionId, identity: m.identity, cwd: m.cwd, sessionId: row.nativeId, contextSha256: m.contextSha256, ...(m.binding ? { bindingId: m.binding.bindingId, workspaceId: m.binding.workspaceId } : {}), ...(m.hostSource ? { hostSource: m.hostSource } : {}), ...(m.modelConfiguration ? { modelConfiguration: m.modelConfiguration } : {}) } };
359
357
  }
360
358
  release(sessionId, id) { if (this.live.get(sessionId) === id)
361
359
  this.live.delete(sessionId); }
@@ -1,7 +1,6 @@
1
1
  import type { Context } from '@deepseek-ai/cordis';
2
2
  import { NeedError } from './remote.ts';
3
3
  import type { ConnectTarget } from './provider.ts';
4
- import type { UsageSnapshot } from './mapping.ts';
5
4
  export interface ColdWrite {
6
5
  id: string;
7
6
  sha256: string;
@@ -43,8 +42,8 @@ export interface ColdRound {
43
42
  revision: number;
44
43
  };
45
44
  hostSource?: unknown;
46
- contextSha256: string;
47
- baseline: UsageSnapshot | null;
45
+ contextSha256: string; /** 只读旧版字段;不再作为跨轮基线。 */
46
+ baseline?: unknown;
48
47
  modelConfiguration?: unknown;
49
48
  header: unknown;
50
49
  model: string;
@@ -70,7 +69,7 @@ export interface ColdRound {
70
69
  inputNotDelivered: true;
71
70
  receipt: unknown;
72
71
  };
73
- finalUsage?: UsageSnapshot | null;
72
+ /** 只读旧版字段;不再参与恢复结算。 */ finalUsage?: unknown;
74
73
  errorDelivery?: {
75
74
  markerId: string;
76
75
  code: string;
@@ -4,6 +4,7 @@ import type { ConnectApi, ConnectTarget, ConnectionState, Project, Runtime, Runt
4
4
  import { type BrokerIo, type SshArgv } from './broker.ts';
5
5
  import type { DetailChannel } from './remote-details.ts';
6
6
  import type { LocalWorkspaceContext } from '@ai-workbench/connect/api';
7
+ import type { EmployeeStartup } from './employee-startup.ts';
7
8
  export interface EmployeeProviderOptions {
8
9
  getNetwork(): NetworkApi | undefined;
9
10
  workspace(request: RuntimeRequest): Promise<{
@@ -26,6 +27,7 @@ interface Admission {
26
27
  target: ConnectTarget;
27
28
  connection: ConnectionState;
28
29
  request: RuntimeRequest;
30
+ preparation?: EmployeeStartup;
29
31
  }
30
32
  /** Inspect the current local workspace once at turn start, before host readiness. */
31
33
  export declare function inspectEmployeeWorkspace(get: () => ConnectApi | undefined, employee: EmployeeProviderOptions, agent: AgentDefinition, api: ConnectApi, request: RuntimeRequest): Promise<Readonly<LocalWorkspaceContext> | undefined>;
@@ -134,13 +134,13 @@ export function createEmployeeProvider(get, options, agent) {
134
134
  throw fail('EMPLOYEE_OPERATION_UNSUPPORTED');
135
135
  if (!Number.isSafeInteger(request.acpMaxMessageBytes) || request.acpMaxMessageBytes < 1)
136
136
  throw fail('SETTINGS_REQUIRED');
137
- const prepareLocation = () => admitEmployeeLocation({ api: api, network, workspace, connection, expectedLocal: { instanceId: context.instanceId, epoch: context.epoch, workspaceId: context.workspaceId, bindingId: context.bindingId, directory: { ...context.directory } }, settingsPath: target.session.settingsPath, signal: roundSignal });
138
- const resolveNative = () => employee.native();
137
+ const prepareLocation = () => input.preparation ? input.preparation.location(network, context) : admitEmployeeLocation({ api: api, network, workspace, connection, expectedLocal: { instanceId: context.instanceId, epoch: context.epoch, workspaceId: context.workspaceId, bindingId: context.bindingId, directory: { ...context.directory } }, settingsPath: target.session.settingsPath, signal: roundSignal });
138
+ const resolveNative = () => input.preparation ? input.preparation.native() : employee.native();
139
139
  // 仅把无授权、无目标的静态包路径解析与本轮N准备重叠。两项都收敛后,
140
140
  // 按原顺序处理错误;每轮N准备、事件撤销、执行目标绑定仍完整执行。
141
141
  const [locationResult, nativeResult] = await Promise.allSettled([
142
- request.startupTiming?.run('endpoint-prepare', prepareLocation) ?? prepareLocation(),
143
- request.startupTiming?.run('native-metadata', resolveNative) ?? resolveNative(),
142
+ input.preparation ? prepareLocation() : request.startupTiming?.run('endpoint-prepare', prepareLocation) ?? prepareLocation(),
143
+ input.preparation ? resolveNative() : request.startupTiming?.run('native-metadata', resolveNative) ?? resolveNative(),
144
144
  ]);
145
145
  if (locationResult.status === 'rejected')
146
146
  throw locationResult.reason;
@@ -0,0 +1,18 @@
1
+ import type { NetworkApi } from '@ai-workbench/network/api';
2
+ import type { LocalWorkspaceContext } from '@ai-workbench/connect/api';
3
+ import type { EmployeeProviderOptions } from './employee-provider.ts';
4
+ import { type ConnectApi, type ConnectTarget, type ConnectionState, type RuntimeRequest } from './provider.ts';
5
+ import { admitEmployeeLocation } from './employee-location.ts';
6
+ type Location = Awaited<ReturnType<typeof admitEmployeeLocation>>;
7
+ /** 只拥有本次请求的等待和围栏,不拥有、关闭或缓存N的共享设备服务。 */
8
+ export interface EmployeeStartup {
9
+ ready: Promise<void>;
10
+ confirm(target: ConnectTarget, connection: ConnectionState): void;
11
+ location(network: NetworkApi, context: Readonly<LocalWorkspaceContext>): Promise<Location>;
12
+ native(): Promise<{
13
+ path: string;
14
+ }>;
15
+ cancel(): void;
16
+ }
17
+ export declare function beginEmployeeStartup(get: () => ConnectApi | undefined, employee: EmployeeProviderOptions, api: ConnectApi, request: RuntimeRequest): EmployeeStartup | undefined;
18
+ export {};
@@ -0,0 +1,95 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ import { awaitL, sameTarget, validateTarget } from "./provider.js";
3
+ import { admitEmployeeLocation } from "./employee-location.js";
4
+ import { connectNeedError } from "./connect-need.js";
5
+ import { NeedError } from "./remote.js";
6
+ const failure = (code) => new NeedError(code, '员工电脑的工作区或执行连接已变化,本轮没有继续执行。', '当前工作区绑定与员工端执行器');
7
+ export function beginEmployeeStartup(get, employee, api, request) {
8
+ const context = request.localContext ? structuredClone(request.localContext) : undefined, connection = api.getConnectionState();
9
+ // 只在原context已接纳且已有执行用途可信target的路径重叠;首次未连接仍按原顺序开通。
10
+ if (!context || connection.phase !== 'connected' || typeof api.getSshTarget !== 'function')
11
+ return;
12
+ const network = employee.getNetwork(), lifetime = new AbortController(), offs = [];
13
+ const signal = AbortSignal.any([lifetime.signal, ...request.signal ? [request.signal] : []]);
14
+ let closed = false, target, location, native;
15
+ const nativeMetadata = () => native ??= (request.startupTiming?.run('native-metadata', () => employee.native()) ?? Promise.resolve().then(() => employee.native()));
16
+ const close = () => { if (closed)
17
+ return; closed = true; for (const off of offs.splice(0))
18
+ off(); };
19
+ const cancel = () => { lifetime.abort(failure('ABORTED')); close(); };
20
+ const check = () => {
21
+ signal.throwIfAborted();
22
+ request.localAdmissionCheck?.();
23
+ if (get() !== api || employee.getNetwork() !== network)
24
+ throw failure('EMPLOYEE_CONTEXT_CHANGED');
25
+ const now = api.getConnectionState();
26
+ if (now.phase !== 'connected' || now.instanceId !== connection.instanceId || now.epoch !== connection.epoch)
27
+ throw failure('CONNECTION_LOST');
28
+ if (!network || network.getState().phase !== 'online')
29
+ throw failure('CONNECTION_LOST');
30
+ };
31
+ const changed = () => { try {
32
+ check();
33
+ }
34
+ catch (error) {
35
+ lifetime.abort(error);
36
+ close();
37
+ } };
38
+ const revokeNetwork = (event) => { if (event.kind === 'lost') {
39
+ lifetime.abort(failure('CONNECTION_LOST'));
40
+ close();
41
+ }
42
+ else
43
+ changed(); };
44
+ const aborted = () => close();
45
+ signal.addEventListener('abort', aborted, { once: true });
46
+ offs.push(() => signal.removeEventListener('abort', aborted));
47
+ const pending = (async () => {
48
+ if (typeof api.onConnectionState !== 'function' || typeof api.onWorkspaceLocationState !== 'function' || !network || typeof network.onState !== 'function' || typeof network.prepareEmployeeEndpoint !== 'function')
49
+ throw failure('DEPENDENCY_REQUIRED');
50
+ const watch = (off) => { if (closed)
51
+ off();
52
+ else
53
+ offs.push(off); };
54
+ watch(api.onConnectionState(changed));
55
+ watch(api.onWorkspaceLocationState(changed));
56
+ watch(network.onState(revokeNetwork));
57
+ if (network.getState().phase !== 'online')
58
+ throw failure('EMPLOYEE_ENDPOINT_UNAVAILABLE');
59
+ check();
60
+ const current = await awaitL(() => api.getSshTarget(), signal);
61
+ if (!current.ok)
62
+ throw connectNeedError(current.error);
63
+ target = structuredClone(current.value);
64
+ validateTarget(target);
65
+ check();
66
+ // 保留O1既有的纯静态解析重叠;实际执行与broker仍须等待两道门及静态结果。
67
+ void nativeMetadata().catch(() => { });
68
+ const prepare = () => admitEmployeeLocation({ api: api, network, workspace: { id: context.workspaceId, path: context.directory.path }, connection, expectedLocal: { instanceId: context.instanceId, epoch: context.epoch, workspaceId: context.workspaceId, bindingId: context.bindingId, directory: { ...context.directory } }, settingsPath: target.session.settingsPath, signal });
69
+ location = await awaitL(() => request.startupTiming?.run('endpoint-prepare', prepare) ?? prepare(), signal);
70
+ check();
71
+ })();
72
+ // 登录失败始终优先;端点提前失败也先被观察,不能产生未处理拒绝或抢先改变失败语义。
73
+ void pending.catch(() => { });
74
+ const confirm = (current, ready) => { check(); if (!target || !sameTarget(target, current) || ready.instanceId !== connection.instanceId || ready.epoch !== connection.epoch)
75
+ throw failure('EMPLOYEE_CONTEXT_CHANGED'); };
76
+ return { ready: pending, confirm, cancel, native: nativeMetadata, async location(currentNetwork, currentContext) {
77
+ await pending;
78
+ check();
79
+ if (currentNetwork !== network || !isDeepStrictEqual(currentContext, context))
80
+ throw failure('EMPLOYEE_CONTEXT_CHANGED');
81
+ // 准备完成至登录结束之间仍可能替换物理目录;只重读L的只读context,不再prepare第二次。
82
+ const [current, physical] = await Promise.all([
83
+ awaitL(() => api.getSshTarget(), signal),
84
+ awaitL(() => api.getLocalWorkspaceContext({ instanceId: context.instanceId, epoch: context.epoch, workspaceId: context.workspaceId, expectedBindingId: context.bindingId }), signal),
85
+ ]);
86
+ check();
87
+ if (!current.ok)
88
+ throw connectNeedError(current.error);
89
+ if (!physical.ok)
90
+ throw connectNeedError(physical.error);
91
+ if (!target || !sameTarget(target, current.value) || !isDeepStrictEqual(physical.value, context))
92
+ throw failure('EMPLOYEE_CONTEXT_CHANGED');
93
+ return location;
94
+ } };
95
+ }
package/dist/index.js CHANGED
@@ -481,12 +481,12 @@ export class CodexRemoteAdapter extends LlmAdapter {
481
481
  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 });
482
482
  if (runtime.hostWorkspace)
483
483
  details.record({ kind: 'session', severity: 'info', code: 'HOST_WORKSPACE_CONTEXT', summary: '本轮模型工作区上下文及审批会话目录使用已确认的主机目录。', payload: { source: 'host', cwd: runtime.hostWorkspace.cwd } });
484
- const mapper = new StreamMapper(mode === 'session' ? (previous ? (previous.usageSnapshot ?? null) : undefined) : undefined, observation => details.record(observation));
484
+ const mapper = new StreamMapper(observation => details.record(observation));
485
485
  activeMapper = mapper;
486
486
  let id;
487
487
  let stop;
488
488
  const pointerRuntime = runtime;
489
- 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 } : {}) });
489
+ 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 } : {}) });
490
490
  if (runtime.employeePresentation)
491
491
  details.record({ kind: 'session', severity: 'warning', code: 'EMPLOYEE_EXECUTION_SCOPE', summary: runtime.employeePresentation, payload: { source: 'local' } });
492
492
  if (runtime.execution)
@@ -565,10 +565,15 @@ export class CodexRemoteAdapter extends LlmAdapter {
565
565
  }
566
566
  }
567
567
  } bridge?.observe(notification.update); push(mapper.acp(notification.update)); if (inRound)
568
- nativeUpdates++; }); }, onResponse: response => render(() => { push(mapper.acpResponse(response)); }), onDetail: detail => details.record(detail) };
568
+ nativeUpdates++; }); }, onResponse: response => render(async () => {
569
+ // 可靠回执先持久化,再向DSH投影;退出后即使原broker被回收也能补记同轮未落盘用量。
570
+ if (runtime.cold)
571
+ 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; });
572
+ push(mapper.acpResponse(response));
573
+ }), onDetail: detail => details.record(detail) };
569
574
  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 });
570
575
  session = new AcpSession(transport, hooks);
571
- live = { session, runtime, configuration, contextSha256, usageSnapshot: mapper.usageSnapshot, options, acceptingSteer: true, turnId: randomUUID(), steerIds: new Map(), steerTail: Promise.resolve(), maxBytes: config.acpMaxMessageBytes, notice: renderNotice };
576
+ live = { session, runtime, configuration, contextSha256, options, acceptingSteer: true, turnId: randomUUID(), steerIds: new Map(), steerTail: Promise.resolve(), maxBytes: config.acpMaxMessageBytes, notice: renderNotice };
572
577
  if (key)
573
578
  this.sessions.set(key, live);
574
579
  promptBaseline = session.promptDispatchCount;
@@ -668,7 +673,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
668
673
  details.beginTurn(runtime.detailContext?.() ?? { turn: null, step: null });
669
674
  await renderTail;
670
675
  if (runtime.cold && this.coldRecovery)
671
- 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 });
676
+ 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 });
672
677
  coldPromptStarted = true;
673
678
  await runtime.execution?.beginTurn(modelSignal);
674
679
  if (bridge?.enabled)
@@ -733,8 +738,6 @@ export class CodexRemoteAdapter extends LlmAdapter {
733
738
  details.endTurn();
734
739
  if (!id)
735
740
  throw new NeedError('SESSION_ID_MISSING', '远端没有返回会话标识', '有效的远端会话标识');
736
- if (live)
737
- live.usageSnapshot = mapper.usageSnapshot;
738
741
  if (modelConfiguration) {
739
742
  const actual = session.modelConfiguration;
740
743
  const changed = !actual?.confirmed || actual.model !== modelConfiguration.configured.model || actual.effort !== modelConfiguration.configured.effort;
@@ -743,14 +746,14 @@ export class CodexRemoteAdapter extends LlmAdapter {
743
746
  }
744
747
  }
745
748
  yield* mapper.flush();
746
- 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;
749
+ 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;
747
750
  const pointer = { ...makePointer(id), ...(finalCold ? { coldRoundTerminal: true, coldPromptId: finalCold.promptId, coldOutputAfter: runtime.broker?.lastSequence } : {}) };
748
751
  succeeded = true;
749
752
  yield { type: 'finish', reason: { kind: stop === 'max_tokens' || stop === 'max_turn_requests' ? 'max-tokens' : 'stop' }, replayState: { response: pointer } };
750
753
  }
751
754
  catch (error) {
752
755
  if (original.signal?.reason?.kind === 'user' && runtime?.cold && this.coldRecovery)
753
- await this.coldRecovery.recordUserCancellation(runtime, options, session?.id ?? request?.resumeSessionId, { identity: runtime.identity, cwd: runtime.cwd, binding: runtime.binding, hostSource: runtime.hostSource, contextSha256: request?.contextSha256 ?? '', baseline: activeMapper?.usageSnapshot ?? null, modelConfiguration: modelConfiguration ?? { selected }, model: options.model, prelude: coldPrelude, localDirectory: runtime.localDirectory });
756
+ 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 });
754
757
  if (session && session.promptDispatchCount > promptBaseline)
755
758
  onPromptDispatched();
756
759
  if (bridge?.unsettled && !signal.aborted)
@@ -769,6 +772,8 @@ export class CodexRemoteAdapter extends LlmAdapter {
769
772
  throw withFirstFailureEvidence(error, runtime?.closeDiagnostics?.first?.reason, failureCode);
770
773
  }
771
774
  finally {
775
+ if (request)
776
+ this.resolveRuntime.releasePreparation?.(request);
772
777
  permissionOff?.();
773
778
  permissionOff = undefined;
774
779
  permissionEpoch.abort();
package/dist/mapping.d.ts CHANGED
@@ -1,36 +1,18 @@
1
1
  import type { StreamChunk } from '@deepseek-ai/dsh-llm';
2
2
  import type { PromptResponse, SessionUpdate } from '@agentclientprotocol/sdk/unstable';
3
3
  import { type SanitizedObservation } from './conversation-details.ts';
4
- /** Persist alongside the exact remote session identity; null means no trusted baseline. */
5
- export type UsageSnapshot = {
6
- version: 1;
7
- kind: 'zero';
8
- } | {
9
- version: 1;
10
- kind: 'cumulative';
11
- source: 'usage' | 'quota';
12
- inputTokens: number;
13
- outputTokens: number;
14
- cachedReadTokens?: number;
15
- cachedWriteTokens?: number;
16
- thoughtTokens?: number;
17
- totalTokens?: number;
18
- /** A response was missing or unusable; the next complete response only re-establishes a baseline. */
19
- gap?: true;
20
- };
21
4
  /** Only model text enters DSH blocks; remote operations remain diagnostic observations. */
22
5
  export declare class StreamMapper {
23
6
  private index;
24
7
  private active;
25
- private baseline;
8
+ private responseSettled;
26
9
  private readonly observations;
27
10
  private readonly modelMetadata;
28
11
  private anonymousMetadata;
29
12
  private lastMetadataType;
30
13
  private readonly onDiagnostic;
31
- /** Omitted argument is exclusively for a known new session; pass null on unknown resume. */
32
- constructor(previousUsage?: UsageSnapshot | null, onDiagnostic?: (observation: Readonly<SanitizedObservation>) => void);
33
- get usageSnapshot(): UsageSnapshot | null;
14
+ /** 一个映射器对应一个 ACP prompt;旧检查点中的累计快照不参与结算。 */
15
+ constructor(onDiagnostic?: (observation: Readonly<SanitizedObservation>) => void);
34
16
  get diagnostics(): readonly Readonly<SanitizedObservation>[];
35
17
  private diagnostic;
36
18
  private usageWarning;
@@ -40,9 +22,7 @@ export declare class StreamMapper {
40
22
  /** Close the current text or reasoning block once, before the stream settles. */
41
23
  flush(): StreamChunk[];
42
24
  acp(update: SessionUpdate): StreamChunk[];
43
- /** ACP usage and the fixed Claude quota both accumulate across the session, not per turn. */
25
+ /** Codex aw.15 与 Claude 0.94.0 的 usage/quota 都是本次 prompt 的用量。 */
44
26
  acpResponse(response: PromptResponse): StreamChunk[];
45
- private usageGap;
46
- private cumulativeUsage;
47
27
  private usage;
48
28
  }
package/dist/mapping.js CHANGED
@@ -1,25 +1,18 @@
1
- import { NeedError } from "./remote.js";
2
1
  import { sanitizeObservation } from "./conversation-details.js";
3
- const usageCounters = ['inputTokens', 'outputTokens', 'cachedReadTokens', 'cachedWriteTokens', 'thoughtTokens', 'totalTokens'];
4
- const optionalUsageCounters = ['cachedReadTokens', 'cachedWriteTokens', 'thoughtTokens', 'totalTokens'];
5
2
  /** Only model text enters DSH blocks; remote operations remain diagnostic observations. */
6
3
  export class StreamMapper {
7
4
  index = 0;
8
5
  active;
9
- baseline;
6
+ responseSettled = false;
10
7
  observations = [];
11
8
  modelMetadata = new Map();
12
9
  anonymousMetadata = 0;
13
10
  lastMetadataType;
14
11
  onDiagnostic;
15
- /** Omitted argument is exclusively for a known new session; pass null on unknown resume. */
16
- constructor(previousUsage = { version: 1, kind: 'zero' }, onDiagnostic) {
17
- if (previousUsage !== null && !validUsageSnapshot(previousUsage))
18
- throw new NeedError('USAGE_BASELINE_INVALID', '已保存的远端累计用量基线无效,不能重复结算历史用量', '与原远端会话关联的有效用量快照');
19
- this.baseline = previousUsage === null ? null : { ...previousUsage };
12
+ /** 一个映射器对应一个 ACP prompt;旧检查点中的累计快照不参与结算。 */
13
+ constructor(onDiagnostic) {
20
14
  this.onDiagnostic = onDiagnostic;
21
15
  }
22
- get usageSnapshot() { return this.baseline === null ? null : { ...this.baseline }; }
23
16
  get diagnostics() {
24
17
  return Object.freeze(this.observations.map(observation => sanitizeObservation(observation)));
25
18
  }
@@ -136,8 +129,12 @@ export class StreamMapper {
136
129
  }
137
130
  return this.diagnostic({ kind, severity, code, summary, method: 'session/update', payload: update });
138
131
  }
139
- /** ACP usage and the fixed Claude quota both accumulate across the session, not per turn. */
132
+ /** Codex aw.15 与 Claude 0.94.0 的 usage/quota 都是本次 prompt 的用量。 */
140
133
  acpResponse(response) {
134
+ if (this.responseSettled)
135
+ return [];
136
+ // 先认领终态:诊断落盘异常也不能使同一回执再次结算。
137
+ this.responseSettled = true;
141
138
  this.flushMetadata();
142
139
  this.diagnostic({ kind: 'usage', severity: 'info', code: 'ACP_PROMPT_RESPONSE', summary: '远端响应与真实用量', method: 'session/prompt', payload: response });
143
140
  const quota = record(response._meta?.quota);
@@ -145,63 +142,25 @@ export class StreamMapper {
145
142
  const usage = response.usage;
146
143
  let chunks;
147
144
  if (usage) {
148
- chunks = this.cumulativeUsage('usage', usage.inputTokens, usage.outputTokens, usage.cachedReadTokens, usage.cachedWriteTokens, usage.thoughtTokens, usage.totalTokens);
145
+ chunks = this.usage(usage.inputTokens, usage.outputTokens, usage.cachedReadTokens, usage.cachedWriteTokens, usage.thoughtTokens, usage.totalTokens);
149
146
  }
150
147
  else if (tokens) {
151
148
  // Fixed Claude adapter's quotaTokenCount: inputTokens excludes both
152
149
  // cachedInputTokens (reads) and cachedWriteTokens (writes).
153
- chunks = this.cumulativeUsage('quota', tokens.inputTokens, tokens.outputTokens, tokens.cachedInputTokens, tokens.cachedWriteTokens, undefined, tokens.totalTokens);
150
+ chunks = this.usage(tokens.inputTokens, tokens.outputTokens, tokens.cachedInputTokens, tokens.cachedWriteTokens ?? tokens.cacheWriteInputTokens, undefined, tokens.totalTokens);
154
151
  }
155
152
  else {
156
- this.usageGap();
157
153
  chunks = this.usageWarning('\n[远端用量] 本轮生成用量未提供;上下文占用不能替代输入或输出计数。\n');
158
154
  }
159
155
  return chunks;
160
156
  }
161
- usageGap() { this.baseline = this.baseline?.kind === 'cumulative' ? { ...this.baseline, gap: true } : null; }
162
- cumulativeUsage(source, input, output, read, write, thought, total) {
163
- const values = [input, output, ...(read == null ? [] : [read]), ...(write == null ? [] : [write]), ...(thought == null ? [] : [thought]), ...(total == null ? [] : [total])];
164
- if (!values.every(validCount)) {
165
- this.usageGap();
166
- return this.usageWarning('\n[远端用量] 远端累计计数无效,本轮未记录生成用量;需要有效的输入、输出与缓存计数。\n');
167
- }
168
- const current = { version: 1, kind: 'cumulative', source, inputTokens: input, outputTokens: output,
169
- ...(read == null ? {} : { cachedReadTokens: read }), ...(write == null ? {} : { cachedWriteTokens: write }),
170
- ...(thought == null ? {} : { thoughtTokens: thought }), ...(total == null ? {} : { totalTokens: total }) };
171
- const previous = this.baseline;
172
- if (previous?.kind === 'cumulative' && previous.source === source) {
173
- if (usageCounters.some(key => current[key] !== undefined && previous[key] !== undefined && current[key] < previous[key])) {
174
- this.usageGap();
175
- return this.usageWarning('\n[远端用量] 远端累计计数发生回退,本轮未记录生成用量;已保留此前高水位,需要核对远端会话计数。\n');
176
- }
177
- if (optionalUsageCounters.some(key => previous[key] !== undefined && current[key] === undefined)) {
178
- this.baseline = { ...previous, ...current, gap: true };
179
- return this.usageWarning('\n[远端用量] 可选累计计数缺失,本轮未记录生成用量;未把缺失值补为零,等待完整计数重建基线。\n');
180
- }
181
- }
182
- const sum = current.inputTokens + current.outputTokens + (current.cachedReadTokens ?? 0) + (current.cachedWriteTokens ?? 0);
183
- if (!Number.isSafeInteger(sum) || (current.totalTokens !== undefined && current.totalTokens !== sum) || (current.thoughtTokens !== undefined && current.thoughtTokens > current.outputTokens)) {
184
- this.usageGap();
185
- return this.usageWarning('\n[远端用量] 输入、输出、缓存与合计计数不一致,本轮未记录生成用量;需要远端提供语义一致的真实计数。\n');
186
- }
187
- this.baseline = current;
188
- if (previous === null || previous.kind === 'cumulative' && (previous.source !== source || previous.gap || optionalUsageCounters.some(key => previous[key] === undefined && current[key] !== undefined))) {
189
- return this.usageWarning('\n[远端用量] 已建立当前累计用量基线;本轮未记录生成用量,避免把无法核对的历史累计重复结算。\n');
190
- }
191
- if (previous.kind === 'zero')
192
- return this.usage(current.inputTokens, current.outputTokens, current.cachedReadTokens, current.cachedWriteTokens, current.thoughtTokens, current.totalTokens);
193
- const delta = (key) => current[key] === undefined ? undefined : current[key] - previous[key];
194
- if (!usageCounters.some(key => (delta(key) ?? 0) !== 0))
195
- return [];
196
- return this.usage(delta('inputTokens'), delta('outputTokens'), delta('cachedReadTokens'), delta('cachedWriteTokens'), delta('thoughtTokens'), delta('totalTokens'));
197
- }
198
157
  usage(input, output, read, write, thought, total) {
199
158
  const values = [input, output, ...(read == null ? [] : [read]), ...(write == null ? [] : [write]), ...(thought == null ? [] : [thought]), ...(total == null ? [] : [total])];
200
159
  if (!values.every(n => typeof n === 'number' && Number.isSafeInteger(n) && n >= 0)) {
201
160
  return this.usageWarning('\n[远端用量] 远端真实计数无效,本轮未记录生成用量;需要有效的输入、输出与缓存计数。\n');
202
161
  }
203
162
  const sum = input + output + (read ?? 0) + (write ?? 0);
204
- if ((total != null && total !== sum) || (thought != null && thought > output)) {
163
+ if (!Number.isSafeInteger(sum) || (total != null && total !== sum) || (thought != null && thought > output)) {
205
164
  return this.usageWarning('\n[远端用量] 输入、输出、缓存与合计计数不一致,本轮未记录生成用量;需要远端提供语义一致的真实计数。\n');
206
165
  }
207
166
  return [{ type: 'usage', usage: { inputTokens: input, outputTokens: output,
@@ -209,17 +168,4 @@ export class StreamMapper {
209
168
  ...(thought == null ? {} : { reasoningTokens: thought }) } }];
210
169
  }
211
170
  }
212
- function validCount(value) { return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0; }
213
- function validUsageSnapshot(value) {
214
- const snapshot = record(value);
215
- if (snapshot?.version !== 1)
216
- return false;
217
- if (snapshot.kind === 'zero')
218
- return Object.keys(snapshot).every(key => key === 'kind' || key === 'version');
219
- if (snapshot.kind !== 'cumulative' || (snapshot.source !== 'usage' && snapshot.source !== 'quota') || (snapshot.gap !== undefined && snapshot.gap !== true)
220
- || !validCount(snapshot.inputTokens) || !validCount(snapshot.outputTokens) || optionalUsageCounters.some(key => snapshot[key] !== undefined && !validCount(snapshot[key])))
221
- return false;
222
- const sum = snapshot.inputTokens + snapshot.outputTokens + (snapshot.cachedReadTokens ?? 0) + (snapshot.cachedWriteTokens ?? 0);
223
- return snapshot.gap === true || Number.isSafeInteger(sum) && (snapshot.totalTokens === undefined || snapshot.totalTokens === sum) && (snapshot.thoughtTokens === undefined || snapshot.thoughtTokens <= snapshot.outputTokens);
224
- }
225
171
  function record(value) { return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : undefined; }
@@ -113,6 +113,7 @@ export interface RuntimeRequest extends Invocation {
113
113
  }
114
114
  export type RuntimeProvider = ((request: RuntimeRequest) => Promise<Runtime>) & {
115
115
  preflight?: (request: RuntimeRequest) => Promise<void>;
116
+ releasePreparation?: (request: RuntimeRequest) => void;
116
117
  };
117
118
  export interface ConnectTarget {
118
119
  host: string;
package/dist/provider.js CHANGED
@@ -149,6 +149,16 @@ export function connectProvider(get, options = {}) {
149
149
  // Cache the initialization promise so concurrent sessions share this provider's binding lifetimes.
150
150
  let employee;
151
151
  const admissions = new WeakMap();
152
+ const preparations = new WeakMap();
153
+ const releasePreparation = (request) => { const owned = preparations.get(request); preparations.delete(request); admissions.delete(request); owned?.restore(); owned?.preparation.cancel(); };
154
+ const ownPreparation = (request, preparation) => {
155
+ const original = request.recordEarlyFailure;
156
+ const wrapped = async (error, stage) => { releasePreparation(request); if (original)
157
+ await original(error, stage); };
158
+ preparations.set(request, { preparation, restore: () => { if (request.recordEarlyFailure === wrapped)
159
+ request.recordEarlyFailure = original; } });
160
+ request.recordEarlyFailure = wrapped;
161
+ };
152
162
  const preflight = async (request) => {
153
163
  request.signal?.throwIfAborted();
154
164
  const api = get();
@@ -157,6 +167,7 @@ export function connectProvider(get, options = {}) {
157
167
  requireNativeWorkspace(api);
158
168
  requireLoginCoordinator(api);
159
169
  let sourceStage = 'input-acceptance';
170
+ let preparation;
160
171
  try {
161
172
  request.workspaceSource = options.source ? await options.source(request, api) : request.hostSource;
162
173
  if (!options.source && !request.workspaceSource && options.workspace && request.sessionId && api.getContractInfo().workspaceLocations === 1) {
@@ -169,6 +180,12 @@ export function connectProvider(get, options = {}) {
169
180
  request.localContext = await module.inspectEmployeeWorkspace(get, options.employee, agent, api, request);
170
181
  }
171
182
  sourceStage = 'login-readiness';
183
+ if (!host && agent.loginProvider === 'codex' && options.employee && request.localContext) {
184
+ const module = await import("./employee-startup.js");
185
+ preparation = module.beginEmployeeStartup(get, options.employee, api, request);
186
+ if (preparation)
187
+ ownPreparation(request, preparation);
188
+ }
172
189
  const loginReady = async () => {
173
190
  request.localAdmissionCheck?.();
174
191
  const before = api.getConnectionState();
@@ -191,8 +208,13 @@ export function connectProvider(get, options = {}) {
191
208
  throw connectNeedError(locations.need);
192
209
  if (!host)
193
210
  await options.local?.admit?.(request, api, connection, target);
211
+ if (preparation) {
212
+ await preparation.ready;
213
+ preparation.confirm(target, connection);
214
+ }
194
215
  }
195
216
  catch (error) {
217
+ preparation?.cancel();
196
218
  admissions.delete(request);
197
219
  const record = request.recordEarlyFailure;
198
220
  request.recordEarlyFailure = undefined;
@@ -207,41 +229,51 @@ export function connectProvider(get, options = {}) {
207
229
  const admitted = admissions.get(request);
208
230
  admissions.delete(request);
209
231
  const { api, target, connection } = admitted;
210
- if (!request.sessionId)
211
- throw new NeedError('PROJECT_BINDING_REQUIRED', '我需要当前会话和已选择的工作区,请使用原生工作区入口', 'DSH会话与原生工作区');
212
- const host = request.workspaceSource?.source === 'host';
213
- if (!host && options.employee) {
214
- employee ??= import("./employee-provider.js").then(module => module.createEmployeeProvider(get, options, agent));
215
- const local = await (await employee)({ api, target, connection, request });
216
- if (local) {
217
- local.loginRequired = () => offerLogin(api, request, get, agent);
218
- return local;
232
+ const owned = preparations.get(request);
233
+ preparations.delete(request);
234
+ owned?.restore();
235
+ const preparation = owned?.preparation;
236
+ try {
237
+ if (!request.sessionId)
238
+ throw new NeedError('PROJECT_BINDING_REQUIRED', '我需要当前会话和已选择的工作区,请使用原生工作区入口', 'DSH会话与原生工作区');
239
+ const host = request.workspaceSource?.source === 'host';
240
+ if (!host && options.employee) {
241
+ employee ??= import("./employee-provider.js").then(module => module.createEmployeeProvider(get, options, agent));
242
+ const local = await (await employee)({ api, target, connection, request, preparation });
243
+ if (local) {
244
+ local.loginRequired = () => offerLogin(api, request, get, agent);
245
+ return local;
246
+ }
247
+ }
248
+ if (!host && agent.loginProvider === 'claude' && options.local) {
249
+ const runtime = await options.local(request, api, connection, target);
250
+ if (runtime)
251
+ return runtime;
219
252
  }
253
+ // A local source must have been handled by its employee provider above.
254
+ // Host execution requires an explicit host location; no name-based resolver.
255
+ if (!host)
256
+ throw new NeedError('WORKSPACE_LOCATION_REQUIRED', '请选择文件夹来源;改变来源后请新建会话。', '已选择的本机或主机文件夹');
257
+ const resolved = await resolveHostWorkspace(api, request, agent.loginProvider);
258
+ const project = resolved.project;
259
+ const details = await options.details?.(request, api, connection, target);
260
+ if (!options.open)
261
+ throw new NeedError('RUNTIME_REQUIRED', '我需要主机运行适配器', '主机broker适配');
262
+ const runtime = await options.open(resolved.target, project, { ...request, agent, bindingId: undefined, workspaceId: undefined, bindingRevision: undefined, detailChannel: details });
263
+ runtime.hostSource = Object.freeze({ ...request.workspaceSource });
264
+ runtime.hostWorkspace = Object.freeze({ cwd: project.path });
265
+ // The transport can outlive a turn; presentation belongs only to this invocation.
266
+ runtime.details = details ?? runtime.details;
267
+ runtime.binding = undefined;
268
+ runtime.connection = { ...connection };
269
+ runtime.loginRequired = () => offerLogin(api, request, get, agent);
270
+ return runtime;
220
271
  }
221
- if (!host && agent.loginProvider === 'claude' && options.local) {
222
- const runtime = await options.local(request, api, connection, target);
223
- if (runtime)
224
- return runtime;
272
+ finally {
273
+ preparation?.cancel();
225
274
  }
226
- // A local source must have been handled by its employee provider above.
227
- // Host execution requires an explicit host location; no name-based resolver.
228
- if (!host)
229
- throw new NeedError('WORKSPACE_LOCATION_REQUIRED', '请选择文件夹来源;改变来源后请新建会话。', '已选择的本机或主机文件夹');
230
- const resolved = await resolveHostWorkspace(api, request, agent.loginProvider);
231
- const project = resolved.project;
232
- const details = await options.details?.(request, api, connection, target);
233
- if (!options.open)
234
- throw new NeedError('RUNTIME_REQUIRED', '我需要主机运行适配器', '主机broker适配');
235
- const runtime = await options.open(resolved.target, project, { ...request, agent, bindingId: undefined, workspaceId: undefined, bindingRevision: undefined, detailChannel: details });
236
- runtime.hostSource = Object.freeze({ ...request.workspaceSource });
237
- runtime.hostWorkspace = Object.freeze({ cwd: project.path });
238
- // The transport can outlive a turn; presentation belongs only to this invocation.
239
- runtime.details = details ?? runtime.details;
240
- runtime.binding = undefined;
241
- runtime.connection = { ...connection };
242
- runtime.loginRequired = () => offerLogin(api, request, get, agent);
243
- return runtime;
244
275
  };
245
276
  resolve.preflight = preflight;
277
+ resolve.releasePreparation = releasePreparation;
246
278
  return resolve;
247
279
  }
@@ -8,4 +8,4 @@ export interface BridgeTool {
8
8
  wire: Tool;
9
9
  }
10
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>;
11
+ export declare function bridgeTable(tools?: readonly ToolSchema[], catalog?: readonly string[], catalogInCurrentPrompt?: boolean): ReadonlyMap<string, BridgeTool>;
@@ -17,7 +17,7 @@ export function dshSkillCatalog(messages = []) {
17
17
  return source.entries.map(entry => entry.name);
18
18
  }
19
19
  }
20
- export function bridgeTable(tools = [], catalog) {
20
+ export function bridgeTable(tools = [], catalog, catalogInCurrentPrompt = false) {
21
21
  const table = new Map(), names = new Set();
22
22
  for (const tool of tools) {
23
23
  if (excluded.has(tool.name))
@@ -29,7 +29,7 @@ export function bridgeTable(tools = [], catalog) {
29
29
  if (table.has(alias))
30
30
  throw new NeedError('TOOLBRIDGE_NAME_COLLISION', '工具桥名称冲突,未执行。', '唯一工具桥名称');
31
31
  const schema = structuredClone(tool);
32
- const skill = schema.name === 'skill' ? ' 这是DSH技能加载器,名字取自DSH的<available_skills>目录;主机Claude/Codex的原生技能按各自原生技能指令加载。' + (catalog === undefined ? '请以当前DSH技能目录为准。' : '本次DSH公布的目录快照:' + JSON.stringify(catalog) + ';实际可用性由DSH调用时确认。') + '技能资源按返回的<skill_resources>基址读取。' : '';
32
+ const skill = schema.name === 'skill' ? ' 这是DSH技能加载器,名字取自DSH的<available_skills>目录;主机Claude/Codex的原生技能按各自原生技能指令加载。' + (catalogInCurrentPrompt ? '实际可用性由DSH调用时确认。' : catalog === undefined ? '请以当前DSH技能目录为准。' : '本次DSH公布的目录快照:' + JSON.stringify(catalog) + ';实际可用性由DSH调用时确认。') + '技能资源按返回的<skill_resources>基址读取。' : '';
33
33
  table.set(alias, { alias, schema, wire: { name: alias, description: 'DSH工具 ' + schema.name + ':' + schema.description + skill, inputSchema: structuredClone(schema.parameters) } });
34
34
  }
35
35
  return table;
@@ -16,7 +16,26 @@ export class ToolBridge {
16
16
  readImage;
17
17
  controller = new AbortController();
18
18
  snapshot;
19
- get table() { return this.snapshot ??= bridgeTable(this.options.tools, dshSkillCatalog(this.options.messages)); }
19
+ get table() {
20
+ if (this.snapshot)
21
+ return this.snapshot;
22
+ const messages = this.options.messages, catalog = dshSkillCatalog(messages);
23
+ // prepareInput只转发最后assistant之后的user内容;历史目录不能代替当前prompt。
24
+ // 正文不含目录全部名字时仍保留原schema快照,避免分支/切模型时丢发现入口。
25
+ const current = messages.slice(messages.findLastIndex(message => message.role === 'assistant') + 1);
26
+ const forwarded = catalog !== undefined && catalog.length > 0 && current.some(message => {
27
+ const names = dshSkillCatalog([message]);
28
+ if (names === undefined || JSON.stringify(names) !== JSON.stringify(catalog))
29
+ return false;
30
+ const text = message.content.filter(block => block.type === 'text').map(block => block.text).join('\n');
31
+ // 只认官方目录中明确声明的完整名字;子串命中不能证明office也已随office-xlsx送达。
32
+ // 未识别的格式继续携带原名字快照,不推测目录内容。
33
+ const declared = new Set([...text.matchAll(/<available_skills>([\s\S]*?)<\/available_skills>/g)]
34
+ .flatMap(section => [...section[1].matchAll(/^[ \t]*-[ \t]+`([^`\r\n]+)`[ \t]*:/gm)].map(item => item[1])));
35
+ return catalog.every(name => declared.has(name));
36
+ });
37
+ return this.snapshot = bridgeTable(this.options.tools, catalog, forwarded);
38
+ }
20
39
  calls = new Map();
21
40
  enabled = false;
22
41
  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.27",
3
+ "version": "0.9.0-toolbridge.29",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",