@gaoding/cli 1.3.1 → 1.4.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 (37) hide show
  1. package/contracts/operations/model.get/output.schema.json +13 -0
  2. package/dist/bin/agent-worker.js +13 -1
  3. package/dist/bin/gd-cli.js +7 -0
  4. package/dist/bin/insmind-cli.js +7 -0
  5. package/dist/bin/postinstall.js +11 -2
  6. package/dist/src/bootstrap/create-cli.js +15 -7
  7. package/dist/src/bootstrap/create-runtime.js +79 -36
  8. package/dist/src/bootstrap/run-agent-worker.js +12 -1
  9. package/dist/src/cli/action-binding.js +1 -2
  10. package/dist/src/cli/errors.js +5 -3
  11. package/dist/src/cli/task-commands.js +3 -2
  12. package/dist/src/features/agent/creative-agent-adapter.js +1 -0
  13. package/dist/src/features/agent/creative-protocol.js +4 -2
  14. package/dist/src/features/auth/access-policy.js +8 -0
  15. package/dist/src/features/auth/sso-service.js +76 -26
  16. package/dist/src/features/auth/use-cases.js +1 -1
  17. package/dist/src/features/dam/file-downloader.js +6 -6
  18. package/dist/src/features/dam/object-storage.js +6 -4
  19. package/dist/src/features/editor/bridge-process.js +9 -3
  20. package/dist/src/features/editor/bridge-server.js +4 -2
  21. package/dist/src/features/org/use-cases.js +8 -3
  22. package/dist/src/features/task/store.js +34 -2
  23. package/dist/src/features/task/use-cases.js +71 -6
  24. package/dist/src/features/tool/dynamic-schema.js +35 -7
  25. package/dist/src/features/tool/mns-catalog-adapter.js +30 -10
  26. package/dist/src/features/tool/tool-api-adapter.js +1 -0
  27. package/dist/src/features/update/update-notification.js +4 -2
  28. package/dist/src/platform/file-lock.js +68 -0
  29. package/dist/src/platform/redact.js +1 -1
  30. package/dist/src/platform/safe-upload-file.js +3 -3
  31. package/dist/src/platform/signed-http-transport.js +23 -9
  32. package/dist/src/telemetry/invocation.js +74 -122
  33. package/dist/src/telemetry/process-errors.js +43 -0
  34. package/dist/src/telemetry/sanitize.js +72 -0
  35. package/dist/src/telemetry/sls-sink.js +209 -22
  36. package/package.json +4 -4
  37. package/skills/gd-cli/references/creation.md +12 -0
@@ -141,6 +141,19 @@
141
141
  "$ref": "#/$defs/NonBlankString",
142
142
  "description": "参数的用途说明。"
143
143
  },
144
+ "minimum": {
145
+ "type": "number",
146
+ "description": "数值参数允许的最小值(包含);滑块参数的约束。"
147
+ },
148
+ "maximum": {
149
+ "type": "number",
150
+ "description": "数值参数允许的最大值(包含);滑块参数的约束。"
151
+ },
152
+ "step": {
153
+ "type": "number",
154
+ "exclusiveMinimum": 0,
155
+ "description": "滑块参数相邻允许值之间的正数步长,从 minimum 起算。"
156
+ },
144
157
  "default": {
145
158
  "anyOf": [
146
159
  {
@@ -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
  }
@@ -2,6 +2,7 @@
2
2
  const controller = new AbortController();
3
3
  const interrupt = () => controller.abort(new Error("SIGINT"));
4
4
  process.once("SIGINT", interrupt);
5
+ process.once("SIGTERM", interrupt);
5
6
  let runtime;
6
7
  let mapCliError;
7
8
  let redact;
@@ -32,6 +33,11 @@ try {
32
33
  });
33
34
  }
34
35
  catch (error) {
36
+ try {
37
+ const { reportProcessError } = await import("../src/telemetry/process-errors.js");
38
+ await reportProcessError(error, { operation: "bootstrap", stateDirectory: ".gd" });
39
+ }
40
+ catch { /* Retain startup error output even if diagnostic modules cannot load. */ }
35
41
  // Dynamic module loading can fail before the error mapper is available.
36
42
  // Keep that rare startup failure bounded and avoid an unhandled rejection.
37
43
  if (mapCliError === undefined || redact === undefined) {
@@ -57,5 +63,6 @@ catch (error) {
57
63
  }
58
64
  finally {
59
65
  process.removeListener("SIGINT", interrupt);
66
+ process.removeListener("SIGTERM", interrupt);
60
67
  }
61
68
  export {};
@@ -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
@@ -202,7 +208,12 @@ export function createProductionRuntime(options = {}) {
202
208
  const validators = createContractValidators({
203
209
  organizations: product.exposesOrganizations
204
210
  });
205
- const modelCatalog = createMnsCatalogAdapter({ transport: mnsTransport });
211
+ const modelCatalog = createMnsCatalogAdapter({
212
+ transport: mnsTransport,
213
+ ...(product.id === "insmind"
214
+ ? { invalidModelWarning: (count) => `Ignored ${count} invalid model configuration${count === 1 ? "" : "s"}.` }
215
+ : {})
216
+ });
206
217
  const damApi = createDamApiAdapter({ transport: damTransport });
207
218
  const damRepositories = createDamRepositoryCatalog({ transport: damTransport });
208
219
  const damOperations = createDamOperationExecutor({
@@ -244,26 +255,44 @@ export function createProductionRuntime(options = {}) {
244
255
  },
245
256
  telemetry
246
257
  });
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) => {
258
+ const resourceAuthKeys = options.resourceAuthKeys
259
+ ?? createFilemsResourceAuthKeyProvider({ transport: createSignedHttpTransport({
260
+ baseUrl: endpoints.filemsApi,
261
+ fetch,
262
+ now,
263
+ channelId: "32",
264
+ traceparent: () => telemetry.traceparent(),
265
+ ...(businessHeaders ? { businessHeaders } : {})
266
+ }) });
267
+ const resourceAuthorizer = createAgentResourceAuthorizer({ authKeys: resourceAuthKeys });
268
+ const accessPolicies = createAccessPolicies({ store, now, refreshCurrentOrganization: org.refreshCurrentOrganization });
269
+ const authorizeTaskAccess = async (state, signal) => {
270
+ await telemetry.stage("access", async () => {
271
+ const current = await accessPolicies.organization.authorize(signal);
272
+ if (!("state" in current) || !current.state.organization
273
+ || taskScope(current.state) !== taskScope(state)
274
+ || current.state.credential.accessKey !== state.credential.accessKey) {
275
+ throw new TaskNotFoundError(text("身份或组织已切换,请重新查询原任务。", "The identity or organization changed. Query the original task again."));
276
+ }
277
+ });
278
+ };
279
+ const authorizeTaskResult = async (result, state, signal, alreadyAuthorized = false) => {
280
+ // Bind only if this result actually needs a fresh resource token.
281
+ const taskAuthorizer = createAgentResourceAuthorizer({ authKeys: {
282
+ async getAuthKey(access, tokenSignal) {
283
+ if (!alreadyAuthorized)
284
+ await authorizeTaskAccess(state, tokenSignal);
285
+ return resourceAuthKeys.getAuthKey(access, tokenSignal);
286
+ }
287
+ } });
259
288
  const access = { credential: state.credential, organizationId: state.organization.id };
260
289
  if ("message" in result)
261
- return resourceAuthorizer.authorize(result, access, signal);
290
+ return taskAuthorizer.authorize(result, access, signal);
262
291
  const links = result.content.filter(part => part.type === "resource_link");
263
292
  if (links.length === 0)
264
293
  return result;
265
294
  const parts = links.map(part => ({ url: part.uri, mediaType: part.mimeType ?? "application/octet-stream" }));
266
- const authorized = await resourceAuthorizer.authorize({
295
+ const authorized = await taskAuthorizer.authorize({
267
296
  message: { contextId: "resource-authorization", parts: [parts[0], ...parts.slice(1)] },
268
297
  usage: { cost: { unit: "gaodou", amount: 0 }, items: [] }
269
298
  }, access, signal);
@@ -276,6 +305,14 @@ export function createProductionRuntime(options = {}) {
276
305
  }) };
277
306
  };
278
307
  const tasks = createTaskUseCases({
308
+ telemetry,
309
+ ...(options.telemetryVersion ? { creationVersion: options.telemetryVersion } : {}),
310
+ validateResult: result => {
311
+ if ("message" in result)
312
+ validators.agentSendOutput(result);
313
+ else
314
+ validators.toolCallOutput(result);
315
+ },
279
316
  store: createTaskStore({
280
317
  ...(options.homeDirectory ? { homeDirectory: options.homeDirectory } : {}),
281
318
  stateDirectory: product.stateDirectory,
@@ -298,13 +335,14 @@ export function createProductionRuntime(options = {}) {
298
335
  return {
299
336
  state: "unknown", note: text("本地记录未取得服务端会话标识;无法确认提交结果,不自动重新生成。", "No service context was recorded. The submission outcome is unknown; do not generate again.")
300
337
  };
338
+ await authorizeTaskAccess(state, signal);
301
339
  const snapshot = await readAgentResult(agentTransport, {
302
340
  contextId: progress.contextId, localMessageId: progress.localMessageId,
303
341
  credential: state.credential, organizationId: state.organization.id, signal
304
342
  });
305
343
  return { state: "unknown",
306
344
  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) } : {})
345
+ ...(snapshot.partialResult ? { partialResult: await authorizeTaskResult(agentOutputWithBillingUnit(snapshot.partialResult, product.billingUnit), state, signal, true) } : {})
308
346
  };
309
347
  },
310
348
  async tool(progress, state, signal) {
@@ -312,17 +350,20 @@ export function createProductionRuntime(options = {}) {
312
350
  return {
313
351
  state: "unknown", note: text("本地记录未取得可查询的 Tool 回执;不自动重新生成。", "No queryable Tool receipt was recorded; do not generate again.")
314
352
  };
353
+ await authorizeTaskAccess(state, signal);
315
354
  const response = await queryToolResult(toolTransport, {
316
355
  taskId: progress.remoteTaskId, credential: state.credential,
317
356
  organizationId: state.organization.id, signal
318
357
  });
319
358
  if (response.state === "pending")
320
359
  return { state: "running", note: text("原 Tool 查询尚未返回最终结果。", "The original Tool is still processing.") };
321
- if (response.state === "failed")
360
+ if (response.state === "failed") {
361
+ await telemetry.stage("task.recover", () => { throw response.error; }).catch(() => undefined);
322
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
+ }
323
364
  return { state: "completed", result: await authorizeTaskResult(toolOutputWithBillingUnit({
324
365
  content: response.content, usage: progress.toolUsage
325
- }, product.billingUnit), state, signal) };
366
+ }, product.billingUnit), state, signal, true) };
326
367
  }
327
368
  }
328
369
  });
@@ -393,6 +434,7 @@ export function createProductionRuntime(options = {}) {
393
434
  }
394
435
  };
395
436
  const updateNotification = createUpdateNotificationService({
437
+ reportError: error => telemetry.stage("update_check", () => { throw error; }).catch(() => undefined),
396
438
  currentVersion: primarySkill.version,
397
439
  fetch,
398
440
  now,
@@ -411,11 +453,7 @@ export function createProductionRuntime(options = {}) {
411
453
  version: primarySkill.version,
412
454
  telemetry,
413
455
  telemetrySink,
414
- accessPolicies: createAccessPolicies({
415
- store,
416
- now,
417
- refreshCurrentOrganization: org.refreshCurrentOrganization
418
- }),
456
+ accessPolicies,
419
457
  auth,
420
458
  org,
421
459
  agent,
@@ -423,8 +461,13 @@ export function createProductionRuntime(options = {}) {
423
461
  startAgentTask: (input, signal) => (options.agentBackground ?? createAgentBackgroundLauncher({
424
462
  workerPath: join(packageRoot, "dist", "bin", "agent-worker.js"), env
425
463
  })).submit({ ...input, product: product.id, homeDirectory: options.homeDirectory ?? homedir(),
464
+ telemetryEnvironment, telemetryVersion: primarySkill.version,
465
+ telemetryTrackingUrl: String(options.telemetryTrackingUrl ?? product.telemetryUrl),
426
466
  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}`))),
467
+ }, signal, task => {
468
+ telemetry.annotate({ cli_task_id: task.taskId, execution_mode: "async", result_state: task.state });
469
+ 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}`));
470
+ }),
428
471
  editor,
429
472
  dam,
430
473
  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);