@insmind/cli 1.5.1 → 1.5.3

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 (67) hide show
  1. package/contracts/operations/auth.status/output.schema.json +3 -4
  2. package/dist/bin/insmind-cli.js +12 -7
  3. package/dist/bin/postinstall.js +7 -5
  4. package/dist/bin/{agent-worker.js → task-worker.js} +5 -4
  5. package/dist/src/analytics/device.js +23 -0
  6. package/dist/src/analytics/wind.js +54 -0
  7. package/dist/src/bootstrap/create-cli.js +33 -19
  8. package/dist/src/bootstrap/create-runtime.js +45 -16
  9. package/dist/src/bootstrap/{run-agent-worker.js → run-task-worker.js} +20 -10
  10. package/dist/src/bootstrap/validators.js +10 -5
  11. package/dist/src/cli/action-binding.js +14 -0
  12. package/dist/src/cli/agent-commands.js +9 -4
  13. package/dist/src/cli/auth-commands.js +5 -3
  14. package/dist/src/cli/credits-command.js +2 -2
  15. package/dist/src/cli/dam-commands.js +51 -52
  16. package/dist/src/cli/editor-commands.js +13 -15
  17. package/dist/src/cli/errors.js +97 -44
  18. package/dist/src/cli/model-commands.js +6 -4
  19. package/dist/src/cli/presenter.js +13 -10
  20. package/dist/src/cli/task-commands.js +13 -5
  21. package/dist/src/cli/tool-commands.js +11 -5
  22. package/dist/src/features/agent/use-cases.js +11 -5
  23. package/dist/src/features/auth/access-policy.js +2 -0
  24. package/dist/src/features/auth/credential-store.js +2 -2
  25. package/dist/src/features/auth/sso-service.js +5 -4
  26. package/dist/src/features/auth/state.js +11 -1
  27. package/dist/src/features/auth/use-cases.js +43 -40
  28. package/dist/src/features/credits/use-cases.js +2 -0
  29. package/dist/src/features/dam/file-downloader.js +38 -16
  30. package/dist/src/features/dam/object-storage.js +23 -11
  31. package/dist/src/features/dam/operation-executor.js +46 -37
  32. package/dist/src/features/dam/registered-uploader.js +39 -29
  33. package/dist/src/features/dam/storage-upload.js +5 -4
  34. package/dist/src/features/dam/use-cases.js +81 -60
  35. package/dist/src/features/editor/bridge-client.js +6 -6
  36. package/dist/src/features/editor/bridge-process.js +2 -1
  37. package/dist/src/features/editor/session-state.js +6 -4
  38. package/dist/src/features/editor/session.js +26 -8
  39. package/dist/src/features/editor/use-cases.js +10 -3
  40. package/dist/src/features/org/use-cases.js +2 -1
  41. package/dist/src/features/task/store.js +4 -0
  42. package/dist/src/features/task/{agent-background.js → task-background.js} +5 -4
  43. package/dist/src/features/task/use-cases.js +123 -28
  44. package/dist/src/features/tool/catalog.js +11 -5
  45. package/dist/src/features/tool/dynamic-schema.js +9 -7
  46. package/dist/src/features/tool/mns-catalog-adapter.js +1 -0
  47. package/dist/src/features/tool/tool-api-adapter.js +8 -7
  48. package/dist/src/features/tool/use-cases.js +8 -4
  49. package/dist/src/features/update/update-notification.js +75 -70
  50. package/dist/src/features/update/update-service.js +24 -20
  51. package/dist/src/platform/file-lock.js +36 -9
  52. package/dist/src/platform/interruption.js +13 -0
  53. package/dist/src/platform/json-input.js +12 -9
  54. package/dist/src/platform/local-json-file.js +8 -4
  55. package/dist/src/platform/redact.js +7 -1
  56. package/dist/src/platform/remote-protocol.js +2 -2
  57. package/dist/src/platform/safe-upload-file.js +2 -1
  58. package/dist/src/platform/schema-issues.js +8 -0
  59. package/dist/src/platform/signed-http-transport.js +8 -7
  60. package/dist/src/platform/text-output.js +33 -0
  61. package/dist/src/telemetry/invocation.js +19 -4
  62. package/dist/src/telemetry/process-errors.js +14 -4
  63. package/dist/src/telemetry/sanitize.js +4 -2
  64. package/dist/src/telemetry/sls-sink.js +36 -20
  65. package/dist/vendor/README.md +10 -0
  66. package/dist/vendor/gd-tracker-node.mjs +1175 -0
  67. package/package.json +4 -4
@@ -1,9 +1,9 @@
1
- import { AgentBackgroundError } from "../features/task/agent-background.js";
1
+ import { TaskBackgroundError } from "../features/task/task-background.js";
2
2
  import { TaskNotFoundError } from "../features/task/use-cases.js";
3
3
  import { TaskStoreError } from "../features/task/store.js";
4
4
  import { CommanderError } from "commander";
5
5
  import { AuthExpiredError, AuthRequiredError } from "../features/auth/access-policy.js";
6
- import { AuthStateInvalidError } from "../features/auth/state.js";
6
+ import { AuthStateInvalidError, UserIdentityMissingError } from "../features/auth/state.js";
7
7
  import { SsoRequestError } from "../features/auth/sso-service.js";
8
8
  import { AuthorizedAccountContextMissingError, DeviceAuthorizationExpiredError } from "../features/auth/use-cases.js";
9
9
  import { AgentInputError } from "../features/agent/use-cases.js";
@@ -11,7 +11,7 @@ import { ToolInputError } from "../features/tool/catalog.js";
11
11
  import { ToolTaskFailedError } from "../features/tool/tool-api-adapter.js";
12
12
  import { ObjectStorageUploadError } from "../features/dam/object-storage.js";
13
13
  import { DamAssetNotDownloadableError, DamAssetNotFoundError, DamFolderNotFoundError } from "../features/dam/dam-api-adapter.js";
14
- import { DamDownloadDestinationExistsError } from "../features/dam/file-downloader.js";
14
+ import { DamDownloadError, DamDownloadDestinationExistsError } from "../features/dam/file-downloader.js";
15
15
  import { DamOperationFailedError } from "../features/dam/operation-executor.js";
16
16
  import { DamInputError, DamOperationUnconfirmedError, DamRepositoryNotFoundError } from "../features/dam/use-cases.js";
17
17
  import { OrganizationResponseError } from "../features/org/org-service.js";
@@ -21,7 +21,9 @@ import { RemoteProtocolError } from "../platform/remote-protocol.js";
21
21
  import { InputContractError, OutputContractError } from "../bootstrap/validators.js";
22
22
  import { JsonInputError } from "../platform/json-input.js";
23
23
  import { LocalFileInputError } from "../platform/safe-upload-file.js";
24
- import { EditorBridgeError } from "../features/editor/bridge-client.js";
24
+ import { EditorBridgeError, EditorBridgeUnavailableError } from "../features/editor/bridge-client.js";
25
+ import { LocalFileError } from "../platform/local-json-file.js";
26
+ import { redactSensitiveText } from "../platform/redact.js";
25
27
  import { EditorNotReadyError, EditorSessionNotFoundError, EditorTargetError } from "../features/editor/session.js";
26
28
  import { UpdateError } from "../features/update/update-service.js";
27
29
  export class CliUsageError extends Error {
@@ -33,7 +35,7 @@ export class CliUsageError extends Error {
33
35
  const INSUFFICIENT_CREDITS_REMOTE_CODE = "12020770";
34
36
  const INSUFFICIENT_CREDITS_NEXT_STEPS = [
35
37
  "前往 https://www.gaoding.art/pricing 购买稿豆",
36
- "也可以执行 gd-cli org switch 切换到有可用稿豆的组织",
38
+ "也可以执行 gd-cli org list,再用 gd-cli org switch --org <org-id> 切换到有可用稿豆的组织",
37
39
  "处理后重新发起本次创作"
38
40
  ];
39
41
  export function isHelpOutcome(error) {
@@ -44,16 +46,26 @@ export function isHelpOutcome(error) {
44
46
  export function mapCliError(error, options) {
45
47
  const insmind = options.product?.id === "insmind";
46
48
  const command = options.product?.commandName ?? "gd-cli";
49
+ const text = (zh, en) => insmind ? en : zh;
47
50
  if (options.aborted)
48
- return { kind: "interrupted", exitCode: 130 };
49
- if (error instanceof AgentBackgroundError)
51
+ return { kind: "interrupted", exitCode: 130, failure: {
52
+ code: "INTERRUPTED", message: text("已停止本地等待;已派发的任务或写操作可能仍在继续。", "Local waiting stopped; dispatched tasks or writes may still be active."),
53
+ details: { ...(error instanceof DamOperationUnconfirmedError ? { operation: error.operation, ...error.context } : {}),
54
+ ...(error instanceof DamDownloadError ? { phase: error.phase, remaining_paths: error.remainingPaths } : {}),
55
+ next_steps: [text(`创作用 ${command} task list 找到原任务,再用 task get <id> 查询;Editor 写入先检查原作品。不要直接重复提交。`, `For creation, find the original task with ${command} task list, then task get <id>. For Editor writes, inspect the original work. Do not resubmit directly.`)] }
56
+ } };
57
+ if (error instanceof TaskBackgroundError)
50
58
  return { kind: "failure", failure: error.failure, exitCode: error.exitCode };
51
59
  if (error instanceof TaskNotFoundError)
52
60
  return failure("TASK_NOT_FOUND", error.message, 1);
53
61
  if (error instanceof TaskStoreError)
54
62
  return failure("LOCAL_STATE_ERROR", insmind
55
63
  ? "Cannot read or write local task records. Check permissions and file integrity in ~/.insmind/tasks."
56
- : "无法读写本地执行记录;请检查 ~/.gd/tasks 的权限和文件完整性。", 1);
64
+ : "无法读写本地执行记录;请检查 ~/.gd/tasks 的权限和文件完整性。", 1, error.context ? [text("保留已有输出;恢复文件访问后查询原任务,不要重新提交创作。", "Keep any output; restore file access and query the original task without submitting again."),
65
+ `${command} task get ${error.context.cli_task_id}`] : undefined, { ...error.context, reason: "task_storage", system_code: systemErrorCode(error) });
66
+ if (error instanceof UserIdentityMissingError) {
67
+ return failure("AUTH_REQUIRED", text("登录身份缺少用户 ID,请重新登录。", "The login identity has no user ID. Please sign in again."), 1, [`${command} auth login`]);
68
+ }
57
69
  if (error instanceof AuthRequiredError) {
58
70
  if (insmind)
59
71
  return failure("AUTH_REQUIRED", `Run ${command} auth login first.`, 1, [`${command} auth login`]);
@@ -65,31 +77,50 @@ export function mapCliError(error, options) {
65
77
  return failure("AUTH_EXPIRED", "登录已过期,请退出后重新登录。", 1, ["gd-cli auth logout", "gd-cli auth login"]);
66
78
  }
67
79
  if (error instanceof AuthStateInvalidError) {
80
+ if (error.reason === "local_io")
81
+ return failure("AUTH_STATE_INVALID", text("无法读写本地凭证,当前无法判断登录是否有效。", "Cannot access local credentials; authentication validity is unknown."), 1, [text("恢复凭证文件的访问权限或宿主文件访问能力;不要执行 logout 或删除凭证。", "Restore access to the credential file or host file permissions; do not log out or delete credentials.")], { reason: error.reason, system_code: systemErrorCode(error) });
68
82
  if (insmind)
69
- return failure("AUTH_STATE_INVALID", "Local authentication state is invalid. Sign out and sign in again.", 1, [`${command} auth logout`, `${command} auth login`]);
70
- return failure("AUTH_STATE_INVALID", "本地登录状态已失效,请退出后重新登录。", 1, ["gd-cli auth logout", "gd-cli auth login"]);
83
+ return failure("AUTH_STATE_INVALID", "Local authentication state is invalid. Sign out and sign in again.", 1, [`${command} auth logout`, `${command} auth login`], { reason: error.reason });
84
+ return failure("AUTH_STATE_INVALID", "本地登录状态内容无效,请退出后重新登录。", 1, ["gd-cli auth logout", "gd-cli auth login"], { reason: error.reason });
71
85
  }
72
86
  if (error instanceof OrganizationInvalidError) {
73
87
  if (insmind)
74
88
  return failure("AUTH_STATE_INVALID", "The account context is unavailable. Sign out and sign in again.", 1, [`${command} auth logout`, `${command} auth login`]);
75
- return failure("ORG_INVALID", "所选组织不可用,请重新选择组织。", 1, ["gd-cli org switch"]);
89
+ return failure("ORG_INVALID", "所选组织不可用,请重新选择组织。", 1, ["gd-cli org list", "gd-cli org switch --org <org-id>"]);
76
90
  }
77
91
  if (error instanceof UpdateError) {
78
- return failure(error.code, error.message, 1, error.nextSteps);
92
+ return failure(error.code, error.message, 1, error.nextSteps, error.details);
79
93
  }
80
94
  if (error instanceof EditorTargetError) {
81
95
  if (insmind)
82
96
  return failure(error.code, "Editor target must be a work ID or a complete trusted insMind Editor URL.", 2);
83
97
  return failure(error.code, error.message, 2);
84
98
  }
99
+ if (error instanceof JsonInputError)
100
+ return failure("USAGE_ERROR", error.reason === "read"
101
+ ? text("无法读取 JSON 输入。", "Cannot read the JSON input.")
102
+ : text("JSON 输入语法无效。", "The input is not valid JSON."), 2, [error.reason === "read" ? text("检查输入文件是否存在、是否可读,或 stdin 是否可用。", "Check that the input file exists and is readable, or that stdin is available.")
103
+ : text("修正 JSON 语法后重新执行;输入尚未提交。", "Correct the JSON syntax and run again; the input has not been submitted.")], { reason: `json_${error.reason}`, system_code: systemErrorCode(error) });
104
+ if (error instanceof InputContractError)
105
+ return failure("USAGE_ERROR", text("输入不符合命令要求,请修正所列字段。", "The input does not match the command requirements; correct the listed fields."), 2, [text("使用该命令 --help 中的 Schema 发现入口核对输入。file URL 请用 pathToFileURL(path).href 生成,中文文件名无需改名。", "Use the Schema discovery described in this command's --help. Generate file URLs with pathToFileURL(path).href; Unicode filenames are supported.")], { reason: "schema_validation", issues: error.issues });
106
+ if (error instanceof ToolInputError || error instanceof AgentInputError) {
107
+ const descriptions = {
108
+ model_not_found: ["指定模型不在当前可用目录中。", "The selected model is not in the current catalog."],
109
+ tool_not_found: ["指定工具不在当前可用目录中。", "The selected tool is not in the current catalog."],
110
+ model_tool_mismatch: ["模型不属于所选工具。", "The model does not belong to the selected tool."],
111
+ model_required: ["缺少 model 字段。", "The model field is required."],
112
+ model_parameters: ["参数不符合所选模型要求。", "The arguments do not match the selected model requirements."],
113
+ invalid_asset_url: ["素材 URL 不符合可访问资源要求。", "The asset URL does not meet the accessible resource requirements."]
114
+ };
115
+ const description = descriptions[error.reason];
116
+ 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 } : {}) });
117
+ }
118
+ if (error instanceof LocalFileInputError)
119
+ 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) });
120
+ if (error instanceof DamInputError)
121
+ 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 });
85
122
  if (error instanceof OrgUsageError
86
123
  || error instanceof CliUsageError
87
- || error instanceof JsonInputError
88
- || error instanceof InputContractError
89
- || error instanceof AgentInputError
90
- || error instanceof ToolInputError
91
- || error instanceof DamInputError
92
- || error instanceof LocalFileInputError
93
124
  || error instanceof CommanderError) {
94
125
  if (insmind)
95
126
  return failure("USAGE_ERROR", "Invalid command or arguments. See --help.", 2);
@@ -101,9 +132,7 @@ export function mapCliError(error, options) {
101
132
  return failure("INSUFFICIENT_CREDITS", "当前组织稿豆不足,无法完成本次创作。", 1, INSUFFICIENT_CREDITS_NEXT_STEPS);
102
133
  }
103
134
  if (error instanceof RemoteProtocolError) {
104
- if (insmind)
105
- return failure("REMOTE_PROTOCOL_INCOMPATIBLE", "The insMind service returned a result this CLI cannot safely process; processing stopped to avoid duplicate creation.", 1);
106
- return failure("REMOTE_PROTOCOL_INCOMPATIBLE", "稿定服务返回了当前 CLI 无法安全处理的结果;为避免重复创作,已停止处理。", 1);
135
+ 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.`)]);
107
136
  }
108
137
  if (error instanceof ToolTaskFailedError) {
109
138
  return failure("TOOL_TASK_FAILED", insmind ? "The Tool task failed." : "稿定工具任务执行失败。", 1);
@@ -124,10 +153,13 @@ export function mapCliError(error, options) {
124
153
  ? "The destination file already exists and was not overwritten. Choose another output directory."
125
154
  : "目标文件已存在,未覆盖任何文件;请更换输出目录或移走同名文件。", 1);
126
155
  }
156
+ if (error instanceof DamDownloadError)
157
+ return failure("DAM_DOWNLOAD_FAILED", text("素材下载未完成;请按失败阶段检查源文件访问或目标目录。", "The asset download did not complete; check source access or the destination for the reported phase."), 1, [text("已有素材无需重新生成;先检查文件状态再决定是否重新下载。", "Do not regenerate the asset; inspect file state before downloading again.")], { phase: error.phase, system_code: systemErrorCode(error), http_status: error.status,
158
+ ...(error.remainingPaths.length ? { remaining_paths: error.remainingPaths } : {}) });
127
159
  if (error instanceof DamOperationUnconfirmedError) {
128
160
  return failure("DAM_OPERATION_UNCONFIRMED", insmind
129
161
  ? "The operation was submitted, but its final result could not be confirmed. Check the destination before retrying."
130
- : "操作已提交,但未能确认最终结果;请先查询目标位置,不要立即重复提交。", 1);
162
+ : "操作已提交,但未能确认最终结果;请先查询目标位置,不要立即重复提交。", 1, [text(`查询原素材用 ${command} dam get <asset-id>;查询目标位置用 dam list --repository-id <id> --folder-id <id>。删除结果需在回收站核对,不重复提交。`, `Inspect the original asset with ${command} dam get <asset-id>, or the destination with dam list --repository-id <id> --folder-id <id>. Inspect the recycle bin for deletion outcomes before submitting again.`)], { operation: error.operation, ...error.context });
131
163
  }
132
164
  if (error instanceof DamOperationFailedError) {
133
165
  return failure("DAM_OPERATION_FAILED", insmind
@@ -136,25 +168,38 @@ export function mapCliError(error, options) {
136
168
  }
137
169
  if (error instanceof DamRepositoryNotFoundError) {
138
170
  if (insmind)
139
- return failure("DAM_REPOSITORY_NOT_FOUND", "No accessible asset repository is available for this account.", 1, [`${command} auth logout`, `${command} auth login`]);
171
+ return failure("DAM_REPOSITORY_NOT_FOUND", "No accessible asset repository is available for this account.", 1, ["Check asset repository access for this account, then run insmind-cli dam repository list."]);
140
172
  return failure("DAM_REPOSITORY_NOT_FOUND", "当前组织没有可用的 DAM 资源库。", 1, ["gd-cli org list", "gd-cli org switch --org <org-id>"]);
141
173
  }
174
+ if (error instanceof DeviceAuthorizationExpiredError)
175
+ return failure("REMOTE_REQUEST_FAILED", text("本次登录授权已过期,请重新开始授权。", "This login authorization expired; start authorization again."), 1, [`${command} auth login`], { reason: "authorization_expired" });
142
176
  if (error instanceof RemoteRequestError
143
177
  || error instanceof SsoRequestError
144
- || error instanceof DeviceAuthorizationExpiredError
145
178
  || error instanceof OrganizationResponseError
146
179
  || error instanceof OrganizationBindFailedError
147
180
  || error instanceof ObjectStorageUploadError
148
181
  || error instanceof AuthorizedAccountContextMissingError) {
149
- if (insmind)
150
- return failure("REMOTE_REQUEST_FAILED", "The insMind service request failed.", 1);
151
- return failure("REMOTE_REQUEST_FAILED", "稿定服务请求失败。", 1);
182
+ const reason = error instanceof OrganizationResponseError ? "organization_response"
183
+ : error instanceof OrganizationBindFailedError ? "organization_binding"
184
+ : error instanceof AuthorizedAccountContextMissingError ? "account_context_missing"
185
+ : error instanceof ObjectStorageUploadError ? "asset_upload" : "request";
186
+ const messages = {
187
+ organization_response: ["组织服务返回的数据无法处理。", "The organization response could not be processed."],
188
+ organization_binding: ["未能完成组织绑定。", "Organization binding did not complete."],
189
+ account_context_missing: ["授权响应缺少必要的账号上下文。", "The authorization response is missing the required account context."],
190
+ asset_upload: ["素材上传未完成。", "The asset upload did not complete."],
191
+ request: ["稿定服务请求失败;是否已受理取决于本次请求阶段。", "The service request failed; acceptance depends on the request phase."]
192
+ };
193
+ 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),
194
+ ...((error instanceof RemoteRequestError || error instanceof SsoRequestError) && error.status !== undefined ? { http_status: error.status } : {}) });
152
195
  }
153
196
  if (error instanceof OutputContractError) {
154
- if (insmind)
155
- return failure("INTERNAL_ERROR", "CLI result validation failed.", 1);
156
- return failure("INTERNAL_ERROR", "CLI 内部结果校验失败。", 1);
197
+ return failure("INTERNAL_ERROR", text("CLI 内部结果校验失败,不能确认可交付结果。", "CLI result validation failed; a deliverable result could not be confirmed."), 1, [text("保留诊断 ID;创作或写入可能已发生,先查询原任务或对象。", "Keep the diagnostic ID; creation or changes may have occurred. Query the original task or object first.")], { phase: "output_validation", issues: error.issues });
157
198
  }
199
+ if (error instanceof LocalFileError)
200
+ 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) });
201
+ if (error instanceof EditorBridgeUnavailableError)
202
+ 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" });
158
203
  if (error instanceof EditorBridgeError
159
204
  || error instanceof EditorSessionNotFoundError
160
205
  || error instanceof EditorNotReadyError) {
@@ -163,9 +208,9 @@ export function mapCliError(error, options) {
163
208
  return failure(error.code, `No Editor session is available. Run ${command} editor connect [target] again.`, 1);
164
209
  if (error instanceof EditorNotReadyError)
165
210
  return failure(error.code, "The Editor page did not become ready in time.", 1);
166
- return failure(error.code, "The Editor operation failed.", 1);
211
+ 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."]);
167
212
  }
168
- return failure(error.code, error.message, 1);
213
+ return failure(error.code, redactSensitiveText(error.message).slice(0, 1024), 1, ["写入失败时先检查原作品,不直接重复 apply 或 save;按 editor --help 中的对应错误指引处理。"]);
169
214
  }
170
215
  return failure("INTERNAL_ERROR", insmind ? "The CLI encountered an internal error." : "CLI 发生内部错误。", 1);
171
216
  }
@@ -175,19 +220,20 @@ function isInsufficientCreditsError(error) {
175
220
  || error instanceof ToolTaskFailedError) && error.remoteCode === INSUFFICIENT_CREDITS_REMOTE_CODE;
176
221
  }
177
222
  export function classifyTelemetryError(error, options = {}) {
178
- const outcome = mapCliError(error, { ...options, aborted: options.aborted === true || (error instanceof Error && (error.name === "AbortError" || error.message === "SIGINT" || error.message === "SIGTERM")) });
179
- const remoteError = error instanceof RemoteRequestError
180
- || error instanceof RemoteProtocolError
181
- || error instanceof ToolTaskFailedError
182
- || error instanceof SsoRequestError
183
- || error instanceof OrganizationBindFailedError
184
- ? error
185
- : undefined;
223
+ const outcome = mapCliError(error, { ...options, aborted: options.aborted === true });
224
+ let remoteError;
225
+ for (let cause = error, depth = 0; cause instanceof Error && depth < 10; cause = cause.cause, depth++) {
226
+ if (cause instanceof RemoteRequestError || cause instanceof RemoteProtocolError || cause instanceof ToolTaskFailedError
227
+ || cause instanceof SsoRequestError || cause instanceof OrganizationBindFailedError) {
228
+ remoteError = cause;
229
+ break;
230
+ }
231
+ }
186
232
  return {
187
233
  outcome: outcome.kind === "interrupted" ? "interrupted" : "failure",
188
234
  ...(outcome.kind === "failure" ? { errorCode: outcome.failure.code } : {}),
189
- ...((error instanceof RemoteRequestError || error instanceof SsoRequestError) && error.status !== undefined
190
- ? { httpStatus: error.status }
235
+ ...((remoteError instanceof RemoteRequestError || remoteError instanceof SsoRequestError) && remoteError.status !== undefined
236
+ ? { httpStatus: remoteError.status }
191
237
  : {}),
192
238
  ...(remoteError?.remoteCode === undefined
193
239
  ? {}
@@ -197,14 +243,21 @@ export function classifyTelemetryError(error, options = {}) {
197
243
  : { remoteErrorBody: remoteError.remoteBody })
198
244
  };
199
245
  }
200
- function failure(code, message, exitCode, nextSteps) {
246
+ function failure(code, message, exitCode, nextSteps, details) {
201
247
  return {
202
248
  kind: "failure",
203
249
  failure: {
204
250
  code,
205
251
  message,
206
- ...(nextSteps ? { details: { next_steps: nextSteps } } : {})
252
+ ...(nextSteps || details ? { details: { ...details, ...(nextSteps ? { next_steps: nextSteps } : {}) } } : {})
207
253
  },
208
254
  exitCode
209
255
  };
210
256
  }
257
+ function systemErrorCode(error) {
258
+ for (let depth = 0; error instanceof Error && depth < 10; depth++, error = error.cause) {
259
+ if ("code" in error && typeof error.code === "string" && /^E[A-Z0-9_]{1,40}$/u.test(error.code))
260
+ return error.code;
261
+ }
262
+ return undefined;
263
+ }
@@ -1,4 +1,4 @@
1
- import { bindAction } from "./action-binding.js";
1
+ import { jsonOutput, bindAction } from "./action-binding.js";
2
2
  import { CliUsageError } from "./errors.js";
3
3
  import { productText as text } from "../product/text.js";
4
4
  export function registerModelCommands(program, runtime) {
@@ -9,8 +9,11 @@ export function registerModelCommands(program, runtime) {
9
9
  .description(text(runtime.product, "列出图片/视频生成模型(不含独立风格)", "List image/video generation models (excluding standalone styles)"))
10
10
  .option("--tool <tool>", text(runtime.product, "按工具筛选", "filter by tool"))
11
11
  .allowExcessArguments(false);
12
+ jsonOutput(list);
12
13
  bindAction(list, "organization", async (context, signal) => {
13
14
  const selectedTool = list.opts().tool;
15
+ if (selectedTool !== undefined)
16
+ runtime.telemetry.annotate({ tool_name: selectedTool });
14
17
  const input = selectedTool === undefined ? {} : { tool: selectedTool };
15
18
  await runtime.telemetry.stage("input", async () => {
16
19
  runtime.validators.modelListInput(input);
@@ -23,8 +26,6 @@ export function registerModelCommands(program, runtime) {
23
26
  },
24
27
  signal
25
28
  });
26
- if (selectedTool !== undefined)
27
- runtime.telemetry.annotate({ tool_name: selectedTool });
28
29
  await runtime.telemetry.stage("output", async () => {
29
30
  runtime.validators.modelListOutput(result);
30
31
  runtime.io.writeOut(`${JSON.stringify(result)}\n`);
@@ -42,10 +43,12 @@ export function registerModelCommands(program, runtime) {
42
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
44
  ""
44
45
  ].join("\n"));
46
+ jsonOutput(get);
45
47
  bindAction(get, "organization", async (context, signal) => {
46
48
  const modelName = get.processedArgs[0];
47
49
  if (typeof modelName !== "string" || modelName.trim() === "")
48
50
  throw new CliUsageError();
51
+ runtime.telemetry.annotate({ model_id: modelName });
49
52
  const input = { model: modelName };
50
53
  await runtime.telemetry.stage("input", async () => {
51
54
  runtime.validators.modelGetInput(input);
@@ -59,7 +62,6 @@ export function registerModelCommands(program, runtime) {
59
62
  access,
60
63
  signal
61
64
  });
62
- runtime.telemetry.annotate({ model_id: modelName });
63
65
  await runtime.telemetry.stage("output", async () => {
64
66
  runtime.validators.modelGetOutput(result);
65
67
  runtime.io.writeOut(`${JSON.stringify(result)}\n`);
@@ -26,14 +26,11 @@ export function createPresenter(options) {
26
26
  options.writeError(`${insmind ? "Warning" : "警告"}: ${message}\n`);
27
27
  },
28
28
  error(outcome, presentation) {
29
- if (outcome.kind === "interrupted") {
30
- options.writeError(insmind ? "Cancelled.\n" : "已取消。\n");
31
- return;
32
- }
29
+ const failure = outcome.failure ?? { code: "INTERRUPTED", message: insmind ? "Local waiting stopped." : "已停止本地等待。" };
33
30
  if (presentation.json) {
34
31
  options.writeError(`${JSON.stringify({
35
32
  error: {
36
- ...outcome.failure,
33
+ ...failure,
37
34
  ...(presentation.traceId
38
35
  ? { trace_id: presentation.traceId }
39
36
  : {})
@@ -41,8 +38,13 @@ export function createPresenter(options) {
41
38
  })}\n`);
42
39
  return;
43
40
  }
44
- options.writeError(`${outcome.failure.code}: ${outcome.failure.message}\n`);
45
- const nextSteps = nextStepsFrom(outcome.failure.details);
41
+ options.writeError(`${failure.code}: ${failure.message}\n`);
42
+ if (failure.details && typeof failure.details === "object") {
43
+ const { next_steps: _, ...details } = failure.details;
44
+ if (Object.keys(details).length)
45
+ options.writeError(`${insmind ? "Details" : "详情"}: ${JSON.stringify(details)}\n`);
46
+ }
47
+ const nextSteps = nextStepsFrom(failure.details);
46
48
  if (nextSteps.length > 0) {
47
49
  options.writeError(`${insmind ? "Next steps" : "下一步"}: ${nextSteps.join(insmind ? ", " : ",")}\n`);
48
50
  }
@@ -90,15 +92,16 @@ export const orgCurrentView = (value) => {
90
92
  ? `当前组织: ${result.organization.name} (${result.organization.id})`
91
93
  : lines("尚未选择组织。", nextStepsLine(result.next_steps));
92
94
  };
93
- export const repositoryListView = (value) => {
95
+ export const repositoryListView = (value, product) => {
96
+ const english = product?.id === "insmind";
94
97
  const result = value;
95
98
  if (result.repositories.length === 0)
96
- return "没有可用资源库。";
99
+ return english ? "No repositories." : "没有可用资源库。";
97
100
  return result.repositories.map((repository) => {
98
101
  const permission = repository.permission_code === undefined
99
102
  ? ""
100
103
  : ` · ${repository.permission_code}`;
101
- const defaultMarker = repository.is_default ? " [默认]" : "";
104
+ const defaultMarker = repository.is_default ? (english ? " [default]" : " [默认]") : "";
102
105
  return `${repository.name} (${repository.repository_id}) · ${repository.type}${permission}${defaultMarker}`;
103
106
  }).join("\n");
104
107
  };
@@ -1,6 +1,6 @@
1
1
  import { productText } from "../product/text.js";
2
2
  import { validTaskId } from "../features/task/store.js";
3
- import { bindPreparedAction } from "./action-binding.js";
3
+ import { jsonOutput, bindPreparedAction } from "./action-binding.js";
4
4
  import { CliUsageError } from "./errors.js";
5
5
  export function registerTaskCommands(program, runtime) {
6
6
  const tasks = runtime.tasks;
@@ -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
+ jsonOutput(list);
13
14
  bindPreparedAction(list, "local-organization", async () => {
14
15
  const options = list.opts();
15
16
  const limit = Number(options.limit);
@@ -20,8 +21,10 @@ export function registerTaskCommands(program, runtime) {
20
21
  ...(options.operation === undefined ? {} : { operation: options.operation }) } };
21
22
  }, async (context, input) => {
22
23
  const result = await tasks.list({ ...input, state: context.state });
23
- runtime.validators.taskListResult(result);
24
- runtime.io.writeOut(`${JSON.stringify(result)}\n`);
24
+ await runtime.telemetry.stage("output", async () => {
25
+ runtime.validators.taskListResult(result);
26
+ runtime.io.writeOut(`${JSON.stringify(result)}\n`);
27
+ });
25
28
  }, { operation: "task.list" });
26
29
  const get = task.command("get").description(text("查询原执行状态并取回已有结果,不重新生成", "Query a task and retrieve existing results without generating again"))
27
30
  .argument("<id>", text("task list 或原命令提示的任务 ID", "Task ID from task list or the original command"))
@@ -31,11 +34,14 @@ export function registerTaskCommands(program, runtime) {
31
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."),
32
35
  text("unknown 表示无法确认本次执行终态;partialResult 仅是已取得的消息片段,不代表完成。", "unknown means completion cannot be confirmed; partialResult is a message snapshot, not a complete result."),
33
36
  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
+ 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
+ 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."),
34
39
  text("查询不重新提交创作;同一执行记录多次读取的 usage 是同一份费用。", "Queries never resubmit a creation. Reading the same task again does not add another usage charge."),
35
40
  text(`记录仅来自本机执行;保留至用户删除 ~/${runtime.product.stateDirectory}/tasks。切换身份或组织后只显示对应记录。`, `Tasks are local to this machine and identity context; they remain until you remove ~/${runtime.product.stateDirectory}/tasks.`),
36
41
  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."),
37
42
  ""
38
43
  ].join("\n"));
44
+ jsonOutput(get);
39
45
  bindPreparedAction(get, "local-organization", async () => {
40
46
  const id = get.processedArgs[0];
41
47
  if (typeof id !== "string" || !validTaskId(id))
@@ -43,7 +49,9 @@ export function registerTaskCommands(program, runtime) {
43
49
  return { handled: false, input: id.toLowerCase() };
44
50
  }, async (context, id, signal) => {
45
51
  const result = await tasks.get({ id, state: context.state, signal });
46
- runtime.validators.taskResult(result);
47
- runtime.io.writeOut(`${JSON.stringify(result)}\n`);
52
+ await runtime.telemetry.stage("output", async () => {
53
+ runtime.validators.taskResult(result);
54
+ runtime.io.writeOut(`${JSON.stringify(result)}\n`);
55
+ });
48
56
  }, { operation: "task.get" });
49
57
  }
@@ -1,4 +1,4 @@
1
- import { bindAction, bindPreparedAction } from "./action-binding.js";
1
+ import { jsonOutput, bindAction, bindPreparedAction } from "./action-binding.js";
2
2
  import { CliUsageError } from "./errors.js";
3
3
  import { productText as text } from "../product/text.js";
4
4
  export function registerToolCommands(program, runtime) {
@@ -8,6 +8,7 @@ export function registerToolCommands(program, runtime) {
8
8
  const list = tool.command("list")
9
9
  .description(text(runtime.product, "列出可用工具", "List available tools"))
10
10
  .allowExcessArguments(false);
11
+ jsonOutput(list);
11
12
  bindAction(list, "organization", async (context, signal) => {
12
13
  const result = await runtime.tool.listTools({
13
14
  access: {
@@ -30,13 +31,17 @@ export function registerToolCommands(program, runtime) {
30
31
  .allowExcessArguments(false);
31
32
  call.addHelpText("after", [
32
33
  "",
34
+ 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."),
35
+ 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."),
33
36
  text(runtime.product, "--async 在服务端受理后输出包含 taskId 和 state 的 JSON;退出码 0 仅表示受理。", "--async returns JSON with taskId and state after acceptance; exit code 0 means accepted only."),
37
+ text(runtime.product, "异步任务由本机后台进程继续等待结果;进程终止或关机可能使状态变为 unknown。", "Async work continues in a local background process; termination or shutdown may leave its state unknown."),
34
38
  text(runtime.product, "用 task get <taskId> 查询原任务;completed 时 result 为完整结果,running/unknown 或查询超时不应重新提交。", "Query the same taskId with task get; completed includes result. Do not resubmit on running, unknown, or a query timeout."),
35
39
  text(runtime.product, "默认等待原 Tool 结果;任务 ID 写入 stderr,stdout 保持原 JSON。", "By default, the command waits for the original Tool result; stderr shows the Task ID and stdout keeps the result JSON."),
36
40
  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.`),
37
41
  text(runtime.product, "查询返回同一份 usage;Tool usage.cost 为当次目录预估价格。", "Queries return the same usage; Tool usage.cost is the catalog price estimate for that invocation."),
38
42
  ""
39
43
  ].join("\n"));
44
+ jsonOutput(call);
40
45
  bindPreparedAction(call, "organization", async (signal) => {
41
46
  signal.throwIfAborted();
42
47
  const name = call.processedArgs[0];
@@ -76,10 +81,11 @@ export function registerToolCommands(program, runtime) {
76
81
  label: `${prepared.input.name}: ${String(prepared.input.arguments.prompt ?? prepared.input.arguments.model ?? "")}`
77
82
  };
78
83
  if (prepared.async) {
79
- const result = await runtime.tasks.submit({ ...task,
80
- run: observe => runtime.tool.submit({ input: prepared.input, access, signal, observe }) });
81
- runtime.validators.taskResult(result);
82
- runtime.io.writeOut(`${JSON.stringify(result)}\n`);
84
+ const result = await runtime.startBackgroundTask({ ...task, input: prepared.input }, signal);
85
+ await runtime.telemetry.stage("output", async () => {
86
+ runtime.validators.taskResult(result);
87
+ runtime.io.writeOut(`${JSON.stringify(result)}\n`);
88
+ });
83
89
  return;
84
90
  }
85
91
  const run = async (observe) => {
@@ -2,8 +2,12 @@ import { findModel, ToolInputError } from "../tool/catalog.js";
2
2
  import { modelControlArgumentsAreValid } from "../tool/dynamic-schema.js";
3
3
  import { parseSafeRemoteAssetUrl, UrlSafetyError } from "../../platform/url-safety.js";
4
4
  export class AgentInputError extends Error {
5
- constructor() {
6
- super("Agent 输入不可用。");
5
+ reason;
6
+ field;
7
+ constructor(reason = "invalid_agent_input", field, cause) {
8
+ super(`Agent 输入不可用:${reason}${field ? ` (${field})` : ""}`, { cause });
9
+ this.reason = reason;
10
+ this.field = field;
7
11
  this.name = "AgentInputError";
8
12
  }
9
13
  }
@@ -49,6 +53,8 @@ export function createAgentUseCases(dependencies) {
49
53
  dependencies.telemetry.annotate({ model_id: generation.model });
50
54
  const catalog = await dependencies.telemetry.stage("catalog", () => (dependencies.catalog.load({ access, signal })));
51
55
  signal.throwIfAborted();
56
+ if (catalog.warnings.length)
57
+ dependencies.telemetry.annotate({ warning_codes: ["MODEL_CATALOG_INCOMPLETE"], invalid_model_count: catalog.invalidModelCount });
52
58
  for (const warning of catalog.warnings)
53
59
  dependencies.warn(warning);
54
60
  await dependencies.telemetry.stage("input", async () => {
@@ -58,11 +64,11 @@ export function createAgentUseCases(dependencies) {
58
64
  }
59
65
  catch (error) {
60
66
  if (error instanceof ToolInputError)
61
- throw new AgentInputError();
67
+ throw new AgentInputError(error.reason, "/generation/model", error);
62
68
  throw error;
63
69
  }
64
70
  if (!modelControlArgumentsAreValid(model, generation.arguments ?? {}))
65
- throw new AgentInputError();
71
+ throw new AgentInputError("model_parameters", "/generation/arguments");
66
72
  });
67
73
  }
68
74
  const prepare = async () => {
@@ -90,7 +96,7 @@ export function createAgentUseCases(dependencies) {
90
96
  }
91
97
  catch (error) {
92
98
  if (error instanceof UrlSafetyError)
93
- throw new AgentInputError();
99
+ throw new AgentInputError("invalid_asset_url", `/message/parts/${input.message.parts.indexOf(part)}/url`, error);
94
100
  throw error;
95
101
  }
96
102
  const filename = part.filename ?? pathnameFilename(url);
@@ -1,3 +1,4 @@
1
+ import { requireUserIdentity } from "./state.js";
1
2
  import { OrganizationInvalidError } from "../org/use-cases.js";
2
3
  export class AuthRequiredError extends Error {
3
4
  constructor() {
@@ -20,6 +21,7 @@ export function createAccessPolicies(dependencies) {
20
21
  signal.throwIfAborted();
21
22
  if (!state)
22
23
  throw new AuthRequiredError();
24
+ requireUserIdentity(state);
23
25
  if (Date.parse(state.credential.expiresAt) <= dependencies.now().getTime()) {
24
26
  throw new AuthExpiredError();
25
27
  }
@@ -1,6 +1,6 @@
1
1
  import { homedir } from "node:os";
2
2
  import { join } from "node:path";
3
- import { createLocalJsonFile, LocalFileError } from "../../platform/local-json-file.js";
3
+ import { createLocalJsonFile } from "../../platform/local-json-file.js";
4
4
  import { AuthStateInvalidError, parseStoredAuthState } from "./state.js";
5
5
  export function createLocalCredentialStore(options = {}) {
6
6
  const file = options.file ?? createLocalJsonFile({
@@ -57,6 +57,6 @@ function serialize(state) {
57
57
  }
58
58
  function invalidState(cause) {
59
59
  return new AuthStateInvalidError({
60
- cause: cause instanceof LocalFileError ? cause.cause : cause
60
+ cause, reason: "local_io"
61
61
  });
62
62
  }
@@ -1,3 +1,4 @@
1
+ import { isInterruption } from "../../platform/interruption.js";
1
2
  import { remoteErrorEvidence } from "../../platform/remote-error-evidence.js";
2
3
  import { normalizeScope } from "./state.js";
3
4
  import { signBindOrganization } from "../../platform/signature.js";
@@ -82,7 +83,7 @@ export function createSsoService(options) {
82
83
  return response;
83
84
  }
84
85
  catch (error) {
85
- if (signal.aborted)
86
+ if (isInterruption(error, signal))
86
87
  throw signal.reason;
87
88
  throw new SsoRequestError(undefined, remoteErrorEvidence({ request: requestInfo, network: networkFailure(error) }), error);
88
89
  }
@@ -137,8 +138,8 @@ export function createSsoService(options) {
137
138
  if (isRecord(body.user)) {
138
139
  const id = identifier(body.user.id);
139
140
  const name = nonEmptyString(body.user.name);
140
- if (id && name)
141
- result.account = { id, name };
141
+ if (id)
142
+ result.account = { id, name: name ?? id };
142
143
  }
143
144
  const organizationId = identifier(body.orgId ?? body.org_id ?? body.orgID);
144
145
  if (organizationId)
@@ -177,7 +178,7 @@ export function createSsoService(options) {
177
178
  if (!response.ok)
178
179
  throw await responseError(response);
179
180
  const text = await response.text().catch(async (error) => {
180
- if (signal.aborted)
181
+ if (isInterruption(error, signal))
181
182
  throw signal.reason;
182
183
  throw await responseError(response, error);
183
184
  });