@gaoding/cli 1.9.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 (45) hide show
  1. package/contracts/operations/agent.send/output.schema.json +1 -1
  2. package/dist/bin/gd-cli.js +31 -24
  3. package/dist/bin/insmind-cli.js +31 -24
  4. package/dist/bin/task-worker.js +4 -1
  5. package/dist/src/analytics/device.js +2 -2
  6. package/dist/src/bootstrap/create-cli.js +7 -0
  7. package/dist/src/bootstrap/create-runtime.js +3 -7
  8. package/dist/src/bootstrap/run-task-worker.js +5 -1
  9. package/dist/src/bootstrap/validators.js +11 -4
  10. package/dist/src/cli/dam-commands.js +3 -3
  11. package/dist/src/cli/errors.js +60 -12
  12. package/dist/src/cli/observed-errors.js +3 -1
  13. package/dist/src/features/agent/creative-agent-adapter.js +37 -11
  14. package/dist/src/features/agent/creative-protocol.js +9 -5
  15. package/dist/src/features/agent/creative-stream.js +54 -6
  16. package/dist/src/features/agent/result-reader.js +3 -1
  17. package/dist/src/features/auth/credential-store.js +6 -10
  18. package/dist/src/features/auth/sso-service.js +22 -6
  19. package/dist/src/features/auth/state.js +6 -0
  20. package/dist/src/features/auth/use-cases.js +90 -32
  21. package/dist/src/features/dam/asset-projection.js +10 -1
  22. package/dist/src/features/dam/dam-api-adapter.js +30 -15
  23. package/dist/src/features/dam/input.js +23 -0
  24. package/dist/src/features/dam/use-cases.js +32 -22
  25. package/dist/src/features/task/store.js +5 -5
  26. package/dist/src/features/task/task-background.js +67 -19
  27. package/dist/src/features/task/use-cases.js +34 -6
  28. package/dist/src/features/tool/canvas-media.js +82 -27
  29. package/dist/src/features/tool/dynamic-schema.js +8 -4
  30. package/dist/src/features/tool/matting-billing.js +38 -26
  31. package/dist/src/features/tool/tool-api-adapter.js +17 -14
  32. package/dist/src/platform/file-lock.js +58 -15
  33. package/dist/src/platform/input-uri.js +105 -0
  34. package/dist/src/platform/local-json-file.js +7 -4
  35. package/dist/src/platform/remote-error-evidence.js +23 -1
  36. package/dist/src/platform/safe-upload-file.js +18 -4
  37. package/dist/src/platform/schema-issues.js +18 -0
  38. package/dist/src/platform/signed-http-transport.js +77 -16
  39. package/dist/src/platform/text-output.js +55 -13
  40. package/dist/src/telemetry/failure-summary.js +53 -2
  41. package/dist/src/telemetry/host-diagnostics.js +95 -0
  42. package/dist/src/telemetry/invocation.js +24 -3
  43. package/dist/src/telemetry/process-errors.js +2 -1
  44. package/dist/src/telemetry/sls-sink.js +66 -18
  45. package/package.json +4 -4
@@ -1,4 +1,5 @@
1
1
  import { RemoteProtocolError } from "../../platform/remote-protocol.js";
2
+ import { RemoteRequestError } from "../../platform/signed-http-transport.js";
2
3
  function isMessage(value) {
3
4
  return value !== null && typeof value === "object" && !Array.isArray(value);
4
5
  }
@@ -87,12 +88,24 @@ function parseSequence(payload) {
87
88
  }
88
89
  return values;
89
90
  }
90
- export async function parseCreativeStream(stream, signal, onContextId) {
91
+ export async function parseCreativeStream(stream, signal, onContextId, diagnostics = {}) {
91
92
  signal.throwIfAborted();
92
93
  const reader = stream.getReader();
93
94
  const decoder = new TextDecoder();
94
95
  let raw = "";
95
96
  let contextReported = false;
97
+ const now = diagnostics.now ?? Date.now;
98
+ const startedAt = diagnostics.startedAt ?? now();
99
+ let receivedBytes = 0;
100
+ let firstByteMs;
101
+ let terminalReason = "canceled";
102
+ const summary = () => ({
103
+ streamHadBytes: receivedBytes > 0,
104
+ streamReceivedBytes: receivedBytes,
105
+ ...(firstByteMs === undefined ? {} : { streamFirstByteMs: firstByteMs }),
106
+ streamTerminalReason: terminalReason,
107
+ abortSource: signal.aborted ? "caller" : "none"
108
+ });
96
109
  const onAbort = () => {
97
110
  void reader.cancel(signal.reason).catch(() => undefined);
98
111
  };
@@ -100,10 +113,25 @@ export async function parseCreativeStream(stream, signal, onContextId) {
100
113
  try {
101
114
  while (true) {
102
115
  signal.throwIfAborted();
103
- const result = await reader.read();
116
+ let result;
117
+ try {
118
+ result = await reader.read();
119
+ }
120
+ catch (error) {
121
+ if (signal.aborted)
122
+ throw signal.reason;
123
+ terminalReason = "error";
124
+ throw new RemoteRequestError(diagnostics.httpStatus, false, {}, error, "AGENT_STREAM_READ_FAILED", summary());
125
+ }
126
+ if (!result.done && result.value.byteLength) {
127
+ receivedBytes = Math.min(Number.MAX_SAFE_INTEGER, receivedBytes + result.value.byteLength);
128
+ firstByteMs ??= Math.max(0, Math.min(Number.MAX_SAFE_INTEGER, now() - startedAt));
129
+ }
104
130
  signal.throwIfAborted();
105
- if (result.done)
131
+ if (result.done) {
132
+ terminalReason = "eof";
106
133
  break;
134
+ }
107
135
  raw += decoder.decode(result.value, { stream: true });
108
136
  if (onContextId && !contextReported) {
109
137
  const contextId = messagesFrom(raw).find(message => typeof message.thread_id === "string" && message.thread_id)?.thread_id;
@@ -115,16 +143,36 @@ export async function parseCreativeStream(stream, signal, onContextId) {
115
143
  }
116
144
  raw += decoder.decode();
117
145
  }
146
+ catch (error) {
147
+ try {
148
+ if (error instanceof Error && Object.isExtensible(error)) {
149
+ const previous = error.diagnosticSummary;
150
+ Object.assign(error, { diagnosticSummary: {
151
+ ...(previous && typeof previous === "object" && !Array.isArray(previous) ? previous : {}), ...summary()
152
+ } });
153
+ }
154
+ }
155
+ catch { /* Diagnostic attachment cannot replace the original failure. */ }
156
+ if (terminalReason === "canceled")
157
+ void reader.cancel(error).catch(() => undefined);
158
+ throw error;
159
+ }
118
160
  finally {
119
161
  signal.removeEventListener("abort", onAbort);
120
162
  reader.releaseLock();
163
+ try {
164
+ diagnostics.onDiagnostics?.(summary());
165
+ }
166
+ catch { /* Diagnostics cannot replace a result or primary error. */ }
121
167
  }
122
168
  const messages = messagesFrom(raw);
123
169
  if (messages.length === 0) {
124
170
  const payloads = extractPayloads(raw);
125
- throw new RemoteProtocolError({ remoteBody: JSON.stringify({ messageCount: 0, contextIdPresent: false, systemErrorCount: 0,
126
- streamHadBytes: raw.length > 0, streamPayloadCount: Math.min(payloads.length, 100_000),
127
- streamJsonValueCount: Math.min(payloads.reduce((count, payload) => count + parseSequence(payload).length, 0), 100_000) }) }, undefined, "AGENT_CONTEXT_ID_MISSING");
171
+ throw Object.assign(new RemoteProtocolError({ remoteBody: JSON.stringify({ messageCount: 0, contextIdPresent: false, systemErrorCount: 0,
172
+ ...summary(), streamPayloadCount: Math.min(payloads.length, 100_000),
173
+ streamJsonValueCount: Math.min(payloads.reduce((count, payload) => count + parseSequence(payload).length, 0), 100_000) }) }, undefined, "AGENT_CONTEXT_ID_MISSING"), {
174
+ ...(diagnostics.httpStatus === undefined ? {} : { status: diagnostics.httpStatus }), diagnosticSummary: summary()
175
+ });
128
176
  }
129
177
  return messages;
130
178
  }
@@ -20,7 +20,9 @@ export async function readAgentResult(transport, request) {
20
20
  if (!turn.some(m => m.role !== "user" && m.content))
21
21
  return { connectionState: connection.state };
22
22
  try {
23
- return { connectionState: connection.state, partialResult: normalizeCreativeMessages(turn) };
23
+ let usageModelMissing = false;
24
+ const partialResult = normalizeCreativeMessages(turn, () => { usageModelMissing = true; });
25
+ return { connectionState: connection.state, partialResult, ...(usageModelMissing ? { usageModelMissing: true } : {}) };
24
26
  }
25
27
  catch (error) {
26
28
  if (error instanceof RemoteProtocolError)
@@ -1,11 +1,12 @@
1
1
  import { homedir } from "node:os";
2
2
  import { join } from "node:path";
3
3
  import { createLocalJsonFile } from "../../platform/local-json-file.js";
4
- import { AuthStateInvalidError, parseStoredAuthState } from "./state.js";
4
+ import { AuthStateInvalidError, AuthStateUnavailableError, parseStoredAuthState } from "./state.js";
5
5
  export function createLocalCredentialStore(options = {}) {
6
6
  const file = options.file ?? createLocalJsonFile({
7
7
  directory: join(options.homeDirectory ?? homedir(), options.stateDirectory ?? ".gd"),
8
- filename: "credentials.json"
8
+ filename: "credentials.json",
9
+ role: "credentials"
9
10
  });
10
11
  return {
11
12
  async read() {
@@ -28,7 +29,7 @@ export function createLocalCredentialStore(options = {}) {
28
29
  catch (cause) {
29
30
  if (cause instanceof AuthStateInvalidError)
30
31
  throw cause;
31
- throw invalidState(cause);
32
+ throw new AuthStateUnavailableError({ cause });
32
33
  }
33
34
  },
34
35
  async write(state) {
@@ -39,7 +40,7 @@ export function createLocalCredentialStore(options = {}) {
39
40
  catch (cause) {
40
41
  if (cause instanceof AuthStateInvalidError)
41
42
  throw cause;
42
- throw invalidState(cause);
43
+ throw new AuthStateUnavailableError({ cause });
43
44
  }
44
45
  },
45
46
  async remove() {
@@ -47,7 +48,7 @@ export function createLocalCredentialStore(options = {}) {
47
48
  await file.remove();
48
49
  }
49
50
  catch (cause) {
50
- throw invalidState(cause);
51
+ throw new AuthStateUnavailableError({ cause });
51
52
  }
52
53
  }
53
54
  };
@@ -55,8 +56,3 @@ export function createLocalCredentialStore(options = {}) {
55
56
  function serialize(state) {
56
57
  return `${JSON.stringify(state, null, 2)}\n`;
57
58
  }
58
- function invalidState(cause) {
59
- return new AuthStateInvalidError({
60
- cause, reason: "local_io"
61
- });
62
- }
@@ -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
+ }