@insmind/cli 1.8.0 → 1.9.1

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 (92) hide show
  1. package/contracts/operations/model.get/input.schema.json +5 -0
  2. package/contracts/operations/model.get/output.schema.json +9 -1
  3. package/contracts/operations/tool.call/canvas-input.schema.json +60 -0
  4. package/contracts/operations/tool.call/models/image-edit-smart.schema.json +39 -0
  5. package/contracts/operations/tool.call/models/image-edit-standard.schema.json +31 -0
  6. package/contracts/operations/tool.call/models/image-enhance-smart.schema.json +26 -0
  7. package/contracts/operations/tool.call/models/image-enhance-standard.schema.json +25 -0
  8. package/contracts/operations/tool.call/models/image-expand-smart.schema.json +72 -0
  9. package/contracts/operations/tool.call/models/image-expand-standard.schema.json +58 -0
  10. package/contracts/operations/tool.call/models/image-layers-layout.schema.json +20 -0
  11. package/contracts/operations/tool.call/models/image-layers-smart.schema.json +26 -0
  12. package/contracts/operations/tool.call/models/image-matting-smart.schema.json +34 -0
  13. package/contracts/operations/tool.call/models/image-matting-standard.schema.json +24 -0
  14. package/contracts/operations/tool.call/models/image-ocr.schema.json +20 -0
  15. package/contracts/operations/tool.call/models/image-remove-smart.schema.json +30 -0
  16. package/contracts/operations/tool.call/models/image-remove-standard.schema.json +25 -0
  17. package/contracts/operations/tool.call/models/image-text-edit.schema.json +43 -0
  18. package/contracts/operations/tool.call/models/image-vectorize.schema.json +20 -0
  19. package/contracts/operations/tool.call/models/video-edit-smart.schema.json +68 -0
  20. package/contracts/operations/tool.call/models/video-enhance-smart.schema.json +32 -0
  21. package/contracts/operations/tool.call/models/video-enhance-standard.schema.json +26 -0
  22. package/contracts/operations/tool.call/ocr-payload.schema.json +65 -0
  23. package/contracts/operations/tool.call/output.schema.json +38 -0
  24. package/contracts/operations/tool.call/template-payload.schema.json +95 -0
  25. package/dist/bin/insmind-cli.js +31 -24
  26. package/dist/bin/task-worker.js +4 -1
  27. package/dist/src/analytics/device.js +2 -2
  28. package/dist/src/bootstrap/create-cli.js +7 -0
  29. package/dist/src/bootstrap/create-runtime.js +53 -30
  30. package/dist/src/bootstrap/run-task-worker.js +5 -1
  31. package/dist/src/bootstrap/validators.js +11 -4
  32. package/dist/src/cli/agent-commands.js +1 -0
  33. package/dist/src/cli/dam-commands.js +3 -3
  34. package/dist/src/cli/errors.js +63 -15
  35. package/dist/src/cli/model-commands.js +6 -3
  36. package/dist/src/cli/observed-errors.js +3 -1
  37. package/dist/src/cli/tool-commands.js +2 -0
  38. package/dist/src/contracts/schema.js +4 -1
  39. package/dist/src/features/agent/creative-agent-adapter.js +37 -11
  40. package/dist/src/features/agent/creative-protocol.js +31 -10
  41. package/dist/src/features/agent/creative-stream.js +54 -6
  42. package/dist/src/features/agent/resource-authorizer.js +1 -0
  43. package/dist/src/features/agent/result-reader.js +3 -1
  44. package/dist/src/features/agent/use-cases.js +15 -5
  45. package/dist/src/features/auth/credential-store.js +6 -10
  46. package/dist/src/features/auth/sso-service.js +22 -6
  47. package/dist/src/features/auth/state.js +6 -0
  48. package/dist/src/features/auth/use-cases.js +90 -32
  49. package/dist/src/features/dam/asset-projection.js +10 -1
  50. package/dist/src/features/dam/dam-api-adapter.js +30 -15
  51. package/dist/src/features/dam/input.js +23 -0
  52. package/dist/src/features/dam/use-cases.js +32 -22
  53. package/dist/src/features/task/store.js +5 -5
  54. package/dist/src/features/task/task-background.js +67 -19
  55. package/dist/src/features/task/use-cases.js +38 -9
  56. package/dist/src/features/tool/canvas-copy.js +61 -0
  57. package/dist/src/features/tool/canvas-media.js +248 -0
  58. package/dist/src/features/tool/canvas-models.js +109 -0
  59. package/dist/src/features/tool/canvas-pricing.js +81 -0
  60. package/dist/src/features/tool/canvas-recovery.js +68 -0
  61. package/dist/src/features/tool/canvas-results.js +144 -0
  62. package/dist/src/features/tool/canvas-tool-adapter.js +366 -0
  63. package/dist/src/features/tool/canvas-video.js +84 -0
  64. package/dist/src/features/tool/catalog.js +35 -13
  65. package/dist/src/features/tool/dynamic-schema.js +55 -25
  66. package/dist/src/features/tool/matting-billing.js +115 -0
  67. package/dist/src/features/tool/mns-catalog-adapter.js +66 -19
  68. package/dist/src/features/tool/resource-authorizer.js +34 -0
  69. package/dist/src/features/tool/scene-catalog-adapter.js +35 -0
  70. package/dist/src/features/tool/tool-api-adapter.js +29 -17
  71. package/dist/src/features/tool/use-cases.js +28 -3
  72. package/dist/src/platform/file-lock.js +58 -15
  73. package/dist/src/platform/input-uri.js +105 -0
  74. package/dist/src/platform/local-json-file.js +7 -4
  75. package/dist/src/platform/remote-error-evidence.js +23 -1
  76. package/dist/src/platform/safe-upload-file.js +18 -4
  77. package/dist/src/platform/schema-issues.js +18 -0
  78. package/dist/src/platform/signed-http-transport.js +77 -16
  79. package/dist/src/platform/text-output.js +55 -13
  80. package/dist/src/product/config.js +12 -1
  81. package/dist/src/telemetry/failure-summary.js +53 -2
  82. package/dist/src/telemetry/host-diagnostics.js +95 -0
  83. package/dist/src/telemetry/invocation.js +24 -3
  84. package/dist/src/telemetry/process-errors.js +2 -1
  85. package/dist/src/telemetry/sls-sink.js +66 -18
  86. package/package.json +5 -4
  87. package/skills/insmind-cli/SKILL.md +2 -0
  88. package/skills/insmind-cli/references/creation.md +2 -0
  89. package/skills/insmind-cli/references/generation-constraints.md +3 -1
  90. package/skills/insmind-cli/references/matting.md +29 -0
  91. package/skills/insmind-cli/references/media-tools.md +40 -0
  92. package/skills/insmind-cli/references/tool.md +1 -1
@@ -35,6 +35,15 @@ export function createSsoService(options) {
35
35
  if (!baseUrl.pathname.endsWith("/"))
36
36
  baseUrl.pathname += "/";
37
37
  const requests = new WeakMap();
38
+ const requestStartedAt = new WeakMap();
39
+ function responseDiagnostics(response) {
40
+ const requestId = ["x-request-id", "x-gd-request-id", "request-id"].map(key => response.headers.get(key))
41
+ .find((value) => value !== null && /^[A-Za-z0-9_.:-]{1,128}$/u.test(value));
42
+ const startedAt = requestStartedAt.get(response);
43
+ return { requestTimeoutMs: options.timeoutMs ?? 30_000,
44
+ ...(startedAt === undefined ? {} : { requestDurationMs: Math.max(0, Date.now() - startedAt) }),
45
+ ...(requestId ? { requestId } : {}) };
46
+ }
38
47
  async function responseError(response, networkError) {
39
48
  let evidence = {};
40
49
  if (!response.ok && !response.bodyUsed) {
@@ -51,16 +60,16 @@ export function createSsoService(options) {
51
60
  ...remoteErrorEvidence({ request: requests.get(response),
52
61
  ...(evidence.remoteBody === undefined ? {} : { response: evidence.remoteBody }),
53
62
  ...(networkError === undefined ? {} : { network: networkFailure(networkError) }) })
54
- }, networkError);
63
+ }, networkError, responseDiagnostics(response));
55
64
  }
56
65
  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(",") });
66
+ return new SsoRequestError(response.status, { diagnosticReason: "SSO_RESPONSE_FIELDS_MISSING" }, undefined, { ...responseDiagnostics(response), ssoPhase: phase, ssoInvalidFields: Object.entries(fields).filter(([, valid]) => !valid).map(([key]) => key).join(",") });
58
67
  }
59
68
  async function responseRecord(response) {
60
69
  if (!response.ok) {
61
- // OAuth pending/slow_down are normal token polling responses.
70
+ // OAuth polling states can use HTTP 400 as well as HTTP 200.
62
71
  const body = await response.clone().json().catch(() => undefined);
63
- if (isRecord(body) && ["authorization_pending", "slow_down"].includes(String(body.error).toLowerCase()))
72
+ if (isRecord(body) && ["authorization_pending", "slow_down", "expired_token"].includes(String(body.error).toLowerCase()))
64
73
  return body;
65
74
  throw await responseError(response);
66
75
  }
@@ -78,22 +87,27 @@ export function createSsoService(options) {
78
87
  signal.throwIfAborted();
79
88
  const url = new URL(relativeUrl, baseUrl);
80
89
  const requestInfo = { method, path: url.pathname };
90
+ const startedAt = Date.now();
91
+ const timeoutMs = options.timeoutMs ?? 30_000;
92
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
81
93
  try {
82
94
  const response = await options.fetch(url, {
83
95
  method,
84
96
  headers: { Accept: "application/json", ...(options.traceparent ? { traceparent: options.traceparent() } : {}) },
85
97
  signal: AbortSignal.any([
86
98
  signal,
87
- AbortSignal.timeout(options.timeoutMs ?? 30_000)
99
+ timeoutSignal
88
100
  ])
89
101
  });
90
102
  requests.set(response, requestInfo);
103
+ requestStartedAt.set(response, startedAt);
91
104
  return response;
92
105
  }
93
106
  catch (error) {
94
107
  if (isInterruption(error, signal))
95
108
  throw signal.reason;
96
- throw new SsoRequestError(undefined, remoteErrorEvidence({ request: requestInfo, network: networkFailure(error) }), error);
109
+ throw new SsoRequestError(undefined, remoteErrorEvidence({ request: requestInfo, network: networkFailure(error) }), error, { requestTimeoutMs: timeoutMs, requestDurationMs: Math.max(0, Date.now() - startedAt),
110
+ abortSource: timeoutSignal.aborted ? "request_timeout" : "none" });
97
111
  }
98
112
  }
99
113
  return {
@@ -126,6 +140,8 @@ export function createSsoService(options) {
126
140
  return { status: "pending" };
127
141
  if (error === "slow_down")
128
142
  return { status: "slow_down" };
143
+ if (error === "expired_token")
144
+ return { status: "expired", httpStatus: response.status };
129
145
  if (!response.ok)
130
146
  throw await responseError(response);
131
147
  const accessKey = nonEmptyString(body.ak);
@@ -6,6 +6,12 @@ export class AuthStateInvalidError extends Error {
6
6
  this.reason = options?.reason ?? "invalid_data";
7
7
  }
8
8
  }
9
+ export class AuthStateUnavailableError extends Error {
10
+ constructor(options) {
11
+ super("无法访问本地登录状态,登录有效性未知。", options);
12
+ this.name = "AuthStateUnavailableError";
13
+ }
14
+ }
9
15
  export function parseStoredAuthState(value) {
10
16
  try {
11
17
  if (!isRecord(value))
@@ -1,8 +1,13 @@
1
1
  import { isInterruption } from "../../platform/interruption.js";
2
2
  import { requireUserIdentity, UserIdentityMissingError } from "./state.js";
3
+ const AUTHORIZATION_WAIT_TIMEOUT_MS = 10 * 60 * 1000;
3
4
  export class DeviceAuthorizationExpiredError extends Error {
4
- constructor(commandName = "gd-cli") {
5
+ expirationSource;
6
+ httpStatus;
7
+ constructor(commandName = "gd-cli", expirationSource = "cli_timeout", httpStatus) {
5
8
  super(`Authorization expired. Run ${commandName} auth login again.`);
9
+ this.expirationSource = expirationSource;
10
+ this.httpStatus = httpStatus;
6
11
  this.name = "DeviceAuthorizationExpiredError";
7
12
  }
8
13
  }
@@ -78,44 +83,97 @@ export function createAuthUseCases(dependencies) {
78
83
  organizationSelected: existing.organization !== undefined
79
84
  };
80
85
  }
86
+ const authorizationStartedAt = dependencies.now().getTime();
87
+ const deadline = authorizationStartedAt + AUTHORIZATION_WAIT_TIMEOUT_MS;
88
+ const deadlineController = new AbortController();
89
+ const authorizationSignal = AbortSignal.any([input.signal, deadlineController.signal]);
90
+ const deadlineTimer = setTimeout(() => deadlineController.abort(new DeviceAuthorizationExpiredError(dependencies.commandName)), AUTHORIZATION_WAIT_TIMEOUT_MS);
91
+ const withinAuthorization = (run) => {
92
+ if (dependencies.now().getTime() >= deadline)
93
+ return Promise.reject(new DeviceAuthorizationExpiredError(dependencies.commandName));
94
+ if (authorizationSignal.aborted)
95
+ return Promise.reject(authorizationSignal.reason);
96
+ return new Promise((resolve, reject) => {
97
+ const abort = () => reject(authorizationSignal.reason);
98
+ authorizationSignal.addEventListener("abort", abort, { once: true });
99
+ Promise.resolve().then(() => { authorizationSignal.throwIfAborted(); return run(); }).then(result => {
100
+ if (dependencies.now().getTime() > deadline)
101
+ reject(new DeviceAuthorizationExpiredError(dependencies.commandName));
102
+ else
103
+ resolve(result);
104
+ }, reject).finally(() => authorizationSignal.removeEventListener("abort", abort));
105
+ });
106
+ };
107
+ let pollCount = 0;
108
+ dependencies.telemetry.annotate({ auth_started_at_ms: authorizationStartedAt,
109
+ auth_wait_timeout_ms: AUTHORIZATION_WAIT_TIMEOUT_MS, auth_deadline_at_ms: deadline });
110
+ const recordResult = (result) => {
111
+ clearTimeout(deadlineTimer);
112
+ dependencies.telemetry.annotate({ auth_result: result,
113
+ auth_elapsed_ms: Math.max(0, dependencies.now().getTime() - authorizationStartedAt), auth_poll_count: pollCount });
114
+ };
115
+ const recordFailure = (cause) => {
116
+ recordResult(isInterruption(cause, input.signal) ? "interrupted"
117
+ : cause instanceof DeviceAuthorizationExpiredError ? cause.expirationSource : "failed");
118
+ throw cause;
119
+ };
81
120
  const authorization = await dependencies.telemetry.stage("authorize", async () => {
82
- const authorization = await dependencies.sso.startDeviceAuthorization(input.signal);
83
- const authorizationUrl = new URL("/cli/device-authorization", dependencies.authPageOrigin);
84
- authorizationUrl.searchParams.set("code", authorization.authorizeCode);
85
- await input.interaction.showAuthorization(authorizationUrl);
86
- if (!input.noBrowser) {
87
- try {
88
- await dependencies.telemetry.stage("browser", () => input.interaction.openBrowser(authorizationUrl));
89
- }
90
- catch (cause) {
91
- if (isInterruption(cause, input.signal))
92
- throw input.signal.reason;
93
- if (input.requireBrowser)
94
- throw new BrowserOpenError(cause);
95
- input.interaction.warn(insmind
96
- ? "Could not open the browser. Open the authorization URL manually."
97
- : "无法自动打开浏览器,请手动访问授权链接。");
121
+ try {
122
+ const authorization = await withinAuthorization(() => dependencies.sso.startDeviceAuthorization(authorizationSignal));
123
+ dependencies.telemetry.annotate({ auth_server_expires_in_s: authorization.expiresInSeconds });
124
+ const authorizationUrl = new URL("/cli/device-authorization", dependencies.authPageOrigin);
125
+ authorizationUrl.searchParams.set("code", authorization.authorizeCode);
126
+ await withinAuthorization(() => input.interaction.showAuthorization(authorizationUrl));
127
+ if (!input.noBrowser) {
128
+ try {
129
+ await dependencies.telemetry.stage("browser", () => withinAuthorization(() => input.interaction.openBrowser(authorizationUrl)));
130
+ }
131
+ catch (cause) {
132
+ if (isInterruption(cause, input.signal))
133
+ throw input.signal.reason;
134
+ if (cause instanceof DeviceAuthorizationExpiredError)
135
+ throw cause;
136
+ if (input.requireBrowser)
137
+ throw new BrowserOpenError(cause);
138
+ input.interaction.warn(insmind
139
+ ? "Could not open the browser. Open the authorization URL manually."
140
+ : "无法自动打开浏览器,请手动访问授权链接。");
141
+ }
98
142
  }
143
+ return authorization;
144
+ }
145
+ catch (cause) {
146
+ return recordFailure(cause);
99
147
  }
100
- return authorization;
101
148
  });
102
- const deadline = dependencies.now().getTime() + authorization.expiresInSeconds * 1000;
103
149
  let interval = authorization.intervalSeconds * 1000;
104
150
  const token = await dependencies.telemetry.stage("wait", async () => {
105
- while (true) {
106
- if (dependencies.now().getTime() + interval > deadline) {
107
- throw new DeviceAuthorizationExpiredError(dependencies.commandName);
151
+ try {
152
+ while (dependencies.now().getTime() < deadline) {
153
+ const remaining = deadline - dependencies.now().getTime();
154
+ await withinAuthorization(() => dependencies.sleep(Math.min(interval, remaining), authorizationSignal));
155
+ input.signal.throwIfAborted();
156
+ // Wait through the deadline without polling faster than the server permits.
157
+ if (remaining < interval || dependencies.now().getTime() >= deadline)
158
+ break;
159
+ pollCount += 1;
160
+ const result = await withinAuthorization(() => dependencies.sso.pollDeviceToken(authorization.deviceCode, authorizationSignal));
161
+ if (result.status === "pending")
162
+ continue;
163
+ if (result.status === "slow_down") {
164
+ interval += 5_000;
165
+ continue;
166
+ }
167
+ if (result.status === "expired") {
168
+ throw new DeviceAuthorizationExpiredError(dependencies.commandName, "server_expired", result.httpStatus);
169
+ }
170
+ recordResult("authorized");
171
+ return result;
108
172
  }
109
- await dependencies.sleep(interval, input.signal);
110
- input.signal.throwIfAborted();
111
- const result = await dependencies.sso.pollDeviceToken(authorization.deviceCode, input.signal);
112
- if (result.status === "pending")
113
- continue;
114
- if (result.status === "slow_down") {
115
- interval += 5_000;
116
- continue;
117
- }
118
- return result;
173
+ throw new DeviceAuthorizationExpiredError(dependencies.commandName);
174
+ }
175
+ catch (cause) {
176
+ return recordFailure(cause);
119
177
  }
120
178
  });
121
179
  let state = {
@@ -1,5 +1,10 @@
1
1
  import { isSensitiveKey } from "../../platform/redact.js";
2
2
  import { parseSafeRemoteAssetUrl } from "../../platform/url-safety.js";
3
+ const sourcePresence = new WeakMap();
4
+ /** Internal presence evidence survives public URL safety filtering without exposing the URL. */
5
+ export function damAssetSourcePresent(asset) {
6
+ return sourcePresence.get(asset) ?? (typeof asset.url === "string" && asset.url.trim() !== "");
7
+ }
3
8
  const publicAssetTypes = new Set([
4
9
  "image",
5
10
  "video",
@@ -230,7 +235,7 @@ export function projectDamAssetDetail(value, fallback) {
230
235
  const asset = normalizeAsset(value, fallback);
231
236
  if (asset === undefined)
232
237
  return undefined;
233
- return compact({
238
+ const result = compact({
234
239
  asset_id: asset.asset_id,
235
240
  title: asset.title,
236
241
  description: asset.description,
@@ -251,6 +256,10 @@ export function projectDamAssetDetail(value, fallback) {
251
256
  created_at: asset.created_at,
252
257
  updated_at: asset.updated_at
253
258
  });
259
+ const item = findAssetRecord(value);
260
+ const origin = record(item?.origin_info) ?? record(item?.originInfo);
261
+ sourcePresence.set(result, [origin?.url, item?.origin_url, item?.url].some(value => nonblank(value) !== undefined));
262
+ return result;
254
263
  }
255
264
  export function projectDamAssetSummary(value) {
256
265
  const asset = normalizeAsset(value);
@@ -2,6 +2,7 @@ import { RemoteRequestError } from "../../platform/signed-http-transport.js";
2
2
  import { RemoteProtocolError } from "../../platform/remote-protocol.js";
3
3
  import { parseSafeRemoteAssetUrl, UrlSafetyError } from "../../platform/url-safety.js";
4
4
  import { projectDamAssetDetail, projectDamAssetSummary } from "./asset-projection.js";
5
+ import { normalizeDamAssetId } from "./input.js";
5
6
  export class DamAssetNotFoundError extends Error {
6
7
  constructor() {
7
8
  super("DAM 素材不存在。");
@@ -9,9 +10,13 @@ export class DamAssetNotFoundError extends Error {
9
10
  }
10
11
  }
11
12
  export class DamAssetNotDownloadableError extends Error {
13
+ diagnosticSummary;
14
+ status;
12
15
  diagnosticReason = "ASSET_DOWNLOAD_URL_MISSING";
13
- constructor() {
16
+ constructor(diagnosticSummary = {}, status) {
14
17
  super("该 DAM 素材当前不可下载。");
18
+ this.diagnosticSummary = diagnosticSummary;
19
+ this.status = status;
15
20
  this.name = "DamAssetNotDownloadableError";
16
21
  }
17
22
  }
@@ -128,13 +133,17 @@ function tagRows(value) {
128
133
  }];
129
134
  });
130
135
  }
131
- function downloadUrls(value) {
136
+ function downloadUrls(value, headers, status) {
132
137
  if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) {
133
138
  throw new RemoteProtocolError();
134
139
  }
135
140
  const urls = value.filter((item) => (typeof item === "string" && item.trim() !== ""));
136
- if (urls.length === 0)
137
- throw new DamAssetNotDownloadableError();
141
+ if (urls.length === 0) {
142
+ const requestId = ["x-request-id", "x-gd-request-id", "request-id"]
143
+ .map(name => headers.get(name)).find((value) => value !== null && /^[A-Za-z0-9._:-]{1,128}$/u.test(value));
144
+ throw new DamAssetNotDownloadableError({ downloadPhase: "url_lookup", downloadUrlCount: 0,
145
+ ...(requestId === undefined ? {} : { requestId }) }, status);
146
+ }
138
147
  for (const value of urls) {
139
148
  try {
140
149
  const url = parseSafeRemoteAssetUrl(value);
@@ -346,7 +355,7 @@ function requestContext(input) {
346
355
  function recycleBody(input) {
347
356
  return {
348
357
  repository_id: input.repositoryId,
349
- file_ids: [input.assetId],
358
+ file_ids: [normalizeDamAssetId(input.assetId)],
350
359
  folder_ids: []
351
360
  };
352
361
  }
@@ -418,12 +427,13 @@ export function createDamApiAdapter(dependencies) {
418
427
  return { repository_id: input.repositoryId, tags: tagRows(response) };
419
428
  },
420
429
  async getDownloadUrls(input) {
421
- const response = await dependencies.transport.getJson({
422
- path: `/dam/asset/files/download/${encodeURIComponent(input.assetId)}/url-list`,
430
+ const assetId = normalizeDamAssetId(input.assetId);
431
+ const response = await dependencies.transport.getJsonResponse({
432
+ path: `/dam/asset/files/download/${encodeURIComponent(assetId)}/url-list`,
423
433
  query: { repository_id: input.repositoryId },
424
434
  ...requestContext(input)
425
435
  });
426
- return downloadUrls(response);
436
+ return downloadUrls(response.body, response.headers, response.status);
427
437
  },
428
438
  async getFolder(input) {
429
439
  let response;
@@ -443,12 +453,13 @@ export function createDamApiAdapter(dependencies) {
443
453
  return folderDetail(response);
444
454
  },
445
455
  async renameEntry(input) {
456
+ const entryId = input.kind === "asset" ? normalizeDamAssetId(input.entryId, "entry_id") : input.entryId;
446
457
  await dependencies.transport.putJson({
447
458
  path: input.kind === "asset"
448
- ? `/dam/asset/${encodeURIComponent(input.entryId)}/rename`
459
+ ? `/dam/asset/${encodeURIComponent(entryId)}/rename`
449
460
  : `/dam/folders/${encodeURIComponent(input.entryId)}/rename`,
450
461
  body: {
451
- id: input.entryId,
462
+ id: entryId,
452
463
  repository_id: input.repositoryId,
453
464
  title: input.title
454
465
  },
@@ -458,11 +469,12 @@ export function createDamApiAdapter(dependencies) {
458
469
  async submitEntryOperation(input) {
459
470
  assertSingleOperationInput(input);
460
471
  const asset = input.kind === "asset";
472
+ const entryId = asset ? normalizeDamAssetId(input.entryId, "entry_id") : input.entryId;
461
473
  const body = asset
462
474
  ? {
463
475
  source_infos: [{
464
476
  source_repository_id: input.sourceRepositoryId,
465
- content_ids: [input.entryId]
477
+ content_ids: [entryId]
466
478
  }],
467
479
  target_folder_id: input.targetFolderId,
468
480
  target_repository_id: input.targetRepositoryId,
@@ -500,10 +512,11 @@ export function createDamApiAdapter(dependencies) {
500
512
  return operationChildren(response);
501
513
  },
502
514
  async getAsset(input) {
515
+ const assetId = normalizeDamAssetId(input.assetId);
503
516
  let response;
504
517
  try {
505
518
  response = await dependencies.transport.getJson({
506
- path: `/dam/asset/${encodeURIComponent(input.assetId)}`,
519
+ path: `/dam/asset/${encodeURIComponent(assetId)}`,
507
520
  ...requestContext(input)
508
521
  });
509
522
  }
@@ -513,7 +526,7 @@ export function createDamApiAdapter(dependencies) {
513
526
  }
514
527
  throw error;
515
528
  }
516
- const asset = projectDamAssetDetail(response, input.assetId);
529
+ const asset = projectDamAssetDetail(response, assetId);
517
530
  if (asset === undefined)
518
531
  throw new RemoteRequestError();
519
532
  return asset;
@@ -527,9 +540,10 @@ export function createDamApiAdapter(dependencies) {
527
540
  return assetId(response);
528
541
  },
529
542
  async createMaterial(input) {
543
+ const body = { ...input.body, asset_info: { ...input.body.asset_info, id: normalizeDamAssetId(input.body.asset_info.id) } };
530
544
  const response = await dependencies.transport.postJson({
531
545
  path: "/dam/asset/createMaterial",
532
- body: input.body,
546
+ body,
533
547
  ...requestContext(input)
534
548
  });
535
549
  const asset = projectDamAssetDetail(response, input.fallback);
@@ -538,9 +552,10 @@ export function createDamApiAdapter(dependencies) {
538
552
  return asset;
539
553
  },
540
554
  async getBatchStatus(input) {
555
+ const assetId = normalizeDamAssetId(input.assetId);
541
556
  const response = await dependencies.transport.getJson({
542
557
  path: "/dam/asset/batch-status",
543
- query: { ids: input.assetId },
558
+ query: { ids: assetId },
544
559
  ...requestContext(input)
545
560
  });
546
561
  return projectDamAssetDetail(response, input.fallback) ?? null;
@@ -0,0 +1,23 @@
1
+ export class DamInputError extends Error {
2
+ reason;
3
+ field;
4
+ diagnosticSummary;
5
+ constructor(reason = "invalid_value", field) {
6
+ super("DAM 输入不可用。");
7
+ this.reason = reason;
8
+ this.field = field;
9
+ this.name = "DamInputError";
10
+ this.diagnosticSummary = { inputReason: reason, ...(field ? { inputField: `/${field}` } : {}) };
11
+ }
12
+ }
13
+ /** Only machine identifiers tolerate pasted line endings; filenames and text do not. */
14
+ export function normalizeDamAssetId(value, field = "asset_id") {
15
+ if (typeof value !== "string")
16
+ throw new DamInputError("id_required_not_url", field);
17
+ const id = value.replace(/^[ \r\n]+|[ \r\n]+$/gu, "");
18
+ if (/[\u0000-\u001f\u007f-\u009f]/u.test(id))
19
+ throw new DamInputError("identifier_control_character", field);
20
+ if (id.trim() === "" || /^https?:\/\//iu.test(id))
21
+ throw new DamInputError("id_required_not_url", field);
22
+ return id;
23
+ }
@@ -1,16 +1,10 @@
1
1
  import { resolve } from "node:path";
2
2
  import { pathToFileURL } from "node:url";
3
+ import { DamAssetNotDownloadableError } from "./dam-api-adapter.js";
4
+ import { DamInputError, normalizeDamAssetId } from "./input.js";
5
+ import { damAssetSourcePresent } from "./asset-projection.js";
3
6
  import { DamOperationUnconfirmedError } from "./operation-executor.js";
4
- export class DamInputError extends Error {
5
- reason;
6
- field;
7
- constructor(reason = "invalid_value", field) {
8
- super("DAM 输入不可用。");
9
- this.reason = reason;
10
- this.field = field;
11
- this.name = "DamInputError";
12
- }
13
- }
7
+ export { DamInputError } from "./input.js";
14
8
  export class DamRepositoryNotFoundError extends Error {
15
9
  constructor() {
16
10
  super("当前组织没有可用的 DAM 资源库。");
@@ -37,8 +31,7 @@ function assertOptionalNonblank(value, field) {
37
31
  invalid("nonblank", field);
38
32
  }
39
33
  function assertAssetId(value, field = "asset_id") {
40
- if (value.trim() === "" || /^https?:\/\//iu.test(value))
41
- invalid("id_required_not_url", field);
34
+ normalizeDamAssetId(value, field);
42
35
  }
43
36
  function assertRepositorySelection(input) {
44
37
  if (input.repositoryId !== undefined && !nonblank(input.repositoryId))
@@ -275,7 +268,7 @@ export function createDamUseCases(dependencies) {
275
268
  },
276
269
  async download({ input, access, signal }) {
277
270
  signal.throwIfAborted();
278
- assertAssetId(input.asset_id);
271
+ input = { ...input, asset_id: normalizeDamAssetId(input.asset_id) };
279
272
  assertOptionalNonblank(input.outputDir, "outputDir");
280
273
  const [repository] = await dependencies.telemetry.stage("repository", () => (resolveRepositories({
281
274
  ...(input.repositoryId === undefined ? {} : { repositoryId: input.repositoryId })
@@ -284,12 +277,27 @@ export function createDamUseCases(dependencies) {
284
277
  throw new DamRepositoryNotFoundError();
285
278
  const detail = await dependencies.telemetry.stage("resolve", () => (dependencies.api.getAsset({ assetId: input.asset_id, access, signal })));
286
279
  signal.throwIfAborted();
287
- const urls = await dependencies.telemetry.stage("download", () => (dependencies.api.getDownloadUrls({
288
- assetId: input.asset_id,
289
- repositoryId: repository.id,
290
- access,
291
- signal
292
- })));
280
+ const urls = await dependencies.telemetry.stage("download", async () => {
281
+ try {
282
+ const urls = await dependencies.api.getDownloadUrls({ assetId: input.asset_id, repositoryId: repository.id, access, signal });
283
+ if (!urls.some(url => url.trim() !== ""))
284
+ throw new DamAssetNotDownloadableError({ downloadUrlCount: 0 });
285
+ return urls;
286
+ }
287
+ catch (error) {
288
+ if (error instanceof Error) {
289
+ const existing = "diagnosticSummary" in error && error.diagnosticSummary && typeof error.diagnosticSummary === "object" ? error.diagnosticSummary : {};
290
+ Object.assign(error, { diagnosticSummary: {
291
+ ...existing, downloadPhase: "url_lookup", assetType: detail.type ?? "unknown",
292
+ ...(detail.format && /^[A-Za-z0-9][A-Za-z0-9.+_-]{0,31}$/u.test(detail.format) ? { assetFormat: detail.format } : {}),
293
+ assetSourcePresent: damAssetSourcePresent(detail),
294
+ ...(/^[A-Za-z0-9._:-]{1,128}$/u.test(repository.id) ? { selectedRepositoryId: repository.id } : {}),
295
+ ...(detail.repository_id && /^[A-Za-z0-9._:-]{1,128}$/u.test(detail.repository_id) ? { actualRepositoryId: detail.repository_id } : {})
296
+ } });
297
+ }
298
+ throw error;
299
+ }
300
+ });
293
301
  signal.throwIfAborted();
294
302
  const files = await dependencies.telemetry.stage("persist", () => (dependencies.downloader.download({
295
303
  urls,
@@ -305,7 +313,7 @@ export function createDamUseCases(dependencies) {
305
313
  },
306
314
  async rename({ input, access, signal }) {
307
315
  signal.throwIfAborted();
308
- assertAssetId(input.entry_id, "entry_id");
316
+ input = { ...input, entry_id: normalizeDamAssetId(input.entry_id, "entry_id") };
309
317
  if (input.kind !== "asset" && input.kind !== "folder")
310
318
  invalid("asset_or_folder", "kind");
311
319
  if (!nonblank(input.title) || input.title.length > 100)
@@ -370,6 +378,7 @@ export function createDamUseCases(dependencies) {
370
378
  },
371
379
  async move({ input, access, signal }) {
372
380
  signal.throwIfAborted();
381
+ input = { ...input, entry_id: normalizeDamAssetId(input.entry_id, "entry_id") };
373
382
  const operation = await entryOperation({ operation: "move", request: input, access, signal });
374
383
  try {
375
384
  await dependencies.telemetry.stage("verify", async () => {
@@ -406,6 +415,7 @@ export function createDamUseCases(dependencies) {
406
415
  },
407
416
  async copy({ input, access, signal }) {
408
417
  signal.throwIfAborted();
418
+ input = { ...input, entry_id: normalizeDamAssetId(input.entry_id, "entry_id") };
409
419
  const operation = await entryOperation({ operation: "copy", request: input, access, signal });
410
420
  const result = {
411
421
  source_entry_id: input.entry_id,
@@ -421,7 +431,7 @@ export function createDamUseCases(dependencies) {
421
431
  },
422
432
  async get({ input, access, signal }) {
423
433
  signal.throwIfAborted();
424
- assertAssetId(input.asset_id);
434
+ input = { ...input, asset_id: normalizeDamAssetId(input.asset_id) };
425
435
  return dependencies.telemetry.stage("request", async () => {
426
436
  const result = await dependencies.api.getAsset({
427
437
  assetId: input.asset_id,
@@ -462,7 +472,7 @@ export function createDamUseCases(dependencies) {
462
472
  },
463
473
  async delete({ input, access, signal }) {
464
474
  signal.throwIfAborted();
465
- assertAssetId(input.asset_id);
475
+ input = { ...input, asset_id: normalizeDamAssetId(input.asset_id) };
466
476
  const [repository] = await dependencies.telemetry.stage("repository", () => (resolveRepositories({
467
477
  ...(input.repositoryId === undefined ? {} : { repositoryId: input.repositoryId })
468
478
  }, access, signal)));
@@ -20,7 +20,7 @@ export function createTaskStore(options) {
20
20
  function file(scope, id) {
21
21
  if (!/^[a-f0-9]{64}$/u.test(scope) || !validTaskId(id))
22
22
  throw new LocalFileError(undefined);
23
- return createLocalJsonFile({ directory: join(root, scope), filename: `${id}.json` });
23
+ return createLocalJsonFile({ directory: join(root, scope), filename: `${id}.json`, role: "task" });
24
24
  }
25
25
  const store = {
26
26
  async read(scope, id) {
@@ -52,7 +52,7 @@ export function createTaskStore(options) {
52
52
  if (record.progress[key] !== undefined && typeof record.progress[key] !== "string")
53
53
  throw new Error();
54
54
  }
55
- for (const key of ["submissionStarted", "detached", "accepted"]) {
55
+ for (const key of ["submissionStarted", "detached", "accepted", "agentUsageModelMissing"]) {
56
56
  if (record.progress[key] !== undefined && typeof record.progress[key] !== "boolean")
57
57
  throw new Error();
58
58
  }
@@ -68,7 +68,7 @@ export function createTaskStore(options) {
68
68
  const previous = await store.read(scope, record.task.taskId);
69
69
  if (previous) {
70
70
  record.progress = { ...previous.progress, ...record.progress };
71
- for (const key of ["accepted", "submissionStarted", "detached"]) {
71
+ for (const key of ["accepted", "submissionStarted", "detached", "agentUsageModelMissing"]) {
72
72
  if (previous.progress[key])
73
73
  record.progress[key] = true;
74
74
  }
@@ -88,7 +88,7 @@ export function createTaskStore(options) {
88
88
  }
89
89
  options.validate(record.task);
90
90
  await file(scope, record.task.taskId).writeTextAtomically(`${JSON.stringify(record)}\n`);
91
- });
91
+ }, { action: "task_write" });
92
92
  },
93
93
  async update(scope, id, change) {
94
94
  file(scope, id);
@@ -100,7 +100,7 @@ export function createTaskStore(options) {
100
100
  options.validate(record.task);
101
101
  await file(scope, id).writeTextAtomically(`${JSON.stringify(record)}\n`);
102
102
  return record;
103
- });
103
+ }, { action: "task_update" });
104
104
  },
105
105
  async list(scope) {
106
106
  let names;