@insmind/cli 1.5.0 → 1.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/dist/bin/agent-worker.js +2 -1
  2. package/dist/bin/insmind-cli.js +12 -7
  3. package/dist/bin/postinstall.js +7 -5
  4. package/dist/src/bootstrap/create-cli.js +26 -17
  5. package/dist/src/bootstrap/create-runtime.js +31 -13
  6. package/dist/src/bootstrap/run-agent-worker.js +2 -1
  7. package/dist/src/bootstrap/validators.js +10 -5
  8. package/dist/src/cli/action-binding.js +14 -0
  9. package/dist/src/cli/agent-commands.js +8 -3
  10. package/dist/src/cli/auth-commands.js +1 -1
  11. package/dist/src/cli/credits-command.js +2 -2
  12. package/dist/src/cli/dam-commands.js +51 -52
  13. package/dist/src/cli/editor-commands.js +13 -15
  14. package/dist/src/cli/errors.js +91 -41
  15. package/dist/src/cli/model-commands.js +7 -5
  16. package/dist/src/cli/presenter.js +13 -10
  17. package/dist/src/cli/task-commands.js +13 -5
  18. package/dist/src/cli/tool-commands.js +9 -3
  19. package/dist/src/features/agent/use-cases.js +11 -5
  20. package/dist/src/features/auth/credential-store.js +2 -2
  21. package/dist/src/features/auth/sso-service.js +3 -2
  22. package/dist/src/features/auth/state.js +2 -0
  23. package/dist/src/features/auth/use-cases.js +30 -34
  24. package/dist/src/features/credits/use-cases.js +2 -0
  25. package/dist/src/features/dam/file-downloader.js +38 -16
  26. package/dist/src/features/dam/object-storage.js +23 -11
  27. package/dist/src/features/dam/operation-executor.js +46 -37
  28. package/dist/src/features/dam/registered-uploader.js +39 -29
  29. package/dist/src/features/dam/storage-upload.js +5 -4
  30. package/dist/src/features/dam/use-cases.js +81 -60
  31. package/dist/src/features/editor/bridge-client.js +6 -6
  32. package/dist/src/features/editor/bridge-process.js +2 -1
  33. package/dist/src/features/editor/session-state.js +6 -4
  34. package/dist/src/features/editor/session.js +26 -8
  35. package/dist/src/features/editor/use-cases.js +10 -3
  36. package/dist/src/features/org/use-cases.js +2 -1
  37. package/dist/src/features/task/agent-background.js +1 -0
  38. package/dist/src/features/task/store.js +2 -0
  39. package/dist/src/features/task/use-cases.js +80 -27
  40. package/dist/src/features/tool/catalog.js +11 -5
  41. package/dist/src/features/tool/dynamic-schema.js +9 -7
  42. package/dist/src/features/tool/mns-catalog-adapter.js +7 -23
  43. package/dist/src/features/tool/tool-api-adapter.js +8 -7
  44. package/dist/src/features/tool/use-cases.js +7 -3
  45. package/dist/src/features/update/update-notification.js +75 -70
  46. package/dist/src/features/update/update-service.js +24 -20
  47. package/dist/src/platform/file-lock.js +36 -9
  48. package/dist/src/platform/interruption.js +13 -0
  49. package/dist/src/platform/json-input.js +12 -9
  50. package/dist/src/platform/local-json-file.js +8 -4
  51. package/dist/src/platform/redact.js +7 -1
  52. package/dist/src/platform/remote-protocol.js +2 -2
  53. package/dist/src/platform/safe-upload-file.js +2 -1
  54. package/dist/src/platform/schema-issues.js +8 -0
  55. package/dist/src/platform/signed-http-transport.js +8 -7
  56. package/dist/src/platform/text-output.js +33 -0
  57. package/dist/src/telemetry/invocation.js +19 -4
  58. package/dist/src/telemetry/process-errors.js +14 -4
  59. package/dist/src/telemetry/sanitize.js +4 -2
  60. package/dist/src/telemetry/sls-sink.js +36 -20
  61. package/package.json +4 -4
@@ -9,6 +9,7 @@ if (!process.send) {
9
9
  process.exitCode = 2;
10
10
  }
11
11
  else {
12
+ const startedAt = Date.now();
12
13
  const controller = new AbortController();
13
14
  const interrupt = () => controller.abort(new Error("SIGINT"));
14
15
  process.once("SIGINT", interrupt);
@@ -36,7 +37,7 @@ else {
36
37
  await runAgentWorker({ runtime, job, signal: controller.signal, send });
37
38
  }
38
39
  catch (error) {
39
- await reportProcessError(error, { operation: "bootstrap", processRole: "agent_worker",
40
+ await reportProcessError(error, { operation: "bootstrap", processRole: "agent_worker", startedAt, signal: controller.signal,
40
41
  stateDirectory: currentJob?.product === "insmind" ? ".insmind" : ".gd",
41
42
  ...(currentJob?.telemetryTrackingUrl ? { trackingUrl: new URL(currentJob.telemetryTrackingUrl) } : {}),
42
43
  ...(currentJob?.telemetryEnvironment ? { environment: currentJob.telemetryEnvironment } : {}),
@@ -1,6 +1,10 @@
1
1
  #!/usr/bin/env node
2
+ import { randomBytes } from "node:crypto";
3
+ import { isInterruption } from "../src/platform/interruption.js";
2
4
  import { insmindProduct } from "../src/product/config.js";
3
5
  import { localeOption } from "../src/product/locale.js";
6
+ const startedAt = Date.now();
7
+ const bootstrapTraceId = randomBytes(16).toString("hex");
4
8
  const controller = new AbortController();
5
9
  const interrupt = () => controller.abort(new Error("SIGINT"));
6
10
  process.once("SIGINT", interrupt);
@@ -35,28 +39,29 @@ try {
35
39
  });
36
40
  }
37
41
  catch (error) {
42
+ const traceId = runtime?.telemetry.traceId ?? bootstrapTraceId;
38
43
  try {
39
44
  const { reportProcessError } = await import("../src/telemetry/process-errors.js");
40
- await reportProcessError(error, { operation: "bootstrap", stateDirectory: ".insmind" });
45
+ await reportProcessError(error, { operation: "bootstrap", startedAt, traceId, signal: controller.signal, stateDirectory: ".insmind" });
41
46
  }
42
47
  catch { /* Retain startup error output even if diagnostic modules cannot load. */ }
43
48
  if (mapCliError === undefined || redact === undefined) {
44
- process.stderr.write("INTERNAL_ERROR: CLI failed to start.\n");
49
+ process.stderr.write(`INTERNAL_ERROR: CLI failed to start. Diagnostic ID: ${traceId}\n`);
45
50
  process.exitCode = 1;
46
51
  }
47
52
  else {
48
- const outcome = redact(mapCliError(error, { aborted: controller.signal.aborted, product: insmindProduct }));
53
+ const outcome = redact(mapCliError(error, { aborted: isInterruption(error, controller.signal), product: insmindProduct }));
49
54
  if (runtime) {
50
- runtime.presenter.error(outcome, { json: process.argv.includes("--json") });
55
+ runtime.presenter.error(outcome, { json: process.argv.includes("--json"), traceId });
51
56
  }
52
57
  else if (outcome.kind === "interrupted") {
53
- process.stderr.write("Cancelled.\n");
58
+ process.stderr.write(`Local waiting stopped; dispatched operations may still be active. Diagnostic ID: ${traceId}\n`);
54
59
  }
55
60
  else if (process.argv.includes("--json")) {
56
- process.stderr.write(`${JSON.stringify({ error: outcome.failure })}\n`);
61
+ process.stderr.write(`${JSON.stringify({ error: { ...outcome.failure, trace_id: traceId } })}\n`);
57
62
  }
58
63
  else {
59
- process.stderr.write(`${outcome.failure.code}: ${outcome.failure.message}\n`);
64
+ process.stderr.write(`${outcome.failure.code}: ${outcome.failure.message}\nDiagnostic ID: ${traceId}\n`);
60
65
  }
61
66
  process.exitCode = outcome.exitCode;
62
67
  }
@@ -18,11 +18,13 @@ export function isSupportedGlobalLifecycle(env) {
18
18
  && /\/v\d+\/[0-9a-f]+-[0-9a-f]+-[0-9a-f]{16}$/u.test(initialDirectory);
19
19
  }
20
20
  export async function runPostinstall(options = {}) {
21
+ const startedAt = Date.now();
21
22
  const env = options.env ?? process.env;
23
+ const english = env.npm_package_name === "@insmind/cli";
22
24
  if (!isSupportedGlobalLifecycle(env))
23
25
  return;
24
26
  const reportError = options.reportError ?? (options.env ? async () => undefined : (error) => reportProcessError(error, {
25
- operation: "postinstall", processRole: "postinstall", stateDirectory: env.npm_package_name === "@insmind/cli" ? ".insmind" : ".gd"
27
+ operation: "postinstall", startedAt, processRole: "postinstall", stateDirectory: env.npm_package_name === "@insmind/cli" ? ".insmind" : ".gd"
26
28
  }));
27
29
  const writeError = options.writeError ?? ((text) => process.stderr.write(text));
28
30
  let skills;
@@ -32,9 +34,9 @@ export async function runPostinstall(options = {}) {
32
34
  catch (error) {
33
35
  await reportError(error);
34
36
  if (env.GD_CLI_INSTALL_OWNER === "workbuddy") {
35
- throw new Error("无法确认当前安装的 package。");
37
+ throw new Error(english ? "Cannot identify the installed package." : "无法确认当前安装的 package。", { cause: error });
36
38
  }
37
- writeError(`警告: ${oneLineMessage(error)}\n`);
39
+ writeError(`${english ? "Warning: Agent Skill installation failed; inspect the target paths and permissions." : "警告: Agent Skill 安装失败,请检查目标路径和权限。"} ${oneLineMessage(error)}\n`);
38
40
  return;
39
41
  }
40
42
  const [primarySkill] = skills;
@@ -49,7 +51,7 @@ export async function runPostinstall(options = {}) {
49
51
  if (owner === "workbuddy")
50
52
  return;
51
53
  if (owner === "invalid")
52
- throw new Error("无法确认当前安装的托管信息。");
54
+ throw new Error(english ? "Cannot identify the installation owner." : "无法确认当前安装的托管信息。");
53
55
  try {
54
56
  await (options.syncSkills ?? syncBundledSkills)(skills, {
55
57
  env,
@@ -58,7 +60,7 @@ export async function runPostinstall(options = {}) {
58
60
  }
59
61
  catch (error) {
60
62
  await reportError(error);
61
- writeError(`警告: ${oneLineMessage(error)}\n`);
63
+ writeError(`${english ? "Warning: Agent Skill installation failed; inspect the target paths and permissions." : "警告: Agent Skill 安装失败,请检查目标路径和权限。"} ${oneLineMessage(error)}\n`);
62
64
  }
63
65
  }
64
66
  function oneLineMessage(error) {
@@ -1,6 +1,7 @@
1
+ import { isInterruption } from "../platform/interruption.js";
1
2
  import { registerTaskCommands } from "../cli/task-commands.js";
2
3
  import { Command, CommanderError } from "commander";
3
- import { assertAllLeafCommandsBound, configureActionEnvironment } from "../cli/action-binding.js";
4
+ import { assertAllLeafCommandsBound, errorUsesJson, configureActionEnvironment } from "../cli/action-binding.js";
4
5
  import { registerAgentCommands } from "../cli/agent-commands.js";
5
6
  import { registerAuthCommands } from "../cli/auth-commands.js";
6
7
  import { classifyTelemetryError, isHelpOutcome, mapCliError } from "../cli/errors.js";
@@ -13,6 +14,7 @@ import { registerUpdateCommand } from "../cli/update-command.js";
13
14
  import { registerCreditsCommand } from "../cli/credits-command.js";
14
15
  import { redact } from "../platform/redact.js";
15
16
  export { assertAllLeafCommandsBound, bindAction } from "../cli/action-binding.js";
17
+ const outputs = new WeakMap();
16
18
  export function createCli(runtime, options) {
17
19
  runtime.telemetry.useSignal(options.signal);
18
20
  const program = new Command()
@@ -28,6 +30,9 @@ export function createCli(runtime, options) {
28
30
  writeOut: runtime.io.writeOut,
29
31
  writeErr: () => undefined
30
32
  });
33
+ program.addHelpText("after", runtime.product.id === "insmind"
34
+ ? "\nstdout contains command results; stderr contains progress, warnings and errors. Fixed JSON commands and --json use {error:{code,message,details?,trace_id?}} for final errors. stderr may contain multiple messages.\nExit codes: 0 success, 1 execution failure, 2 invalid input, 130 local interruption; dispatched work may still be active.\n"
35
+ : "\nstdout 输出命令结果;stderr 输出进度、警告和错误。固定 JSON 命令和 --json 的最终错误使用 {error:{code,message,details?,trace_id?}},stderr 可能包含多条信息。\n退出码:0 成功,1 执行失败,2 输入无效,130 本地中断;已派发的工作可能仍在继续。\n");
31
36
  if (runtime.product.id === "insmind") {
32
37
  program.option("--locale <locale>", "locale for service-owned business descriptions");
33
38
  }
@@ -50,26 +55,29 @@ export function createCli(runtime, options) {
50
55
  registerUpdateCommand(program, runtime);
51
56
  registerTaskCommands(program, runtime);
52
57
  assertAllLeafCommandsBound(program);
58
+ outputs.set(program, runtime.io);
53
59
  return program;
54
60
  }
55
61
  export async function executeCli(options) {
62
+ let helpOnly = false;
56
63
  try {
57
- await options.program.parseAsync(options.argv, { from: "user" });
58
- await sendFinished(options, { outcome: "success" });
64
+ try {
65
+ await options.program.parseAsync(options.argv, { from: "user" });
66
+ }
67
+ catch (error) {
68
+ if (!isHelpOutcome(error))
69
+ throw error;
70
+ helpOnly = true;
71
+ if (options.argv[0] !== "update")
72
+ await checkUpdateNotification(options.updateNotification, options.signal);
73
+ options.signal.throwIfAborted();
74
+ }
75
+ await options.telemetry.stage("output", async () => { await outputs.get(options.program)?.flush?.(); });
76
+ if (!helpOnly)
77
+ await sendFinished(options, { outcome: "success" });
59
78
  return 0;
60
79
  }
61
80
  catch (error) {
62
- if (isHelpOutcome(error)) {
63
- if (options.argv[0] !== "update") {
64
- await checkUpdateNotification(options.updateNotification, options.signal);
65
- }
66
- if (options.signal.aborted) {
67
- options.presenter.error({ kind: "interrupted", exitCode: 130 }, { json: options.argv.includes("--json") });
68
- await sendFinished(options, { outcome: "interrupted" });
69
- return 130;
70
- }
71
- return 0;
72
- }
73
81
  if (!options.telemetry.selected)
74
82
  options.telemetry.select({ operation: "unknown" });
75
83
  if (options.telemetry.selected && error instanceof CommanderError) {
@@ -81,22 +89,23 @@ export async function executeCli(options) {
81
89
  }
82
90
  }
83
91
  const outcome = redact(mapCliError(error, {
84
- aborted: options.signal.aborted && (error === options.signal.reason || error instanceof Error && error.name === "AbortError"),
92
+ aborted: isInterruption(error, options.signal),
85
93
  ...(options.product ? { product: options.product } : {})
86
94
  }));
87
- const telemetryError = classifyTelemetryError(error, { aborted: options.signal.aborted && (error === options.signal.reason || error instanceof Error && error.name === "AbortError"), ...(options.product ? { product: options.product } : {}) });
95
+ const telemetryError = classifyTelemetryError(error, { aborted: isInterruption(error, options.signal), ...(options.product ? { product: options.product } : {}) });
88
96
  const traceId = options.telemetry.selected
89
97
  ? options.telemetry.traceId
90
98
  : undefined;
91
99
  try {
92
100
  options.presenter.error(outcome, {
93
- json: options.argv.includes("--json"),
101
+ json: errorUsesJson(options.program, options.argv),
94
102
  ...(traceId ? { traceId } : {})
95
103
  });
96
104
  }
97
105
  catch (presenterError) {
98
106
  await options.telemetry.stage("output", () => { throw presenterError; }).catch(() => undefined);
99
107
  }
108
+ await options.telemetry.stage("output", async () => { await outputs.get(options.program)?.flush?.(); }).catch(() => undefined);
100
109
  await sendFinished(options, outcome.kind === "interrupted"
101
110
  ? { outcome: "interrupted", error }
102
111
  : {
@@ -1,4 +1,5 @@
1
1
  import { taskScope } from "../features/task/store.js";
2
+ import { createTextOutput } from "../platform/text-output.js";
2
3
  import { TaskNotFoundError } from "../features/task/use-cases.js";
3
4
  import { homedir } from "node:os";
4
5
  import { createAgentBackgroundLauncher } from "../features/task/agent-background.js";
@@ -105,9 +106,12 @@ export function createProductionRuntime(options = {}) {
105
106
  inputTerminal: process.stdin.isTTY === true,
106
107
  stderrTerminal: process.stderr.isTTY === true
107
108
  };
109
+ const stdout = createTextOutput(rawIo.stdout);
110
+ const stderr = createTextOutput(rawIo.stderr);
108
111
  const io = {
109
- writeOut: (text) => { rawIo.stdout.write(text); },
110
- writeError: (text) => { rawIo.stderr.write(text); },
112
+ writeOut: stdout.write,
113
+ writeError: stderr.write,
114
+ flush: async () => { await Promise.all([stdout.flush(), stderr.flush()]); },
111
115
  inputTerminal: rawIo.inputTerminal ?? hasTerminal(rawIo.input),
112
116
  stderrTerminal: rawIo.stderrTerminal ?? hasTerminal(rawIo.stderr)
113
117
  };
@@ -188,7 +192,7 @@ export function createProductionRuntime(options = {}) {
188
192
  }
189
193
  });
190
194
  const storage = options.objectStorage ?? createObjectStorageUploader({ fetch, now,
191
- reportError: error => telemetry.stage("upload.attempt", () => { throw error; }).catch(() => undefined)
195
+ telemetry
192
196
  });
193
197
  const credits = createCreditsUseCases({
194
198
  transport: creditsTransport,
@@ -230,7 +234,8 @@ export function createProductionRuntime(options = {}) {
230
234
  uploader: createDamRegisteredUploader({
231
235
  api: damApi,
232
236
  storage: storageUpload,
233
- warn: (message) => { presenter.warning(message); },
237
+ warn: (message) => { telemetry.annotate({ warning_codes: ["ASSET_ANALYSIS_PENDING"] }); presenter.warning(message); },
238
+ ...(product.id === "insmind" ? { analysisPendingMessage: "Asset analysis is still pending; the current registered asset is returned." } : {}),
234
239
  now,
235
240
  telemetry
236
241
  }),
@@ -321,6 +326,7 @@ export function createProductionRuntime(options = {}) {
321
326
  idFactory: randomUUID,
322
327
  now,
323
328
  notice: message => presenter.notice(message),
329
+ warning: message => presenter.warning(message),
324
330
  commandName: product.commandName,
325
331
  text,
326
332
  failureNote: error => {
@@ -351,16 +357,27 @@ export function createProductionRuntime(options = {}) {
351
357
  state: "unknown", note: text("本地记录未取得可查询的 Tool 回执;不自动重新生成。", "No queryable Tool receipt was recorded; do not generate again.")
352
358
  };
353
359
  await authorizeTaskAccess(state, signal);
354
- const response = await queryToolResult(toolTransport, {
355
- taskId: progress.remoteTaskId, credential: state.credential,
356
- organizationId: state.organization.id, signal
357
- });
360
+ const taskId = progress.remoteTaskId;
361
+ let response;
362
+ try {
363
+ response = await telemetry.stage("task.query", async () => {
364
+ const result = await queryToolResult(toolTransport, {
365
+ taskId, credential: state.credential, organizationId: state.organization.id, signal
366
+ });
367
+ if (result.difyTaskId)
368
+ telemetry.annotate({ dify_task_id: result.difyTaskId });
369
+ if (result.state === "failed")
370
+ throw result.error;
371
+ return result;
372
+ });
373
+ }
374
+ catch (error) {
375
+ if (!(error instanceof ToolTaskFailedError))
376
+ throw error;
377
+ return { state: "failed", note: text(error.message, "The Tool run failed.") };
378
+ }
358
379
  if (response.state === "pending")
359
380
  return { state: "running", note: text("原 Tool 查询尚未返回最终结果。", "The original Tool is still processing.") };
360
- if (response.state === "failed") {
361
- await telemetry.stage("task.recover", () => { throw response.error; }).catch(() => undefined);
362
- return { state: "failed", note: text(response.error.message, response.error instanceof ToolTaskFailedError ? "The Tool run failed." : "The Tool service response is incompatible with this CLI.") };
363
- }
364
381
  return { state: "completed", result: await authorizeTaskResult(toolOutputWithBillingUnit({
365
382
  content: response.content, usage: progress.toolUsage
366
383
  }, product.billingUnit), state, signal, true) };
@@ -382,6 +399,7 @@ export function createProductionRuntime(options = {}) {
382
399
  const tool = withToolBillingUnit(createToolUseCases({
383
400
  catalog: modelCatalog,
384
401
  tools: product.tools,
402
+ ...(product.id === "insmind" ? { modelDescription: "Model machine identifier from model list." } : {}),
385
403
  execution: createToolApiAdapter({ transport: toolTransport, telemetry }),
386
404
  uploader: transientUploader,
387
405
  warn: (message) => { presenter.warning(message); },
@@ -434,7 +452,7 @@ export function createProductionRuntime(options = {}) {
434
452
  }
435
453
  };
436
454
  const updateNotification = createUpdateNotificationService({
437
- reportError: error => telemetry.stage("update_check", () => { throw error; }).catch(() => undefined),
455
+ telemetry,
438
456
  currentVersion: primarySkill.version,
439
457
  fetch,
440
458
  now,
@@ -1,3 +1,4 @@
1
+ import { isInterruption } from "../platform/interruption.js";
1
2
  import { mapCliError } from "../cli/errors.js";
2
3
  import { redact } from "../platform/redact.js";
3
4
  export async function runAgentWorker(options) {
@@ -36,7 +37,7 @@ export async function runAgentWorker(options) {
36
37
  });
37
38
  }
38
39
  catch (error) {
39
- const outcome = redact(mapCliError(error, { aborted: signal.aborted && (error === signal.reason || error instanceof Error && error.name === "AbortError"), product: runtime.product }));
40
+ const outcome = redact(mapCliError(error, { aborted: isInterruption(error, signal), product: runtime.product }));
40
41
  completion = outcome.kind === "interrupted" ? { outcome: "interrupted", error }
41
42
  : { outcome: "failure", error, errorCode: outcome.failure.code, errorMessage: outcome.failure.message };
42
43
  if (outcome.kind === "failure")
@@ -1,3 +1,4 @@
1
+ import { validationIssues } from "../platform/schema-issues.js";
1
2
  import { Ajv2020 } from "ajv/dist/2020.js";
2
3
  import addFormatsImport, {} from "ajv-formats";
3
4
  import { contractSchema } from "../contracts/schema.js";
@@ -43,14 +44,18 @@ const toolCallInputSchema = contractSchema("tool.call", "input");
43
44
  const toolCallOutputSchema = contractSchema("tool.call", "output");
44
45
  const toolListOutputSchema = contractSchema("tool.list", "output");
45
46
  export class InputContractError extends Error {
46
- constructor() {
47
- super("输入不符合命令契约。");
47
+ issues;
48
+ constructor(issues = []) {
49
+ super(`输入不符合命令契约。${issues.length ? ` ${JSON.stringify(issues)}` : ""}`);
50
+ this.issues = issues;
48
51
  this.name = "InputContractError";
49
52
  }
50
53
  }
51
54
  export class OutputContractError extends Error {
52
- constructor() {
53
- super("命令结果不符合公开契约。");
55
+ issues;
56
+ constructor(issues = []) {
57
+ super(`命令结果不符合公开契约。${issues.length ? ` ${JSON.stringify(issues)}` : ""}`);
58
+ this.issues = issues;
54
59
  this.name = "OutputContractError";
55
60
  }
56
61
  }
@@ -164,6 +169,6 @@ const unavailableValidator = Object.assign(() => false, { errors: null, schema:
164
169
  function assertion(validate, ErrorType) {
165
170
  return (value) => {
166
171
  if (!validate(value))
167
- throw new ErrorType();
172
+ throw new ErrorType(validationIssues(validate.errors));
168
173
  };
169
174
  }
@@ -1,5 +1,18 @@
1
1
  const environments = new WeakMap();
2
2
  const boundPolicies = new WeakMap();
3
+ const jsonCommands = new WeakSet();
4
+ const selectedCommands = new WeakMap();
5
+ /** Declare the existing fixed JSON contract alongside the command registration. */
6
+ export function jsonOutput(command) {
7
+ jsonCommands.add(command);
8
+ }
9
+ export function errorUsesJson(program, argv) {
10
+ const command = selectedCommands.get(program);
11
+ if (command)
12
+ return jsonCommands.has(command) || command.opts().json === true;
13
+ const end = argv.indexOf("--");
14
+ return (end < 0 ? argv : argv.slice(0, end)).includes("--json");
15
+ }
3
16
  export function configureActionEnvironment(program, environment) {
4
17
  environments.set(program, environment);
5
18
  }
@@ -83,6 +96,7 @@ function bindTelemetrySelection(command, definition) {
83
96
  command.parent.hook("preSubcommand", (parent, selected) => {
84
97
  if (selected !== command)
85
98
  return;
99
+ selectedCommands.set(rootCommand(parent), command);
86
100
  const environment = environments.get(rootCommand(parent));
87
101
  if (!environment)
88
102
  throw new Error("CLI action environment is missing.");
@@ -1,5 +1,5 @@
1
1
  import { contractSchema } from "../contracts/schema.js";
2
- import { bindPreparedAction } from "./action-binding.js";
2
+ import { jsonOutput, bindPreparedAction } from "./action-binding.js";
3
3
  import { CliUsageError } from "./errors.js";
4
4
  import { productText as text } from "../product/text.js";
5
5
  const agentSendInputSchema = contractSchema("agent.send", "input");
@@ -15,6 +15,8 @@ export function registerAgentCommands(program, runtime) {
15
15
  .allowExcessArguments(false);
16
16
  send.addHelpText("after", [
17
17
  "",
18
+ text(runtime.product, "完整结果已校验但最终本地记录保存失败时仍返回结果和退出码 0;stderr 警告 task get 可能无法恢复,请保留输出。", "A validated complete result is delivered with exit code 0 even if its final local record cannot be saved; stderr warns that task get may not recover it. Keep the output."),
19
+ text(runtime.product, "最终错误为 stderr 中的 JSON error 对象;stderr 也可能有进度和警告。中断退出码 130 只表示本地停止等待。", "The final error is a JSON error object on stderr, which may also contain progress and warnings. Exit code 130 means local waiting stopped."),
18
20
  text(runtime.product, "--async 在服务端受理后输出包含 taskId 和 state 的 JSON;退出码 0 仅表示受理。", "--async returns JSON with taskId and state after acceptance; exit code 0 means accepted only."),
19
21
  text(runtime.product, "用 task get <taskId> 查询原任务;completed 时 result 为完整结果,running/unknown 或查询超时不应重新提交。", "Query the same taskId with task get; completed includes result. Do not resubmit on running, unknown, or a query timeout."),
20
22
  text(runtime.product, "Agent 异步由本机后台进程继续执行;进程终止或关机可能使状态变为 unknown。", "Agent async continues in a local background process; termination or shutdown may leave its state unknown."),
@@ -27,6 +29,7 @@ export function registerAgentCommands(program, runtime) {
27
29
  text(runtime.product, "usage 仅覆盖本次调用,不包含其他命令调用的消耗。", "usage covers this invocation only, excluding other command invocations."),
28
30
  ""
29
31
  ].join("\n"));
32
+ jsonOutput(send);
30
33
  bindPreparedAction(send, "organization", async (signal) => {
31
34
  signal.throwIfAborted();
32
35
  const options = send.opts();
@@ -51,8 +54,10 @@ export function registerAgentCommands(program, runtime) {
51
54
  };
52
55
  if (send.opts().async) {
53
56
  const result = await runtime.startAgentTask({ state: context.state, label: task.label, input }, signal);
54
- runtime.validators.taskResult(result);
55
- runtime.io.writeOut(`${JSON.stringify(result)}\n`);
57
+ await runtime.telemetry.stage("output", async () => {
58
+ runtime.validators.taskResult(result);
59
+ runtime.io.writeOut(`${JSON.stringify(result)}\n`);
60
+ });
56
61
  return;
57
62
  }
58
63
  const run = async (observe) => {
@@ -28,7 +28,7 @@ export function registerAuthCommands(program, runtime) {
28
28
  ? text(runtime.product, "已登录。", "Already signed in.")
29
29
  : text(runtime.product, "登录成功。", "Signed in successfully."));
30
30
  if (result.status === "already_logged_in" && !result.organizationSelected) {
31
- runtime.presenter.warning("尚未选择组织,请执行 gd-cli org switch。");
31
+ runtime.presenter.warning("尚未选择组织,请执行 gd-cli org list,再执行 gd-cli org switch --org <org-id>。");
32
32
  }
33
33
  });
34
34
  }, { operation: "auth.login" });
@@ -5,11 +5,11 @@ export function registerCreditsCommand(program, runtime) {
5
5
  .option("--json", "output JSON")
6
6
  .allowExcessArguments(false);
7
7
  bindAction(credits, "organization", async (context, signal) => {
8
- const result = await runtime.credits.get({
8
+ const result = await runtime.telemetry.stage("request", () => runtime.credits.get({
9
9
  credential: context.state.credential,
10
10
  organizationId: context.state.organization.id,
11
11
  signal
12
- });
12
+ }));
13
13
  await runtime.telemetry.stage("output", async () => {
14
14
  runtime.presenter.result(result, {
15
15
  json: credits.opts().json === true,