@insmind/cli 1.5.1 → 1.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/contracts/operations/auth.status/output.schema.json +3 -4
  2. package/dist/bin/insmind-cli.js +12 -7
  3. package/dist/bin/postinstall.js +7 -5
  4. package/dist/bin/{agent-worker.js → task-worker.js} +5 -4
  5. package/dist/src/analytics/device.js +23 -0
  6. package/dist/src/analytics/wind.js +54 -0
  7. package/dist/src/bootstrap/create-cli.js +33 -19
  8. package/dist/src/bootstrap/create-runtime.js +45 -16
  9. package/dist/src/bootstrap/{run-agent-worker.js → run-task-worker.js} +20 -10
  10. package/dist/src/bootstrap/validators.js +10 -5
  11. package/dist/src/cli/action-binding.js +14 -0
  12. package/dist/src/cli/agent-commands.js +9 -4
  13. package/dist/src/cli/auth-commands.js +5 -3
  14. package/dist/src/cli/credits-command.js +2 -2
  15. package/dist/src/cli/dam-commands.js +51 -52
  16. package/dist/src/cli/editor-commands.js +13 -15
  17. package/dist/src/cli/errors.js +97 -44
  18. package/dist/src/cli/model-commands.js +6 -4
  19. package/dist/src/cli/presenter.js +13 -10
  20. package/dist/src/cli/task-commands.js +13 -5
  21. package/dist/src/cli/tool-commands.js +11 -5
  22. package/dist/src/features/agent/use-cases.js +11 -5
  23. package/dist/src/features/auth/access-policy.js +2 -0
  24. package/dist/src/features/auth/credential-store.js +2 -2
  25. package/dist/src/features/auth/sso-service.js +5 -4
  26. package/dist/src/features/auth/state.js +11 -1
  27. package/dist/src/features/auth/use-cases.js +43 -40
  28. package/dist/src/features/credits/use-cases.js +2 -0
  29. package/dist/src/features/dam/file-downloader.js +38 -16
  30. package/dist/src/features/dam/object-storage.js +23 -11
  31. package/dist/src/features/dam/operation-executor.js +46 -37
  32. package/dist/src/features/dam/registered-uploader.js +39 -29
  33. package/dist/src/features/dam/storage-upload.js +5 -4
  34. package/dist/src/features/dam/use-cases.js +81 -60
  35. package/dist/src/features/editor/bridge-client.js +6 -6
  36. package/dist/src/features/editor/bridge-process.js +2 -1
  37. package/dist/src/features/editor/session-state.js +6 -4
  38. package/dist/src/features/editor/session.js +26 -8
  39. package/dist/src/features/editor/use-cases.js +10 -3
  40. package/dist/src/features/org/use-cases.js +2 -1
  41. package/dist/src/features/task/store.js +4 -0
  42. package/dist/src/features/task/{agent-background.js → task-background.js} +5 -4
  43. package/dist/src/features/task/use-cases.js +123 -28
  44. package/dist/src/features/tool/catalog.js +11 -5
  45. package/dist/src/features/tool/dynamic-schema.js +9 -7
  46. package/dist/src/features/tool/mns-catalog-adapter.js +1 -0
  47. package/dist/src/features/tool/tool-api-adapter.js +8 -7
  48. package/dist/src/features/tool/use-cases.js +8 -4
  49. package/dist/src/features/update/update-notification.js +75 -70
  50. package/dist/src/features/update/update-service.js +24 -20
  51. package/dist/src/platform/file-lock.js +36 -9
  52. package/dist/src/platform/interruption.js +13 -0
  53. package/dist/src/platform/json-input.js +12 -9
  54. package/dist/src/platform/local-json-file.js +8 -4
  55. package/dist/src/platform/redact.js +7 -1
  56. package/dist/src/platform/remote-protocol.js +2 -2
  57. package/dist/src/platform/safe-upload-file.js +2 -1
  58. package/dist/src/platform/schema-issues.js +8 -0
  59. package/dist/src/platform/signed-http-transport.js +8 -7
  60. package/dist/src/platform/text-output.js +33 -0
  61. package/dist/src/telemetry/invocation.js +19 -4
  62. package/dist/src/telemetry/process-errors.js +14 -4
  63. package/dist/src/telemetry/sanitize.js +4 -2
  64. package/dist/src/telemetry/sls-sink.js +36 -20
  65. package/dist/vendor/README.md +10 -0
  66. package/dist/vendor/gd-tracker-node.mjs +1175 -0
  67. package/package.json +4 -4
@@ -1,7 +1,9 @@
1
1
  export class AuthStateInvalidError extends Error {
2
+ reason;
2
3
  constructor(options) {
3
4
  super("本地登录状态无效。", options);
4
5
  this.name = "AuthStateInvalidError";
6
+ this.reason = options?.reason ?? "invalid_data";
5
7
  }
6
8
  }
7
9
  export function parseStoredAuthState(value) {
@@ -38,7 +40,7 @@ function parseVersionOne(value) {
38
40
  throw new Error("invalid account");
39
41
  result.account = {
40
42
  id: requiredString(value.account.id),
41
- name: requiredString(value.account.name)
43
+ name: optionalString(value.account.name) ?? requiredString(value.account.id)
42
44
  };
43
45
  }
44
46
  if (value.organization !== undefined) {
@@ -127,3 +129,11 @@ function legacyString(value) {
127
129
  function isRecord(value) {
128
130
  return typeof value === "object" && value !== null && !Array.isArray(value);
129
131
  }
132
+ export class UserIdentityMissingError extends Error {
133
+ constructor() { super("The login state has no valid user ID."); this.name = "UserIdentityMissingError"; }
134
+ }
135
+ export function requireUserIdentity(state) {
136
+ if (!state.account?.id.trim())
137
+ throw new UserIdentityMissingError();
138
+ return state.account;
139
+ }
@@ -1,3 +1,5 @@
1
+ import { isInterruption } from "../../platform/interruption.js";
2
+ import { requireUserIdentity, UserIdentityMissingError } from "./state.js";
1
3
  export class DeviceAuthorizationExpiredError extends Error {
2
4
  constructor(commandName = "gd-cli") {
3
5
  super(`Authorization expired. Run ${commandName} auth login again.`);
@@ -20,6 +22,7 @@ export function createAuthUseCases(dependencies) {
20
22
  logged_in: false,
21
23
  next_steps: [`${dependencies.commandName ?? "gd-cli"} auth login`]
22
24
  };
25
+ const account = await dependencies.telemetry.stage("identity", async () => requireUserIdentity(state));
23
26
  dependencies.telemetry.annotate({
24
27
  account_id: state.account?.id,
25
28
  organization_id: state.organization?.id
@@ -28,8 +31,8 @@ export function createAuthUseCases(dependencies) {
28
31
  return {
29
32
  logged_in: true,
30
33
  account: {
31
- user_id: state.account?.id ?? null,
32
- name: state.account?.name ?? null
34
+ user_id: account.id,
35
+ name: account.name
33
36
  },
34
37
  organization: !dependencies.requireOrganization && state.organization
35
38
  ? { id: state.organization.id, name: state.organization.name }
@@ -45,16 +48,19 @@ export function createAuthUseCases(dependencies) {
45
48
  ? []
46
49
  : state.organization
47
50
  ? []
48
- : ["gd-cli org list", "gd-cli org switch"]
51
+ : ["gd-cli org list", "gd-cli org switch --org <org-id>"]
49
52
  };
50
53
  },
51
54
  async logout() {
55
+ const state = await dependencies.telemetry.stage("state", () => dependencies.store.read()).catch(() => null);
56
+ if (state)
57
+ dependencies.telemetry.annotate({ account_id: state.account?.id, organization_id: state.organization?.id });
52
58
  await dependencies.telemetry.stage("state", () => dependencies.store.remove());
53
59
  },
54
60
  async login(input) {
55
61
  input.signal.throwIfAborted();
56
62
  const existing = await dependencies.telemetry.stage("state", () => dependencies.store.read());
57
- if (existing
63
+ if (existing?.account?.id.trim()
58
64
  && Date.parse(existing.credential.expiresAt) > dependencies.now().getTime()
59
65
  && (!dependencies.requireOrganization || existing.organization !== undefined)) {
60
66
  dependencies.telemetry.annotate({
@@ -107,56 +113,53 @@ export function createAuthUseCases(dependencies) {
107
113
  credential: token.credential,
108
114
  ...(token.account ? { account: token.account } : {})
109
115
  };
110
- if (!dependencies.requireOrganization) {
111
- await dependencies.telemetry.stage("state", () => dependencies.store.write(state));
112
- }
113
116
  dependencies.telemetry.annotate({ account_id: state.account?.id });
114
117
  let organizationId = token.organizationId;
115
- try {
116
- const identity = await dependencies.telemetry.stage("identity", () => (dependencies.sso.getIdentity(token.credential.accessKey, input.signal)));
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)
118
+ const identity = await dependencies.telemetry.stage("identity", async () => {
119
+ const identity = await dependencies.sso.getIdentity(token.credential.accessKey, input.signal);
120
+ if (!state.account?.id.trim() && !identity.account?.id.trim())
121
+ throw new UserIdentityMissingError();
122
+ return identity;
123
+ }).catch(cause => {
124
+ if (isInterruption(cause, input.signal))
128
125
  throw input.signal.reason;
126
+ if (!state.account?.id.trim())
127
+ throw cause;
128
+ return undefined;
129
+ });
130
+ organizationId = identity?.organizationId ?? organizationId;
131
+ if (!state.account && identity?.account) {
132
+ state = { ...state, account: identity.account };
133
+ dependencies.telemetry.annotate({ account_id: identity.account.id });
134
+ }
135
+ requireUserIdentity(state);
136
+ if (!dependencies.requireOrganization) {
137
+ await dependencies.telemetry.stage("state", () => dependencies.store.write(state));
129
138
  }
130
139
  if (!organizationId) {
131
140
  if (dependencies.requireOrganization)
132
141
  throw new AuthorizedAccountContextMissingError();
133
- input.interaction.warn("登录成功,请执行 gd-cli org switch 选择组织。");
142
+ input.interaction.warn("登录成功,请执行 gd-cli org list,再执行 gd-cli org switch --org <org-id> 选择组织。");
134
143
  return { status: "logged_in", organizationSelected: false };
135
144
  }
136
- try {
137
- const organization = await dependencies.telemetry.stage("bind", () => (dependencies.organizationBinder.bindAuthorizedOrganization({
138
- credential: token.credential,
139
- organizationId,
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)
145
+ const organization = await dependencies.telemetry.stage("bind", () => (dependencies.organizationBinder.bindAuthorizedOrganization({
146
+ credential: token.credential, organizationId, signal: input.signal
147
+ }))).catch(cause => {
148
+ if (isInterruption(cause, input.signal))
154
149
  throw input.signal.reason;
150
+ if (dependencies.requireOrganization)
151
+ throw cause;
152
+ return undefined;
153
+ });
154
+ if (!organization) {
155
155
  if (dependencies.requireOrganization)
156
156
  throw new AuthorizedAccountContextMissingError();
157
- input.interaction.warn("登录成功,但组织绑定失败;请执行 gd-cli org switch。");
157
+ input.interaction.warn("登录成功,但未能选择组织;请执行 gd-cli org list,再执行 gd-cli org switch --org <org-id>。");
158
158
  return { status: "logged_in", organizationSelected: false };
159
159
  }
160
+ dependencies.telemetry.annotate({ organization_id: organization.id });
161
+ await dependencies.telemetry.stage("state", () => dependencies.store.write({ ...state, organization }));
162
+ return { status: "logged_in", organizationSelected: true };
160
163
  }
161
164
  };
162
165
  }
@@ -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, rename, rm } from "node:fs/promises";
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
- constructor(cause) {
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
- rename,
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.aborted)
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 (!finalPath.startsWith(`${outputDirectory}/`) && finalPath !== outputDirectory) {
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
- await dependencies.fileSystem.rename(item.temporaryPath, item.finalPath);
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(() => undefined);
230
- await dependencies.fileSystem.rm(item.temporaryPath, { force: true }).catch(() => undefined);
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(() => undefined))));
233
- if (input.signal.aborted)
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
- await dependencies.putOss(input);
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.aborted)
96
+ if (isInterruption(error, input.signal))
92
97
  throw input.signal.reason;
93
- await dependencies.reportError?.(error).catch(() => undefined);
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.aborted)
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 dependencies = {
171
+ const baseDependencies = {
165
172
  putOss: options.putOss ?? defaultPutOss,
166
- ...(options.reportError ? { reportError: options.reportError } : {}),
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
- await uploadObs({ ...input, endpoint: endpoints[0] }, dependencies);
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
  }
@@ -7,9 +7,11 @@ export class DamOperationFailedError extends Error {
7
7
  }
8
8
  }
9
9
  export class DamOperationUnconfirmedError extends Error {
10
+ context;
10
11
  operation;
11
- constructor(operation) {
12
- super("DAM 操作已提交,但未能确认最终结果。");
12
+ constructor(operation, context = {}, cause) {
13
+ super(`DAM ${operation} was submitted; final outcome is unconfirmed (phase: ${String(context.phase ?? "verify")}).`, { cause });
14
+ this.context = context;
13
15
  this.name = "DamOperationUnconfirmedError";
14
16
  this.operation = operation;
15
17
  }
@@ -24,48 +26,55 @@ export function createDamOperationExecutor(dependencies) {
24
26
  input.signal.throwIfAborted();
25
27
  const startedAt = dependencies.now();
26
28
  const submission = await input.submit();
27
- input.signal.throwIfAborted();
28
29
  const taskId = submission.task_id;
29
- if (taskId === undefined) {
30
- const copied = input.operation === "copy"
31
- ? copiedEntryId(submission.result_ids)
32
- : undefined;
33
- return copied === undefined ? {} : { copied_entry_id: copied };
34
- }
35
- dependencies.annotate({ task_id: taskId });
36
- let delayMilliseconds = 1_000;
37
- const deadline = startedAt + 180_000;
38
- while (true) {
30
+ try {
39
31
  input.signal.throwIfAborted();
40
- if (dependencies.now() >= deadline) {
41
- throw new DamOperationUnconfirmedError(input.operation);
32
+ if (taskId === undefined) {
33
+ const copied = input.operation === "copy"
34
+ ? copiedEntryId(submission.result_ids)
35
+ : undefined;
36
+ return copied === undefined ? {} : { copied_entry_id: copied };
42
37
  }
43
- const task = await input.getTask(taskId, input.signal);
44
- input.signal.throwIfAborted();
45
- if (task === null)
46
- throw new DamOperationUnconfirmedError(input.operation);
47
- if (task.status === 2) {
48
- if (task.fail_count !== null && task.fail_count > 0) {
38
+ dependencies.annotate({ task_id: taskId });
39
+ let delayMilliseconds = 1_000;
40
+ const deadline = startedAt + 180_000;
41
+ while (true) {
42
+ input.signal.throwIfAborted();
43
+ if (dependencies.now() >= deadline) {
44
+ throw new DamOperationUnconfirmedError(input.operation);
45
+ }
46
+ const task = await input.getTask(taskId, input.signal);
47
+ input.signal.throwIfAborted();
48
+ if (task === null)
49
+ throw new DamOperationUnconfirmedError(input.operation);
50
+ if (task.status === 2) {
51
+ if (task.fail_count !== null && task.fail_count > 0) {
52
+ throw new DamOperationFailedError(input.operation);
53
+ }
54
+ if (input.operation !== "copy" || input.inspectResult === undefined)
55
+ return {};
56
+ const result = await input.inspectResult(taskId, input.signal);
57
+ input.signal.throwIfAborted();
58
+ const copied = copiedEntryId(result.result_ids);
59
+ return copied === undefined ? {} : { copied_entry_id: copied };
60
+ }
61
+ if (task.status === 3)
49
62
  throw new DamOperationFailedError(input.operation);
63
+ if (task.status !== 0 && task.status !== 1) {
64
+ throw new DamOperationUnconfirmedError(input.operation);
50
65
  }
51
- if (input.operation !== "copy" || input.inspectResult === undefined)
52
- return {};
53
- const result = await input.inspectResult(taskId, input.signal);
66
+ const remaining = deadline - dependencies.now();
67
+ if (remaining <= 0)
68
+ throw new DamOperationUnconfirmedError(input.operation);
69
+ await dependencies.sleep(Math.min(delayMilliseconds, remaining), input.signal);
54
70
  input.signal.throwIfAborted();
55
- const copied = copiedEntryId(result.result_ids);
56
- return copied === undefined ? {} : { copied_entry_id: copied };
71
+ delayMilliseconds = Math.min(delayMilliseconds + 500, 3_000);
57
72
  }
58
- if (task.status === 3)
59
- throw new DamOperationFailedError(input.operation);
60
- if (task.status !== 0 && task.status !== 1) {
61
- throw new DamOperationUnconfirmedError(input.operation);
62
- }
63
- const remaining = deadline - dependencies.now();
64
- if (remaining <= 0)
65
- throw new DamOperationUnconfirmedError(input.operation);
66
- await dependencies.sleep(Math.min(delayMilliseconds, remaining), input.signal);
67
- input.signal.throwIfAborted();
68
- delayMilliseconds = Math.min(delayMilliseconds + 500, 3_000);
73
+ }
74
+ catch (error) {
75
+ if (error instanceof DamOperationFailedError)
76
+ throw error;
77
+ throw new DamOperationUnconfirmedError(input.operation, { ...input.context, phase: "verify", accepted: true, ...(taskId ? { task_id: taskId } : {}) }, error);
69
78
  }
70
79
  }
71
80
  };
@@ -1,9 +1,11 @@
1
+ import { isInterruption } from "../../platform/interruption.js";
1
2
  import { createHash } from "node:crypto";
2
3
  import { createReadStream } from "node:fs";
3
4
  import { setTimeout as delay } from "node:timers/promises";
4
5
  import sharp from "sharp";
5
6
  import { RemoteRequestError } from "../../platform/signed-http-transport.js";
6
7
  import { projectDamAssetDetail } from "./asset-projection.js";
8
+ import { DamOperationUnconfirmedError } from "./operation-executor.js";
7
9
  const imageFormats = new Set([
8
10
  "png", "jpg", "jpeg", "gif", "svg", "webp", "jfif", "bmp", "tiff", "tif", "heic", "avif"
9
11
  ]);
@@ -58,7 +60,7 @@ async function hashes(filePath, signal) {
58
60
  return { md5: md5.digest("hex"), sha1: sha1.digest("hex") };
59
61
  }
60
62
  catch (error) {
61
- if (signal.aborted)
63
+ if (isInterruption(error, signal))
62
64
  throw signal.reason;
63
65
  throw error;
64
66
  }
@@ -77,7 +79,7 @@ async function defaultSleep(milliseconds, signal) {
77
79
  await delay(milliseconds, undefined, { signal });
78
80
  }
79
81
  catch (error) {
80
- if (signal.aborted)
82
+ if (isInterruption(error, signal))
81
83
  throw signal.reason;
82
84
  throw error;
83
85
  }
@@ -105,8 +107,8 @@ export function createDamRegisteredUploader(dependencies) {
105
107
  : {})
106
108
  };
107
109
  }
108
- catch {
109
- if (signal.aborted)
110
+ catch (error) {
111
+ if (isInterruption(error, signal))
110
112
  throw signal.reason;
111
113
  return {};
112
114
  }
@@ -119,11 +121,11 @@ export function createDamRegisteredUploader(dependencies) {
119
121
  return await run();
120
122
  }
121
123
  catch (error) {
122
- if (input.signal.aborted)
124
+ if (isInterruption(error, input.signal))
123
125
  throw input.signal.reason;
124
126
  if (error instanceof RemoteRequestError)
125
127
  throw error;
126
- throw new RemoteRequestError();
128
+ throw new RemoteRequestError(undefined, false, {}, error);
127
129
  }
128
130
  }));
129
131
  input.signal.throwIfAborted();
@@ -212,35 +214,43 @@ export function createDamRegisteredUploader(dependencies) {
212
214
  if (input.input.waitAnalysis !== true || terminalAnalysisStatus(latest.analysis_status)) {
213
215
  return latest;
214
216
  }
215
- return stage("wait", async () => {
216
- const deadline = now().getTime() + 180_000;
217
- while (true) {
218
- input.signal.throwIfAborted();
219
- const current = await dependencies.api.getBatchStatus({
220
- assetId: latest.asset_id,
221
- fallback: latest,
222
- access: input.access,
223
- signal: input.signal
224
- });
225
- if (current !== null)
226
- latest = current;
227
- if (terminalAnalysisStatus(latest.analysis_status))
228
- return latest;
229
- const remaining = deadline - now().getTime();
230
- if (remaining <= 0) {
231
- dependencies.warn("素材分析仍在处理中,已返回当前结果。");
232
- return latest;
217
+ try {
218
+ return await stage("wait", async () => {
219
+ const deadline = now().getTime() + 180_000;
220
+ while (true) {
221
+ input.signal.throwIfAborted();
222
+ const current = await dependencies.api.getBatchStatus({
223
+ assetId: latest.asset_id,
224
+ fallback: latest,
225
+ access: input.access,
226
+ signal: input.signal
227
+ });
228
+ if (current !== null)
229
+ latest = current;
230
+ if (terminalAnalysisStatus(latest.analysis_status))
231
+ return latest;
232
+ const remaining = deadline - now().getTime();
233
+ if (remaining <= 0) {
234
+ dependencies.warn(dependencies.analysisPendingMessage ?? "素材分析仍在处理中,已返回当前结果。");
235
+ return latest;
236
+ }
237
+ await sleep(Math.min(3000, remaining), input.signal);
233
238
  }
234
- await sleep(Math.min(3000, remaining), input.signal);
235
- }
236
- });
239
+ });
240
+ }
241
+ catch (error) {
242
+ throw new DamOperationUnconfirmedError("upload", { phase: "analysis", registered: true,
243
+ asset_id: latest.asset_id, repository_id: input.repository.id, folder_id: folderId }, error);
244
+ }
237
245
  }
238
246
  catch (error) {
239
- if (input.signal.aborted)
247
+ if (error instanceof DamOperationUnconfirmedError)
248
+ throw error;
249
+ if (isInterruption(error, input.signal))
240
250
  throw input.signal.reason;
241
251
  if (error instanceof RemoteRequestError)
242
252
  throw error;
243
- throw new RemoteRequestError();
253
+ throw new RemoteRequestError(undefined, false, {}, error);
244
254
  }
245
255
  }
246
256
  };
@@ -1,3 +1,4 @@
1
+ import { isInterruption } from "../../platform/interruption.js";
1
2
  import { RemoteRequestError } from "../../platform/signed-http-transport.js";
2
3
  import { inspectUploadFile } from "../../platform/safe-upload-file.js";
3
4
  function isRecord(value) {
@@ -110,11 +111,11 @@ export function createDamStorageUploader(dependencies) {
110
111
  url = publicAssetUrl(token);
111
112
  }
112
113
  catch (error) {
113
- if (signal.aborted)
114
+ if (isInterruption(error, signal))
114
115
  throw signal.reason;
115
116
  if (error instanceof RemoteRequestError)
116
117
  throw error;
117
- throw new RemoteRequestError();
118
+ throw new RemoteRequestError(undefined, false, {}, error);
118
119
  }
119
120
  try {
120
121
  await dependencies.storage.upload({
@@ -130,11 +131,11 @@ export function createDamStorageUploader(dependencies) {
130
131
  };
131
132
  }
132
133
  catch (error) {
133
- if (signal.aborted)
134
+ if (isInterruption(error, signal))
134
135
  throw signal.reason;
135
136
  if (error instanceof RemoteRequestError)
136
137
  throw error;
137
- throw new RemoteRequestError();
138
+ throw new RemoteRequestError(undefined, false, {}, error);
138
139
  }
139
140
  }
140
141
  };