@gaoding/cli 1.8.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 (95) hide show
  1. package/contracts/operations/agent.send/input.schema.json +1 -1
  2. package/contracts/operations/agent.send/output.schema.json +1 -1
  3. package/contracts/operations/model.get/input.schema.json +6 -0
  4. package/contracts/operations/model.get/output.schema.json +10 -1
  5. package/contracts/operations/tool.call/canvas-input.schema.json +60 -0
  6. package/contracts/operations/tool.call/models/image-edit-smart.schema.json +42 -0
  7. package/contracts/operations/tool.call/models/image-edit-standard.schema.json +33 -0
  8. package/contracts/operations/tool.call/models/image-enhance-smart.schema.json +27 -0
  9. package/contracts/operations/tool.call/models/image-enhance-standard.schema.json +27 -0
  10. package/contracts/operations/tool.call/models/image-expand-smart.schema.json +76 -0
  11. package/contracts/operations/tool.call/models/image-expand-standard.schema.json +61 -0
  12. package/contracts/operations/tool.call/models/image-layers-layout.schema.json +21 -0
  13. package/contracts/operations/tool.call/models/image-layers-smart.schema.json +28 -0
  14. package/contracts/operations/tool.call/models/image-matting-smart.schema.json +37 -0
  15. package/contracts/operations/tool.call/models/image-matting-standard.schema.json +26 -0
  16. package/contracts/operations/tool.call/models/image-ocr.schema.json +21 -0
  17. package/contracts/operations/tool.call/models/image-remove-smart.schema.json +32 -0
  18. package/contracts/operations/tool.call/models/image-remove-standard.schema.json +27 -0
  19. package/contracts/operations/tool.call/models/image-text-edit.schema.json +46 -0
  20. package/contracts/operations/tool.call/models/image-vectorize.schema.json +21 -0
  21. package/contracts/operations/tool.call/models/video-edit-smart.schema.json +76 -0
  22. package/contracts/operations/tool.call/models/video-enhance-smart.schema.json +33 -0
  23. package/contracts/operations/tool.call/models/video-enhance-standard.schema.json +27 -0
  24. package/contracts/operations/tool.call/ocr-payload.schema.json +66 -0
  25. package/contracts/operations/tool.call/output.schema.json +38 -0
  26. package/contracts/operations/tool.call/template-payload.schema.json +96 -0
  27. package/dist/bin/gd-cli.js +31 -24
  28. package/dist/bin/insmind-cli.js +31 -24
  29. package/dist/bin/task-worker.js +4 -1
  30. package/dist/src/analytics/device.js +2 -2
  31. package/dist/src/bootstrap/create-cli.js +7 -0
  32. package/dist/src/bootstrap/create-runtime.js +53 -30
  33. package/dist/src/bootstrap/run-task-worker.js +5 -1
  34. package/dist/src/bootstrap/validators.js +11 -4
  35. package/dist/src/cli/agent-commands.js +1 -0
  36. package/dist/src/cli/dam-commands.js +3 -3
  37. package/dist/src/cli/errors.js +63 -15
  38. package/dist/src/cli/model-commands.js +6 -3
  39. package/dist/src/cli/observed-errors.js +3 -1
  40. package/dist/src/cli/tool-commands.js +2 -0
  41. package/dist/src/contracts/schema.js +4 -1
  42. package/dist/src/features/agent/creative-agent-adapter.js +37 -11
  43. package/dist/src/features/agent/creative-protocol.js +31 -10
  44. package/dist/src/features/agent/creative-stream.js +54 -6
  45. package/dist/src/features/agent/resource-authorizer.js +1 -0
  46. package/dist/src/features/agent/result-reader.js +3 -1
  47. package/dist/src/features/agent/use-cases.js +15 -5
  48. package/dist/src/features/auth/credential-store.js +6 -10
  49. package/dist/src/features/auth/sso-service.js +22 -6
  50. package/dist/src/features/auth/state.js +6 -0
  51. package/dist/src/features/auth/use-cases.js +90 -32
  52. package/dist/src/features/dam/asset-projection.js +10 -1
  53. package/dist/src/features/dam/dam-api-adapter.js +30 -15
  54. package/dist/src/features/dam/input.js +23 -0
  55. package/dist/src/features/dam/use-cases.js +32 -22
  56. package/dist/src/features/task/store.js +5 -5
  57. package/dist/src/features/task/task-background.js +67 -19
  58. package/dist/src/features/task/use-cases.js +38 -9
  59. package/dist/src/features/tool/canvas-copy.js +61 -0
  60. package/dist/src/features/tool/canvas-media.js +248 -0
  61. package/dist/src/features/tool/canvas-models.js +109 -0
  62. package/dist/src/features/tool/canvas-pricing.js +81 -0
  63. package/dist/src/features/tool/canvas-recovery.js +68 -0
  64. package/dist/src/features/tool/canvas-results.js +144 -0
  65. package/dist/src/features/tool/canvas-tool-adapter.js +366 -0
  66. package/dist/src/features/tool/canvas-video.js +84 -0
  67. package/dist/src/features/tool/catalog.js +35 -13
  68. package/dist/src/features/tool/dynamic-schema.js +55 -25
  69. package/dist/src/features/tool/matting-billing.js +115 -0
  70. package/dist/src/features/tool/mns-catalog-adapter.js +66 -19
  71. package/dist/src/features/tool/resource-authorizer.js +34 -0
  72. package/dist/src/features/tool/scene-catalog-adapter.js +35 -0
  73. package/dist/src/features/tool/tool-api-adapter.js +29 -17
  74. package/dist/src/features/tool/use-cases.js +28 -3
  75. package/dist/src/platform/file-lock.js +58 -15
  76. package/dist/src/platform/input-uri.js +105 -0
  77. package/dist/src/platform/local-json-file.js +7 -4
  78. package/dist/src/platform/remote-error-evidence.js +23 -1
  79. package/dist/src/platform/safe-upload-file.js +18 -4
  80. package/dist/src/platform/schema-issues.js +18 -0
  81. package/dist/src/platform/signed-http-transport.js +77 -16
  82. package/dist/src/platform/text-output.js +55 -13
  83. package/dist/src/product/config.js +12 -1
  84. package/dist/src/telemetry/failure-summary.js +53 -2
  85. package/dist/src/telemetry/host-diagnostics.js +95 -0
  86. package/dist/src/telemetry/invocation.js +24 -3
  87. package/dist/src/telemetry/process-errors.js +2 -1
  88. package/dist/src/telemetry/sls-sink.js +66 -18
  89. package/package.json +5 -4
  90. package/skills/gd-cli/SKILL.md +2 -0
  91. package/skills/gd-cli/references/creation.md +2 -0
  92. package/skills/gd-cli/references/generation-constraints.md +3 -1
  93. package/skills/gd-cli/references/matting.md +29 -0
  94. package/skills/gd-cli/references/media-tools.md +40 -0
  95. package/skills/gd-cli/references/tool.md +4 -4
@@ -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;
@@ -97,7 +97,7 @@ function resourceName(uri) {
97
97
  return protocolFailure(uri);
98
98
  }
99
99
  }
100
- function normalizeContent(value) {
100
+ export function normalizeToolContent(value) {
101
101
  if (!isRecord(value))
102
102
  return protocolFailure(value);
103
103
  if (value.type === "text") {
@@ -138,23 +138,33 @@ export class ToolTaskFailedError extends Error {
138
138
  this.diagnosticReason = evidence.diagnosticReason;
139
139
  }
140
140
  }
141
+ export class ToolInsufficientCreditsError extends ToolTaskFailedError {
142
+ diagnosticReason = "INSUFFICIENT_CREDITS";
143
+ constructor() {
144
+ super();
145
+ this.name = "ToolInsufficientCreditsError";
146
+ }
147
+ }
141
148
  export class ToolTaskCanceledError extends Error {
142
149
  diagnosticReason = "TASK_CANCELED";
143
150
  constructor() { super("用户已取消生成任务。"); this.name = "ToolTaskCanceledError"; }
144
151
  }
145
152
  export async function queryToolResult(transport, request) {
153
+ let difyTaskId;
146
154
  try {
147
- return pollResult(await safePost(transport, {
155
+ return await safePost(transport, {
148
156
  credential: request.credential,
149
157
  ...(request.organizationId === undefined ? {} : { organizationId: request.organizationId }),
150
158
  signal: request.signal,
151
159
  path: "/gdesign/tool/v1/dify/process/batch",
152
160
  body: { task_ids: [request.taskId] }
153
- }), request.taskId, request.onDifyTaskId);
161
+ }, value => pollResult(value, request.taskId, id => { difyTaskId = id; request.onDifyTaskId?.(id); }, request.normalize));
154
162
  }
155
163
  catch (error) {
156
164
  if (isInterruption(error, request.signal) || error instanceof ToolTaskCanceledError)
157
165
  throw error;
166
+ if (error instanceof ToolTaskFailedError)
167
+ return failedPoll(error, difyTaskId);
158
168
  const evidence = error instanceof RemoteRequestError || error instanceof RemoteProtocolError
159
169
  ? { ...(error.remoteCode === undefined ? {} : { remoteCode: error.remoteCode }),
160
170
  ...(error.remoteBody === undefined ? {} : { remoteBody: error.remoteBody }) } : {};
@@ -189,7 +199,7 @@ function isJsonRpcError(value) {
189
199
  && typeof value.error.message === "string"
190
200
  && value.error.message.trim() !== "";
191
201
  }
192
- function pollResult(value, taskId, onDifyTaskId) {
202
+ function pollResult(value, taskId, onDifyTaskId, normalize = normalizeToolContent) {
193
203
  if (!Array.isArray(value))
194
204
  return protocolFailure(value);
195
205
  const item = value.find((candidate) => isRecord(candidate) && candidate.task_id === taskId);
@@ -225,15 +235,15 @@ function pollResult(value, taskId, onDifyTaskId) {
225
235
  if (typeof difyTaskId === "string")
226
236
  onDifyTaskId?.(difyTaskId);
227
237
  if (Object.prototype.hasOwnProperty.call(inner, "error")) {
228
- return isJsonRpcError(inner)
229
- ? failedPoll(new ToolTaskFailedError(remoteErrorEvidence(inner)), difyTaskId)
230
- : failedPoll(new RemoteProtocolError(remoteErrorEvidence(inner)), difyTaskId);
238
+ if (isJsonRpcError(inner))
239
+ throw new ToolTaskFailedError(remoteErrorEvidence(inner));
240
+ throw new RemoteProtocolError(remoteErrorEvidence(inner));
231
241
  }
232
242
  if (!isRecord(inner.result)) {
233
243
  return failedPoll(new RemoteProtocolError(remoteErrorEvidence(inner)), difyTaskId);
234
244
  }
235
245
  if (inner.result.isError === true) {
236
- return failedPoll(new ToolTaskFailedError(remoteErrorEvidence(inner)), difyTaskId);
246
+ throw new ToolTaskFailedError(remoteErrorEvidence(inner));
237
247
  }
238
248
  if (inner.result.isError !== false) {
239
249
  return failedPoll(new RemoteProtocolError(remoteErrorEvidence(inner)), difyTaskId);
@@ -257,7 +267,7 @@ function pollResult(value, taskId, onDifyTaskId) {
257
267
  try {
258
268
  return {
259
269
  state: "complete",
260
- content: content.map(normalizeContent),
270
+ content: content.map(normalize),
261
271
  ...(difyTaskId === undefined ? {} : { difyTaskId })
262
272
  };
263
273
  }
@@ -267,14 +277,14 @@ function pollResult(value, taskId, onDifyTaskId) {
267
277
  throw error;
268
278
  }
269
279
  }
270
- async function safePost(transport, request) {
280
+ async function safePost(transport, request, interpret) {
271
281
  try {
272
- return await transport.postJson(request);
282
+ return await withResponseDiagnostics(async (onResponse) => interpret(await transport.postJson({ ...request, onResponse })));
273
283
  }
274
284
  catch (error) {
275
285
  if (isInterruption(error, request.signal))
276
286
  throw request.signal.reason;
277
- if (error instanceof RemoteRequestError || error instanceof RemoteProtocolError)
287
+ if (error instanceof RemoteRequestError || error instanceof RemoteProtocolError || error instanceof ToolTaskFailedError || error instanceof ToolTaskCanceledError)
278
288
  throw error;
279
289
  throw new RemoteRequestError(undefined, false, {}, error);
280
290
  }
@@ -298,11 +308,13 @@ export function createToolApiAdapter(dependencies) {
298
308
  const sleep = dependencies.sleep ?? defaultSleep;
299
309
  async function submit({ invocation, access, signal, observe }) {
300
310
  signal.throwIfAborted();
311
+ if (invocation.kind === "canvas")
312
+ throw new RemoteProtocolError({}, undefined, "TOOL_ADAPTER_MISSING");
301
313
  const managedContentId = contentId(createContentId());
302
314
  const resolved = invocation.kind === "direct"
303
315
  ? { name: invocation.name, arguments: invocation.arguments }
304
316
  : await dependencies.telemetry.stage("intent", async () => {
305
- const intent = parseIntent(await safePost(dependencies.transport, {
317
+ const intent = await safePost(dependencies.transport, {
306
318
  path: "/ai-agent/v1/tool-intent",
307
319
  body: {
308
320
  prompt: invocation.prompt,
@@ -312,7 +324,7 @@ export function createToolApiAdapter(dependencies) {
312
324
  credential: access.credential,
313
325
  organizationId: access.organizationId,
314
326
  signal
315
- }));
327
+ }, parseIntent);
316
328
  return {
317
329
  ...intent,
318
330
  arguments: withoutEmptyOptionalMedia(intent.arguments, invocation.optionalMediaParameters)
@@ -322,7 +334,7 @@ export function createToolApiAdapter(dependencies) {
322
334
  await observe?.({ submissionStarted: true });
323
335
  const taskId = await dependencies.telemetry.stage("submit", async () => {
324
336
  dependencies.telemetry.annotate({ content_id: managedContentId });
325
- return submittedTask(await safePost(dependencies.transport, {
337
+ return safePost(dependencies.transport, {
326
338
  path: "/gdesign/tool/v1/dify/call_async",
327
339
  ...(observe ? { onDispatch: (dispatchedAt) => observe({ dispatchedAt }) } : {}),
328
340
  body: {
@@ -337,7 +349,7 @@ export function createToolApiAdapter(dependencies) {
337
349
  credential: access.credential,
338
350
  organizationId: access.organizationId,
339
351
  signal
340
- }));
352
+ }, submittedTask);
341
353
  });
342
354
  await observe?.({ remoteTaskId: taskId });
343
355
  dependencies.telemetry.annotate({ task_id: taskId });
@@ -1,6 +1,7 @@
1
1
  import { parseSafeRemoteAssetUrl, UrlSafetyError } from "../../platform/url-safety.js";
2
2
  import { findToolModel, defaultToolDefinitions, projectModelDetail, projectModelList, projectToolList, ToolInputError } from "./catalog.js";
3
3
  import { assertModelArguments, buildToolArgumentsSchema } from "./dynamic-schema.js";
4
+ import { hasCanvasMetering } from "./canvas-pricing.js";
4
5
  const mediaTypes = {
5
6
  avif: "image/avif",
6
7
  gif: "image/gif",
@@ -66,6 +67,17 @@ export function createToolUseCases(dependencies) {
66
67
  throw new ToolInputError("model_required", "/arguments/model");
67
68
  const selected = findToolModel(catalog, input.name, modelName);
68
69
  assertModelArguments(selected, input.arguments);
70
+ if (selected.execution?.kind === "canvas") {
71
+ for (const parameter of selected.parameters) {
72
+ const value = input.arguments[parameter.name];
73
+ const uris = parameter.type === "uri[]" ? value
74
+ : parameter.type === "uri" && typeof value === "string" ? [value] : undefined;
75
+ for (const [index, uri] of (uris ?? []).entries()) {
76
+ if (!uri.startsWith("file:"))
77
+ remoteMedia(uri, parameter.type === "uri[]" ? `${parameter.name}/${index}` : parameter.name);
78
+ }
79
+ }
80
+ }
69
81
  return selected;
70
82
  });
71
83
  const { model: ignoredModel, ...parameters } = input.arguments;
@@ -75,6 +87,11 @@ export function createToolUseCases(dependencies) {
75
87
  model_id: model.model,
76
88
  parameters
77
89
  });
90
+ if (model.execution?.kind === "canvas") {
91
+ const usage = { model: model.model, ...(model.cost === undefined || hasCanvasMetering(model) ? {} : { cost: model.cost }) };
92
+ await observe?.({ toolUsage: usage, generation: { tool: model.tool, model: model.model } });
93
+ return { invocation: { kind: "canvas", model, arguments: input.arguments }, usage };
94
+ }
78
95
  const prompt = [];
79
96
  const requestParameters = {};
80
97
  const directArguments = {};
@@ -166,14 +183,22 @@ export function createToolUseCases(dependencies) {
166
183
  return projectModelList(await load(access, signal), input.tool, dependencies.tools ?? defaultToolDefinitions);
167
184
  },
168
185
  async getModel({ input, access, signal }) {
169
- return projectModelDetail(await load(access, signal), input.model);
186
+ return projectModelDetail(await load(access, signal), input.model, input.tool);
170
187
  },
171
188
  async getArgumentsSchema({ name, access, signal }) {
172
189
  return buildToolArgumentsSchema(await load(access, signal), name, dependencies.modelDescription);
173
190
  },
174
191
  async call(input) {
175
- const { invocation, usage } = await prepare(input);
176
- const content = await dependencies.execution.execute({ invocation, access: input.access, signal: input.signal, ...(input.observe ? { observe: input.observe } : {}) });
192
+ const prepared = await prepare(input);
193
+ const { invocation } = prepared;
194
+ let usage = prepared.usage;
195
+ const observe = async (progress) => {
196
+ if (progress.toolUsage)
197
+ usage = progress.toolUsage;
198
+ await input.observe?.(progress);
199
+ };
200
+ const observer = invocation.kind === "canvas" ? observe : input.observe;
201
+ const content = await dependencies.execution.execute({ invocation, access: input.access, signal: input.signal, ...(observer ? { observe: observer } : {}) });
177
202
  return { content, usage };
178
203
  },
179
204
  async submit(input) {
@@ -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)