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

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 (53) hide show
  1. package/README.md +32 -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.js +46 -11
  23. package/dist/employee-relay.js +148 -1
  24. package/dist/employee-shell.d.ts +2 -0
  25. package/dist/employee-shell.js +22 -19
  26. package/dist/employee-tools.js +2 -2
  27. package/dist/employee-workspace.d.ts +20 -4
  28. package/dist/employee-workspace.js +26 -5
  29. package/dist/index.d.ts +12 -3
  30. package/dist/index.js +221 -51
  31. package/dist/input.js +4 -1
  32. package/dist/live-steering.d.ts +46 -0
  33. package/dist/live-steering.js +45 -0
  34. package/dist/mapping.d.ts +4 -24
  35. package/dist/mapping.js +11 -65
  36. package/dist/model-catalog.d.ts +2 -0
  37. package/dist/model-catalog.js +5 -1
  38. package/dist/preflight-diagnostic.js +1 -1
  39. package/dist/presentation.js +1 -0
  40. package/dist/provider.d.ts +15 -0
  41. package/dist/provider.js +3 -2
  42. package/dist/rpc-namespace.js +16 -2
  43. package/dist/session-source.d.ts +3 -1
  44. package/dist/session-source.js +2 -1
  45. package/dist/startup-timing.d.ts +14 -0
  46. package/dist/startup-timing.js +34 -0
  47. package/dist/toolbridge-loop.d.ts +3 -2
  48. package/dist/toolbridge-loop.js +4 -2
  49. package/dist/toolbridge-table.d.ts +4 -3
  50. package/dist/toolbridge-table.js +14 -5
  51. package/dist/toolbridge.d.ts +1 -1
  52. package/dist/toolbridge.js +4 -4
  53. package/package.json +23 -16
@@ -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, {
package/dist/provider.js CHANGED
@@ -169,7 +169,7 @@ export function connectProvider(get, options = {}) {
169
169
  request.localContext = await module.inspectEmployeeWorkspace(get, options.employee, agent, api, request);
170
170
  }
171
171
  sourceStage = 'login-readiness';
172
- const { target, connection } = await (async () => {
172
+ const loginReady = async () => {
173
173
  request.localAdmissionCheck?.();
174
174
  const before = api.getConnectionState();
175
175
  const target = await ensureReady(api, agent.loginProvider, request.signal);
@@ -179,7 +179,8 @@ export function connectProvider(get, options = {}) {
179
179
  throw new NeedError('CONNECTION_LOST', '远程主机连接组件已更换', '当前员工连接');
180
180
  const connection = await waitForLogin(api, agent.loginProvider, before, get, request.signal);
181
181
  return { target, connection };
182
- })();
182
+ };
183
+ const { target, connection } = await (request.startupTiming?.run('login-readiness', loginReady) ?? loginReady());
183
184
  if (request.workspaceSource?.source !== 'host' && request.identity && request.identity !== identity(target))
184
185
  throw new NeedError('SESSION_CONTEXT_MISMATCH', '员工主机与原会话不一致,请新建会话', '原员工主机');
185
186
  request.localAdmissionCheck?.();
@@ -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
+ }
@@ -1,4 +1,4 @@
1
- import { type GenerateOptions, type StreamChunk } from '@deepseek-ai/dsh-llm';
1
+ import { type GenerateOptions, type StreamChunk, type UserMessage } from '@deepseek-ai/dsh-llm';
2
2
  import { ToolBridge } from './toolbridge.ts';
3
3
  import type { ImageReader } from './input.ts';
4
4
  type Producer = (options: GenerateOptions, bridge: ToolBridge) => AsyncGenerator<StreamChunk>;
@@ -6,9 +6,10 @@ type Producer = (options: GenerateOptions, bridge: ToolBridge) => AsyncGenerator
6
6
  export declare class ToolBridgeLoop {
7
7
  private readImage?;
8
8
  private stopped?;
9
+ private isInjected?;
9
10
  private runs;
10
11
  private concluding;
11
- constructor(readImage?: ImageReader | undefined, stopped?: ((sessionId: string, notice: string) => void) | undefined);
12
+ constructor(readImage?: ImageReader | undefined, stopped?: ((sessionId: string, notice: string) => void) | undefined, isInjected?: ((sessionId: string, message: UserMessage) => boolean) | undefined);
12
13
  private launch;
13
14
  conclude(id: string, messages: GenerateOptions['messages']): Promise<void>;
14
15
  active(id: string): boolean;
@@ -44,11 +44,13 @@ class Projection {
44
44
  export class ToolBridgeLoop {
45
45
  readImage;
46
46
  stopped;
47
+ isInjected;
47
48
  runs = new Map();
48
49
  concluding = new Map();
49
- constructor(readImage, stopped) {
50
+ constructor(readImage, stopped, isInjected) {
50
51
  this.readImage = readImage;
51
52
  this.stopped = stopped;
53
+ this.isInjected = isInjected;
52
54
  }
53
55
  launch(options, producer) {
54
56
  const controller = new AbortController(), bridge = new ToolBridge(options, this.readImage);
@@ -181,7 +183,7 @@ export class ToolBridgeLoop {
181
183
  throw new NeedError('ABORTED', '本轮已取消,工具结果没有重放。', '确认主机取消状态');
182
184
  if (run.latest !== options) {
183
185
  for (const m of options.messages)
184
- if (m.role === 'user' && 'source' in m && m.source?.kind === 'user' && 'id' in m && typeof m.id === 'string' && !run.seen.has(m.id)) {
186
+ if (m.role === 'user' && 'source' in m && m.source?.kind === 'user' && 'id' in m && typeof m.id === 'string' && !run.seen.has(m.id) && !this.isInjected?.(key, m)) {
185
187
  run.seen.add(m.id);
186
188
  run.deferred.push(m);
187
189
  }
@@ -1,10 +1,11 @@
1
- import type { ToolSchema } from '@deepseek-ai/dsh-llm';
1
+ import type { ToolSchema, GenerateOptions } from '@deepseek-ai/dsh-llm';
2
2
  import type { Tool } from '@modelcontextprotocol/sdk/types.js';
3
3
  /** Fixed official tool names; no description heuristics or plugin-name branches. */
4
- export declare const TOOLBRIDGE_EXCLUDED: readonly ["read", "write", "edit", "read_image", "glob", "grep", "bash", "pwsh", "str_replace_editor", "job_output", "job_list", "job_kill", "load_workspace_dependencies", "terminal_open", "terminal_send", "terminal_read", "terminal_signal", "terminal_close", "terminal_list", "subagent", "list_subagent_models", "send_message", "interrupt_agent", "spawn_teammate", "list_agents", "wait_agent", "team_task_create", "team_task_list", "team_task_get", "team_task_update", "run_code"];
4
+ export declare const TOOLBRIDGE_EXCLUDED: readonly ["read", "write", "edit", "read_image", "glob", "grep", "bash", "pwsh", "str_replace_editor", "terminal_open", "terminal_send", "terminal_read", "terminal_signal", "terminal_close", "terminal_list", "run_code"];
5
5
  export interface BridgeTool {
6
6
  alias: string;
7
7
  schema: ToolSchema;
8
8
  wire: Tool;
9
9
  }
10
- export declare function bridgeTable(tools?: readonly ToolSchema[]): ReadonlyMap<string, BridgeTool>;
10
+ export declare function dshSkillCatalog(messages?: GenerateOptions['messages']): readonly string[] | undefined;
11
+ export declare function bridgeTable(tools?: readonly ToolSchema[], catalog?: readonly string[]): ReadonlyMap<string, BridgeTool>;
@@ -3,13 +3,21 @@ import { NeedError } from "./remote.js";
3
3
  /** Fixed official tool names; no description heuristics or plugin-name branches. */
4
4
  export const TOOLBRIDGE_EXCLUDED = Object.freeze([
5
5
  'read', 'write', 'edit', 'read_image', 'glob', 'grep', 'bash', 'pwsh', 'str_replace_editor',
6
- 'job_output', 'job_list', 'job_kill', 'load_workspace_dependencies',
7
6
  'terminal_open', 'terminal_send', 'terminal_read', 'terminal_signal', 'terminal_close', 'terminal_list',
8
- 'subagent', 'list_subagent_models', 'send_message', 'interrupt_agent', 'spawn_teammate', 'list_agents', 'wait_agent',
9
- 'team_task_create', 'team_task_list', 'team_task_get', 'team_task_update', 'run_code',
7
+ 'run_code',
10
8
  ]);
11
9
  const excluded = new Set(TOOLBRIDGE_EXCLUDED);
12
- export function bridgeTable(tools = []) {
10
+ export function dshSkillCatalog(messages = []) {
11
+ for (const message of messages.toReversed()) {
12
+ const source = message.source;
13
+ if (message.role !== 'user' || source?.kind !== 'skill-catalog' || source.form !== 'catalog' || !Array.isArray(source.entries))
14
+ continue;
15
+ if (!source.entries.every(entry => entry && typeof entry.name === 'string' && typeof entry.description === 'string'))
16
+ continue;
17
+ return source.entries.map(entry => entry.name);
18
+ }
19
+ }
20
+ export function bridgeTable(tools = [], catalog) {
13
21
  const table = new Map(), names = new Set();
14
22
  for (const tool of tools) {
15
23
  if (excluded.has(tool.name))
@@ -21,7 +29,8 @@ export function bridgeTable(tools = []) {
21
29
  if (table.has(alias))
22
30
  throw new NeedError('TOOLBRIDGE_NAME_COLLISION', '工具桥名称冲突,未执行。', '唯一工具桥名称');
23
31
  const schema = structuredClone(tool);
24
- table.set(alias, { alias, schema, wire: { name: alias, description: 'DSH工具 ' + schema.name + ':' + schema.description, inputSchema: structuredClone(schema.parameters) } });
32
+ const skill = schema.name === 'skill' ? ' 这是DSH技能加载器,名字取自DSH的<available_skills>目录;主机Claude/Codex的原生技能按各自原生技能指令加载。' + (catalog === undefined ? '请以当前DSH技能目录为准。' : '本次DSH公布的目录快照:' + JSON.stringify(catalog) + ';实际可用性由DSH调用时确认。') + '技能资源按返回的<skill_resources>基址读取。' : '';
33
+ table.set(alias, { alias, schema, wire: { name: alias, description: 'DSH工具 ' + schema.name + ':' + schema.description + skill, inputSchema: structuredClone(schema.parameters) } });
25
34
  }
26
35
  return table;
27
36
  }
@@ -5,7 +5,7 @@ import { type BridgeTool } from './toolbridge-table.ts';
5
5
  import type { ImageReader } from './input.ts';
6
6
  import type { DetailObservation } from './conversation-details.ts';
7
7
  export declare const TOOLBRIDGE_TIMEOUT_SECONDS = 1800;
8
- export declare const TOOLBRIDGE_NOTICE = "\u542B\u5DE5\u5177\u6865\uFF1A\u672C\u673A\u6587\u4EF6\u5939\u7684\u6269\u5C55\u5DE5\u5177\u7531DSH\u6267\u884C\u5E76\u6309\u5F53\u524D\u6743\u9650\u5BA1\u6279\uFF1B\u6587\u4EF6\u548C\u547D\u4EE4\u4FDD\u6301\u539F\u6267\u884C\u65B9\u5F0F\u3002\u5DE5\u5177\u8868\u5728\u65B0\u4E00\u8F6E\u4E3B\u673A\u8FDE\u63A5\u65F6\u66F4\u65B0\u3002";
8
+ export declare const TOOLBRIDGE_NOTICE = "\u542B\u5DE5\u5177\u6865\uFF1A\u672C\u673A\u6587\u4EF6\u5939\u7684\u6269\u5C55\u5DE5\u5177\uFF08\u542BDSH\u5B50\u4EE3\u7406\u3001workflow\u548C\u540E\u53F0\u4EFB\u52A1\u5DE5\u5177\uFF09\u7531DSH\u6267\u884C\u5E76\u6309\u5F53\u524D\u6743\u9650\u5BA1\u6279\uFF1B\u6587\u4EF6\u548C\u547D\u4EE4\u4FDD\u6301\u539F\u6267\u884C\u65B9\u5F0F\u3002\u5DE5\u5177\u8868\u5728\u65B0\u4E00\u8F6E\u4E3B\u673A\u8FDE\u63A5\u65F6\u66F4\u65B0\u3002";
9
9
  export declare const TOOLBRIDGE_ENDED = "\u4E3B\u673A\u5DF2\u7ED3\u675F\u8FD9\u6B21\u5DE5\u5177\u7B49\u5F85\uFF1B\u672C\u8F6E\u5DF2\u505C\u6B62\uFF0C\u8FDF\u5230\u7ED3\u679C\u4E0D\u4F1A\u4EA4\u56DE\uFF0C\u4E5F\u4E0D\u4F1A\u91CD\u65B0\u6267\u884C\u3002\u8BF7\u6838\u5BF9\u5DF2\u53D1\u751F\u7684\u64CD\u4F5C\u3002";
10
10
  interface Pending {
11
11
  block: ToolCallBlock;