@insmind/cli 2.1.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 (95) hide show
  1. package/contracts/operations/agent.send/input.schema.json +1 -77
  2. package/contracts/operations/dam.folder.list/input.schema.json +0 -1
  3. package/contracts/operations/dam.folder.list/output.schema.json +1 -2
  4. package/contracts/operations/dam.list/input.schema.json +3 -6
  5. package/contracts/operations/dam.list/output.schema.json +1 -2
  6. package/contracts/operations/dam.search/input.schema.json +3 -6
  7. package/contracts/operations/dam.search/output.schema.json +1 -2
  8. package/contracts/operations/tool.call/models/image-edit-smart.schema.json +1 -2
  9. package/contracts/operations/tool.call/models/image-expand-smart.schema.json +1 -2
  10. package/contracts/operations/tool.call/models/image-layers-smart.schema.json +1 -3
  11. package/contracts/operations/tool.call/models/video-edit-smart.schema.json +0 -3
  12. package/contracts/operations/tool.call/ocr-payload.schema.json +4 -5
  13. package/dist/bin/postinstall.js +22 -6
  14. package/dist/bin/task-worker.js +2 -2
  15. package/dist/src/bootstrap/create-cli.js +13 -6
  16. package/dist/src/bootstrap/create-runtime.js +98 -28
  17. package/dist/src/bootstrap/run-task-worker.js +6 -2
  18. package/dist/src/bootstrap/validators.js +1 -1
  19. package/dist/src/cli/action-binding.js +14 -37
  20. package/dist/src/cli/agent-commands.js +11 -11
  21. package/dist/src/cli/auth-commands.js +2 -1
  22. package/dist/src/cli/creation-help.js +9 -0
  23. package/dist/src/cli/dam-commands.js +10 -14
  24. package/dist/src/cli/editor-commands.js +7 -5
  25. package/dist/src/cli/errors.js +81 -22
  26. package/dist/src/cli/host-input.js +64 -5
  27. package/dist/src/cli/model-commands.js +9 -3
  28. package/dist/src/cli/observed-errors.js +7 -3
  29. package/dist/src/cli/org-commands.js +3 -1
  30. package/dist/src/cli/task-commands.js +6 -2
  31. package/dist/src/cli/tool-commands.js +12 -11
  32. package/dist/src/features/agent/creative-agent-adapter.js +6 -2
  33. package/dist/src/features/agent/creative-protocol.js +8 -29
  34. package/dist/src/features/agent/resource-authorizer.js +25 -17
  35. package/dist/src/features/agent/result-reader.js +31 -14
  36. package/dist/src/features/agent/use-cases.js +6 -31
  37. package/dist/src/features/credits/use-cases.js +55 -28
  38. package/dist/src/features/dam/asset-projection.js +3 -6
  39. package/dist/src/features/dam/dam-api-adapter.js +30 -15
  40. package/dist/src/features/dam/repository-catalog.js +30 -21
  41. package/dist/src/features/dam/use-cases.js +12 -7
  42. package/dist/src/features/editor/bridge-client.js +0 -2
  43. package/dist/src/features/editor/public-url.js +1 -36
  44. package/dist/src/features/editor/session.js +3 -2
  45. package/dist/src/features/editor/use-cases.js +27 -2
  46. package/dist/src/features/org/org-service.js +10 -1
  47. package/dist/src/features/org/use-cases.js +18 -4
  48. package/dist/src/features/task/process-owner.js +54 -0
  49. package/dist/src/features/task/store.js +37 -10
  50. package/dist/src/features/task/task-background.js +5 -2
  51. package/dist/src/features/task/use-cases.js +184 -84
  52. package/dist/src/features/tool/argument-paths.js +14 -0
  53. package/dist/src/features/tool/canvas-copy.js +28 -15
  54. package/dist/src/features/tool/canvas-matting.js +123 -0
  55. package/dist/src/features/tool/canvas-media.js +100 -52
  56. package/dist/src/features/tool/canvas-models.js +66 -33
  57. package/dist/src/features/tool/canvas-pricing.js +12 -0
  58. package/dist/src/features/tool/canvas-recovery.js +13 -30
  59. package/dist/src/features/tool/canvas-results.js +79 -87
  60. package/dist/src/features/tool/canvas-tool-adapter.js +134 -157
  61. package/dist/src/features/tool/canvas-video.js +44 -37
  62. package/dist/src/features/tool/dynamic-schema.js +39 -40
  63. package/dist/src/features/tool/ffprobe-executable.js +21 -0
  64. package/dist/src/features/tool/mns-catalog-adapter.js +61 -24
  65. package/dist/src/features/tool/resource-authorizer.js +11 -3
  66. package/dist/src/features/tool/tool-api-adapter.js +73 -82
  67. package/dist/src/features/tool/tool-errors.js +25 -0
  68. package/dist/src/features/tool/tool-output.js +15 -0
  69. package/dist/src/features/tool/use-cases.js +74 -98
  70. package/dist/src/features/update/update-service.js +95 -21
  71. package/dist/src/platform/media-type.js +46 -0
  72. package/dist/src/platform/public-url.js +35 -0
  73. package/dist/src/platform/remote-error-evidence.js +33 -6
  74. package/dist/src/platform/resource-auth-key.js +35 -1
  75. package/dist/src/platform/safe-upload-file.js +36 -41
  76. package/dist/src/platform/signature.js +2 -2
  77. package/dist/src/platform/signed-http-transport.js +4 -1
  78. package/dist/src/platform/url-safety.js +6 -1
  79. package/dist/src/platform/webm-header.js +41 -0
  80. package/dist/src/telemetry/command-route.js +38 -0
  81. package/dist/src/telemetry/command-routes.json +1 -0
  82. package/dist/src/telemetry/failure-summary.js +1 -1
  83. package/dist/src/telemetry/invocation.js +1 -2
  84. package/dist/src/telemetry/process-errors.js +17 -33
  85. package/dist/src/telemetry/sanitize.js +19 -4
  86. package/dist/src/telemetry/sls-sink.js +8 -0
  87. package/package.json +4 -4
  88. package/skills/insmind-cli/SKILL.md +18 -5
  89. package/skills/insmind-cli/references/agent.md +9 -4
  90. package/skills/insmind-cli/references/creation.md +3 -1
  91. package/skills/insmind-cli/references/editor.md +7 -5
  92. package/skills/insmind-cli/references/errors.md +20 -9
  93. package/skills/insmind-cli/references/matting.md +3 -5
  94. package/skills/insmind-cli/references/media-tools.md +10 -4
  95. package/skills/insmind-cli/references/tool.md +9 -15
@@ -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
  }
@@ -10,6 +10,7 @@ export function registerModelCommands(program, runtime) {
10
10
  .description(text(runtime.product, "列出当前可用的创作与媒体处理模型(不含独立风格)", "List available creation and media-processing models (excluding standalone styles)"))
11
11
  .option("--tool <tool>", text(runtime.product, "按工具筛选", "filter by tool"))
12
12
  .allowExcessArguments(false);
13
+ list.addHelpText("after", text(runtime.product, "\n列表只提供模型摘要。选择后用 model get <model> --tool <tool> 读取完整输入、用途与保留范围,再判断是否符合需求;不能仅凭摘要推断整个工具不支持。\n", "\nThis list is a summary. Read model get <model> --tool <tool> for full inputs, purpose and preservation scope before deciding whether it meets the request; the summary alone cannot establish that the whole Tool is unsupported.\n"));
13
14
  jsonOutput(list);
14
15
  bindAction(list, "organization", async (context, signal) => {
15
16
  const selectedTool = list.opts().tool;
@@ -40,10 +41,13 @@ export function registerModelCommands(program, runtime) {
40
41
  get.addHelpText("after", [
41
42
  "",
42
43
  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."),
44
+ text(runtime.product, "cost.minimum/maximum 为目录估价,即使相等也不表示已扣费。计量公式见 usageDescription,未知价格保持未知;实际消费和归还从 credits usage 查询。", "cost.minimum/maximum are catalog estimates, even when equal, and do not indicate a charge. Read usageDescription for metering formulas and leave unknown prices unknown. Query credits usage for actual consumption and restoration."),
43
45
  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."),
44
46
  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."),
45
- text(runtime.product, "required 和 default 说明模型的输入要求和服务默认值。用户未指定有默认值的参数时可以省略;显式值原样发送。model 放在输入顶层。", "required and default describe the model input and service defaults. Omit a defaulted parameter the user did not specify. Explicit values are forwarded. Put model at the top level."),
47
+ text(runtime.product, "按 inputSchema.required 提供必填字段。default 是模型声明的默认值;有默认值的字段也可能需要显式提供。model 放在输入顶层。", "Follow inputSchema.required even when a default is documented. Provide model at the top level."),
48
+ text(runtime.product, "required 只属于当前模型,不代表同一工具的其他模型也需要这些字段。前置素材无法准备时,先查看同工具其他模型的要求;遵守用户指定模型及保真等约束,不将单个模型或本地环境的限制说成整个工具不支持。", "required belongs to this model, not every model of the Tool. If a prerequisite cannot be prepared, inspect other models of the same Tool while honoring explicit model and fidelity constraints. A model-specific or local-environment limitation does not establish that the whole Tool is unavailable."),
46
49
  text(runtime.product, "usageDescription 说明跨字段组合规则。tool call <tool> --schema 按 model 展示字段、选项和范围;step 及跨字段规则见本 Model 元数据。Agent 只传显式生成约束,不照搬 Tool 的完整必填参数。", "usageDescription explains cross-field combinations. tool call <tool> --schema describes fields, options 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."),
50
+ text(runtime.product, "公开 Schema 指导构参;CLI 仅检查自身读取、转换、授权和交付所必需的条件。服务端决定业务参数是否可接受,返回明确错误时按实际原因处理,不能静默替换用户值。", "The public Schema guides input construction. The CLI checks only what it needs for reading, conversion, authorization and delivery. The service decides business validity; handle its stated error without silently replacing user values."),
47
51
  ""
48
52
  ].join("\n"));
49
53
  jsonOutput(get);
@@ -67,8 +71,10 @@ export function registerModelCommands(program, runtime) {
67
71
  signal
68
72
  });
69
73
  await runtime.telemetry.stage("output", async () => {
70
- runtime.validators.modelGetOutput(result);
71
- runtime.io.writeOut(`${JSON.stringify(result.inputSchema ? { ...result, inputSchema: hostSchema(runtime, result.inputSchema) } : result)}\n`);
74
+ const projected = result.inputSchema ? hostSchema(runtime, result.inputSchema, result.tool) : undefined;
75
+ const output = { ...result, ...(projected ? { inputSchema: projected } : {}) };
76
+ runtime.validators.modelGetOutput(output);
77
+ runtime.io.writeOut(JSON.stringify(output) + "\n");
72
78
  });
73
79
  }, {
74
80
  operation: "model.get"
@@ -1,6 +1,6 @@
1
1
  const messages = {
2
2
  credits: ["当前可用额度不足,本次生成未能完成。", "There are not enough available credits to complete this creation."],
3
- review: ["这次内容未通过审核,请调整描述或参考图片。", "This content did not pass content review. Adjust the description or reference image."],
3
+ review: ["本次创作内容未通过审核,没有可交付结果。", "This creation did not pass content review and has no deliverable result."],
4
4
  session_busy: ["这个会话正在使用中,请稍后再试。", "This conversation is in use. Please try again later."],
5
5
  service_busy: ["当前服务繁忙,请稍后再试。", "The service is busy. Please try again later."],
6
6
  timeout: ["本次操作等待超时。", "This operation timed out."],
@@ -42,7 +42,7 @@ export function observedErrorCategory(e) {
42
42
  if (gd && e.operation === "agent.send" && e.httpStatus === 429)
43
43
  return "service_busy";
44
44
  if (gd && e.operation === "auth.login" && e.httpStatus === 504 || e.code === "EDITOR_RPC_TIMEOUT"
45
- || ins && e.operation === "tool.call" && e.remoteCode === "-31994" && e.diagnosticReason === "IMAGE_AUDIT_TIMEOUT")
45
+ || (gd || ins) && e.operation === "tool.call" && e.remoteCode === "-31994" && e.diagnosticReason === "IMAGE_AUDIT_TIMEOUT")
46
46
  return "timeout";
47
47
  if (ins && e.operation === "tool.call" && e.remoteCode === "-31993")
48
48
  return "settings";
@@ -100,8 +100,12 @@ export function observedErrorCategory(e) {
100
100
  }
101
101
  export function observedErrorMessage(category, e) {
102
102
  const text = (zh, en) => e.product === "insmind" ? en : zh;
103
+ if (e.diagnosticReason === "DAM_DEFAULT_REPOSITORY_UNKNOWN")
104
+ return text("未能确认默认素材库。请从 dam repository list 的可用结果中选择并传入 --repository-id。", "The default repository could not be established. Choose an available repository with dam repository list and pass --repository-id.");
105
+ if (e.diagnosticReason === "CREDITS_NEXT_CURSOR_MISSING")
106
+ return 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.");
103
107
  if (category === "timeout" && e.diagnosticReason === "IMAGE_AUDIT_TIMEOUT")
104
- return text("本次图片检查未能及时完成。", "The image check did not finish in time.");
108
+ return text("图片审核处理超时,尚未取得结果。", "The image check did not finish in time.");
105
109
  if (category === "login" && e.errorType === "DeviceAuthorizationExpiredError")
106
110
  return text("本次登录已超时,请重新登录。", "This sign-in timed out. Please sign in again.");
107
111
  if (category === "account" && e.code === "ORG_INVALID")
@@ -5,6 +5,7 @@ export function registerOrgCommands(program, runtime) {
5
5
  const org = program.command("org")
6
6
  .description("组织选择")
7
7
  .helpCommand(false);
8
+ org.addHelpText("after", "\nlist 查询当前账号可用组织;current 只读本机当前选择,不验证远端权限;switch 改变后续 CLI 调用的组织和任务查询范围。资源库不是组织,素材库通过 dam repository list 另行选择。\n");
8
9
  const list = leaf(org.command("list"))
9
10
  .description("列出可用组织")
10
11
  .option("--json", "输出 JSON");
@@ -33,7 +34,8 @@ export function registerOrgCommands(program, runtime) {
33
34
  }, { operation: "org.current" });
34
35
  const switchCommand = leaf(org.command("switch"))
35
36
  .description("切换当前组织")
36
- .option("--org <org-id>", "指定组织 ID");
37
+ .option("--org <org-id>", "目标组织 ID;非交互调用必填,可通过 org list 查询")
38
+ .addHelpText("after", "\n使用用户指定的组织 ID,或通过 org list 查找;不要以名称或资源库 ID 代替。切换影响同一本机登录的后续调用,正在执行的创作仍保留提交时的身份和组织。成功输出组织名称与 ID,不提供 --json。\n");
37
39
  bindAction(switchCommand, "credential", async (context, signal) => {
38
40
  const organizationId = switchCommand.opts().org;
39
41
  if (organizationId === undefined && !isInteractive(runtime))
@@ -10,6 +10,7 @@ export function registerTaskCommands(program, runtime) {
10
10
  .option("--limit <number>", text("返回 1–100 条,默认 20", "return 1–100 tasks; defaults to 20"), "20")
11
11
  .option("--operation <operation>", text("筛选 agent.send 或 tool.call", "filter by agent.send or tool.call"))
12
12
  .allowExcessArguments(false);
13
+ list.addHelpText("after", text("\n只读本机当前身份和组织的记录,按创建时间倒序;不查询远端进度,不返回成品或费用。用时间、operation 和 label 定位原调用,再 task get <taskId>。多个候选不明确时先澄清,不自动选最新任务。\n", "\nReads local records for the current identity and organization in reverse creation order, without remote polling, assets or usage. Match time, operation and label, then task get <taskId>. Clarify ambiguous matches rather than choosing the latest automatically.\n"));
13
14
  jsonOutput(list);
14
15
  bindPreparedAction(list, "local-organization", async () => {
15
16
  const options = list.opts();
@@ -31,12 +32,15 @@ export function registerTaskCommands(program, runtime) {
31
32
  .allowExcessArguments(false)
32
33
  .addHelpText("after", [
33
34
  "",
34
- text("completed 表示该次执行已有完整结果;running 表示原 CLI 仍在更新记录,或远端任务仍在执行。", "completed means this task has a complete result; running means the original CLI is updating the record or the service is still processing."),
35
+ text("退出码 0 表示查询成功。现在要结果且 state=running 时隔数秒继续查同一 ID。用户指定稍后取回时,受理后就交接原 taskId 和状态,等用户回来再查。", "Exit 0 means the query succeeded. For delivery now, check the same ID every few seconds while running. For later pickup, hand off the taskId and state upon acceptance and query when the user returns."),
36
+ text("completed 时读取 result。tool.call 返回 content,agent.send 返回 message.parts。重发成品时原样复制本次结果里的完整链接,包括查询参数和签名。若本轮返回文本或补充问题,向用户转述或提问。", "On completed, read result.content for tool.call or result.message.parts for agent.send. When resending an asset, copy the complete link from this result, including its query parameters and signature. Relay text or questions to the user when that is what the turn returned."),
37
+ text("若稿定资源链接已过期,再查原 taskId 可刷新结构化资源的下载授权。第三方链接和正文按原样返回,CLI 不能替第三方续签。", "If a Gaoding file link has expired, query the original taskId for fresh access to structured assets. Third-party URLs and prose are returned unchanged; the CLI cannot renew another provider's signature."),
38
+ text("failed 时向用户说明 note 中的原因。只有错误明确说明尚未派发,才按提示修正并再调用。服务已明确拒绝时,换模型也会发起一次新创作,须有用户补充的需求或另做一次的授权。受理后状态为 unknown 时保留原 ID 核查。", "On failed, relay the cause from note. Correct and retry an input when the error confirms the request was never dispatched. After a definite service refusal, switching models starts another creation and requires a revised request or authorization from the user. On unknown after acceptance, keep and check the original ID."),
35
39
  text("unknown 表示无法确认本次执行终态;partialResult 仅是已取得的消息片段,不代表完成。", "unknown means completion cannot be confirmed; partialResult is a message snapshot, not a complete result."),
36
40
  text("读取本地状态不请求组织绑定;查询远端进度或获取下载授权仍需联网授权。查询请求失败不代表生成失败,可用原 taskId 重查。", "Local status reads do not bind the organization. Remote progress and download authorization still require network access. A failed query does not mean generation failed; query the same taskId again."),
37
41
  text("查询得到完整结果但最终缓存保存失败时仍返回结果和退出码 0;请保留 stderr 警告所指的输出,后续可能无法恢复。", "A complete result is delivered with exit code 0 if only final cache persistence fails; keep the output as warned on stderr because later recovery may be unavailable."),
38
42
  text("最终错误为 stderr 中的 JSON error 对象;stderr 也可能有进度和警告,中断不代表远端任务取消。", "The final error is a JSON error object on stderr, which may also contain progress and warnings. Interruption does not mean the remote task was cancelled."),
39
- text("查询不重新提交创作;同一执行记录多次读取的 usage 是同一份费用。", "Queries never resubmit a creation. Reading the same task again does not add another usage charge."),
43
+ text("查询不重新提交创作。同一任务的 usage 不重复相加;Agent usage.cost.amount 为本轮实扣,Tool minimum/maximum 为目录估价,即使相等也不是实扣。", "Queries never resubmit creation or add usage for repeated reads. Agent usage.cost.amount is this turn's actual charge; Tool minimum/maximum are catalog estimates even when equal."),
40
44
  text(`记录仅来自本机执行;保留至用户删除 ~/${runtime.product.stateDirectory}/tasks。切换身份或组织后只显示对应记录。`, `Tasks are local to this machine and identity context; they remain until you remove ~/${runtime.product.stateDirectory}/tasks.`),
41
45
  text("Agent 首次回执未取得或原连接中断时可能只能确认未知;不会自动选择最近 Context 或重新生成。", "A missing first Agent receipt or interrupted connection may leave the outcome unknown; the CLI does not select another Context or generate again."),
42
46
  ""
@@ -1,11 +1,13 @@
1
+ import { creationTaskHelp } from "./creation-help.js";
1
2
  import { hostSchema, readHostInput } from "./host-input.js";
2
3
  import { jsonOutput, bindAction, bindPreparedAction } from "./action-binding.js";
3
4
  import { CliUsageError } from "./errors.js";
4
5
  import { productText as text } from "../product/text.js";
5
6
  export function registerToolCommands(program, runtime) {
6
7
  const tool = program.command("tool")
7
- .description(text(runtime.product, "创作工具", "Creation tools"))
8
+ .description(text(runtime.product, "生成及附件图片/视频处理:改字、抠图、分层等", "Generate and process attached images/videos: text, cutouts, layers and more"))
8
9
  .helpCommand(false);
10
+ tool.addHelpText("after", text(runtime.product, "\n附件、素材链接或导出图片的处理从 tool list 发现,再用 model list --tool <tool> 和 model get <model> --tool <tool> 选择实现。无需先连接 Editor。模型选择和参数不决定 Agent/Tool 路线;业务策划或持续多轮创作用 agent send。\n", "\nDiscover processing for attachments, asset links and exported images with tool list, then model list --tool <tool> and model get <model> --tool <tool>. No Editor connection is needed. Model choices and controls do not determine Agent/Tool routing; use agent send for planning or multi-turn creation.\n"));
9
11
  const list = tool.command("list")
10
12
  .description(text(runtime.product, "列出可用工具", "List available tools"))
11
13
  .allowExcessArguments(false);
@@ -32,16 +34,15 @@ export function registerToolCommands(program, runtime) {
32
34
  .allowExcessArguments(false);
33
35
  call.addHelpText("after", [
34
36
  "",
37
+ text(runtime.product, "一次调用执行一个工具。输入 JSON 顶层放 model、host_application 和所选模型参数;不要再包一层 arguments。字段、类型与媒体角色见 --schema,当前档位与说明见 model get。", "One call executes one tool. Put model, host_application and the selected model's parameters at the JSON top level, without an arguments wrapper. Read --schema for fields, types and media roles, and model get for current choices and guidance."),
38
+ text(runtime.product, "先保存完整 JSON 文件,再用 --input request.json 执行。命令不交互填参;--input - 必须在同一条 shell 命令中通过管道或重定向送入完整 JSON,单独执行不会再提问。", "Save complete JSON first, then run with --input request.json. Input is not an interactive form: --input - requires piping or redirecting complete JSON in the same shell command and does not prompt for fields."),
35
39
  text(runtime.product, "完整结果已校验但最终本地记录保存失败时仍返回结果和退出码 0;stderr 警告 task get 可能无法恢复,请保留输出。", "A validated complete result is delivered with exit code 0 even if its final local record cannot be saved; stderr warns that task get may not recover it. Keep the output."),
36
40
  text(runtime.product, "最终错误为 stderr 中的 JSON error 对象;stderr 也可能有进度和警告。中断退出码 130 只表示本地停止等待。", "The final error is a JSON error object on stderr, which may also contain progress and warnings. Exit code 130 means local waiting stopped."),
37
- text(runtime.product, "--async 在服务端受理后输出包含 taskId 和 state 的 JSON;退出码 0 仅表示受理。", "--async returns JSON with taskId and state after acceptance; exit code 0 means accepted only."),
38
- text(runtime.product, "异步任务由本机后台进程继续等待结果;进程终止或关机可能使状态变为 unknown。", "Async work continues in a local background process; termination or shutdown may leave its state unknown."),
39
- 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."),
40
- 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."),
41
- 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."),
42
- 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.`),
43
- 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."),
44
- text(runtime.product, "查询返回同一份 usage;Tool usage.cost 为当次目录预估价格。", "Queries return the same usage; Tool usage.cost is the catalog price estimate for that invocation."),
41
+ ...creationTaskHelp(runtime.product),
42
+ text(runtime.product, "媒体 URI 字段支持 HTTP(S) 与本地 file URI;本地路径用 Python Path(path).resolve().as_uri() 或 Node.js pathToFileURL(path).href 生成,正确转义中文、空格和 #。CLI 按调用上传素材;原图、参考和选区分别放入对应字段,数组保留顺序和重复项。", "Media URI fields accept HTTP(S) and local file URIs. Generate local URIs with Python Path(path).resolve().as_uri() or Node.js pathToFileURL(path).href to escape Unicode, spaces and #. The CLI uploads them for the call; keep sources, references and masks in their own fields and preserve array order and duplicates."),
43
+ text(runtime.product, "完整结果为 {content,usage}。content 项为 text、resource_link(uri/name/mimeType)或 resource(resource.uri/mimeType/text);OCR 的 resource.text 是 JSON。分层返回原生模板 JSON 链接,不是 PSD。交付资源链接时原样保留完整 URI 及查询参数,不截断、拼接或去掉授权参数。", "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. Preserve each complete delivery URI and its query parameters without truncating, splicing or stripping authorization parameters."),
44
+ text(runtime.product, "Tool usage.cost 的 minimum/maximum 是目录估价,即使相等也不是实际扣费;缺失表示未提供估价,不是免费。实扣须查询可对应的 credits usage 账本;同一 taskId 重复读取不累计费用。", "Tool usage.cost minimum/maximum are catalog estimates even when equal; missing cost means no estimate, not free. Actual charges require matching credits usage ledger records. Repeated reads of one taskId do not add usage."),
45
+ text(runtime.product, "先交付服务返回的已有结果。效果与用户预期有差异时如实说明,后续新创作按用户要求执行;CLI 不按效果阈值判失败或自动重做。本地插值、描图等替代文件不能报告为本工具的服务结果。", "Deliver the existing service result first. Describe any difference from the user's goal and follow the user's instructions for further creation; the CLI does not fail or regenerate based on aesthetic thresholds. Files produced by local interpolation or tracing are not this Tool's service results."),
45
46
  ""
46
47
  ].join("\n"));
47
48
  jsonOutput(call);
@@ -74,7 +75,7 @@ export function registerToolCommands(program, runtime) {
74
75
  });
75
76
  runtime.telemetry.annotate({ tool_name: prepared.name });
76
77
  await runtime.telemetry.stage("output", async () => {
77
- runtime.io.writeOut(`${JSON.stringify(hostSchema(runtime, { ...schema }))}\n`);
78
+ runtime.io.writeOut(`${JSON.stringify(hostSchema(runtime, { ...schema }, prepared.name))}\n`);
78
79
  });
79
80
  return;
80
81
  }
@@ -94,7 +95,7 @@ export function registerToolCommands(program, runtime) {
94
95
  }
95
96
  const run = (observe) => runtime.tool.call({ input: prepared.input, access, signal,
96
97
  ...(observe ? { observe } : {}) });
97
- const result = await runtime.tasks.track({ ...task, run });
98
+ const result = await runtime.tasks.track({ ...task, run, signal });
98
99
  await runtime.telemetry.stage("output", async () => {
99
100
  runtime.io.writeOut(`${JSON.stringify(result)}\n`);
100
101
  });
@@ -24,6 +24,7 @@ export function createCreativeAgentAdapter(dependencies) {
24
24
  let httpStatus;
25
25
  const stream = await dependencies.transport.postStream({
26
26
  path: "/ai-agent/v1/thread/completion",
27
+ sensitiveResponse: true,
27
28
  ...(observe ? { onDispatch: (dispatchedAt) => observe({ dispatchedAt }) } : {}),
28
29
  body: buildCreativeRequest(message, ids),
29
30
  accept: "text/event-stream",
@@ -49,13 +50,16 @@ export function createCreativeAgentAdapter(dependencies) {
49
50
  const output = await withResponseDiagnostics(async (onResponse) => {
50
51
  const messages = await dependencies.transport.getJson({
51
52
  path: `/ai-agent/v1/thread/${encodeURIComponent(contextId)}/messages`,
53
+ sensitiveResponse: true,
52
54
  credential: access.credential,
53
55
  organizationId: access.organizationId,
54
56
  onResponse,
55
57
  signal
56
58
  });
57
- let usageModelMissing = false;
58
- const normalized = normalizeCreativeMessages(restoreCreativeResourceUrls(creativeTurnMessages(messages, ids.localMessageId), streamed), () => { usageModelMissing = true; });
59
+ let usageModelMissing = false, usageAmountMissing = false;
60
+ const normalized = normalizeCreativeMessages(restoreCreativeResourceUrls(creativeTurnMessages(messages, ids.localMessageId), streamed), () => { usageModelMissing = true; }, () => { usageAmountMissing = true; });
61
+ if (usageAmountMissing)
62
+ await observe?.({ agentUsageAmountMissing: true });
59
63
  if (usageModelMissing)
60
64
  await observe?.({ agentUsageModelMissing: true });
61
65
  return normalized;
@@ -375,36 +375,14 @@ function parseQuestionPart(message) {
375
375
  }
376
376
  };
377
377
  }
378
- function dedupeParts(parts) {
379
- const texts = new Set();
380
- const urls = new Set();
381
- return parts.filter((part) => {
382
- if ("text" in part) {
383
- if (texts.has(part.text))
384
- return false;
385
- texts.add(part.text);
386
- return true;
387
- }
388
- if ("url" in part) {
389
- if (urls.has(part.url))
390
- return false;
391
- urls.add(part.url);
392
- }
393
- return true;
394
- });
395
- }
396
- export function normalizeCreativeMessages(messages, onUsageModelMissing) {
378
+ export function normalizeCreativeMessages(messages, onUsageModelMissing, onUsageAmountMissing) {
397
379
  const contextId = creativeContextId(messages);
398
380
  const latest = new Map();
399
- const anonymous = [];
400
381
  for (const message of messages) {
401
382
  const id = nonEmptyString(message.message_id);
402
- if (id === undefined)
403
- anonymous.push(message);
404
- else
405
- latest.set(id, message);
383
+ latest.set(id ?? Symbol(), message);
406
384
  }
407
- const normalized = [...latest.values(), ...anonymous];
385
+ const normalized = [...latest.values()];
408
386
  const parts = [];
409
387
  for (const message of normalized) {
410
388
  if (hasHiddenTransportRole(message))
@@ -434,7 +412,7 @@ export function normalizeCreativeMessages(messages, onUsageModelMissing) {
434
412
  return fail();
435
413
  parts.push(parseQuestionPart(question));
436
414
  }
437
- const publicParts = dedupeParts(parts);
415
+ const publicParts = parts;
438
416
  if (publicParts.length === 0)
439
417
  return fail("AGENT_RESULT_EMPTY", { messageCount: normalized.length, publicPartCount: 0 });
440
418
  const usageItems = [];
@@ -444,10 +422,11 @@ export function normalizeCreativeMessages(messages, onUsageModelMissing) {
444
422
  continue;
445
423
  const extra = record(message.extra);
446
424
  const amount = extra?.deduct_points;
447
- if (amount === undefined)
425
+ if (typeof amount !== "number" || !Number.isFinite(amount) || amount < 0) {
426
+ if (amount !== undefined || (nonEmptyString(extra?.task_id) && nonEmptyString(extra?.scene_code)))
427
+ onUsageAmountMissing?.();
448
428
  continue;
449
- if (typeof amount !== "number" || !Number.isFinite(amount) || amount < 0)
450
- return fail();
429
+ }
451
430
  totalCost += amount;
452
431
  const model = nonEmptyString(extra?.scene_code);
453
432
  if (model === undefined) {