@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.
- package/dist/src/bootstrap/create-cli.js +3 -1
- package/dist/src/bootstrap/create-runtime.js +24 -12
- package/dist/src/bootstrap/run-task-worker.js +2 -2
- package/dist/src/bootstrap/validators.js +1 -1
- package/dist/src/cli/action-binding.js +3 -0
- package/dist/src/cli/errors.js +77 -24
- package/dist/src/cli/model-commands.js +1 -1
- package/dist/src/cli/observed-errors.js +118 -0
- package/dist/src/cli/task-commands.js +1 -1
- package/dist/src/cli/tool-commands.js +1 -1
- package/dist/src/features/auth/sso-service.js +13 -4
- package/dist/src/features/dam/dam-api-adapter.js +1 -0
- package/dist/src/features/dam/file-downloader.js +23 -2
- package/dist/src/features/task/creation-refusal.js +14 -10
- package/dist/src/features/task/store.js +10 -4
- package/dist/src/features/task/use-cases.js +45 -16
- package/dist/src/features/tool/dynamic-schema.js +4 -1
- package/dist/src/features/tool/tool-api-adapter.js +42 -33
- package/dist/src/features/update/update-service.js +4 -2
- package/dist/src/platform/file-lock.js +12 -0
- package/dist/src/platform/local-json-file.js +19 -5
- package/dist/src/platform/remote-error-evidence.js +13 -1
- package/dist/src/platform/remote-protocol.js +1 -1
- package/dist/src/platform/safe-upload-file.js +18 -10
- package/dist/src/platform/schema-issues.js +47 -2
- package/dist/src/platform/signed-http-transport.js +1 -1
- package/dist/src/platform/text-output.js +17 -4
- package/dist/src/telemetry/failure-summary.js +18 -0
- package/package.json +4 -4
- package/skills/insmind-cli/references/errors.md +3 -1
- package/skills/insmind-cli/references/tool.md +1 -1
|
@@ -97,6 +97,7 @@ export async function executeCli(options) {
|
|
|
97
97
|
}
|
|
98
98
|
const outcome = redact(mapCliError(error, {
|
|
99
99
|
aborted: isInterruption(error, options.signal),
|
|
100
|
+
operation: options.telemetry.creationContext().operation, failureStage: options.telemetry.failureStage(error),
|
|
100
101
|
...(options.product ? { product: options.product } : {})
|
|
101
102
|
}));
|
|
102
103
|
// The invocation already carries the task created by this command, even on interruption.
|
|
@@ -111,7 +112,8 @@ export async function executeCli(options) {
|
|
|
111
112
|
: "保留此任务 ID,不要自动重新提交创作。"
|
|
112
113
|
] };
|
|
113
114
|
}
|
|
114
|
-
const telemetryError = classifyTelemetryError(error, { aborted: isInterruption(error, options.signal),
|
|
115
|
+
const telemetryError = classifyTelemetryError(error, { aborted: isInterruption(error, options.signal),
|
|
116
|
+
operation: options.telemetry.creationContext().operation, failureStage: options.telemetry.failureStage(error), ...(options.product ? { product: options.product } : {}) });
|
|
115
117
|
const traceId = options.telemetry.selected
|
|
116
118
|
? options.telemetry.traceId
|
|
117
119
|
: undefined;
|
|
@@ -97,9 +97,15 @@ export function createProductionRuntime(options = {}) {
|
|
|
97
97
|
traceIdFactory: () => randomBytes(16).toString("hex"),
|
|
98
98
|
spanIdFactory: () => randomBytes(8).toString("hex"),
|
|
99
99
|
runtime: { os: process.platform, arch: process.arch, nodeMajor: Number.parseInt(process.versions.node, 10) },
|
|
100
|
-
classifyError: error => classifyTelemetryError(error, { product }),
|
|
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 });
|
|
@@ -340,16 +349,15 @@ export function createProductionRuntime(options = {}) {
|
|
|
340
349
|
commandName: product.commandName,
|
|
341
350
|
text,
|
|
342
351
|
failureNote: error => {
|
|
343
|
-
const outcome = mapCliError(error, { aborted: false, product });
|
|
344
|
-
|
|
345
|
-
return outcome.kind === "failure" ? `${outcome.failure.code}${status}: ${outcome.failure.message}` : "";
|
|
352
|
+
const outcome = mapCliError(error, { aborted: false, product, operation: telemetry.creationContext().operation, failureStage: telemetry.failureStage(error) });
|
|
353
|
+
return outcome.kind === "failure" ? outcome.failure.message : "";
|
|
346
354
|
},
|
|
347
355
|
recovery: {
|
|
348
356
|
authorize: authorizeTaskResult,
|
|
349
357
|
async agent(progress, state, signal) {
|
|
350
358
|
if (!progress.contextId || !progress.localMessageId)
|
|
351
359
|
return {
|
|
352
|
-
state: "unknown", note: text("
|
|
360
|
+
state: "unknown", note: text("尚未取得任务结果。", "The task result has not been received.")
|
|
353
361
|
};
|
|
354
362
|
await authorizeTaskAccess(state, signal);
|
|
355
363
|
const snapshot = await readAgentResult(agentTransport, {
|
|
@@ -357,14 +365,16 @@ export function createProductionRuntime(options = {}) {
|
|
|
357
365
|
credential: state.credential, organizationId: state.organization.id, signal
|
|
358
366
|
});
|
|
359
367
|
return { state: "unknown",
|
|
360
|
-
note:
|
|
368
|
+
note: snapshot.partialResult
|
|
369
|
+
? text("已找到部分内容,尚未取得完整结果。", "Some content was found, but the complete result has not been received.")
|
|
370
|
+
: text("尚未取得任务结果。", "The task result has not been received."),
|
|
361
371
|
...(snapshot.partialResult ? { partialResult: await authorizeTaskResult(agentOutputWithBillingUnit(snapshot.partialResult, product.billingUnit), state, signal, true) } : {})
|
|
362
372
|
};
|
|
363
373
|
},
|
|
364
374
|
async tool(progress, state, signal) {
|
|
365
375
|
if (!progress.remoteTaskId || !progress.toolUsage)
|
|
366
376
|
return {
|
|
367
|
-
state: "unknown", note: text("
|
|
377
|
+
state: "unknown", note: text("尚未取得任务结果。", "The task result has not been received.")
|
|
368
378
|
};
|
|
369
379
|
await authorizeTaskAccess(state, signal);
|
|
370
380
|
const taskId = progress.remoteTaskId;
|
|
@@ -372,7 +382,8 @@ export function createProductionRuntime(options = {}) {
|
|
|
372
382
|
try {
|
|
373
383
|
response = await telemetry.stage("task.query", async () => {
|
|
374
384
|
const result = await queryToolResult(toolTransport, {
|
|
375
|
-
taskId, credential: state.credential, organizationId: state.organization.id, signal
|
|
385
|
+
taskId, credential: state.credential, organizationId: state.organization.id, signal,
|
|
386
|
+
onDifyTaskId: id => telemetry.annotate({ dify_task_id: id })
|
|
376
387
|
});
|
|
377
388
|
if (result.difyTaskId)
|
|
378
389
|
telemetry.annotate({ dify_task_id: result.difyTaskId });
|
|
@@ -384,10 +395,11 @@ export function createProductionRuntime(options = {}) {
|
|
|
384
395
|
catch (error) {
|
|
385
396
|
if (!(error instanceof ToolTaskFailedError))
|
|
386
397
|
throw error;
|
|
387
|
-
|
|
398
|
+
const outcome = mapCliError(error, { aborted: false, product, operation: "task.get", failureStage: "task.query" });
|
|
399
|
+
return { state: "failed", note: outcome.failure?.message ?? text("本次生成未能完成。", "This creation could not be completed."), failure: error };
|
|
388
400
|
}
|
|
389
401
|
if (response.state === "pending")
|
|
390
|
-
return { state: "running", note: text("
|
|
402
|
+
return { state: "running", note: text("任务仍在处理中。", "The task is still processing.") };
|
|
391
403
|
return { state: "completed", result: await authorizeTaskResult(toolOutputWithBillingUnit({
|
|
392
404
|
content: response.content, usage: progress.toolUsage
|
|
393
405
|
}, product.billingUnit), state, signal, true) };
|
|
@@ -44,12 +44,12 @@ export async function runTaskWorker(options) {
|
|
|
44
44
|
});
|
|
45
45
|
}
|
|
46
46
|
catch (error) {
|
|
47
|
-
const outcome = redact(mapCliError(error, { aborted: isInterruption(error, signal), product: runtime.product }));
|
|
47
|
+
const outcome = redact(mapCliError(error, { aborted: isInterruption(error, signal), product: runtime.product, operation: job.operation, failureStage: runtime.telemetry.failureStage(error) }));
|
|
48
48
|
completion = outcome.kind === "interrupted" ? { outcome: "interrupted", error }
|
|
49
49
|
: { outcome: "failure", error, errorCode: outcome.failure.code, errorMessage: outcome.failure.message };
|
|
50
50
|
if (outcome.kind === "failure")
|
|
51
51
|
send({ type: "error", failure: outcome.failure, exitCode: outcome.exitCode,
|
|
52
|
-
diagnostics: taskWorkerDiagnostics(error, classifyTelemetryError(error, { product: runtime.product }), runtime.telemetry.failureStage(error)) });
|
|
52
|
+
diagnostics: taskWorkerDiagnostics(error, classifyTelemetryError(error, { product: runtime.product, operation: job.operation, failureStage: runtime.telemetry.failureStage(error) }), runtime.telemetry.failureStage(error)) });
|
|
53
53
|
}
|
|
54
54
|
finally {
|
|
55
55
|
await runtime.analytics?.shutdown().catch(() => undefined);
|
|
@@ -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)
|
package/dist/src/cli/errors.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { observedErrorCategory, observedErrorMessage } from "./observed-errors.js";
|
|
1
2
|
import { TaskBackgroundError } from "../features/task/task-background.js";
|
|
2
3
|
import { TaskNotFoundError } from "../features/task/use-cases.js";
|
|
3
4
|
import { TaskStoreError } from "../features/task/store.js";
|
|
@@ -8,7 +9,7 @@ import { SsoRequestError } from "../features/auth/sso-service.js";
|
|
|
8
9
|
import { AuthorizedAccountContextMissingError, BrowserOpenError, DeviceAuthorizationExpiredError } from "../features/auth/use-cases.js";
|
|
9
10
|
import { AgentInputError } from "../features/agent/use-cases.js";
|
|
10
11
|
import { ToolInputError } from "../features/tool/catalog.js";
|
|
11
|
-
import { ToolTaskFailedError } from "../features/tool/tool-api-adapter.js";
|
|
12
|
+
import { ToolTaskFailedError, ToolTaskCanceledError } from "../features/tool/tool-api-adapter.js";
|
|
12
13
|
import { AgentAuditRejectedError } from "../features/agent/creative-protocol.js";
|
|
13
14
|
import { isContentReviewRejection } from "../features/task/creation-refusal.js";
|
|
14
15
|
import { ObjectStorageUploadError } from "../features/dam/object-storage.js";
|
|
@@ -30,27 +31,54 @@ import { EditorNotReadyError, EditorSessionNotFoundError, EditorTargetError } fr
|
|
|
30
31
|
import { UpdateError } from "../features/update/update-service.js";
|
|
31
32
|
import { WindAnalyticsError } from "../analytics/wind.js";
|
|
32
33
|
import { safeFailureSummary } from "../telemetry/failure-summary.js";
|
|
34
|
+
import { OutputStreamError } from "../platform/text-output.js";
|
|
33
35
|
export class CliUsageError extends Error {
|
|
34
|
-
|
|
36
|
+
reason;
|
|
37
|
+
constructor(reason = "command_arguments") {
|
|
35
38
|
super("命令或参数无效。");
|
|
39
|
+
this.reason = reason;
|
|
36
40
|
this.name = "CliUsageError";
|
|
37
41
|
}
|
|
38
42
|
}
|
|
39
43
|
const INSUFFICIENT_CREDITS_REMOTE_CODE = "12020770";
|
|
40
|
-
const INSUFFICIENT_CREDITS_NEXT_STEPS = [
|
|
41
|
-
"前往 https://www.gaoding.art/pricing 购买稿豆",
|
|
42
|
-
"也可以执行 gd-cli org list,再用 gd-cli org switch --org <org-id> 切换到有可用稿豆的组织",
|
|
43
|
-
"处理后重新发起本次创作"
|
|
44
|
-
];
|
|
45
44
|
export function isHelpOutcome(error) {
|
|
46
45
|
return error instanceof CommanderError
|
|
47
46
|
&& error.exitCode === 0
|
|
48
47
|
&& (error.code === "commander.helpDisplayed" || error.code === "commander.version");
|
|
49
48
|
}
|
|
50
49
|
export function mapCliError(error, options) {
|
|
50
|
+
const outcome = mapBaseCliError(error, options);
|
|
51
|
+
if (outcome.kind === "interrupted")
|
|
52
|
+
return { ...outcome, failure: { code: "INTERRUPTED",
|
|
53
|
+
message: options.product?.id === "insmind" ? "This operation stopped waiting." : "本次操作已停止等待。",
|
|
54
|
+
...(outcome.failure?.details ? { details: outcome.failure.details } : {}) } };
|
|
55
|
+
if (error instanceof TaskBackgroundError)
|
|
56
|
+
return outcome;
|
|
57
|
+
const remote = remoteCause(error);
|
|
58
|
+
const evidence = {
|
|
59
|
+
product: options.product?.id ?? "gaoding", operation: options.operation, failureStage: options.failureStage,
|
|
60
|
+
code: outcome.failure.code, errorType: error instanceof Error ? error.name : undefined,
|
|
61
|
+
remoteCode: remote?.remoteCode,
|
|
62
|
+
httpStatus: remote instanceof RemoteRequestError || remote instanceof SsoRequestError ? remote.status : 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
|
|
66
|
+
};
|
|
67
|
+
const category = observedErrorCategory(evidence);
|
|
68
|
+
if (!category)
|
|
69
|
+
return outcome;
|
|
70
|
+
// Keep precise input corrections and their fields; general failures have a short user message.
|
|
71
|
+
if (category === "input" && ["USAGE_ERROR", "INVALID_ACTIONS"].includes(outcome.failure.code))
|
|
72
|
+
return outcome;
|
|
73
|
+
return { ...outcome, failure: { ...outcome.failure, message: observedErrorMessage(category, evidence) } };
|
|
74
|
+
}
|
|
75
|
+
function mapBaseCliError(error, options) {
|
|
51
76
|
const insmind = options.product?.id === "insmind";
|
|
52
77
|
const command = options.product?.commandName ?? "gd-cli";
|
|
53
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.") } };
|
|
54
82
|
if (options.aborted)
|
|
55
83
|
return { kind: "interrupted", exitCode: 130, failure: {
|
|
56
84
|
code: "INTERRUPTED", message: text("已停止本地等待;已派发的任务或写操作可能仍在继续。", "Local waiting stopped; dispatched tasks or writes may still be active."),
|
|
@@ -120,7 +148,9 @@ export function mapCliError(error, options) {
|
|
|
120
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 } : {}) });
|
|
121
149
|
}
|
|
122
150
|
if (error instanceof LocalFileInputError)
|
|
123
|
-
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:
|
|
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 });
|
|
124
154
|
if (error instanceof DamInputError)
|
|
125
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 });
|
|
126
156
|
if (error instanceof OrgUsageError
|
|
@@ -130,12 +160,10 @@ export function mapCliError(error, options) {
|
|
|
130
160
|
return failure("USAGE_ERROR", "Invalid command or arguments. See --help.", 2);
|
|
131
161
|
return failure("USAGE_ERROR", "命令或参数无效,请查看 --help。", 2);
|
|
132
162
|
}
|
|
133
|
-
if (isInsufficientCreditsError(error)) {
|
|
134
|
-
|
|
135
|
-
return failure("INSUFFICIENT_CREDITS", "There are not enough insMind credits to complete this creation.", 1, [`Buy credits at ${options.product.pricingUrl.href}`, "Retry after adding credits."]);
|
|
136
|
-
return failure("INSUFFICIENT_CREDITS", "当前组织稿豆不足,无法完成本次创作。", 1, INSUFFICIENT_CREDITS_NEXT_STEPS);
|
|
163
|
+
if (options.product?.id !== "insmind" && options.operation === "tool.call" && isInsufficientCreditsError(error)) {
|
|
164
|
+
return failure("INSUFFICIENT_CREDITS", "当前可用额度不足,本次生成未能完成。", 1);
|
|
137
165
|
}
|
|
138
|
-
if (isContentReviewRejection(error)) {
|
|
166
|
+
if (isContentReviewRejection(error, { product: options.product?.id ?? "gaoding", operation: options.operation })) {
|
|
139
167
|
const phase = error instanceof AgentAuditRejectedError ? error.phase : undefined;
|
|
140
168
|
const reason = phase === undefined ? "audit_rejected" : `${phase}_audit_rejected`;
|
|
141
169
|
const message = phase === "input"
|
|
@@ -236,6 +264,8 @@ function isInsufficientCreditsError(error) {
|
|
|
236
264
|
|| error instanceof ToolTaskFailedError) && error.remoteCode === INSUFFICIENT_CREDITS_REMOTE_CODE;
|
|
237
265
|
}
|
|
238
266
|
export function classifyTelemetryError(error, options = {}) {
|
|
267
|
+
if (error instanceof ToolTaskCanceledError)
|
|
268
|
+
return { outcome: "interrupted", errorCode: "INTERRUPTED", diagnosticReason: "TASK_CANCELED" };
|
|
239
269
|
if (error instanceof WindAnalyticsError)
|
|
240
270
|
return { outcome: "failure", errorCode: error.code,
|
|
241
271
|
...(error.status === undefined ? {} : { httpStatus: error.status }) };
|
|
@@ -251,14 +281,7 @@ export function classifyTelemetryError(error, options = {}) {
|
|
|
251
281
|
...(diagnostics?.diagnostic_summary ? { diagnosticSummary: diagnostics.diagnostic_summary } : {}),
|
|
252
282
|
...(diagnostics?.diagnostic_reason ? { diagnosticReason: diagnostics.diagnostic_reason } : {}) };
|
|
253
283
|
}
|
|
254
|
-
|
|
255
|
-
for (let cause = error, depth = 0; cause instanceof Error && depth < 10; cause = cause.cause, depth++) {
|
|
256
|
-
if (cause instanceof RemoteRequestError || cause instanceof RemoteProtocolError || cause instanceof ToolTaskFailedError
|
|
257
|
-
|| cause instanceof SsoRequestError || cause instanceof OrganizationBindFailedError) {
|
|
258
|
-
remoteError = cause;
|
|
259
|
-
break;
|
|
260
|
-
}
|
|
261
|
-
}
|
|
284
|
+
const remoteError = remoteCause(error);
|
|
262
285
|
let summary;
|
|
263
286
|
if ((remoteError instanceof RemoteRequestError || remoteError instanceof RemoteProtocolError)
|
|
264
287
|
&& /^(?:RESPONSE_|AGENT_)/u.test(remoteError.diagnosticReason ?? "")) {
|
|
@@ -268,8 +291,16 @@ export function classifyTelemetryError(error, options = {}) {
|
|
|
268
291
|
catch { /* No safe summary available. */ }
|
|
269
292
|
}
|
|
270
293
|
const diagnosticSummary = safeFailureSummary({
|
|
294
|
+
...localFileSummary(error),
|
|
295
|
+
...(error instanceof OutputStreamError ? { outputStream: error.outputStream } : {}),
|
|
296
|
+
...(remoteError instanceof SsoRequestError ? remoteError.diagnosticSummary : {}),
|
|
271
297
|
...(summary && typeof summary === "object" && !Array.isArray(summary) ? summary : {}),
|
|
272
|
-
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
|
|
273
304
|
});
|
|
274
305
|
return {
|
|
275
306
|
outcome: outcome.kind === "interrupted" ? "interrupted" : "failure",
|
|
@@ -284,8 +315,12 @@ export function classifyTelemetryError(error, options = {}) {
|
|
|
284
315
|
...(remoteError?.remoteBody === undefined
|
|
285
316
|
? {}
|
|
286
317
|
: { remoteErrorBody: remoteError.remoteBody }),
|
|
287
|
-
...(
|
|
288
|
-
? { 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 } : {})
|
|
289
324
|
};
|
|
290
325
|
}
|
|
291
326
|
function failure(code, message, exitCode, nextSteps, details) {
|
|
@@ -306,3 +341,21 @@ function systemErrorCode(error) {
|
|
|
306
341
|
}
|
|
307
342
|
return undefined;
|
|
308
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
|
+
}
|
|
354
|
+
function remoteCause(error) {
|
|
355
|
+
for (let depth = 0; error instanceof Error && depth < 10; error = error.cause, depth++) {
|
|
356
|
+
if (error instanceof RemoteRequestError || error instanceof RemoteProtocolError || error instanceof ToolTaskFailedError
|
|
357
|
+
|| error instanceof SsoRequestError || error instanceof OrganizationBindFailedError)
|
|
358
|
+
return error;
|
|
359
|
+
}
|
|
360
|
+
return undefined;
|
|
361
|
+
}
|
|
@@ -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
|
|
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);
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
const messages = {
|
|
2
|
+
credits: ["当前可用额度不足,本次生成未能完成。", "There are not enough available credits to complete this creation."],
|
|
3
|
+
review: ["这次内容未通过审核,请调整描述或参考图片。", "This content did not pass content review. Adjust the description or reference image."],
|
|
4
|
+
session_busy: ["这个会话正在使用中,请稍后再试。", "This conversation is in use. Please try again later."],
|
|
5
|
+
service_busy: ["当前服务繁忙,请稍后再试。", "The service is busy. Please try again later."],
|
|
6
|
+
timeout: ["本次操作等待超时。", "This operation timed out."],
|
|
7
|
+
settings: ["当前生成设置暂不可用,请更换生成设置。", "These generation settings are unavailable. Choose different settings."],
|
|
8
|
+
login: ["请先登录后继续。", "Please sign in to continue."],
|
|
9
|
+
account: ["当前登录信息无法使用。", "Your current sign-in information cannot be used."],
|
|
10
|
+
input_asset: ["无法使用这份素材,请检查文件后重新选择。", "This asset cannot be used. Check the file and select it again."],
|
|
11
|
+
input: ["输入或设置不符合要求,请按提示调整。", "The input or settings are invalid. Adjust them as indicated."],
|
|
12
|
+
upload: ["当前账号无法完成此次上传。", "This account cannot complete this upload."],
|
|
13
|
+
task_missing: ["未找到这个任务,请核对任务编号。", "This task was not found. Check the task ID."],
|
|
14
|
+
asset_missing: ["未找到这份素材,请核对素材信息。", "This asset was not found. Check the asset details."],
|
|
15
|
+
file_exists: ["保存位置已有同名文件,请更换名称或位置。", "A file with this name already exists. Choose another name or location."],
|
|
16
|
+
asset_read: ["未能获取这份素材。", "This asset could not be retrieved."],
|
|
17
|
+
editor: ["暂时无法连接编辑器,请打开作品后再试。", "The editor cannot be reached. Open the design and try again."],
|
|
18
|
+
unsupported: ["当前内容暂不支持这项编辑。", "This content does not support this edit."],
|
|
19
|
+
save: ["保存遇到问题,请在编辑器查看作品。", "There was a problem saving. Check the design in the editor."],
|
|
20
|
+
local: ["无法读取或保存本次操作记录。", "The record for this operation could not be read or saved."],
|
|
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."],
|
|
24
|
+
output: ["结果未能完整显示。", "The result could not be fully displayed."],
|
|
25
|
+
read: ["暂时无法读取结果。", "The result cannot be read right now."],
|
|
26
|
+
tool: ["本次生成未能完成。", "This creation could not be completed."],
|
|
27
|
+
request: ["本次请求未能完成。", "This request could not be completed."],
|
|
28
|
+
client: ["程序运行遇到问题,本次操作未能完成。", "The app encountered a problem and could not complete this operation."]
|
|
29
|
+
};
|
|
30
|
+
const reviewCodes = new Set(["12020751", "12020752", "12020757", "12020758", "12020760", "12020790"]);
|
|
31
|
+
export function observedErrorCategory(e) {
|
|
32
|
+
const gd = e.product === "gaoding", ins = e.product === "insmind";
|
|
33
|
+
const toolOrQuery = e.operation === "tool.call" || e.operation === "task.get";
|
|
34
|
+
if (e.code === "INSUFFICIENT_CREDITS" || gd && e.operation === "tool.call" && e.remoteCode === "12020770")
|
|
35
|
+
return "credits";
|
|
36
|
+
if (e.errorType === "AgentAuditRejectedError" || e.diagnosticReason === "AGENT_INPUT_AUDIT_REJECTED"
|
|
37
|
+
|| gd && (toolOrQuery && reviewCodes.has(e.remoteCode ?? "") || e.operation === "agent.send" && e.remoteCode === "-1006")
|
|
38
|
+
|| ins && toolOrQuery && e.remoteCode === "12020760")
|
|
39
|
+
return "review";
|
|
40
|
+
if (gd && e.operation === "agent.send" && e.httpStatus === 409)
|
|
41
|
+
return "session_busy";
|
|
42
|
+
if (gd && e.operation === "agent.send" && e.httpStatus === 429)
|
|
43
|
+
return "service_busy";
|
|
44
|
+
if (gd && e.operation === "auth.login" && e.httpStatus === 504 || e.code === "EDITOR_RPC_TIMEOUT"
|
|
45
|
+
|| ins && e.operation === "tool.call" && e.remoteCode === "-31994" && e.diagnosticReason === "IMAGE_AUDIT_TIMEOUT")
|
|
46
|
+
return "timeout";
|
|
47
|
+
if (ins && e.operation === "tool.call" && e.remoteCode === "-31993")
|
|
48
|
+
return "settings";
|
|
49
|
+
if (["AUTH_REQUIRED", "LOGIN_REQUIRED"].includes(e.code) || e.errorType === "DeviceAuthorizationExpiredError")
|
|
50
|
+
return "login";
|
|
51
|
+
if (["AUTH_STATE_INVALID", "ORG_INVALID"].includes(e.code))
|
|
52
|
+
return "account";
|
|
53
|
+
if (e.code === "USAGE_ERROR" && e.errorType === "LocalFileInputError")
|
|
54
|
+
return "input_asset";
|
|
55
|
+
if (gd && e.operation === "dam.rename" && e.remoteCode === "00010014")
|
|
56
|
+
return "file_exists";
|
|
57
|
+
if (["USAGE_ERROR", "INVALID_ACTIONS"].includes(e.code))
|
|
58
|
+
return "input";
|
|
59
|
+
if (gd && e.operation === "dam.upload" && e.remoteCode === "36002105")
|
|
60
|
+
return "upload";
|
|
61
|
+
if (e.code === "TASK_NOT_FOUND" || e.operation === "task.get" && e.remoteCode === "12020704")
|
|
62
|
+
return "task_missing";
|
|
63
|
+
if (e.code === "DAM_ASSET_NOT_FOUND")
|
|
64
|
+
return "asset_missing";
|
|
65
|
+
if (e.code === "DAM_DOWNLOAD_DESTINATION_EXISTS")
|
|
66
|
+
return "file_exists";
|
|
67
|
+
if (["DAM_DOWNLOAD_FAILED", "DAM_ASSET_NOT_DOWNLOADABLE"].includes(e.code)
|
|
68
|
+
|| gd && ["dam.download", "dam.get", "dam.list", "dam.search"].includes(e.operation ?? "")
|
|
69
|
+
&& e.code === "REMOTE_REQUEST_FAILED" && [403, 404].includes(e.httpStatus ?? 0))
|
|
70
|
+
return "asset_read";
|
|
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))
|
|
74
|
+
return "editor";
|
|
75
|
+
if (e.code === "UNSUPPORTED_PAGE_CONTENT")
|
|
76
|
+
return "unsupported";
|
|
77
|
+
if (e.code === "SAVE_FAILED")
|
|
78
|
+
return "save";
|
|
79
|
+
if (e.code === "LOCAL_STATE_ERROR")
|
|
80
|
+
return "local";
|
|
81
|
+
if (e.code === "UPDATE_FAILED" && e.diagnosticReason === "UPDATE_MANAGED_BY_HOST")
|
|
82
|
+
return "managed_update";
|
|
83
|
+
if (e.code === "UPDATE_FAILED")
|
|
84
|
+
return "update";
|
|
85
|
+
if (e.diagnosticReason === "OUTPUT_STREAM_FAILED" || e.code === "INTERNAL_ERROR" && e.failureStage === "output")
|
|
86
|
+
return "output";
|
|
87
|
+
if (gd && (e.operation === "tool.call" && ["12020700", "12020791", "500"].includes(e.remoteCode ?? "")
|
|
88
|
+
|| toolOrQuery && e.remoteCode === "12020780" || e.operation === "dam.upload" && e.remoteCode === "500"))
|
|
89
|
+
return "request";
|
|
90
|
+
if (e.diagnosticReason?.startsWith("SSO_RESPONSE_") || e.code === "REMOTE_PROTOCOL_INCOMPATIBLE"
|
|
91
|
+
|| ["AGENT_CONTEXT_ID_MISSING", "AGENT_USAGE_MODEL_MISSING", "RESPONSE_BODY_ALREADY_USED"].includes(e.diagnosticReason ?? ""))
|
|
92
|
+
return "read";
|
|
93
|
+
if (e.code === "TOOL_TASK_FAILED")
|
|
94
|
+
return "tool";
|
|
95
|
+
if (e.code === "REMOTE_REQUEST_FAILED")
|
|
96
|
+
return "request";
|
|
97
|
+
if (e.code === "INTERNAL_ERROR")
|
|
98
|
+
return "client";
|
|
99
|
+
return undefined;
|
|
100
|
+
}
|
|
101
|
+
export function observedErrorMessage(category, e) {
|
|
102
|
+
const text = (zh, en) => e.product === "insmind" ? en : zh;
|
|
103
|
+
if (category === "timeout" && e.diagnosticReason === "IMAGE_AUDIT_TIMEOUT")
|
|
104
|
+
return text("本次图片检查未能及时完成。", "The image check did not finish in time.");
|
|
105
|
+
if (category === "login" && e.errorType === "DeviceAuthorizationExpiredError")
|
|
106
|
+
return text("本次登录已超时,请重新登录。", "This sign-in timed out. Please sign in again.");
|
|
107
|
+
if (category === "account" && e.code === "ORG_INVALID")
|
|
108
|
+
return text("当前团队不可用,请重新选择团队。", "This team is unavailable. Select another team.");
|
|
109
|
+
if (category === "file_exists" && e.operation === "dam.rename" && e.remoteCode === "00010014")
|
|
110
|
+
return text("名称已存在,请换个名称。", "This name already exists. Choose another name.");
|
|
111
|
+
if (category === "asset_read" && e.code === "DAM_DOWNLOAD_FAILED")
|
|
112
|
+
return text("素材下载未完成。", "The asset download did not complete.");
|
|
113
|
+
if (category === "local" && e.errorType === "LocalFileError")
|
|
114
|
+
return text("无法读取或保存所需文件。", "A required file could not be read or saved.");
|
|
115
|
+
if (category === "request" && e.operation === "task.get")
|
|
116
|
+
return text("本次未能读取任务结果。", "The task result could not be retrieved.");
|
|
117
|
+
return text(messages[category][0], messages[category][1]);
|
|
118
|
+
}
|
|
@@ -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, "
|
|
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
|
-
|
|
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
|
|
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
|
|
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
|
|
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
|
-
|
|
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))
|