@gaoding/cli 2.0.0 → 2.1.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 (132) hide show
  1. package/README.md +5 -0
  2. package/contracts/operations/agent.send/input.schema.json +8 -84
  3. package/contracts/operations/agent.send/output.schema.json +6 -6
  4. package/contracts/operations/credits.get/input.schema.json +9 -0
  5. package/contracts/operations/credits.get/output.schema.json +107 -0
  6. package/contracts/operations/credits.usage.get/input.schema.json +18 -0
  7. package/contracts/operations/credits.usage.get/output.schema.json +53 -0
  8. package/contracts/operations/credits.usage.list/input.schema.json +32 -0
  9. package/contracts/operations/credits.usage.list/output.schema.json +144 -0
  10. package/contracts/operations/dam.folder.list/input.schema.json +1 -1
  11. package/contracts/operations/dam.folder.list/output.schema.json +1 -1
  12. package/contracts/operations/dam.list/input.schema.json +2 -5
  13. package/contracts/operations/dam.list/output.schema.json +1 -1
  14. package/contracts/operations/dam.search/input.schema.json +2 -5
  15. package/contracts/operations/dam.search/output.schema.json +1 -1
  16. package/contracts/operations/model.get/output.schema.json +6 -5
  17. package/contracts/operations/model.list/output.schema.json +5 -4
  18. package/contracts/operations/task.get/output.schema.json +22 -11
  19. package/contracts/operations/tool.call/models/image-edit-smart.schema.json +7 -5
  20. package/contracts/operations/tool.call/models/image-edit-standard.schema.json +6 -4
  21. package/contracts/operations/tool.call/models/image-enhance-smart.schema.json +5 -3
  22. package/contracts/operations/tool.call/models/image-enhance-standard.schema.json +3 -2
  23. package/contracts/operations/tool.call/models/image-expand-smart.schema.json +16 -10
  24. package/contracts/operations/tool.call/models/image-expand-standard.schema.json +13 -8
  25. package/contracts/operations/tool.call/models/image-layers-layout.schema.json +3 -2
  26. package/contracts/operations/tool.call/models/image-layers-smart.schema.json +3 -4
  27. package/contracts/operations/tool.call/models/image-matting-smart.schema.json +6 -4
  28. package/contracts/operations/tool.call/models/image-matting-standard.schema.json +3 -2
  29. package/contracts/operations/tool.call/models/image-ocr.schema.json +3 -2
  30. package/contracts/operations/tool.call/models/image-remove-smart.schema.json +6 -4
  31. package/contracts/operations/tool.call/models/image-remove-standard.schema.json +4 -3
  32. package/contracts/operations/tool.call/models/image-text-edit.schema.json +5 -3
  33. package/contracts/operations/tool.call/models/image-vectorize.schema.json +3 -2
  34. package/contracts/operations/tool.call/models/video-edit-smart.schema.json +6 -6
  35. package/contracts/operations/tool.call/models/video-enhance-smart.schema.json +7 -4
  36. package/contracts/operations/tool.call/models/video-enhance-standard.schema.json +5 -3
  37. package/contracts/operations/tool.call/ocr-payload.schema.json +4 -5
  38. package/contracts/operations/tool.call/output.schema.json +9 -8
  39. package/dist/bin/postinstall.js +22 -6
  40. package/dist/bin/task-worker.js +2 -2
  41. package/dist/src/bootstrap/create-cli.js +31 -15
  42. package/dist/src/bootstrap/create-runtime.js +103 -30
  43. package/dist/src/bootstrap/run-task-worker.js +6 -2
  44. package/dist/src/bootstrap/validators.js +4 -1
  45. package/dist/src/cli/action-binding.js +17 -50
  46. package/dist/src/cli/agent-commands.js +11 -11
  47. package/dist/src/cli/auth-commands.js +2 -1
  48. package/dist/src/cli/creation-help.js +9 -0
  49. package/dist/src/cli/credits-command.js +127 -16
  50. package/dist/src/cli/dam-commands.js +10 -14
  51. package/dist/src/cli/editor-commands.js +7 -5
  52. package/dist/src/cli/errors.js +81 -22
  53. package/dist/src/cli/host-input.js +64 -5
  54. package/dist/src/cli/model-commands.js +9 -3
  55. package/dist/src/cli/observed-errors.js +7 -3
  56. package/dist/src/cli/org-commands.js +3 -1
  57. package/dist/src/cli/presenter.js +4 -0
  58. package/dist/src/cli/task-commands.js +6 -2
  59. package/dist/src/cli/tool-commands.js +12 -11
  60. package/dist/src/cli/update-command.js +24 -1
  61. package/dist/src/features/agent/creative-agent-adapter.js +6 -2
  62. package/dist/src/features/agent/creative-protocol.js +8 -29
  63. package/dist/src/features/agent/resource-authorizer.js +25 -17
  64. package/dist/src/features/agent/result-reader.js +31 -14
  65. package/dist/src/features/agent/use-cases.js +6 -31
  66. package/dist/src/features/credits/amount.js +51 -0
  67. package/dist/src/features/credits/response.js +11 -0
  68. package/dist/src/features/credits/use-cases.js +200 -30
  69. package/dist/src/features/dam/asset-projection.js +3 -6
  70. package/dist/src/features/dam/dam-api-adapter.js +30 -15
  71. package/dist/src/features/dam/repository-catalog.js +30 -21
  72. package/dist/src/features/dam/use-cases.js +12 -7
  73. package/dist/src/features/editor/bridge-client.js +0 -2
  74. package/dist/src/features/editor/public-url.js +1 -36
  75. package/dist/src/features/editor/session.js +3 -2
  76. package/dist/src/features/editor/use-cases.js +27 -2
  77. package/dist/src/features/org/org-service.js +10 -1
  78. package/dist/src/features/org/use-cases.js +18 -4
  79. package/dist/src/features/task/process-owner.js +54 -0
  80. package/dist/src/features/task/store.js +37 -10
  81. package/dist/src/features/task/task-background.js +5 -2
  82. package/dist/src/features/task/use-cases.js +184 -84
  83. package/dist/src/features/tool/argument-paths.js +14 -0
  84. package/dist/src/features/tool/canvas-copy.js +28 -15
  85. package/dist/src/features/tool/canvas-matting.js +123 -0
  86. package/dist/src/features/tool/canvas-media.js +100 -52
  87. package/dist/src/features/tool/canvas-models.js +66 -33
  88. package/dist/src/features/tool/canvas-pricing.js +12 -0
  89. package/dist/src/features/tool/canvas-recovery.js +13 -30
  90. package/dist/src/features/tool/canvas-results.js +79 -87
  91. package/dist/src/features/tool/canvas-tool-adapter.js +134 -157
  92. package/dist/src/features/tool/canvas-video.js +44 -37
  93. package/dist/src/features/tool/dynamic-schema.js +39 -40
  94. package/dist/src/features/tool/ffprobe-executable.js +21 -0
  95. package/dist/src/features/tool/mns-catalog-adapter.js +61 -24
  96. package/dist/src/features/tool/resource-authorizer.js +11 -3
  97. package/dist/src/features/tool/tool-api-adapter.js +73 -82
  98. package/dist/src/features/tool/tool-errors.js +25 -0
  99. package/dist/src/features/tool/tool-output.js +15 -0
  100. package/dist/src/features/tool/use-cases.js +74 -98
  101. package/dist/src/features/update/check-schema.js +17 -0
  102. package/dist/src/features/update/host-receipt.js +30 -0
  103. package/dist/src/features/update/notice-output.js +30 -0
  104. package/dist/src/features/update/update-lock.js +80 -0
  105. package/dist/src/features/update/update-notification.js +129 -240
  106. package/dist/src/features/update/update-service.js +95 -21
  107. package/dist/src/platform/media-type.js +46 -0
  108. package/dist/src/platform/public-url.js +35 -0
  109. package/dist/src/platform/remote-error-evidence.js +33 -6
  110. package/dist/src/platform/resource-auth-key.js +35 -1
  111. package/dist/src/platform/safe-upload-file.js +36 -41
  112. package/dist/src/platform/signature.js +3 -1
  113. package/dist/src/platform/signed-http-transport.js +14 -6
  114. package/dist/src/platform/url-safety.js +6 -1
  115. package/dist/src/platform/webm-header.js +41 -0
  116. package/dist/src/telemetry/command-route.js +38 -0
  117. package/dist/src/telemetry/command-routes.json +1 -0
  118. package/dist/src/telemetry/failure-summary.js +1 -1
  119. package/dist/src/telemetry/invocation.js +1 -2
  120. package/dist/src/telemetry/process-errors.js +17 -33
  121. package/dist/src/telemetry/sanitize.js +19 -4
  122. package/dist/src/telemetry/sls-sink.js +8 -0
  123. package/package.json +4 -4
  124. package/skills/gd-cli/SKILL.md +19 -5
  125. package/skills/gd-cli/references/agent.md +9 -4
  126. package/skills/gd-cli/references/creation.md +3 -1
  127. package/skills/gd-cli/references/editor.md +7 -5
  128. package/skills/gd-cli/references/errors.md +19 -8
  129. package/skills/gd-cli/references/matting.md +3 -5
  130. package/skills/gd-cli/references/media-tools.md +10 -4
  131. package/skills/gd-cli/references/tool.md +9 -15
  132. package/skills/gd-cli/references/update.md +6 -0
@@ -1,23 +1,134 @@
1
- import { bindAction } from "./action-binding.js";
1
+ import { normalizeCreditsUsageListInput } from "../features/credits/use-cases.js";
2
+ import { contractSchema } from "../contracts/schema.js";
3
+ import { productText as text } from "../product/text.js";
4
+ import { bindPreparedAction } from "./action-binding.js";
5
+ import { CliUsageError } from "./errors.js";
2
6
  export function registerCreditsCommand(program, runtime) {
7
+ const product = runtime.product;
3
8
  const credits = program.command("credits")
4
- .description("Show the current insMind credits balance")
5
- .option("--json", "output JSON")
6
- .allowExcessArguments(false);
7
- bindAction(credits, "organization", async (context, signal) => {
9
+ .description(text(product, "查看当前身份与组织的稿豆余额及变动流水", "Show the current credits balance and usage records"))
10
+ .helpCommand(false);
11
+ presentationOptions(credits, runtime);
12
+ credits.addHelpText("after", text(product, "\n只读当前 CLI 身份和组织的权益概览;不提供跨组织钱包或任意用户查询。available=max(0,total-used),成员周期限额单独展示,不能将权益池余额视为成员实际可用额度。pending 保留服务端 wait,不承诺待生效或冻结。\n流水见 credits usage --help;数量是稿豆,不折算货币。\n", "\nRead-only overview for the current CLI identity and organization context. available=max(0,total-used); member period limits are shown separately and may restrict spendable credits. pending preserves service wait without assuming activation or reservation semantics.\nDiscover records with credits usage --help. Credits are not currency.\n"));
13
+ bindPreparedAction(credits, "organization", async () => {
14
+ if (await showSchemas(credits, runtime, "credits.get"))
15
+ return { handled: true };
16
+ return { handled: false, input: undefined };
17
+ }, async (context, _input, signal) => {
8
18
  const result = await runtime.telemetry.stage("request", () => runtime.credits.get({
9
- credential: context.state.credential,
10
- organizationId: context.state.organization.id,
11
- signal
19
+ credential: context.state.credential, organizationId: context.state.organization.id, signal
20
+ }));
21
+ await runtime.telemetry.stage("output", async () => {
22
+ runtime.validators.creditsOutput(result);
23
+ runtime.presenter.result(result, { json: credits.optsWithGlobals().json === true, view: value => balanceView(value, runtime) });
24
+ });
25
+ }, { operation: "credits.get", mode: () => credits.optsWithGlobals().schema === true ? "schema" : "execute" });
26
+ const usage = credits.command("usage")
27
+ .description(text(product, "查询消费、归还、回收和过期流水", "Query consumption, restoration, recycling and expiry records"))
28
+ .helpCommand(false);
29
+ const list = usage.command("list")
30
+ .description(text(product, "读取指定时间区间的一页流水", "Read one page of records in a time range"))
31
+ .option("--from <timestamp>", text(product, "含起始时刻,带时区 ISO 8601;默认 UTC 本月月首", "inclusive ISO 8601 start with timezone; defaults to current UTC month start"))
32
+ .option("--to <timestamp>", text(product, "含结束时刻,带时区 ISO 8601;默认 UTC 本月月末", "inclusive ISO 8601 end with timezone; defaults to current UTC month end"))
33
+ .option("--limit <number>", text(product, "每页条数,默认 20", "page size, default 20"))
34
+ .option("--cursor <cursor>", text(product, "原样使用上一页 nextCursor,并保持查询区间", "reuse nextCursor unchanged with the same time range"));
35
+ presentationOptions(list, runtime);
36
+ list.addHelpText("after", text(product, "\n只读一页服务端账本,输出实际 UTC 区间、items、hasMore 和 nextCursor。没有总条数或完整区间消费合计;不能把消费、归还、回收和过期数量相加称为消费。RESTORE 为归还稿豆,不代表现金退款;未知类型保留原值,不推断方向。\n首次查询可省略日期,翻页时固定首次返回的 range 和 --limit。单条来源拆分见 credits usage get --help。\n", "\nReads one page of the service ledger, returning its actual UTC range, items, hasMore and nextCursor. No ledger total or range spending total is inferred. Consumption, restoration, recycling and expiry are distinct; RESTORE is a credit restoration, not a cash refund. Unknown types retain their value without an assumed direction.\nDates may be omitted on the first page. Continue with the returned range and the same --limit. Discover source breakdown with credits usage get --help.\n"));
37
+ bindPreparedAction(list, "organization", async () => {
38
+ if (await showSchemas(list, runtime, "credits.usage.list"))
39
+ return { handled: true };
40
+ const options = list.opts();
41
+ try {
42
+ const input = normalizeCreditsUsageListInput({
43
+ ...(options.from === undefined ? {} : { from: options.from }),
44
+ ...(options.to === undefined ? {} : { to: options.to }),
45
+ ...(options.limit === undefined ? {} : { limit: Number(options.limit) }),
46
+ ...(options.cursor === undefined ? {} : { cursor: options.cursor })
47
+ }, runtime.now());
48
+ return { handled: false, input };
49
+ }
50
+ catch (error) {
51
+ if (error instanceof RangeError)
52
+ throw new CliUsageError();
53
+ throw error;
54
+ }
55
+ }, async (context, input, signal) => {
56
+ const result = await runtime.telemetry.stage("request", () => runtime.credits.listUsage({
57
+ input, credential: context.state.credential, organizationId: context.state.organization.id, signal
58
+ }));
59
+ await runtime.telemetry.stage("output", async () => {
60
+ runtime.validators.creditsUsageListOutput(result);
61
+ runtime.presenter.result(result, { json: list.optsWithGlobals().json === true, view: value => usageListView(value, input.limit, runtime) });
62
+ });
63
+ }, { operation: "credits.usage.list", mode: () => list.optsWithGlobals().schema === true ? "schema" : "execute" });
64
+ const get = usage.command("get")
65
+ .description(text(product, "按流水 ID 读取来源拆分", "Read source breakdown by record ID"))
66
+ .argument("[record-id]", text(product, "流水 ID;执行查询时必填", "record ID, required for execution"));
67
+ presentationOptions(get, runtime);
68
+ get.addHelpText("after", text(product, "\n直接查询服务端单条来源拆分,不重新扫描流水。旧记录或某些变动类型可能没有来源拆分;空 breakdown 不表示该记录消费为零。usageType=1 为消费、2 为归还,其他值不推断方向。\n", "\nQueries one record directly without rescanning the ledger. Legacy records or some change types may have no source breakdown; an empty breakdown does not mean zero consumption. usageType=1 means consumption, 2 restoration; other values have no assumed direction.\n"));
69
+ bindPreparedAction(get, "organization", async () => {
70
+ if (await showSchemas(get, runtime, "credits.usage.get"))
71
+ return { handled: true };
72
+ const id = get.processedArgs[0];
73
+ if (typeof id !== "string" || id.trim() === "" || id === "." || id === "..")
74
+ throw new CliUsageError();
75
+ return { handled: false, input: { id } };
76
+ }, async (context, input, signal) => {
77
+ const result = await runtime.telemetry.stage("request", () => runtime.credits.getUsage({
78
+ input, credential: context.state.credential, organizationId: context.state.organization.id, signal
12
79
  }));
13
80
  await runtime.telemetry.stage("output", async () => {
14
- runtime.presenter.result(result, {
15
- json: credits.opts().json === true,
16
- view: (value) => {
17
- const balance = value;
18
- return `${balance.credits.available} insMind credits available`;
19
- }
20
- });
81
+ runtime.validators.creditsUsageGetOutput(result);
82
+ runtime.presenter.result(result, { json: get.optsWithGlobals().json === true, view: value => usageGetView(value, runtime) });
21
83
  });
22
- }, { operation: "credits.get" });
84
+ }, { operation: "credits.usage.get", mode: () => get.optsWithGlobals().schema === true ? "schema" : "execute" });
85
+ }
86
+ function presentationOptions(command, runtime) {
87
+ command.option("--json", text(runtime.product, "输出 JSON", "output JSON"))
88
+ .option("--schema", text(runtime.product, "输出本地 inputSchema 与 outputSchema,无需登录,不执行查询", "output local inputSchema and outputSchema without login or execution"))
89
+ .allowExcessArguments(false);
90
+ }
91
+ async function showSchemas(command, runtime, operation) {
92
+ if (command.optsWithGlobals().schema !== true)
93
+ return false;
94
+ await runtime.telemetry.stage("output", async () => {
95
+ runtime.io.writeOut(`${JSON.stringify({ inputSchema: contractSchema(operation, "input"), outputSchema: contractSchema(operation, "output") })}\n`);
96
+ });
97
+ return true;
98
+ }
99
+ function balanceView(result, runtime) {
100
+ const english = runtime.product.id === "insmind";
101
+ const unit = english ? "credits" : "稿豆";
102
+ const balance = result.credits;
103
+ return [english ? `${balance.available} ${unit} available in the overview` : `概览余额:${balance.available} ${unit}`,
104
+ `total=${balance.total}, used=${balance.used}, pending(wait)=${balance.pending}`,
105
+ ...(result.balances ?? []).map(row => [row.identifier ?? "—", `total=${row.total}`, `used=${row.used}`, `pending(wait)=${row.pending}`, `available=${row.available}`,
106
+ ...(row.memberPeriodLimit === undefined ? [] : [english ? `member period limit=${row.memberPeriodLimit}` : `成员周期限额=${row.memberPeriodLimit}`])].join(" · ")),
107
+ ...(result.balances?.some(row => row.memberPeriodLimit !== undefined) ? [english
108
+ ? "Member limits are separate; the overview balance does not guarantee spendable credits."
109
+ : "成员限额单独生效,概览余额不保证当前成员可用数量。"] : [])
110
+ ].join("\n");
111
+ }
112
+ function usageListView(result, limit, runtime) {
113
+ const product = runtime.product;
114
+ const unit = product.id === "gaoding" ? "稿豆" : "credits";
115
+ const more = result.hasMore ? `${product.commandName} credits usage list --from ${quote(result.range.from)} --to ${quote(result.range.to)} --limit ${limit} --cursor ${quote(result.nextCursor)} --json`
116
+ : text(product, "已到末页", "End of records");
117
+ return [`${result.range.from} → ${result.range.to} (UTC)`,
118
+ ...result.items.map(row => `${row.recordedAt} · ${row.id} · ${row.changeType} · ${signedAmount(row.amount, row.changeType)} ${unit}${row.description ? ` · ${row.description}` : ""}`),
119
+ ...(result.items.length ? [] : [text(product, "本页无记录", "No records on this page")]),
120
+ `${text(product, "本页条数", "Page count")}: ${result.items.length}; hasMore=${result.hasMore}`,
121
+ more, text(product, "本页不是区间消费总计;完整字段见 --json。", "This page is not a range spending total. Use --json for all fields.")].join("\n");
122
+ }
123
+ function usageGetView(result, runtime) {
124
+ const product = runtime.product;
125
+ const unit = product.id === "gaoding" ? "稿豆" : "credits";
126
+ return [result.id, ...result.breakdown.map(row => `${row.sourceType ?? text(product, "来源未知", "Unknown source")} · usageType=${row.usageType ?? "?"} · ${row.usageType === 2 ? "+" : row.usageType === 1 ? "-" : ""}${row.amount} ${unit}`),
127
+ ...(result.breakdown.length ? [] : [text(product, "服务端未提供拆分,不代表消耗为零。", "No breakdown returned; this does not mean zero consumption.")])].join("\n");
128
+ }
129
+ function signedAmount(amount, type) {
130
+ if (amount === 0)
131
+ return "0";
132
+ return `${type === "RESTORE" ? "+" : ["CONSUME", "RECYCLE", "EXPIRE"].includes(type) ? "-" : ""}${amount}`;
23
133
  }
134
+ function quote(value) { return `'${value.replaceAll("'", "'\\''")}'`; }
@@ -11,6 +11,7 @@ export function registerDamCommands(program, runtime) {
11
11
  "",
12
12
  text(runtime.product, "先通过 repository list、folder list、tag list 或资源查询取得真实 ID,再操作;名称、前端 URL 和旧缓存不能代替 ID。", "Discover real IDs with repository list, folder list, tag list or asset queries before acting; names, frontend URLs and old caches are not IDs."),
13
13
  text(runtime.product, "支持的命令以本 help 为准;读取所选子命令的 --help 获取参数、作用范围和输出形式。", "Available commands are listed here; read the selected subcommand's --help for parameters, scope and output mode."),
14
+ text(runtime.product, "资源库 ID 与组织 ID 不同。团队/企业资料显式传查询到的 repository_id;list/search/upload 省略资源库时默认个人库。素材处理使用详情中的资源链接或下载后的本地文件,再从 tool list 发现处理能力。", "Repository IDs differ from organization IDs. Pass a discovered repository_id for team/enterprise assets; list/search/upload default to the personal repository when omitted. To process an asset, use its resource link or downloaded file and discover processing with tool list."),
14
15
  text(runtime.product, "写入结果未确认时先查询实际状态,不重复提交。跨资源库查询、受保护路径上传和永久删除须有用户明确授权。", "Inspect actual state before retrying an unconfirmed write. Cross-repository queries, protected-path uploads and permanent deletion require explicit user authorization."),
15
16
  ""
16
17
  ].join("\n"));
@@ -41,7 +42,7 @@ export function registerDamCommands(program, runtime) {
41
42
  .option("--parent-id <id>", text(runtime.product, "父文件夹 ID", "parent folder ID"))
42
43
  .option("--query <text>", text(runtime.product, "按名称筛选", "filter by name"))
43
44
  .option("--page <n>", text(runtime.product, "页码", "page number"), positiveInteger)
44
- .option("--page-size <1-100>", text(runtime.product, "分页大小", "page size"), pageSize)
45
+ .option("--page-size <number>", text(runtime.product, "分页大小", "page size"), positiveInteger)
45
46
  .option("--json", text(runtime.product, "输出 JSON", "output JSON"));
46
47
  bindPreparedAction(folderList, "organization", async (signal) => {
47
48
  signal.throwIfAborted();
@@ -294,6 +295,7 @@ export function registerDamCommands(program, runtime) {
294
295
  .option("--allow-sensitive-path", text(runtime.product, "明确允许受保护路径", "allow a protected local path"))
295
296
  .option("--wait-analysis", text(runtime.product, "等待素材分析结束", "wait for asset analysis"))
296
297
  .option("--json", text(runtime.product, "输出 JSON", "output JSON"));
298
+ upload.addHelpText("after", text(runtime.product, "\n<file> 是本地文件路径(不是 file URI);路径含空格时按 shell 规则引用。默认上传个人库根目录 0,标题默认取不含扩展名的文件名;团队位置显式传资源库和文件夹 ID。返回素材详情表示已创建;--wait-analysis 额外等待分析,未知写入先查目标位置,不重复上传。\n", "\n<file> is a local path, not a file URI; quote spaces for the shell. Defaults to personal repository root 0 and a title from the filename without its extension. Specify repository/folder IDs for team destinations. Returned asset details confirm creation; --wait-analysis also waits for analysis. Inspect the destination before repeating an unconfirmed upload.\n"));
297
299
  bindPreparedAction(upload, "organization", async (signal) => {
298
300
  signal.throwIfAborted();
299
301
  const options = upload.opts();
@@ -364,9 +366,10 @@ function browseCommand(command, runtime) {
364
366
  .option("--type <type>", text(runtime.product, "素材类型", "asset type"))
365
367
  .option("--asset-format <csv>", text(runtime.product, "文件格式,逗号分隔", "comma-separated file formats"))
366
368
  .option("--tag-ids <csv>", text(runtime.product, "标签 ID,逗号分隔", "comma-separated tag IDs"))
367
- .option("--page-size <1-100>", text(runtime.product, "请求分页大小", "request page size"), pageSize)
368
- .option("--cursor <id>", text(runtime.product, "分页游标", "pagination cursor"))
369
- .option("--json", text(runtime.product, "输出 JSON", "output JSON"));
369
+ .option("--page-size <number>", text(runtime.product, "请求分页大小", "request page size"), positiveInteger)
370
+ .option("--cursor <id>", text(runtime.product, "原样使用上一页 next_cursor,并保持相同筛选", "reuse the previous next_cursor unchanged with the same filters"))
371
+ .option("--json", text(runtime.product, "输出 JSON", "output JSON"))
372
+ .addHelpText("after", text(runtime.product, "\n默认个人资源库,每页 20 条,包含子文件夹;finish=false 时用 next_cursor 继续同范围查询,本页不代表全部结果。空结果不证明其他资源库不存在该素材;按用户指定范围核对资源库和筛选。\n", "\nDefaults to the personal repository, 20 items and inclusion of child folders. When finish=false, continue with next_cursor and unchanged scope; one page is not the entire result. An empty page says nothing about other repositories; check the user's intended repository and filters.\n"));
370
373
  }
371
374
  function browseInput(command) {
372
375
  const options = command.opts();
@@ -388,15 +391,7 @@ function defined(key, value) {
388
391
  return value === undefined ? {} : { [key]: value };
389
392
  }
390
393
  function csv(value) {
391
- return value?.split(",").map((item) => item.trim()).filter((item) => item !== "");
392
- }
393
- function pageSize(value) {
394
- if (!/^\d+$/u.test(value))
395
- throw new CliUsageError();
396
- const parsed = Number(value);
397
- if (!Number.isInteger(parsed) || parsed < 1 || parsed > 100)
398
- throw new CliUsageError();
399
- return parsed;
394
+ return value?.split(",").map((item) => item.trim());
400
395
  }
401
396
  function positiveInteger(value) {
402
397
  if (!/^\d+$/u.test(value))
@@ -424,7 +419,8 @@ function assetListView(value, product) {
424
419
  `${text(product, "资源库", "Repositories")}: ${result.repository_ids.join(", ")}`,
425
420
  `${text(product, "本批 / 总数", "This batch / total")}: ${result.assets.length} / ${result.total}`,
426
421
  result.finish ? text(product, "已到最后一页。", "Last page.")
427
- : text(product, `还有下一页;保留筛选条件,使用 --cursor ${result.next_cursor ?? "<cursor>"} 查询。`, `More results; keep the same filters and query with --cursor ${result.next_cursor ?? "<cursor>"}.`),
422
+ : !result.next_cursor ? text(product, "服务提示还有结果,但未返回可用游标,无法续页。", "More results are indicated, but the service supplied no cursor.")
423
+ : text(product, `还有下一页;保留筛选条件,使用 --cursor ${result.next_cursor ?? "<cursor>"} 查询。`, `More results; keep the same filters and query with --cursor ${result.next_cursor ?? "<cursor>"}.`),
428
424
  ...(result.assets.length ? [text(product, "ID\t标题\t类型\t格式", "ID\tTitle\tType\tFormat"), ...result.assets.map(assetRow)]
429
425
  : [text(product, "暂无素材。", "No assets.")])
430
426
  ].join("\n");
@@ -15,19 +15,20 @@ export function registerEditorCommands(program, runtime) {
15
15
  .helpCommand(false);
16
16
  editor.addHelpText("after", [
17
17
  "",
18
+ text(runtime.product, "对象是已连接作品中的元素。用户提供附件图片/媒体链接并要求改字、分层、矢量化或其他图片处理时,先从 tool list 发现能力;无需为了这些操作新建 Board。", "This group operates elements in a connected work. For attached images or media links needing text replacement, decomposition, vectorization or other processing, discover tool list first; these operations do not require a new Board."),
18
19
  text(runtime.product, "操作一个当前 Session、当前 Page 的直属 Shape 和绑定 Connector;单操作者串行执行。", "Operate one current Session and its Page's direct Shapes and bound Connectors, serially with one operator."),
19
20
  text(runtime.product, "元素类型与字段以 editor apply --schema 为准;Schema 查询无需登录或连接 Editor。", "Discover element types and fields with editor apply --schema; no login or Editor connection is required."),
20
21
  text(runtime.product, "当前不支持嵌套元素、自由/半绑定 Connector、页面或选择修改;UNSUPPORTED_PAGE_CONTENT 时保留原作品并换用空白或专用 Page。", "Nested elements, free/half-bound Connectors, page and selection changes are unsupported. On UNSUPPORTED_PAGE_CONTENT, preserve the work and use a blank or dedicated Page."),
21
- text(runtime.product, "流程:connect → snapshot → apply → snapshot/screenshot 复查 → save → disconnect。apply 不代替 save。", "Workflow: connect → snapshot → apply → review snapshot/screenshot → save → disconnect. Apply does not replace Save."),
22
+ text(runtime.product, "流程:connect → snapshot → apply → snapshot/screenshot 复查 → 按用户授权 save → disconnect。apply 不代替 save。只预览/暂不保存时停在预览;用户要求断开就执行 disconnect,断开不隐含保存。", "Workflow: connect → snapshot → apply → review snapshot/screenshot → save as authorized → disconnect. Apply does not replace Save. For preview-only requests stop at preview; on a request to disconnect, execute disconnect without implicitly saving."),
22
23
  text(runtime.product, "EDITOR_BUSY 时等待原命令结束;写入超时、取消或断连时,先重新连接同一作品并检查真实状态,不直接重试写入。", "On EDITOR_BUSY, wait for the original command. After a write times out, is cancelled or disconnects, reconnect to the same work and inspect its state before deciding what to do."),
23
24
  ""
24
25
  ].join("\n"));
25
26
  const connect = leaf(editor.command("connect"))
26
27
  .description(text(runtime.product, "打开并连接一个 AI+ Editor 作品", "Open and connect to an Editor work"))
27
- .argument("[target]", text(runtime.product, "作品 ID 或完整 URL", "work ID or complete URL"));
28
+ .argument("[target]", text(runtime.product, "已有作品的 ID 或完整 URL;留空会新建线上 Board", "existing work ID or full URL; omitting it creates a new production Board"));
28
29
  connect.addHelpText("after", [
29
30
  "",
30
- text(runtime.product, "省略 target 新建线上 Board;数字按作品 ID 打开;完整 HTTP(S) URL 按该 URL 的环境打开。", "Omit target for a new production Board, use a numeric work ID, or provide a supported insMind production Editor URL."),
31
+ text(runtime.product, "继续已有作品时,传数字作品 ID 或完整 HTTP(S) URL。还没有目标就先向用户索取作品链接或 ID。用户要求新建时才省略 target。", "To continue an existing work, pass its numeric ID or supported insMind production Editor URL. If the target is missing, ask the user for the link or ID. Omit target only when the user requests a new Board."),
31
32
  text(runtime.product, "会打开浏览器并替换旧 Session;浏览器登录、加载、Board 类型、编辑/保存权限与页面内容检查通过后才成功。CLI 登录不能替代浏览器登录。", "Opens the browser and replaces the old Session. Browser login, loading, Board type, edit/save permission and page-content checks must pass. CLI credentials do not replace browser login."),
32
33
  text(runtime.product, "输出 JSON {target},不含连接凭证。连接失败时停止写入,让用户在页面处理登录或权限,再重新连接。", "Returns JSON {target} without connection credentials. On failure, stop writing and let the user resolve browser login or permissions before reconnecting."),
33
34
  text(runtime.product, "页面切换作品会断开 Session;EDITOR_NOT_READY、EDITOR_SESSION_NOT_FOUND 或 EDITOR_NOT_CONNECTED 时确认目标后重连,不轮询旧 Session。", "Switching works disconnects the Session. On EDITOR_NOT_READY, EDITOR_SESSION_NOT_FOUND or EDITOR_NOT_CONNECTED, verify the target and reconnect instead of polling the old Session."),
@@ -46,7 +47,7 @@ export function registerEditorCommands(program, runtime) {
46
47
  });
47
48
  const disconnect = leaf(editor.command("disconnect"))
48
49
  .description(text(runtime.product, "断开当前 Editor 连接", "Disconnect the current Editor"));
49
- disconnect.addHelpText("after", `\n${text(runtime.product, "输出 JSON {disconnected};断开连接不保存作品,需先显式执行 editor save。", "Returns JSON {disconnected}. Disconnecting does not save the work; run editor save explicitly first.")}\n`);
50
+ disconnect.addHelpText("after", `\n${text(runtime.product, "输出 JSON {disconnected},解除当前 CLI 会话连接,不保存作品、不关闭浏览器页面。需要保留修改且已获保存授权时先 save;用户只要求断开或明确不保存时直接断开,并说明未保存状态。", "Returns JSON {disconnected}, ending the CLI session without saving the work or closing its browser page. Save first only when persistence is intended and authorized; if the user requests only disconnection or no save, disconnect and state what remains unsaved.")}\n`);
50
51
  jsonOutput(disconnect);
51
52
  bindAction(disconnect, "none", async (_context, signal) => {
52
53
  writeJson(runtime, await runtime.telemetry.stage("editor.disconnect", () => runtime.editor.disconnect({ signal })));
@@ -70,11 +71,12 @@ export function registerEditorCommands(program, runtime) {
70
71
  apply.addHelpText("after", [
71
72
  "",
72
73
  text(runtime.product, "--schema 与 --input 必须且只能选择一个。Schema 为本地契约,不连接 Editor;执行成功输出 JSON {appliedCount}。", "Choose exactly one of --schema and --input. Schema reads the local contract without connecting to Editor; successful execution returns JSON {appliedCount}."),
74
+ text(runtime.product, "先保存完整 JSON,再用 --input request.json 执行;--input - 必须在同一条 shell 命令中经管道或重定向提供完整 JSON,不交互填参。", "Save complete JSON before using --input request.json. With --input -, pipe or redirect complete JSON in the same shell command; input is not an interactive form."),
73
75
  text(runtime.product, "输入对象包含 host_application 和按序执行的 actions 数组;类型、必填字段与可选值见 --schema。使用简短语义 ID;create ID 必须唯一,Connector 可引用本批次更早创建的 Shape。", "Input is an object with host_application and an ordered actions array; discover types, required fields and choices with --schema. Use short semantic IDs. Create IDs must be unique; a Connector may reference a Shape created earlier in the batch."),
74
76
  text(runtime.product, "update 提交完整元素而非 patch,不改变 id 或 _type。delete 要求 ID 存在;删除 Shape 同时删除绑定的 Connector。", "Update requires the full element, not a patch, without changing id or _type. Delete requires an existing ID; deleting a Shape also deletes its bound Connectors."),
75
77
  text(runtime.product, "Shape 的 x/y 为 Page 左上角坐标,w/h 大于 0;数值必须有限。颜色用 #RRGGBB 或 #RRGGBBAA,仅 stroke 可为 null。Connector 用 fromId/toId 表达有方向的 Shape 关系。", "Shape x/y locate its top-left corner in Page coordinates; w/h must exceed zero and numbers must be finite. Colors use #RRGGBB or #RRGGBBAA; only stroke accepts null. Connector fromId/toId express a directed Shape relationship."),
76
78
  text(runtime.product, "整批先预检,再在可回滚事务中应用;INVALID_ACTIONS 时修正输入,APPLY_FAILED 时读 Snapshot 确认回滚。EDITOR_ROLLBACK_FAILED 时停止 apply/save,只读检查并报告。", "The batch is checked before one rollback-capable transaction. Correct INVALID_ACTIONS; on APPLY_FAILED read a Snapshot to confirm rollback. On EDITOR_ROLLBACK_FAILED, stop apply/save, inspect read-only and report."),
77
- text(runtime.product, "成功不表示已保存或视觉正确;读取新 Snapshot,涉及布局/文字/连线时查看截图,再显式 save。超时、取消或断连后先检查真实状态,不重复提交。", "Success proves neither persistence nor correct rendering. Read a new Snapshot, view a screenshot for layout/text/connectors, then explicitly save. Inspect real state after timeout, cancellation or disconnection instead of resubmitting."),
79
+ text(runtime.product, "成功不表示已保存或视觉正确;读取新 Snapshot,涉及布局/文字/连线时查看截图。只预览时交付截图且不 save;需要持久化并已获授权时再显式 save。超时、取消或断连后先检查真实状态,不重复提交。", "Success proves neither persistence nor correct rendering. Read a new Snapshot and view a screenshot for layout/text/connectors. Deliver preview-only requests without save; explicitly save when persistence is intended and authorized. Inspect real state after timeout, cancellation or disconnection instead of resubmitting."),
78
80
  ""
79
81
  ].join("\n"));
80
82
  jsonOutput(apply);
@@ -1,6 +1,7 @@
1
+ import { CreditsPageCursorError } from "../features/credits/use-cases.js";
1
2
  import { observedErrorCategory, observedErrorMessage } from "./observed-errors.js";
2
3
  import { TaskBackgroundError } from "../features/task/task-background.js";
3
- import { TaskNotFoundError } from "../features/task/use-cases.js";
4
+ import { CreationInputUploadError, TaskNotFoundError } from "../features/task/use-cases.js";
4
5
  import { TaskStoreError } from "../features/task/store.js";
5
6
  import { CommanderError } from "commander";
6
7
  import { AuthExpiredError, AuthRequiredError } from "../features/auth/access-policy.js";
@@ -9,7 +10,7 @@ import { SsoRequestError } from "../features/auth/sso-service.js";
9
10
  import { AuthorizedAccountContextMissingError, BrowserOpenError, DeviceAuthorizationExpiredError } from "../features/auth/use-cases.js";
10
11
  import { AgentInputError } from "../features/agent/use-cases.js";
11
12
  import { ToolInputError } from "../features/tool/catalog.js";
12
- import { ToolTaskFailedError, ToolTaskCanceledError, ToolInsufficientCreditsError } from "../features/tool/tool-api-adapter.js";
13
+ import { ToolTaskFailedError, ToolTaskCanceledError, ToolInsufficientCreditsError } from "../features/tool/tool-errors.js";
13
14
  import { AgentAuditRejectedError } from "../features/agent/creative-protocol.js";
14
15
  import { isContentReviewRejection } from "../features/task/creation-refusal.js";
15
16
  import { ObjectStorageUploadError } from "../features/dam/object-storage.js";
@@ -47,12 +48,18 @@ export function isHelpOutcome(error) {
47
48
  && (error.code === "commander.helpDisplayed" || error.code === "commander.version");
48
49
  }
49
50
  export function mapCliError(error, options) {
50
- const outcome = mapBaseCliError(error, options);
51
+ const outcome = mapBaseCliError(error instanceof CreationInputUploadError ? error.cause : error, options);
51
52
  if (outcome.kind === "interrupted")
52
53
  return { ...outcome, failure: { code: "INTERRUPTED",
53
54
  message: options.product?.id === "insmind" ? "This operation stopped waiting." : "本次操作已停止等待。",
54
55
  ...(outcome.failure?.details ? { details: outcome.failure.details } : {}) } };
55
- if (error instanceof TaskBackgroundError)
56
+ if (error instanceof CreationInputUploadError) {
57
+ const en = options.product?.id === "insmind";
58
+ return failure(outcome.failure.code, en ? "An input file could not be uploaded. The creation request has not been sent."
59
+ : "输入素材上传失败,本次创作请求尚未派发。", outcome.exitCode, [en ? "Tell the user which step failed. Once the connection is available, the same request and original files can be used again."
60
+ : "向用户说明失败发生在上传原素材时。网络可用后,可用原需求和原素材再次发起。"], { ...outcome.failure.details, phase: "input_upload_before_dispatch" });
61
+ }
62
+ if (error instanceof TaskBackgroundError || (error instanceof ToolTaskFailedError && error.imagePixelRequirement))
56
63
  return outcome;
57
64
  const remote = remoteCause(error);
58
65
  const evidence = {
@@ -72,10 +79,38 @@ export function mapCliError(error, options) {
72
79
  return outcome;
73
80
  return { ...outcome, failure: { ...outcome.failure, message: observedErrorMessage(category, evidence) } };
74
81
  }
82
+ // Project the service's explicit validation error, never its full response or rejected input.
83
+ function toolBusinessDetails(error) {
84
+ const details = {};
85
+ if (error.remoteCode && /^[\w.-]{1,80}$/u.test(error.remoteCode))
86
+ details.remote_code = error.remoteCode;
87
+ let body;
88
+ try {
89
+ body = JSON.parse(error.remoteBody ?? "");
90
+ }
91
+ catch {
92
+ return details;
93
+ }
94
+ if (!body || typeof body !== "object" || Array.isArray(body))
95
+ return details;
96
+ const envelope = body;
97
+ const item = Array.isArray(envelope.detail) ? envelope.detail[0] : undefined;
98
+ const issue = item && typeof item === "object" ? item : undefined;
99
+ const field = Array.isArray(issue?.loc) ? issue.loc.map(String).join(".") : envelope.field;
100
+ if (typeof field === "string" && /^[\w.-]{1,160}$/u.test(field))
101
+ details.field = field;
102
+ const message = issue?.msg ?? envelope.message;
103
+ if (typeof message === "string" && message.trim() && message.length <= 180
104
+ && !/[\u0000-\u001f\u007f<>/\\]|\[REDACTED\]|(?:bearer|password|prompt|token|secret)\s*[:=\s]/iu.test(message)
105
+ && redactSensitiveText(message) === message)
106
+ details.remote_message = message;
107
+ return details;
108
+ }
75
109
  function mapBaseCliError(error, options) {
76
110
  const insmind = options.product?.id === "insmind";
77
111
  const command = options.product?.commandName ?? "gd-cli";
78
112
  const text = (zh, en) => insmind ? en : zh;
113
+ const refusalSteps = ["agent.send", "tool.call", "task.get"].includes(options.operation ?? "") ? [text("向用户说明本次失败原因和可交付结果。换模型或改参数再做一次属于新创作,须有用户补充的需求或另做一次的明确授权。", "Tell the user why this creation failed and what, if anything, can be delivered. A different model or revised settings start a new creation. Proceed only with a revised request or explicit authorization for another creation.")] : undefined;
79
114
  if (error instanceof ToolTaskCanceledError)
80
115
  return { kind: "interrupted", exitCode: 130,
81
116
  failure: { code: "INTERRUPTED", message: text("生成任务已取消。", "The creation task was canceled.") } };
@@ -144,18 +179,20 @@ function mapBaseCliError(error, options) {
144
179
  model_tool_mismatch: ["模型不属于所选工具。", "The model does not belong to the selected tool."],
145
180
  model_required: ["缺少 model 字段。", "The model field is required."],
146
181
  model_parameters: ["参数不符合所选模型要求。", "The arguments do not match the selected model requirements."],
147
- invalid_asset_url: ["素材 URL 不符合可访问资源要求。", "The asset URL does not meet the accessible resource requirements."]
182
+ invalid_asset_url: ["素材 URL 不符合可访问资源要求。", "The asset URL does not meet the accessible resource requirements."],
183
+ mask_geometry_or_format: ["无法转换 mask。请提供可读取的单帧 PNG;叠加选区时需与转正后的原图尺寸一致。", "Could not convert the mask. Supply a readable single-frame PNG. For an overlay, match the auto-oriented source dimensions."]
148
184
  };
149
185
  const description = descriptions[error.reason];
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 } : {}) });
186
+ return failure("USAGE_ERROR", description ? text(...description) : text("创作输入不可用,请核对模型与参数。", "Check the model and creation arguments."), 2, error.reason === "mask_geometry_or_format" ? [text(`该选区尚未提交处理。用 ${command} model get <model> 查看 mask 的要求,保留用户选区,修正文件后再调用。`, `This selection has not been submitted. Check the mask requirements with ${command} model get <model>, preserve the user's selection and call again after correcting the file.`)]
187
+ : [`${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 } : {}) });
151
188
  }
152
189
  if (error instanceof LocalFileInputError) {
153
190
  const message = error.reason === "invalid_file_uri"
154
191
  ? text("本地文件地址格式不正确。Windows 地址示例:file:///C:/目录/文件。", "Invalid local file URL. Windows example: file:///C:/folder/file.")
155
192
  : error.reason === "file_read_failed" && systemErrorCode(error) === "ENOENT"
156
193
  ? 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.")
194
+ : error.reason === "invalid_media_type_header"
195
+ ? text("mediaType 包含无法作为上传请求头发送的字符,请更正。", "The mediaType contains characters that cannot be sent in an upload header. Correct the value.")
159
196
  : text("本地素材文件不可用于上传。", "The local asset file cannot be uploaded.");
160
197
  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
198
  }
@@ -174,7 +211,7 @@ function mapBaseCliError(error, options) {
174
211
  return failure("USAGE_ERROR", "命令或参数无效,请查看 --help。", 2);
175
212
  }
176
213
  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);
214
+ return failure("INSUFFICIENT_CREDITS", text("当前可用额度不足,本次生成未能完成。", "Available credits are insufficient; this creation could not complete."), 1, refusalSteps);
178
215
  }
179
216
  if (isContentReviewRejection(error, { product: options.product?.id ?? "gaoding", operation: options.operation })) {
180
217
  const phase = error instanceof AgentAuditRejectedError ? error.phase : undefined;
@@ -184,13 +221,20 @@ function mapBaseCliError(error, options) {
184
221
  : phase === "output"
185
222
  ? text("生成内容未通过审核,无法交付本次结果。", "The generated content did not pass review. This result cannot be delivered.")
186
223
  : text("本次创作被内容审核拒绝。", "This creation was rejected by content review.");
187
- return failure(error instanceof ToolTaskFailedError ? "TOOL_TASK_FAILED" : "REMOTE_REQUEST_FAILED", message, 1, [text("请检查并调整创作内容;不要重复提交相同请求。", "Review and adjust the creation content; do not resubmit the same request.")], { reason });
224
+ return failure(error instanceof ToolTaskFailedError ? "TOOL_TASK_FAILED" : "REMOTE_REQUEST_FAILED", message, 1, refusalSteps, { reason });
188
225
  }
226
+ if (error instanceof CreditsPageCursorError)
227
+ return failure("REMOTE_PROTOCOL_INCOMPATIBLE", text("已收到本页流水,但服务没有返回可用的下一页游标。已知流水在 details.partial_result,本次无法续页。", "This page was received without a usable cursor. Its records are in details.partial_result; the next page cannot be requested."), 1, undefined, { partial_result: error.partialResult });
189
228
  if (error instanceof RemoteProtocolError) {
190
229
  return failure("REMOTE_PROTOCOL_INCOMPATIBLE", text("稿定服务返回了当前 CLI 无法安全处理的结果;为避免重复创作,已停止处理。", "The insMind service returned a result this CLI cannot safely process; processing stopped to avoid duplicate creation."), 1, [text(`保留诊断 ID。若已有任务 ID,用 ${command} task get <id> 查询原任务;查询异常不能证明生成失败,不要重新提交。`, `Keep the diagnostic ID. If a Task ID is available, use ${command} task get <id>. A query error does not prove generation failed; do not resubmit.`)]);
191
230
  }
192
231
  if (error instanceof ToolTaskFailedError) {
193
- return failure("TOOL_TASK_FAILED", insmind ? "The Tool task failed." : "稿定工具任务执行失败。", 1);
232
+ if (error.imagePixelRequirement) {
233
+ const { minimumPixels, width, height } = error.imagePixelRequirement;
234
+ return failure("TOOL_TASK_FAILED", text(`服务端收到的图片为 ${width} × ${height} 像素。请换用总像素数至少为 ${minimumPixels} 的图片。`, `The service received a ${width} × ${height} pixel image. Use an image with at least ${minimumPixels} pixels in total.`), 1, refusalSteps, { remote_code: error.remoteCode, field: "image", minimum_pixels: minimumPixels, received_width: width, received_height: height });
235
+ }
236
+ const details = toolBusinessDetails(error);
237
+ return failure("TOOL_TASK_FAILED", insmind ? "The Tool task failed." : "稿定工具任务执行失败。", 1, refusalSteps, Object.keys(details).length ? details : undefined);
194
238
  }
195
239
  if (error instanceof DamAssetNotFoundError) {
196
240
  return failure("DAM_ASSET_NOT_FOUND", insmind ? "The requested asset was not found." : "未找到指定的 DAM 素材。", 1);
@@ -248,6 +292,8 @@ function mapBaseCliError(error, options) {
248
292
  request: ["稿定服务请求失败;是否已受理取决于本次请求阶段。", "The service request failed; acceptance depends on the request phase."]
249
293
  };
250
294
  return failure("REMOTE_REQUEST_FAILED", text(...messages[reason]), 1, [text("创作或写操作若已派发,先查询原任务或对象;不要直接重复提交。使用诊断 ID 排查原因。", "For dispatched creation or write operations, query the original task or object before submitting again. Use the diagnostic ID to investigate.")], { reason, system_code: systemErrorCode(error),
295
+ ...(error instanceof RemoteRequestError && options.operation === "tool.call"
296
+ && error.status !== undefined && error.status >= 400 && error.status < 500 ? toolBusinessDetails(error) : {}),
251
297
  ...((error instanceof RemoteRequestError || error instanceof SsoRequestError) && error.status !== undefined ? { http_status: error.status } : {}) });
252
298
  }
253
299
  if (error instanceof OutputContractError) {
@@ -255,19 +301,32 @@ function mapBaseCliError(error, options) {
255
301
  }
256
302
  if (error instanceof LocalFileError)
257
303
  return failure("LOCAL_STATE_ERROR", text("无法访问或解析本地文件,操作未完成。", "A local file could not be accessed or parsed; the operation did not complete."), 1, [text("先检查所列文件的权限、可用空间和内容;不要删除凭证来处理文件故障。", "Check the file's permissions, available space and contents; do not delete credentials to resolve a file failure.")], { reason: error.reason, file: error.file, system_code: systemErrorCode(error) });
258
- if (error instanceof EditorBridgeUnavailableError)
259
- return failure("EDITOR_NOT_READY", text("本地 Editor Bridge 连接不可用。", "The local Editor Bridge connection is unavailable."), 1, [text(`先检查原作品状态,再执行 ${command} editor connect [target];不要直接重复写入。`, `Inspect the original work, then run ${command} editor connect [target]; do not repeat writes directly.`)], { phase: "editor_connection" });
260
- if (error instanceof EditorBridgeError
261
- || error instanceof EditorSessionNotFoundError
262
- || error instanceof EditorNotReadyError) {
263
- if (insmind) {
304
+ if (error instanceof EditorBridgeUnavailableError || error instanceof EditorBridgeError
305
+ || error instanceof EditorSessionNotFoundError || error instanceof EditorNotReadyError) {
306
+ const unavailable = error instanceof EditorBridgeUnavailableError;
307
+ const code = unavailable ? "EDITOR_NOT_READY" : error.code;
308
+ let message = redactSensitiveText(error.message).slice(0, 1024);
309
+ if (unavailable)
310
+ message = text("本地 Editor Bridge 连接不可用。", "The local Editor Bridge connection is unavailable.");
311
+ else if (insmind) {
264
312
  if (error instanceof EditorSessionNotFoundError)
265
- return failure(error.code, `No Editor session is available. Run ${command} editor connect [target] again.`, 1);
266
- if (error instanceof EditorNotReadyError)
267
- return failure(error.code, "The Editor page did not become ready in time.", 1);
268
- return failure(error.code, error.code === "EDITOR_BRIDGE_INVALID_RESPONSE" ? "The Editor Bridge returned an invalid response." : `Editor: ${redactSensitiveText(error.message).slice(0, 1024)}`, 1, ["For a failed write, inspect the original work before repeating apply or save. Use editor --help for recovery by error code."]);
313
+ message = "No Editor session is available.";
314
+ else if (error instanceof EditorNotReadyError)
315
+ message = "The Editor page did not become ready in time.";
316
+ else
317
+ message = code === "EDITOR_BRIDGE_INVALID_RESPONSE" ? "The Editor Bridge returned an invalid response." : `Editor: ${message}`;
318
+ }
319
+ const connectionError = ["EDITOR_SESSION_NOT_FOUND", "EDITOR_NOT_CONNECTED", "EDITOR_DISCONNECTED", "EDITOR_NOT_READY", "EDITOR_RPC_TIMEOUT"].includes(code);
320
+ let nextStep = text(`按 ${command} editor --help 中该错误的说明处理。`, `Follow the instructions for this error in ${command} editor --help.`);
321
+ if (connectionError && (options.operation === "editor.snapshot" || options.operation === "editor.screenshot")) {
322
+ const read = options.operation === "editor.snapshot" ? "snapshot" : "screenshot";
323
+ nextStep = text(`要继续原作品,若还没有作品链接或 ID,先向用户索取。省略目标会新建线上 Board。拿到原作品的链接或 ID 后,用 ${command} editor connect <target> 连接,再执行 ${command} editor ${read}。`, `To continue the original work, ask the user for its link or ID if you don't have it. Omitting the target creates a new production Board. With the link or ID, run ${command} editor connect <target>, then ${command} editor ${read}.`);
324
+ }
325
+ else if ((options.operation === "editor.apply" || options.operation === "editor.save")
326
+ && (connectionError || ["EDITOR_ROLLBACK_FAILED", "APPLY_FAILED", "SAVE_FAILED", "EDITOR_BRIDGE_INVALID_RESPONSE"].includes(code))) {
327
+ nextStep = text("先检查原作品的实际状态,再决定后续操作。无法确认状态时停止写入,不重复 apply 或 save。", "Inspect the original work before taking further action. If the state is uncertain, stop writing without repeating apply or save.");
269
328
  }
270
- return failure(error.code, redactSensitiveText(error.message).slice(0, 1024), 1, ["写入失败时先检查原作品,不直接重复 apply 或 save;按 editor --help 中的对应错误指引处理。"]);
329
+ return failure(code, message, 1, [nextStep], unavailable ? { phase: "editor_connection" } : undefined);
271
330
  }
272
331
  if (systemErrorCode(error) === "ECONNRESET")
273
332
  return failure("REMOTE_REQUEST_FAILED", text("连接中断,未能完整收到结果。", "The connection closed before the full result was received."), 1);
@@ -1,3 +1,5 @@
1
+ import { Ajv2020 } from "ajv/dist/2020.js";
2
+ import addFormats, {} from "ajv-formats";
1
3
  import { InputContractError } from "../bootstrap/validators.js";
2
4
  import { productText } from "../product/text.js";
3
5
  function object(value) {
@@ -11,12 +13,69 @@ export function readHostInput(runtime, raw) {
11
13
  runtime.telemetry.observeHost(host_application);
12
14
  return input;
13
15
  }
14
- export function hostSchema(runtime, schema) {
15
- const description = productText(runtime.product, "填写发起本次 CLI 命令的应用名称,例如 workbuddy、qwenwork 或 trae。应用通过终端执行命令时仍填该应用的名称。用户直接在终端执行时填 terminal。其他应用填写其实际名称。", "Name the application invoking this command, for example workbuddy, qwenwork or trae. When an app uses a terminal, name the app. For direct terminal use, enter terminal. For other apps, enter their actual name.");
16
- const augment = (source) => ({ ...source,
17
- properties: { ...(object(source.properties) ? source.properties : {}), host_application: { type: "string", description } },
18
- required: [...new Set([...(Array.isArray(source.required) ? source.required : []), "host_application"])] });
16
+ const examples = new Ajv2020({ strict: false, addUsedSchema: false });
17
+ addFormats(examples);
18
+ function toolExample(runtime, source, properties, required, tool) {
19
+ const sample = { host_application: "terminal" };
20
+ const english = runtime.product.id === "insmind";
21
+ const requests = {
22
+ "image-matting-smart": ["把包单独抠出来,补全被遮住的提手。", "Isolate the bag and restore the hidden part of the handle."],
23
+ "image-edit-smart": ["把杯子改成深绿色。", "Change the cup to dark green."],
24
+ "image-remove-smart": ["把桌上的杂物移走。", "Remove the clutter from the table."],
25
+ "image-enhance-smart": ["修复这张照片中模糊的细节。", "Restore the blurred details in this photo."]
26
+ };
27
+ const model = object(properties.model) ? properties.model.const : undefined;
28
+ const request = typeof model === "string" ? requests[model] : undefined;
29
+ const values = { prompt: request?.[english ? 1 : 0] ?? (english ? "A cat at a rainy bus stop." : "一只在雨里等车的猫。"),
30
+ image: "file:///inputs/source.png", video: "file:///inputs/source.mp4", base_video: "file:///inputs/source.mp4", mask: "file:///inputs/selection.png",
31
+ resolution: tool.startsWith("video.") ? "720p" : "2K", quality: "high", audioEnabled: "false",
32
+ targetLongEdge: 2048, maxLayers: 3, canvas: { width: 1200, height: 800 }, placement: { x: 100, y: 50 },
33
+ replacements: [{ from: "2025", to: "2026" }] };
34
+ for (const key of required) {
35
+ if (typeof key !== "string" || key === "host_application")
36
+ continue;
37
+ const property = properties[key];
38
+ if (!object(property))
39
+ return;
40
+ const value = property.const ?? property.default ?? (Array.isArray(property.enum) ? property.enum[0] : undefined)
41
+ ?? values[key] ?? (property.format === "uri" ? "file:///inputs/source.png" : undefined)
42
+ ?? (object(property.items) && property.items.format === "uri" ? ["file:///inputs/source.png"] : undefined);
43
+ if (value === undefined)
44
+ return;
45
+ sample[key] = value;
46
+ }
47
+ if (object(properties.prompt) && (request || tool === "image.generate" || tool === "video.generate")) {
48
+ sample.prompt ??= values.prompt;
49
+ }
50
+ // Directory extensions can introduce requirements we cannot illustrate faithfully.
51
+ return examples.validate(source, sample) ? sample : undefined;
52
+ }
53
+ export function hostSchema(runtime, schema, tool) {
54
+ const localMedia = productText(runtime.product, "本地附件用 Path(path).resolve().as_uri() 或 pathToFileURL(path).href 生成标准 file URI,转义中文、空格和 #;已有 HTTP(S) URL 原样使用。", "Generate local file URIs with Path(path).resolve().as_uri() or pathToFileURL(path).href to escape Unicode, spaces and #; preserve existing HTTP(S) URLs.");
55
+ const description = productText(runtime.product, "填写实际发起命令的应用名。例如 Codex Agent 通过 shell 执行时填 codex,WorkBuddy 填 workbuddy,其他应用填自己的名称。示例中的 terminal 仅指用户亲自在终端运行。", "Enter the calling application's name. A Codex agent running a shell command uses codex, WorkBuddy uses workbuddy, and other apps use their own names. The example value terminal is for a person running the command directly.");
56
+ const augment = (source) => {
57
+ const properties = { ...(object(source.properties) ? source.properties : {}), host_application: { type: "string", description } };
58
+ for (const [key, property] of Object.entries(properties)) {
59
+ if (object(property) && (property.format === "uri" || (object(property.items) && property.items.format === "uri"))) {
60
+ properties[key] = { ...property, description: [property.description, localMedia].filter(Boolean).join(" ") };
61
+ }
62
+ }
63
+ if (object(properties.model) && properties.model.description === "要调用的模型机器标识。" && runtime.product.id === "insmind") {
64
+ properties.model = { ...properties.model, description: "Identifier of the selected model." };
65
+ }
66
+ const required = [...new Set([...(Array.isArray(source.required) ? source.required : []), "host_application"])];
67
+ const result = { ...source, properties, required };
68
+ if (!tool || !object(properties.model) || typeof properties.model.const !== "string")
69
+ return result;
70
+ const example = toolExample(runtime, result, properties, required, tool);
71
+ return { ...result,
72
+ ...(example ? { examples: [example] } : {}) };
73
+ };
19
74
  const result = augment(schema);
75
+ if (tool) {
76
+ const ratio = tool === "image.generate" && productText(runtime.product, "ratio 表示请求的目标宽高比。", "ratio is the requested aspect ratio.");
77
+ result.description = [result.description, localMedia, ratio].filter(Boolean).join(" ");
78
+ }
20
79
  if (Array.isArray(schema.allOf)) {
21
80
  return { ...result, allOf: schema.allOf.map(branch => object(branch) && object(branch.then) ? { ...branch, then: augment(branch.then) } : branch) };
22
81
  }