@insmind/cli 1.7.1 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -100,6 +100,12 @@ export function createProductionRuntime(options = {}) {
100
100
  classifyError: error => classifyTelemetryError(error, { product, operation: telemetry.creationContext().operation, failureStage: telemetry.failureStage(error) }),
101
101
  ...(telemetrySink.enqueue ? { onEvent: (event) => telemetrySink.enqueue([event]) } : {})
102
102
  });
103
+ telemetry.annotate({ installation_owner: installationOwner,
104
+ ...(["workbuddy", "qwenwork"].includes(env.CLI_HOST_APPLICATION ?? "")
105
+ ? { host_application: env.CLI_HOST_APPLICATION } : {}),
106
+ ...(["auth_status", "version_check"].includes(env.CLI_INVOCATION_PURPOSE ?? "")
107
+ ? { invocation_purpose: env.CLI_INVOCATION_PURPOSE } : {}),
108
+ ...(/^[a-f0-9]{32}$/u.test(env.CLI_HOST_INVOCATION_ID ?? "") ? { host_invocation_id: env.CLI_HOST_INVOCATION_ID } : {}) });
103
109
  // Explicit test transport enables SDK tests; test-mode child processes never emit real analytics.
104
110
  const analytics = options.analytics ?? (telemetryEnvironment === "production" || options.windFetch
105
111
  ? createWindAnalytics({ product: product.id, version: options.telemetryVersion ?? primarySkill.version,
@@ -116,7 +122,7 @@ export function createProductionRuntime(options = {}) {
116
122
  stderrTerminal: process.stderr.isTTY === true
117
123
  };
118
124
  const stdout = createTextOutput(rawIo.stdout);
119
- const stderr = createTextOutput(rawIo.stderr);
125
+ const stderr = createTextOutput(rawIo.stderr, "stderr");
120
126
  const io = {
121
127
  writeOut: stdout.write,
122
128
  writeError: stderr.write,
@@ -248,7 +254,10 @@ export function createProductionRuntime(options = {}) {
248
254
  now,
249
255
  telemetry
250
256
  }),
251
- downloader: createDamFileDownloader({ fetch }),
257
+ downloader: createDamFileDownloader({ fetch, warn: code => {
258
+ telemetry.annotate({ warning_codes: [code] });
259
+ presenter.warning(text("临时文件未能清理;已下载的文件可以继续使用。", "Temporary files could not be cleaned up; completed downloads remain available."));
260
+ } }),
252
261
  operations: damOperations,
253
262
  sleep: async (milliseconds, signal) => {
254
263
  await delay(milliseconds, undefined, { signal });
@@ -169,6 +169,6 @@ const unavailableValidator = Object.assign(() => false, { errors: null, schema:
169
169
  function assertion(validate, ErrorType) {
170
170
  return (value) => {
171
171
  if (!validate(value))
172
- throw new ErrorType(validationIssues(validate.errors));
172
+ throw new ErrorType(validationIssues(validate.errors, value, validate.schema));
173
173
  };
174
174
  }
@@ -6,6 +6,9 @@ const selectedCommands = new WeakMap();
6
6
  /** Declare the existing fixed JSON contract alongside the command registration. */
7
7
  export function jsonOutput(command) {
8
8
  jsonCommands.add(command);
9
+ if (!command.options.some(option => option.long === "--json")) {
10
+ command.option("--json", "JSON output (default)");
11
+ }
9
12
  }
10
13
  export function errorUsesJson(program, argv) {
11
14
  if (program.opts().jsonErrors === true)
@@ -9,7 +9,7 @@ import { SsoRequestError } from "../features/auth/sso-service.js";
9
9
  import { AuthorizedAccountContextMissingError, BrowserOpenError, DeviceAuthorizationExpiredError } from "../features/auth/use-cases.js";
10
10
  import { AgentInputError } from "../features/agent/use-cases.js";
11
11
  import { ToolInputError } from "../features/tool/catalog.js";
12
- import { ToolTaskFailedError } from "../features/tool/tool-api-adapter.js";
12
+ import { ToolTaskFailedError, ToolTaskCanceledError } from "../features/tool/tool-api-adapter.js";
13
13
  import { AgentAuditRejectedError } from "../features/agent/creative-protocol.js";
14
14
  import { isContentReviewRejection } from "../features/task/creation-refusal.js";
15
15
  import { ObjectStorageUploadError } from "../features/dam/object-storage.js";
@@ -31,9 +31,12 @@ import { EditorNotReadyError, EditorSessionNotFoundError, EditorTargetError } fr
31
31
  import { UpdateError } from "../features/update/update-service.js";
32
32
  import { WindAnalyticsError } from "../analytics/wind.js";
33
33
  import { safeFailureSummary } from "../telemetry/failure-summary.js";
34
+ import { OutputStreamError } from "../platform/text-output.js";
34
35
  export class CliUsageError extends Error {
35
- constructor() {
36
+ reason;
37
+ constructor(reason = "command_arguments") {
36
38
  super("命令或参数无效。");
39
+ this.reason = reason;
37
40
  this.name = "CliUsageError";
38
41
  }
39
42
  }
@@ -57,8 +60,9 @@ export function mapCliError(error, options) {
57
60
  code: outcome.failure.code, errorType: error instanceof Error ? error.name : undefined,
58
61
  remoteCode: remote?.remoteCode,
59
62
  httpStatus: remote instanceof RemoteRequestError || remote instanceof SsoRequestError ? remote.status : undefined,
60
- diagnosticReason: remote instanceof RemoteRequestError || remote instanceof RemoteProtocolError || remote instanceof ToolTaskFailedError
61
- ? remote.diagnosticReason : undefined
63
+ diagnosticReason: error instanceof UpdateError ? error.diagnosticReason
64
+ : remote instanceof RemoteRequestError || remote instanceof RemoteProtocolError || remote instanceof ToolTaskFailedError || remote instanceof SsoRequestError
65
+ ? remote.diagnosticReason : undefined
62
66
  };
63
67
  const category = observedErrorCategory(evidence);
64
68
  if (!category)
@@ -72,6 +76,9 @@ function mapBaseCliError(error, options) {
72
76
  const insmind = options.product?.id === "insmind";
73
77
  const command = options.product?.commandName ?? "gd-cli";
74
78
  const text = (zh, en) => insmind ? en : zh;
79
+ if (error instanceof ToolTaskCanceledError)
80
+ return { kind: "interrupted", exitCode: 130,
81
+ failure: { code: "INTERRUPTED", message: text("生成任务已取消。", "The creation task was canceled.") } };
75
82
  if (options.aborted)
76
83
  return { kind: "interrupted", exitCode: 130, failure: {
77
84
  code: "INTERRUPTED", message: text("已停止本地等待;已派发的任务或写操作可能仍在继续。", "Local waiting stopped; dispatched tasks or writes may still be active."),
@@ -141,7 +148,9 @@ function mapBaseCliError(error, options) {
141
148
  return failure("USAGE_ERROR", description ? text(...description) : text("创作输入不可用,请核对模型与参数。", "Check the model and creation arguments."), 2, [`${command} model list`, text(`使用 ${command} model get <model> 核对模型参数;素材应使用安全的 HTTP(S) URL 或本地 file URL。`, `Use ${command} model get <model> to inspect parameters; assets require safe HTTP(S) URLs or local file URLs.`)], { reason: error.reason, field: error.field, ...(error instanceof ToolInputError ? { issues: error.issues } : {}) });
142
149
  }
143
150
  if (error instanceof LocalFileInputError)
144
- return failure("USAGE_ERROR", text("本地素材文件不可用于上传。", "The local asset file cannot be uploaded."), 2, [text("检查文件访问权限、文件类型和声明的 mediaType;受保护路径不可上传。", "Check file access, type and declared mediaType; protected paths cannot be uploaded.")], { reason: "local_asset", system_code: systemErrorCode(error) });
151
+ return failure("USAGE_ERROR", text("本地素材文件不可用于上传。", "The local asset file cannot be uploaded."), 2, [text("检查文件访问权限、文件类型和声明的 mediaType;受保护路径不可上传。", "Check file access, type and declared mediaType; protected paths cannot be uploaded.")], { reason: error.reason, system_code: systemErrorCode(error) });
152
+ if (error instanceof CliUsageError && error.reason === "invalid_task_id")
153
+ return failure("USAGE_ERROR", text("任务编号不正确,请使用本机任务列表中的 taskId。", "Invalid Task ID. Use a taskId from the local task list."), 2, [`${command} task list`, `${command} task get <taskId>`], { reason: error.reason });
145
154
  if (error instanceof DamInputError)
146
155
  return failure("USAGE_ERROR", text("素材管理参数无效,请根据字段和原因核对命令 --help。", "Invalid asset-management argument; check the field and reason against the command's --help."), 2, undefined, { reason: error.reason, field: error.field });
147
156
  if (error instanceof OrgUsageError
@@ -255,6 +264,8 @@ function isInsufficientCreditsError(error) {
255
264
  || error instanceof ToolTaskFailedError) && error.remoteCode === INSUFFICIENT_CREDITS_REMOTE_CODE;
256
265
  }
257
266
  export function classifyTelemetryError(error, options = {}) {
267
+ if (error instanceof ToolTaskCanceledError)
268
+ return { outcome: "interrupted", errorCode: "INTERRUPTED", diagnosticReason: "TASK_CANCELED" };
258
269
  if (error instanceof WindAnalyticsError)
259
270
  return { outcome: "failure", errorCode: error.code,
260
271
  ...(error.status === undefined ? {} : { httpStatus: error.status }) };
@@ -280,8 +291,16 @@ export function classifyTelemetryError(error, options = {}) {
280
291
  catch { /* No safe summary available. */ }
281
292
  }
282
293
  const diagnosticSummary = safeFailureSummary({
294
+ ...localFileSummary(error),
295
+ ...(error instanceof OutputStreamError ? { outputStream: error.outputStream } : {}),
296
+ ...(remoteError instanceof SsoRequestError ? remoteError.diagnosticSummary : {}),
283
297
  ...(summary && typeof summary === "object" && !Array.isArray(summary) ? summary : {}),
284
- systemCode: systemErrorCode(error)
298
+ systemCode: systemErrorCode(error),
299
+ inputReason: error instanceof LocalFileInputError ? error.reason
300
+ : error instanceof JsonInputError ? `json_${error.reason}`
301
+ : error instanceof InputContractError ? "schema_validation"
302
+ : error instanceof CliUsageError || error instanceof ToolInputError || error instanceof AgentInputError ? error.reason
303
+ : error instanceof CommanderError ? error.code : undefined
285
304
  });
286
305
  return {
287
306
  outcome: outcome.kind === "interrupted" ? "interrupted" : "failure",
@@ -296,8 +315,12 @@ export function classifyTelemetryError(error, options = {}) {
296
315
  ...(remoteError?.remoteBody === undefined
297
316
  ? {}
298
317
  : { remoteErrorBody: remoteError.remoteBody }),
299
- ...((remoteError instanceof RemoteRequestError || remoteError instanceof RemoteProtocolError || remoteError instanceof ToolTaskFailedError) && remoteError.diagnosticReason
300
- ? { diagnosticReason: remoteError.diagnosticReason } : {})
318
+ ...(error instanceof DamAssetNotDownloadableError ? { diagnosticReason: error.diagnosticReason }
319
+ : error instanceof DamDownloadError ? { diagnosticReason: `DOWNLOAD_${error.phase.toUpperCase()}_FAILED` }
320
+ : error instanceof OutputStreamError ? { diagnosticReason: "OUTPUT_STREAM_FAILED" }
321
+ : error instanceof UpdateError && error.diagnosticReason ? { diagnosticReason: error.diagnosticReason }
322
+ : (remoteError instanceof RemoteRequestError || remoteError instanceof RemoteProtocolError || remoteError instanceof ToolTaskFailedError || remoteError instanceof SsoRequestError) && remoteError.diagnosticReason
323
+ ? { diagnosticReason: remoteError.diagnosticReason } : {})
301
324
  };
302
325
  }
303
326
  function failure(code, message, exitCode, nextSteps, details) {
@@ -318,6 +341,16 @@ function systemErrorCode(error) {
318
341
  }
319
342
  return undefined;
320
343
  }
344
+ function localFileSummary(error) {
345
+ for (let depth = 0; error instanceof Error && depth < 10; depth++, error = error.cause) {
346
+ if (error instanceof LocalFileError && error.diagnostic)
347
+ return {
348
+ localFileOperation: error.diagnostic.operation,
349
+ localFileStep: error.diagnostic.step
350
+ };
351
+ }
352
+ return undefined;
353
+ }
321
354
  function remoteCause(error) {
322
355
  for (let depth = 0; error instanceof Error && depth < 10; error = error.cause, depth++) {
323
356
  if (error instanceof RemoteRequestError || error instanceof RemoteProtocolError || error instanceof ToolTaskFailedError
@@ -40,7 +40,7 @@ export function registerModelCommands(program, runtime) {
40
40
  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."),
41
41
  text(runtime.product, "parameters 是结构化元数据,不是 JSON Schema:遵守 required/type、minimum/maximum/step,SELECT 使用 options[].value 而非 label。", "parameters is structured metadata, not JSON Schema: follow required/type, minimum/maximum/step, and use SELECT options[].value rather than label."),
42
42
  text(runtime.product, "Tool 调用须显式提供所有 required 字段;用户未指定时显式使用返回的 default。model 标识放入调用参数顶层,与模型参数并列。", "Tool calls explicitly supply every required field, using a returned default when the user omitted it. Include the returned model identifier at the top level alongside its parameters."),
43
- text(runtime.product, "usageDescription 说明跨字段组合规则。tool call <tool> --schema 是 Tool 级参数并集,不能代替本 Model 的要求。Agent 只传显式生成约束,不照搬 Tool 的完整必填参数。", "usageDescription explains cross-field combinations. tool call <tool> --schema is a tool-wide union, not this Model's exact requirements. For Agent, pass explicit generation constraints rather than copying every Tool-required parameter."),
43
+ text(runtime.product, "usageDescription 说明跨字段组合规则。tool call <tool> --schema 根据 model 校验对应必填字段、可用参数和范围;step 及跨字段规则另见本 Model 元数据。Agent 只传显式生成约束,不照搬 Tool 的完整必填参数。", "usageDescription explains cross-field combinations. tool call <tool> --schema validates required fields, allowed parameters and ranges per model; follow this Model's metadata for step and cross-field rules. For Agent, pass explicit generation constraints rather than copying every Tool-required parameter."),
44
44
  ""
45
45
  ].join("\n"));
46
46
  jsonOutput(get);
@@ -19,6 +19,8 @@ const messages = {
19
19
  save: ["保存遇到问题,请在编辑器查看作品。", "There was a problem saving. Check the design in the editor."],
20
20
  local: ["无法读取或保存本次操作记录。", "The record for this operation could not be read or saved."],
21
21
  update: ["本次更新未完成。", "This update did not complete."],
22
+ managed_update: ["请在原应用中更新此工具。", "Update this tool in the app where it was installed."],
23
+ editor_required: ["请先打开作品并连接编辑器。", "Open a design and connect to the editor first."],
22
24
  output: ["结果未能完整显示。", "The result could not be fully displayed."],
23
25
  read: ["暂时无法读取结果。", "The result cannot be read right now."],
24
26
  tool: ["本次生成未能完成。", "This creation could not be completed."],
@@ -50,7 +52,9 @@ export function observedErrorCategory(e) {
50
52
  return "account";
51
53
  if (e.code === "USAGE_ERROR" && e.errorType === "LocalFileInputError")
52
54
  return "input_asset";
53
- if (["USAGE_ERROR", "INVALID_ACTIONS"].includes(e.code) || gd && e.operation === "dam.rename" && e.remoteCode === "00010014")
55
+ if (gd && e.operation === "dam.rename" && e.remoteCode === "00010014")
56
+ return "file_exists";
57
+ if (["USAGE_ERROR", "INVALID_ACTIONS"].includes(e.code))
54
58
  return "input";
55
59
  if (gd && e.operation === "dam.upload" && e.remoteCode === "36002105")
56
60
  return "upload";
@@ -64,7 +68,9 @@ export function observedErrorCategory(e) {
64
68
  || gd && ["dam.download", "dam.get", "dam.list", "dam.search"].includes(e.operation ?? "")
65
69
  && e.code === "REMOTE_REQUEST_FAILED" && [403, 404].includes(e.httpStatus ?? 0))
66
70
  return "asset_read";
67
- if (["EDITOR_NOT_CONNECTED", "EDITOR_DISCONNECTED", "EDITOR_NOT_READY", "EDITOR_SESSION_NOT_FOUND"].includes(e.code))
71
+ if (e.code === "EDITOR_SESSION_NOT_FOUND")
72
+ return "editor_required";
73
+ if (["EDITOR_NOT_CONNECTED", "EDITOR_DISCONNECTED", "EDITOR_NOT_READY"].includes(e.code))
68
74
  return "editor";
69
75
  if (e.code === "UNSUPPORTED_PAGE_CONTENT")
70
76
  return "unsupported";
@@ -72,14 +78,16 @@ export function observedErrorCategory(e) {
72
78
  return "save";
73
79
  if (e.code === "LOCAL_STATE_ERROR")
74
80
  return "local";
81
+ if (e.code === "UPDATE_FAILED" && e.diagnosticReason === "UPDATE_MANAGED_BY_HOST")
82
+ return "managed_update";
75
83
  if (e.code === "UPDATE_FAILED")
76
84
  return "update";
77
- if (e.code === "INTERNAL_ERROR" && e.failureStage === "output")
85
+ if (e.diagnosticReason === "OUTPUT_STREAM_FAILED" || e.code === "INTERNAL_ERROR" && e.failureStage === "output")
78
86
  return "output";
79
87
  if (gd && (e.operation === "tool.call" && ["12020700", "12020791", "500"].includes(e.remoteCode ?? "")
80
88
  || toolOrQuery && e.remoteCode === "12020780" || e.operation === "dam.upload" && e.remoteCode === "500"))
81
89
  return "request";
82
- if (e.code === "REMOTE_PROTOCOL_INCOMPATIBLE"
90
+ if (e.diagnosticReason?.startsWith("SSO_RESPONSE_") || e.code === "REMOTE_PROTOCOL_INCOMPATIBLE"
83
91
  || ["AGENT_CONTEXT_ID_MISSING", "AGENT_USAGE_MODEL_MISSING", "RESPONSE_BODY_ALREADY_USED"].includes(e.diagnosticReason ?? ""))
84
92
  return "read";
85
93
  if (e.code === "TOOL_TASK_FAILED")
@@ -98,7 +106,7 @@ export function observedErrorMessage(category, e) {
98
106
  return text("本次登录已超时,请重新登录。", "This sign-in timed out. Please sign in again.");
99
107
  if (category === "account" && e.code === "ORG_INVALID")
100
108
  return text("当前团队不可用,请重新选择团队。", "This team is unavailable. Select another team.");
101
- if (category === "input" && e.operation === "dam.rename" && e.remoteCode === "00010014")
109
+ if (category === "file_exists" && e.operation === "dam.rename" && e.remoteCode === "00010014")
102
110
  return text("名称已存在,请换个名称。", "This name already exists. Choose another name.");
103
111
  if (category === "asset_read" && e.code === "DAM_DOWNLOAD_FAILED")
104
112
  return text("素材下载未完成。", "The asset download did not complete.");
@@ -45,7 +45,7 @@ export function registerTaskCommands(program, runtime) {
45
45
  bindPreparedAction(get, "local-organization", async () => {
46
46
  const id = get.processedArgs[0];
47
47
  if (typeof id !== "string" || !validTaskId(id))
48
- throw new CliUsageError();
48
+ throw new CliUsageError("invalid_task_id");
49
49
  return { handled: false, input: id.toLowerCase() };
50
50
  }, async (context, id, signal) => {
51
51
  const result = await tasks.get({ id, state: context.state, signal });
@@ -25,7 +25,7 @@ export function registerToolCommands(program, runtime) {
25
25
  const call = tool.command("call")
26
26
  .description(text(runtime.product, "调用创作工具", "Call a creation tool"))
27
27
  .argument("<tool>", text(runtime.product, "工具机器标识", "tool machine identifier"))
28
- .option("--schema", text(runtime.product, "输出当前工具所有模型参数并集的输入 Schema", "output the tool-wide input Schema"))
28
+ .option("--schema", text(runtime.product, "输出按 model 区分必填字段和参数限制的输入 Schema", "output the input Schema with per-model required fields and constraints"))
29
29
  .option("--input <file|->", text(runtime.product, "从文件或标准输入读取参数 JSON", "read argument JSON from a file or stdin"))
30
30
  .option("--async", text(runtime.product, "提交后返回 taskId,通过 task get 查询结果", "return taskId after submission; retrieve results with task get"))
31
31
  .allowExcessArguments(false);
@@ -3,15 +3,19 @@ import { remoteErrorEvidence } from "../../platform/remote-error-evidence.js";
3
3
  import { normalizeScope } from "./state.js";
4
4
  import { signBindOrganization } from "../../platform/signature.js";
5
5
  export class SsoRequestError extends Error {
6
+ diagnosticSummary;
6
7
  status;
7
8
  remoteCode;
8
9
  remoteBody;
9
- constructor(status, evidence = {}, cause) {
10
+ diagnosticReason;
11
+ constructor(status, evidence = {}, cause, diagnosticSummary) {
10
12
  super(status === undefined ? "无法连接稿定登录服务。" : `稿定登录服务请求失败(HTTP ${status})。`, { cause });
13
+ this.diagnosticSummary = diagnosticSummary;
11
14
  this.name = "SsoRequestError";
12
15
  this.status = status;
13
16
  this.remoteCode = evidence.remoteCode;
14
17
  this.remoteBody = evidence.remoteBody;
18
+ this.diagnosticReason = evidence.diagnosticReason;
15
19
  }
16
20
  }
17
21
  export function classifyBindOutcome(input) {
@@ -42,12 +46,16 @@ export function createSsoService(options) {
42
46
  }
43
47
  }
44
48
  return new SsoRequestError(response.status, {
49
+ ...(response.ok ? { diagnosticReason: "SSO_RESPONSE_INVALID" } : {}),
45
50
  ...(evidence.remoteCode === undefined ? {} : { remoteCode: evidence.remoteCode }),
46
51
  ...remoteErrorEvidence({ request: requests.get(response),
47
52
  ...(evidence.remoteBody === undefined ? {} : { response: evidence.remoteBody }),
48
53
  ...(networkError === undefined ? {} : { network: networkFailure(networkError) }) })
49
54
  }, networkError);
50
55
  }
56
+ function invalidFields(response, phase, fields) {
57
+ return new SsoRequestError(response.status, { diagnosticReason: "SSO_RESPONSE_FIELDS_MISSING" }, undefined, { ssoPhase: phase, ssoInvalidFields: Object.entries(fields).filter(([, valid]) => !valid).map(([key]) => key).join(",") });
58
+ }
51
59
  async function responseRecord(response) {
52
60
  if (!response.ok) {
53
61
  // OAuth pending/slow_down are normal token polling responses.
@@ -101,7 +109,8 @@ export function createSsoService(options) {
101
109
  const expiresInSeconds = positiveNumber(body.expires_in);
102
110
  const intervalSeconds = positiveNumber(body.interval);
103
111
  if (!authorizeCode || !deviceCode || !expiresInSeconds || !intervalSeconds) {
104
- throw await responseError(response);
112
+ throw invalidFields(response, "authorize", { authorize_code: authorizeCode, device_code: deviceCode,
113
+ expires_in: expiresInSeconds, interval: intervalSeconds });
105
114
  }
106
115
  return { authorizeCode, deviceCode, expiresInSeconds, intervalSeconds };
107
116
  },
@@ -123,13 +132,13 @@ export function createSsoService(options) {
123
132
  const secretKey = nonEmptyString(body.sk);
124
133
  const expiresAt = dateString(body.expires_at);
125
134
  if (!accessKey || !secretKey || !expiresAt)
126
- throw await responseError(response);
135
+ throw invalidFields(response, "token", { ak: accessKey, sk: secretKey, expires_at: expiresAt });
127
136
  let scope;
128
137
  try {
129
138
  scope = normalizeScope(body.scope);
130
139
  }
131
140
  catch {
132
- throw await responseError(response);
141
+ throw invalidFields(response, "token", { scope: false });
133
142
  }
134
143
  const result = {
135
144
  status: "authorized",
@@ -9,6 +9,7 @@ export class DamAssetNotFoundError extends Error {
9
9
  }
10
10
  }
11
11
  export class DamAssetNotDownloadableError extends Error {
12
+ diagnosticReason = "ASSET_DOWNLOAD_URL_MISSING";
12
13
  constructor() {
13
14
  super("该 DAM 素材当前不可下载。");
14
15
  this.name = "DamAssetNotDownloadableError";
@@ -84,6 +84,9 @@ function safeFilename(candidate, fallback, format) {
84
84
  const segments = raw.normalize("NFKC").replace(/[\u0000-\u001f\u007f]/gu, "")
85
85
  .split(/[\\/]+/u);
86
86
  let filename = (segments.at(-1) ?? "").trim().replace(/^\.+/u, "");
87
+ filename = filename.replace(/[<>:"|?*]/gu, "_").replace(/[. ]+$/u, "");
88
+ if (/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/iu.test(filename))
89
+ filename = `_${filename}`;
87
90
  if (filename === "" || filename === "." || filename === "..")
88
91
  filename = "asset";
89
92
  if (extname(filename) === "")
@@ -153,6 +156,15 @@ export function createDamFileDownloader(options = {}) {
153
156
  randomId: options.randomId ?? randomUUID,
154
157
  cwd: options.cwd ?? process.cwd
155
158
  };
159
+ const warnCleanup = () => {
160
+ try {
161
+ options.warn?.("DOWNLOAD_TEMP_CLEANUP_FAILED");
162
+ }
163
+ catch {
164
+ // An advisory warning can encounter a closed stderr. It must neither
165
+ // roll back committed results nor replace the original download error.
166
+ }
167
+ };
156
168
  return {
157
169
  async download(input) {
158
170
  input.signal.throwIfAborted();
@@ -230,8 +242,14 @@ export function createDamFileDownloader(options = {}) {
230
242
  throw new DamDownloadError(cause, "commit");
231
243
  }
232
244
  createdFinalPaths.push(item.finalPath);
233
- await dependencies.fileSystem.rm(item.temporaryPath, { force: true });
234
245
  }
246
+ // Every result is committed before best-effort temporary cleanup. A
247
+ // host cleanup guard must never delete a successfully downloaded file.
248
+ let cleanupFailed = false;
249
+ await Promise.all(pending.map(item => dependencies.fileSystem.rm(item.temporaryPath, { force: true })
250
+ .catch(() => { cleanupFailed = true; })));
251
+ if (cleanupFailed)
252
+ warnCleanup();
235
253
  return pending.map((item) => ({
236
254
  path: item.finalPath,
237
255
  bytes: item.bytes,
@@ -241,15 +259,18 @@ export function createDamFileDownloader(options = {}) {
241
259
  catch (error) {
242
260
  const remainingPaths = [];
243
261
  const cleanupErrors = [];
262
+ let temporaryCleanupFailed = false;
244
263
  await Promise.all(pending.map(async (item) => {
245
264
  if (item.open)
246
265
  await item.handle.close().catch(cause => { cleanupErrors.push(cause); });
247
266
  await dependencies.fileSystem.rm(item.temporaryPath, { force: true }).catch(cause => {
248
267
  remainingPaths.push(item.temporaryPath);
249
- cleanupErrors.push(cause);
268
+ temporaryCleanupFailed = true;
250
269
  });
251
270
  }));
252
271
  await Promise.all(createdFinalPaths.map((path) => (dependencies.fileSystem.rm(path, { force: true }).catch(cause => { remainingPaths.push(path); cleanupErrors.push(cause); }))));
272
+ if (temporaryCleanupFailed)
273
+ warnCleanup();
253
274
  if (cleanupErrors.length)
254
275
  throw new DamDownloadError(new AggregateError([error, ...cleanupErrors], "Download cleanup failed.", { cause: error }), "cleanup", undefined, remainingPaths);
255
276
  if (isInterruption(error, input.signal))
@@ -28,18 +28,22 @@ export function createTaskStore(options) {
28
28
  try {
29
29
  const stat = await lstat(join(root, scope, `${id}.json`));
30
30
  if (!stat.isFile() || stat.isSymbolicLink())
31
- throw new LocalFileError(undefined);
31
+ throw new LocalFileError(undefined, undefined, "invalid_data", { operation: "read", step: "stat" });
32
32
  }
33
33
  catch (error) {
34
34
  if (error instanceof Error && "code" in error && error.code === "ENOENT")
35
35
  return null;
36
- throw error;
36
+ if (error instanceof LocalFileError)
37
+ throw error;
38
+ throw new LocalFileError(error, undefined, "io", { operation: "read", step: "stat" });
37
39
  }
38
40
  const text = await stateFile.readText();
39
41
  if (text === null)
40
42
  return null;
43
+ let step = "parse";
41
44
  try {
42
45
  const record = JSON.parse(text);
46
+ step = "validate";
43
47
  if (record.version !== 1 || record.task.taskId !== id || !record.progress
44
48
  || typeof record.progress !== "object" || Array.isArray(record.progress))
45
49
  throw new Error();
@@ -55,7 +59,7 @@ export function createTaskStore(options) {
55
59
  return record;
56
60
  }
57
61
  catch (cause) {
58
- throw new LocalFileError(cause);
62
+ throw new LocalFileError(cause, undefined, "invalid_data", { operation: "read", step });
59
63
  }
60
64
  },
61
65
  async write(scope, record) {
@@ -106,7 +110,7 @@ export function createTaskStore(options) {
106
110
  catch (error) {
107
111
  if (error instanceof Error && "code" in error && error.code === "ENOENT")
108
112
  return [];
109
- throw new LocalFileError(error);
113
+ throw new LocalFileError(error, undefined, "io", { operation: "list", step: "directory_read" });
110
114
  }
111
115
  const records = [];
112
116
  for (const name of names) {
@@ -260,7 +260,7 @@ export function createTaskUseCases(dependencies) {
260
260
  clearInterval(timer);
261
261
  const diagnostic = telemetry?.taskFailure(error).diagnostic_reason
262
262
  ?? (error instanceof RemoteRequestError ? error.diagnosticReason : undefined);
263
- const observationOnly = diagnostic === "LOCAL_WAIT_INTERRUPTED" || diagnostic === "TASK_QUERY_FAILED";
263
+ const observationOnly = diagnostic === "LOCAL_WAIT_INTERRUPTED" || diagnostic === "TASK_QUERY_FAILED" || diagnostic === "TASK_CANCELED";
264
264
  if (record.task.state !== "completed") {
265
265
  const mayBeRunning = dispatched || record.progress.submissionStarted;
266
266
  const auditRejected = isContentReviewRejection(error, { product: commandName === "insmind-cli" ? "insmind" : "gaoding", operation: input.operation });
@@ -269,13 +269,15 @@ export function createTaskUseCases(dependencies) {
269
269
  && error.remoteCode === "12020770";
270
270
  const confirmedFailure = error instanceof ToolTaskFailedError || auditRejected || creditsRejected;
271
271
  record.task.state = observationOnly ? "unknown" : confirmedFailure || !mayBeRunning ? "failed" : "unknown";
272
- record.task.note = diagnostic === "LOCAL_WAIT_INTERRUPTED"
273
- ? text("本次操作已停止等待。", "This operation stopped waiting.")
274
- : confirmedFailure
275
- ? text("本次生成未能完成。", "This creation could not be completed.")
276
- : mayBeRunning
277
- ? text("尚未取得任务结果。", "The task result has not been received.")
278
- : text("本次生成尚未开始。", "This creation has not started.");
272
+ record.task.note = diagnostic === "TASK_CANCELED"
273
+ ? text("生成任务已取消。", "The creation task was canceled.")
274
+ : diagnostic === "LOCAL_WAIT_INTERRUPTED"
275
+ ? text("本次操作已停止等待。", "This operation stopped waiting.")
276
+ : confirmedFailure
277
+ ? text("本次生成未能完成。", "This creation could not be completed.")
278
+ : mayBeRunning
279
+ ? text("尚未取得任务结果。", "The task result has not been received.")
280
+ : text("本次生成尚未开始。", "This creation has not started.");
279
281
  }
280
282
  const detail = dependencies.failureNote?.(error);
281
283
  if (detail && diagnostic !== "LOCAL_WAIT_INTERRUPTED")
@@ -63,6 +63,7 @@ export function buildToolArgumentsSchema(catalog, tool, modelDescription = "要
63
63
  const properties = {
64
64
  model: {
65
65
  type: "string",
66
+ enum: models.map(model => model.model),
66
67
  description: modelDescription
67
68
  }
68
69
  };
@@ -77,7 +78,9 @@ export function buildToolArgumentsSchema(catalog, tool, modelDescription = "要
77
78
  type: "object",
78
79
  properties,
79
80
  required: ["model"],
80
- additionalProperties: false
81
+ additionalProperties: false,
82
+ allOf: models.map(model => ({ if: { properties: { model: { const: model.model } }, required: ["model"] },
83
+ then: buildModelArgumentsSchema(model) }))
81
84
  };
82
85
  }
83
86
  export function buildModelArgumentsSchema(model) {
@@ -138,6 +138,10 @@ export class ToolTaskFailedError extends Error {
138
138
  this.diagnosticReason = evidence.diagnosticReason;
139
139
  }
140
140
  }
141
+ export class ToolTaskCanceledError extends Error {
142
+ diagnosticReason = "TASK_CANCELED";
143
+ constructor() { super("用户已取消生成任务。"); this.name = "ToolTaskCanceledError"; }
144
+ }
141
145
  export async function queryToolResult(transport, request) {
142
146
  try {
143
147
  return pollResult(await safePost(transport, {
@@ -149,7 +153,7 @@ export async function queryToolResult(transport, request) {
149
153
  }), request.taskId, request.onDifyTaskId);
150
154
  }
151
155
  catch (error) {
152
- if (isInterruption(error, request.signal))
156
+ if (isInterruption(error, request.signal) || error instanceof ToolTaskCanceledError)
153
157
  throw error;
154
158
  const evidence = error instanceof RemoteRequestError || error instanceof RemoteProtocolError
155
159
  ? { ...(error.remoteCode === undefined ? {} : { remoteCode: error.remoteCode }),
@@ -244,6 +248,12 @@ function pollResult(value, taskId, onDifyTaskId) {
244
248
  if (!Array.isArray(content)) {
245
249
  return failedPoll(new RemoteProtocolError(remoteErrorEvidence(inner)), difyTaskId);
246
250
  }
251
+ // Only the structured task envelope is authoritative. Text containing a
252
+ // cancellation message is ordinary content and does not change task state.
253
+ if (content.length === 1 && isRecord(content[0]) && content[0].type === "task"
254
+ && isRecord(content[0].task) && content[0].task.status === "CANCELED"
255
+ && content[0].task.id === taskId)
256
+ throw new ToolTaskCanceledError();
247
257
  try {
248
258
  return {
249
259
  state: "complete",
@@ -9,10 +9,12 @@ import { readInstallationOwner } from "../../platform/installation-owner.js";
9
9
  export class UpdateError extends Error {
10
10
  code;
11
11
  nextSteps;
12
- constructor(code, message, nextSteps, cause) {
12
+ diagnosticReason;
13
+ constructor(code, message, nextSteps, cause, diagnosticReason) {
13
14
  super(message, { cause });
14
15
  this.code = code;
15
16
  this.nextSteps = nextSteps;
17
+ this.diagnosticReason = diagnosticReason;
16
18
  this.name = "UpdateError";
17
19
  }
18
20
  get details() {
@@ -73,7 +75,7 @@ export function createUpdateService(options) {
73
75
  ? "This insMind CLI installation is managed by WorkBuddy."
74
76
  : "此 gd-cli 由 WorkBuddy 连接器管理。", [insmind
75
77
  ? "Update the insMind connector in WorkBuddy."
76
- : "请在 WorkBuddy 中更新「稿定」连接器。"]);
78
+ : "请在 WorkBuddy 中更新「稿定」连接器。"], undefined, "UPDATE_MANAGED_BY_HOST");
77
79
  }
78
80
  if (owner === "invalid") {
79
81
  throw new UpdateError("UPDATE_FAILED", insmind
@@ -118,6 +118,18 @@ async function acquireFileLock(path, run, options) {
118
118
  if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) {
119
119
  // Only our finished owner is retired. Old clients also ignore this suffix.
120
120
  await rename(ownPath, `${ownPath}.released`).catch(cause => {
121
+ // A host may have removed the source before throwing from unlink.
122
+ // Verify our own owner is gone; ENOENT on the rename alone can also
123
+ // mean the destination directory disappeared.
124
+ if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") {
125
+ return readFile(ownPath).then(() => {
126
+ releaseErrors.push(new AggregateError([error, cause], "Cannot retire the local lock owner."));
127
+ }, verification => {
128
+ if (!(verification instanceof Error && "code" in verification && verification.code === "ENOENT")) {
129
+ releaseErrors.push(new AggregateError([error, cause, verification], "Cannot verify the local lock owner."));
130
+ }
131
+ });
132
+ }
121
133
  releaseErrors.push(new AggregateError([error, cause], "Cannot retire the local lock owner."));
122
134
  });
123
135
  }
@@ -4,10 +4,12 @@ import { join } from "node:path";
4
4
  export class LocalFileError extends Error {
5
5
  file;
6
6
  reason;
7
- constructor(cause, file, reason = "io") {
7
+ diagnostic;
8
+ constructor(cause, file, reason = "io", diagnostic) {
8
9
  super("无法访问本地状态文件。", { cause });
9
10
  this.file = file;
10
11
  this.reason = reason;
12
+ this.diagnostic = diagnostic;
11
13
  this.name = "LocalFileError";
12
14
  }
13
15
  }
@@ -19,10 +21,14 @@ export function createLocalJsonFile(options) {
19
21
  let handle;
20
22
  let failed = false;
21
23
  let primaryError;
24
+ let step = "directory_permissions";
22
25
  try {
23
26
  await fileSystem.chmod(options.directory, 0o700);
27
+ step = "open";
24
28
  handle = await fileSystem.open(path, "r");
29
+ step = "file_permissions";
25
30
  await handle.chmod(0o600);
31
+ step = "read";
26
32
  return await handle.readFile("utf8");
27
33
  }
28
34
  catch (cause) {
@@ -30,7 +36,7 @@ export function createLocalJsonFile(options) {
30
36
  return null;
31
37
  failed = true;
32
38
  primaryError = cause;
33
- throw new LocalFileError(cause, options.filename);
39
+ throw new LocalFileError(cause, options.filename, "io", { operation: "read", step });
34
40
  }
35
41
  finally {
36
42
  try {
@@ -39,28 +45,36 @@ export function createLocalJsonFile(options) {
39
45
  catch (cause) {
40
46
  throw new LocalFileError(failed
41
47
  ? new AggregateError([primaryError, cause], "Cannot read and close local state.", { cause: primaryError })
42
- : cause, options.filename);
48
+ : cause, options.filename, "io", { operation: "read", step: failed ? step : "close" });
43
49
  }
44
50
  }
45
51
  },
46
52
  async writeTextAtomically(value) {
47
53
  const temporaryPath = join(options.directory, `${options.filename}.tmp-${randomUUID()}`);
48
54
  let handle;
55
+ let step = "directory_create";
49
56
  try {
50
57
  await fileSystem.mkdir(options.directory, { mode: 0o700, recursive: true });
58
+ step = "directory_permissions";
51
59
  await fileSystem.chmod(options.directory, 0o700);
60
+ step = "open";
52
61
  handle = await fileSystem.open(temporaryPath, "wx", 0o600);
62
+ step = "file_permissions";
53
63
  await handle.chmod(0o600);
64
+ step = "write";
54
65
  await handle.writeFile(value, "utf8");
66
+ step = "sync";
55
67
  await handle.sync();
68
+ step = "close";
56
69
  await handle.close();
57
70
  handle = undefined;
71
+ step = "rename";
58
72
  await fileSystem.rename(temporaryPath, path);
59
73
  }
60
74
  catch (cause) {
61
75
  await handle?.close().catch(() => undefined);
62
76
  await fileSystem.unlink(temporaryPath).catch(() => undefined);
63
- throw new LocalFileError(cause, options.filename);
77
+ throw new LocalFileError(cause, options.filename, "io", { operation: "write", step });
64
78
  }
65
79
  },
66
80
  async remove() {
@@ -69,7 +83,7 @@ export function createLocalJsonFile(options) {
69
83
  }
70
84
  catch (cause) {
71
85
  if (!isMissing(cause))
72
- throw new LocalFileError(cause, options.filename);
86
+ throw new LocalFileError(cause, options.filename, "io", { operation: "remove", step: "unlink" });
73
87
  }
74
88
  }
75
89
  };
@@ -3,8 +3,10 @@ import { open, realpath, stat } from "node:fs/promises";
3
3
  import { basename, extname, sep } from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
5
  export class LocalFileInputError extends Error {
6
- constructor(cause) {
6
+ reason;
7
+ constructor(cause, reason = "file_read_failed") {
7
8
  super("本地文件不可用于上传。", { cause });
9
+ this.reason = reason;
8
10
  this.name = "LocalFileInputError";
9
11
  }
10
12
  }
@@ -50,16 +52,15 @@ const mediaTypes = {
50
52
  webm: "video/webm",
51
53
  webp: "image/webp"
52
54
  };
53
- function reject() {
54
- throw new LocalFileInputError();
55
+ function reject(reason) {
56
+ throw new LocalFileInputError(undefined, reason);
55
57
  }
56
58
  function assertSafePath(filePath) {
57
59
  const segments = filePath.split(sep).filter(Boolean).map((segment) => segment.toLowerCase());
58
60
  const filename = segments.at(-1) ?? "";
59
- if (protectedFilenames.has(filename) || /^\.env(?:\.|$)/.test(filename))
60
- reject();
61
- if (segments.some((segment) => segment.startsWith(".") || protectedSegments.has(segment))) {
62
- reject();
61
+ if (protectedFilenames.has(filename) || filename.startsWith(".")
62
+ || segments.some(segment => protectedSegments.has(segment))) {
63
+ reject("path_restricted");
63
64
  }
64
65
  }
65
66
  function detectedFormat(header) {
@@ -113,18 +114,25 @@ export async function inspectUploadFile(input) {
113
114
  assertSafePath(filePath);
114
115
  const details = await stat(filePath);
115
116
  if (!details.isFile())
116
- return reject();
117
+ return reject("not_regular_file");
117
118
  const header = await readHeader(filePath, input.signal);
118
119
  const detected = detectedFormat(header);
120
+ // Hidden host/workspace ancestors are not themselves secrets. Only known
121
+ // media headers may pass there; named credential paths remain blocked on
122
+ // both requested and canonical paths before any file is opened.
123
+ if (input.allowSensitivePath !== true && detected === undefined
124
+ && [requestedPath, filePath].some(path => path.split(sep).some(segment => segment.startsWith(".")))) {
125
+ return reject("path_restricted");
126
+ }
119
127
  const extension = extname(requestedPath).slice(1).toLowerCase();
120
128
  const format = detected ?? (extension === "jpg" ? "jpeg" : extension);
121
129
  if (format === "")
122
- return reject();
130
+ return reject("format_missing");
123
131
  const detectedMediaType = detected === undefined ? undefined : mediaTypes[detected];
124
132
  if (detectedMediaType !== undefined
125
133
  && input.claimedMediaType !== undefined
126
134
  && input.claimedMediaType.trim().toLowerCase() !== detectedMediaType) {
127
- return reject();
135
+ return reject("media_type_mismatch");
128
136
  }
129
137
  return {
130
138
  filePath,
@@ -1,5 +1,50 @@
1
- export function validationIssues(errors) {
2
- return (errors ?? []).slice(0, 8).map(error => ({
1
+ export function validationIssues(errors, value, schema) {
2
+ let selected = errors ?? [];
3
+ const at = (root, pointer) => pointer.replace(/^#\/?/u, "").split("/").filter(Boolean)
4
+ .reduce((node, key) => node && typeof node === "object" ? node[key.replace(/~1/gu, "/").replace(/~0/gu, "~")] : undefined, root);
5
+ const unions = [];
6
+ const visit = (node) => {
7
+ if (!node || typeof node !== "object")
8
+ return;
9
+ if ("oneOf" in node && Array.isArray(node.oneOf))
10
+ unions.push(node.oneOf);
11
+ for (const child of Object.values(node))
12
+ visit(child);
13
+ };
14
+ visit(schema);
15
+ for (const union of errors ?? []) {
16
+ if (union.keyword !== "oneOf")
17
+ continue;
18
+ // AJV may emit #/oneOf for an inlined $ref. Recover that group only when
19
+ // its referenced branches are evidenced at this exact input location.
20
+ const branches = at(schema, union.schemaPath) ?? unions.find(group => group.every(branch => branch && typeof branch === "object" && "$ref" in branch && typeof branch.$ref === "string"
21
+ && selected.some(error => (error.instancePath === union.instancePath || error.instancePath.startsWith(`${union.instancePath}/`))
22
+ && error.schemaPath.startsWith(`${branch.$ref}/`))));
23
+ const input = at(value, union.instancePath);
24
+ if (!Array.isArray(branches) || !input || typeof input !== "object")
25
+ continue;
26
+ const refs = branches.map(branch => typeof branch?.$ref === "string" && branch.$ref.startsWith("#/") ? branch.$ref : undefined);
27
+ if (refs.some(ref => !ref))
28
+ continue;
29
+ const matches = refs.filter(ref => {
30
+ const branch = at(schema, ref);
31
+ if (!branch || !Array.isArray(branch.required) || !branch.required.length)
32
+ return false;
33
+ return branch.required.every(key => typeof key === "string" && Object.hasOwn(input, key))
34
+ && Object.entries(branch.properties ?? {}).every(([key, property]) => !Object.hasOwn(property, "const")
35
+ || input[key] === property.const);
36
+ });
37
+ if (matches.length !== 1)
38
+ continue;
39
+ const blocked = refs.filter(ref => ref !== matches[0]);
40
+ selected = selected.filter(error => {
41
+ if (error === union)
42
+ return false;
43
+ const related = error.instancePath === union.instancePath || error.instancePath.startsWith(`${union.instancePath}/`);
44
+ return !related || !blocked.some(ref => error.schemaPath.startsWith(`${ref}/`));
45
+ });
46
+ }
47
+ return selected.slice(0, 8).map(error => ({
3
48
  field: `${error.instancePath}${typeof error.params.missingProperty === "string" ? `/${error.params.missingProperty}`
4
49
  : typeof error.params.additionalProperty === "string" ? `/${error.params.additionalProperty}` : ""}`.slice(0, 256) || "/",
5
50
  rule: error.keyword,
@@ -1,9 +1,22 @@
1
1
  import { Writable } from "node:stream";
2
+ export class OutputStreamError extends Error {
3
+ outputStream;
4
+ constructor(outputStream, cause) {
5
+ super("结果未能完整返回。", { cause });
6
+ this.outputStream = outputStream;
7
+ this.name = "OutputStreamError";
8
+ }
9
+ }
2
10
  /** Writes remain synchronous for command presenters; flush acknowledges delivery. */
3
- export function createTextOutput(stream) {
11
+ export function createTextOutput(stream, outputStream = "stdout") {
4
12
  if (!(stream instanceof Writable))
5
13
  return {
6
- write: text => { stream.write(text); }, flush: async () => { }
14
+ write: text => { try {
15
+ stream.write(text);
16
+ }
17
+ catch (cause) {
18
+ throw new OutputStreamError(outputStream, cause);
19
+ } }, flush: async () => { }
7
20
  };
8
21
  const pending = new Set();
9
22
  let failure;
@@ -11,7 +24,7 @@ export function createTextOutput(stream) {
11
24
  return {
12
25
  write(text) {
13
26
  if (failure)
14
- throw failure;
27
+ throw new OutputStreamError(outputStream, failure);
15
28
  const writing = new Promise(resolve => {
16
29
  try {
17
30
  stream.write(text, error => { failure ??= error ?? undefined; resolve(); });
@@ -27,7 +40,7 @@ export function createTextOutput(stream) {
27
40
  async flush() {
28
41
  await Promise.all(pending);
29
42
  if (failure)
30
- throw failure;
43
+ throw new OutputStreamError(outputStream, failure);
31
44
  }
32
45
  };
33
46
  }
@@ -2,6 +2,11 @@ const flags = new Set(["bodyUsedAtReceipt", "bodyLockedAtReceipt", "bodyUsedBefo
2
2
  "bodyLockedBeforeRead", "reusedResponse", "contextIdPresent", "streamHadBytes"]);
3
3
  const counts = new Set(["messageCount", "invalidMessageCount", "systemErrorCount", "publicPartCount",
4
4
  "streamPayloadCount", "streamJsonValueCount"]);
5
+ const localFileSteps = new Set(["directory_create", "directory_permissions", "directory_read", "stat", "parse", "validate", "open", "file_permissions", "read", "write", "sync", "close", "rename", "unlink"]);
6
+ const inputReasons = new Set(["path_restricted", "not_regular_file", "format_missing", "media_type_mismatch", "file_read_failed",
7
+ "json_read", "json_parse", "schema_validation", "invalid_task_id", "command_arguments", "model_required", "model_not_found",
8
+ "model_tool_mismatch", "model_parameters", "tool_not_found", "invalid_asset_url", "commander.unknownOption",
9
+ "commander.unknownCommand", "commander.missingArgument", "commander.excessArguments", "commander.help"]);
5
10
  /** Fixed diagnostic facts, never arbitrary response fields or error messages. */
6
11
  export function safeFailureSummary(value) {
7
12
  if (!value || typeof value !== "object" || Array.isArray(value))
@@ -12,6 +17,19 @@ export function safeFailureSummary(value) {
12
17
  result[key] = field;
13
18
  if (counts.has(key) && typeof field === "number" && Number.isSafeInteger(field) && field >= 0 && field <= 100_000)
14
19
  result[key] = field;
20
+ if (key === "inputReason" && typeof field === "string" && inputReasons.has(field))
21
+ result[key] = field;
22
+ if (key === "ssoPhase" && (field === "authorize" || field === "token"))
23
+ result[key] = field;
24
+ if (key === "outputStream" && (field === "stdout" || field === "stderr"))
25
+ result[key] = field;
26
+ if (key === "localFileOperation" && (field === "read" || field === "write" || field === "remove" || field === "list"))
27
+ result[key] = field;
28
+ if (key === "localFileStep" && typeof field === "string" && localFileSteps.has(field))
29
+ result[key] = field;
30
+ if (key === "ssoInvalidFields" && typeof field === "string"
31
+ && /^(?:authorize_code|device_code|expires_in|interval|ak|sk|expires_at|scope)(?:,(?:authorize_code|device_code|expires_in|interval|ak|sk|expires_at|scope))*$/u.test(field))
32
+ result[key] = field;
15
33
  if (key === "systemCode" && typeof field === "string"
16
34
  && /^(?:E[A-Z0-9_]{1,40}|UND_ERR_[A-Z0-9_]{1,40}|LOCAL_LOCK_TIMEOUT)$/u.test(field))
17
35
  result[key] = field;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@insmind/cli",
3
- "version": "1.7.1",
3
+ "version": "1.8.0",
4
4
  "description": "insMind command-line interface for agents and people.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -46,8 +46,8 @@
46
46
  "@gaoding/cli": "workspace:*"
47
47
  },
48
48
  "gaodingRelease": {
49
- "sourceCommit": "53aa55169df83ca3437874f7d002c741b694be76",
50
- "pipelineId": "229607",
51
- "pipelineUrl": "https://git.intra.gaoding.com/gtt/gaoding-cli/-/pipelines/229607"
49
+ "sourceCommit": "d1722afac1b5acdc776ee3fbc2f2d69496e1a8af",
50
+ "pipelineId": "230438",
51
+ "pipelineUrl": "https://git.intra.gaoding.com/gtt/gaoding-cli/-/pipelines/230438"
52
52
  }
53
53
  }
@@ -14,7 +14,7 @@ insmind-cli task get <taskId>
14
14
 
15
15
  `tool list` lists available Tools. Model discovery provides current descriptions, prices, estimated duration and structured parameters. Follow each parameter's `required`, `type` and `description`; for SELECT parameters use `options[].value`. Explicitly supply a required parameter's `default` when the user did not specify it. Read `usageDescription` for combinations such as video mode and frame/media requirements; individual fields cannot establish these rules. Do not freeze catalog values in prompts or scripts.
16
16
 
17
- Provide all required fields. Put width, height, resolution and similar requirements in dedicated structured parameters when available, rather than only in prompt text. `tool call <tool> --schema` is the parameter union of all models in the Tool; after selecting a model, use its `model get` parameters and `usageDescription`.
17
+ Provide all required fields. Put width, height, resolution and similar requirements in dedicated structured parameters when available, rather than only in prompt text. `tool call <tool> --schema` selects required fields, allowed parameters and ranges by model. Use `model get` for step, defaults and cross-field rules in `usageDescription`. Fixed JSON commands also accept `--json`.
18
18
 
19
19
  Copy the returned `model` identifier into the top-level `model` field of request JSON (runtime `arguments.model`), alongside its parameters:
20
20