@ai-workbench/remote-agent 0.9.0-toolbridge.3 → 0.9.0-toolbridge.31

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.
Files changed (56) hide show
  1. package/README.md +36 -7
  2. package/dist/acp.d.ts +23 -3
  3. package/dist/acp.js +106 -21
  4. package/dist/broker-runtime.d.ts +2 -0
  5. package/dist/broker-runtime.js +60 -3
  6. package/dist/broker.d.ts +56 -1
  7. package/dist/broker.js +310 -11
  8. package/dist/claude-local.js +26 -5
  9. package/dist/client.js +1 -1
  10. package/dist/close-diagnostics.d.ts +1 -1
  11. package/dist/close-diagnostics.js +1 -1
  12. package/dist/cold-protocol.d.ts +17 -0
  13. package/dist/cold-protocol.js +399 -0
  14. package/dist/cold-recovery.d.ts +62 -0
  15. package/dist/cold-recovery.js +595 -0
  16. package/dist/cold-store.d.ts +99 -0
  17. package/dist/cold-store.js +29 -0
  18. package/dist/conversation-details.js +21 -8
  19. package/dist/employee-endpoint.js +15 -1
  20. package/dist/employee-mcp.js +1 -1
  21. package/dist/employee-native.js +7 -1
  22. package/dist/employee-provider.d.ts +2 -0
  23. package/dist/employee-provider.js +46 -11
  24. package/dist/employee-relay.js +148 -1
  25. package/dist/employee-shell.d.ts +2 -0
  26. package/dist/employee-shell.js +22 -19
  27. package/dist/employee-startup.d.ts +18 -0
  28. package/dist/employee-startup.js +95 -0
  29. package/dist/employee-tools.js +2 -2
  30. package/dist/employee-workspace.d.ts +20 -4
  31. package/dist/employee-workspace.js +26 -5
  32. package/dist/index.d.ts +12 -3
  33. package/dist/index.js +223 -51
  34. package/dist/input.js +4 -1
  35. package/dist/live-steering.d.ts +46 -0
  36. package/dist/live-steering.js +45 -0
  37. package/dist/mapping.d.ts +4 -24
  38. package/dist/mapping.js +11 -65
  39. package/dist/model-catalog.d.ts +2 -0
  40. package/dist/model-catalog.js +5 -1
  41. package/dist/preflight-diagnostic.js +1 -1
  42. package/dist/presentation.js +1 -0
  43. package/dist/provider.d.ts +16 -0
  44. package/dist/provider.js +66 -33
  45. package/dist/rpc-namespace.js +16 -2
  46. package/dist/session-source.d.ts +3 -1
  47. package/dist/session-source.js +2 -1
  48. package/dist/startup-timing.d.ts +14 -0
  49. package/dist/startup-timing.js +34 -0
  50. package/dist/toolbridge-loop.d.ts +3 -2
  51. package/dist/toolbridge-loop.js +4 -2
  52. package/dist/toolbridge-table.d.ts +4 -3
  53. package/dist/toolbridge-table.js +14 -5
  54. package/dist/toolbridge.d.ts +1 -1
  55. package/dist/toolbridge.js +23 -4
  56. package/package.json +23 -16
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
+ }
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; }
@@ -17,6 +17,8 @@ export interface HostModel {
17
17
  defaultKnown: boolean;
18
18
  };
19
19
  source: unknown;
20
+ /** Host-sourced token capacity. Absent means unknown: X declares nothing and DSH reports it. */
21
+ contextWindow?: number;
20
22
  }
21
23
  export interface CatalogLease {
22
24
  readonly target: ModelCatalogTarget;
@@ -61,6 +61,10 @@ export function parseHostCatalog(input, provider, username) {
61
61
  reject('具体型号与发送模型值不一致');
62
62
  continue;
63
63
  }
64
+ if (model.contextWindow !== undefined && (!Number.isSafeInteger(model.contextWindow) || model.contextWindow < 1)) {
65
+ reject('上下文窗口不是正整数', 'MODEL_CONTEXT_WINDOW_INVALID');
66
+ continue;
67
+ }
64
68
  const r = model.reasoning;
65
69
  if (!Array.isArray(r.options) || typeof r.defaultKnown !== 'boolean' || (r.defaultValue !== null && !text(r.defaultValue)) || (!r.defaultKnown && r.defaultValue !== null)) {
66
70
  reject('推理档位或默认档位资料无效', 'MODEL_REASONING_INVALID');
@@ -161,5 +165,5 @@ export class ModelCatalog {
161
165
  }
162
166
  export function modelInfo(provider, model) {
163
167
  // Official rc.2 represents no reasoning levels by absence, and rejects an empty efforts array.
164
- return { provider, id: model.id, name: model.name, inputModalities: ['text', 'image'], ...(model.reasoning.options.length ? { reasoning: { efforts: model.reasoning.options.map(option => ({ id: ReasoningEffortId(option.value), name: option.name })), ...(model.reasoning.defaultKnown && model.reasoning.defaultValue !== null ? { defaultEffort: ReasoningEffortId(model.reasoning.defaultValue) } : {}) } } : {}), catalog: model };
168
+ return { provider, id: model.id, name: model.name, inputModalities: ['text', 'image'], ...(model.contextWindow === undefined ? {} : { context: { contextWindow: model.contextWindow } }), ...(model.reasoning.options.length ? { reasoning: { efforts: model.reasoning.options.map(option => ({ id: ReasoningEffortId(option.value), name: option.name })), ...(model.reasoning.defaultKnown && model.reasoning.defaultValue !== null ? { defaultEffort: ReasoningEffortId(model.reasoning.defaultValue) } : {}) } } : {}), catalog: model };
165
169
  }
@@ -37,7 +37,7 @@ export function createPreflightDiagnostics(options) {
37
37
  if (sessionId && session) {
38
38
  let workspace;
39
39
  try {
40
- workspace = officialEmployeeWorkspace(sessionId, options.ctx.get('workspaceRegistry'), session.header);
40
+ workspace = officialEmployeeWorkspace(sessionId, options.ctx.get('workspaceRegistry'), options.ctx.get('sessions'));
41
41
  }
42
42
  catch (error) {
43
43
  if (!(error instanceof NeedError && error.code === 'EMPLOYEE_WORKSPACE_UNAVAILABLE'))
@@ -54,6 +54,7 @@ export function employeeFailure(code, brand = 'codex', promptDispatched = true)
54
54
  PROMPT_CONTENT_UNSUPPORTED: '远端没有声明这类输入能力,本轮未发送;请使用受支持的内容或联系管理员。',
55
55
  ATTACHMENT_REQUIRED: '我需要官方附件组件读取这张图片,请联系管理员检查组件。',
56
56
  ATTACHMENT_INVALID: '图片附件没有返回匹配的已核验内容,本轮未发送;请重新添加图片或联系管理员。',
57
+ PURPOSE_UNSUPPORTED: '这段对话太长,需要先整理上下文,但远程模型不支持整理;这句话未发送,需要重新输入。请新建会话继续,或换回原来的模型',
57
58
  ACP_MESSAGE_TOO_LARGE: '本轮输入超过会话消息容量,未截断或发送;请联系管理员调整acpMaxMessageBytes。',
58
59
  };
59
60
  if (messages[code])
@@ -1,3 +1,5 @@
1
+ import type { StartupTiming } from './startup-timing.ts';
2
+ import type { ColdRound, ColdStore } from './cold-store.ts';
1
3
  import type { ToolBridge } from './toolbridge.ts';
2
4
  import { type SessionSource } from './host-workspace.ts';
3
5
  import type { CloseCause, CloseDiagnostics } from './close-diagnostics.ts';
@@ -27,6 +29,18 @@ export interface EmployeeExecution {
27
29
  validate(signal?: AbortSignal): Promise<void>;
28
30
  }
29
31
  export interface Runtime {
32
+ localDirectory?: {
33
+ path: string;
34
+ device: number;
35
+ inode: number;
36
+ };
37
+ cold?: {
38
+ id: string;
39
+ store: ColdStore;
40
+ bound: Promise<number>;
41
+ failBinding: (error: unknown) => void;
42
+ prepare: (nativeId: string | undefined, meta: NonNullable<ColdRound['meta']>) => Promise<void>;
43
+ };
30
44
  identity: string;
31
45
  cwd: string;
32
46
  hostWorkspace?: Readonly<HostWorkspacePresentation>;
@@ -67,6 +81,7 @@ export interface Runtime {
67
81
  closeDiagnostics?: CloseDiagnostics;
68
82
  }
69
83
  export interface RuntimeRequest extends Invocation {
84
+ startupTiming?: StartupTiming;
70
85
  toolBridge?: ToolBridge;
71
86
  workspaceSource?: SessionSource;
72
87
  hostSource?: Extract<SessionSource, {
@@ -98,6 +113,7 @@ export interface RuntimeRequest extends Invocation {
98
113
  }
99
114
  export type RuntimeProvider = ((request: RuntimeRequest) => Promise<Runtime>) & {
100
115
  preflight?: (request: RuntimeRequest) => Promise<void>;
116
+ releasePreparation?: (request: RuntimeRequest) => void;
101
117
  };
102
118
  export interface ConnectTarget {
103
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,7 +180,13 @@ 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';
172
- const { target, connection } = await (async () => {
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
+ }
189
+ const loginReady = async () => {
173
190
  request.localAdmissionCheck?.();
174
191
  const before = api.getConnectionState();
175
192
  const target = await ensureReady(api, agent.loginProvider, request.signal);
@@ -179,7 +196,8 @@ export function connectProvider(get, options = {}) {
179
196
  throw new NeedError('CONNECTION_LOST', '远程主机连接组件已更换', '当前员工连接');
180
197
  const connection = await waitForLogin(api, agent.loginProvider, before, get, request.signal);
181
198
  return { target, connection };
182
- })();
199
+ };
200
+ const { target, connection } = await (request.startupTiming?.run('login-readiness', loginReady) ?? loginReady());
183
201
  if (request.workspaceSource?.source !== 'host' && request.identity && request.identity !== identity(target))
184
202
  throw new NeedError('SESSION_CONTEXT_MISMATCH', '员工主机与原会话不一致,请新建会话', '原员工主机');
185
203
  request.localAdmissionCheck?.();
@@ -190,8 +208,13 @@ export function connectProvider(get, options = {}) {
190
208
  throw connectNeedError(locations.need);
191
209
  if (!host)
192
210
  await options.local?.admit?.(request, api, connection, target);
211
+ if (preparation) {
212
+ await preparation.ready;
213
+ preparation.confirm(target, connection);
214
+ }
193
215
  }
194
216
  catch (error) {
217
+ preparation?.cancel();
195
218
  admissions.delete(request);
196
219
  const record = request.recordEarlyFailure;
197
220
  request.recordEarlyFailure = undefined;
@@ -206,41 +229,51 @@ export function connectProvider(get, options = {}) {
206
229
  const admitted = admissions.get(request);
207
230
  admissions.delete(request);
208
231
  const { api, target, connection } = admitted;
209
- if (!request.sessionId)
210
- throw new NeedError('PROJECT_BINDING_REQUIRED', '我需要当前会话和已选择的工作区,请使用原生工作区入口', 'DSH会话与原生工作区');
211
- const host = request.workspaceSource?.source === 'host';
212
- if (!host && options.employee) {
213
- employee ??= import("./employee-provider.js").then(module => module.createEmployeeProvider(get, options, agent));
214
- const local = await (await employee)({ api, target, connection, request });
215
- if (local) {
216
- local.loginRequired = () => offerLogin(api, request, get, agent);
217
- 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;
218
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;
219
271
  }
220
- if (!host && agent.loginProvider === 'claude' && options.local) {
221
- const runtime = await options.local(request, api, connection, target);
222
- if (runtime)
223
- return runtime;
272
+ finally {
273
+ preparation?.cancel();
224
274
  }
225
- // A local source must have been handled by its employee provider above.
226
- // Host execution requires an explicit host location; no name-based resolver.
227
- if (!host)
228
- throw new NeedError('WORKSPACE_LOCATION_REQUIRED', '请选择文件夹来源;改变来源后请新建会话。', '已选择的本机或主机文件夹');
229
- const resolved = await resolveHostWorkspace(api, request, agent.loginProvider);
230
- const project = resolved.project;
231
- const details = await options.details?.(request, api, connection, target);
232
- if (!options.open)
233
- throw new NeedError('RUNTIME_REQUIRED', '我需要主机运行适配器', '主机broker适配');
234
- const runtime = await options.open(resolved.target, project, { ...request, agent, bindingId: undefined, workspaceId: undefined, bindingRevision: undefined, detailChannel: details });
235
- runtime.hostSource = Object.freeze({ ...request.workspaceSource });
236
- runtime.hostWorkspace = Object.freeze({ cwd: project.path });
237
- // The transport can outlive a turn; presentation belongs only to this invocation.
238
- runtime.details = details ?? runtime.details;
239
- runtime.binding = undefined;
240
- runtime.connection = { ...connection };
241
- runtime.loginRequired = () => offerLogin(api, request, get, agent);
242
- return runtime;
243
275
  };
244
276
  resolve.preflight = preflight;
277
+ resolve.releasePreparation = releasePreparation;
245
278
  return resolve;
246
279
  }
@@ -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 {
@@ -15,4 +15,6 @@ export declare const sessionSourceSpec: {
15
15
  };
16
16
  };
17
17
  /** Official domain metadata, keyed by native session ID. No L files, local path probes or host identity hashes. */
18
- export declare function createSessionSources(ctx: Context, getApi: () => ConnectApi | undefined): (request: RuntimeRequest, api: ConnectApi) => Promise<SessionSource | undefined>;
18
+ export declare function createSessionSources(ctx: Context, getApi: () => ConnectApi | undefined): ((request: RuntimeRequest, api: ConnectApi) => Promise<SessionSource | undefined>) & {
19
+ read: (sessionId: string) => Promise<SessionSource | undefined>;
20
+ };
@@ -79,7 +79,7 @@ export function createSessionSources(ctx, getApi) {
79
79
  return;
80
80
  void save(session, api).catch(() => ctx.logger('remote-agent').warn('会话文件来源暂未保存;发送时将重试'));
81
81
  });
82
- return async (request, api) => {
82
+ const resolve = async (request, api) => {
83
83
  if (!request.sessionId || api.getContractInfo?.().workspaceLocations !== 1 && !request.hostSource)
84
84
  return;
85
85
  const session = ctx.get('sessions')?.get(SessionId(request.sessionId));
@@ -87,4 +87,5 @@ export function createSessionSources(ctx, getApi) {
87
87
  throw storageNeed();
88
88
  return save(session, api, request);
89
89
  };
90
+ return Object.assign(resolve, { read: async (sessionId) => { const source = (await open()).table('sessions').get(sessionId); return source ? Object.freeze({ ...source }) : undefined; } });
90
91
  }
@@ -0,0 +1,14 @@
1
+ import type { DetailObservation } from './conversation-details.ts';
2
+ /** 仅记录单调时钟和固定阶段,不收集命令、路径、正文或授权资料。 */
3
+ export declare const STARTUP_STAGES: readonly ["startup", "source-admission", "workspace-context", "login-readiness", "input-prepare", "runtime-resolve", "endpoint-prepare", "native-metadata", "broker-open", "bridge-open", "acp-initialize", "acp-session-new", "acp-session-load", "acp-session-resume", "model-confirm", "permission-confirm", "prompt-dispatch", "prompt-delivery"];
4
+ export type StartupStage = typeof STARTUP_STAGES[number];
5
+ export declare class StartupTiming {
6
+ private readonly origin;
7
+ private pending;
8
+ private sink?;
9
+ constructor(sink?: (event: DetailObservation) => void);
10
+ bind(sink: (event: DetailObservation) => void): void;
11
+ private send;
12
+ start(stage: StartupStage): (outcome?: 'completed' | 'failed') => void;
13
+ run<T>(stage: StartupStage, operation: () => Promise<T>): Promise<T>;
14
+ }
@@ -0,0 +1,34 @@
1
+ /** 仅记录单调时钟和固定阶段,不收集命令、路径、正文或授权资料。 */
2
+ export const STARTUP_STAGES = ['startup', 'source-admission', 'workspace-context', 'login-readiness', 'input-prepare', 'runtime-resolve', 'endpoint-prepare', 'native-metadata', 'broker-open', 'bridge-open', 'acp-initialize', 'acp-session-new', 'acp-session-load', 'acp-session-resume', 'model-confirm', 'permission-confirm', 'prompt-dispatch', 'prompt-delivery'];
3
+ export class StartupTiming {
4
+ origin = performance.now();
5
+ pending = [];
6
+ sink;
7
+ constructor(sink) { this.sink = sink; }
8
+ bind(sink) { this.sink = sink; for (const event of this.pending.splice(0))
9
+ this.send(event); }
10
+ send(event) { if (!this.sink) {
11
+ this.pending.push(event);
12
+ return;
13
+ } try {
14
+ this.sink(event);
15
+ }
16
+ catch {
17
+ console.warn('[remote-agent] 启动计时未保存');
18
+ } }
19
+ start(stage) {
20
+ const startMs = performance.now() - this.origin;
21
+ let ended = false;
22
+ return (outcome = 'completed') => { if (ended)
23
+ return; ended = true; const endMs = performance.now() - this.origin; this.send({ kind: 'session', severity: 'info', code: 'STARTUP_TIMING', summary: '开工前阶段计时', payload: { clock: 'client-monotonic', stage, startMs, endMs, durationMs: endMs - startMs, outcome } }); };
24
+ }
25
+ async run(stage, operation) { const end = this.start(stage); try {
26
+ const value = await operation();
27
+ end();
28
+ return value;
29
+ }
30
+ catch (error) {
31
+ end('failed');
32
+ throw error;
33
+ } }
34
+ }