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

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.28 · 插件 → 添加插件
2
2
 
3
3
  ## 办公依赖与开工计时(O1,2026-11-15)
4
4
 
@@ -87,4 +87,4 @@ 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 的规则传递保持。无新增设置、限制或错误码。
@@ -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;
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)
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; }
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.28",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",