@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
@@ -4,12 +4,12 @@ import { TaskNotFoundError } from "../features/task/use-cases.js";
4
4
  import { TaskStoreError } from "../features/task/store.js";
5
5
  import { CommanderError } from "commander";
6
6
  import { AuthExpiredError, AuthRequiredError } from "../features/auth/access-policy.js";
7
- import { AuthStateInvalidError, UserIdentityMissingError } from "../features/auth/state.js";
7
+ import { AuthStateInvalidError, AuthStateUnavailableError, UserIdentityMissingError } from "../features/auth/state.js";
8
8
  import { SsoRequestError } from "../features/auth/sso-service.js";
9
9
  import { AuthorizedAccountContextMissingError, BrowserOpenError, DeviceAuthorizationExpiredError } from "../features/auth/use-cases.js";
10
10
  import { AgentInputError } from "../features/agent/use-cases.js";
11
11
  import { ToolInputError } from "../features/tool/catalog.js";
12
- import { ToolTaskFailedError, ToolTaskCanceledError } from "../features/tool/tool-api-adapter.js";
12
+ import { ToolTaskFailedError, ToolTaskCanceledError, ToolInsufficientCreditsError } from "../features/tool/tool-api-adapter.js";
13
13
  import { AgentAuditRejectedError } from "../features/agent/creative-protocol.js";
14
14
  import { isContentReviewRejection } from "../features/task/creation-refusal.js";
15
15
  import { ObjectStorageUploadError } from "../features/dam/object-storage.js";
@@ -68,7 +68,7 @@ export function mapCliError(error, options) {
68
68
  if (!category)
69
69
  return outcome;
70
70
  // Keep precise input corrections and their fields; general failures have a short user message.
71
- if (category === "input" && ["USAGE_ERROR", "INVALID_ACTIONS"].includes(outcome.failure.code))
71
+ if ((category === "input" || category === "input_asset") && ["USAGE_ERROR", "INVALID_ACTIONS"].includes(outcome.failure.code))
72
72
  return outcome;
73
73
  return { ...outcome, failure: { ...outcome.failure, message: observedErrorMessage(category, evidence) } };
74
74
  }
@@ -108,6 +108,8 @@ function mapBaseCliError(error, options) {
108
108
  return failure("AUTH_EXPIRED", "Authentication expired. Sign out and sign in again.", 1, [`${command} auth logout`, `${command} auth login`]);
109
109
  return failure("AUTH_EXPIRED", "登录已过期,请退出后重新登录。", 1, ["gd-cli auth logout", "gd-cli auth login"]);
110
110
  }
111
+ if (error instanceof AuthStateUnavailableError)
112
+ return failure("AUTH_STATE_UNAVAILABLE", text("无法读取或保存本地登录信息。", "Local sign-in information could not be read or saved."), 1, [text("请检查文件访问权限后重试。", "Check file access permissions and try again.")], { reason: "local_io", system_code: systemErrorCode(error) });
111
113
  if (error instanceof AuthStateInvalidError) {
112
114
  if (error.reason === "local_io")
113
115
  return failure("AUTH_STATE_INVALID", text("无法读写本地凭证,当前无法判断登录是否有效。", "Cannot access local credentials; authentication validity is unknown."), 1, [text("恢复凭证文件的访问权限或宿主文件访问能力;不要执行 logout 或删除凭证。", "Restore access to the credential file or host file permissions; do not log out or delete credentials.")], { reason: error.reason, system_code: systemErrorCode(error) });
@@ -147,12 +149,23 @@ function mapBaseCliError(error, options) {
147
149
  const description = descriptions[error.reason];
148
150
  return failure("USAGE_ERROR", description ? text(...description) : text("创作输入不可用,请核对模型与参数。", "Check the model and creation arguments."), 2, [`${command} model list`, text(`使用 ${command} model get <model> 核对模型参数;素材应使用安全的 HTTP(S) URL 或本地 file URL。`, `Use ${command} model get <model> to inspect parameters; assets require safe HTTP(S) URLs or local file URLs.`)], { reason: error.reason, field: error.field, ...(error instanceof ToolInputError ? { issues: error.issues } : {}) });
149
151
  }
150
- if (error instanceof LocalFileInputError)
151
- return failure("USAGE_ERROR", text("本地素材文件不可用于上传。", "The local asset file cannot be uploaded."), 2, [text("检查文件访问权限、文件类型和声明的 mediaType;受保护路径不可上传。", "Check file access, type and declared mediaType; protected paths cannot be uploaded.")], { reason: error.reason, system_code: systemErrorCode(error) });
152
+ if (error instanceof LocalFileInputError) {
153
+ const message = error.reason === "invalid_file_uri"
154
+ ? text("本地文件地址格式不正确。Windows 地址示例:file:///C:/目录/文件。", "Invalid local file URL. Windows example: file:///C:/folder/file.")
155
+ : error.reason === "file_read_failed" && systemErrorCode(error) === "ENOENT"
156
+ ? text("找不到指定的本地文件,请核对完整路径。", "The local file was not found. Check its full path.")
157
+ : error.reason === "media_type_mismatch"
158
+ ? text("素材类型与文件实际格式不一致,请修正 mediaType 或重新选择文件。", "The mediaType does not match the file format. Correct it or select another file.")
159
+ : text("本地素材文件不可用于上传。", "The local asset file cannot be uploaded.");
160
+ return failure("USAGE_ERROR", message, 2, [text("检查文件访问权限、文件类型和声明的 mediaType;受保护路径不可上传。", "Check file access, type and declared mediaType; protected paths cannot be uploaded.")], { reason: error.reason, system_code: systemErrorCode(error) });
161
+ }
152
162
  if (error instanceof CliUsageError && error.reason === "invalid_task_id")
153
163
  return failure("USAGE_ERROR", text("任务编号不正确,请使用本机任务列表中的 taskId。", "Invalid Task ID. Use a taskId from the local task list."), 2, [`${command} task list`, `${command} task get <taskId>`], { reason: error.reason });
154
164
  if (error instanceof DamInputError)
155
165
  return failure("USAGE_ERROR", text("素材管理参数无效,请根据字段和原因核对命令 --help。", "Invalid asset-management argument; check the field and reason against the command's --help."), 2, undefined, { reason: error.reason, field: error.field });
166
+ if (error instanceof CommanderError && error.code === "commander.unknownOption" && options.operation === "dam.download"
167
+ && /unknown option ['"]--output['"]/u.test(error.message))
168
+ return failure("USAGE_ERROR", text("下载目录请使用 --output-dir <directory>。", "Use --output-dir <directory> to choose the download directory."), 2);
156
169
  if (error instanceof OrgUsageError
157
170
  || error instanceof CliUsageError
158
171
  || error instanceof CommanderError) {
@@ -160,8 +173,8 @@ function mapBaseCliError(error, options) {
160
173
  return failure("USAGE_ERROR", "Invalid command or arguments. See --help.", 2);
161
174
  return failure("USAGE_ERROR", "命令或参数无效,请查看 --help。", 2);
162
175
  }
163
- if (options.product?.id !== "insmind" && options.operation === "tool.call" && isInsufficientCreditsError(error)) {
164
- return failure("INSUFFICIENT_CREDITS", "当前可用额度不足,本次生成未能完成。", 1);
176
+ if (error instanceof ToolInsufficientCreditsError || options.product?.id !== "insmind" && options.operation === "tool.call" && isInsufficientCreditsError(error)) {
177
+ return failure("INSUFFICIENT_CREDITS", text("当前可用额度不足,本次生成未能完成。", "Available credits are insufficient; this creation could not complete."), 1);
165
178
  }
166
179
  if (isContentReviewRejection(error, { product: options.product?.id ?? "gaoding", operation: options.operation })) {
167
180
  const phase = error instanceof AgentAuditRejectedError ? error.phase : undefined;
@@ -256,6 +269,8 @@ function mapBaseCliError(error, options) {
256
269
  }
257
270
  return failure(error.code, redactSensitiveText(error.message).slice(0, 1024), 1, ["写入失败时先检查原作品,不直接重复 apply 或 save;按 editor --help 中的对应错误指引处理。"]);
258
271
  }
272
+ if (systemErrorCode(error) === "ECONNRESET")
273
+ return failure("REMOTE_REQUEST_FAILED", text("连接中断,未能完整收到结果。", "The connection closed before the full result was received."), 1);
259
274
  return failure("INTERNAL_ERROR", insmind ? "The CLI encountered an internal error." : "CLI 发生内部错误。", 1);
260
275
  }
261
276
  function isInsufficientCreditsError(error) {
@@ -270,6 +285,13 @@ export function classifyTelemetryError(error, options = {}) {
270
285
  return { outcome: "failure", errorCode: error.code,
271
286
  ...(error.status === undefined ? {} : { httpStatus: error.status }) };
272
287
  const outcome = mapCliError(error, { ...options, aborted: options.aborted === true });
288
+ if (error instanceof DeviceAuthorizationExpiredError && outcome.kind !== "interrupted")
289
+ return {
290
+ outcome: "failure", errorCode: "REMOTE_REQUEST_FAILED",
291
+ diagnosticReason: error.expirationSource === "server_expired" ? "AUTHORIZATION_SERVER_EXPIRED" : "AUTHORIZATION_WAIT_TIMEOUT",
292
+ ...(error.httpStatus === undefined ? {} : { httpStatus: error.httpStatus }),
293
+ ...(error.expirationSource === "server_expired" ? { remoteErrorCode: "expired_token" } : {})
294
+ };
273
295
  if (error instanceof TaskBackgroundError) {
274
296
  const diagnostics = error.diagnostics;
275
297
  return { outcome: outcome.kind === "interrupted" ? "interrupted" : "failure",
@@ -290,24 +312,27 @@ export function classifyTelemetryError(error, options = {}) {
290
312
  }
291
313
  catch { /* No safe summary available. */ }
292
314
  }
315
+ const inputReason = error instanceof LocalFileInputError ? error.reason
316
+ : error instanceof JsonInputError ? `json_${error.reason}`
317
+ : error instanceof InputContractError ? "schema_validation"
318
+ : error instanceof CliUsageError || error instanceof ToolInputError || error instanceof AgentInputError || error instanceof DamInputError ? error.reason
319
+ : error instanceof CommanderError ? error.code : undefined;
320
+ const systemCode = systemErrorCode(error);
293
321
  const diagnosticSummary = safeFailureSummary({
294
322
  ...localFileSummary(error),
295
323
  ...(error instanceof OutputStreamError ? { outputStream: error.outputStream } : {}),
296
324
  ...(remoteError instanceof SsoRequestError ? remoteError.diagnosticSummary : {}),
297
325
  ...(summary && typeof summary === "object" && !Array.isArray(summary) ? summary : {}),
298
- systemCode: systemErrorCode(error),
299
- inputReason: error instanceof LocalFileInputError ? error.reason
300
- : error instanceof JsonInputError ? `json_${error.reason}`
301
- : error instanceof InputContractError ? "schema_validation"
302
- : error instanceof CliUsageError || error instanceof ToolInputError || error instanceof AgentInputError ? error.reason
303
- : error instanceof CommanderError ? error.code : undefined
326
+ ...nestedDiagnosticSummary(error),
327
+ ...(systemCode ? { systemCode } : {}),
328
+ ...(inputReason ? { inputReason } : {})
304
329
  });
305
330
  return {
306
331
  outcome: outcome.kind === "interrupted" ? "interrupted" : "failure",
307
332
  ...(diagnosticSummary ? { diagnosticSummary } : {}),
308
333
  ...(outcome.kind === "failure" ? { errorCode: outcome.failure.code } : {}),
309
- ...((remoteError instanceof RemoteRequestError || remoteError instanceof SsoRequestError) && remoteError.status !== undefined
310
- ? { httpStatus: remoteError.status }
334
+ ...(httpErrorStatus(error) !== undefined
335
+ ? { httpStatus: httpErrorStatus(error) }
311
336
  : {}),
312
337
  ...(remoteError?.remoteCode === undefined
313
338
  ? {}
@@ -323,6 +348,29 @@ export function classifyTelemetryError(error, options = {}) {
323
348
  ? { diagnosticReason: remoteError.diagnosticReason } : {})
324
349
  };
325
350
  }
351
+ function nestedDiagnosticSummary(error) {
352
+ const facts = {};
353
+ const seen = new Set();
354
+ for (let depth = 0; error instanceof Error && depth < 10 && !seen.has(error); depth++, error = error.cause) {
355
+ seen.add(error);
356
+ if (!("diagnosticSummary" in error))
357
+ continue;
358
+ const summary = safeFailureSummary(error.diagnosticSummary);
359
+ for (const [key, value] of Object.entries(summary ?? {}))
360
+ if (!(key in facts))
361
+ facts[key] = value;
362
+ }
363
+ return facts;
364
+ }
365
+ function httpErrorStatus(error) {
366
+ const seen = new Set();
367
+ for (let depth = 0; error instanceof Error && depth < 10 && !seen.has(error); depth++, error = error.cause) {
368
+ seen.add(error);
369
+ if ("status" in error && typeof error.status === "number" && Number.isInteger(error.status) && error.status >= 100 && error.status <= 599)
370
+ return error.status;
371
+ }
372
+ return undefined;
373
+ }
326
374
  function failure(code, message, exitCode, nextSteps, details) {
327
375
  return {
328
376
  kind: "failure",
@@ -6,7 +6,7 @@ export function registerModelCommands(program, runtime) {
6
6
  .description(text(runtime.product, "创作模型", "Creation models"))
7
7
  .helpCommand(false);
8
8
  const list = model.command("list")
9
- .description(text(runtime.product, "列出图片/视频生成模型(不含独立风格)", "List image/video generation models (excluding standalone styles)"))
9
+ .description(text(runtime.product, "列出当前可用的创作与媒体处理模型(不含独立风格)", "List available creation and media-processing models (excluding standalone styles)"))
10
10
  .option("--tool <tool>", text(runtime.product, "按工具筛选", "filter by tool"))
11
11
  .allowExcessArguments(false);
12
12
  jsonOutput(list);
@@ -32,12 +32,14 @@ export function registerModelCommands(program, runtime) {
32
32
  });
33
33
  }, { operation: "model.list" });
34
34
  const get = model.command("get")
35
- .description(text(runtime.product, "查看模型完整信息", "Show complete model information"))
35
+ .description(text(runtime.product, "查看模型完整信息与输入 Schema", "Show complete model information and input Schema"))
36
36
  .argument("<model>", text(runtime.product, "模型机器标识", "model machine identifier"))
37
+ .option("--tool <tool>", text(runtime.product, "指定模型用途上下文", "select the model's tool context"))
37
38
  .allowExcessArguments(false);
38
39
  get.addHelpText("after", [
39
40
  "",
40
41
  text(runtime.product, "只读查询当前身份可用的 Model,输出 JSON;不提交创作。参数、费用和预估耗时来自实时目录。", "Reads a Model available to the current identity as JSON without submitting creation. Parameters, cost and estimated time come from the live catalog."),
42
+ text(runtime.product, "inputSchema 是选定 Tool + Model 的完整 JSON Schema,包含嵌套对象、数组及约束。同一 Model 用于多个 Tool 时请加 --tool;优先按 inputSchema 构造 Tool 输入。", "inputSchema is the complete JSON Schema for the selected Tool + Model, including nested objects, arrays and constraints. Use --tool when a Model supports multiple Tools; construct Tool input from inputSchema."),
41
43
  text(runtime.product, "parameters 是结构化元数据,不是 JSON Schema:遵守 required/type、minimum/maximum/step,SELECT 使用 options[].value 而非 label。", "parameters is structured metadata, not JSON Schema: follow required/type, minimum/maximum/step, and use SELECT options[].value rather than label."),
42
44
  text(runtime.product, "Tool 调用须显式提供所有 required 字段;用户未指定时显式使用返回的 default。model 标识放入调用参数顶层,与模型参数并列。", "Tool calls explicitly supply every required field, using a returned default when the user omitted it. Include the returned model identifier at the top level alongside its parameters."),
43
45
  text(runtime.product, "usageDescription 说明跨字段组合规则。tool call <tool> --schema 根据 model 校验对应必填字段、可用参数和范围;step 及跨字段规则另见本 Model 元数据。Agent 只传显式生成约束,不照搬 Tool 的完整必填参数。", "usageDescription explains cross-field combinations. tool call <tool> --schema validates required fields, allowed parameters and ranges per model; follow this Model's metadata for step and cross-field rules. For Agent, pass explicit generation constraints rather than copying every Tool-required parameter."),
@@ -49,7 +51,8 @@ export function registerModelCommands(program, runtime) {
49
51
  if (typeof modelName !== "string" || modelName.trim() === "")
50
52
  throw new CliUsageError();
51
53
  runtime.telemetry.annotate({ model_id: modelName });
52
- const input = { model: modelName };
54
+ const selectedTool = get.opts().tool;
55
+ const input = { model: modelName, ...(selectedTool === undefined ? {} : { tool: selectedTool }) };
53
56
  await runtime.telemetry.stage("input", async () => {
54
57
  runtime.validators.modelGetInput(input);
55
58
  });
@@ -76,7 +76,7 @@ export function observedErrorCategory(e) {
76
76
  return "unsupported";
77
77
  if (e.code === "SAVE_FAILED")
78
78
  return "save";
79
- if (e.code === "LOCAL_STATE_ERROR")
79
+ if (["LOCAL_STATE_ERROR", "AUTH_STATE_UNAVAILABLE"].includes(e.code))
80
80
  return "local";
81
81
  if (e.code === "UPDATE_FAILED" && e.diagnosticReason === "UPDATE_MANAGED_BY_HOST")
82
82
  return "managed_update";
@@ -112,6 +112,8 @@ export function observedErrorMessage(category, e) {
112
112
  return text("素材下载未完成。", "The asset download did not complete.");
113
113
  if (category === "local" && e.errorType === "LocalFileError")
114
114
  return text("无法读取或保存所需文件。", "A required file could not be read or saved.");
115
+ if (category === "local" && e.code === "AUTH_STATE_UNAVAILABLE")
116
+ return text("无法读取或保存本地登录信息。", "Local sign-in information could not be read or saved.");
115
117
  if (category === "request" && e.operation === "task.get")
116
118
  return text("本次未能读取任务结果。", "The task result could not be retrieved.");
117
119
  return text(messages[category][0], messages[category][1]);
@@ -37,7 +37,9 @@ export function registerToolCommands(program, runtime) {
37
37
  text(runtime.product, "异步任务由本机后台进程继续等待结果;进程终止或关机可能使状态变为 unknown。", "Async work continues in a local background process; termination or shutdown may leave its state unknown."),
38
38
  text(runtime.product, "用 task get <taskId> 查询原任务;completed 时 result 为完整结果,running/unknown 或查询超时不应重新提交。", "Query the same taskId with task get; completed includes result. Do not resubmit on running, unknown, or a query timeout."),
39
39
  text(runtime.product, "默认等待原 Tool 结果;任务 ID 写入 stderr,stdout 保持原 JSON。", "By default, the command waits for the original Tool result; stderr shows the Task ID and stdout keeps the result JSON."),
40
+ text(runtime.product, "媒体 URI 字段支持 HTTP(S) 与本地 file:// URI;CLI 会按调用上传本地素材,可直接用于原图、参考素材和选区。", "Media URI fields accept HTTP(S) and local file:// URIs; the CLI uploads local inputs for the call, including source media, references and masks."),
40
41
  text(runtime.product, `结果未收到时用 ${runtime.product.commandName} task list 找到调用,再用 ${runtime.product.commandName} task get <id> 查询,不重复生成。`, `If output is missing, use ${runtime.product.commandName} task list and ${runtime.product.commandName} task get <id> to recover it without generating again.`),
42
+ text(runtime.product, "完整结果为 {content,usage}。content 项为 text、resource_link(uri/name/mimeType)或 resource(resource.uri/mimeType/text);OCR 的 resource.text 是 JSON。分层返回原生模板 JSON 链接,不是 PSD;视频处理需检查实际音轨。", "Complete results are {content,usage}. Content items are text, resource_link (uri/name/mimeType), or resource (resource.uri/mimeType/text); OCR resource.text contains JSON. Layer decomposition returns a native template JSON link, not PSD; verify actual audio after video processing."),
41
43
  text(runtime.product, "查询返回同一份 usage;Tool usage.cost 为当次目录预估价格。", "Queries return the same usage; Tool usage.cost is the catalog price estimate for that invocation."),
42
44
  ""
43
45
  ].join("\n"));
@@ -1,4 +1,7 @@
1
1
  import { readFileSync } from "node:fs";
2
2
  export function contractSchema(operation, direction) {
3
- return JSON.parse(readFileSync(new URL(`../../../contracts/operations/${operation}/${direction}.schema.json`, import.meta.url), "utf8"));
3
+ return contractDocument(`${operation}/${direction}.schema.json`);
4
+ }
5
+ export function contractDocument(path) {
6
+ return JSON.parse(readFileSync(new URL(`../../../contracts/operations/${path}`, import.meta.url), "utf8"));
4
7
  }
@@ -1,3 +1,4 @@
1
+ import { withResponseDiagnostics } from "../../platform/signed-http-transport.js";
1
2
  import { buildCreativeRequest, creativeContextId, creativeTurnMessages, normalizeCreativeMessages, restoreCreativeResourceUrls } from "./creative-protocol.js";
2
3
  import { parseCreativeStream } from "./creative-stream.js";
3
4
  export function createCreativeAgentAdapter(dependencies) {
@@ -10,30 +11,55 @@ export function createCreativeAgentAdapter(dependencies) {
10
11
  localMessageId: dependencies.idFactory()
11
12
  }
12
13
  : { localMessageId: dependencies.idFactory() };
14
+ const correlation = {
15
+ localMessageId: ids.localMessageId,
16
+ ...("localThreadId" in ids ? { localThreadId: ids.localThreadId } : {}),
17
+ ...(message.contextId ? { agentContextId: message.contextId } : {})
18
+ };
19
+ dependencies.telemetry.annotate({ diagnostic_summary: correlation });
13
20
  await observe?.({ localMessageId: ids.localMessageId, ...(message.contextId ? { contextId: message.contextId } : {}) });
14
- const { streamed, contextId } = await dependencies.telemetry.stage("execute", async () => {
21
+ const { streamed, contextId } = await dependencies.telemetry.stage("execute", () => withResponseDiagnostics(async (onResponse) => {
15
22
  await observe?.({ submissionStarted: true });
23
+ const startedAt = Date.now();
24
+ let httpStatus;
16
25
  const stream = await dependencies.transport.postStream({
17
26
  path: "/ai-agent/v1/thread/completion",
18
27
  ...(observe ? { onDispatch: (dispatchedAt) => observe({ dispatchedAt }) } : {}),
19
28
  body: buildCreativeRequest(message, ids),
20
29
  accept: "text/event-stream",
30
+ onResponse: (status, summary) => { httpStatus = status; onResponse(status, summary); },
21
31
  credential: access.credential,
22
32
  organizationId: access.organizationId,
23
33
  signal
24
34
  });
25
35
  await observe?.({ accepted: true });
26
- const streamed = await parseCreativeStream(stream, signal, observe ? async (contextId) => observe({ contextId }) : undefined);
27
- return { streamed, contextId: creativeContextId(streamed) };
28
- });
29
- return dependencies.telemetry.stage("result", async () => {
30
- const messages = await dependencies.transport.getJson({
31
- path: `/ai-agent/v1/thread/${encodeURIComponent(contextId)}/messages`,
32
- credential: access.credential,
33
- organizationId: access.organizationId,
34
- signal
36
+ const streamed = await parseCreativeStream(stream, signal, async (contextId) => {
37
+ correlation.agentContextId = contextId;
38
+ dependencies.telemetry.annotate({ diagnostic_summary: { agentContextId: contextId } });
39
+ await observe?.({ contextId });
40
+ }, {
41
+ startedAt, ...(httpStatus === undefined ? {} : { httpStatus }),
42
+ onDiagnostics: diagnostic_summary => dependencies.telemetry.annotate({ diagnostic_summary })
35
43
  });
36
- const output = normalizeCreativeMessages(restoreCreativeResourceUrls(creativeTurnMessages(messages, ids.localMessageId), streamed));
44
+ const contextId = creativeContextId(streamed);
45
+ dependencies.telemetry.annotate({ diagnostic_summary: { agentContextId: contextId } });
46
+ return { streamed, contextId };
47
+ }, correlation));
48
+ return dependencies.telemetry.stage("result", async () => {
49
+ const output = await withResponseDiagnostics(async (onResponse) => {
50
+ const messages = await dependencies.transport.getJson({
51
+ path: `/ai-agent/v1/thread/${encodeURIComponent(contextId)}/messages`,
52
+ credential: access.credential,
53
+ organizationId: access.organizationId,
54
+ onResponse,
55
+ signal
56
+ });
57
+ let usageModelMissing = false;
58
+ const normalized = normalizeCreativeMessages(restoreCreativeResourceUrls(creativeTurnMessages(messages, ids.localMessageId), streamed), () => { usageModelMissing = true; });
59
+ if (usageModelMissing)
60
+ await observe?.({ agentUsageModelMissing: true });
61
+ return normalized;
62
+ }, correlation);
37
63
  return dependencies.resourceAuthorizer
38
64
  ? dependencies.resourceAuthorizer.authorize(output, access, signal)
39
65
  : output;
@@ -203,8 +203,25 @@ function inferMediaType(url) {
203
203
  webp: "image/webp"
204
204
  }[extension ?? ""] ?? "application/octet-stream";
205
205
  }
206
- function functionResponseParts(raw) {
207
- const parsed = parseJson(raw);
206
+ function isBillingMetadataText(text, message) {
207
+ if (message.role !== "function")
208
+ return false;
209
+ const extra = record(message.extra);
210
+ const amount = extra?.deduct_points;
211
+ if (nonEmptyString(extra?.task_id) === undefined
212
+ || nonEmptyString(extra?.scene_code) === undefined
213
+ || typeof amount !== "number" || !Number.isFinite(amount) || amount < 0)
214
+ return false;
215
+ // The Agent appends this exact metadata mirror as tool text. Require matching
216
+ // structured billing evidence; ordinary JSON and assistant text remain intact.
217
+ const fields = record(parseJson(text));
218
+ return fields !== undefined && Object.keys(fields).length === 2
219
+ && fields.deduct_points === amount
220
+ && typeof fields.balance_points === "number"
221
+ && Number.isFinite(fields.balance_points) && fields.balance_points >= 0;
222
+ }
223
+ function functionResponseParts(message) {
224
+ const parsed = parseJson(contentOf(message)?.text);
208
225
  const values = Array.isArray(parsed) ? parsed : parsed === undefined ? [] : [parsed];
209
226
  const parts = [];
210
227
  for (const value of values) {
@@ -212,7 +229,7 @@ function functionResponseParts(raw) {
212
229
  if (item === undefined)
213
230
  continue;
214
231
  const text = nonEmptyString(item.text);
215
- if (text !== undefined)
232
+ if (text !== undefined && !isBillingMetadataText(text, message))
216
233
  parts.push({ text });
217
234
  const url = nonEmptyString(item.uri ?? item.url);
218
235
  if (url === undefined)
@@ -255,7 +272,7 @@ export function restoreCreativeResourceUrls(messages, streamed) {
255
272
  const content = contentOf(message);
256
273
  if (content?.type !== "function_response")
257
274
  continue;
258
- for (const part of functionResponseParts(content.text)) {
275
+ for (const part of functionResponseParts(message)) {
259
276
  if (!("url" in part) || !hasAuthKey(part.url))
260
277
  continue;
261
278
  const identity = resourceUrlIdentity(part.url);
@@ -378,7 +395,7 @@ function dedupeParts(parts) {
378
395
  return true;
379
396
  });
380
397
  }
381
- export function normalizeCreativeMessages(messages) {
398
+ export function normalizeCreativeMessages(messages, onUsageModelMissing) {
382
399
  const contextId = creativeContextId(messages);
383
400
  const latest = new Map();
384
401
  const anonymous = [];
@@ -402,7 +419,7 @@ export function normalizeCreativeMessages(messages) {
402
419
  parts.push({ text });
403
420
  }
404
421
  else if (content.type === "function_response") {
405
- parts.push(...functionResponseParts(content.text));
422
+ parts.push(...functionResponseParts(message));
406
423
  }
407
424
  }
408
425
  else {
@@ -423,6 +440,7 @@ export function normalizeCreativeMessages(messages) {
423
440
  if (publicParts.length === 0)
424
441
  return fail("AGENT_RESULT_EMPTY", { messageCount: normalized.length, publicPartCount: 0 });
425
442
  const usageItems = [];
443
+ let totalCost = 0;
426
444
  for (const message of normalized) {
427
445
  if (contentOf(message)?.type !== "function_response")
428
446
  continue;
@@ -432,11 +450,14 @@ export function normalizeCreativeMessages(messages) {
432
450
  continue;
433
451
  if (typeof amount !== "number" || !Number.isFinite(amount) || amount < 0)
434
452
  return fail();
453
+ totalCost += amount;
454
+ const model = nonEmptyString(extra?.scene_code);
455
+ if (model === undefined) {
456
+ onUsageModelMissing?.();
457
+ continue;
458
+ }
435
459
  if (amount === 0)
436
460
  continue;
437
- const model = nonEmptyString(extra?.scene_code);
438
- if (model === undefined)
439
- return fail("AGENT_USAGE_MODEL_MISSING", { messageCount: normalized.length, publicPartCount: publicParts.length });
440
461
  usageItems.push({ model, cost: { unit: "gaodou", amount } });
441
462
  }
442
463
  return {
@@ -448,7 +469,7 @@ export function normalizeCreativeMessages(messages) {
448
469
  usage: {
449
470
  cost: {
450
471
  unit: "gaodou",
451
- amount: usageItems.reduce((total, item) => total + item.cost.amount, 0)
472
+ amount: totalCost
452
473
  },
453
474
  items: usageItems
454
475
  }
@@ -1,4 +1,5 @@
1
1
  import { RemoteProtocolError } from "../../platform/remote-protocol.js";
2
+ import { RemoteRequestError } from "../../platform/signed-http-transport.js";
2
3
  function isMessage(value) {
3
4
  return value !== null && typeof value === "object" && !Array.isArray(value);
4
5
  }
@@ -87,12 +88,24 @@ function parseSequence(payload) {
87
88
  }
88
89
  return values;
89
90
  }
90
- export async function parseCreativeStream(stream, signal, onContextId) {
91
+ export async function parseCreativeStream(stream, signal, onContextId, diagnostics = {}) {
91
92
  signal.throwIfAborted();
92
93
  const reader = stream.getReader();
93
94
  const decoder = new TextDecoder();
94
95
  let raw = "";
95
96
  let contextReported = false;
97
+ const now = diagnostics.now ?? Date.now;
98
+ const startedAt = diagnostics.startedAt ?? now();
99
+ let receivedBytes = 0;
100
+ let firstByteMs;
101
+ let terminalReason = "canceled";
102
+ const summary = () => ({
103
+ streamHadBytes: receivedBytes > 0,
104
+ streamReceivedBytes: receivedBytes,
105
+ ...(firstByteMs === undefined ? {} : { streamFirstByteMs: firstByteMs }),
106
+ streamTerminalReason: terminalReason,
107
+ abortSource: signal.aborted ? "caller" : "none"
108
+ });
96
109
  const onAbort = () => {
97
110
  void reader.cancel(signal.reason).catch(() => undefined);
98
111
  };
@@ -100,10 +113,25 @@ export async function parseCreativeStream(stream, signal, onContextId) {
100
113
  try {
101
114
  while (true) {
102
115
  signal.throwIfAborted();
103
- const result = await reader.read();
116
+ let result;
117
+ try {
118
+ result = await reader.read();
119
+ }
120
+ catch (error) {
121
+ if (signal.aborted)
122
+ throw signal.reason;
123
+ terminalReason = "error";
124
+ throw new RemoteRequestError(diagnostics.httpStatus, false, {}, error, "AGENT_STREAM_READ_FAILED", summary());
125
+ }
126
+ if (!result.done && result.value.byteLength) {
127
+ receivedBytes = Math.min(Number.MAX_SAFE_INTEGER, receivedBytes + result.value.byteLength);
128
+ firstByteMs ??= Math.max(0, Math.min(Number.MAX_SAFE_INTEGER, now() - startedAt));
129
+ }
104
130
  signal.throwIfAborted();
105
- if (result.done)
131
+ if (result.done) {
132
+ terminalReason = "eof";
106
133
  break;
134
+ }
107
135
  raw += decoder.decode(result.value, { stream: true });
108
136
  if (onContextId && !contextReported) {
109
137
  const contextId = messagesFrom(raw).find(message => typeof message.thread_id === "string" && message.thread_id)?.thread_id;
@@ -115,16 +143,36 @@ export async function parseCreativeStream(stream, signal, onContextId) {
115
143
  }
116
144
  raw += decoder.decode();
117
145
  }
146
+ catch (error) {
147
+ try {
148
+ if (error instanceof Error && Object.isExtensible(error)) {
149
+ const previous = error.diagnosticSummary;
150
+ Object.assign(error, { diagnosticSummary: {
151
+ ...(previous && typeof previous === "object" && !Array.isArray(previous) ? previous : {}), ...summary()
152
+ } });
153
+ }
154
+ }
155
+ catch { /* Diagnostic attachment cannot replace the original failure. */ }
156
+ if (terminalReason === "canceled")
157
+ void reader.cancel(error).catch(() => undefined);
158
+ throw error;
159
+ }
118
160
  finally {
119
161
  signal.removeEventListener("abort", onAbort);
120
162
  reader.releaseLock();
163
+ try {
164
+ diagnostics.onDiagnostics?.(summary());
165
+ }
166
+ catch { /* Diagnostics cannot replace a result or primary error. */ }
121
167
  }
122
168
  const messages = messagesFrom(raw);
123
169
  if (messages.length === 0) {
124
170
  const payloads = extractPayloads(raw);
125
- throw new RemoteProtocolError({ remoteBody: JSON.stringify({ messageCount: 0, contextIdPresent: false, systemErrorCount: 0,
126
- streamHadBytes: raw.length > 0, streamPayloadCount: Math.min(payloads.length, 100_000),
127
- streamJsonValueCount: Math.min(payloads.reduce((count, payload) => count + parseSequence(payload).length, 0), 100_000) }) }, undefined, "AGENT_CONTEXT_ID_MISSING");
171
+ throw Object.assign(new RemoteProtocolError({ remoteBody: JSON.stringify({ messageCount: 0, contextIdPresent: false, systemErrorCount: 0,
172
+ ...summary(), streamPayloadCount: Math.min(payloads.length, 100_000),
173
+ streamJsonValueCount: Math.min(payloads.reduce((count, payload) => count + parseSequence(payload).length, 0), 100_000) }) }, undefined, "AGENT_CONTEXT_ID_MISSING"), {
174
+ ...(diagnostics.httpStatus === undefined ? {} : { status: diagnostics.httpStatus }), diagnosticSummary: summary()
175
+ });
128
176
  }
129
177
  return messages;
130
178
  }
@@ -8,6 +8,7 @@ function unsignedPrivateUrl(value) {
8
8
  throw new RemoteProtocolError();
9
9
  }
10
10
  const isPrivate = /^gd-ai-[a-z0-9-]+\.dancf\.com$/iu.test(url.hostname)
11
+ || /^gdesign-dam(?:-[a-z0-9-]+)?\.dancf\.com$/iu.test(url.hostname)
11
12
  || url.hostname === "dify-grsai.dancf.com"
12
13
  || url.hostname === "dify-aiznt.dancf.com";
13
14
  if (!isPrivate || url.searchParams.get("auth_key")?.trim())
@@ -20,7 +20,9 @@ export async function readAgentResult(transport, request) {
20
20
  if (!turn.some(m => m.role !== "user" && m.content))
21
21
  return { connectionState: connection.state };
22
22
  try {
23
- return { connectionState: connection.state, partialResult: normalizeCreativeMessages(turn) };
23
+ let usageModelMissing = false;
24
+ const partialResult = normalizeCreativeMessages(turn, () => { usageModelMissing = true; });
25
+ return { connectionState: connection.state, partialResult, ...(usageModelMissing ? { usageModelMissing: true } : {}) };
24
26
  }
25
27
  catch (error) {
26
28
  if (error instanceof RemoteProtocolError)
@@ -1,5 +1,6 @@
1
1
  import { findModel, ToolInputError } from "../tool/catalog.js";
2
2
  import { modelControlArgumentsAreValid } from "../tool/dynamic-schema.js";
3
+ import { canvasRemoteControlArguments } from "../tool/canvas-models.js";
3
4
  import { parseSafeRemoteAssetUrl, UrlSafetyError } from "../../platform/url-safety.js";
4
5
  export class AgentInputError extends Error {
5
6
  reason;
@@ -50,6 +51,7 @@ export function createAgentUseCases(dependencies) {
50
51
  }
51
52
  }
52
53
  if (generation?.model !== undefined) {
54
+ const requested = generation;
53
55
  dependencies.telemetry.annotate({ model_id: generation.model });
54
56
  const catalog = await dependencies.telemetry.stage("catalog", () => (dependencies.catalog.load({ access, signal })));
55
57
  signal.throwIfAborted();
@@ -60,15 +62,23 @@ export function createAgentUseCases(dependencies) {
60
62
  await dependencies.telemetry.stage("input", async () => {
61
63
  let model;
62
64
  try {
63
- model = findModel(catalog, generation.model);
65
+ model = findModel(catalog, requested.model);
64
66
  }
65
67
  catch (error) {
66
68
  if (error instanceof ToolInputError)
67
69
  throw new AgentInputError(error.reason, "/generation/model", error);
68
70
  throw error;
69
71
  }
70
- if (!modelControlArgumentsAreValid(model, generation.arguments ?? {}))
72
+ if (!modelControlArgumentsAreValid(model, requested.arguments ?? {}))
71
73
  throw new AgentInputError("model_parameters", "/generation/arguments");
74
+ if (model.execution?.kind === "canvas") {
75
+ generation = {
76
+ model: model.execution.code,
77
+ ...(requested.arguments === undefined ? {} : {
78
+ arguments: canvasRemoteControlArguments(model.model, requested.arguments)
79
+ })
80
+ };
81
+ }
72
82
  });
73
83
  }
74
84
  const prepare = async () => {
@@ -128,10 +138,10 @@ export function createAgentUseCases(dependencies) {
128
138
  prepared.push({
129
139
  kind: "generation",
130
140
  data: {
131
- ...(part.data.model === undefined ? {} : { model: part.data.model }),
132
- ...(part.data.arguments === undefined
141
+ ...(generation?.model === undefined ? {} : { model: generation.model }),
142
+ ...(generation?.arguments === undefined
133
143
  ? {}
134
- : { arguments: { ...part.data.arguments } })
144
+ : { arguments: { ...generation.arguments } })
135
145
  }
136
146
  });
137
147
  }
@@ -1,11 +1,12 @@
1
1
  import { homedir } from "node:os";
2
2
  import { join } from "node:path";
3
3
  import { createLocalJsonFile } from "../../platform/local-json-file.js";
4
- import { AuthStateInvalidError, parseStoredAuthState } from "./state.js";
4
+ import { AuthStateInvalidError, AuthStateUnavailableError, parseStoredAuthState } from "./state.js";
5
5
  export function createLocalCredentialStore(options = {}) {
6
6
  const file = options.file ?? createLocalJsonFile({
7
7
  directory: join(options.homeDirectory ?? homedir(), options.stateDirectory ?? ".gd"),
8
- filename: "credentials.json"
8
+ filename: "credentials.json",
9
+ role: "credentials"
9
10
  });
10
11
  return {
11
12
  async read() {
@@ -28,7 +29,7 @@ export function createLocalCredentialStore(options = {}) {
28
29
  catch (cause) {
29
30
  if (cause instanceof AuthStateInvalidError)
30
31
  throw cause;
31
- throw invalidState(cause);
32
+ throw new AuthStateUnavailableError({ cause });
32
33
  }
33
34
  },
34
35
  async write(state) {
@@ -39,7 +40,7 @@ export function createLocalCredentialStore(options = {}) {
39
40
  catch (cause) {
40
41
  if (cause instanceof AuthStateInvalidError)
41
42
  throw cause;
42
- throw invalidState(cause);
43
+ throw new AuthStateUnavailableError({ cause });
43
44
  }
44
45
  },
45
46
  async remove() {
@@ -47,7 +48,7 @@ export function createLocalCredentialStore(options = {}) {
47
48
  await file.remove();
48
49
  }
49
50
  catch (cause) {
50
- throw invalidState(cause);
51
+ throw new AuthStateUnavailableError({ cause });
51
52
  }
52
53
  }
53
54
  };
@@ -55,8 +56,3 @@ export function createLocalCredentialStore(options = {}) {
55
56
  function serialize(state) {
56
57
  return `${JSON.stringify(state, null, 2)}\n`;
57
58
  }
58
- function invalidState(cause) {
59
- return new AuthStateInvalidError({
60
- cause, reason: "local_io"
61
- });
62
- }