@insmind/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 (43) hide show
  1. package/dist/bin/insmind-cli.js +31 -24
  2. package/dist/bin/task-worker.js +4 -1
  3. package/dist/src/analytics/device.js +2 -2
  4. package/dist/src/bootstrap/create-cli.js +7 -0
  5. package/dist/src/bootstrap/create-runtime.js +3 -7
  6. package/dist/src/bootstrap/run-task-worker.js +5 -1
  7. package/dist/src/bootstrap/validators.js +11 -4
  8. package/dist/src/cli/dam-commands.js +3 -3
  9. package/dist/src/cli/errors.js +60 -12
  10. package/dist/src/cli/observed-errors.js +3 -1
  11. package/dist/src/features/agent/creative-agent-adapter.js +37 -11
  12. package/dist/src/features/agent/creative-protocol.js +9 -5
  13. package/dist/src/features/agent/creative-stream.js +54 -6
  14. package/dist/src/features/agent/result-reader.js +3 -1
  15. package/dist/src/features/auth/credential-store.js +6 -10
  16. package/dist/src/features/auth/sso-service.js +22 -6
  17. package/dist/src/features/auth/state.js +6 -0
  18. package/dist/src/features/auth/use-cases.js +90 -32
  19. package/dist/src/features/dam/asset-projection.js +10 -1
  20. package/dist/src/features/dam/dam-api-adapter.js +30 -15
  21. package/dist/src/features/dam/input.js +23 -0
  22. package/dist/src/features/dam/use-cases.js +32 -22
  23. package/dist/src/features/task/store.js +5 -5
  24. package/dist/src/features/task/task-background.js +67 -19
  25. package/dist/src/features/task/use-cases.js +34 -6
  26. package/dist/src/features/tool/canvas-media.js +82 -27
  27. package/dist/src/features/tool/dynamic-schema.js +8 -4
  28. package/dist/src/features/tool/matting-billing.js +38 -26
  29. package/dist/src/features/tool/tool-api-adapter.js +17 -14
  30. package/dist/src/platform/file-lock.js +58 -15
  31. package/dist/src/platform/input-uri.js +105 -0
  32. package/dist/src/platform/local-json-file.js +7 -4
  33. package/dist/src/platform/remote-error-evidence.js +23 -1
  34. package/dist/src/platform/safe-upload-file.js +18 -4
  35. package/dist/src/platform/schema-issues.js +18 -0
  36. package/dist/src/platform/signed-http-transport.js +77 -16
  37. package/dist/src/platform/text-output.js +55 -13
  38. package/dist/src/telemetry/failure-summary.js +53 -2
  39. package/dist/src/telemetry/host-diagnostics.js +95 -0
  40. package/dist/src/telemetry/invocation.js +24 -3
  41. package/dist/src/telemetry/process-errors.js +2 -1
  42. package/dist/src/telemetry/sls-sink.js +66 -18
  43. package/package.json +4 -4
@@ -15,30 +15,37 @@ let runtime;
15
15
  let mapCliError;
16
16
  let redact;
17
17
  try {
18
- const [cliModule, runtimeModule, errorsModule, redactModule] = await Promise.all([
19
- import("../src/bootstrap/create-cli.js"),
20
- import("../src/bootstrap/create-runtime.js"),
21
- import("../src/cli/errors.js"),
22
- import("../src/platform/redact.js")
23
- ]);
24
- mapCliError = errorsModule.mapCliError;
25
- redact = redactModule.redact;
26
- const selectedLocale = localeOption(process.argv.slice(2));
27
- runtime = runtimeModule.createProductionRuntime({
28
- product: insmindProduct,
29
- ...(selectedLocale === undefined ? {} : { locale: selectedLocale })
30
- });
31
- const program = cliModule.createCli(runtime, { signal: controller.signal });
32
- process.exitCode = await cliModule.executeCli({
33
- program,
34
- argv: process.argv.slice(2),
35
- presenter: runtime.presenter,
36
- signal: controller.signal,
37
- telemetry: runtime.telemetry,
38
- telemetrySink: runtime.telemetrySink,
39
- updateNotification: runtime.updateNotification,
40
- product: runtime.product
41
- });
18
+ if (process.env.CLI_INTERNAL_HOST_DIAGNOSTIC === "1" && process.argv.length === 3 && process.argv[2] === "--version") {
19
+ await import("../src/telemetry/host-diagnostics.js")
20
+ .then(({ runHostDiagnosticReporter }) => runHostDiagnosticReporter({ product: insmindProduct }))
21
+ .catch(() => undefined);
22
+ }
23
+ else {
24
+ const [cliModule, runtimeModule, errorsModule, redactModule] = await Promise.all([
25
+ import("../src/bootstrap/create-cli.js"),
26
+ import("../src/bootstrap/create-runtime.js"),
27
+ import("../src/cli/errors.js"),
28
+ import("../src/platform/redact.js")
29
+ ]);
30
+ mapCliError = errorsModule.mapCliError;
31
+ redact = redactModule.redact;
32
+ const selectedLocale = localeOption(process.argv.slice(2));
33
+ runtime = runtimeModule.createProductionRuntime({
34
+ product: insmindProduct,
35
+ ...(selectedLocale === undefined ? {} : { locale: selectedLocale })
36
+ });
37
+ const program = cliModule.createCli(runtime, { signal: controller.signal });
38
+ process.exitCode = await cliModule.executeCli({
39
+ program,
40
+ argv: process.argv.slice(2),
41
+ presenter: runtime.presenter,
42
+ signal: controller.signal,
43
+ telemetry: runtime.telemetry,
44
+ telemetrySink: runtime.telemetrySink,
45
+ updateNotification: runtime.updateNotification,
46
+ product: runtime.product
47
+ });
48
+ }
42
49
  }
43
50
  catch (error) {
44
51
  const traceId = runtime?.telemetry.traceId ?? bootstrapTraceId;
@@ -2,6 +2,7 @@
2
2
  import { reportProcessError } from "../src/telemetry/process-errors.js";
3
3
  import { once } from "node:events";
4
4
  import { Readable } from "node:stream";
5
+ import { taskWorkerUnavailableError } from "../src/features/task/task-background.js";
5
6
  import { gaodingProduct, insmindProduct } from "../src/product/config.js";
6
7
  import { createProductionRuntime } from "../src/bootstrap/create-runtime.js";
7
8
  import { runTaskWorker } from "../src/bootstrap/run-task-worker.js";
@@ -42,7 +43,9 @@ else {
42
43
  ...(currentJob?.telemetryTrackingUrl ? { trackingUrl: new URL(currentJob.telemetryTrackingUrl) } : {}),
43
44
  ...(currentJob?.telemetryEnvironment ? { environment: currentJob.telemetryEnvironment } : {}),
44
45
  ...(currentJob?.homeDirectory ? { homeDirectory: currentJob.homeDirectory } : {}) });
45
- send({ type: "error", failure: { code: "TASK_WORKER_UNAVAILABLE", message: "The background task could not start. Check task list/get before submitting again." }, exitCode: 1 });
46
+ const unavailable = taskWorkerUnavailableError({ product: currentJob?.product === "insmind" ? "insmind" : "gaoding",
47
+ phase: "bootstrap", cause: error, pid: process.pid });
48
+ send({ type: "error", failure: unavailable.failure, ...(unavailable.diagnostics ? { diagnostics: unavailable.diagnostics } : {}), exitCode: 1 });
46
49
  process.exitCode = 1;
47
50
  }
48
51
  finally {
@@ -3,7 +3,7 @@ import { join } from "node:path";
3
3
  import { withFileLock } from "../platform/file-lock.js";
4
4
  import { createLocalJsonFile } from "../platform/local-json-file.js";
5
5
  export async function loadAnalyticsDevice(directory, now) {
6
- const file = createLocalJsonFile({ directory, filename: "analytics-device.json" });
6
+ const file = createLocalJsonFile({ directory, filename: "analytics-device.json", role: "analytics_device" });
7
7
  async function read() {
8
8
  const text = await file.readText();
9
9
  if (text !== null) {
@@ -26,7 +26,7 @@ export async function loadAnalyticsDevice(directory, now) {
26
26
  const device = { id: randomUUID(), createdAt: now() };
27
27
  await file.writeTextAtomically(`${JSON.stringify(device)}\n`);
28
28
  return device;
29
- });
29
+ }, { action: "analytics_device" });
30
30
  }
31
31
  export function isFirstDay(createdAt, now) {
32
32
  return new Date(createdAt).setHours(23, 59, 59, 999) >= now ? 1 : 0;
@@ -66,6 +66,12 @@ export function createCli(runtime, options) {
66
66
  }
67
67
  export async function executeCli(options) {
68
68
  let helpOnly = false;
69
+ // Commander handles version before action selection. Preserve the real
70
+ // operation if writing that version to a closed host pipe fails.
71
+ if (options.argv.some(argument => argument === "--version" || argument === "-V")
72
+ && options.argv.every(argument => ["--version", "-V", "--json-errors"].includes(argument))) {
73
+ options.telemetry.select({ operation: "version" });
74
+ }
69
75
  try {
70
76
  try {
71
77
  await options.program.parseAsync(options.argv, { from: "user" });
@@ -157,6 +163,7 @@ async function checkUpdateNotification(updateNotification, signal) {
157
163
  }
158
164
  async function sendFinished(options, completion) {
159
165
  await analyticsShutdown.get(options.program)?.().catch(() => undefined);
166
+ await options.telemetrySink.refreshDiagnostics?.().catch(() => undefined);
160
167
  options.telemetry.annotate(options.telemetrySink.diagnostics?.() ?? {});
161
168
  const events = options.telemetry.finish(completion);
162
169
  if (events.length > 0)
@@ -54,7 +54,7 @@ import { loadBundledSkills } from "../features/skill/bundled-skills.js";
54
54
  import { createUpdateService } from "../features/update/update-service.js";
55
55
  import { createUpdateNotificationService } from "../features/update/update-notification.js";
56
56
  import { classifyTelemetryError, mapCliError } from "../cli/errors.js";
57
- import { createTelemetryInvocation } from "../telemetry/invocation.js";
57
+ import { createTelemetryInvocation, hostTelemetryContext } from "../telemetry/invocation.js";
58
58
  import { createSlsTelemetrySink } from "../telemetry/sls-sink.js";
59
59
  import { gaodingProduct } from "../product/config.js";
60
60
  import { resolveProductLocale, systemLocale } from "../product/locale.js";
@@ -106,12 +106,7 @@ export function createProductionRuntime(options = {}) {
106
106
  classifyError: error => classifyTelemetryError(error, { product, operation: telemetry.creationContext().operation, failureStage: telemetry.failureStage(error) }),
107
107
  ...(telemetrySink.enqueue ? { onEvent: (event) => telemetrySink.enqueue([event]) } : {})
108
108
  });
109
- telemetry.annotate({ installation_owner: installationOwner,
110
- ...(["workbuddy", "qwenwork"].includes(env.CLI_HOST_APPLICATION ?? "")
111
- ? { host_application: env.CLI_HOST_APPLICATION } : {}),
112
- ...(["auth_status", "version_check"].includes(env.CLI_INVOCATION_PURPOSE ?? "")
113
- ? { invocation_purpose: env.CLI_INVOCATION_PURPOSE } : {}),
114
- ...(/^[a-f0-9]{32}$/u.test(env.CLI_HOST_INVOCATION_ID ?? "") ? { host_invocation_id: env.CLI_HOST_INVOCATION_ID } : {}) });
109
+ telemetry.annotate({ installation_owner: installationOwner, ...hostTelemetryContext(env) });
115
110
  // Explicit test transport enables SDK tests; test-mode child processes never emit real analytics.
116
111
  const analytics = options.analytics ?? (telemetryEnvironment === "production" || options.windFetch
117
112
  ? createWindAnalytics({ product: product.id, version: options.telemetryVersion ?? primarySkill.version,
@@ -362,6 +357,7 @@ export function createProductionRuntime(options = {}) {
362
357
  credential: state.credential, organizationId: state.organization.id, signal
363
358
  });
364
359
  return { state: "unknown",
360
+ ...(snapshot.usageModelMissing ? { usageModelMissing: true } : {}),
365
361
  note: snapshot.partialResult
366
362
  ? text("已找到部分内容,尚未取得完整结果。", "Some content was found, but the complete result has not been received.")
367
363
  : text("尚未取得任务结果。", "The task result has not been received."),
@@ -49,10 +49,14 @@ export async function runTaskWorker(options) {
49
49
  : { outcome: "failure", error, errorCode: outcome.failure.code, errorMessage: outcome.failure.message };
50
50
  if (outcome.kind === "failure")
51
51
  send({ type: "error", failure: outcome.failure, exitCode: outcome.exitCode,
52
- diagnostics: taskWorkerDiagnostics(error, classifyTelemetryError(error, { product: runtime.product, operation: job.operation, failureStage: runtime.telemetry.failureStage(error) }), runtime.telemetry.failureStage(error)) });
52
+ diagnostics: taskWorkerDiagnostics(error, {
53
+ ...classifyTelemetryError(error, { product: runtime.product, operation: job.operation, failureStage: runtime.telemetry.failureStage(error) }),
54
+ diagnosticSummary: runtime.telemetry.taskFailure(error).diagnostic_summary ?? {}
55
+ }, runtime.telemetry.failureStage(error)) });
53
56
  }
54
57
  finally {
55
58
  await runtime.analytics?.shutdown().catch(() => undefined);
59
+ await runtime.telemetrySink.refreshDiagnostics?.().catch(() => undefined);
56
60
  runtime.telemetry.annotate(runtime.telemetrySink.diagnostics?.() ?? {});
57
61
  await runtime.telemetrySink.send(runtime.telemetry.finish(completion)).catch(() => undefined);
58
62
  }
@@ -1,4 +1,5 @@
1
- import { validationIssues } from "../platform/schema-issues.js";
1
+ import { inputValidationSummary, validationIssues } from "../platform/schema-issues.js";
2
+ import { canonicalizeInputFileUris } from "../platform/input-uri.js";
2
3
  import { Ajv2020 } from "ajv/dist/2020.js";
3
4
  import addFormatsImport, {} from "ajv-formats";
4
5
  import { contractSchema } from "../contracts/schema.js";
@@ -45,9 +46,11 @@ const toolCallOutputSchema = contractSchema("tool.call", "output");
45
46
  const toolListOutputSchema = contractSchema("tool.list", "output");
46
47
  export class InputContractError extends Error {
47
48
  issues;
48
- constructor(issues = []) {
49
+ diagnosticSummary;
50
+ constructor(issues = [], diagnosticSummary = {}) {
49
51
  super(`输入不符合命令契约。${issues.length ? ` ${JSON.stringify(issues)}` : ""}`);
50
52
  this.issues = issues;
53
+ this.diagnosticSummary = diagnosticSummary;
51
54
  this.name = "InputContractError";
52
55
  }
53
56
  }
@@ -168,7 +171,11 @@ export function createContractValidators(options = {}) {
168
171
  const unavailableValidator = Object.assign(() => false, { errors: null, schema: false, schemaEnv: undefined });
169
172
  function assertion(validate, ErrorType) {
170
173
  return (value) => {
171
- if (!validate(value))
172
- throw new ErrorType(validationIssues(validate.errors, value, validate.schema));
174
+ if (ErrorType === InputContractError)
175
+ canonicalizeInputFileUris(value, validate.schema);
176
+ if (!validate(value)) {
177
+ const issues = validationIssues(validate.errors, value, validate.schema);
178
+ throw new ErrorType(issues, inputValidationSummary(issues, value));
179
+ }
173
180
  };
174
181
  }
@@ -100,12 +100,12 @@ export function registerDamCommands(program, runtime) {
100
100
  });
101
101
  }, { operation: "dam.tag.list" });
102
102
  const download = leaf(dam.command("download"))
103
- .description(text(runtime.product, "下载一个素材", "Download an asset"))
103
+ .description(text(runtime.product, "下载一个素材的源文件", "Download an asset's source file"))
104
104
  .argument("<asset>", text(runtime.product, "素材 ID", "asset ID"))
105
105
  .option("--repository-id <id>", text(runtime.product, "所属资源库 ID", "repository ID"))
106
- .option("--output-dir <directory>", text(runtime.product, "输出目录", "output directory"))
106
+ .option("--output-dir <directory>", text(runtime.product, "输出目录,默认当前目录", "output directory; defaults to the current directory"))
107
107
  .option("--json", text(runtime.product, "输出 JSON", "output JSON"));
108
- download.addHelpText("after", `\n${text(runtime.product, "只下载一个素材,不支持文件夹;写入本机目录,不覆盖已有同名文件。--json 返回 files 中的路径、字节数与摘要。", "Downloads one asset, not a folder, to a local directory without overwriting same-named files. --json returns paths, byte counts and digests in files.")}\n`);
108
+ download.addHelpText("after", `\n${text(runtime.product, "下载单个素材的源文件,不支持文件夹,也不会自动导出作品。--output-dir 指定目录;已有同名文件时选择其他目录或先处理该文件。--json 返回 files 中的路径、字节数与摘要。", "Downloads one asset's source file; folders and automatic design export are not supported. --output-dir selects a directory. If a same-named file exists, choose another directory or handle the existing file first. --json returns paths, byte counts and digests in files.")}\n`);
109
109
  bindPreparedAction(download, "organization", async (signal) => {
110
110
  signal.throwIfAborted();
111
111
  const options = download.opts();
@@ -4,7 +4,7 @@ import { TaskNotFoundError } from "../features/task/use-cases.js";
4
4
  import { TaskStoreError } from "../features/task/store.js";
5
5
  import { CommanderError } from "commander";
6
6
  import { AuthExpiredError, AuthRequiredError } from "../features/auth/access-policy.js";
7
- import { AuthStateInvalidError, UserIdentityMissingError } from "../features/auth/state.js";
7
+ import { AuthStateInvalidError, AuthStateUnavailableError, UserIdentityMissingError } from "../features/auth/state.js";
8
8
  import { SsoRequestError } from "../features/auth/sso-service.js";
9
9
  import { AuthorizedAccountContextMissingError, BrowserOpenError, DeviceAuthorizationExpiredError } from "../features/auth/use-cases.js";
10
10
  import { AgentInputError } from "../features/agent/use-cases.js";
@@ -68,7 +68,7 @@ export function mapCliError(error, options) {
68
68
  if (!category)
69
69
  return outcome;
70
70
  // Keep precise input corrections and their fields; general failures have a short user message.
71
- if (category === "input" && ["USAGE_ERROR", "INVALID_ACTIONS"].includes(outcome.failure.code))
71
+ if ((category === "input" || category === "input_asset") && ["USAGE_ERROR", "INVALID_ACTIONS"].includes(outcome.failure.code))
72
72
  return outcome;
73
73
  return { ...outcome, failure: { ...outcome.failure, message: observedErrorMessage(category, evidence) } };
74
74
  }
@@ -108,6 +108,8 @@ function mapBaseCliError(error, options) {
108
108
  return failure("AUTH_EXPIRED", "Authentication expired. Sign out and sign in again.", 1, [`${command} auth logout`, `${command} auth login`]);
109
109
  return failure("AUTH_EXPIRED", "登录已过期,请退出后重新登录。", 1, ["gd-cli auth logout", "gd-cli auth login"]);
110
110
  }
111
+ if (error instanceof AuthStateUnavailableError)
112
+ return failure("AUTH_STATE_UNAVAILABLE", text("无法读取或保存本地登录信息。", "Local sign-in information could not be read or saved."), 1, [text("请检查文件访问权限后重试。", "Check file access permissions and try again.")], { reason: "local_io", system_code: systemErrorCode(error) });
111
113
  if (error instanceof AuthStateInvalidError) {
112
114
  if (error.reason === "local_io")
113
115
  return failure("AUTH_STATE_INVALID", text("无法读写本地凭证,当前无法判断登录是否有效。", "Cannot access local credentials; authentication validity is unknown."), 1, [text("恢复凭证文件的访问权限或宿主文件访问能力;不要执行 logout 或删除凭证。", "Restore access to the credential file or host file permissions; do not log out or delete credentials.")], { reason: error.reason, system_code: systemErrorCode(error) });
@@ -147,12 +149,23 @@ function mapBaseCliError(error, options) {
147
149
  const description = descriptions[error.reason];
148
150
  return failure("USAGE_ERROR", description ? text(...description) : text("创作输入不可用,请核对模型与参数。", "Check the model and creation arguments."), 2, [`${command} model list`, text(`使用 ${command} model get <model> 核对模型参数;素材应使用安全的 HTTP(S) URL 或本地 file URL。`, `Use ${command} model get <model> to inspect parameters; assets require safe HTTP(S) URLs or local file URLs.`)], { reason: error.reason, field: error.field, ...(error instanceof ToolInputError ? { issues: error.issues } : {}) });
149
151
  }
150
- if (error instanceof LocalFileInputError)
151
- return failure("USAGE_ERROR", text("本地素材文件不可用于上传。", "The local asset file cannot be uploaded."), 2, [text("检查文件访问权限、文件类型和声明的 mediaType;受保护路径不可上传。", "Check file access, type and declared mediaType; protected paths cannot be uploaded.")], { reason: error.reason, system_code: systemErrorCode(error) });
152
+ if (error instanceof LocalFileInputError) {
153
+ const message = error.reason === "invalid_file_uri"
154
+ ? text("本地文件地址格式不正确。Windows 地址示例:file:///C:/目录/文件。", "Invalid local file URL. Windows example: file:///C:/folder/file.")
155
+ : error.reason === "file_read_failed" && systemErrorCode(error) === "ENOENT"
156
+ ? text("找不到指定的本地文件,请核对完整路径。", "The local file was not found. Check its full path.")
157
+ : error.reason === "media_type_mismatch"
158
+ ? text("素材类型与文件实际格式不一致,请修正 mediaType 或重新选择文件。", "The mediaType does not match the file format. Correct it or select another file.")
159
+ : text("本地素材文件不可用于上传。", "The local asset file cannot be uploaded.");
160
+ return failure("USAGE_ERROR", message, 2, [text("检查文件访问权限、文件类型和声明的 mediaType;受保护路径不可上传。", "Check file access, type and declared mediaType; protected paths cannot be uploaded.")], { reason: error.reason, system_code: systemErrorCode(error) });
161
+ }
152
162
  if (error instanceof CliUsageError && error.reason === "invalid_task_id")
153
163
  return failure("USAGE_ERROR", text("任务编号不正确,请使用本机任务列表中的 taskId。", "Invalid Task ID. Use a taskId from the local task list."), 2, [`${command} task list`, `${command} task get <taskId>`], { reason: error.reason });
154
164
  if (error instanceof DamInputError)
155
165
  return failure("USAGE_ERROR", text("素材管理参数无效,请根据字段和原因核对命令 --help。", "Invalid asset-management argument; check the field and reason against the command's --help."), 2, undefined, { reason: error.reason, field: error.field });
166
+ if (error instanceof CommanderError && error.code === "commander.unknownOption" && options.operation === "dam.download"
167
+ && /unknown option ['"]--output['"]/u.test(error.message))
168
+ return failure("USAGE_ERROR", text("下载目录请使用 --output-dir <directory>。", "Use --output-dir <directory> to choose the download directory."), 2);
156
169
  if (error instanceof OrgUsageError
157
170
  || error instanceof CliUsageError
158
171
  || error instanceof CommanderError) {
@@ -256,6 +269,8 @@ function mapBaseCliError(error, options) {
256
269
  }
257
270
  return failure(error.code, redactSensitiveText(error.message).slice(0, 1024), 1, ["写入失败时先检查原作品,不直接重复 apply 或 save;按 editor --help 中的对应错误指引处理。"]);
258
271
  }
272
+ if (systemErrorCode(error) === "ECONNRESET")
273
+ return failure("REMOTE_REQUEST_FAILED", text("连接中断,未能完整收到结果。", "The connection closed before the full result was received."), 1);
259
274
  return failure("INTERNAL_ERROR", insmind ? "The CLI encountered an internal error." : "CLI 发生内部错误。", 1);
260
275
  }
261
276
  function isInsufficientCreditsError(error) {
@@ -270,6 +285,13 @@ export function classifyTelemetryError(error, options = {}) {
270
285
  return { outcome: "failure", errorCode: error.code,
271
286
  ...(error.status === undefined ? {} : { httpStatus: error.status }) };
272
287
  const outcome = mapCliError(error, { ...options, aborted: options.aborted === true });
288
+ if (error instanceof DeviceAuthorizationExpiredError && outcome.kind !== "interrupted")
289
+ return {
290
+ outcome: "failure", errorCode: "REMOTE_REQUEST_FAILED",
291
+ diagnosticReason: error.expirationSource === "server_expired" ? "AUTHORIZATION_SERVER_EXPIRED" : "AUTHORIZATION_WAIT_TIMEOUT",
292
+ ...(error.httpStatus === undefined ? {} : { httpStatus: error.httpStatus }),
293
+ ...(error.expirationSource === "server_expired" ? { remoteErrorCode: "expired_token" } : {})
294
+ };
273
295
  if (error instanceof TaskBackgroundError) {
274
296
  const diagnostics = error.diagnostics;
275
297
  return { outcome: outcome.kind === "interrupted" ? "interrupted" : "failure",
@@ -290,24 +312,27 @@ export function classifyTelemetryError(error, options = {}) {
290
312
  }
291
313
  catch { /* No safe summary available. */ }
292
314
  }
315
+ const inputReason = error instanceof LocalFileInputError ? error.reason
316
+ : error instanceof JsonInputError ? `json_${error.reason}`
317
+ : error instanceof InputContractError ? "schema_validation"
318
+ : error instanceof CliUsageError || error instanceof ToolInputError || error instanceof AgentInputError || error instanceof DamInputError ? error.reason
319
+ : error instanceof CommanderError ? error.code : undefined;
320
+ const systemCode = systemErrorCode(error);
293
321
  const diagnosticSummary = safeFailureSummary({
294
322
  ...localFileSummary(error),
295
323
  ...(error instanceof OutputStreamError ? { outputStream: error.outputStream } : {}),
296
324
  ...(remoteError instanceof SsoRequestError ? remoteError.diagnosticSummary : {}),
297
325
  ...(summary && typeof summary === "object" && !Array.isArray(summary) ? summary : {}),
298
- systemCode: systemErrorCode(error),
299
- inputReason: error instanceof LocalFileInputError ? error.reason
300
- : error instanceof JsonInputError ? `json_${error.reason}`
301
- : error instanceof InputContractError ? "schema_validation"
302
- : error instanceof CliUsageError || error instanceof ToolInputError || error instanceof AgentInputError ? error.reason
303
- : error instanceof CommanderError ? error.code : undefined
326
+ ...nestedDiagnosticSummary(error),
327
+ ...(systemCode ? { systemCode } : {}),
328
+ ...(inputReason ? { inputReason } : {})
304
329
  });
305
330
  return {
306
331
  outcome: outcome.kind === "interrupted" ? "interrupted" : "failure",
307
332
  ...(diagnosticSummary ? { diagnosticSummary } : {}),
308
333
  ...(outcome.kind === "failure" ? { errorCode: outcome.failure.code } : {}),
309
- ...((remoteError instanceof RemoteRequestError || remoteError instanceof SsoRequestError) && remoteError.status !== undefined
310
- ? { httpStatus: remoteError.status }
334
+ ...(httpErrorStatus(error) !== undefined
335
+ ? { httpStatus: httpErrorStatus(error) }
311
336
  : {}),
312
337
  ...(remoteError?.remoteCode === undefined
313
338
  ? {}
@@ -323,6 +348,29 @@ export function classifyTelemetryError(error, options = {}) {
323
348
  ? { diagnosticReason: remoteError.diagnosticReason } : {})
324
349
  };
325
350
  }
351
+ function nestedDiagnosticSummary(error) {
352
+ const facts = {};
353
+ const seen = new Set();
354
+ for (let depth = 0; error instanceof Error && depth < 10 && !seen.has(error); depth++, error = error.cause) {
355
+ seen.add(error);
356
+ if (!("diagnosticSummary" in error))
357
+ continue;
358
+ const summary = safeFailureSummary(error.diagnosticSummary);
359
+ for (const [key, value] of Object.entries(summary ?? {}))
360
+ if (!(key in facts))
361
+ facts[key] = value;
362
+ }
363
+ return facts;
364
+ }
365
+ function httpErrorStatus(error) {
366
+ const seen = new Set();
367
+ for (let depth = 0; error instanceof Error && depth < 10 && !seen.has(error); depth++, error = error.cause) {
368
+ seen.add(error);
369
+ if ("status" in error && typeof error.status === "number" && Number.isInteger(error.status) && error.status >= 100 && error.status <= 599)
370
+ return error.status;
371
+ }
372
+ return undefined;
373
+ }
326
374
  function failure(code, message, exitCode, nextSteps, details) {
327
375
  return {
328
376
  kind: "failure",
@@ -76,7 +76,7 @@ export function observedErrorCategory(e) {
76
76
  return "unsupported";
77
77
  if (e.code === "SAVE_FAILED")
78
78
  return "save";
79
- if (e.code === "LOCAL_STATE_ERROR")
79
+ if (["LOCAL_STATE_ERROR", "AUTH_STATE_UNAVAILABLE"].includes(e.code))
80
80
  return "local";
81
81
  if (e.code === "UPDATE_FAILED" && e.diagnosticReason === "UPDATE_MANAGED_BY_HOST")
82
82
  return "managed_update";
@@ -112,6 +112,8 @@ export function observedErrorMessage(category, e) {
112
112
  return text("素材下载未完成。", "The asset download did not complete.");
113
113
  if (category === "local" && e.errorType === "LocalFileError")
114
114
  return text("无法读取或保存所需文件。", "A required file could not be read or saved.");
115
+ if (category === "local" && e.code === "AUTH_STATE_UNAVAILABLE")
116
+ return text("无法读取或保存本地登录信息。", "Local sign-in information could not be read or saved.");
115
117
  if (category === "request" && e.operation === "task.get")
116
118
  return text("本次未能读取任务结果。", "The task result could not be retrieved.");
117
119
  return text(messages[category][0], messages[category][1]);
@@ -1,3 +1,4 @@
1
+ import { withResponseDiagnostics } from "../../platform/signed-http-transport.js";
1
2
  import { buildCreativeRequest, creativeContextId, creativeTurnMessages, normalizeCreativeMessages, restoreCreativeResourceUrls } from "./creative-protocol.js";
2
3
  import { parseCreativeStream } from "./creative-stream.js";
3
4
  export function createCreativeAgentAdapter(dependencies) {
@@ -10,30 +11,55 @@ export function createCreativeAgentAdapter(dependencies) {
10
11
  localMessageId: dependencies.idFactory()
11
12
  }
12
13
  : { localMessageId: dependencies.idFactory() };
14
+ const correlation = {
15
+ localMessageId: ids.localMessageId,
16
+ ...("localThreadId" in ids ? { localThreadId: ids.localThreadId } : {}),
17
+ ...(message.contextId ? { agentContextId: message.contextId } : {})
18
+ };
19
+ dependencies.telemetry.annotate({ diagnostic_summary: correlation });
13
20
  await observe?.({ localMessageId: ids.localMessageId, ...(message.contextId ? { contextId: message.contextId } : {}) });
14
- const { streamed, contextId } = await dependencies.telemetry.stage("execute", async () => {
21
+ const { streamed, contextId } = await dependencies.telemetry.stage("execute", () => withResponseDiagnostics(async (onResponse) => {
15
22
  await observe?.({ submissionStarted: true });
23
+ const startedAt = Date.now();
24
+ let httpStatus;
16
25
  const stream = await dependencies.transport.postStream({
17
26
  path: "/ai-agent/v1/thread/completion",
18
27
  ...(observe ? { onDispatch: (dispatchedAt) => observe({ dispatchedAt }) } : {}),
19
28
  body: buildCreativeRequest(message, ids),
20
29
  accept: "text/event-stream",
30
+ onResponse: (status, summary) => { httpStatus = status; onResponse(status, summary); },
21
31
  credential: access.credential,
22
32
  organizationId: access.organizationId,
23
33
  signal
24
34
  });
25
35
  await observe?.({ accepted: true });
26
- const streamed = await parseCreativeStream(stream, signal, observe ? async (contextId) => observe({ contextId }) : undefined);
27
- return { streamed, contextId: creativeContextId(streamed) };
28
- });
29
- return dependencies.telemetry.stage("result", async () => {
30
- const messages = await dependencies.transport.getJson({
31
- path: `/ai-agent/v1/thread/${encodeURIComponent(contextId)}/messages`,
32
- credential: access.credential,
33
- organizationId: access.organizationId,
34
- signal
36
+ const streamed = await parseCreativeStream(stream, signal, async (contextId) => {
37
+ correlation.agentContextId = contextId;
38
+ dependencies.telemetry.annotate({ diagnostic_summary: { agentContextId: contextId } });
39
+ await observe?.({ contextId });
40
+ }, {
41
+ startedAt, ...(httpStatus === undefined ? {} : { httpStatus }),
42
+ onDiagnostics: diagnostic_summary => dependencies.telemetry.annotate({ diagnostic_summary })
35
43
  });
36
- const output = normalizeCreativeMessages(restoreCreativeResourceUrls(creativeTurnMessages(messages, ids.localMessageId), streamed));
44
+ const contextId = creativeContextId(streamed);
45
+ dependencies.telemetry.annotate({ diagnostic_summary: { agentContextId: contextId } });
46
+ return { streamed, contextId };
47
+ }, correlation));
48
+ return dependencies.telemetry.stage("result", async () => {
49
+ const output = await withResponseDiagnostics(async (onResponse) => {
50
+ const messages = await dependencies.transport.getJson({
51
+ path: `/ai-agent/v1/thread/${encodeURIComponent(contextId)}/messages`,
52
+ credential: access.credential,
53
+ organizationId: access.organizationId,
54
+ onResponse,
55
+ signal
56
+ });
57
+ let usageModelMissing = false;
58
+ const normalized = normalizeCreativeMessages(restoreCreativeResourceUrls(creativeTurnMessages(messages, ids.localMessageId), streamed), () => { usageModelMissing = true; });
59
+ if (usageModelMissing)
60
+ await observe?.({ agentUsageModelMissing: true });
61
+ return normalized;
62
+ }, correlation);
37
63
  return dependencies.resourceAuthorizer
38
64
  ? dependencies.resourceAuthorizer.authorize(output, access, signal)
39
65
  : output;
@@ -395,7 +395,7 @@ function dedupeParts(parts) {
395
395
  return true;
396
396
  });
397
397
  }
398
- export function normalizeCreativeMessages(messages) {
398
+ export function normalizeCreativeMessages(messages, onUsageModelMissing) {
399
399
  const contextId = creativeContextId(messages);
400
400
  const latest = new Map();
401
401
  const anonymous = [];
@@ -440,6 +440,7 @@ export function normalizeCreativeMessages(messages) {
440
440
  if (publicParts.length === 0)
441
441
  return fail("AGENT_RESULT_EMPTY", { messageCount: normalized.length, publicPartCount: 0 });
442
442
  const usageItems = [];
443
+ let totalCost = 0;
443
444
  for (const message of normalized) {
444
445
  if (contentOf(message)?.type !== "function_response")
445
446
  continue;
@@ -449,11 +450,14 @@ export function normalizeCreativeMessages(messages) {
449
450
  continue;
450
451
  if (typeof amount !== "number" || !Number.isFinite(amount) || amount < 0)
451
452
  return fail();
453
+ totalCost += amount;
454
+ const model = nonEmptyString(extra?.scene_code);
455
+ if (model === undefined) {
456
+ onUsageModelMissing?.();
457
+ continue;
458
+ }
452
459
  if (amount === 0)
453
460
  continue;
454
- const model = nonEmptyString(extra?.scene_code);
455
- if (model === undefined)
456
- return fail("AGENT_USAGE_MODEL_MISSING", { messageCount: normalized.length, publicPartCount: publicParts.length });
457
461
  usageItems.push({ model, cost: { unit: "gaodou", amount } });
458
462
  }
459
463
  return {
@@ -465,7 +469,7 @@ export function normalizeCreativeMessages(messages) {
465
469
  usage: {
466
470
  cost: {
467
471
  unit: "gaodou",
468
- amount: usageItems.reduce((total, item) => total + item.cost.amount, 0)
472
+ amount: totalCost
469
473
  },
470
474
  items: usageItems
471
475
  }
@@ -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)