@gaoding/cli 1.9.0 → 1.9.1

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 (45) hide show
  1. package/contracts/operations/agent.send/output.schema.json +1 -1
  2. package/dist/bin/gd-cli.js +31 -24
  3. package/dist/bin/insmind-cli.js +31 -24
  4. package/dist/bin/task-worker.js +4 -1
  5. package/dist/src/analytics/device.js +2 -2
  6. package/dist/src/bootstrap/create-cli.js +7 -0
  7. package/dist/src/bootstrap/create-runtime.js +3 -7
  8. package/dist/src/bootstrap/run-task-worker.js +5 -1
  9. package/dist/src/bootstrap/validators.js +11 -4
  10. package/dist/src/cli/dam-commands.js +3 -3
  11. package/dist/src/cli/errors.js +60 -12
  12. package/dist/src/cli/observed-errors.js +3 -1
  13. package/dist/src/features/agent/creative-agent-adapter.js +37 -11
  14. package/dist/src/features/agent/creative-protocol.js +9 -5
  15. package/dist/src/features/agent/creative-stream.js +54 -6
  16. package/dist/src/features/agent/result-reader.js +3 -1
  17. package/dist/src/features/auth/credential-store.js +6 -10
  18. package/dist/src/features/auth/sso-service.js +22 -6
  19. package/dist/src/features/auth/state.js +6 -0
  20. package/dist/src/features/auth/use-cases.js +90 -32
  21. package/dist/src/features/dam/asset-projection.js +10 -1
  22. package/dist/src/features/dam/dam-api-adapter.js +30 -15
  23. package/dist/src/features/dam/input.js +23 -0
  24. package/dist/src/features/dam/use-cases.js +32 -22
  25. package/dist/src/features/task/store.js +5 -5
  26. package/dist/src/features/task/task-background.js +67 -19
  27. package/dist/src/features/task/use-cases.js +34 -6
  28. package/dist/src/features/tool/canvas-media.js +82 -27
  29. package/dist/src/features/tool/dynamic-schema.js +8 -4
  30. package/dist/src/features/tool/matting-billing.js +38 -26
  31. package/dist/src/features/tool/tool-api-adapter.js +17 -14
  32. package/dist/src/platform/file-lock.js +58 -15
  33. package/dist/src/platform/input-uri.js +105 -0
  34. package/dist/src/platform/local-json-file.js +7 -4
  35. package/dist/src/platform/remote-error-evidence.js +23 -1
  36. package/dist/src/platform/safe-upload-file.js +18 -4
  37. package/dist/src/platform/schema-issues.js +18 -0
  38. package/dist/src/platform/signed-http-transport.js +77 -16
  39. package/dist/src/platform/text-output.js +55 -13
  40. package/dist/src/telemetry/failure-summary.js +53 -2
  41. package/dist/src/telemetry/host-diagnostics.js +95 -0
  42. package/dist/src/telemetry/invocation.js +24 -3
  43. package/dist/src/telemetry/process-errors.js +2 -1
  44. package/dist/src/telemetry/sls-sink.js +66 -18
  45. package/package.json +4 -4
@@ -1,4 +1,5 @@
1
1
  import { constants, createPublicKey, publicEncrypt, randomBytes, verify } from "node:crypto";
2
+ import { withResponseDiagnostics } from "../../platform/signed-http-transport.js";
2
3
  import { RemoteProtocolError } from "../../platform/remote-protocol.js";
3
4
  import { remoteErrorEvidence } from "../../platform/remote-error-evidence.js";
4
5
  import { record } from "./canvas-results.js";
@@ -25,19 +26,21 @@ export function encryptMattingParameters(text, key = serviceKey) {
25
26
  export function createMattingRights(dependencies) {
26
27
  const { transport } = dependencies;
27
28
  return async function rights(path, parameters, context) {
28
- const code = `0.${randomBytes(12).readBigUInt64BE().toString()}`;
29
- const plaintext = `gaoding?key=${randomBytes(18).toString("base64url")}&timestamp=${Date.now()}&verify_code=${code}&${parameters}`;
30
- const result = await transport.postJson({ path, body: { data: encryptMattingParameters(plaintext, dependencies.key ?? serviceKey) },
31
- ...context.access, signal: context.signal });
32
- if (!record(result))
33
- throw new RemoteProtocolError();
34
- if (result.code !== undefined && result.code !== 0 && result.code !== "0")
35
- throw new ToolTaskFailedError(remoteErrorEvidence(result));
36
- if (typeof result.export_permit !== "string" || !verify("RSA-SHA256", Buffer.from(code), dependencies.key ?? serviceKey, Buffer.from(result.export_permit, "base64"))
37
- || typeof result.used_count !== "number" || !Number.isFinite(result.used_count) || result.used_count < 0) {
38
- throw new RemoteProtocolError({}, undefined, "MATTING_BILLING_VERIFICATION_FAILED");
39
- }
40
- return result;
29
+ return withResponseDiagnostics(async (onResponse) => {
30
+ const code = `0.${randomBytes(12).readBigUInt64BE().toString()}`;
31
+ const plaintext = `gaoding?key=${randomBytes(18).toString("base64url")}&timestamp=${Date.now()}&verify_code=${code}&${parameters}`;
32
+ const result = await transport.postJson({ path, body: { data: encryptMattingParameters(plaintext, dependencies.key ?? serviceKey) },
33
+ ...context.access, signal: context.signal, onResponse });
34
+ if (!record(result))
35
+ throw new RemoteProtocolError();
36
+ if (result.code !== undefined && result.code !== 0 && result.code !== "0")
37
+ throw new ToolTaskFailedError(remoteErrorEvidence(result));
38
+ if (typeof result.export_permit !== "string" || !verify("RSA-SHA256", Buffer.from(code), dependencies.key ?? serviceKey, Buffer.from(result.export_permit, "base64"))
39
+ || typeof result.used_count !== "number" || !Number.isFinite(result.used_count) || result.used_count < 0) {
40
+ throw new RemoteProtocolError({}, undefined, "MATTING_BILLING_VERIFICATION_FAILED");
41
+ }
42
+ return result;
43
+ });
41
44
  };
42
45
  }
43
46
  export function createStandardMatting(dependencies) {
@@ -49,19 +52,28 @@ export function createStandardMatting(dependencies) {
49
52
  if (quote.need_deduct !== undefined && typeof quote.need_deduct !== "boolean")
50
53
  throw new RemoteProtocolError();
51
54
  if (quote.need_deduct === true || quote.need_deduct === undefined && Number(quote.used_count) > 0) {
52
- const balances = await transport.getJson({ path: "/trade/rights-overview", query: { goods_type_enums: "GAODOU" }, ...context.access, signal: context.signal });
53
- if (!Array.isArray(balances))
54
- throw new RemoteProtocolError();
55
- const item = balances.find(item => record(item) && item.goods_type_enum === "GAODOU" && item.identifier === "GAODOU");
56
- if (!record(item))
57
- throw new RemoteProtocolError();
58
- const value = (raw) => { if ((typeof raw !== "number" && typeof raw !== "string") || raw === "" || !Number.isFinite(Number(raw)))
59
- throw new RemoteProtocolError(); return Number(raw); };
60
- let available = value(item.total) - value(item.used) - value(item.wait);
61
- if (item.member_period_limit !== undefined && item.member_period_limit !== null)
62
- available = Math.min(available, value(item.member_period_limit) - value(item.member_period_used ?? 0));
63
- if (available < Number(quote.used_count))
64
- throw new ToolInsufficientCreditsError();
55
+ await withResponseDiagnostics(async (onResponse) => {
56
+ const balances = await transport.getJson({ path: "/trade/rights-overview", query: { goods_type_enums: "GAODOU" }, ...context.access, signal: context.signal, onResponse });
57
+ if (!Array.isArray(balances))
58
+ throw new RemoteProtocolError();
59
+ const item = balances.find(item => record(item) && item.goods_type_enum === "GAODOU" && item.identifier === "GAODOU");
60
+ if (!record(item))
61
+ throw new RemoteProtocolError();
62
+ const value = (raw) => { if ((typeof raw !== "number" && typeof raw !== "string") || raw === "" || !Number.isFinite(Number(raw)))
63
+ throw new RemoteProtocolError(); return Number(raw); };
64
+ const total = value(item.total), used = value(item.used), pending = value(item.wait);
65
+ const accountAvailable = total - used - pending;
66
+ const memberLimit = item.member_period_limit === undefined || item.member_period_limit === null ? undefined : value(item.member_period_limit);
67
+ const memberUsed = memberLimit === undefined ? undefined : value(item.member_period_used ?? 0);
68
+ const available = memberLimit === undefined ? accountAvailable : Math.min(accountAvailable, memberLimit - memberUsed);
69
+ if (available < Number(quote.used_count))
70
+ throw Object.assign(new ToolInsufficientCreditsError(), {
71
+ diagnosticSummary: { quotaDecisionSource: "cli_precheck", quotaUnit: "gaodou",
72
+ quotaLimitScope: memberLimit !== undefined && memberLimit - memberUsed < accountAvailable ? "member_period" : "account",
73
+ quotaTotal: total, quotaUsed: used, quotaPending: pending, quotaAvailable: available, quotaRequired: Number(quote.used_count),
74
+ ...(memberLimit === undefined ? {} : { quotaMemberLimit: memberLimit, quotaMemberUsed: memberUsed }) }
75
+ });
76
+ });
65
77
  }
66
78
  const repositories = await recordTransport.getJson({ path: "/tb-dam/repositories", ...context.access, signal: context.signal });
67
79
  if (!Array.isArray(repositories))
@@ -1,7 +1,7 @@
1
1
  import { isInterruption } from "../../platform/interruption.js";
2
2
  import { randomInt } from "node:crypto";
3
3
  import { setTimeout as delay } from "node:timers/promises";
4
- import { RemoteRequestError } from "../../platform/signed-http-transport.js";
4
+ import { RemoteRequestError, withResponseDiagnostics } from "../../platform/signed-http-transport.js";
5
5
  import { remoteErrorEvidence } from "../../platform/remote-error-evidence.js";
6
6
  import { RemoteProtocolError } from "../../platform/remote-protocol.js";
7
7
  const MAX_JAVA_LONG = 9223372036854775807n;
@@ -150,18 +150,21 @@ export class ToolTaskCanceledError extends Error {
150
150
  constructor() { super("用户已取消生成任务。"); this.name = "ToolTaskCanceledError"; }
151
151
  }
152
152
  export async function queryToolResult(transport, request) {
153
+ let difyTaskId;
153
154
  try {
154
- return pollResult(await safePost(transport, {
155
+ return await safePost(transport, {
155
156
  credential: request.credential,
156
157
  ...(request.organizationId === undefined ? {} : { organizationId: request.organizationId }),
157
158
  signal: request.signal,
158
159
  path: "/gdesign/tool/v1/dify/process/batch",
159
160
  body: { task_ids: [request.taskId] }
160
- }), request.taskId, request.onDifyTaskId, request.normalize);
161
+ }, value => pollResult(value, request.taskId, id => { difyTaskId = id; request.onDifyTaskId?.(id); }, request.normalize));
161
162
  }
162
163
  catch (error) {
163
164
  if (isInterruption(error, request.signal) || error instanceof ToolTaskCanceledError)
164
165
  throw error;
166
+ if (error instanceof ToolTaskFailedError)
167
+ return failedPoll(error, difyTaskId);
165
168
  const evidence = error instanceof RemoteRequestError || error instanceof RemoteProtocolError
166
169
  ? { ...(error.remoteCode === undefined ? {} : { remoteCode: error.remoteCode }),
167
170
  ...(error.remoteBody === undefined ? {} : { remoteBody: error.remoteBody }) } : {};
@@ -232,15 +235,15 @@ function pollResult(value, taskId, onDifyTaskId, normalize = normalizeToolConten
232
235
  if (typeof difyTaskId === "string")
233
236
  onDifyTaskId?.(difyTaskId);
234
237
  if (Object.prototype.hasOwnProperty.call(inner, "error")) {
235
- return isJsonRpcError(inner)
236
- ? failedPoll(new ToolTaskFailedError(remoteErrorEvidence(inner)), difyTaskId)
237
- : failedPoll(new RemoteProtocolError(remoteErrorEvidence(inner)), difyTaskId);
238
+ if (isJsonRpcError(inner))
239
+ throw new ToolTaskFailedError(remoteErrorEvidence(inner));
240
+ throw new RemoteProtocolError(remoteErrorEvidence(inner));
238
241
  }
239
242
  if (!isRecord(inner.result)) {
240
243
  return failedPoll(new RemoteProtocolError(remoteErrorEvidence(inner)), difyTaskId);
241
244
  }
242
245
  if (inner.result.isError === true) {
243
- return failedPoll(new ToolTaskFailedError(remoteErrorEvidence(inner)), difyTaskId);
246
+ throw new ToolTaskFailedError(remoteErrorEvidence(inner));
244
247
  }
245
248
  if (inner.result.isError !== false) {
246
249
  return failedPoll(new RemoteProtocolError(remoteErrorEvidence(inner)), difyTaskId);
@@ -274,14 +277,14 @@ function pollResult(value, taskId, onDifyTaskId, normalize = normalizeToolConten
274
277
  throw error;
275
278
  }
276
279
  }
277
- async function safePost(transport, request) {
280
+ async function safePost(transport, request, interpret) {
278
281
  try {
279
- return await transport.postJson(request);
282
+ return await withResponseDiagnostics(async (onResponse) => interpret(await transport.postJson({ ...request, onResponse })));
280
283
  }
281
284
  catch (error) {
282
285
  if (isInterruption(error, request.signal))
283
286
  throw request.signal.reason;
284
- if (error instanceof RemoteRequestError || error instanceof RemoteProtocolError)
287
+ if (error instanceof RemoteRequestError || error instanceof RemoteProtocolError || error instanceof ToolTaskFailedError || error instanceof ToolTaskCanceledError)
285
288
  throw error;
286
289
  throw new RemoteRequestError(undefined, false, {}, error);
287
290
  }
@@ -311,7 +314,7 @@ export function createToolApiAdapter(dependencies) {
311
314
  const resolved = invocation.kind === "direct"
312
315
  ? { name: invocation.name, arguments: invocation.arguments }
313
316
  : await dependencies.telemetry.stage("intent", async () => {
314
- const intent = parseIntent(await safePost(dependencies.transport, {
317
+ const intent = await safePost(dependencies.transport, {
315
318
  path: "/ai-agent/v1/tool-intent",
316
319
  body: {
317
320
  prompt: invocation.prompt,
@@ -321,7 +324,7 @@ export function createToolApiAdapter(dependencies) {
321
324
  credential: access.credential,
322
325
  organizationId: access.organizationId,
323
326
  signal
324
- }));
327
+ }, parseIntent);
325
328
  return {
326
329
  ...intent,
327
330
  arguments: withoutEmptyOptionalMedia(intent.arguments, invocation.optionalMediaParameters)
@@ -331,7 +334,7 @@ export function createToolApiAdapter(dependencies) {
331
334
  await observe?.({ submissionStarted: true });
332
335
  const taskId = await dependencies.telemetry.stage("submit", async () => {
333
336
  dependencies.telemetry.annotate({ content_id: managedContentId });
334
- return submittedTask(await safePost(dependencies.transport, {
337
+ return safePost(dependencies.transport, {
335
338
  path: "/gdesign/tool/v1/dify/call_async",
336
339
  ...(observe ? { onDispatch: (dispatchedAt) => observe({ dispatchedAt }) } : {}),
337
340
  body: {
@@ -346,7 +349,7 @@ export function createToolApiAdapter(dependencies) {
346
349
  credential: access.credential,
347
350
  organizationId: access.organizationId,
348
351
  signal
349
- }));
352
+ }, submittedTask);
350
353
  });
351
354
  await observe?.({ remoteTaskId: taskId });
352
355
  dependencies.telemetry.annotate({ task_id: taskId });
@@ -3,13 +3,35 @@ import * as nodeFileSystem from "node:fs/promises";
3
3
  import { join, resolve } from "node:path";
4
4
  import { setTimeout as delay } from "node:timers/promises";
5
5
  const localTurns = new Map();
6
- const lockTimeout = () => Object.assign(new Error("Local state lock timed out."), { code: "LOCAL_LOCK_TIMEOUT" });
6
+ const actions = new Set(["task_write", "task_update", "sls_queue", "analytics_device"]);
7
+ const localOwners = new Map();
8
+ function lockTimeout(startedAt, contenderId, phase, owners = [], action) {
9
+ const owner = owners[0];
10
+ const now = Date.now();
11
+ return Object.assign(new Error("Local state lock timed out."), {
12
+ code: "LOCAL_LOCK_TIMEOUT",
13
+ diagnosticSummary: {
14
+ lockWaitMs: Math.max(0, Math.min(Number.MAX_SAFE_INTEGER, now - startedAt)),
15
+ lockWaitPhase: phase,
16
+ ...(owner ? { lockWaitScope: owner.pid === process.pid ? "same_process" : "cross_process",
17
+ lockOwnerPid: owner.pid, lockOwnerId: owner.id,
18
+ ...(owner.alive ? { lockOwnerAlive: true } : {}),
19
+ ...(owner.action ? { lockOwnerAction: owner.action } : {}),
20
+ ...(owner.startedAtMs !== undefined ? { lockOwnerStartedAtMs: owner.startedAtMs, lockOwnerAgeMs: Math.max(0, now - owner.startedAtMs) } : {}),
21
+ ...(owner.acquiredAtMs !== undefined ? { lockOwnerAcquiredAtMs: owner.acquiredAtMs, lockOwnerHeldMs: Math.max(0, now - owner.acquiredAtMs) } : {}) } : {}),
22
+ ...(action ? { lockContenderAction: action } : {}),
23
+ lockOwnerCount: Math.min(100_000, owners.length), lockContenderPid: process.pid, lockContenderId: contenderId
24
+ }
25
+ });
26
+ }
7
27
  /** Same-process waiters queue before creating bakery owners. Separate processes
8
28
  * still coordinate through unique owner files and retain the two-second budget. */
9
29
  export async function withFileLock(path, run, options = {}) {
30
+ const startedAt = Date.now();
31
+ const contenderId = randomUUID();
10
32
  const deadline = Math.min(options.deadline ?? Infinity, Date.now() + 2_000);
11
33
  if (Date.now() >= deadline)
12
- throw lockTimeout();
34
+ throw lockTimeout(startedAt, contenderId, "local_queue", [], options.action);
13
35
  const key = resolve(path);
14
36
  const previous = localTurns.get(key) ?? Promise.resolve();
15
37
  let release;
@@ -19,14 +41,22 @@ export async function withFileLock(path, run, options = {}) {
19
41
  let timer;
20
42
  try {
21
43
  await new Promise((ready, reject) => {
22
- timer = setTimeout(() => reject(lockTimeout()), Math.max(0, deadline - Date.now()));
44
+ timer = setTimeout(() => {
45
+ const owner = localOwners.get(key);
46
+ reject(lockTimeout(startedAt, contenderId, "local_queue", owner ? [owner] : [], options.action));
47
+ }, Math.max(0, deadline - Date.now()));
23
48
  void previous.then(ready);
24
49
  });
25
50
  clearTimeout(timer);
26
- return await acquireFileLock(path, run, { ...options, deadline });
51
+ const owner = { id: contenderId, pid: process.pid, alive: true, startedAtMs: startedAt,
52
+ ...(options.action ? { action: options.action } : {}) };
53
+ localOwners.set(key, owner);
54
+ return await acquireFileLock(path, async () => { owner.acquiredAtMs = Date.now(); return run(); }, { ...options, deadline }, { startedAt, contenderId });
27
55
  }
28
56
  finally {
29
57
  clearTimeout(timer);
58
+ if (localOwners.get(key)?.id === contenderId)
59
+ localOwners.delete(key);
30
60
  release();
31
61
  // A timed-out waiter cannot let a new caller bypass a still-active predecessor.
32
62
  void tail.then(() => { if (localTurns.get(key) === tail)
@@ -34,26 +64,30 @@ export async function withFileLock(path, run, options = {}) {
34
64
  }
35
65
  }
36
66
  /** Unique owners avoid deleting a new writer during concurrent crash recovery. */
37
- async function acquireFileLock(path, run, options) {
67
+ async function acquireFileLock(path, run, options, identity) {
38
68
  const fileSystem = options.fileSystem ?? nodeFileSystem;
39
69
  const { mkdir, open, readFile, readdir, unlink, chmod, rename } = fileSystem;
40
70
  const deadline = Math.min(options.deadline ?? Infinity, Date.now() + 2_000);
41
71
  if (Date.now() >= deadline)
42
- throw lockTimeout();
72
+ throw lockTimeout(identity.startedAt, identity.contenderId, "owner_files", [], options.action);
43
73
  const directory = `${path}.d`;
44
74
  await mkdir(directory, { recursive: true, mode: 0o700 });
45
75
  await chmod(directory, 0o700);
46
- const name = `${process.pid}-${randomUUID()}.json`;
76
+ const name = `${process.pid}-${identity.contenderId}.json`;
47
77
  const ownPath = join(directory, name);
48
78
  async function contenders() {
49
79
  const found = [];
50
80
  for (const entry of await readdir(directory)) {
51
- const match = /^(\d+)-[a-f0-9-]{36}\.json$/u.exec(entry);
81
+ const match = /^(\d+)-([a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12})\.json$/u.exec(entry);
52
82
  if (!match)
53
83
  continue;
54
84
  const pid = Number(match[1]);
85
+ if (!Number.isSafeInteger(pid) || pid <= 0)
86
+ continue;
87
+ let alive;
55
88
  try {
56
89
  process.kill(pid, 0);
90
+ alive = true;
57
91
  }
58
92
  catch (error) {
59
93
  if (error instanceof Error && "code" in error && error.code === "ESRCH") {
@@ -64,13 +98,21 @@ async function acquireFileLock(path, run, options) {
64
98
  try {
65
99
  const text = await readFile(join(directory, entry), "utf8");
66
100
  let ticket = null;
101
+ let action;
102
+ let startedAtMs;
67
103
  try {
68
- const value = JSON.parse(text).ticket;
104
+ const record = JSON.parse(text);
105
+ const value = record.ticket;
69
106
  if (typeof value === "number" && Number.isSafeInteger(value) && value > 0)
70
107
  ticket = value;
108
+ if (typeof record.action === "string" && actions.has(record.action))
109
+ action = record.action;
110
+ if (typeof record.startedAtMs === "number" && Number.isSafeInteger(record.startedAtMs) && record.startedAtMs >= 0 && record.startedAtMs <= Date.now())
111
+ startedAtMs = record.startedAtMs;
71
112
  }
72
113
  catch { /* The owner has opened its choosing file but not written it yet. */ }
73
- found.push({ name: entry, ticket });
114
+ found.push({ name: entry, id: match[2], pid, ticket, ...(alive ? { alive } : {}),
115
+ ...(action ? { action } : {}), ...(startedAtMs === undefined ? {} : { startedAtMs }) });
74
116
  }
75
117
  catch (error) {
76
118
  if (!(error instanceof Error && "code" in error && error.code === "ENOENT"))
@@ -88,16 +130,17 @@ async function acquireFileLock(path, run, options) {
88
130
  // Empty/partial owner files already mean "choosing" to readers. Write in
89
131
  // place because Windows can reject replacement while another reader is open.
90
132
  await handle.truncate(0);
91
- await handle.write(JSON.stringify({ ticket }), 0, "utf8");
133
+ await handle.write(JSON.stringify({ ticket, startedAtMs: identity.startedAt, ...(options.action ? { action: options.action } : {}) }), 0, "utf8");
92
134
  await handle.close();
135
+ let owners = [];
93
136
  for (;;) {
94
137
  if (Date.now() >= deadline)
95
- throw lockTimeout();
96
- const waiting = (await contenders()).some(owner => owner.name !== name
138
+ throw lockTimeout(identity.startedAt, identity.contenderId, "owner_files", owners, options.action);
139
+ owners = (await contenders()).filter(owner => owner.name !== name
97
140
  && (owner.ticket === null || owner.ticket < ticket || (owner.ticket === ticket && owner.name < name)));
98
- if (!waiting) {
141
+ if (!owners.length) {
99
142
  if (Date.now() >= deadline)
100
- throw lockTimeout();
143
+ throw lockTimeout(identity.startedAt, identity.contenderId, "owner_files", owners, options.action);
101
144
  return await run();
102
145
  }
103
146
  await delay(10);
@@ -0,0 +1,105 @@
1
+ /** Structural evidence for an already rejected URI; never include its value. */
2
+ export function uriIssue(value) {
3
+ if (/[\u0000-\u001f\u007f-\u009f]/u.test(value))
4
+ return "control_character";
5
+ if (/%(?![A-Fa-f0-9]{2})/u.test(value))
6
+ return "invalid_percent_encoding";
7
+ if (!/^[A-Za-z][A-Za-z0-9+.-]*:/u.test(value))
8
+ return "missing_scheme";
9
+ if (value.includes("\\"))
10
+ return "backslash";
11
+ if (/\s/u.test(value))
12
+ return "whitespace";
13
+ if (/[^\u0000-\u007f]/u.test(value))
14
+ return "non_ascii";
15
+ if (/^file:\/\/[A-Za-z]:/iu.test(value))
16
+ return "file_authority_drive";
17
+ if (/^file:\/{3}[A-Za-z]\|/iu.test(value))
18
+ return "file_drive_separator";
19
+ if (/^https?:/iu.test(value)) {
20
+ const authority = /^https?:\/\/([^/?#]*)/iu.exec(value)?.[1];
21
+ if (!authority || !authority.split("@").at(-1))
22
+ return "missing_host";
23
+ try {
24
+ new URL(value);
25
+ }
26
+ catch {
27
+ return "invalid_host";
28
+ }
29
+ }
30
+ if (/^file:/iu.test(value) && /[?#]/u.test(value))
31
+ return "file_uri_components";
32
+ return "other_format";
33
+ }
34
+ /** URI shape only: no path, host, credentials, query values or input text. */
35
+ export function uriShape(value) {
36
+ const scheme = /^([A-Za-z][A-Za-z0-9+.-]*):/u.exec(value)?.[1]?.toLowerCase();
37
+ const localPath = value.replace(/^file:\/*/iu, "");
38
+ const windowsDrive = /^[A-Za-z]:[\\/]/u.test(localPath) ? "valid"
39
+ : (process.platform === "win32" && /^file:\/{2,3}[A-Za-z][\\/]/iu.test(value)) ? "missing_colon" : "none";
40
+ return {
41
+ uriScheme: scheme === undefined ? "none" : ["file", "http", "https"].includes(scheme) ? scheme : "other",
42
+ uriHasNonAscii: /[^\u0000-\u007f]/u.test(value),
43
+ uriHasWhitespace: /\s/u.test(value),
44
+ uriHasControlChars: /[\u0000-\u001f\u007f-\u009f]/u.test(value),
45
+ uriHasBackslash: value.includes("\\"),
46
+ uriHasPercentEncoding: /%[A-Fa-f0-9]{2}/u.test(value),
47
+ uriHasQuery: value.includes("?"),
48
+ uriHasFragment: value.includes("#"),
49
+ uriHasCredentials: /^[A-Za-z][A-Za-z0-9+.-]*:\/\/[^/?#]*@/u.test(value),
50
+ uriWindowsDrive: windowsDrive
51
+ };
52
+ }
53
+ /** Canonicalize explicit file URIs, without repairing paths or losing filename spaces. */
54
+ export function canonicalFileUri(value) {
55
+ if (!/^file:\//iu.test(value) || /[\\\u0000-\u001f\u007f-\u009f]/u.test(value)
56
+ || /^file:\/\/[A-Za-z]:/iu.test(value) || /^file:\/{3}[A-Za-z]\|/iu.test(value))
57
+ return undefined;
58
+ try {
59
+ const url = new URL(value.replace(/ /gu, "%20"));
60
+ if (url.protocol !== "file:" || url.username || url.password || url.search || url.hash)
61
+ return undefined;
62
+ // URL accepts malformed escapes, whereas fileURLToPath cannot read them.
63
+ decodeURIComponent(url.pathname);
64
+ return url.href;
65
+ }
66
+ catch {
67
+ return undefined;
68
+ }
69
+ }
70
+ /** Normalize only schema-declared URI fields; never inspect or rewrite free text. */
71
+ export function canonicalizeInputFileUris(value, schema) {
72
+ const root = schema;
73
+ const record = (node) => !!node && typeof node === "object" && !Array.isArray(node);
74
+ const resolve = (reference) => reference.startsWith("#/")
75
+ ? reference.slice(2).split("/").reduce((node, key) => {
76
+ const name = key.replace(/~1/gu, "/").replace(/~0/gu, "~");
77
+ return record(node) && Object.hasOwn(node, name) ? node[name] : undefined;
78
+ }, root) : undefined;
79
+ const visit = (input, node, depth) => {
80
+ if (!record(node) || depth > 64)
81
+ return input;
82
+ if (typeof node.$ref === "string")
83
+ input = visit(input, resolve(node.$ref), depth + 1);
84
+ for (const keyword of ["allOf", "anyOf", "oneOf"]) {
85
+ const branches = node[keyword];
86
+ if (Array.isArray(branches))
87
+ for (const branch of branches)
88
+ input = visit(input, branch, depth + 1);
89
+ }
90
+ if (node.format === "uri" && typeof input === "string")
91
+ return canonicalFileUri(input) ?? input;
92
+ if (Array.isArray(input) && record(node.items)) {
93
+ for (let index = 0; index < input.length; index++)
94
+ input[index] = visit(input[index], node.items, depth + 1);
95
+ }
96
+ else if (record(input) && record(node.properties)) {
97
+ for (const [key, child] of Object.entries(node.properties)) {
98
+ if (Object.hasOwn(input, key))
99
+ input[key] = visit(input[key], child, depth + 1);
100
+ }
101
+ }
102
+ return input;
103
+ };
104
+ visit(value, schema, 0);
105
+ }
@@ -5,12 +5,15 @@ export class LocalFileError extends Error {
5
5
  file;
6
6
  reason;
7
7
  diagnostic;
8
+ diagnosticSummary;
8
9
  constructor(cause, file, reason = "io", diagnostic) {
9
10
  super("无法访问本地状态文件。", { cause });
10
11
  this.file = file;
11
12
  this.reason = reason;
12
13
  this.diagnostic = diagnostic;
13
14
  this.name = "LocalFileError";
15
+ this.diagnosticSummary = { localProcessPid: process.pid, localParentPid: process.ppid,
16
+ ...(diagnostic?.role ? { localFileRole: diagnostic.role } : {}) };
14
17
  }
15
18
  }
16
19
  export function createLocalJsonFile(options) {
@@ -36,7 +39,7 @@ export function createLocalJsonFile(options) {
36
39
  return null;
37
40
  failed = true;
38
41
  primaryError = cause;
39
- throw new LocalFileError(cause, options.filename, "io", { operation: "read", step });
42
+ throw new LocalFileError(cause, options.filename, "io", { operation: "read", step, ...(options.role ? { role: options.role } : {}) });
40
43
  }
41
44
  finally {
42
45
  try {
@@ -45,7 +48,7 @@ export function createLocalJsonFile(options) {
45
48
  catch (cause) {
46
49
  throw new LocalFileError(failed
47
50
  ? new AggregateError([primaryError, cause], "Cannot read and close local state.", { cause: primaryError })
48
- : cause, options.filename, "io", { operation: "read", step: failed ? step : "close" });
51
+ : cause, options.filename, "io", { operation: "read", step: failed ? step : "close", ...(options.role ? { role: options.role } : {}) });
49
52
  }
50
53
  }
51
54
  },
@@ -74,7 +77,7 @@ export function createLocalJsonFile(options) {
74
77
  catch (cause) {
75
78
  await handle?.close().catch(() => undefined);
76
79
  await fileSystem.unlink(temporaryPath).catch(() => undefined);
77
- throw new LocalFileError(cause, options.filename, "io", { operation: "write", step });
80
+ throw new LocalFileError(cause, options.filename, "io", { operation: "write", step, ...(options.role ? { role: options.role } : {}) });
78
81
  }
79
82
  },
80
83
  async remove() {
@@ -83,7 +86,7 @@ export function createLocalJsonFile(options) {
83
86
  }
84
87
  catch (cause) {
85
88
  if (!isMissing(cause))
86
- throw new LocalFileError(cause, options.filename, "io", { operation: "remove", step: "unlink" });
89
+ throw new LocalFileError(cause, options.filename, "io", { operation: "remove", step: "unlink", ...(options.role ? { role: options.role } : {}) });
87
90
  }
88
91
  }
89
92
  };
@@ -3,7 +3,7 @@ const maximumLength = 8_192;
3
3
  const truncationMarker = "[TRUNCATED]";
4
4
  export function remoteErrorEvidence(value) {
5
5
  const normalized = parseJson(value);
6
- const remoteCode = topLevelCode(normalized) ?? jsonRpcErrorCode(normalized);
6
+ const remoteCode = topLevelCode(normalized) ?? jsonRpcErrorCode(normalized) ?? mcpErrorContentCode(normalized);
7
7
  const diagnosticReason = imageAuditTimeout(normalized, remoteCode);
8
8
  const sanitized = sanitize(normalized);
9
9
  if (sanitized === undefined) {
@@ -47,6 +47,28 @@ function jsonRpcErrorCode(value) {
47
47
  }
48
48
  return normalizeCode(record.error.code);
49
49
  }
50
+ function mcpErrorContentCode(value) {
51
+ if (value === null || typeof value !== "object" || Array.isArray(value))
52
+ return undefined;
53
+ const result = value.result;
54
+ if (result === null || typeof result !== "object" || Array.isArray(result))
55
+ return undefined;
56
+ const record = result;
57
+ // Only MCP's explicit error result is a trusted error boundary. Ordinary
58
+ // assistant replies and arbitrary nested objects never provide error codes.
59
+ if (record.isError !== true || !Array.isArray(record.content))
60
+ return undefined;
61
+ for (const item of record.content.slice(0, 32)) {
62
+ if (item === null || typeof item !== "object" || item.type !== "text"
63
+ || typeof item.text !== "string" || item.text.length > maximumLength)
64
+ continue;
65
+ const error = parseJson(item.text);
66
+ const code = topLevelCode(error) ?? jsonRpcErrorCode(error);
67
+ if (code !== undefined)
68
+ return code;
69
+ }
70
+ return undefined;
71
+ }
50
72
  function normalizeCode(code) {
51
73
  if (typeof code === "string")
52
74
  return redactRemoteText(code);
@@ -2,11 +2,14 @@ import { isInterruption } from "./interruption.js";
2
2
  import { open, realpath, stat } from "node:fs/promises";
3
3
  import { basename, extname, sep } from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
+ import { canonicalFileUri, uriShape } from "./input-uri.js";
5
6
  export class LocalFileInputError extends Error {
6
7
  reason;
7
- constructor(cause, reason = "file_read_failed") {
8
+ diagnosticSummary;
9
+ constructor(cause, reason = "file_read_failed", diagnosticSummary = {}) {
8
10
  super("本地文件不可用于上传。", { cause });
9
11
  this.reason = reason;
12
+ this.diagnosticSummary = diagnosticSummary;
10
13
  this.name = "LocalFileInputError";
11
14
  }
12
15
  }
@@ -106,7 +109,16 @@ async function readHeader(filePath, signal) {
106
109
  export async function inspectUploadFile(input) {
107
110
  input.signal.throwIfAborted();
108
111
  try {
109
- const requestedPath = fileURLToPath(input.url);
112
+ let requestedPath;
113
+ try {
114
+ const url = canonicalFileUri(input.url);
115
+ if (url === undefined)
116
+ throw new TypeError("Invalid local file URI.");
117
+ requestedPath = fileURLToPath(url);
118
+ }
119
+ catch (cause) {
120
+ throw new LocalFileInputError(cause, "invalid_file_uri");
121
+ }
110
122
  if (input.allowSensitivePath !== true)
111
123
  assertSafePath(requestedPath);
112
124
  const filePath = await realpath(requestedPath);
@@ -148,8 +160,10 @@ export async function inspectUploadFile(input) {
148
160
  catch (error) {
149
161
  if (isInterruption(error, input.signal))
150
162
  throw input.signal.reason;
151
- if (error instanceof LocalFileInputError)
163
+ if (error instanceof LocalFileInputError) {
164
+ Object.assign(error.diagnosticSummary, uriShape(input.url));
152
165
  throw error;
153
- throw new LocalFileInputError(error);
166
+ }
167
+ throw new LocalFileInputError(error, "file_read_failed", uriShape(input.url));
154
168
  }
155
169
  }
@@ -1,3 +1,21 @@
1
+ import { uriIssue, uriShape } from "./input-uri.js";
2
+ export function inputValidationSummary(issues, input, prefix = "") {
3
+ const issue = issues[0];
4
+ if (!issue)
5
+ return {};
6
+ const value = issue.field === "/" ? input : issue.field.slice(1).split("/").reduce((node, key) => {
7
+ const name = key.replace(/~1/gu, "/").replace(/~0/gu, "~");
8
+ return node && typeof node === "object" && Object.hasOwn(node, name) ? node[name] : undefined;
9
+ }, input);
10
+ // additionalProperty names are supplied by the caller; report their parent.
11
+ const field = `${prefix}${issue.rule === "additionalProperties" ? issue.field.replace(/\/[^/]*$/u, "") : issue.field}` || "/";
12
+ return {
13
+ ...(/^\/[A-Za-z0-9_./~-]*$/u.test(field) && field.length <= 256 ? { inputField: field } : {}),
14
+ inputRule: issue.rule,
15
+ inputValueType: value === null ? "null" : Array.isArray(value) ? "array" : typeof value,
16
+ ...(issue.rule === "format" && typeof value === "string" ? { ...uriShape(value), uriIssue: uriIssue(value) } : {})
17
+ };
18
+ }
1
19
  export function validationIssues(errors, value, schema) {
2
20
  let selected = errors ?? [];
3
21
  const at = (root, pointer) => pointer.replace(/^#\/?/u, "").split("/").filter(Boolean)