@insmind/cli 1.5.0 → 1.5.2
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/bin/agent-worker.js +2 -1
- package/dist/bin/insmind-cli.js +12 -7
- package/dist/bin/postinstall.js +7 -5
- package/dist/src/bootstrap/create-cli.js +26 -17
- package/dist/src/bootstrap/create-runtime.js +31 -13
- package/dist/src/bootstrap/run-agent-worker.js +2 -1
- package/dist/src/bootstrap/validators.js +10 -5
- package/dist/src/cli/action-binding.js +14 -0
- package/dist/src/cli/agent-commands.js +8 -3
- package/dist/src/cli/auth-commands.js +1 -1
- package/dist/src/cli/credits-command.js +2 -2
- package/dist/src/cli/dam-commands.js +51 -52
- package/dist/src/cli/editor-commands.js +13 -15
- package/dist/src/cli/errors.js +91 -41
- package/dist/src/cli/model-commands.js +7 -5
- package/dist/src/cli/presenter.js +13 -10
- package/dist/src/cli/task-commands.js +13 -5
- package/dist/src/cli/tool-commands.js +9 -3
- package/dist/src/features/agent/use-cases.js +11 -5
- package/dist/src/features/auth/credential-store.js +2 -2
- package/dist/src/features/auth/sso-service.js +3 -2
- package/dist/src/features/auth/state.js +2 -0
- package/dist/src/features/auth/use-cases.js +30 -34
- package/dist/src/features/credits/use-cases.js +2 -0
- package/dist/src/features/dam/file-downloader.js +38 -16
- package/dist/src/features/dam/object-storage.js +23 -11
- package/dist/src/features/dam/operation-executor.js +46 -37
- package/dist/src/features/dam/registered-uploader.js +39 -29
- package/dist/src/features/dam/storage-upload.js +5 -4
- package/dist/src/features/dam/use-cases.js +81 -60
- package/dist/src/features/editor/bridge-client.js +6 -6
- package/dist/src/features/editor/bridge-process.js +2 -1
- package/dist/src/features/editor/session-state.js +6 -4
- package/dist/src/features/editor/session.js +26 -8
- package/dist/src/features/editor/use-cases.js +10 -3
- package/dist/src/features/org/use-cases.js +2 -1
- package/dist/src/features/task/agent-background.js +1 -0
- package/dist/src/features/task/store.js +2 -0
- package/dist/src/features/task/use-cases.js +80 -27
- package/dist/src/features/tool/catalog.js +11 -5
- package/dist/src/features/tool/dynamic-schema.js +9 -7
- package/dist/src/features/tool/mns-catalog-adapter.js +7 -23
- package/dist/src/features/tool/tool-api-adapter.js +8 -7
- package/dist/src/features/tool/use-cases.js +7 -3
- package/dist/src/features/update/update-notification.js +75 -70
- package/dist/src/features/update/update-service.js +24 -20
- package/dist/src/platform/file-lock.js +36 -9
- package/dist/src/platform/interruption.js +13 -0
- package/dist/src/platform/json-input.js +12 -9
- package/dist/src/platform/local-json-file.js +8 -4
- package/dist/src/platform/redact.js +7 -1
- package/dist/src/platform/remote-protocol.js +2 -2
- package/dist/src/platform/safe-upload-file.js +2 -1
- package/dist/src/platform/schema-issues.js +8 -0
- package/dist/src/platform/signed-http-transport.js +8 -7
- package/dist/src/platform/text-output.js +33 -0
- package/dist/src/telemetry/invocation.js +19 -4
- package/dist/src/telemetry/process-errors.js +14 -4
- package/dist/src/telemetry/sanitize.js +4 -2
- package/dist/src/telemetry/sls-sink.js +36 -20
- package/package.json +4 -4
|
@@ -26,14 +26,11 @@ export function createPresenter(options) {
|
|
|
26
26
|
options.writeError(`${insmind ? "Warning" : "警告"}: ${message}\n`);
|
|
27
27
|
},
|
|
28
28
|
error(outcome, presentation) {
|
|
29
|
-
|
|
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
|
-
...
|
|
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(`${
|
|
45
|
-
|
|
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.
|
|
24
|
-
|
|
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.
|
|
47
|
-
|
|
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,6 +31,8 @@ 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."),
|
|
34
37
|
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
38
|
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."),
|
|
@@ -37,6 +40,7 @@ export function registerToolCommands(program, runtime) {
|
|
|
37
40
|
text(runtime.product, "查询返回同一份 usage;Tool usage.cost 为当次目录预估价格。", "Queries return the same usage; Tool usage.cost is the catalog price estimate for that invocation."),
|
|
38
41
|
""
|
|
39
42
|
].join("\n"));
|
|
43
|
+
jsonOutput(call);
|
|
40
44
|
bindPreparedAction(call, "organization", async (signal) => {
|
|
41
45
|
signal.throwIfAborted();
|
|
42
46
|
const name = call.processedArgs[0];
|
|
@@ -78,8 +82,10 @@ export function registerToolCommands(program, runtime) {
|
|
|
78
82
|
if (prepared.async) {
|
|
79
83
|
const result = await runtime.tasks.submit({ ...task,
|
|
80
84
|
run: observe => runtime.tool.submit({ input: prepared.input, access, signal, observe }) });
|
|
81
|
-
runtime.
|
|
82
|
-
|
|
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
|
-
|
|
6
|
-
|
|
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,6 +1,6 @@
|
|
|
1
1
|
import { homedir } from "node:os";
|
|
2
2
|
import { join } from "node:path";
|
|
3
|
-
import { createLocalJsonFile
|
|
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
|
|
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
|
|
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
|
}
|
|
@@ -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
|
|
181
|
+
if (isInterruption(error, signal))
|
|
181
182
|
throw signal.reason;
|
|
182
183
|
throw await responseError(response, error);
|
|
183
184
|
});
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isInterruption } from "../../platform/interruption.js";
|
|
1
2
|
export class DeviceAuthorizationExpiredError extends Error {
|
|
2
3
|
constructor(commandName = "gd-cli") {
|
|
3
4
|
super(`Authorization expired. Run ${commandName} auth login again.`);
|
|
@@ -45,10 +46,13 @@ export function createAuthUseCases(dependencies) {
|
|
|
45
46
|
? []
|
|
46
47
|
: state.organization
|
|
47
48
|
? []
|
|
48
|
-
: ["gd-cli org list", "gd-cli org switch"]
|
|
49
|
+
: ["gd-cli org list", "gd-cli org switch --org <org-id>"]
|
|
49
50
|
};
|
|
50
51
|
},
|
|
51
52
|
async logout() {
|
|
53
|
+
const state = await dependencies.telemetry.stage("state", () => dependencies.store.read()).catch(() => null);
|
|
54
|
+
if (state)
|
|
55
|
+
dependencies.telemetry.annotate({ account_id: state.account?.id, organization_id: state.organization?.id });
|
|
52
56
|
await dependencies.telemetry.stage("state", () => dependencies.store.remove());
|
|
53
57
|
},
|
|
54
58
|
async login(input) {
|
|
@@ -112,51 +116,43 @@ export function createAuthUseCases(dependencies) {
|
|
|
112
116
|
}
|
|
113
117
|
dependencies.telemetry.annotate({ account_id: state.account?.id });
|
|
114
118
|
let organizationId = token.organizationId;
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
organizationId = identity.organizationId ?? organizationId;
|
|
118
|
-
if (!state.account && identity.account) {
|
|
119
|
-
state = { ...state, account: identity.account };
|
|
120
|
-
if (!dependencies.requireOrganization) {
|
|
121
|
-
await dependencies.telemetry.stage("state", () => dependencies.store.write(state));
|
|
122
|
-
}
|
|
123
|
-
dependencies.telemetry.annotate({ account_id: identity.account.id });
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
catch {
|
|
127
|
-
if (input.signal.aborted)
|
|
119
|
+
const identity = await dependencies.telemetry.stage("identity", () => (dependencies.sso.getIdentity(token.credential.accessKey, input.signal))).catch(cause => {
|
|
120
|
+
if (isInterruption(cause, input.signal))
|
|
128
121
|
throw input.signal.reason;
|
|
122
|
+
return undefined;
|
|
123
|
+
});
|
|
124
|
+
organizationId = identity?.organizationId ?? organizationId;
|
|
125
|
+
if (!state.account && identity?.account) {
|
|
126
|
+
state = { ...state, account: identity.account };
|
|
127
|
+
dependencies.telemetry.annotate({ account_id: identity.account.id });
|
|
128
|
+
if (!dependencies.requireOrganization) {
|
|
129
|
+
await dependencies.telemetry.stage("state", () => dependencies.store.write(state));
|
|
130
|
+
}
|
|
129
131
|
}
|
|
130
132
|
if (!organizationId) {
|
|
131
133
|
if (dependencies.requireOrganization)
|
|
132
134
|
throw new AuthorizedAccountContextMissingError();
|
|
133
|
-
input.interaction.warn("登录成功,请执行 gd-cli org switch 选择组织。");
|
|
135
|
+
input.interaction.warn("登录成功,请执行 gd-cli org list,再执行 gd-cli org switch --org <org-id> 选择组织。");
|
|
134
136
|
return { status: "logged_in", organizationSelected: false };
|
|
135
137
|
}
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
signal: input.signal
|
|
141
|
-
})));
|
|
142
|
-
if (!organization) {
|
|
143
|
-
if (dependencies.requireOrganization)
|
|
144
|
-
throw new AuthorizedAccountContextMissingError();
|
|
145
|
-
input.interaction.warn("登录成功,但未能选择组织;请执行 gd-cli org switch。");
|
|
146
|
-
return { status: "logged_in", organizationSelected: false };
|
|
147
|
-
}
|
|
148
|
-
await dependencies.telemetry.stage("state", () => dependencies.store.write({ ...state, organization }));
|
|
149
|
-
dependencies.telemetry.annotate({ organization_id: organization.id });
|
|
150
|
-
return { status: "logged_in", organizationSelected: true };
|
|
151
|
-
}
|
|
152
|
-
catch {
|
|
153
|
-
if (input.signal.aborted)
|
|
138
|
+
const organization = await dependencies.telemetry.stage("bind", () => (dependencies.organizationBinder.bindAuthorizedOrganization({
|
|
139
|
+
credential: token.credential, organizationId, signal: input.signal
|
|
140
|
+
}))).catch(cause => {
|
|
141
|
+
if (isInterruption(cause, input.signal))
|
|
154
142
|
throw input.signal.reason;
|
|
143
|
+
if (dependencies.requireOrganization)
|
|
144
|
+
throw cause;
|
|
145
|
+
return undefined;
|
|
146
|
+
});
|
|
147
|
+
if (!organization) {
|
|
155
148
|
if (dependencies.requireOrganization)
|
|
156
149
|
throw new AuthorizedAccountContextMissingError();
|
|
157
|
-
input.interaction.warn("
|
|
150
|
+
input.interaction.warn("登录成功,但未能选择组织;请执行 gd-cli org list,再执行 gd-cli org switch --org <org-id>。");
|
|
158
151
|
return { status: "logged_in", organizationSelected: false };
|
|
159
152
|
}
|
|
153
|
+
dependencies.telemetry.annotate({ organization_id: organization.id });
|
|
154
|
+
await dependencies.telemetry.stage("state", () => dependencies.store.write({ ...state, organization }));
|
|
155
|
+
return { status: "logged_in", organizationSelected: true };
|
|
160
156
|
}
|
|
161
157
|
};
|
|
162
158
|
}
|
|
@@ -44,6 +44,8 @@ function findCreditsRecord(value) {
|
|
|
44
44
|
return record;
|
|
45
45
|
}
|
|
46
46
|
function number(value) {
|
|
47
|
+
if (typeof value !== "number" && (typeof value !== "string" || value.trim() === ""))
|
|
48
|
+
return undefined;
|
|
47
49
|
const parsed = typeof value === "number" ? value : Number(value);
|
|
48
50
|
return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;
|
|
49
51
|
}
|
|
@@ -1,10 +1,17 @@
|
|
|
1
|
+
import { isInterruption } from "../../platform/interruption.js";
|
|
1
2
|
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
-
import { access, mkdir, open,
|
|
3
|
-
import { extname, resolve } from "node:path";
|
|
3
|
+
import { access, mkdir, open, link, rm } from "node:fs/promises";
|
|
4
|
+
import { dirname, extname, resolve } from "node:path";
|
|
4
5
|
import { parseSafeRemoteAssetUrl } from "../../platform/url-safety.js";
|
|
5
6
|
export class DamDownloadError extends Error {
|
|
6
|
-
|
|
7
|
+
phase;
|
|
8
|
+
status;
|
|
9
|
+
remainingPaths;
|
|
10
|
+
constructor(cause, phase = "download", status, remainingPaths = []) {
|
|
7
11
|
super("素材下载失败。", { cause });
|
|
12
|
+
this.phase = phase;
|
|
13
|
+
this.status = status;
|
|
14
|
+
this.remainingPaths = remainingPaths;
|
|
8
15
|
this.name = "DamDownloadError";
|
|
9
16
|
}
|
|
10
17
|
}
|
|
@@ -30,7 +37,7 @@ const nodeFileSystem = {
|
|
|
30
37
|
};
|
|
31
38
|
},
|
|
32
39
|
access,
|
|
33
|
-
|
|
40
|
+
link,
|
|
34
41
|
async rm(path, options) {
|
|
35
42
|
await rm(path, options);
|
|
36
43
|
}
|
|
@@ -99,14 +106,14 @@ async function fetchDownload(initial, fetch, signal) {
|
|
|
99
106
|
response = await fetch(url, { method: "GET", redirect: "manual", signal });
|
|
100
107
|
}
|
|
101
108
|
catch (cause) {
|
|
102
|
-
if (signal
|
|
109
|
+
if (isInterruption(cause, signal))
|
|
103
110
|
throw signal.reason;
|
|
104
111
|
throw new DamDownloadError(cause);
|
|
105
112
|
}
|
|
106
113
|
signal.throwIfAborted();
|
|
107
114
|
if (!redirectStatuses.has(response.status)) {
|
|
108
115
|
if (!response.ok || response.body === null)
|
|
109
|
-
throw new DamDownloadError();
|
|
116
|
+
throw new DamDownloadError(undefined, "http", response.status);
|
|
110
117
|
return response;
|
|
111
118
|
}
|
|
112
119
|
const location = response.headers.get("location");
|
|
@@ -115,8 +122,8 @@ async function fetchDownload(initial, fetch, signal) {
|
|
|
115
122
|
try {
|
|
116
123
|
url = safeDownloadUrl(new URL(location, url).href);
|
|
117
124
|
}
|
|
118
|
-
catch {
|
|
119
|
-
throw new DamDownloadError();
|
|
125
|
+
catch (cause) {
|
|
126
|
+
throw new DamDownloadError(cause, "redirect");
|
|
120
127
|
}
|
|
121
128
|
finally {
|
|
122
129
|
await response.body?.cancel().catch(() => undefined);
|
|
@@ -164,7 +171,7 @@ export function createDamFileDownloader(options = {}) {
|
|
|
164
171
|
const disposition = response.headers.get("content-disposition");
|
|
165
172
|
const filename = withIndex(safeFilename(disposition === null ? undefined : decodedFilename(disposition), fallback, format), index, input.urls.length);
|
|
166
173
|
const finalPath = resolve(outputDirectory, filename);
|
|
167
|
-
if (
|
|
174
|
+
if (dirname(finalPath) !== outputDirectory) {
|
|
168
175
|
throw new DamDownloadError();
|
|
169
176
|
}
|
|
170
177
|
const temporaryPath = resolve(outputDirectory, `.part-${dependencies.randomId()}-${index + 1}`);
|
|
@@ -205,7 +212,7 @@ export function createDamFileDownloader(options = {}) {
|
|
|
205
212
|
if (error instanceof DamDownloadDestinationExistsError)
|
|
206
213
|
throw error;
|
|
207
214
|
if (!isMissingFile(error))
|
|
208
|
-
throw new DamDownloadError();
|
|
215
|
+
throw new DamDownloadError(error, "destination");
|
|
209
216
|
}
|
|
210
217
|
}
|
|
211
218
|
for (const item of pending) {
|
|
@@ -214,8 +221,16 @@ export function createDamFileDownloader(options = {}) {
|
|
|
214
221
|
item.open = false;
|
|
215
222
|
}
|
|
216
223
|
for (const item of pending) {
|
|
217
|
-
|
|
224
|
+
try {
|
|
225
|
+
await dependencies.fileSystem.link(item.temporaryPath, item.finalPath);
|
|
226
|
+
}
|
|
227
|
+
catch (cause) {
|
|
228
|
+
if (cause instanceof Error && "code" in cause && cause.code === "EEXIST")
|
|
229
|
+
throw new DamDownloadDestinationExistsError();
|
|
230
|
+
throw new DamDownloadError(cause, "commit");
|
|
231
|
+
}
|
|
218
232
|
createdFinalPaths.push(item.finalPath);
|
|
233
|
+
await dependencies.fileSystem.rm(item.temporaryPath, { force: true });
|
|
219
234
|
}
|
|
220
235
|
return pending.map((item) => ({
|
|
221
236
|
path: item.finalPath,
|
|
@@ -224,18 +239,25 @@ export function createDamFileDownloader(options = {}) {
|
|
|
224
239
|
}));
|
|
225
240
|
}
|
|
226
241
|
catch (error) {
|
|
242
|
+
const remainingPaths = [];
|
|
243
|
+
const cleanupErrors = [];
|
|
227
244
|
await Promise.all(pending.map(async (item) => {
|
|
228
245
|
if (item.open)
|
|
229
|
-
await item.handle.close().catch(
|
|
230
|
-
await dependencies.fileSystem.rm(item.temporaryPath, { force: true }).catch(
|
|
246
|
+
await item.handle.close().catch(cause => { cleanupErrors.push(cause); });
|
|
247
|
+
await dependencies.fileSystem.rm(item.temporaryPath, { force: true }).catch(cause => {
|
|
248
|
+
remainingPaths.push(item.temporaryPath);
|
|
249
|
+
cleanupErrors.push(cause);
|
|
250
|
+
});
|
|
231
251
|
}));
|
|
232
|
-
await Promise.all(createdFinalPaths.map((path) => (dependencies.fileSystem.rm(path, { force: true }).catch(()
|
|
233
|
-
if (
|
|
252
|
+
await Promise.all(createdFinalPaths.map((path) => (dependencies.fileSystem.rm(path, { force: true }).catch(cause => { remainingPaths.push(path); cleanupErrors.push(cause); }))));
|
|
253
|
+
if (cleanupErrors.length)
|
|
254
|
+
throw new DamDownloadError(new AggregateError([error, ...cleanupErrors], "Download cleanup failed.", { cause: error }), "cleanup", undefined, remainingPaths);
|
|
255
|
+
if (isInterruption(error, input.signal))
|
|
234
256
|
throw input.signal.reason;
|
|
235
257
|
if (error instanceof DamDownloadDestinationExistsError
|
|
236
258
|
|| error instanceof DamDownloadError)
|
|
237
259
|
throw error;
|
|
238
|
-
throw new DamDownloadError();
|
|
260
|
+
throw new DamDownloadError(error, "write");
|
|
239
261
|
}
|
|
240
262
|
}
|
|
241
263
|
};
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { isInterruption } from "../../platform/interruption.js";
|
|
2
|
+
import { RemoteRequestError } from "../../platform/signed-http-transport.js";
|
|
1
3
|
import { createHmac } from "node:crypto";
|
|
2
4
|
import { createReadStream } from "node:fs";
|
|
3
5
|
import { stat } from "node:fs/promises";
|
|
@@ -16,8 +18,8 @@ function normalizeEndpoint(value) {
|
|
|
16
18
|
}
|
|
17
19
|
return url;
|
|
18
20
|
}
|
|
19
|
-
catch {
|
|
20
|
-
throw new ObjectStorageUploadError();
|
|
21
|
+
catch (error) {
|
|
22
|
+
throw new ObjectStorageUploadError(error);
|
|
21
23
|
}
|
|
22
24
|
}
|
|
23
25
|
function endpointOrigin(value) {
|
|
@@ -83,14 +85,19 @@ async function attemptOss(input, dependencies) {
|
|
|
83
85
|
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
84
86
|
input.signal.throwIfAborted();
|
|
85
87
|
try {
|
|
86
|
-
|
|
88
|
+
if (dependencies.telemetry)
|
|
89
|
+
await dependencies.telemetry.stage("upload.attempt", () => dependencies.putOss(input));
|
|
90
|
+
else
|
|
91
|
+
await dependencies.putOss(input);
|
|
87
92
|
input.signal.throwIfAborted();
|
|
88
93
|
return "success";
|
|
89
94
|
}
|
|
90
95
|
catch (error) {
|
|
91
|
-
if (input.signal
|
|
96
|
+
if (isInterruption(error, input.signal))
|
|
92
97
|
throw input.signal.reason;
|
|
93
|
-
|
|
98
|
+
dependencies.errors.push(error);
|
|
99
|
+
if (input.signal.aborted)
|
|
100
|
+
throw new ObjectStorageUploadError(error);
|
|
94
101
|
if (!input.authorizationV4 && isUnsupportedAuthorization(error)) {
|
|
95
102
|
return "unsupported-authorization";
|
|
96
103
|
}
|
|
@@ -148,12 +155,12 @@ async function uploadObs(input, dependencies) {
|
|
|
148
155
|
input.signal.throwIfAborted();
|
|
149
156
|
if (!response.ok) {
|
|
150
157
|
stream.destroy();
|
|
151
|
-
throw new ObjectStorageUploadError();
|
|
158
|
+
throw new ObjectStorageUploadError(new RemoteRequestError(response.status));
|
|
152
159
|
}
|
|
153
160
|
}
|
|
154
161
|
catch (error) {
|
|
155
162
|
stream.destroy();
|
|
156
|
-
if (input.signal
|
|
163
|
+
if (isInterruption(error, input.signal))
|
|
157
164
|
throw input.signal.reason;
|
|
158
165
|
if (error instanceof ObjectStorageUploadError)
|
|
159
166
|
throw error;
|
|
@@ -161,21 +168,26 @@ async function uploadObs(input, dependencies) {
|
|
|
161
168
|
}
|
|
162
169
|
}
|
|
163
170
|
export function createObjectStorageUploader(options = {}) {
|
|
164
|
-
const
|
|
171
|
+
const baseDependencies = {
|
|
165
172
|
putOss: options.putOss ?? defaultPutOss,
|
|
166
|
-
...(options.
|
|
173
|
+
...(options.telemetry ? { telemetry: options.telemetry } : {}),
|
|
167
174
|
fetch: options.fetch ?? globalThis.fetch,
|
|
168
175
|
sleep: options.sleep ?? sleepWithSignal,
|
|
169
176
|
now: options.now ?? (() => new Date())
|
|
170
177
|
};
|
|
171
178
|
return {
|
|
172
179
|
async upload(input) {
|
|
180
|
+
const dependencies = { ...baseDependencies, errors: [] };
|
|
173
181
|
input.signal.throwIfAborted();
|
|
174
182
|
const endpoints = endpointOrder(input.token);
|
|
175
183
|
if (endpoints.length === 0)
|
|
176
184
|
throw new ObjectStorageUploadError();
|
|
177
185
|
if (isHuaweiObs(endpoints[0])) {
|
|
178
|
-
|
|
186
|
+
const upload = () => uploadObs({ ...input, endpoint: endpoints[0] }, dependencies);
|
|
187
|
+
if (dependencies.telemetry)
|
|
188
|
+
await dependencies.telemetry.stage("upload.attempt", upload);
|
|
189
|
+
else
|
|
190
|
+
await upload();
|
|
179
191
|
return;
|
|
180
192
|
}
|
|
181
193
|
for (const endpoint of endpoints) {
|
|
@@ -189,7 +201,7 @@ export function createObjectStorageUploader(options = {}) {
|
|
|
189
201
|
if (v4 === "success")
|
|
190
202
|
return;
|
|
191
203
|
}
|
|
192
|
-
throw new ObjectStorageUploadError();
|
|
204
|
+
throw new ObjectStorageUploadError(new AggregateError(dependencies.errors, "Object storage attempts exhausted.", { cause: dependencies.errors.at(-1) }));
|
|
193
205
|
}
|
|
194
206
|
};
|
|
195
207
|
}
|