@insmind/cli 1.3.1 → 1.4.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 (33) hide show
  1. package/dist/bin/agent-worker.js +13 -1
  2. package/dist/bin/insmind-cli.js +7 -0
  3. package/dist/bin/postinstall.js +11 -2
  4. package/dist/src/bootstrap/create-cli.js +15 -7
  5. package/dist/src/bootstrap/create-runtime.js +73 -35
  6. package/dist/src/bootstrap/run-agent-worker.js +12 -1
  7. package/dist/src/cli/action-binding.js +1 -2
  8. package/dist/src/cli/errors.js +5 -3
  9. package/dist/src/cli/task-commands.js +3 -2
  10. package/dist/src/features/agent/creative-agent-adapter.js +1 -0
  11. package/dist/src/features/agent/creative-protocol.js +4 -2
  12. package/dist/src/features/auth/access-policy.js +8 -0
  13. package/dist/src/features/auth/sso-service.js +76 -26
  14. package/dist/src/features/auth/use-cases.js +1 -1
  15. package/dist/src/features/dam/file-downloader.js +6 -6
  16. package/dist/src/features/dam/object-storage.js +6 -4
  17. package/dist/src/features/editor/bridge-process.js +9 -3
  18. package/dist/src/features/editor/bridge-server.js +4 -2
  19. package/dist/src/features/org/use-cases.js +8 -3
  20. package/dist/src/features/task/store.js +34 -2
  21. package/dist/src/features/task/use-cases.js +71 -6
  22. package/dist/src/features/tool/tool-api-adapter.js +1 -0
  23. package/dist/src/features/update/update-notification.js +4 -2
  24. package/dist/src/platform/file-lock.js +68 -0
  25. package/dist/src/platform/redact.js +1 -1
  26. package/dist/src/platform/safe-upload-file.js +3 -3
  27. package/dist/src/platform/signed-http-transport.js +23 -9
  28. package/dist/src/telemetry/invocation.js +74 -122
  29. package/dist/src/telemetry/process-errors.js +43 -0
  30. package/dist/src/telemetry/sanitize.js +72 -0
  31. package/dist/src/telemetry/sls-sink.js +209 -22
  32. package/package.json +4 -4
  33. package/skills/insmind-cli/references/creation.md +12 -0
@@ -1,4 +1,5 @@
1
1
  // Private one-task process; not a public CLI command or a resident service.
2
+ import { reportProcessError } from "../src/telemetry/process-errors.js";
2
3
  import { once } from "node:events";
3
4
  import { Readable } from "node:stream";
4
5
  import { gaodingProduct, insmindProduct } from "../src/product/config.js";
@@ -16,19 +17,30 @@ else {
16
17
  if (process.connected)
17
18
  process.send?.(message, () => undefined);
18
19
  };
20
+ let currentJob;
19
21
  try {
20
22
  const [job] = await once(process, "message");
23
+ currentJob = job;
21
24
  const product = job.product === "insmind" ? insmindProduct : gaodingProduct;
22
25
  const endpoints = { ...product.endpoints };
23
26
  for (const key of Object.keys(endpoints))
24
27
  endpoints[key] = new URL(job.endpoints[key]);
25
28
  const runtime = createProductionRuntime({
29
+ processRole: "agent_worker",
30
+ ...(job.telemetryVersion ? { telemetryVersion: job.telemetryVersion } : {}),
31
+ ...(job.telemetryTrackingUrl ? { telemetryTrackingUrl: new URL(job.telemetryTrackingUrl) } : {}),
32
+ ...(job.telemetryEnvironment ? { telemetryEnvironment: job.telemetryEnvironment } : {}),
26
33
  product, endpoints, homeDirectory: job.homeDirectory, locale: job.locale,
27
34
  io: { input: Readable.from([]), stdout: { write() { } }, stderr: { write() { } } }
28
35
  });
29
36
  await runAgentWorker({ runtime, job, signal: controller.signal, send });
30
37
  }
31
- catch {
38
+ catch (error) {
39
+ await reportProcessError(error, { operation: "bootstrap", processRole: "agent_worker",
40
+ stateDirectory: currentJob?.product === "insmind" ? ".insmind" : ".gd",
41
+ ...(currentJob?.telemetryTrackingUrl ? { trackingUrl: new URL(currentJob.telemetryTrackingUrl) } : {}),
42
+ ...(currentJob?.telemetryEnvironment ? { environment: currentJob.telemetryEnvironment } : {}),
43
+ ...(currentJob?.homeDirectory ? { homeDirectory: currentJob.homeDirectory } : {}) });
32
44
  send({ type: "error", failure: { code: "TASK_WORKER_UNAVAILABLE", message: "The background task could not start. Check task list/get before submitting again." }, exitCode: 1 });
33
45
  process.exitCode = 1;
34
46
  }
@@ -4,6 +4,7 @@ import { localeOption } from "../src/product/locale.js";
4
4
  const controller = new AbortController();
5
5
  const interrupt = () => controller.abort(new Error("SIGINT"));
6
6
  process.once("SIGINT", interrupt);
7
+ process.once("SIGTERM", interrupt);
7
8
  let runtime;
8
9
  let mapCliError;
9
10
  let redact;
@@ -34,6 +35,11 @@ try {
34
35
  });
35
36
  }
36
37
  catch (error) {
38
+ try {
39
+ const { reportProcessError } = await import("../src/telemetry/process-errors.js");
40
+ await reportProcessError(error, { operation: "bootstrap", stateDirectory: ".insmind" });
41
+ }
42
+ catch { /* Retain startup error output even if diagnostic modules cannot load. */ }
37
43
  if (mapCliError === undefined || redact === undefined) {
38
44
  process.stderr.write("INTERNAL_ERROR: CLI failed to start.\n");
39
45
  process.exitCode = 1;
@@ -57,4 +63,5 @@ catch (error) {
57
63
  }
58
64
  finally {
59
65
  process.removeListener("SIGINT", interrupt);
66
+ process.removeListener("SIGTERM", interrupt);
60
67
  }
@@ -1,3 +1,5 @@
1
+ import { reportProcessError } from "../src/telemetry/process-errors.js";
2
+ import { cleanText } from "../src/telemetry/sanitize.js";
1
3
  import { fileURLToPath } from "node:url";
2
4
  import { dirname, resolve } from "node:path";
3
5
  import { loadBundledSkills } from "../src/features/skill/bundled-skills.js";
@@ -19,12 +21,16 @@ export async function runPostinstall(options = {}) {
19
21
  const env = options.env ?? process.env;
20
22
  if (!isSupportedGlobalLifecycle(env))
21
23
  return;
24
+ 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"
26
+ }));
22
27
  const writeError = options.writeError ?? ((text) => process.stderr.write(text));
23
28
  let skills;
24
29
  try {
25
30
  skills = (options.loadSkills ?? loadBundledSkills)(options.startFile ?? fileURLToPath(import.meta.url));
26
31
  }
27
32
  catch (error) {
33
+ await reportError(error);
28
34
  if (env.GD_CLI_INSTALL_OWNER === "workbuddy") {
29
35
  throw new Error("无法确认当前安装的 package。");
30
36
  }
@@ -51,18 +57,21 @@ export async function runPostinstall(options = {}) {
51
57
  });
52
58
  }
53
59
  catch (error) {
60
+ await reportError(error);
54
61
  writeError(`警告: ${oneLineMessage(error)}\n`);
55
62
  }
56
63
  }
57
64
  function oneLineMessage(error) {
58
65
  const value = error instanceof Error ? error.message : String(error);
59
- return value.replace(/\s+/gu, " ").trim() || "Agent Skill 自动安装失败";
66
+ return cleanText(value).replace(/\s+/gu, " ").trim() || "Agent Skill 自动安装失败";
60
67
  }
61
68
  const entryPath = process.argv[1];
62
69
  const isDirectEntry = entryPath !== undefined
63
70
  && resolve(entryPath) === fileURLToPath(import.meta.url);
64
71
  if (isDirectEntry || process.env.npm_lifecycle_event === "postinstall") {
65
- void runPostinstall().catch((error) => {
72
+ void runPostinstall().catch(async (error) => {
73
+ await reportProcessError(error, { operation: "postinstall", processRole: "postinstall",
74
+ stateDirectory: process.env.npm_package_name === "@insmind/cli" ? ".insmind" : ".gd" });
66
75
  process.stderr.write(`${oneLineMessage(error)}\n`);
67
76
  process.exitCode = 1;
68
77
  });
@@ -14,6 +14,7 @@ import { registerCreditsCommand } from "../cli/credits-command.js";
14
14
  import { redact } from "../platform/redact.js";
15
15
  export { assertAllLeafCommandsBound, bindAction } from "../cli/action-binding.js";
16
16
  export function createCli(runtime, options) {
17
+ runtime.telemetry.useSignal(options.signal);
17
18
  const program = new Command()
18
19
  .name(runtime.product.commandName)
19
20
  .description(runtime.product.description)
@@ -69,6 +70,8 @@ export async function executeCli(options) {
69
70
  }
70
71
  return 0;
71
72
  }
73
+ if (!options.telemetry.selected)
74
+ options.telemetry.select({ operation: "unknown" });
72
75
  if (options.telemetry.selected && error instanceof CommanderError) {
73
76
  try {
74
77
  await options.telemetry.stage("input", () => { throw error; });
@@ -78,17 +81,22 @@ export async function executeCli(options) {
78
81
  }
79
82
  }
80
83
  const outcome = redact(mapCliError(error, {
81
- aborted: options.signal.aborted,
84
+ aborted: options.signal.aborted && (error === options.signal.reason || error instanceof Error && error.name === "AbortError"),
82
85
  ...(options.product ? { product: options.product } : {})
83
86
  }));
84
- const telemetryError = classifyTelemetryError(error);
87
+ const telemetryError = classifyTelemetryError(error, { aborted: options.signal.aborted && (error === options.signal.reason || error instanceof Error && error.name === "AbortError"), ...(options.product ? { product: options.product } : {}) });
85
88
  const traceId = options.telemetry.selected
86
89
  ? options.telemetry.traceId
87
90
  : undefined;
88
- options.presenter.error(outcome, {
89
- json: options.argv.includes("--json"),
90
- ...(traceId ? { traceId } : {})
91
- });
91
+ try {
92
+ options.presenter.error(outcome, {
93
+ json: options.argv.includes("--json"),
94
+ ...(traceId ? { traceId } : {})
95
+ });
96
+ }
97
+ catch (presenterError) {
98
+ await options.telemetry.stage("output", () => { throw presenterError; }).catch(() => undefined);
99
+ }
92
100
  await sendFinished(options, outcome.kind === "interrupted"
93
101
  ? { outcome: "interrupted", error }
94
102
  : {
@@ -120,5 +128,5 @@ async function checkUpdateNotification(updateNotification, signal) {
120
128
  async function sendFinished(options, completion) {
121
129
  const events = options.telemetry.finish(completion);
122
130
  if (events.length > 0)
123
- await options.telemetrySink.send(events);
131
+ await options.telemetrySink.send(events).catch(() => undefined);
124
132
  }
@@ -1,3 +1,5 @@
1
+ import { taskScope } from "../features/task/store.js";
2
+ import { TaskNotFoundError } from "../features/task/use-cases.js";
1
3
  import { homedir } from "node:os";
2
4
  import { createAgentBackgroundLauncher } from "../features/task/agent-background.js";
3
5
  import { createTaskStore } from "../features/task/store.js";
@@ -79,21 +81,22 @@ export function createProductionRuntime(options = {}) {
79
81
  "X-Legal-Region": locale.legalRegion
80
82
  } : undefined;
81
83
  const now = options.now ?? (() => new Date());
84
+ const telemetryEnvironment = options.telemetryEnvironment ?? (env.CLI_TELEMETRY_ENV === "test" ? "test" : "production");
85
+ const telemetrySink = options.telemetrySink ?? createSlsTelemetrySink({
86
+ fetch, trackingUrl: options.telemetryTrackingUrl ?? product.telemetryUrl,
87
+ background: options.telemetryBackground ?? true,
88
+ directory: join(options.homeDirectory ?? homedir(), product.stateDirectory, "telemetry"),
89
+ now: () => now().getTime()
90
+ });
82
91
  const telemetry = createTelemetryInvocation({
83
- cliVersion: primarySkill.version,
92
+ cliVersion: primarySkill.version, cliName: product.commandName, env: telemetryEnvironment,
93
+ processRole: options.processRole ?? "cli",
84
94
  now: () => now().getTime(),
85
95
  traceIdFactory: () => randomBytes(16).toString("hex"),
86
96
  spanIdFactory: () => randomBytes(8).toString("hex"),
87
- runtime: {
88
- os: process.platform,
89
- arch: process.arch,
90
- nodeMajor: Number.parseInt(process.versions.node, 10)
91
- },
92
- classifyError: classifyTelemetryError
93
- });
94
- const telemetrySink = createSlsTelemetrySink({
95
- fetch,
96
- trackingUrl: product.telemetryUrl
97
+ runtime: { os: process.platform, arch: process.arch, nodeMajor: Number.parseInt(process.versions.node, 10) },
98
+ classifyError: error => classifyTelemetryError(error, { product }),
99
+ onEvent: async (event) => { await telemetrySink.enqueue?.([event]); }
97
100
  });
98
101
  const rawIo = options.io ?? {
99
102
  input: process.stdin,
@@ -158,6 +161,7 @@ export function createProductionRuntime(options = {}) {
158
161
  const sso = createSsoService({
159
162
  ssoApi: endpoints.ssoApi,
160
163
  clientId: product.deviceClientId,
164
+ traceparent: () => telemetry.traceparent(),
161
165
  fetch,
162
166
  now
163
167
  });
@@ -183,7 +187,9 @@ export function createProductionRuntime(options = {}) {
183
187
  await delay(milliseconds, undefined, { signal });
184
188
  }
185
189
  });
186
- const storage = options.objectStorage ?? createObjectStorageUploader({ fetch, now });
190
+ const storage = options.objectStorage ?? createObjectStorageUploader({ fetch, now,
191
+ reportError: error => telemetry.stage("upload.attempt", () => { throw error; }).catch(() => undefined)
192
+ });
187
193
  const credits = createCreditsUseCases({
188
194
  transport: creditsTransport,
189
195
  billingUnit: product.billingUnit
@@ -244,26 +250,44 @@ export function createProductionRuntime(options = {}) {
244
250
  },
245
251
  telemetry
246
252
  });
247
- const resourceAuthorizer = createAgentResourceAuthorizer({
248
- authKeys: options.resourceAuthKeys
249
- ?? createFilemsResourceAuthKeyProvider({ transport: createSignedHttpTransport({
250
- baseUrl: endpoints.filemsApi,
251
- fetch,
252
- now,
253
- channelId: "32",
254
- traceparent: () => telemetry.traceparent(),
255
- ...(businessHeaders ? { businessHeaders } : {})
256
- }) })
257
- });
258
- const authorizeTaskResult = async (result, state, signal) => {
253
+ const resourceAuthKeys = options.resourceAuthKeys
254
+ ?? createFilemsResourceAuthKeyProvider({ transport: createSignedHttpTransport({
255
+ baseUrl: endpoints.filemsApi,
256
+ fetch,
257
+ now,
258
+ channelId: "32",
259
+ traceparent: () => telemetry.traceparent(),
260
+ ...(businessHeaders ? { businessHeaders } : {})
261
+ }) });
262
+ const resourceAuthorizer = createAgentResourceAuthorizer({ authKeys: resourceAuthKeys });
263
+ const accessPolicies = createAccessPolicies({ store, now, refreshCurrentOrganization: org.refreshCurrentOrganization });
264
+ const authorizeTaskAccess = async (state, signal) => {
265
+ await telemetry.stage("access", async () => {
266
+ const current = await accessPolicies.organization.authorize(signal);
267
+ if (!("state" in current) || !current.state.organization
268
+ || taskScope(current.state) !== taskScope(state)
269
+ || current.state.credential.accessKey !== state.credential.accessKey) {
270
+ throw new TaskNotFoundError(text("身份或组织已切换,请重新查询原任务。", "The identity or organization changed. Query the original task again."));
271
+ }
272
+ });
273
+ };
274
+ const authorizeTaskResult = async (result, state, signal, alreadyAuthorized = false) => {
275
+ // Bind only if this result actually needs a fresh resource token.
276
+ const taskAuthorizer = createAgentResourceAuthorizer({ authKeys: {
277
+ async getAuthKey(access, tokenSignal) {
278
+ if (!alreadyAuthorized)
279
+ await authorizeTaskAccess(state, tokenSignal);
280
+ return resourceAuthKeys.getAuthKey(access, tokenSignal);
281
+ }
282
+ } });
259
283
  const access = { credential: state.credential, organizationId: state.organization.id };
260
284
  if ("message" in result)
261
- return resourceAuthorizer.authorize(result, access, signal);
285
+ return taskAuthorizer.authorize(result, access, signal);
262
286
  const links = result.content.filter(part => part.type === "resource_link");
263
287
  if (links.length === 0)
264
288
  return result;
265
289
  const parts = links.map(part => ({ url: part.uri, mediaType: part.mimeType ?? "application/octet-stream" }));
266
- const authorized = await resourceAuthorizer.authorize({
290
+ const authorized = await taskAuthorizer.authorize({
267
291
  message: { contextId: "resource-authorization", parts: [parts[0], ...parts.slice(1)] },
268
292
  usage: { cost: { unit: "gaodou", amount: 0 }, items: [] }
269
293
  }, access, signal);
@@ -276,6 +300,14 @@ export function createProductionRuntime(options = {}) {
276
300
  }) };
277
301
  };
278
302
  const tasks = createTaskUseCases({
303
+ telemetry,
304
+ ...(options.telemetryVersion ? { creationVersion: options.telemetryVersion } : {}),
305
+ validateResult: result => {
306
+ if ("message" in result)
307
+ validators.agentSendOutput(result);
308
+ else
309
+ validators.toolCallOutput(result);
310
+ },
279
311
  store: createTaskStore({
280
312
  ...(options.homeDirectory ? { homeDirectory: options.homeDirectory } : {}),
281
313
  stateDirectory: product.stateDirectory,
@@ -298,13 +330,14 @@ export function createProductionRuntime(options = {}) {
298
330
  return {
299
331
  state: "unknown", note: text("本地记录未取得服务端会话标识;无法确认提交结果,不自动重新生成。", "No service context was recorded. The submission outcome is unknown; do not generate again.")
300
332
  };
333
+ await authorizeTaskAccess(state, signal);
301
334
  const snapshot = await readAgentResult(agentTransport, {
302
335
  contextId: progress.contextId, localMessageId: progress.localMessageId,
303
336
  credential: state.credential, organizationId: state.organization.id, signal
304
337
  });
305
338
  return { state: "unknown",
306
339
  note: text(`会话连接为 ${snapshot.connectionState};这不是本次调用的完成凭据。已有内容仅作为消息快照。`, `The context connection is ${snapshot.connectionState}; this does not prove that the run completed. Available content is a message snapshot only.`),
307
- ...(snapshot.partialResult ? { partialResult: await authorizeTaskResult(agentOutputWithBillingUnit(snapshot.partialResult, product.billingUnit), state, signal) } : {})
340
+ ...(snapshot.partialResult ? { partialResult: await authorizeTaskResult(agentOutputWithBillingUnit(snapshot.partialResult, product.billingUnit), state, signal, true) } : {})
308
341
  };
309
342
  },
310
343
  async tool(progress, state, signal) {
@@ -312,17 +345,20 @@ export function createProductionRuntime(options = {}) {
312
345
  return {
313
346
  state: "unknown", note: text("本地记录未取得可查询的 Tool 回执;不自动重新生成。", "No queryable Tool receipt was recorded; do not generate again.")
314
347
  };
348
+ await authorizeTaskAccess(state, signal);
315
349
  const response = await queryToolResult(toolTransport, {
316
350
  taskId: progress.remoteTaskId, credential: state.credential,
317
351
  organizationId: state.organization.id, signal
318
352
  });
319
353
  if (response.state === "pending")
320
354
  return { state: "running", note: text("原 Tool 查询尚未返回最终结果。", "The original Tool is still processing.") };
321
- if (response.state === "failed")
355
+ if (response.state === "failed") {
356
+ await telemetry.stage("task.recover", () => { throw response.error; }).catch(() => undefined);
322
357
  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.") };
358
+ }
323
359
  return { state: "completed", result: await authorizeTaskResult(toolOutputWithBillingUnit({
324
360
  content: response.content, usage: progress.toolUsage
325
- }, product.billingUnit), state, signal) };
361
+ }, product.billingUnit), state, signal, true) };
326
362
  }
327
363
  }
328
364
  });
@@ -393,6 +429,7 @@ export function createProductionRuntime(options = {}) {
393
429
  }
394
430
  };
395
431
  const updateNotification = createUpdateNotificationService({
432
+ reportError: error => telemetry.stage("update_check", () => { throw error; }).catch(() => undefined),
396
433
  currentVersion: primarySkill.version,
397
434
  fetch,
398
435
  now,
@@ -411,11 +448,7 @@ export function createProductionRuntime(options = {}) {
411
448
  version: primarySkill.version,
412
449
  telemetry,
413
450
  telemetrySink,
414
- accessPolicies: createAccessPolicies({
415
- store,
416
- now,
417
- refreshCurrentOrganization: org.refreshCurrentOrganization
418
- }),
451
+ accessPolicies,
419
452
  auth,
420
453
  org,
421
454
  agent,
@@ -423,8 +456,13 @@ export function createProductionRuntime(options = {}) {
423
456
  startAgentTask: (input, signal) => (options.agentBackground ?? createAgentBackgroundLauncher({
424
457
  workerPath: join(packageRoot, "dist", "bin", "agent-worker.js"), env
425
458
  })).submit({ ...input, product: product.id, homeDirectory: options.homeDirectory ?? homedir(),
459
+ telemetryEnvironment, telemetryVersion: primarySkill.version,
460
+ telemetryTrackingUrl: String(options.telemetryTrackingUrl ?? product.telemetryUrl),
426
461
  locale: locale.locale, endpoints: Object.fromEntries(Object.entries(endpoints).map(([key, value]) => [key, String(value)]))
427
- }, signal, task => presenter.notice(text(`任务 ID: ${task.taskId};结果未收到时执行 ${product.commandName} task get ${task.taskId}`, `Task ID: ${task.taskId}; retrieve missing output with ${product.commandName} task get ${task.taskId}`))),
462
+ }, signal, task => {
463
+ telemetry.annotate({ cli_task_id: task.taskId, execution_mode: "async", result_state: task.state });
464
+ presenter.notice(text(`任务 ID: ${task.taskId};结果未收到时执行 ${product.commandName} task get ${task.taskId}`, `Task ID: ${task.taskId}; retrieve missing output with ${product.commandName} task get ${task.taskId}`));
465
+ }),
428
466
  editor,
429
467
  dam,
430
468
  tool,
@@ -3,6 +3,11 @@ import { redact } from "../platform/redact.js";
3
3
  export async function runAgentWorker(options) {
4
4
  const runtime = options.runtime;
5
5
  const { job, signal, send } = options;
6
+ runtime.telemetry.useSignal(signal);
7
+ runtime.telemetry.select({ operation: "agent.send", mode: () => "execute" });
8
+ runtime.telemetry.annotate({ account_id: job.state.account?.id, organization_id: job.state.organization.id,
9
+ parameters: { ...job.input }, execution_mode: "async" });
10
+ let completion = { outcome: "success" };
6
11
  let started = false;
7
12
  let accepted = false;
8
13
  try {
@@ -11,6 +16,7 @@ export async function runAgentWorker(options) {
11
16
  state: job.state,
12
17
  operation: "agent.send",
13
18
  label: job.label,
19
+ executionMode: "async",
14
20
  onUpdate(task, progress) {
15
21
  if (!started) {
16
22
  started = true;
@@ -30,8 +36,13 @@ export async function runAgentWorker(options) {
30
36
  });
31
37
  }
32
38
  catch (error) {
33
- const outcome = redact(mapCliError(error, { aborted: signal.aborted, product: runtime.product }));
39
+ const outcome = redact(mapCliError(error, { aborted: signal.aborted && (error === signal.reason || error instanceof Error && error.name === "AbortError"), product: runtime.product }));
40
+ completion = outcome.kind === "interrupted" ? { outcome: "interrupted", error }
41
+ : { outcome: "failure", error, errorCode: outcome.failure.code, errorMessage: outcome.failure.message };
34
42
  if (outcome.kind === "failure")
35
43
  send({ type: "error", failure: outcome.failure, exitCode: outcome.exitCode });
36
44
  }
45
+ finally {
46
+ await runtime.telemetrySink.send(runtime.telemetry.finish(completion)).catch(() => undefined);
47
+ }
37
48
  }
@@ -77,8 +77,7 @@ function rootCommand(command) {
77
77
  return current;
78
78
  }
79
79
  function bindTelemetrySelection(command, definition) {
80
- if (!definition)
81
- return;
80
+ definition ??= { operation: commandPath(command).split(" ").slice(1).join(".") };
82
81
  if (!command.parent)
83
82
  throw new Error(`Telemetry command has no parent: ${command.name()}`);
84
83
  command.parent.hook("preSubcommand", (parent, selected) => {
@@ -174,17 +174,19 @@ function isInsufficientCreditsError(error) {
174
174
  || error instanceof RemoteProtocolError
175
175
  || error instanceof ToolTaskFailedError) && error.remoteCode === INSUFFICIENT_CREDITS_REMOTE_CODE;
176
176
  }
177
- export function classifyTelemetryError(error) {
178
- const outcome = mapCliError(error, { aborted: false });
177
+ export function classifyTelemetryError(error, options = {}) {
178
+ const outcome = mapCliError(error, { ...options, aborted: options.aborted === true || (error instanceof Error && (error.name === "AbortError" || error.message === "SIGINT" || error.message === "SIGTERM")) });
179
179
  const remoteError = error instanceof RemoteRequestError
180
180
  || error instanceof RemoteProtocolError
181
181
  || error instanceof ToolTaskFailedError
182
+ || error instanceof SsoRequestError
183
+ || error instanceof OrganizationBindFailedError
182
184
  ? error
183
185
  : undefined;
184
186
  return {
185
187
  outcome: outcome.kind === "interrupted" ? "interrupted" : "failure",
186
188
  ...(outcome.kind === "failure" ? { errorCode: outcome.failure.code } : {}),
187
- ...(error instanceof RemoteRequestError && error.status !== undefined
189
+ ...((error instanceof RemoteRequestError || error instanceof SsoRequestError) && error.status !== undefined
188
190
  ? { httpStatus: error.status }
189
191
  : {}),
190
192
  ...(remoteError?.remoteCode === undefined
@@ -10,7 +10,7 @@ export function registerTaskCommands(program, runtime) {
10
10
  .option("--limit <number>", text("返回 1–100 条,默认 20", "return 1–100 tasks; defaults to 20"), "20")
11
11
  .option("--operation <operation>", text("筛选 agent.send 或 tool.call", "filter by agent.send or tool.call"))
12
12
  .allowExcessArguments(false);
13
- bindPreparedAction(list, "organization", async () => {
13
+ bindPreparedAction(list, "local-organization", async () => {
14
14
  const options = list.opts();
15
15
  const limit = Number(options.limit);
16
16
  if (!/^\d+$/u.test(options.limit) || !Number.isInteger(limit) || limit < 1 || limit > 100
@@ -30,12 +30,13 @@ export function registerTaskCommands(program, runtime) {
30
30
  "",
31
31
  text("completed 表示该次执行已有完整结果;running 表示原 CLI 仍在更新记录,或远端任务仍在执行。", "completed means this task has a complete result; running means the original CLI is updating the record or the service is still processing."),
32
32
  text("unknown 表示无法确认本次执行终态;partialResult 仅是已取得的消息片段,不代表完成。", "unknown means completion cannot be confirmed; partialResult is a message snapshot, not a complete result."),
33
+ text("读取本地状态不请求组织绑定;查询远端进度或获取下载授权仍需联网授权。查询请求失败不代表生成失败,可用原 taskId 重查。", "Local status reads do not bind the organization. Remote progress and download authorization still require network access. A failed query does not mean generation failed; query the same taskId again."),
33
34
  text("查询不重新提交创作;同一执行记录多次读取的 usage 是同一份费用。", "Queries never resubmit a creation. Reading the same task again does not add another usage charge."),
34
35
  text(`记录仅来自本机执行;保留至用户删除 ~/${runtime.product.stateDirectory}/tasks。切换身份或组织后只显示对应记录。`, `Tasks are local to this machine and identity context; they remain until you remove ~/${runtime.product.stateDirectory}/tasks.`),
35
36
  text("Agent 首次回执未取得或原连接中断时可能只能确认未知;不会自动选择最近 Context 或重新生成。", "A missing first Agent receipt or interrupted connection may leave the outcome unknown; the CLI does not select another Context or generate again."),
36
37
  ""
37
38
  ].join("\n"));
38
- bindPreparedAction(get, "organization", async () => {
39
+ bindPreparedAction(get, "local-organization", async () => {
39
40
  const id = get.processedArgs[0];
40
41
  if (typeof id !== "string" || !validTaskId(id))
41
42
  throw new CliUsageError();
@@ -15,6 +15,7 @@ export function createCreativeAgentAdapter(dependencies) {
15
15
  await observe?.({ submissionStarted: true });
16
16
  const stream = await dependencies.transport.postStream({
17
17
  path: "/ai-agent/v1/thread/completion",
18
+ ...(observe ? { onDispatch: (dispatchedAt) => observe({ dispatchedAt }) } : {}),
18
19
  body: buildCreativeRequest(message, ids),
19
20
  accept: "text/event-stream",
20
21
  credential: access.credential,
@@ -312,9 +312,11 @@ function parseQuestionPart(message) {
312
312
  return fail();
313
313
  return { label };
314
314
  });
315
- const allowMultiple = question.allow_multiple ?? question.allowMultiple;
316
- if (typeof allowMultiple !== "boolean")
315
+ const rawAllowMultiple = question.allow_multiple !== undefined
316
+ ? question.allow_multiple : question.allowMultiple;
317
+ if (rawAllowMultiple !== undefined && typeof rawAllowMultiple !== "boolean")
317
318
  return fail();
319
+ const allowMultiple = rawAllowMultiple ?? false;
318
320
  return { question: text, options, allowMultiple };
319
321
  });
320
322
  const title = nonEmptyString(argumentsRecord.title);
@@ -72,6 +72,14 @@ export function createAccessPolicies(dependencies) {
72
72
  return { policy: "credential", state };
73
73
  }
74
74
  },
75
+ "local-organization": {
76
+ async authorize(signal) {
77
+ const state = await readValidState(signal);
78
+ if (!state.organization)
79
+ throw new OrganizationInvalidError();
80
+ return { policy: "local-organization", state: state };
81
+ }
82
+ },
75
83
  organization: {
76
84
  async authorize(signal) {
77
85
  let state = await readValidState(signal);