@insmind/cli 1.7.0 → 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.
Files changed (31) hide show
  1. package/dist/src/bootstrap/create-cli.js +3 -1
  2. package/dist/src/bootstrap/create-runtime.js +24 -12
  3. package/dist/src/bootstrap/run-task-worker.js +2 -2
  4. package/dist/src/bootstrap/validators.js +1 -1
  5. package/dist/src/cli/action-binding.js +3 -0
  6. package/dist/src/cli/errors.js +77 -24
  7. package/dist/src/cli/model-commands.js +1 -1
  8. package/dist/src/cli/observed-errors.js +118 -0
  9. package/dist/src/cli/task-commands.js +1 -1
  10. package/dist/src/cli/tool-commands.js +1 -1
  11. package/dist/src/features/auth/sso-service.js +13 -4
  12. package/dist/src/features/dam/dam-api-adapter.js +1 -0
  13. package/dist/src/features/dam/file-downloader.js +23 -2
  14. package/dist/src/features/task/creation-refusal.js +14 -10
  15. package/dist/src/features/task/store.js +10 -4
  16. package/dist/src/features/task/use-cases.js +45 -16
  17. package/dist/src/features/tool/dynamic-schema.js +4 -1
  18. package/dist/src/features/tool/tool-api-adapter.js +42 -33
  19. package/dist/src/features/update/update-service.js +4 -2
  20. package/dist/src/platform/file-lock.js +12 -0
  21. package/dist/src/platform/local-json-file.js +19 -5
  22. package/dist/src/platform/remote-error-evidence.js +13 -1
  23. package/dist/src/platform/remote-protocol.js +1 -1
  24. package/dist/src/platform/safe-upload-file.js +18 -10
  25. package/dist/src/platform/schema-issues.js +47 -2
  26. package/dist/src/platform/signed-http-transport.js +1 -1
  27. package/dist/src/platform/text-output.js +17 -4
  28. package/dist/src/telemetry/failure-summary.js +18 -0
  29. package/package.json +4 -4
  30. package/skills/insmind-cli/references/errors.md +3 -1
  31. package/skills/insmind-cli/references/tool.md +1 -1
@@ -2,14 +2,18 @@ import { AgentAuditRejectedError } from "../agent/creative-protocol.js";
2
2
  import { ToolTaskFailedError } from "../tool/tool-api-adapter.js";
3
3
  import { RemoteRequestError } from "../../platform/signed-http-transport.js";
4
4
  import { RemoteProtocolError } from "../../platform/remote-protocol.js";
5
- // Explicit CRC_SPAM refusals. Review timeouts and unknown request errors do not
6
- // prove that a dispatched creation stopped, even when they use HTTP 400.
7
- const CONTENT_REVIEW_CODES = new Set([
8
- "12020751", "12020752", "12020753", "12020754", "12020755", "12020756",
9
- "12020757", "12020758", "12020759", "12020760", "12020761"
10
- ]);
11
- export function isContentReviewRejection(error) {
12
- return error instanceof AgentAuditRejectedError
13
- || ((error instanceof RemoteRequestError || error instanceof RemoteProtocolError || error instanceof ToolTaskFailedError)
14
- && error.remoteCode !== undefined && CONTENT_REVIEW_CODES.has(error.remoteCode));
5
+ // Scope numeric codes to the product/entry where they have a confirmed meaning.
6
+ const CONTENT_REVIEW_CODES = new Set(["12020751", "12020752", "12020757", "12020758", "12020760", "12020790"]);
7
+ export function isContentReviewRejection(error, context = {}) {
8
+ if (error instanceof AgentAuditRejectedError)
9
+ return true;
10
+ if (!(error instanceof RemoteRequestError || error instanceof RemoteProtocolError || error instanceof ToolTaskFailedError))
11
+ return false;
12
+ if (error.diagnosticReason === "AGENT_INPUT_AUDIT_REJECTED")
13
+ return true;
14
+ const toolOrQuery = context.operation === "tool.call" || context.operation === "task.get";
15
+ if (context.product === "insmind")
16
+ return toolOrQuery && error.remoteCode === "12020760";
17
+ return toolOrQuery && CONTENT_REVIEW_CODES.has(error.remoteCode ?? "")
18
+ || context.operation === "agent.send" && error.remoteCode === "-1006";
15
19
  }
@@ -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) {
@@ -70,6 +74,8 @@ export function createTaskStore(options) {
70
74
  }
71
75
  if (previous.task.state === "completed" || (previous.task.state === "failed" && record.task.state !== "completed"))
72
76
  record.task = previous.task;
77
+ if (previous.failureCorrection)
78
+ record.failureCorrection = previous.failureCorrection;
73
79
  if (previous.analytics)
74
80
  record.analytics = { ...record.analytics, ...previous.analytics };
75
81
  if (previous.telemetry)
@@ -104,7 +110,7 @@ export function createTaskStore(options) {
104
110
  catch (error) {
105
111
  if (error instanceof Error && "code" in error && error.code === "ENOENT")
106
112
  return [];
107
- throw new LocalFileError(error);
113
+ throw new LocalFileError(error, undefined, "io", { operation: "list", step: "directory_read" });
108
114
  }
109
115
  const records = [];
110
116
  for (const name of names) {
@@ -120,7 +120,7 @@ export function createTaskUseCases(dependencies) {
120
120
  const { result: _result, partialResult: _partial, ...task } = record.task;
121
121
  if (!record.progress.detached && task.state === "running"
122
122
  && dependencies.now().getTime() - Date.parse(task.updatedAt) >= LEASE_MS) {
123
- return { ...task, state: "unknown", note: text("原 CLI 未继续更新记录;使用 task get 查询,不能据此重新生成。", "The original CLI stopped updating this task. Use task get to check; do not submit again.") };
123
+ return { ...task, state: "unknown", note: text("尚未取得任务结果。", "The task result has not been received.") };
124
124
  }
125
125
  return task;
126
126
  }
@@ -258,26 +258,32 @@ export function createTaskUseCases(dependencies) {
258
258
  }
259
259
  catch (error) {
260
260
  clearInterval(timer);
261
+ const diagnostic = telemetry?.taskFailure(error).diagnostic_reason
262
+ ?? (error instanceof RemoteRequestError ? error.diagnosticReason : undefined);
263
+ const observationOnly = diagnostic === "LOCAL_WAIT_INTERRUPTED" || diagnostic === "TASK_QUERY_FAILED" || diagnostic === "TASK_CANCELED";
261
264
  if (record.task.state !== "completed") {
262
265
  const mayBeRunning = dispatched || record.progress.submissionStarted;
263
- const auditRejected = isContentReviewRejection(error);
264
- const creditsRejected = (error instanceof RemoteRequestError || error instanceof RemoteProtocolError)
266
+ const auditRejected = isContentReviewRejection(error, { product: commandName === "insmind-cli" ? "insmind" : "gaoding", operation: input.operation });
267
+ const creditsRejected = commandName !== "insmind-cli" && input.operation === "tool.call"
268
+ && (error instanceof RemoteRequestError || error instanceof RemoteProtocolError)
265
269
  && error.remoteCode === "12020770";
266
270
  const confirmedFailure = error instanceof ToolTaskFailedError || auditRejected || creditsRejected;
267
- record.task.state = confirmedFailure || !mayBeRunning ? "failed" : "unknown";
268
- record.task.note = auditRejected
269
- ? text("内容未通过审核,本次创作已拒绝;具体错误见原命令。", "Content review rejected this creation. See the original command for the error.")
270
- : confirmedFailure
271
- ? text("服务已明确拒绝本次创作或返回任务失败;具体错误见原命令。", "The service explicitly rejected this creation or reported task failure. See the original command for the error.")
272
- : mayBeRunning
273
- ? text("CLI 未取得完整回执或结果;远端可能仍在执行。查询原任务,不自动重新生成。", "The CLI did not receive a complete receipt or result; the service may still be running. Query this task instead of submitting again.")
274
- : text("CLI 在提交创作前结束;具体错误见原命令。", "The CLI stopped before submitting the creation. See the original command for the error.");
271
+ record.task.state = observationOnly ? "unknown" : confirmedFailure || !mayBeRunning ? "failed" : "unknown";
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.");
275
281
  }
276
282
  const detail = dependencies.failureNote?.(error);
277
- if (detail)
278
- record.task.note = [record.task.note, redactSensitiveText(detail)].filter(Boolean).join(" ");
283
+ if (detail && diagnostic !== "LOCAL_WAIT_INTERRUPTED")
284
+ record.task.note = redactSensitiveText(detail);
279
285
  telemetry?.annotate({ result_state: record.task.state });
280
- if (dispatched && record.task.state !== "completed")
286
+ if (dispatched && !observationOnly && record.task.state !== "completed")
281
287
  await fact(scope, record, "failed", dependencies.now().getTime(), error);
282
288
  await stage("task.persist", save).catch(() => undefined);
283
289
  throw error;
@@ -308,9 +314,19 @@ export function createTaskUseCases(dependencies) {
308
314
  signal.throwIfAborted();
309
315
  const scope = taskScope(state);
310
316
  telemetry?.annotate({ cli_task_id: id });
311
- const record = await stage("task.read", () => dependencies.store.read(scope, id));
317
+ let record = await stage("task.read", () => dependencies.store.read(scope, id));
312
318
  if (!record)
313
319
  throw new TaskNotFoundError(text(`当前身份中没有该任务。请执行 ${commandName} task list 查找。`, `No task was found in the current identity context. Use ${commandName} task list to find it.`));
320
+ if (recoverableFalseFailure(record)) {
321
+ record = await stage("task.repair", () => dependencies.store.update(scope, id, stored => {
322
+ const reason = recoverableFalseFailure(stored);
323
+ if (!reason)
324
+ return;
325
+ stored.failureCorrection = { reason, correctedAt: dependencies.now().toISOString(),
326
+ previousRevision: stored.telemetry?.states?.at(-1)?.task_revision };
327
+ stored.task = { ...stored.task, state: "unknown", note: text("尚未取得任务结果。", "The task result has not been received.") };
328
+ }));
329
+ }
314
330
  telemetry?.annotate({ cli_task_id: id, result_state: record.task.state });
315
331
  if (record.task.state === "completed" && record.task.result) {
316
332
  const result = { ...record.task, result: await stage("task.authorize", () => dependencies.recovery.authorize(record.task.result, state, signal)) };
@@ -324,7 +340,7 @@ export function createTaskUseCases(dependencies) {
324
340
  const { note: _note, ...metadata } = task;
325
341
  const result = { ...metadata, ...recovered };
326
342
  if (result.state === "unknown" && task.note) {
327
- result.note = [task.note, recovered.note].filter(Boolean).join(" ");
343
+ result.note = [...new Set([task.note, recovered.note].filter(Boolean))].join(" ");
328
344
  }
329
345
  if (result.state === "completed" && result.result) {
330
346
  await stage("task.validate", async () => { dependencies.validateResult?.(result.result); });
@@ -359,3 +375,16 @@ export function createTaskUseCases(dependencies) {
359
375
  }
360
376
  };
361
377
  }
378
+ function recoverableFalseFailure(record) {
379
+ if (record.task.state !== "failed" || record.task.result)
380
+ return;
381
+ const terminal = record.telemetry?.states?.findLast(event => ["failed", "success", "completed"].includes(event.result_state));
382
+ if (terminal?.result_state !== "failed")
383
+ return;
384
+ if (terminal.diagnostic_reason === "LOCAL_WAIT_INTERRUPTED")
385
+ return "LOCAL_WAIT_INTERRUPTED";
386
+ if (record.task.operation === "tool.call" && (terminal.diagnostic_reason === "TASK_QUERY_FAILED"
387
+ || terminal.failure_stage === "task.query" && terminal.remote_error_code === "12020704"))
388
+ return "TASK_QUERY_FAILED";
389
+ return undefined;
390
+ }
@@ -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) {
@@ -129,45 +129,49 @@ function normalizeContent(value) {
129
129
  export class ToolTaskFailedError extends Error {
130
130
  remoteCode;
131
131
  remoteBody;
132
+ diagnosticReason;
132
133
  constructor(evidence = {}) {
133
134
  super("稿定工具任务执行失败。");
134
135
  this.name = "ToolTaskFailedError";
135
136
  this.remoteCode = evidence.remoteCode;
136
137
  this.remoteBody = evidence.remoteBody;
138
+ this.diagnosticReason = evidence.diagnosticReason;
137
139
  }
138
140
  }
141
+ export class ToolTaskCanceledError extends Error {
142
+ diagnosticReason = "TASK_CANCELED";
143
+ constructor() { super("用户已取消生成任务。"); this.name = "ToolTaskCanceledError"; }
144
+ }
139
145
  export async function queryToolResult(transport, request) {
140
- return pollResult(await safePost(transport, {
141
- credential: request.credential,
142
- ...(request.organizationId === undefined ? {} : { organizationId: request.organizationId }),
143
- signal: request.signal,
144
- path: "/gdesign/tool/v1/dify/process/batch",
145
- body: { task_ids: [request.taskId] }
146
- }), request.taskId);
146
+ try {
147
+ return pollResult(await safePost(transport, {
148
+ credential: request.credential,
149
+ ...(request.organizationId === undefined ? {} : { organizationId: request.organizationId }),
150
+ signal: request.signal,
151
+ path: "/gdesign/tool/v1/dify/process/batch",
152
+ body: { task_ids: [request.taskId] }
153
+ }), request.taskId, request.onDifyTaskId);
154
+ }
155
+ catch (error) {
156
+ if (isInterruption(error, request.signal) || error instanceof ToolTaskCanceledError)
157
+ throw error;
158
+ const evidence = error instanceof RemoteRequestError || error instanceof RemoteProtocolError
159
+ ? { ...(error.remoteCode === undefined ? {} : { remoteCode: error.remoteCode }),
160
+ ...(error.remoteBody === undefined ? {} : { remoteBody: error.remoteBody }) } : {};
161
+ if (error instanceof RemoteProtocolError)
162
+ throw new RemoteProtocolError(evidence, error, "TASK_QUERY_FAILED");
163
+ throw new RemoteRequestError(error instanceof RemoteRequestError ? error.status : undefined, error instanceof RemoteRequestError && error.transient, evidence, error, "TASK_QUERY_FAILED");
164
+ }
147
165
  }
148
166
  function failedPoll(error, difyTaskId) {
167
+ if (error instanceof RemoteProtocolError)
168
+ throw error;
149
169
  return {
150
170
  state: "failed",
151
171
  error,
152
172
  ...(difyTaskId === undefined ? {} : { difyTaskId })
153
173
  };
154
174
  }
155
- function optionalInnerDifyTaskId(value) {
156
- if (typeof value !== "string" || value.trim() === "")
157
- return undefined;
158
- try {
159
- const parsed = JSON.parse(value);
160
- if (!isRecord(parsed))
161
- return undefined;
162
- const difyTaskId = parsed.dify_task_id;
163
- return typeof difyTaskId === "string" && difyTaskId.trim() !== ""
164
- ? difyTaskId
165
- : undefined;
166
- }
167
- catch {
168
- return undefined;
169
- }
170
- }
171
175
  function isJsonRpcError(value) {
172
176
  if (value.jsonrpc !== "2.0"
173
177
  || Object.prototype.hasOwnProperty.call(value, "result")
@@ -185,7 +189,7 @@ function isJsonRpcError(value) {
185
189
  && typeof value.error.message === "string"
186
190
  && value.error.message.trim() !== "";
187
191
  }
188
- function pollResult(value, taskId) {
192
+ function pollResult(value, taskId, onDifyTaskId) {
189
193
  if (!Array.isArray(value))
190
194
  return protocolFailure(value);
191
195
  const item = value.find((candidate) => isRecord(candidate) && candidate.task_id === taskId);
@@ -195,7 +199,8 @@ function pollResult(value, taskId) {
195
199
  return protocolFailure(item);
196
200
  }
197
201
  if (item.code !== "200") {
198
- return failedPoll(new ToolTaskFailedError(remoteErrorEvidence(item)), optionalInnerDifyTaskId(item.result));
202
+ // This envelope describes the query request, not the original generation.
203
+ throw new RemoteRequestError(undefined, false, remoteErrorEvidence(item), undefined, "TASK_QUERY_FAILED");
199
204
  }
200
205
  if (typeof item.result !== "string" || item.result.trim() === "") {
201
206
  return protocolFailure(item);
@@ -217,6 +222,8 @@ function pollResult(value, taskId) {
217
222
  && (typeof difyTaskId !== "string" || difyTaskId.trim() === "")) {
218
223
  return protocolFailure(inner);
219
224
  }
225
+ if (typeof difyTaskId === "string")
226
+ onDifyTaskId?.(difyTaskId);
220
227
  if (Object.prototype.hasOwnProperty.call(inner, "error")) {
221
228
  return isJsonRpcError(inner)
222
229
  ? failedPoll(new ToolTaskFailedError(remoteErrorEvidence(inner)), difyTaskId)
@@ -241,6 +248,12 @@ function pollResult(value, taskId) {
241
248
  if (!Array.isArray(content)) {
242
249
  return failedPoll(new RemoteProtocolError(remoteErrorEvidence(inner)), difyTaskId);
243
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();
244
257
  try {
245
258
  return {
246
259
  state: "complete",
@@ -339,14 +352,11 @@ export function createToolApiAdapter(dependencies) {
339
352
  let transientFailures = 0;
340
353
  while (true) {
341
354
  signal.throwIfAborted();
342
- let response;
355
+ let poll;
343
356
  try {
344
- response = await safePost(dependencies.transport, {
345
- path: "/gdesign/tool/v1/dify/process/batch",
346
- body: { task_ids: [taskId] },
347
- credential: access.credential,
348
- organizationId: access.organizationId,
349
- signal
357
+ poll = await queryToolResult(dependencies.transport, {
358
+ taskId, credential: access.credential, organizationId: access.organizationId, signal,
359
+ onDifyTaskId: id => dependencies.telemetry.annotate({ dify_task_id: id })
350
360
  });
351
361
  transientFailures = 0;
352
362
  }
@@ -361,7 +371,6 @@ export function createToolApiAdapter(dependencies) {
361
371
  await sleep(transientFailures * 1_000, signal);
362
372
  continue;
363
373
  }
364
- const poll = pollResult(response, taskId);
365
374
  if (poll.difyTaskId !== undefined) {
366
375
  dependencies.telemetry.annotate({ dify_task_id: poll.difyTaskId });
367
376
  }
@@ -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
  };
@@ -4,6 +4,7 @@ const truncationMarker = "[TRUNCATED]";
4
4
  export function remoteErrorEvidence(value) {
5
5
  const normalized = parseJson(value);
6
6
  const remoteCode = topLevelCode(normalized) ?? jsonRpcErrorCode(normalized);
7
+ const diagnosticReason = imageAuditTimeout(normalized, remoteCode);
7
8
  const sanitized = sanitize(normalized);
8
9
  if (sanitized === undefined) {
9
10
  return remoteCode === undefined ? {} : { remoteCode };
@@ -13,7 +14,8 @@ export function remoteErrorEvidence(value) {
13
14
  : `${sanitized.slice(0, maximumLength - truncationMarker.length)}${truncationMarker}`;
14
15
  return {
15
16
  ...(remoteCode === undefined ? {} : { remoteCode }),
16
- remoteBody
17
+ remoteBody,
18
+ ...(diagnosticReason ? { diagnosticReason } : {})
17
19
  };
18
20
  }
19
21
  function parseJson(value) {
@@ -78,3 +80,13 @@ function redactCookieAssignments(value) {
78
80
  function redactCookieAssignment(value) {
79
81
  return value.replace(/\b(cookie)\s*=\s*[^\s,;}&]+/giu, "$1=[REDACTED]");
80
82
  }
83
+ function imageAuditTimeout(value, remoteCode) {
84
+ if (remoteCode !== "-31994" || value === null || typeof value !== "object" || Array.isArray(value))
85
+ return;
86
+ const record = value;
87
+ const error = record.jsonrpc === "2.0" && !Object.hasOwn(record, "result") ? record.error : record;
88
+ if (error && typeof error === "object" && !Array.isArray(error)
89
+ && String(error.code) === "-31994"
90
+ && error.message === "图片审核处理超时,请稍后重试")
91
+ return "IMAGE_AUDIT_TIMEOUT";
92
+ }
@@ -7,6 +7,6 @@ export class RemoteProtocolError extends Error {
7
7
  this.name = "RemoteProtocolError";
8
8
  this.remoteCode = evidence.remoteCode;
9
9
  this.remoteBody = evidence.remoteBody;
10
- this.diagnosticReason = diagnosticReason;
10
+ this.diagnosticReason = diagnosticReason ?? evidence.diagnosticReason;
11
11
  }
12
12
  }
@@ -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,
@@ -15,7 +15,7 @@ export class RemoteRequestError extends Error {
15
15
  this.transient = transient;
16
16
  this.remoteCode = evidence.remoteCode;
17
17
  this.remoteBody = evidence.remoteBody;
18
- this.diagnosticReason = diagnosticReason;
18
+ this.diagnosticReason = diagnosticReason ?? evidence.diagnosticReason;
19
19
  }
20
20
  }
21
21
  const TRANSIENT_NETWORK_CODES = new Set([