@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,16 +1,10 @@
1
1
  import { resolve } from "node:path";
2
2
  import { pathToFileURL } from "node:url";
3
+ import { DamAssetNotDownloadableError } from "./dam-api-adapter.js";
4
+ import { DamInputError, normalizeDamAssetId } from "./input.js";
5
+ import { damAssetSourcePresent } from "./asset-projection.js";
3
6
  import { DamOperationUnconfirmedError } from "./operation-executor.js";
4
- export class DamInputError extends Error {
5
- reason;
6
- field;
7
- constructor(reason = "invalid_value", field) {
8
- super("DAM 输入不可用。");
9
- this.reason = reason;
10
- this.field = field;
11
- this.name = "DamInputError";
12
- }
13
- }
7
+ export { DamInputError } from "./input.js";
14
8
  export class DamRepositoryNotFoundError extends Error {
15
9
  constructor() {
16
10
  super("当前组织没有可用的 DAM 资源库。");
@@ -37,8 +31,7 @@ function assertOptionalNonblank(value, field) {
37
31
  invalid("nonblank", field);
38
32
  }
39
33
  function assertAssetId(value, field = "asset_id") {
40
- if (value.trim() === "" || /^https?:\/\//iu.test(value))
41
- invalid("id_required_not_url", field);
34
+ normalizeDamAssetId(value, field);
42
35
  }
43
36
  function assertRepositorySelection(input) {
44
37
  if (input.repositoryId !== undefined && !nonblank(input.repositoryId))
@@ -275,7 +268,7 @@ export function createDamUseCases(dependencies) {
275
268
  },
276
269
  async download({ input, access, signal }) {
277
270
  signal.throwIfAborted();
278
- assertAssetId(input.asset_id);
271
+ input = { ...input, asset_id: normalizeDamAssetId(input.asset_id) };
279
272
  assertOptionalNonblank(input.outputDir, "outputDir");
280
273
  const [repository] = await dependencies.telemetry.stage("repository", () => (resolveRepositories({
281
274
  ...(input.repositoryId === undefined ? {} : { repositoryId: input.repositoryId })
@@ -284,12 +277,27 @@ export function createDamUseCases(dependencies) {
284
277
  throw new DamRepositoryNotFoundError();
285
278
  const detail = await dependencies.telemetry.stage("resolve", () => (dependencies.api.getAsset({ assetId: input.asset_id, access, signal })));
286
279
  signal.throwIfAborted();
287
- const urls = await dependencies.telemetry.stage("download", () => (dependencies.api.getDownloadUrls({
288
- assetId: input.asset_id,
289
- repositoryId: repository.id,
290
- access,
291
- signal
292
- })));
280
+ const urls = await dependencies.telemetry.stage("download", async () => {
281
+ try {
282
+ const urls = await dependencies.api.getDownloadUrls({ assetId: input.asset_id, repositoryId: repository.id, access, signal });
283
+ if (!urls.some(url => url.trim() !== ""))
284
+ throw new DamAssetNotDownloadableError({ downloadUrlCount: 0 });
285
+ return urls;
286
+ }
287
+ catch (error) {
288
+ if (error instanceof Error) {
289
+ const existing = "diagnosticSummary" in error && error.diagnosticSummary && typeof error.diagnosticSummary === "object" ? error.diagnosticSummary : {};
290
+ Object.assign(error, { diagnosticSummary: {
291
+ ...existing, downloadPhase: "url_lookup", assetType: detail.type ?? "unknown",
292
+ ...(detail.format && /^[A-Za-z0-9][A-Za-z0-9.+_-]{0,31}$/u.test(detail.format) ? { assetFormat: detail.format } : {}),
293
+ assetSourcePresent: damAssetSourcePresent(detail),
294
+ ...(/^[A-Za-z0-9._:-]{1,128}$/u.test(repository.id) ? { selectedRepositoryId: repository.id } : {}),
295
+ ...(detail.repository_id && /^[A-Za-z0-9._:-]{1,128}$/u.test(detail.repository_id) ? { actualRepositoryId: detail.repository_id } : {})
296
+ } });
297
+ }
298
+ throw error;
299
+ }
300
+ });
293
301
  signal.throwIfAborted();
294
302
  const files = await dependencies.telemetry.stage("persist", () => (dependencies.downloader.download({
295
303
  urls,
@@ -305,7 +313,7 @@ export function createDamUseCases(dependencies) {
305
313
  },
306
314
  async rename({ input, access, signal }) {
307
315
  signal.throwIfAborted();
308
- assertAssetId(input.entry_id, "entry_id");
316
+ input = { ...input, entry_id: normalizeDamAssetId(input.entry_id, "entry_id") };
309
317
  if (input.kind !== "asset" && input.kind !== "folder")
310
318
  invalid("asset_or_folder", "kind");
311
319
  if (!nonblank(input.title) || input.title.length > 100)
@@ -370,6 +378,7 @@ export function createDamUseCases(dependencies) {
370
378
  },
371
379
  async move({ input, access, signal }) {
372
380
  signal.throwIfAborted();
381
+ input = { ...input, entry_id: normalizeDamAssetId(input.entry_id, "entry_id") };
373
382
  const operation = await entryOperation({ operation: "move", request: input, access, signal });
374
383
  try {
375
384
  await dependencies.telemetry.stage("verify", async () => {
@@ -406,6 +415,7 @@ export function createDamUseCases(dependencies) {
406
415
  },
407
416
  async copy({ input, access, signal }) {
408
417
  signal.throwIfAborted();
418
+ input = { ...input, entry_id: normalizeDamAssetId(input.entry_id, "entry_id") };
409
419
  const operation = await entryOperation({ operation: "copy", request: input, access, signal });
410
420
  const result = {
411
421
  source_entry_id: input.entry_id,
@@ -421,7 +431,7 @@ export function createDamUseCases(dependencies) {
421
431
  },
422
432
  async get({ input, access, signal }) {
423
433
  signal.throwIfAborted();
424
- assertAssetId(input.asset_id);
434
+ input = { ...input, asset_id: normalizeDamAssetId(input.asset_id) };
425
435
  return dependencies.telemetry.stage("request", async () => {
426
436
  const result = await dependencies.api.getAsset({
427
437
  assetId: input.asset_id,
@@ -462,7 +472,7 @@ export function createDamUseCases(dependencies) {
462
472
  },
463
473
  async delete({ input, access, signal }) {
464
474
  signal.throwIfAborted();
465
- assertAssetId(input.asset_id);
475
+ input = { ...input, asset_id: normalizeDamAssetId(input.asset_id) };
466
476
  const [repository] = await dependencies.telemetry.stage("repository", () => (resolveRepositories({
467
477
  ...(input.repositoryId === undefined ? {} : { repositoryId: input.repositoryId })
468
478
  }, access, signal)));
@@ -20,7 +20,7 @@ export function createTaskStore(options) {
20
20
  function file(scope, id) {
21
21
  if (!/^[a-f0-9]{64}$/u.test(scope) || !validTaskId(id))
22
22
  throw new LocalFileError(undefined);
23
- return createLocalJsonFile({ directory: join(root, scope), filename: `${id}.json` });
23
+ return createLocalJsonFile({ directory: join(root, scope), filename: `${id}.json`, role: "task" });
24
24
  }
25
25
  const store = {
26
26
  async read(scope, id) {
@@ -52,7 +52,7 @@ export function createTaskStore(options) {
52
52
  if (record.progress[key] !== undefined && typeof record.progress[key] !== "string")
53
53
  throw new Error();
54
54
  }
55
- for (const key of ["submissionStarted", "detached", "accepted"]) {
55
+ for (const key of ["submissionStarted", "detached", "accepted", "agentUsageModelMissing"]) {
56
56
  if (record.progress[key] !== undefined && typeof record.progress[key] !== "boolean")
57
57
  throw new Error();
58
58
  }
@@ -68,7 +68,7 @@ export function createTaskStore(options) {
68
68
  const previous = await store.read(scope, record.task.taskId);
69
69
  if (previous) {
70
70
  record.progress = { ...previous.progress, ...record.progress };
71
- for (const key of ["accepted", "submissionStarted", "detached"]) {
71
+ for (const key of ["accepted", "submissionStarted", "detached", "agentUsageModelMissing"]) {
72
72
  if (previous.progress[key])
73
73
  record.progress[key] = true;
74
74
  }
@@ -88,7 +88,7 @@ export function createTaskStore(options) {
88
88
  }
89
89
  options.validate(record.task);
90
90
  await file(scope, record.task.taskId).writeTextAtomically(`${JSON.stringify(record)}\n`);
91
- });
91
+ }, { action: "task_write" });
92
92
  },
93
93
  async update(scope, id, change) {
94
94
  file(scope, id);
@@ -100,7 +100,7 @@ export function createTaskStore(options) {
100
100
  options.validate(record.task);
101
101
  await file(scope, id).writeTextAtomically(`${JSON.stringify(record)}\n`);
102
102
  return record;
103
- });
103
+ }, { action: "task_update" });
104
104
  },
105
105
  async list(scope) {
106
106
  let names;
@@ -1,5 +1,6 @@
1
1
  import { fork } from "node:child_process";
2
2
  import { safeFailureSummary } from "../../telemetry/failure-summary.js";
3
+ import { validTaskId } from "./store.js";
3
4
  function diagnosticToken(value, pattern) {
4
5
  return typeof value === "string" && pattern.test(value) ? value : undefined;
5
6
  }
@@ -65,55 +66,102 @@ export class TaskBackgroundError extends Error {
65
66
  this.diagnostics = safe;
66
67
  }
67
68
  }
69
+ export function taskWorkerUnavailableError(options) {
70
+ const diagnosticSummary = {
71
+ workerPhase: options.phase,
72
+ ...(options.pid === undefined ? {} : { workerPid: options.pid }),
73
+ ...(options.exitCode === undefined ? {} : { workerExitCode: options.exitCode }),
74
+ ...(options.signal === undefined ? {} : { workerSignal: options.signal })
75
+ };
76
+ const diagnostics = taskWorkerDiagnostics(options.cause ?? new Error("Background process unavailable."), {
77
+ outcome: "failure", diagnosticReason: "TASK_WORKER_UNAVAILABLE", diagnosticSummary
78
+ }, `worker.${options.phase}`);
79
+ const systemCode = diagnostics.causes?.find(cause => cause.system_code)?.system_code;
80
+ if (systemCode)
81
+ diagnostics.diagnostic_summary = safeFailureSummary({ ...diagnosticSummary, systemCode }) ?? {};
82
+ return new TaskBackgroundError({
83
+ code: "TASK_WORKER_UNAVAILABLE",
84
+ message: options.product === "insmind"
85
+ ? "The background process did not return a receipt. Check task list/get before submitting again."
86
+ : "后台进程未返回受理回执。请先用 task list/get 查询,勿重复提交。",
87
+ ...(options.taskId && validTaskId(options.taskId) ? { details: { cli_task_id: options.taskId } } : {})
88
+ }, 1, diagnostics);
89
+ }
68
90
  export function createTaskBackgroundLauncher(options) {
69
91
  return {
70
92
  submit(job, signal, started) {
71
93
  signal.throwIfAborted();
72
94
  return new Promise((resolve, reject) => {
73
- const child = fork(options.workerPath, [], {
74
- detached: true,
75
- stdio: ["ignore", "ignore", "ignore", "ipc"],
76
- execArgv: [],
77
- env: { ...process.env, ...options.env }
78
- });
95
+ let child;
96
+ try {
97
+ child = (options.fork ?? fork)(options.workerPath, [], {
98
+ detached: true,
99
+ stdio: ["ignore", "ignore", "ignore", "ipc"],
100
+ execArgv: [],
101
+ env: { ...process.env, ...options.env }
102
+ });
103
+ }
104
+ catch (cause) {
105
+ reject(taskWorkerUnavailableError({ product: job.product, phase: "spawn", cause }));
106
+ return;
107
+ }
79
108
  let settled = false;
109
+ let taskId;
110
+ let disconnectTimer;
80
111
  const finish = (result) => {
81
112
  if (settled)
82
113
  return;
83
114
  settled = true;
115
+ clearTimeout(disconnectTimer);
84
116
  signal.removeEventListener("abort", aborted);
85
117
  // The one-task worker owns the request after handoff, including when
86
118
  // the caller is interrupted or loses the receipt.
87
- if (child.connected)
88
- child.disconnect();
119
+ try {
120
+ if (child.connected)
121
+ child.disconnect();
122
+ }
123
+ catch { /* Teardown cannot replace the receipt or original failure. */ }
89
124
  child.unref();
90
125
  if (result instanceof Error)
91
126
  reject(result);
92
127
  else
93
128
  resolve(result);
94
129
  };
95
- const unavailable = () => finish(new TaskBackgroundError({
96
- code: "TASK_WORKER_UNAVAILABLE",
97
- message: job.product === "insmind"
98
- ? "The background process did not return a receipt. Check task list/get before submitting again."
99
- : "后台进程未返回受理回执。请先用 task list/get 查询,勿重复提交。"
100
- }));
130
+ const unavailable = (phase, cause, exitCode, signal) => finish(taskWorkerUnavailableError({ product: job.product, phase, cause,
131
+ ...(child.pid === undefined ? {} : { pid: child.pid }),
132
+ ...(taskId === undefined ? {} : { taskId }),
133
+ ...(exitCode === null || exitCode === undefined ? {} : { exitCode }),
134
+ ...(signal ? { signal } : {}) }));
101
135
  const aborted = () => finish(signal.reason instanceof Error ? signal.reason : new Error("SIGINT"));
102
- child.on("error", unavailable);
103
- child.once("exit", unavailable);
136
+ child.on("error", cause => unavailable(child.pid === undefined ? "spawn" : taskId ? "before_accepted" : "before_started", cause));
137
+ child.once("exit", (code, signal) => unavailable(taskId ? "before_accepted" : "before_started", undefined, code, signal));
138
+ child.once("disconnect", () => {
139
+ if (settled)
140
+ return;
141
+ // Node can close IPC just before emitting exit. Allow that terminal
142
+ // event a bounded turn so its actual code/signal is not lost.
143
+ disconnectTimer = setTimeout(() => unavailable("ipc_disconnect"), 100);
144
+ });
104
145
  child.on("message", (message) => {
105
146
  if (settled)
106
147
  return;
107
- if (message.type === "started")
148
+ if (message.type === "started") {
149
+ taskId = message.task.taskId;
108
150
  started(message.task);
151
+ }
109
152
  else if (message.type === "accepted")
110
153
  finish(message.task);
111
154
  else if (message.type === "error")
112
155
  finish(new TaskBackgroundError(message.failure, message.exitCode, message.diagnostics));
113
156
  });
114
157
  signal.addEventListener("abort", aborted, { once: true });
115
- child.send(job, error => { if (error)
116
- unavailable(); });
158
+ try {
159
+ child.send(job, error => { if (error)
160
+ unavailable("ipc_send", error); });
161
+ }
162
+ catch (error) {
163
+ unavailable("ipc_send", error);
164
+ }
117
165
  });
118
166
  }
119
167
  };
@@ -58,13 +58,24 @@ export function createTaskUseCases(dependencies) {
58
58
  const telemetry = dependencies.telemetry;
59
59
  let pendingOutput;
60
60
  const warnedTasks = new Set();
61
+ const warnedUsageTasks = new Set();
61
62
  const stage = (name, run) => telemetry ? telemetry.stage(name, run) : run();
62
- function cacheWarning(id) {
63
+ async function warn(stageName, message) {
64
+ await stage(stageName, async () => { (dependencies.warning ?? dependencies.notice)(message); }).catch(() => undefined);
65
+ }
66
+ async function cacheWarning(id) {
63
67
  if (warnedTasks.has(id))
64
68
  return;
65
69
  warnedTasks.add(id);
66
70
  telemetry?.annotate({ warning_codes: ["TASK_CACHE_UNAVAILABLE"] });
67
- (dependencies.warning ?? dependencies.notice)(text(`任务 ${id} 的本地记录未能保存,task get 可能无法恢复。请保留本次输出,不要重新提交创作。`, `The local record for task ${id} could not be saved; task get may not recover it. Keep this output and do not submit the creation again.`));
71
+ await warn("task.cache_warning", text(`任务 ${id} 的本地记录未能保存,task get 可能无法恢复。请保留本次输出,不要重新提交创作。`, `The local record for task ${id} could not be saved; task get may not recover it. Keep this output and do not submit the creation again.`));
72
+ }
73
+ async function usageWarning(id, incomplete) {
74
+ if (!incomplete || warnedUsageTasks.has(id))
75
+ return;
76
+ warnedUsageTasks.add(id);
77
+ telemetry?.annotate({ warning_codes: ["AGENT_USAGE_MODEL_MISSING"] });
78
+ await warn("task.usage_warning", text("已保留创作结果和服务端确认的实际费用;部分计费明细缺少模型标识,未推断模型或费用。请勿重复提交创作。", "The creation result and confirmed actual charges are retained. Some charge details have no model identifier; no model or fee was inferred. Do not submit the creation again."));
68
79
  }
69
80
  async function fact(scope, record, state, at, error) {
70
81
  if (!telemetry || !record.telemetry)
@@ -185,6 +196,7 @@ export function createTaskUseCases(dependencies) {
185
196
  if (error instanceof TaskStoreError)
186
197
  error.context = { cli_task_id: record.task.taskId, phase,
187
198
  request_sent: dispatched, accepted: record.progress.accepted === true || !!record.progress.remoteTaskId,
199
+ acceptance_durable: durableAcceptance,
188
200
  result_state: record.task.state };
189
201
  return error;
190
202
  }
@@ -223,6 +235,10 @@ export function createTaskUseCases(dependencies) {
223
235
  return;
224
236
  }
225
237
  Object.assign(record.progress, withoutResourceKeys(progress));
238
+ telemetry?.annotate({ diagnostic_summary: {
239
+ ...(progress.contextId ? { agentContextId: progress.contextId } : {}),
240
+ ...(progress.localMessageId ? { localMessageId: progress.localMessageId } : {})
241
+ } });
226
242
  if (progress.contextId)
227
243
  record.task.contextId = progress.contextId;
228
244
  try {
@@ -232,7 +248,7 @@ export function createTaskUseCases(dependencies) {
232
248
  if (!(error instanceof LocalFileError) || !dispatched || (input.executionMode === "async" && !durableAcceptance)) {
233
249
  throw storageContext(error, dispatched ? "after_dispatch" : "before_dispatch");
234
250
  }
235
- cacheWarning(record.task.taskId);
251
+ await cacheWarning(record.task.taskId);
236
252
  return;
237
253
  }
238
254
  durableAcceptance ||= record.progress.accepted === true || !!record.progress.remoteTaskId;
@@ -252,7 +268,7 @@ export function createTaskUseCases(dependencies) {
252
268
  if (!(error instanceof LocalFileError) || record.task.state !== "completed" || input.executionMode === "async") {
253
269
  throw storageContext(error, "final_persist");
254
270
  }
255
- cacheWarning(record.task.taskId);
271
+ await cacheWarning(record.task.taskId);
256
272
  }
257
273
  return { task: record.task, result, record };
258
274
  }
@@ -286,6 +302,8 @@ export function createTaskUseCases(dependencies) {
286
302
  if (dispatched && !observationOnly && record.task.state !== "completed")
287
303
  await fact(scope, record, "failed", dependencies.now().getTime(), error);
288
304
  await stage("task.persist", save).catch(() => undefined);
305
+ if (error instanceof TaskStoreError && error.context)
306
+ error.context.result_state = record.task.state;
289
307
  throw error;
290
308
  }
291
309
  }
@@ -301,6 +319,7 @@ export function createTaskUseCases(dependencies) {
301
319
  if (input.executionMode !== "async") {
302
320
  pendingOutput = { scope: taskScope(input.state), record: execution.record };
303
321
  }
322
+ await usageWarning(execution.task.taskId, execution.record.progress.agentUsageModelMissing === true);
304
323
  return execution.result;
305
324
  },
306
325
  async submit(input) {
@@ -328,16 +347,23 @@ export function createTaskUseCases(dependencies) {
328
347
  }));
329
348
  }
330
349
  record = withoutResourceKeys(record);
350
+ telemetry?.annotate({ diagnostic_summary: {
351
+ ...(record.progress.contextId ? { agentContextId: record.progress.contextId } : {}),
352
+ ...(record.progress.localMessageId ? { localMessageId: record.progress.localMessageId } : {})
353
+ } });
331
354
  telemetry?.annotate({ cli_task_id: id, result_state: record.task.state });
332
355
  if (record.task.state === "completed" && record.task.result) {
333
356
  const result = { ...record.task, result: await stage("task.authorize", () => dependencies.recovery.authorize(record.task.result, state, signal)) };
334
357
  pendingOutput = { scope, record };
358
+ await usageWarning(id, record.progress.agentUsageModelMissing === true);
335
359
  return result;
336
360
  }
337
361
  const task = summary(record);
338
362
  if (task.state === "failed" || (task.state === "running" && !record.progress.detached))
339
363
  return task;
340
- const { failure, ...recovered } = await stage("task.recover", () => dependencies.recovery[task.operation === "agent.send" ? "agent" : "tool"](record.progress, state, signal));
364
+ const { failure, usageModelMissing, ...recovered } = await stage("task.recover", () => dependencies.recovery[task.operation === "agent.send" ? "agent" : "tool"](record.progress, state, signal));
365
+ if (usageModelMissing)
366
+ record.progress.agentUsageModelMissing = true;
341
367
  const { note: _note, ...metadata } = task;
342
368
  const result = { ...metadata, ...recovered };
343
369
  if (result.state === "unknown" && task.note) {
@@ -361,11 +387,13 @@ export function createTaskUseCases(dependencies) {
361
387
  catch (error) {
362
388
  if (!(error instanceof LocalFileError) || result.state !== "completed" || !result.result)
363
389
  throw error;
364
- cacheWarning(id);
390
+ await cacheWarning(id);
365
391
  }
366
392
  }
367
393
  if (result.state === "completed" && result.result)
368
394
  pendingOutput = { scope, record };
395
+ if (result.result ?? result.partialResult)
396
+ await usageWarning(id, record.progress.agentUsageModelMissing === true);
369
397
  return result;
370
398
  },
371
399
  async outputCompleted() {
@@ -2,62 +2,115 @@ import { readFile, mkdtemp, writeFile, rm } from "node:fs/promises";
2
2
  import { tmpdir } from "node:os";
3
3
  import { join } from "node:path";
4
4
  import { pathToFileURL } from "node:url";
5
- import { inspectUploadFile } from "../../platform/safe-upload-file.js";
5
+ import { inspectUploadFile, LocalFileInputError } from "../../platform/safe-upload-file.js";
6
+ import { uriShape } from "../../platform/input-uri.js";
6
7
  import { parseSafeRemoteAssetUrl } from "../../platform/url-safety.js";
7
8
  import { RemoteProtocolError } from "../../platform/remote-protocol.js";
9
+ import { RemoteRequestError } from "../../platform/signed-http-transport.js";
8
10
  import { ToolInputError } from "./catalog.js";
11
+ function responseDiagnostics(url, redirectCount, headers) {
12
+ const requestId = ["x-request-id", "x-gd-request-id", "request-id"]
13
+ .map(name => headers?.get(name)).find((value) => typeof value === "string" && /^[A-Za-z0-9._:-]{1,128}$/u.test(value));
14
+ return {
15
+ ...(url.hostname.length <= 253 ? { mediaHost: url.hostname } : {}),
16
+ redirectCount, mediaBytesRead: 0, ...(requestId ? { requestId } : {})
17
+ };
18
+ }
19
+ function mediaFailure(phase, summary, status, cause) {
20
+ return new RemoteRequestError(status, false, {}, cause, `MEDIA_${phase.toUpperCase()}_FAILED`, { ...summary, mediaPhase: phase });
21
+ }
9
22
  export function createCanvasMedia(dependencies) {
10
- async function read(uri, signal, limit = 64 * 1024 * 1024) {
23
+ async function readWithEvidence(uri, signal, limit = 64 * 1024 * 1024) {
11
24
  signal.throwIfAborted();
12
25
  if (uri.startsWith("file:")) {
13
26
  const file = await inspectUploadFile({ url: uri, signal });
14
27
  if (file.size > limit)
15
28
  throw new ToolInputError("media_too_large", "/arguments");
16
- return readFile(file.filePath, { signal });
29
+ try {
30
+ const bytes = await readFile(file.filePath, { signal });
31
+ return { bytes, summary: { ...uriShape(uri), mediaPhase: "read", mediaBytesRead: bytes.length } };
32
+ }
33
+ catch (cause) {
34
+ if (signal.aborted)
35
+ throw signal.reason;
36
+ throw new LocalFileInputError(cause, "file_read_failed", { ...uriShape(uri), mediaPhase: "read" });
37
+ }
17
38
  }
18
39
  let url = parseSafeRemoteAssetUrl(uri);
19
40
  for (let redirects = 0; redirects <= 5; redirects++) {
20
- const response = await dependencies.fetch(url, { redirect: "manual", signal });
41
+ let response;
42
+ try {
43
+ response = await dependencies.fetch(url, { redirect: "manual", signal });
44
+ }
45
+ catch (cause) {
46
+ if (signal.aborted)
47
+ throw signal.reason;
48
+ throw mediaFailure("request", responseDiagnostics(url, redirects), undefined, cause);
49
+ }
50
+ signal.throwIfAborted();
51
+ const summary = responseDiagnostics(url, redirects, response.headers);
21
52
  if ([301, 302, 303, 307, 308].includes(response.status)) {
22
53
  const location = response.headers.get("location");
23
- await response.body?.cancel();
54
+ await response.body?.cancel().catch(() => undefined);
24
55
  if (!location || redirects === 5)
25
- throw new RemoteProtocolError();
26
- url = parseSafeRemoteAssetUrl(new URL(location, url).href);
56
+ throw mediaFailure("redirect", summary, response.status);
57
+ try {
58
+ url = parseSafeRemoteAssetUrl(new URL(location, url).href);
59
+ }
60
+ catch (cause) {
61
+ throw mediaFailure("redirect", summary, response.status, cause);
62
+ }
27
63
  continue;
28
64
  }
29
- if (!response.ok || !response.body)
30
- throw new RemoteProtocolError();
65
+ if (!response.ok) {
66
+ await response.body?.cancel().catch(() => undefined);
67
+ throw mediaFailure("request", summary, response.status);
68
+ }
69
+ if (!response.body)
70
+ throw mediaFailure("read", summary, response.status);
31
71
  if (Number(response.headers.get("content-length")) > limit) {
32
- await response.body.cancel();
33
- throw new ToolInputError("media_too_large", "/arguments");
72
+ await response.body.cancel().catch(() => undefined);
73
+ throw Object.assign(new ToolInputError("media_too_large", "/arguments"), { diagnosticSummary: { ...summary, mediaPhase: "read" } });
34
74
  }
35
- const reader = response.body.getReader();
36
75
  const chunks = [];
37
76
  let size = 0;
38
77
  try {
39
- while (true) {
40
- const { value, done } = await reader.read();
41
- if (done)
42
- break;
43
- size += value.byteLength;
44
- if (size > limit)
45
- throw new ToolInputError("media_too_large", "/arguments");
46
- chunks.push(Buffer.from(value));
78
+ const reader = response.body.getReader();
79
+ try {
80
+ while (true) {
81
+ const { value, done } = await reader.read();
82
+ if (done)
83
+ break;
84
+ size += value.byteLength;
85
+ if (size > limit)
86
+ throw new ToolInputError("media_too_large", "/arguments");
87
+ chunks.push(Buffer.from(value));
88
+ }
89
+ }
90
+ finally {
91
+ await reader.cancel().catch(() => undefined);
92
+ reader.releaseLock();
47
93
  }
48
94
  }
49
- finally {
50
- await reader.cancel().catch(() => undefined);
51
- reader.releaseLock();
95
+ catch (cause) {
96
+ if (signal.aborted)
97
+ throw signal.reason;
98
+ const evidence = { ...summary, mediaPhase: "read", mediaBytesRead: Math.min(size, 64 * 1024 * 1024) };
99
+ if (cause instanceof ToolInputError)
100
+ throw Object.assign(cause, { diagnosticSummary: evidence });
101
+ throw mediaFailure("read", evidence, response.status, cause);
52
102
  }
53
- return Buffer.concat(chunks);
103
+ return { bytes: Buffer.concat(chunks), summary: { ...summary, mediaPhase: "read", mediaBytesRead: size }, status: response.status };
54
104
  }
55
- throw new RemoteProtocolError();
105
+ throw mediaFailure("redirect", responseDiagnostics(url, 5));
106
+ }
107
+ async function read(uri, signal, limit) {
108
+ return (await readWithEvidence(uri, signal, limit)).bytes;
56
109
  }
57
110
  async function image(uri, signal) {
111
+ const { bytes: raw, summary, status } = await readWithEvidence(uri, signal);
58
112
  try {
59
113
  const { default: sharp } = await import("sharp");
60
- const raw = await read(uri, signal);
61
114
  const metadata = await sharp(raw, { limitInputPixels: 64 * 1024 * 1024 }).metadata();
62
115
  if ((metadata.pages ?? 1) !== 1)
63
116
  throw new ToolInputError("animated_image_not_supported", "/arguments/image");
@@ -69,7 +122,9 @@ export function createCanvasMedia(dependencies) {
69
122
  throw signal.reason;
70
123
  if (cause instanceof ToolInputError)
71
124
  throw cause;
72
- throw new ToolInputError("image_decode_failed", "/arguments/image", [], cause);
125
+ throw Object.assign(new ToolInputError("image_decode_failed", "/arguments/image", [], cause), {
126
+ ...(status === undefined ? {} : { status }), diagnosticSummary: { ...summary, mediaPhase: "decode" }
127
+ });
73
128
  }
74
129
  }
75
130
  async function upload(bytes, extension, access, signal) {
@@ -1,7 +1,8 @@
1
1
  import { Ajv2020 } from "ajv/dist/2020.js";
2
2
  import addFormatsImport, {} from "ajv-formats";
3
3
  import { canvasControlParameterNames } from "./canvas-models.js";
4
- import { validationIssues } from "../../platform/schema-issues.js";
4
+ import { inputValidationSummary, validationIssues } from "../../platform/schema-issues.js";
5
+ import { canonicalizeInputFileUris } from "../../platform/input-uri.js";
5
6
  import { ToolInputError } from "./catalog.js";
6
7
  function parameterSchema(parameter, includeBounds = false) {
7
8
  const common = {
@@ -143,11 +144,14 @@ function controlArgumentsValidator(model) {
143
144
  }
144
145
  export function assertModelArguments(model, value) {
145
146
  const validate = validator(model);
146
- if (!validate(value))
147
- throw new ToolInputError("model_parameters", "/arguments", validationIssues(validate.errors));
147
+ canonicalizeInputFileUris(value, validate.schema);
148
+ if (!validate(value)) {
149
+ const issues = validationIssues(validate.errors, value, validate.schema);
150
+ throw Object.assign(new ToolInputError("model_parameters", "/arguments", issues), { diagnosticSummary: inputValidationSummary(issues, value, "/arguments") });
151
+ }
148
152
  const stepIssues = sliderStepIssues(model, value);
149
153
  if (stepIssues.length) {
150
- throw new ToolInputError("model_parameters", "/arguments", stepIssues);
154
+ throw Object.assign(new ToolInputError("model_parameters", "/arguments", stepIssues), { diagnosticSummary: inputValidationSummary(stepIssues, value, "/arguments") });
151
155
  }
152
156
  }
153
157
  function sliderStepIssues(model, value) {