@gaoding/cli 1.7.1 → 1.9.0

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 (74) hide show
  1. package/contracts/operations/agent.send/input.schema.json +1 -1
  2. package/contracts/operations/model.get/input.schema.json +6 -0
  3. package/contracts/operations/model.get/output.schema.json +10 -1
  4. package/contracts/operations/tool.call/canvas-input.schema.json +60 -0
  5. package/contracts/operations/tool.call/models/image-edit-smart.schema.json +42 -0
  6. package/contracts/operations/tool.call/models/image-edit-standard.schema.json +33 -0
  7. package/contracts/operations/tool.call/models/image-enhance-smart.schema.json +27 -0
  8. package/contracts/operations/tool.call/models/image-enhance-standard.schema.json +27 -0
  9. package/contracts/operations/tool.call/models/image-expand-smart.schema.json +76 -0
  10. package/contracts/operations/tool.call/models/image-expand-standard.schema.json +61 -0
  11. package/contracts/operations/tool.call/models/image-layers-layout.schema.json +21 -0
  12. package/contracts/operations/tool.call/models/image-layers-smart.schema.json +28 -0
  13. package/contracts/operations/tool.call/models/image-matting-smart.schema.json +37 -0
  14. package/contracts/operations/tool.call/models/image-matting-standard.schema.json +26 -0
  15. package/contracts/operations/tool.call/models/image-ocr.schema.json +21 -0
  16. package/contracts/operations/tool.call/models/image-remove-smart.schema.json +32 -0
  17. package/contracts/operations/tool.call/models/image-remove-standard.schema.json +27 -0
  18. package/contracts/operations/tool.call/models/image-text-edit.schema.json +46 -0
  19. package/contracts/operations/tool.call/models/image-vectorize.schema.json +21 -0
  20. package/contracts/operations/tool.call/models/video-edit-smart.schema.json +76 -0
  21. package/contracts/operations/tool.call/models/video-enhance-smart.schema.json +33 -0
  22. package/contracts/operations/tool.call/models/video-enhance-standard.schema.json +27 -0
  23. package/contracts/operations/tool.call/ocr-payload.schema.json +66 -0
  24. package/contracts/operations/tool.call/output.schema.json +38 -0
  25. package/contracts/operations/tool.call/template-payload.schema.json +96 -0
  26. package/dist/src/bootstrap/create-runtime.js +61 -25
  27. package/dist/src/bootstrap/validators.js +1 -1
  28. package/dist/src/cli/action-binding.js +3 -0
  29. package/dist/src/cli/agent-commands.js +1 -0
  30. package/dist/src/cli/errors.js +43 -10
  31. package/dist/src/cli/model-commands.js +7 -4
  32. package/dist/src/cli/observed-errors.js +13 -5
  33. package/dist/src/cli/task-commands.js +1 -1
  34. package/dist/src/cli/tool-commands.js +3 -1
  35. package/dist/src/contracts/schema.js +4 -1
  36. package/dist/src/features/agent/creative-protocol.js +22 -5
  37. package/dist/src/features/agent/resource-authorizer.js +1 -0
  38. package/dist/src/features/agent/use-cases.js +15 -5
  39. package/dist/src/features/auth/sso-service.js +13 -4
  40. package/dist/src/features/dam/dam-api-adapter.js +1 -0
  41. package/dist/src/features/dam/file-downloader.js +23 -2
  42. package/dist/src/features/task/store.js +8 -4
  43. package/dist/src/features/task/use-cases.js +14 -11
  44. package/dist/src/features/tool/canvas-copy.js +61 -0
  45. package/dist/src/features/tool/canvas-media.js +193 -0
  46. package/dist/src/features/tool/canvas-models.js +109 -0
  47. package/dist/src/features/tool/canvas-pricing.js +81 -0
  48. package/dist/src/features/tool/canvas-recovery.js +68 -0
  49. package/dist/src/features/tool/canvas-results.js +144 -0
  50. package/dist/src/features/tool/canvas-tool-adapter.js +366 -0
  51. package/dist/src/features/tool/canvas-video.js +84 -0
  52. package/dist/src/features/tool/catalog.js +35 -13
  53. package/dist/src/features/tool/dynamic-schema.js +52 -23
  54. package/dist/src/features/tool/matting-billing.js +103 -0
  55. package/dist/src/features/tool/mns-catalog-adapter.js +66 -19
  56. package/dist/src/features/tool/resource-authorizer.js +34 -0
  57. package/dist/src/features/tool/scene-catalog-adapter.js +35 -0
  58. package/dist/src/features/tool/tool-api-adapter.js +24 -5
  59. package/dist/src/features/tool/use-cases.js +28 -3
  60. package/dist/src/features/update/update-service.js +4 -2
  61. package/dist/src/platform/file-lock.js +12 -0
  62. package/dist/src/platform/local-json-file.js +19 -5
  63. package/dist/src/platform/safe-upload-file.js +18 -10
  64. package/dist/src/platform/schema-issues.js +47 -2
  65. package/dist/src/platform/text-output.js +17 -4
  66. package/dist/src/product/config.js +12 -1
  67. package/dist/src/telemetry/failure-summary.js +18 -0
  68. package/package.json +5 -4
  69. package/skills/gd-cli/SKILL.md +2 -0
  70. package/skills/gd-cli/references/creation.md +2 -0
  71. package/skills/gd-cli/references/generation-constraints.md +3 -1
  72. package/skills/gd-cli/references/matting.md +29 -0
  73. package/skills/gd-cli/references/media-tools.md +40 -0
  74. package/skills/gd-cli/references/tool.md +5 -5
@@ -9,7 +9,7 @@ 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 } 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";
@@ -31,9 +31,12 @@ import { EditorNotReadyError, EditorSessionNotFoundError, EditorTargetError } fr
31
31
  import { UpdateError } from "../features/update/update-service.js";
32
32
  import { WindAnalyticsError } from "../analytics/wind.js";
33
33
  import { safeFailureSummary } from "../telemetry/failure-summary.js";
34
+ import { OutputStreamError } from "../platform/text-output.js";
34
35
  export class CliUsageError extends Error {
35
- constructor() {
36
+ reason;
37
+ constructor(reason = "command_arguments") {
36
38
  super("命令或参数无效。");
39
+ this.reason = reason;
37
40
  this.name = "CliUsageError";
38
41
  }
39
42
  }
@@ -57,8 +60,9 @@ export function mapCliError(error, options) {
57
60
  code: outcome.failure.code, errorType: error instanceof Error ? error.name : undefined,
58
61
  remoteCode: remote?.remoteCode,
59
62
  httpStatus: remote instanceof RemoteRequestError || remote instanceof SsoRequestError ? remote.status : undefined,
60
- diagnosticReason: remote instanceof RemoteRequestError || remote instanceof RemoteProtocolError || remote instanceof ToolTaskFailedError
61
- ? remote.diagnosticReason : undefined
63
+ diagnosticReason: error instanceof UpdateError ? error.diagnosticReason
64
+ : remote instanceof RemoteRequestError || remote instanceof RemoteProtocolError || remote instanceof ToolTaskFailedError || remote instanceof SsoRequestError
65
+ ? remote.diagnosticReason : undefined
62
66
  };
63
67
  const category = observedErrorCategory(evidence);
64
68
  if (!category)
@@ -72,6 +76,9 @@ function mapBaseCliError(error, options) {
72
76
  const insmind = options.product?.id === "insmind";
73
77
  const command = options.product?.commandName ?? "gd-cli";
74
78
  const text = (zh, en) => insmind ? en : zh;
79
+ if (error instanceof ToolTaskCanceledError)
80
+ return { kind: "interrupted", exitCode: 130,
81
+ failure: { code: "INTERRUPTED", message: text("生成任务已取消。", "The creation task was canceled.") } };
75
82
  if (options.aborted)
76
83
  return { kind: "interrupted", exitCode: 130, failure: {
77
84
  code: "INTERRUPTED", message: text("已停止本地等待;已派发的任务或写操作可能仍在继续。", "Local waiting stopped; dispatched tasks or writes may still be active."),
@@ -141,7 +148,9 @@ function mapBaseCliError(error, options) {
141
148
  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 } : {}) });
142
149
  }
143
150
  if (error instanceof LocalFileInputError)
144
- 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: "local_asset", system_code: systemErrorCode(error) });
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 CliUsageError && error.reason === "invalid_task_id")
153
+ 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 });
145
154
  if (error instanceof DamInputError)
146
155
  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 });
147
156
  if (error instanceof OrgUsageError
@@ -151,8 +160,8 @@ function mapBaseCliError(error, options) {
151
160
  return failure("USAGE_ERROR", "Invalid command or arguments. See --help.", 2);
152
161
  return failure("USAGE_ERROR", "命令或参数无效,请查看 --help。", 2);
153
162
  }
154
- if (options.product?.id !== "insmind" && options.operation === "tool.call" && isInsufficientCreditsError(error)) {
155
- return failure("INSUFFICIENT_CREDITS", "当前可用额度不足,本次生成未能完成。", 1);
163
+ if (error instanceof ToolInsufficientCreditsError || options.product?.id !== "insmind" && options.operation === "tool.call" && isInsufficientCreditsError(error)) {
164
+ return failure("INSUFFICIENT_CREDITS", text("当前可用额度不足,本次生成未能完成。", "Available credits are insufficient; this creation could not complete."), 1);
156
165
  }
157
166
  if (isContentReviewRejection(error, { product: options.product?.id ?? "gaoding", operation: options.operation })) {
158
167
  const phase = error instanceof AgentAuditRejectedError ? error.phase : undefined;
@@ -255,6 +264,8 @@ function isInsufficientCreditsError(error) {
255
264
  || error instanceof ToolTaskFailedError) && error.remoteCode === INSUFFICIENT_CREDITS_REMOTE_CODE;
256
265
  }
257
266
  export function classifyTelemetryError(error, options = {}) {
267
+ if (error instanceof ToolTaskCanceledError)
268
+ return { outcome: "interrupted", errorCode: "INTERRUPTED", diagnosticReason: "TASK_CANCELED" };
258
269
  if (error instanceof WindAnalyticsError)
259
270
  return { outcome: "failure", errorCode: error.code,
260
271
  ...(error.status === undefined ? {} : { httpStatus: error.status }) };
@@ -280,8 +291,16 @@ export function classifyTelemetryError(error, options = {}) {
280
291
  catch { /* No safe summary available. */ }
281
292
  }
282
293
  const diagnosticSummary = safeFailureSummary({
294
+ ...localFileSummary(error),
295
+ ...(error instanceof OutputStreamError ? { outputStream: error.outputStream } : {}),
296
+ ...(remoteError instanceof SsoRequestError ? remoteError.diagnosticSummary : {}),
283
297
  ...(summary && typeof summary === "object" && !Array.isArray(summary) ? summary : {}),
284
- systemCode: systemErrorCode(error)
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
285
304
  });
286
305
  return {
287
306
  outcome: outcome.kind === "interrupted" ? "interrupted" : "failure",
@@ -296,8 +315,12 @@ export function classifyTelemetryError(error, options = {}) {
296
315
  ...(remoteError?.remoteBody === undefined
297
316
  ? {}
298
317
  : { remoteErrorBody: remoteError.remoteBody }),
299
- ...((remoteError instanceof RemoteRequestError || remoteError instanceof RemoteProtocolError || remoteError instanceof ToolTaskFailedError) && remoteError.diagnosticReason
300
- ? { diagnosticReason: remoteError.diagnosticReason } : {})
318
+ ...(error instanceof DamAssetNotDownloadableError ? { diagnosticReason: error.diagnosticReason }
319
+ : error instanceof DamDownloadError ? { diagnosticReason: `DOWNLOAD_${error.phase.toUpperCase()}_FAILED` }
320
+ : error instanceof OutputStreamError ? { diagnosticReason: "OUTPUT_STREAM_FAILED" }
321
+ : error instanceof UpdateError && error.diagnosticReason ? { diagnosticReason: error.diagnosticReason }
322
+ : (remoteError instanceof RemoteRequestError || remoteError instanceof RemoteProtocolError || remoteError instanceof ToolTaskFailedError || remoteError instanceof SsoRequestError) && remoteError.diagnosticReason
323
+ ? { diagnosticReason: remoteError.diagnosticReason } : {})
301
324
  };
302
325
  }
303
326
  function failure(code, message, exitCode, nextSteps, details) {
@@ -318,6 +341,16 @@ function systemErrorCode(error) {
318
341
  }
319
342
  return undefined;
320
343
  }
344
+ function localFileSummary(error) {
345
+ for (let depth = 0; error instanceof Error && depth < 10; depth++, error = error.cause) {
346
+ if (error instanceof LocalFileError && error.diagnostic)
347
+ return {
348
+ localFileOperation: error.diagnostic.operation,
349
+ localFileStep: error.diagnostic.step
350
+ };
351
+ }
352
+ return undefined;
353
+ }
321
354
  function remoteCause(error) {
322
355
  for (let depth = 0; error instanceof Error && depth < 10; error = error.cause, depth++) {
323
356
  if (error instanceof RemoteRequestError || error instanceof RemoteProtocolError || error instanceof ToolTaskFailedError
@@ -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,15 +32,17 @@ 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
- text(runtime.product, "usageDescription 说明跨字段组合规则。tool call <tool> --schema 是 Tool 级参数并集,不能代替本 Model 的要求。Agent 只传显式生成约束,不照搬 Tool 的完整必填参数。", "usageDescription explains cross-field combinations. tool call <tool> --schema is a tool-wide union, not this Model's exact requirements. For Agent, pass explicit generation constraints rather than copying every Tool-required parameter."),
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."),
44
46
  ""
45
47
  ].join("\n"));
46
48
  jsonOutput(get);
@@ -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
  });
@@ -19,6 +19,8 @@ const messages = {
19
19
  save: ["保存遇到问题,请在编辑器查看作品。", "There was a problem saving. Check the design in the editor."],
20
20
  local: ["无法读取或保存本次操作记录。", "The record for this operation could not be read or saved."],
21
21
  update: ["本次更新未完成。", "This update did not complete."],
22
+ managed_update: ["请在原应用中更新此工具。", "Update this tool in the app where it was installed."],
23
+ editor_required: ["请先打开作品并连接编辑器。", "Open a design and connect to the editor first."],
22
24
  output: ["结果未能完整显示。", "The result could not be fully displayed."],
23
25
  read: ["暂时无法读取结果。", "The result cannot be read right now."],
24
26
  tool: ["本次生成未能完成。", "This creation could not be completed."],
@@ -50,7 +52,9 @@ export function observedErrorCategory(e) {
50
52
  return "account";
51
53
  if (e.code === "USAGE_ERROR" && e.errorType === "LocalFileInputError")
52
54
  return "input_asset";
53
- if (["USAGE_ERROR", "INVALID_ACTIONS"].includes(e.code) || gd && e.operation === "dam.rename" && e.remoteCode === "00010014")
55
+ if (gd && e.operation === "dam.rename" && e.remoteCode === "00010014")
56
+ return "file_exists";
57
+ if (["USAGE_ERROR", "INVALID_ACTIONS"].includes(e.code))
54
58
  return "input";
55
59
  if (gd && e.operation === "dam.upload" && e.remoteCode === "36002105")
56
60
  return "upload";
@@ -64,7 +68,9 @@ export function observedErrorCategory(e) {
64
68
  || gd && ["dam.download", "dam.get", "dam.list", "dam.search"].includes(e.operation ?? "")
65
69
  && e.code === "REMOTE_REQUEST_FAILED" && [403, 404].includes(e.httpStatus ?? 0))
66
70
  return "asset_read";
67
- if (["EDITOR_NOT_CONNECTED", "EDITOR_DISCONNECTED", "EDITOR_NOT_READY", "EDITOR_SESSION_NOT_FOUND"].includes(e.code))
71
+ if (e.code === "EDITOR_SESSION_NOT_FOUND")
72
+ return "editor_required";
73
+ if (["EDITOR_NOT_CONNECTED", "EDITOR_DISCONNECTED", "EDITOR_NOT_READY"].includes(e.code))
68
74
  return "editor";
69
75
  if (e.code === "UNSUPPORTED_PAGE_CONTENT")
70
76
  return "unsupported";
@@ -72,14 +78,16 @@ export function observedErrorCategory(e) {
72
78
  return "save";
73
79
  if (e.code === "LOCAL_STATE_ERROR")
74
80
  return "local";
81
+ if (e.code === "UPDATE_FAILED" && e.diagnosticReason === "UPDATE_MANAGED_BY_HOST")
82
+ return "managed_update";
75
83
  if (e.code === "UPDATE_FAILED")
76
84
  return "update";
77
- if (e.code === "INTERNAL_ERROR" && e.failureStage === "output")
85
+ if (e.diagnosticReason === "OUTPUT_STREAM_FAILED" || e.code === "INTERNAL_ERROR" && e.failureStage === "output")
78
86
  return "output";
79
87
  if (gd && (e.operation === "tool.call" && ["12020700", "12020791", "500"].includes(e.remoteCode ?? "")
80
88
  || toolOrQuery && e.remoteCode === "12020780" || e.operation === "dam.upload" && e.remoteCode === "500"))
81
89
  return "request";
82
- if (e.code === "REMOTE_PROTOCOL_INCOMPATIBLE"
90
+ if (e.diagnosticReason?.startsWith("SSO_RESPONSE_") || e.code === "REMOTE_PROTOCOL_INCOMPATIBLE"
83
91
  || ["AGENT_CONTEXT_ID_MISSING", "AGENT_USAGE_MODEL_MISSING", "RESPONSE_BODY_ALREADY_USED"].includes(e.diagnosticReason ?? ""))
84
92
  return "read";
85
93
  if (e.code === "TOOL_TASK_FAILED")
@@ -98,7 +106,7 @@ export function observedErrorMessage(category, e) {
98
106
  return text("本次登录已超时,请重新登录。", "This sign-in timed out. Please sign in again.");
99
107
  if (category === "account" && e.code === "ORG_INVALID")
100
108
  return text("当前团队不可用,请重新选择团队。", "This team is unavailable. Select another team.");
101
- if (category === "input" && e.operation === "dam.rename" && e.remoteCode === "00010014")
109
+ if (category === "file_exists" && e.operation === "dam.rename" && e.remoteCode === "00010014")
102
110
  return text("名称已存在,请换个名称。", "This name already exists. Choose another name.");
103
111
  if (category === "asset_read" && e.code === "DAM_DOWNLOAD_FAILED")
104
112
  return text("素材下载未完成。", "The asset download did not complete.");
@@ -45,7 +45,7 @@ export function registerTaskCommands(program, runtime) {
45
45
  bindPreparedAction(get, "local-organization", async () => {
46
46
  const id = get.processedArgs[0];
47
47
  if (typeof id !== "string" || !validTaskId(id))
48
- throw new CliUsageError();
48
+ throw new CliUsageError("invalid_task_id");
49
49
  return { handled: false, input: id.toLowerCase() };
50
50
  }, async (context, id, signal) => {
51
51
  const result = await tasks.get({ id, state: context.state, signal });
@@ -25,7 +25,7 @@ export function registerToolCommands(program, runtime) {
25
25
  const call = tool.command("call")
26
26
  .description(text(runtime.product, "调用创作工具", "Call a creation tool"))
27
27
  .argument("<tool>", text(runtime.product, "工具机器标识", "tool machine identifier"))
28
- .option("--schema", text(runtime.product, "输出当前工具所有模型参数并集的输入 Schema", "output the tool-wide input Schema"))
28
+ .option("--schema", text(runtime.product, "输出按 model 区分必填字段和参数限制的输入 Schema", "output the input Schema with per-model required fields and constraints"))
29
29
  .option("--input <file|->", text(runtime.product, "从文件或标准输入读取参数 JSON", "read argument JSON from a file or stdin"))
30
30
  .option("--async", text(runtime.product, "提交后返回 taskId,通过 task get 查询结果", "return taskId after submission; retrieve results with task get"))
31
31
  .allowExcessArguments(false);
@@ -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
  }
@@ -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);
@@ -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 {
@@ -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())
@@ -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
  }
@@ -3,15 +3,19 @@ import { remoteErrorEvidence } from "../../platform/remote-error-evidence.js";
3
3
  import { normalizeScope } from "./state.js";
4
4
  import { signBindOrganization } from "../../platform/signature.js";
5
5
  export class SsoRequestError extends Error {
6
+ diagnosticSummary;
6
7
  status;
7
8
  remoteCode;
8
9
  remoteBody;
9
- constructor(status, evidence = {}, cause) {
10
+ diagnosticReason;
11
+ constructor(status, evidence = {}, cause, diagnosticSummary) {
10
12
  super(status === undefined ? "无法连接稿定登录服务。" : `稿定登录服务请求失败(HTTP ${status})。`, { cause });
13
+ this.diagnosticSummary = diagnosticSummary;
11
14
  this.name = "SsoRequestError";
12
15
  this.status = status;
13
16
  this.remoteCode = evidence.remoteCode;
14
17
  this.remoteBody = evidence.remoteBody;
18
+ this.diagnosticReason = evidence.diagnosticReason;
15
19
  }
16
20
  }
17
21
  export function classifyBindOutcome(input) {
@@ -42,12 +46,16 @@ export function createSsoService(options) {
42
46
  }
43
47
  }
44
48
  return new SsoRequestError(response.status, {
49
+ ...(response.ok ? { diagnosticReason: "SSO_RESPONSE_INVALID" } : {}),
45
50
  ...(evidence.remoteCode === undefined ? {} : { remoteCode: evidence.remoteCode }),
46
51
  ...remoteErrorEvidence({ request: requests.get(response),
47
52
  ...(evidence.remoteBody === undefined ? {} : { response: evidence.remoteBody }),
48
53
  ...(networkError === undefined ? {} : { network: networkFailure(networkError) }) })
49
54
  }, networkError);
50
55
  }
56
+ function invalidFields(response, phase, fields) {
57
+ return new SsoRequestError(response.status, { diagnosticReason: "SSO_RESPONSE_FIELDS_MISSING" }, undefined, { ssoPhase: phase, ssoInvalidFields: Object.entries(fields).filter(([, valid]) => !valid).map(([key]) => key).join(",") });
58
+ }
51
59
  async function responseRecord(response) {
52
60
  if (!response.ok) {
53
61
  // OAuth pending/slow_down are normal token polling responses.
@@ -101,7 +109,8 @@ export function createSsoService(options) {
101
109
  const expiresInSeconds = positiveNumber(body.expires_in);
102
110
  const intervalSeconds = positiveNumber(body.interval);
103
111
  if (!authorizeCode || !deviceCode || !expiresInSeconds || !intervalSeconds) {
104
- throw await responseError(response);
112
+ throw invalidFields(response, "authorize", { authorize_code: authorizeCode, device_code: deviceCode,
113
+ expires_in: expiresInSeconds, interval: intervalSeconds });
105
114
  }
106
115
  return { authorizeCode, deviceCode, expiresInSeconds, intervalSeconds };
107
116
  },
@@ -123,13 +132,13 @@ export function createSsoService(options) {
123
132
  const secretKey = nonEmptyString(body.sk);
124
133
  const expiresAt = dateString(body.expires_at);
125
134
  if (!accessKey || !secretKey || !expiresAt)
126
- throw await responseError(response);
135
+ throw invalidFields(response, "token", { ak: accessKey, sk: secretKey, expires_at: expiresAt });
127
136
  let scope;
128
137
  try {
129
138
  scope = normalizeScope(body.scope);
130
139
  }
131
140
  catch {
132
- throw await responseError(response);
141
+ throw invalidFields(response, "token", { scope: false });
133
142
  }
134
143
  const result = {
135
144
  status: "authorized",
@@ -9,6 +9,7 @@ export class DamAssetNotFoundError extends Error {
9
9
  }
10
10
  }
11
11
  export class DamAssetNotDownloadableError extends Error {
12
+ diagnosticReason = "ASSET_DOWNLOAD_URL_MISSING";
12
13
  constructor() {
13
14
  super("该 DAM 素材当前不可下载。");
14
15
  this.name = "DamAssetNotDownloadableError";
@@ -84,6 +84,9 @@ function safeFilename(candidate, fallback, format) {
84
84
  const segments = raw.normalize("NFKC").replace(/[\u0000-\u001f\u007f]/gu, "")
85
85
  .split(/[\\/]+/u);
86
86
  let filename = (segments.at(-1) ?? "").trim().replace(/^\.+/u, "");
87
+ filename = filename.replace(/[<>:"|?*]/gu, "_").replace(/[. ]+$/u, "");
88
+ if (/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/iu.test(filename))
89
+ filename = `_${filename}`;
87
90
  if (filename === "" || filename === "." || filename === "..")
88
91
  filename = "asset";
89
92
  if (extname(filename) === "")
@@ -153,6 +156,15 @@ export function createDamFileDownloader(options = {}) {
153
156
  randomId: options.randomId ?? randomUUID,
154
157
  cwd: options.cwd ?? process.cwd
155
158
  };
159
+ const warnCleanup = () => {
160
+ try {
161
+ options.warn?.("DOWNLOAD_TEMP_CLEANUP_FAILED");
162
+ }
163
+ catch {
164
+ // An advisory warning can encounter a closed stderr. It must neither
165
+ // roll back committed results nor replace the original download error.
166
+ }
167
+ };
156
168
  return {
157
169
  async download(input) {
158
170
  input.signal.throwIfAborted();
@@ -230,8 +242,14 @@ export function createDamFileDownloader(options = {}) {
230
242
  throw new DamDownloadError(cause, "commit");
231
243
  }
232
244
  createdFinalPaths.push(item.finalPath);
233
- await dependencies.fileSystem.rm(item.temporaryPath, { force: true });
234
245
  }
246
+ // Every result is committed before best-effort temporary cleanup. A
247
+ // host cleanup guard must never delete a successfully downloaded file.
248
+ let cleanupFailed = false;
249
+ await Promise.all(pending.map(item => dependencies.fileSystem.rm(item.temporaryPath, { force: true })
250
+ .catch(() => { cleanupFailed = true; })));
251
+ if (cleanupFailed)
252
+ warnCleanup();
235
253
  return pending.map((item) => ({
236
254
  path: item.finalPath,
237
255
  bytes: item.bytes,
@@ -241,15 +259,18 @@ export function createDamFileDownloader(options = {}) {
241
259
  catch (error) {
242
260
  const remainingPaths = [];
243
261
  const cleanupErrors = [];
262
+ let temporaryCleanupFailed = false;
244
263
  await Promise.all(pending.map(async (item) => {
245
264
  if (item.open)
246
265
  await item.handle.close().catch(cause => { cleanupErrors.push(cause); });
247
266
  await dependencies.fileSystem.rm(item.temporaryPath, { force: true }).catch(cause => {
248
267
  remainingPaths.push(item.temporaryPath);
249
- cleanupErrors.push(cause);
268
+ temporaryCleanupFailed = true;
250
269
  });
251
270
  }));
252
271
  await Promise.all(createdFinalPaths.map((path) => (dependencies.fileSystem.rm(path, { force: true }).catch(cause => { remainingPaths.push(path); cleanupErrors.push(cause); }))));
272
+ if (temporaryCleanupFailed)
273
+ warnCleanup();
253
274
  if (cleanupErrors.length)
254
275
  throw new DamDownloadError(new AggregateError([error, ...cleanupErrors], "Download cleanup failed.", { cause: error }), "cleanup", undefined, remainingPaths);
255
276
  if (isInterruption(error, input.signal))
@@ -28,18 +28,22 @@ export function createTaskStore(options) {
28
28
  try {
29
29
  const stat = await lstat(join(root, scope, `${id}.json`));
30
30
  if (!stat.isFile() || stat.isSymbolicLink())
31
- throw new LocalFileError(undefined);
31
+ throw new LocalFileError(undefined, undefined, "invalid_data", { operation: "read", step: "stat" });
32
32
  }
33
33
  catch (error) {
34
34
  if (error instanceof Error && "code" in error && error.code === "ENOENT")
35
35
  return null;
36
- throw error;
36
+ if (error instanceof LocalFileError)
37
+ throw error;
38
+ throw new LocalFileError(error, undefined, "io", { operation: "read", step: "stat" });
37
39
  }
38
40
  const text = await stateFile.readText();
39
41
  if (text === null)
40
42
  return null;
43
+ let step = "parse";
41
44
  try {
42
45
  const record = JSON.parse(text);
46
+ step = "validate";
43
47
  if (record.version !== 1 || record.task.taskId !== id || !record.progress
44
48
  || typeof record.progress !== "object" || Array.isArray(record.progress))
45
49
  throw new Error();
@@ -55,7 +59,7 @@ export function createTaskStore(options) {
55
59
  return record;
56
60
  }
57
61
  catch (cause) {
58
- throw new LocalFileError(cause);
62
+ throw new LocalFileError(cause, undefined, "invalid_data", { operation: "read", step });
59
63
  }
60
64
  },
61
65
  async write(scope, record) {
@@ -106,7 +110,7 @@ export function createTaskStore(options) {
106
110
  catch (error) {
107
111
  if (error instanceof Error && "code" in error && error.code === "ENOENT")
108
112
  return [];
109
- throw new LocalFileError(error);
113
+ throw new LocalFileError(error, undefined, "io", { operation: "list", step: "directory_read" });
110
114
  }
111
115
  const records = [];
112
116
  for (const name of names) {
@@ -159,8 +159,8 @@ export function createTaskUseCases(dependencies) {
159
159
  let details;
160
160
  if (input.operation === "agent.send")
161
161
  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视频生成";
162
+ else if (generation?.model && (generation.tool.startsWith("image.") || generation.tool.startsWith("video."))) {
163
+ const name = generation.tool.startsWith("image.") ? "AI绘图" : "AI视频生成";
164
164
  details = { tool_type: name, tool_name: name, model_name: generation.model };
165
165
  }
166
166
  else
@@ -222,7 +222,7 @@ export function createTaskUseCases(dependencies) {
222
222
  await analyticsFact("started");
223
223
  return;
224
224
  }
225
- Object.assign(record.progress, progress);
225
+ Object.assign(record.progress, withoutResourceKeys(progress));
226
226
  if (progress.contextId)
227
227
  record.task.contextId = progress.contextId;
228
228
  try {
@@ -260,7 +260,7 @@ export function createTaskUseCases(dependencies) {
260
260
  clearInterval(timer);
261
261
  const diagnostic = telemetry?.taskFailure(error).diagnostic_reason
262
262
  ?? (error instanceof RemoteRequestError ? error.diagnosticReason : undefined);
263
- const observationOnly = diagnostic === "LOCAL_WAIT_INTERRUPTED" || diagnostic === "TASK_QUERY_FAILED";
263
+ const observationOnly = diagnostic === "LOCAL_WAIT_INTERRUPTED" || diagnostic === "TASK_QUERY_FAILED" || diagnostic === "TASK_CANCELED";
264
264
  if (record.task.state !== "completed") {
265
265
  const mayBeRunning = dispatched || record.progress.submissionStarted;
266
266
  const auditRejected = isContentReviewRejection(error, { product: commandName === "insmind-cli" ? "insmind" : "gaoding", operation: input.operation });
@@ -269,13 +269,15 @@ export function createTaskUseCases(dependencies) {
269
269
  && error.remoteCode === "12020770";
270
270
  const confirmedFailure = error instanceof ToolTaskFailedError || auditRejected || creditsRejected;
271
271
  record.task.state = observationOnly ? "unknown" : confirmedFailure || !mayBeRunning ? "failed" : "unknown";
272
- record.task.note = diagnostic === "LOCAL_WAIT_INTERRUPTED"
273
- ? text("本次操作已停止等待。", "This operation stopped waiting.")
274
- : confirmedFailure
275
- ? text("本次生成未能完成。", "This creation could not be completed.")
276
- : mayBeRunning
277
- ? text("尚未取得任务结果。", "The task result has not been received.")
278
- : text("本次生成尚未开始。", "This creation has not started.");
272
+ record.task.note = diagnostic === "TASK_CANCELED"
273
+ ? text("生成任务已取消。", "The creation task was canceled.")
274
+ : diagnostic === "LOCAL_WAIT_INTERRUPTED"
275
+ ? text("本次操作已停止等待。", "This operation stopped waiting.")
276
+ : confirmedFailure
277
+ ? text("本次生成未能完成。", "This creation could not be completed.")
278
+ : mayBeRunning
279
+ ? text("尚未取得任务结果。", "The task result has not been received.")
280
+ : text("本次生成尚未开始。", "This creation has not started.");
279
281
  }
280
282
  const detail = dependencies.failureNote?.(error);
281
283
  if (detail && diagnostic !== "LOCAL_WAIT_INTERRUPTED")
@@ -325,6 +327,7 @@ export function createTaskUseCases(dependencies) {
325
327
  stored.task = { ...stored.task, state: "unknown", note: text("尚未取得任务结果。", "The task result has not been received.") };
326
328
  }));
327
329
  }
330
+ record = withoutResourceKeys(record);
328
331
  telemetry?.annotate({ cli_task_id: id, result_state: record.task.state });
329
332
  if (record.task.state === "completed" && record.task.result) {
330
333
  const result = { ...record.task, result: await stage("task.authorize", () => dependencies.recovery.authorize(record.task.result, state, signal)) };