@insmind/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 (92) hide show
  1. package/contracts/operations/model.get/input.schema.json +5 -0
  2. package/contracts/operations/model.get/output.schema.json +9 -1
  3. package/contracts/operations/tool.call/canvas-input.schema.json +60 -0
  4. package/contracts/operations/tool.call/models/image-edit-smart.schema.json +39 -0
  5. package/contracts/operations/tool.call/models/image-edit-standard.schema.json +31 -0
  6. package/contracts/operations/tool.call/models/image-enhance-smart.schema.json +26 -0
  7. package/contracts/operations/tool.call/models/image-enhance-standard.schema.json +25 -0
  8. package/contracts/operations/tool.call/models/image-expand-smart.schema.json +72 -0
  9. package/contracts/operations/tool.call/models/image-expand-standard.schema.json +58 -0
  10. package/contracts/operations/tool.call/models/image-layers-layout.schema.json +20 -0
  11. package/contracts/operations/tool.call/models/image-layers-smart.schema.json +26 -0
  12. package/contracts/operations/tool.call/models/image-matting-smart.schema.json +34 -0
  13. package/contracts/operations/tool.call/models/image-matting-standard.schema.json +24 -0
  14. package/contracts/operations/tool.call/models/image-ocr.schema.json +20 -0
  15. package/contracts/operations/tool.call/models/image-remove-smart.schema.json +30 -0
  16. package/contracts/operations/tool.call/models/image-remove-standard.schema.json +25 -0
  17. package/contracts/operations/tool.call/models/image-text-edit.schema.json +43 -0
  18. package/contracts/operations/tool.call/models/image-vectorize.schema.json +20 -0
  19. package/contracts/operations/tool.call/models/video-edit-smart.schema.json +68 -0
  20. package/contracts/operations/tool.call/models/video-enhance-smart.schema.json +32 -0
  21. package/contracts/operations/tool.call/models/video-enhance-standard.schema.json +26 -0
  22. package/contracts/operations/tool.call/ocr-payload.schema.json +65 -0
  23. package/contracts/operations/tool.call/output.schema.json +38 -0
  24. package/contracts/operations/tool.call/template-payload.schema.json +95 -0
  25. package/dist/bin/insmind-cli.js +31 -24
  26. package/dist/bin/task-worker.js +4 -1
  27. package/dist/src/analytics/device.js +2 -2
  28. package/dist/src/bootstrap/create-cli.js +7 -0
  29. package/dist/src/bootstrap/create-runtime.js +53 -30
  30. package/dist/src/bootstrap/run-task-worker.js +5 -1
  31. package/dist/src/bootstrap/validators.js +11 -4
  32. package/dist/src/cli/agent-commands.js +1 -0
  33. package/dist/src/cli/dam-commands.js +3 -3
  34. package/dist/src/cli/errors.js +63 -15
  35. package/dist/src/cli/model-commands.js +6 -3
  36. package/dist/src/cli/observed-errors.js +3 -1
  37. package/dist/src/cli/tool-commands.js +2 -0
  38. package/dist/src/contracts/schema.js +4 -1
  39. package/dist/src/features/agent/creative-agent-adapter.js +37 -11
  40. package/dist/src/features/agent/creative-protocol.js +31 -10
  41. package/dist/src/features/agent/creative-stream.js +54 -6
  42. package/dist/src/features/agent/resource-authorizer.js +1 -0
  43. package/dist/src/features/agent/result-reader.js +3 -1
  44. package/dist/src/features/agent/use-cases.js +15 -5
  45. package/dist/src/features/auth/credential-store.js +6 -10
  46. package/dist/src/features/auth/sso-service.js +22 -6
  47. package/dist/src/features/auth/state.js +6 -0
  48. package/dist/src/features/auth/use-cases.js +90 -32
  49. package/dist/src/features/dam/asset-projection.js +10 -1
  50. package/dist/src/features/dam/dam-api-adapter.js +30 -15
  51. package/dist/src/features/dam/input.js +23 -0
  52. package/dist/src/features/dam/use-cases.js +32 -22
  53. package/dist/src/features/task/store.js +5 -5
  54. package/dist/src/features/task/task-background.js +67 -19
  55. package/dist/src/features/task/use-cases.js +38 -9
  56. package/dist/src/features/tool/canvas-copy.js +61 -0
  57. package/dist/src/features/tool/canvas-media.js +248 -0
  58. package/dist/src/features/tool/canvas-models.js +109 -0
  59. package/dist/src/features/tool/canvas-pricing.js +81 -0
  60. package/dist/src/features/tool/canvas-recovery.js +68 -0
  61. package/dist/src/features/tool/canvas-results.js +144 -0
  62. package/dist/src/features/tool/canvas-tool-adapter.js +366 -0
  63. package/dist/src/features/tool/canvas-video.js +84 -0
  64. package/dist/src/features/tool/catalog.js +35 -13
  65. package/dist/src/features/tool/dynamic-schema.js +55 -25
  66. package/dist/src/features/tool/matting-billing.js +115 -0
  67. package/dist/src/features/tool/mns-catalog-adapter.js +66 -19
  68. package/dist/src/features/tool/resource-authorizer.js +34 -0
  69. package/dist/src/features/tool/scene-catalog-adapter.js +35 -0
  70. package/dist/src/features/tool/tool-api-adapter.js +29 -17
  71. package/dist/src/features/tool/use-cases.js +28 -3
  72. package/dist/src/platform/file-lock.js +58 -15
  73. package/dist/src/platform/input-uri.js +105 -0
  74. package/dist/src/platform/local-json-file.js +7 -4
  75. package/dist/src/platform/remote-error-evidence.js +23 -1
  76. package/dist/src/platform/safe-upload-file.js +18 -4
  77. package/dist/src/platform/schema-issues.js +18 -0
  78. package/dist/src/platform/signed-http-transport.js +77 -16
  79. package/dist/src/platform/text-output.js +55 -13
  80. package/dist/src/product/config.js +12 -1
  81. package/dist/src/telemetry/failure-summary.js +53 -2
  82. package/dist/src/telemetry/host-diagnostics.js +95 -0
  83. package/dist/src/telemetry/invocation.js +24 -3
  84. package/dist/src/telemetry/process-errors.js +2 -1
  85. package/dist/src/telemetry/sls-sink.js +66 -18
  86. package/package.json +5 -4
  87. package/skills/insmind-cli/SKILL.md +2 -0
  88. package/skills/insmind-cli/references/creation.md +2 -0
  89. package/skills/insmind-cli/references/generation-constraints.md +3 -1
  90. package/skills/insmind-cli/references/matting.md +29 -0
  91. package/skills/insmind-cli/references/media-tools.md +40 -0
  92. package/skills/insmind-cli/references/tool.md +1 -1
@@ -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)
@@ -2,13 +2,45 @@ import { isInterruption } from "./interruption.js";
2
2
  import { remoteErrorEvidence } from "./remote-error-evidence.js";
3
3
  import { RemoteProtocolError } from "./remote-protocol.js";
4
4
  import { canonicalizeQuery, signRequest } from "./signature.js";
5
+ /** Bind adapter interpretation errors to this response, never to a later request. */
6
+ export async function withResponseDiagnostics(run, correlation = {}) {
7
+ let receipt;
8
+ try {
9
+ return await run((status, summary) => { receipt = { status, ...(summary ? { summary } : {}) }; });
10
+ }
11
+ catch (error) {
12
+ try {
13
+ if ((receipt || Object.keys(correlation).length) && error instanceof Error && Object.isExtensible(error)) {
14
+ const previous = error;
15
+ let nestedResponse = false;
16
+ const seen = new Set();
17
+ for (let cause = error.cause; cause instanceof Error && seen.size < 10 && !seen.has(cause); cause = cause.cause) {
18
+ seen.add(cause);
19
+ if ("status" in cause && typeof cause.status === "number") {
20
+ nestedResponse = true;
21
+ break;
22
+ }
23
+ }
24
+ const related = !nestedResponse && (previous.status === undefined || previous.status === receipt?.status)
25
+ && (!previous.diagnosticSummary?.requestId || !receipt?.summary?.requestId || previous.diagnosticSummary.requestId === receipt.summary.requestId);
26
+ const response = related ? receipt : undefined;
27
+ // Existing evidence belongs to the primary failure (e.g. a nested request).
28
+ Object.assign(error, { ...(response ? { status: previous.status ?? response.status } : {}),
29
+ diagnosticSummary: { ...correlation, ...response?.summary, ...previous.diagnosticSummary } });
30
+ }
31
+ }
32
+ catch { /* Diagnostics cannot replace the original failure. */ }
33
+ throw error;
34
+ }
35
+ }
5
36
  export class RemoteRequestError extends Error {
6
37
  status;
7
38
  transient;
8
39
  remoteCode;
9
40
  remoteBody;
10
41
  diagnosticReason;
11
- constructor(status, transient = false, evidence = {}, cause, diagnosticReason) {
42
+ diagnosticSummary;
43
+ constructor(status, transient = false, evidence = {}, cause, diagnosticReason, diagnosticSummary) {
12
44
  super(status === undefined ? "无法连接稿定服务。" : `稿定服务请求失败(HTTP ${status})。`, { cause });
13
45
  this.name = "RemoteRequestError";
14
46
  this.status = status;
@@ -16,7 +48,16 @@ export class RemoteRequestError extends Error {
16
48
  this.remoteCode = evidence.remoteCode;
17
49
  this.remoteBody = evidence.remoteBody;
18
50
  this.diagnosticReason = diagnosticReason ?? evidence.diagnosticReason;
51
+ this.diagnosticSummary = diagnosticSummary;
52
+ }
53
+ }
54
+ function responseDiagnostics(response) {
55
+ for (const header of ["x-request-id", "x-gd-request-id", "request-id"]) {
56
+ const requestId = response.headers.get(header);
57
+ if (requestId && /^[A-Za-z0-9._:-]{1,128}$/u.test(requestId))
58
+ return { requestId };
19
59
  }
60
+ return undefined;
20
61
  }
21
62
  const TRANSIENT_NETWORK_CODES = new Set([
22
63
  "ECONNRESET",
@@ -75,13 +116,18 @@ export function createSignedHttpTransport(options) {
75
116
  headers["Content-Type"] = "application/json";
76
117
  if (request.organizationId !== undefined)
77
118
  headers["X-Org-Id"] = request.organizationId;
78
- const signal = timeout
79
- ? AbortSignal.any([
80
- request.signal,
81
- AbortSignal.timeout(options.timeoutMs ?? 30_000)
82
- ])
119
+ const requestTimeoutMs = timeout ? options.timeoutMs ?? 30_000 : undefined;
120
+ const timeoutSignal = requestTimeoutMs === undefined ? undefined : AbortSignal.timeout(requestTimeoutMs);
121
+ const signal = timeoutSignal
122
+ ? AbortSignal.any([request.signal, timeoutSignal])
83
123
  : request.signal;
84
124
  signal.throwIfAborted();
125
+ const startedAt = Date.now();
126
+ const diagnostics = () => ({
127
+ requestDurationMs: Math.max(0, Math.min(Number.MAX_SAFE_INTEGER, Date.now() - startedAt)),
128
+ ...(requestTimeoutMs === undefined ? {} : { requestTimeoutMs }),
129
+ abortSource: request.signal.aborted ? "caller" : timeoutSignal?.aborted ? "request_timeout" : "none"
130
+ });
85
131
  let dispatched;
86
132
  try {
87
133
  // Invoke fetch at this boundary; diagnostic persistence never gates dispatch.
@@ -98,9 +144,14 @@ export function createSignedHttpTransport(options) {
98
144
  response,
99
145
  bodyUsedAtReceipt: response.bodyUsed,
100
146
  bodyLockedAtReceipt: response.body?.locked ?? false,
101
- reusedResponse: seenResponses.has(response)
147
+ reusedResponse: seenResponses.has(response),
148
+ diagnostics: () => ({ ...diagnostics(), ...responseDiagnostics(response) })
102
149
  };
103
150
  seenResponses.add(response);
151
+ try {
152
+ request.onResponse?.(response.status, received.diagnostics());
153
+ }
154
+ catch { /* Receipt diagnostics only. */ }
104
155
  return received;
105
156
  });
106
157
  }
@@ -114,9 +165,17 @@ export function createSignedHttpTransport(options) {
114
165
  return received;
115
166
  }
116
167
  catch (error) {
117
- if (isInterruption(error, request.signal))
118
- throw request.signal.reason;
119
- throw new RemoteRequestError(undefined, isTransientNetworkFailure(error), {}, error);
168
+ const diagnosticSummary = diagnostics();
169
+ if (isInterruption(error, request.signal)) {
170
+ const reason = request.signal.reason;
171
+ try {
172
+ if (reason instanceof Error && Object.isExtensible(reason))
173
+ Object.assign(reason, { diagnosticSummary });
174
+ }
175
+ catch { /* Preserve the original interruption. */ }
176
+ throw reason;
177
+ }
178
+ throw new RemoteRequestError(undefined, isTransientNetworkFailure(error), {}, error, undefined, diagnosticSummary);
120
179
  }
121
180
  }
122
181
  async function readText(received) {
@@ -136,7 +195,7 @@ export function createSignedHttpTransport(options) {
136
195
  : summary.bodyLockedBeforeRead ? "RESPONSE_BODY_LOCKED" : "RESPONSE_BODY_READ_FAILED";
137
196
  throw new RemoteRequestError(response.status, false, {
138
197
  remoteBody: JSON.stringify(summary)
139
- }, error, diagnosticReason);
198
+ }, error, diagnosticReason, { ...received.diagnostics(), ...summary });
140
199
  }
141
200
  }
142
201
  async function json(received) {
@@ -144,17 +203,19 @@ export function createSignedHttpTransport(options) {
144
203
  const body = await readText(received);
145
204
  const evidence = remoteErrorEvidence(body);
146
205
  if (!response.ok)
147
- throw new RemoteRequestError(response.status, false, evidence);
206
+ throw new RemoteRequestError(response.status, false, evidence, undefined, undefined, received.diagnostics());
148
207
  try {
149
208
  return JSON.parse(body);
150
209
  }
151
210
  catch (error) {
152
- throw new RemoteProtocolError(evidence, error, "RESPONSE_JSON_INVALID");
211
+ throw Object.assign(new RemoteProtocolError(evidence, error, "RESPONSE_JSON_INVALID"), {
212
+ status: response.status, diagnosticSummary: received.diagnostics()
213
+ });
153
214
  }
154
215
  }
155
216
  async function getJsonResponse(request) {
156
217
  const received = await send("GET", request, "application/json", undefined, true);
157
- return { body: await json(received), headers: received.response.headers };
218
+ return { body: await json(received), headers: received.response.headers, status: received.response.status };
158
219
  }
159
220
  return {
160
221
  async getJson(request) {
@@ -172,10 +233,10 @@ export function createSignedHttpTransport(options) {
172
233
  const { response } = received;
173
234
  if (!response.ok) {
174
235
  const body = await readText(received);
175
- throw new RemoteRequestError(response.status, false, remoteErrorEvidence(body));
236
+ throw new RemoteRequestError(response.status, false, remoteErrorEvidence(body), undefined, undefined, received.diagnostics());
176
237
  }
177
238
  if (!response.body)
178
- throw new RemoteRequestError(response.status);
239
+ throw new RemoteRequestError(response.status, false, {}, undefined, "RESPONSE_BODY_MISSING", received.diagnostics());
179
240
  return response.body;
180
241
  }
181
242
  };