@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
@@ -2,6 +2,7 @@ import { RemoteRequestError } from "../../platform/signed-http-transport.js";
2
2
  import { RemoteProtocolError } from "../../platform/remote-protocol.js";
3
3
  import { parseSafeRemoteAssetUrl, UrlSafetyError } from "../../platform/url-safety.js";
4
4
  import { projectDamAssetDetail, projectDamAssetSummary } from "./asset-projection.js";
5
+ import { normalizeDamAssetId } from "./input.js";
5
6
  export class DamAssetNotFoundError extends Error {
6
7
  constructor() {
7
8
  super("DAM 素材不存在。");
@@ -9,9 +10,13 @@ export class DamAssetNotFoundError extends Error {
9
10
  }
10
11
  }
11
12
  export class DamAssetNotDownloadableError extends Error {
13
+ diagnosticSummary;
14
+ status;
12
15
  diagnosticReason = "ASSET_DOWNLOAD_URL_MISSING";
13
- constructor() {
16
+ constructor(diagnosticSummary = {}, status) {
14
17
  super("该 DAM 素材当前不可下载。");
18
+ this.diagnosticSummary = diagnosticSummary;
19
+ this.status = status;
15
20
  this.name = "DamAssetNotDownloadableError";
16
21
  }
17
22
  }
@@ -128,13 +133,17 @@ function tagRows(value) {
128
133
  }];
129
134
  });
130
135
  }
131
- function downloadUrls(value) {
136
+ function downloadUrls(value, headers, status) {
132
137
  if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) {
133
138
  throw new RemoteProtocolError();
134
139
  }
135
140
  const urls = value.filter((item) => (typeof item === "string" && item.trim() !== ""));
136
- if (urls.length === 0)
137
- throw new DamAssetNotDownloadableError();
141
+ if (urls.length === 0) {
142
+ const requestId = ["x-request-id", "x-gd-request-id", "request-id"]
143
+ .map(name => headers.get(name)).find((value) => value !== null && /^[A-Za-z0-9._:-]{1,128}$/u.test(value));
144
+ throw new DamAssetNotDownloadableError({ downloadPhase: "url_lookup", downloadUrlCount: 0,
145
+ ...(requestId === undefined ? {} : { requestId }) }, status);
146
+ }
138
147
  for (const value of urls) {
139
148
  try {
140
149
  const url = parseSafeRemoteAssetUrl(value);
@@ -346,7 +355,7 @@ function requestContext(input) {
346
355
  function recycleBody(input) {
347
356
  return {
348
357
  repository_id: input.repositoryId,
349
- file_ids: [input.assetId],
358
+ file_ids: [normalizeDamAssetId(input.assetId)],
350
359
  folder_ids: []
351
360
  };
352
361
  }
@@ -418,12 +427,13 @@ export function createDamApiAdapter(dependencies) {
418
427
  return { repository_id: input.repositoryId, tags: tagRows(response) };
419
428
  },
420
429
  async getDownloadUrls(input) {
421
- const response = await dependencies.transport.getJson({
422
- path: `/dam/asset/files/download/${encodeURIComponent(input.assetId)}/url-list`,
430
+ const assetId = normalizeDamAssetId(input.assetId);
431
+ const response = await dependencies.transport.getJsonResponse({
432
+ path: `/dam/asset/files/download/${encodeURIComponent(assetId)}/url-list`,
423
433
  query: { repository_id: input.repositoryId },
424
434
  ...requestContext(input)
425
435
  });
426
- return downloadUrls(response);
436
+ return downloadUrls(response.body, response.headers, response.status);
427
437
  },
428
438
  async getFolder(input) {
429
439
  let response;
@@ -443,12 +453,13 @@ export function createDamApiAdapter(dependencies) {
443
453
  return folderDetail(response);
444
454
  },
445
455
  async renameEntry(input) {
456
+ const entryId = input.kind === "asset" ? normalizeDamAssetId(input.entryId, "entry_id") : input.entryId;
446
457
  await dependencies.transport.putJson({
447
458
  path: input.kind === "asset"
448
- ? `/dam/asset/${encodeURIComponent(input.entryId)}/rename`
459
+ ? `/dam/asset/${encodeURIComponent(entryId)}/rename`
449
460
  : `/dam/folders/${encodeURIComponent(input.entryId)}/rename`,
450
461
  body: {
451
- id: input.entryId,
462
+ id: entryId,
452
463
  repository_id: input.repositoryId,
453
464
  title: input.title
454
465
  },
@@ -458,11 +469,12 @@ export function createDamApiAdapter(dependencies) {
458
469
  async submitEntryOperation(input) {
459
470
  assertSingleOperationInput(input);
460
471
  const asset = input.kind === "asset";
472
+ const entryId = asset ? normalizeDamAssetId(input.entryId, "entry_id") : input.entryId;
461
473
  const body = asset
462
474
  ? {
463
475
  source_infos: [{
464
476
  source_repository_id: input.sourceRepositoryId,
465
- content_ids: [input.entryId]
477
+ content_ids: [entryId]
466
478
  }],
467
479
  target_folder_id: input.targetFolderId,
468
480
  target_repository_id: input.targetRepositoryId,
@@ -500,10 +512,11 @@ export function createDamApiAdapter(dependencies) {
500
512
  return operationChildren(response);
501
513
  },
502
514
  async getAsset(input) {
515
+ const assetId = normalizeDamAssetId(input.assetId);
503
516
  let response;
504
517
  try {
505
518
  response = await dependencies.transport.getJson({
506
- path: `/dam/asset/${encodeURIComponent(input.assetId)}`,
519
+ path: `/dam/asset/${encodeURIComponent(assetId)}`,
507
520
  ...requestContext(input)
508
521
  });
509
522
  }
@@ -513,7 +526,7 @@ export function createDamApiAdapter(dependencies) {
513
526
  }
514
527
  throw error;
515
528
  }
516
- const asset = projectDamAssetDetail(response, input.assetId);
529
+ const asset = projectDamAssetDetail(response, assetId);
517
530
  if (asset === undefined)
518
531
  throw new RemoteRequestError();
519
532
  return asset;
@@ -527,9 +540,10 @@ export function createDamApiAdapter(dependencies) {
527
540
  return assetId(response);
528
541
  },
529
542
  async createMaterial(input) {
543
+ const body = { ...input.body, asset_info: { ...input.body.asset_info, id: normalizeDamAssetId(input.body.asset_info.id) } };
530
544
  const response = await dependencies.transport.postJson({
531
545
  path: "/dam/asset/createMaterial",
532
- body: input.body,
546
+ body,
533
547
  ...requestContext(input)
534
548
  });
535
549
  const asset = projectDamAssetDetail(response, input.fallback);
@@ -538,9 +552,10 @@ export function createDamApiAdapter(dependencies) {
538
552
  return asset;
539
553
  },
540
554
  async getBatchStatus(input) {
555
+ const assetId = normalizeDamAssetId(input.assetId);
541
556
  const response = await dependencies.transport.getJson({
542
557
  path: "/dam/asset/batch-status",
543
- query: { ids: input.assetId },
558
+ query: { ids: assetId },
544
559
  ...requestContext(input)
545
560
  });
546
561
  return projectDamAssetDetail(response, input.fallback) ?? null;
@@ -0,0 +1,23 @@
1
+ export class DamInputError extends Error {
2
+ reason;
3
+ field;
4
+ diagnosticSummary;
5
+ constructor(reason = "invalid_value", field) {
6
+ super("DAM 输入不可用。");
7
+ this.reason = reason;
8
+ this.field = field;
9
+ this.name = "DamInputError";
10
+ this.diagnosticSummary = { inputReason: reason, ...(field ? { inputField: `/${field}` } : {}) };
11
+ }
12
+ }
13
+ /** Only machine identifiers tolerate pasted line endings; filenames and text do not. */
14
+ export function normalizeDamAssetId(value, field = "asset_id") {
15
+ if (typeof value !== "string")
16
+ throw new DamInputError("id_required_not_url", field);
17
+ const id = value.replace(/^[ \r\n]+|[ \r\n]+$/gu, "");
18
+ if (/[\u0000-\u001f\u007f-\u009f]/u.test(id))
19
+ throw new DamInputError("identifier_control_character", field);
20
+ if (id.trim() === "" || /^https?:\/\//iu.test(id))
21
+ throw new DamInputError("id_required_not_url", field);
22
+ return id;
23
+ }
@@ -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)
@@ -159,8 +170,8 @@ export function createTaskUseCases(dependencies) {
159
170
  let details;
160
171
  if (input.operation === "agent.send")
161
172
  details = { tool_type: "agent", tool_name: "agent" };
162
- else if (generation?.model && (generation.tool === "image.generate" || generation.tool === "video.generate")) {
163
- const name = generation.tool === "image.generate" ? "AI绘图" : "AI视频生成";
173
+ else if (generation?.model && (generation.tool.startsWith("image.") || generation.tool.startsWith("video."))) {
174
+ const name = generation.tool.startsWith("image.") ? "AI绘图" : "AI视频生成";
164
175
  details = { tool_type: name, tool_name: name, model_name: generation.model };
165
176
  }
166
177
  else
@@ -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
  }
@@ -222,7 +234,11 @@ export function createTaskUseCases(dependencies) {
222
234
  await analyticsFact("started");
223
235
  return;
224
236
  }
225
- Object.assign(record.progress, progress);
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) {
@@ -327,16 +346,24 @@ export function createTaskUseCases(dependencies) {
327
346
  stored.task = { ...stored.task, state: "unknown", note: text("尚未取得任务结果。", "The task result has not been received.") };
328
347
  }));
329
348
  }
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
+ } });
330
354
  telemetry?.annotate({ cli_task_id: id, result_state: record.task.state });
331
355
  if (record.task.state === "completed" && record.task.result) {
332
356
  const result = { ...record.task, result: await stage("task.authorize", () => dependencies.recovery.authorize(record.task.result, state, signal)) };
333
357
  pendingOutput = { scope, record };
358
+ await usageWarning(id, record.progress.agentUsageModelMissing === true);
334
359
  return result;
335
360
  }
336
361
  const task = summary(record);
337
362
  if (task.state === "failed" || (task.state === "running" && !record.progress.detached))
338
363
  return task;
339
- 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;
340
367
  const { note: _note, ...metadata } = task;
341
368
  const result = { ...metadata, ...recovered };
342
369
  if (result.state === "unknown" && task.note) {
@@ -360,11 +387,13 @@ export function createTaskUseCases(dependencies) {
360
387
  catch (error) {
361
388
  if (!(error instanceof LocalFileError) || result.state !== "completed" || !result.result)
362
389
  throw error;
363
- cacheWarning(id);
390
+ await cacheWarning(id);
364
391
  }
365
392
  }
366
393
  if (result.state === "completed" && result.result)
367
394
  pendingOutput = { scope, record };
395
+ if (result.result ?? result.partialResult)
396
+ await usageWarning(id, record.progress.agentUsageModelMissing === true);
368
397
  return result;
369
398
  },
370
399
  async outputCompleted() {