@insmind/cli 1.5.2 → 1.5.3

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.
@@ -43,10 +43,9 @@
43
43
  ],
44
44
  "properties": {
45
45
  "user_id": {
46
- "type": [
47
- "string",
48
- "null"
49
- ]
46
+ "type": "string",
47
+ "minLength": 1,
48
+ "pattern": ".*\\S.*"
50
49
  },
51
50
  "name": {
52
51
  "type": [
@@ -4,7 +4,7 @@ import { once } from "node:events";
4
4
  import { Readable } from "node:stream";
5
5
  import { gaodingProduct, insmindProduct } from "../src/product/config.js";
6
6
  import { createProductionRuntime } from "../src/bootstrap/create-runtime.js";
7
- import { runAgentWorker } from "../src/bootstrap/run-agent-worker.js";
7
+ import { runTaskWorker } from "../src/bootstrap/run-task-worker.js";
8
8
  if (!process.send) {
9
9
  process.exitCode = 2;
10
10
  }
@@ -27,17 +27,17 @@ else {
27
27
  for (const key of Object.keys(endpoints))
28
28
  endpoints[key] = new URL(job.endpoints[key]);
29
29
  const runtime = createProductionRuntime({
30
- processRole: "agent_worker",
30
+ processRole: job.operation === "tool.call" ? "tool_worker" : "agent_worker",
31
31
  ...(job.telemetryVersion ? { telemetryVersion: job.telemetryVersion } : {}),
32
32
  ...(job.telemetryTrackingUrl ? { telemetryTrackingUrl: new URL(job.telemetryTrackingUrl) } : {}),
33
33
  ...(job.telemetryEnvironment ? { telemetryEnvironment: job.telemetryEnvironment } : {}),
34
34
  product, endpoints, homeDirectory: job.homeDirectory, locale: job.locale,
35
35
  io: { input: Readable.from([]), stdout: { write() { } }, stderr: { write() { } } }
36
36
  });
37
- await runAgentWorker({ runtime, job, signal: controller.signal, send });
37
+ await runTaskWorker({ runtime, job, signal: controller.signal, send });
38
38
  }
39
39
  catch (error) {
40
- await reportProcessError(error, { operation: "bootstrap", processRole: "agent_worker", startedAt, signal: controller.signal,
40
+ await reportProcessError(error, { operation: "bootstrap", processRole: currentJob?.operation === "tool.call" ? "tool_worker" : "agent_worker", startedAt, signal: controller.signal,
41
41
  stateDirectory: currentJob?.product === "insmind" ? ".insmind" : ".gd",
42
42
  ...(currentJob?.telemetryTrackingUrl ? { trackingUrl: new URL(currentJob.telemetryTrackingUrl) } : {}),
43
43
  ...(currentJob?.telemetryEnvironment ? { environment: currentJob.telemetryEnvironment } : {}),
@@ -0,0 +1,23 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { join } from "node:path";
3
+ import { withFileLock } from "../platform/file-lock.js";
4
+ import { createLocalJsonFile } from "../platform/local-json-file.js";
5
+ export async function loadAnalyticsDevice(directory, now) {
6
+ return withFileLock(join(directory, "analytics-device.lock"), async () => {
7
+ const file = createLocalJsonFile({ directory, filename: "analytics-device.json" });
8
+ const text = await file.readText();
9
+ if (text !== null) {
10
+ const device = JSON.parse(text);
11
+ if (!/^[A-Za-z0-9_-]{8,64}$/u.test(device.id) || !Number.isFinite(device.createdAt) || device.createdAt <= 0) {
12
+ throw new Error("Invalid analytics device state");
13
+ }
14
+ return device;
15
+ }
16
+ const device = { id: randomUUID(), createdAt: now() };
17
+ await file.writeTextAtomically(`${JSON.stringify(device)}\n`);
18
+ return device;
19
+ });
20
+ }
21
+ export function isFirstDay(createdAt, now) {
22
+ return new Date(createdAt).setHours(23, 59, 59, 999) >= now ? 1 : 0;
23
+ }
@@ -0,0 +1,54 @@
1
+ import { loadAnalyticsDevice, isFirstDay } from "./device.js";
2
+ /** One application adapter owns SDK identity and lifecycle. No SLS payloads enter Wind. */
3
+ export function createWindAnalytics(options) {
4
+ const trackers = new Set();
5
+ const insmind = options.product === "insmind";
6
+ const project = insmind ? "insmind_cli" : "gd_cli";
7
+ return {
8
+ async prepare(identity) {
9
+ try {
10
+ return await options.stage("wind.setup", async () => {
11
+ if (!identity.userId.trim() || !identity.organizationId.trim())
12
+ throw new Error("Missing analytics identity");
13
+ const device = await loadAnalyticsDevice(options.directory, options.now);
14
+ const { CliWindTracker, createNodeAdapters } = await import("../../vendor/gd-tracker-node.mjs");
15
+ const tracker = new CliWindTracker();
16
+ await tracker.setup({ mode: "cli", project, version: options.version, env: options.environment,
17
+ region: insmind ? "US" : "CHINA", deviceId: device.id,
18
+ userAgent: `${insmind ? "insmind-cli" : "gd-cli"}/${options.version}`,
19
+ adapters: createNodeAdapters({ fetch: options.fetch, deliveryBudgetMs: 1_500 }) });
20
+ tracker.set("common", { user_id: identity.userId, is_login: 1,
21
+ organization: { org_id: identity.organizationId },
22
+ channel_id: options.environment === "prod" ? (insmind ? "781" : "32") : (insmind ? "316" : "31") });
23
+ trackers.add(tracker);
24
+ return {
25
+ context: { ...identity, deviceId: device.id, version: options.version, project },
26
+ track(event, details) {
27
+ void options.stage("wind.send", async () => {
28
+ tracker.set("common", { is_first_day: isFirstDay(device.createdAt, options.now()) });
29
+ // Explicit whitelist: command parameters and diagnostics are never spread into details.
30
+ const payload = { event_id: event === "started" ? 37010 : 37011,
31
+ tool_type: details.tool_type, tool_name: details.tool_name,
32
+ ...(details.model_name ? { model_name: details.model_name } : {}) };
33
+ const result = await tracker.trackEvent(event === "started" ? "tool_conflate_start" : "tool_conflate_completed", payload);
34
+ if (!result.accepted)
35
+ throw new Error(result.errorCode ?? "WIND_DELIVERY_FAILED");
36
+ }).catch(() => undefined);
37
+ }
38
+ };
39
+ });
40
+ }
41
+ catch {
42
+ return undefined;
43
+ }
44
+ },
45
+ async shutdown() {
46
+ await Promise.all([...trackers].map(tracker => options.stage("wind.shutdown", async () => {
47
+ const summary = await tracker.shutdown({ timeoutMs: 500 });
48
+ if (!summary.flushed)
49
+ throw new Error(summary.errorCode ?? "WIND_FLUSH_TIMEOUT");
50
+ }).catch(() => undefined)));
51
+ trackers.clear();
52
+ }
53
+ };
54
+ }
@@ -15,6 +15,7 @@ import { registerCreditsCommand } from "../cli/credits-command.js";
15
15
  import { redact } from "../platform/redact.js";
16
16
  export { assertAllLeafCommandsBound, bindAction } from "../cli/action-binding.js";
17
17
  const outputs = new WeakMap();
18
+ const analyticsShutdown = new WeakMap();
18
19
  export function createCli(runtime, options) {
19
20
  runtime.telemetry.useSignal(options.signal);
20
21
  const program = new Command()
@@ -56,6 +57,8 @@ export function createCli(runtime, options) {
56
57
  registerTaskCommands(program, runtime);
57
58
  assertAllLeafCommandsBound(program);
58
59
  outputs.set(program, runtime.io);
60
+ if (runtime.analytics)
61
+ analyticsShutdown.set(program, () => runtime.analytics.shutdown());
59
62
  return program;
60
63
  }
61
64
  export async function executeCli(options) {
@@ -136,6 +139,8 @@ async function checkUpdateNotification(updateNotification, signal) {
136
139
  }
137
140
  async function sendFinished(options, completion) {
138
141
  const events = options.telemetry.finish(completion);
139
- if (events.length > 0)
140
- await options.telemetrySink.send(events).catch(() => undefined);
142
+ await Promise.all([
143
+ events.length > 0 ? options.telemetrySink.send(events).catch(() => undefined) : undefined,
144
+ analyticsShutdown.get(options.program)?.().catch(() => undefined)
145
+ ]);
141
146
  }
@@ -1,8 +1,9 @@
1
+ import { createWindAnalytics } from "../analytics/wind.js";
1
2
  import { taskScope } from "../features/task/store.js";
2
3
  import { createTextOutput } from "../platform/text-output.js";
3
4
  import { TaskNotFoundError } from "../features/task/use-cases.js";
4
5
  import { homedir } from "node:os";
5
- import { createAgentBackgroundLauncher } from "../features/task/agent-background.js";
6
+ import { createTaskBackgroundLauncher } from "../features/task/task-background.js";
6
7
  import { createTaskStore } from "../features/task/store.js";
7
8
  import { createTaskUseCases } from "../features/task/use-cases.js";
8
9
  import { readAgentResult } from "../features/agent/result-reader.js";
@@ -99,6 +100,14 @@ export function createProductionRuntime(options = {}) {
99
100
  classifyError: error => classifyTelemetryError(error, { product }),
100
101
  onEvent: async (event) => { await telemetrySink.enqueue?.([event]); }
101
102
  });
103
+ // Explicit test transport enables SDK tests; test-mode child processes never emit real analytics.
104
+ const analytics = options.analytics ?? (telemetryEnvironment === "production" || options.windFetch
105
+ ? createWindAnalytics({ product: product.id, version: options.telemetryVersion ?? primarySkill.version,
106
+ directory: join(options.homeDirectory ?? homedir(), product.stateDirectory),
107
+ environment: telemetryEnvironment === "production" ? "prod" : "dev", fetch: options.windFetch ?? fetch,
108
+ now: () => now().getTime(),
109
+ stage: (name, run) => telemetry.stage(name, run)
110
+ }) : undefined);
102
111
  const rawIo = options.io ?? {
103
112
  input: process.stdin,
104
113
  stdout: process.stdout,
@@ -311,6 +320,7 @@ export function createProductionRuntime(options = {}) {
311
320
  };
312
321
  const tasks = createTaskUseCases({
313
322
  telemetry,
323
+ ...(analytics ? { analytics } : {}),
314
324
  ...(options.telemetryVersion ? { creationVersion: options.telemetryVersion } : {}),
315
325
  validateResult: result => {
316
326
  if ("message" in result)
@@ -471,13 +481,14 @@ export function createProductionRuntime(options = {}) {
471
481
  version: primarySkill.version,
472
482
  telemetry,
473
483
  telemetrySink,
484
+ ...(analytics ? { analytics } : {}),
474
485
  accessPolicies,
475
486
  auth,
476
487
  org,
477
488
  agent,
478
489
  tasks,
479
- startAgentTask: (input, signal) => (options.agentBackground ?? createAgentBackgroundLauncher({
480
- workerPath: join(packageRoot, "dist", "bin", "agent-worker.js"), env
490
+ startBackgroundTask: (input, signal) => (options.taskBackground ?? createTaskBackgroundLauncher({
491
+ workerPath: join(packageRoot, "dist", "bin", "task-worker.js"), env
481
492
  })).submit({ ...input, product: product.id, homeDirectory: options.homeDirectory ?? homedir(),
482
493
  telemetryEnvironment, telemetryVersion: primarySkill.version,
483
494
  telemetryTrackingUrl: String(options.telemetryTrackingUrl ?? product.telemetryUrl),
@@ -1,21 +1,26 @@
1
+ import { requireUserIdentity } from "../features/auth/state.js";
1
2
  import { isInterruption } from "../platform/interruption.js";
2
3
  import { mapCliError } from "../cli/errors.js";
3
4
  import { redact } from "../platform/redact.js";
4
- export async function runAgentWorker(options) {
5
+ export async function runTaskWorker(options) {
5
6
  const runtime = options.runtime;
6
7
  const { job, signal, send } = options;
7
8
  runtime.telemetry.useSignal(signal);
8
- runtime.telemetry.select({ operation: "agent.send", mode: () => "execute" });
9
+ runtime.telemetry.select({ operation: job.operation, mode: () => "execute" });
9
10
  runtime.telemetry.annotate({ account_id: job.state.account?.id, organization_id: job.state.organization.id,
10
11
  parameters: { ...job.input }, execution_mode: "async" });
11
12
  let completion = { outcome: "success" };
12
13
  let started = false;
13
14
  let accepted = false;
14
15
  try {
15
- runtime.validators.agentSendInput(job.input);
16
+ await runtime.telemetry.stage("access", async () => { requireUserIdentity(job.state); });
17
+ if (job.operation === "agent.send")
18
+ runtime.validators.agentSendInput(job.input);
19
+ else
20
+ runtime.validators.toolCallInput(job.input);
16
21
  await runtime.tasks.track({
17
22
  state: job.state,
18
- operation: "agent.send",
23
+ operation: job.operation,
19
24
  label: job.label,
20
25
  executionMode: "async",
21
26
  onUpdate(task, progress) {
@@ -23,15 +28,16 @@ export async function runAgentWorker(options) {
23
28
  started = true;
24
29
  send({ type: "started", task });
25
30
  }
26
- if (progress.accepted && !accepted) {
31
+ if ((progress.accepted || progress.remoteTaskId) && !accepted) {
27
32
  accepted = true;
28
33
  send({ type: "accepted", task });
29
34
  }
30
35
  },
31
36
  run: async (observe) => {
32
- const result = await runtime.agent.send({ input: job.input, signal, observe,
33
- access: { credential: job.state.credential, organizationId: job.state.organization.id } });
34
- runtime.validators.agentSendOutput(result);
37
+ const access = { credential: job.state.credential, organizationId: job.state.organization.id };
38
+ const result = job.operation === "agent.send"
39
+ ? await runtime.agent.send({ input: job.input, signal, observe, access })
40
+ : await runtime.tool.call({ input: job.input, signal, observe, access });
35
41
  return result;
36
42
  }
37
43
  });
@@ -44,6 +50,9 @@ export async function runAgentWorker(options) {
44
50
  send({ type: "error", failure: outcome.failure, exitCode: outcome.exitCode });
45
51
  }
46
52
  finally {
47
- await runtime.telemetrySink.send(runtime.telemetry.finish(completion)).catch(() => undefined);
53
+ await Promise.all([
54
+ runtime.telemetrySink.send(runtime.telemetry.finish(completion)).catch(() => undefined),
55
+ runtime.analytics?.shutdown().catch(() => undefined)
56
+ ]);
48
57
  }
49
58
  }
@@ -53,7 +53,7 @@ export function registerAgentCommands(program, runtime) {
53
53
  label: input.message.parts.map(part => part && typeof part === "object" && "text" in part ? String(part.text) : text(runtime.product, "[素材或结构化输入]", "[asset or structured input]")).join(" ")
54
54
  };
55
55
  if (send.opts().async) {
56
- const result = await runtime.startAgentTask({ state: context.state, label: task.label, input }, signal);
56
+ const result = await runtime.startBackgroundTask({ operation: "agent.send", state: context.state, label: task.label, input }, signal);
57
57
  await runtime.telemetry.stage("output", async () => {
58
58
  runtime.validators.taskResult(result);
59
59
  runtime.io.writeOut(`${JSON.stringify(result)}\n`);
@@ -7,7 +7,8 @@ export function registerAuthCommands(program, runtime) {
7
7
  .helpCommand(false);
8
8
  const login = leaf(auth.command("login"))
9
9
  .description(text(runtime.product, "登录稿定", "Sign in to insMind"))
10
- .option("--no-browser", text(runtime.product, "不自动打开浏览器", "do not open a browser automatically"));
10
+ .option("--no-browser", text(runtime.product, "不自动打开浏览器", "do not open a browser automatically"))
11
+ .addHelpText("after", text(runtime.product, "\n登录成功必须包含用户 ID;缺少用户 ID 的旧登录态需重新授权。", "\nSuccessful sign-in requires a user ID. Sign in again if an older local login has no user ID."));
11
12
  bindAction(login, "none", async (_context, signal) => {
12
13
  const noBrowser = login.opts().browser === false;
13
14
  runtime.telemetry.annotate({ parameters: { noBrowser } });
@@ -34,7 +35,8 @@ export function registerAuthCommands(program, runtime) {
34
35
  }, { operation: "auth.login" });
35
36
  const status = leaf(auth.command("status"))
36
37
  .description(text(runtime.product, "查看登录状态", "Show authentication status"))
37
- .option("--json", text(runtime.product, "输出 JSON", "output JSON"));
38
+ .option("--json", text(runtime.product, "输出 JSON", "output JSON"))
39
+ .addHelpText("after", text(runtime.product, "\n本地登录态缺少用户 ID 时返回错误,请执行 auth login 重新登录。", "\nA local login without a user ID returns an error. Run auth login to sign in again."));
38
40
  bindAction(status, "none", async () => {
39
41
  const result = await runtime.auth.status({ now: runtime.now() });
40
42
  await runtime.telemetry.stage("output", async () => {
@@ -1,9 +1,9 @@
1
- import { AgentBackgroundError } from "../features/task/agent-background.js";
1
+ import { TaskBackgroundError } from "../features/task/task-background.js";
2
2
  import { TaskNotFoundError } from "../features/task/use-cases.js";
3
3
  import { TaskStoreError } from "../features/task/store.js";
4
4
  import { CommanderError } from "commander";
5
5
  import { AuthExpiredError, AuthRequiredError } from "../features/auth/access-policy.js";
6
- import { AuthStateInvalidError } from "../features/auth/state.js";
6
+ import { AuthStateInvalidError, UserIdentityMissingError } from "../features/auth/state.js";
7
7
  import { SsoRequestError } from "../features/auth/sso-service.js";
8
8
  import { AuthorizedAccountContextMissingError, DeviceAuthorizationExpiredError } from "../features/auth/use-cases.js";
9
9
  import { AgentInputError } from "../features/agent/use-cases.js";
@@ -54,7 +54,7 @@ export function mapCliError(error, options) {
54
54
  ...(error instanceof DamDownloadError ? { phase: error.phase, remaining_paths: error.remainingPaths } : {}),
55
55
  next_steps: [text(`创作用 ${command} task list 找到原任务,再用 task get <id> 查询;Editor 写入先检查原作品。不要直接重复提交。`, `For creation, find the original task with ${command} task list, then task get <id>. For Editor writes, inspect the original work. Do not resubmit directly.`)] }
56
56
  } };
57
- if (error instanceof AgentBackgroundError)
57
+ if (error instanceof TaskBackgroundError)
58
58
  return { kind: "failure", failure: error.failure, exitCode: error.exitCode };
59
59
  if (error instanceof TaskNotFoundError)
60
60
  return failure("TASK_NOT_FOUND", error.message, 1);
@@ -63,6 +63,9 @@ export function mapCliError(error, options) {
63
63
  ? "Cannot read or write local task records. Check permissions and file integrity in ~/.insmind/tasks."
64
64
  : "无法读写本地执行记录;请检查 ~/.gd/tasks 的权限和文件完整性。", 1, error.context ? [text("保留已有输出;恢复文件访问后查询原任务,不要重新提交创作。", "Keep any output; restore file access and query the original task without submitting again."),
65
65
  `${command} task get ${error.context.cli_task_id}`] : undefined, { ...error.context, reason: "task_storage", system_code: systemErrorCode(error) });
66
+ if (error instanceof UserIdentityMissingError) {
67
+ return failure("AUTH_REQUIRED", text("登录身份缺少用户 ID,请重新登录。", "The login identity has no user ID. Please sign in again."), 1, [`${command} auth login`]);
68
+ }
66
69
  if (error instanceof AuthRequiredError) {
67
70
  if (insmind)
68
71
  return failure("AUTH_REQUIRED", `Run ${command} auth login first.`, 1, [`${command} auth login`]);
@@ -34,6 +34,7 @@ export function registerToolCommands(program, runtime) {
34
34
  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."),
35
35
  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."),
36
36
  text(runtime.product, "--async 在服务端受理后输出包含 taskId 和 state 的 JSON;退出码 0 仅表示受理。", "--async returns JSON with taskId and state after acceptance; exit code 0 means accepted only."),
37
+ text(runtime.product, "异步任务由本机后台进程继续等待结果;进程终止或关机可能使状态变为 unknown。", "Async work continues in a local background process; termination or shutdown may leave its state unknown."),
37
38
  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."),
38
39
  text(runtime.product, "默认等待原 Tool 结果;任务 ID 写入 stderr,stdout 保持原 JSON。", "By default, the command waits for the original Tool result; stderr shows the Task ID and stdout keeps the result JSON."),
39
40
  text(runtime.product, `结果未收到时用 ${runtime.product.commandName} task list 找到调用,再用 ${runtime.product.commandName} task get <id> 查询,不重复生成。`, `If output is missing, use ${runtime.product.commandName} task list and ${runtime.product.commandName} task get <id> to recover it without generating again.`),
@@ -80,8 +81,7 @@ export function registerToolCommands(program, runtime) {
80
81
  label: `${prepared.input.name}: ${String(prepared.input.arguments.prompt ?? prepared.input.arguments.model ?? "")}`
81
82
  };
82
83
  if (prepared.async) {
83
- const result = await runtime.tasks.submit({ ...task,
84
- run: observe => runtime.tool.submit({ input: prepared.input, access, signal, observe }) });
84
+ const result = await runtime.startBackgroundTask({ ...task, input: prepared.input }, signal);
85
85
  await runtime.telemetry.stage("output", async () => {
86
86
  runtime.validators.taskResult(result);
87
87
  runtime.io.writeOut(`${JSON.stringify(result)}\n`);
@@ -1,3 +1,4 @@
1
+ import { requireUserIdentity } from "./state.js";
1
2
  import { OrganizationInvalidError } from "../org/use-cases.js";
2
3
  export class AuthRequiredError extends Error {
3
4
  constructor() {
@@ -20,6 +21,7 @@ export function createAccessPolicies(dependencies) {
20
21
  signal.throwIfAborted();
21
22
  if (!state)
22
23
  throw new AuthRequiredError();
24
+ requireUserIdentity(state);
23
25
  if (Date.parse(state.credential.expiresAt) <= dependencies.now().getTime()) {
24
26
  throw new AuthExpiredError();
25
27
  }
@@ -138,8 +138,8 @@ export function createSsoService(options) {
138
138
  if (isRecord(body.user)) {
139
139
  const id = identifier(body.user.id);
140
140
  const name = nonEmptyString(body.user.name);
141
- if (id && name)
142
- result.account = { id, name };
141
+ if (id)
142
+ result.account = { id, name: name ?? id };
143
143
  }
144
144
  const organizationId = identifier(body.orgId ?? body.org_id ?? body.orgID);
145
145
  if (organizationId)
@@ -40,7 +40,7 @@ function parseVersionOne(value) {
40
40
  throw new Error("invalid account");
41
41
  result.account = {
42
42
  id: requiredString(value.account.id),
43
- name: requiredString(value.account.name)
43
+ name: optionalString(value.account.name) ?? requiredString(value.account.id)
44
44
  };
45
45
  }
46
46
  if (value.organization !== undefined) {
@@ -129,3 +129,11 @@ function legacyString(value) {
129
129
  function isRecord(value) {
130
130
  return typeof value === "object" && value !== null && !Array.isArray(value);
131
131
  }
132
+ export class UserIdentityMissingError extends Error {
133
+ constructor() { super("The login state has no valid user ID."); this.name = "UserIdentityMissingError"; }
134
+ }
135
+ export function requireUserIdentity(state) {
136
+ if (!state.account?.id.trim())
137
+ throw new UserIdentityMissingError();
138
+ return state.account;
139
+ }
@@ -1,4 +1,5 @@
1
1
  import { isInterruption } from "../../platform/interruption.js";
2
+ import { requireUserIdentity, UserIdentityMissingError } from "./state.js";
2
3
  export class DeviceAuthorizationExpiredError extends Error {
3
4
  constructor(commandName = "gd-cli") {
4
5
  super(`Authorization expired. Run ${commandName} auth login again.`);
@@ -21,6 +22,7 @@ export function createAuthUseCases(dependencies) {
21
22
  logged_in: false,
22
23
  next_steps: [`${dependencies.commandName ?? "gd-cli"} auth login`]
23
24
  };
25
+ const account = await dependencies.telemetry.stage("identity", async () => requireUserIdentity(state));
24
26
  dependencies.telemetry.annotate({
25
27
  account_id: state.account?.id,
26
28
  organization_id: state.organization?.id
@@ -29,8 +31,8 @@ export function createAuthUseCases(dependencies) {
29
31
  return {
30
32
  logged_in: true,
31
33
  account: {
32
- user_id: state.account?.id ?? null,
33
- name: state.account?.name ?? null
34
+ user_id: account.id,
35
+ name: account.name
34
36
  },
35
37
  organization: !dependencies.requireOrganization && state.organization
36
38
  ? { id: state.organization.id, name: state.organization.name }
@@ -58,7 +60,7 @@ export function createAuthUseCases(dependencies) {
58
60
  async login(input) {
59
61
  input.signal.throwIfAborted();
60
62
  const existing = await dependencies.telemetry.stage("state", () => dependencies.store.read());
61
- if (existing
63
+ if (existing?.account?.id.trim()
62
64
  && Date.parse(existing.credential.expiresAt) > dependencies.now().getTime()
63
65
  && (!dependencies.requireOrganization || existing.organization !== undefined)) {
64
66
  dependencies.telemetry.annotate({
@@ -111,23 +113,28 @@ export function createAuthUseCases(dependencies) {
111
113
  credential: token.credential,
112
114
  ...(token.account ? { account: token.account } : {})
113
115
  };
114
- if (!dependencies.requireOrganization) {
115
- await dependencies.telemetry.stage("state", () => dependencies.store.write(state));
116
- }
117
116
  dependencies.telemetry.annotate({ account_id: state.account?.id });
118
117
  let organizationId = token.organizationId;
119
- const identity = await dependencies.telemetry.stage("identity", () => (dependencies.sso.getIdentity(token.credential.accessKey, input.signal))).catch(cause => {
118
+ const identity = await dependencies.telemetry.stage("identity", async () => {
119
+ const identity = await dependencies.sso.getIdentity(token.credential.accessKey, input.signal);
120
+ if (!state.account?.id.trim() && !identity.account?.id.trim())
121
+ throw new UserIdentityMissingError();
122
+ return identity;
123
+ }).catch(cause => {
120
124
  if (isInterruption(cause, input.signal))
121
125
  throw input.signal.reason;
126
+ if (!state.account?.id.trim())
127
+ throw cause;
122
128
  return undefined;
123
129
  });
124
130
  organizationId = identity?.organizationId ?? organizationId;
125
131
  if (!state.account && identity?.account) {
126
132
  state = { ...state, account: identity.account };
127
133
  dependencies.telemetry.annotate({ account_id: identity.account.id });
128
- if (!dependencies.requireOrganization) {
129
- await dependencies.telemetry.stage("state", () => dependencies.store.write(state));
130
- }
134
+ }
135
+ requireUserIdentity(state);
136
+ if (!dependencies.requireOrganization) {
137
+ await dependencies.telemetry.stage("state", () => dependencies.store.write(state));
131
138
  }
132
139
  if (!organizationId) {
133
140
  if (dependencies.requireOrganization)
@@ -70,6 +70,8 @@ export function createTaskStore(options) {
70
70
  }
71
71
  if (previous.task.state === "completed" || (previous.task.state === "failed" && record.task.state !== "completed"))
72
72
  record.task = previous.task;
73
+ if (previous.analytics)
74
+ record.analytics = { ...record.analytics, ...previous.analytics };
73
75
  if (previous.telemetry)
74
76
  record.telemetry = {
75
77
  ...record.telemetry, ...previous.telemetry,
@@ -1,15 +1,15 @@
1
1
  import { fork } from "node:child_process";
2
- export class AgentBackgroundError extends Error {
2
+ export class TaskBackgroundError extends Error {
3
3
  failure;
4
4
  exitCode;
5
5
  constructor(failure, exitCode = 1) {
6
6
  super(failure.message);
7
7
  this.failure = failure;
8
8
  this.exitCode = exitCode;
9
- this.name = "AgentBackgroundError";
9
+ this.name = "TaskBackgroundError";
10
10
  }
11
11
  }
12
- export function createAgentBackgroundLauncher(options) {
12
+ export function createTaskBackgroundLauncher(options) {
13
13
  return {
14
14
  submit(job, signal, started) {
15
15
  signal.throwIfAborted();
@@ -36,7 +36,7 @@ export function createAgentBackgroundLauncher(options) {
36
36
  else
37
37
  resolve(result);
38
38
  };
39
- const unavailable = () => finish(new AgentBackgroundError({
39
+ const unavailable = () => finish(new TaskBackgroundError({
40
40
  code: "TASK_WORKER_UNAVAILABLE",
41
41
  message: job.product === "insmind"
42
42
  ? "The background process did not return a receipt. Check task list/get before submitting again."
@@ -53,7 +53,7 @@ export function createAgentBackgroundLauncher(options) {
53
53
  else if (message.type === "accepted")
54
54
  finish(message.task);
55
55
  else if (message.type === "error")
56
- finish(new AgentBackgroundError(message.failure, message.exitCode));
56
+ finish(new TaskBackgroundError(message.failure, message.exitCode));
57
57
  });
58
58
  signal.addEventListener("abort", aborted, { once: true });
59
59
  child.send(job, error => { if (error)
@@ -104,6 +104,45 @@ export function createTaskUseCases(dependencies) {
104
104
  ...(dependencies.creationVersion ? { cli_version: dependencies.creationVersion } : {}),
105
105
  ...(input.state.account ? { account_id: input.state.account.id } : {}), organization_id: input.state.organization.id } };
106
106
  }
107
+ // The task execution owns Wind. Recovery reads and SLS replay never call it.
108
+ const analytics = input.state.account ? await dependencies.analytics?.prepare({
109
+ userId: input.state.account.id, organizationId: input.state.organization.id
110
+ }).catch(() => undefined) : undefined;
111
+ if (analytics)
112
+ record.analytics = { context: analytics.context };
113
+ async function analyticsFact(event) {
114
+ if (!analytics || !record.analytics)
115
+ return;
116
+ try {
117
+ let claimed = false;
118
+ const updated = await stage("wind.record", () => dependencies.store.update(scope, record.task.taskId, stored => {
119
+ if (!stored.analytics || stored.analytics[event])
120
+ return;
121
+ if (event === "started") {
122
+ const generation = record.progress.generation;
123
+ let details;
124
+ if (input.operation === "agent.send")
125
+ details = { tool_type: "agent", tool_name: "agent" };
126
+ else if (generation?.model && (generation.tool === "image.generate" || generation.tool === "video.generate")) {
127
+ const name = generation.tool === "image.generate" ? "AI绘图" : "AI视频生成";
128
+ details = { tool_type: name, tool_name: name, model_name: generation.model };
129
+ }
130
+ else
131
+ return;
132
+ stored.analytics.details = details;
133
+ }
134
+ else if (!stored.analytics.started)
135
+ return;
136
+ stored.analytics[event] = true;
137
+ claimed = true;
138
+ }));
139
+ if (updated.analytics)
140
+ record.analytics = updated.analytics;
141
+ if (claimed && updated.analytics?.details)
142
+ analytics.track(event, updated.analytics.details);
143
+ }
144
+ catch { /* Failed analytics persistence cannot change a creation result. */ }
145
+ }
107
146
  let dispatched = false;
108
147
  let durableAcceptance = false;
109
148
  function storageContext(error, phase) {
@@ -144,6 +183,7 @@ export function createTaskUseCases(dependencies) {
144
183
  if (progress.dispatchedAt !== undefined) {
145
184
  dispatched = true;
146
185
  await fact(scope, record, "request_sent", progress.dispatchedAt);
186
+ await analyticsFact("started");
147
187
  return;
148
188
  }
149
189
  Object.assign(record.progress, progress);
@@ -165,8 +205,10 @@ export function createTaskUseCases(dependencies) {
165
205
  clearInterval(timer);
166
206
  await stage("task.validate", async () => { finish(record, result); });
167
207
  telemetry?.annotate({ result_state: record.task.state });
168
- if (record.task.state === "completed")
208
+ if (record.task.state === "completed") {
169
209
  await fact(scope, record, "result_ready", dependencies.now().getTime());
210
+ await analyticsFact("completed");
211
+ }
170
212
  try {
171
213
  await stage("task.persist", save);
172
214
  }
@@ -155,7 +155,7 @@ export function createToolUseCases(dependencies) {
155
155
  model: model.model,
156
156
  ...(model.cost === undefined ? {} : { cost: model.cost })
157
157
  };
158
- await observe?.({ toolUsage: usage });
158
+ await observe?.({ toolUsage: usage, generation: { tool: model.tool, model: model.model } });
159
159
  return { invocation, usage };
160
160
  }
161
161
  return {
@@ -0,0 +1,10 @@
1
+ # GD-Tracker Node artifact
2
+
3
+ Official GD-Tracker `2.21.0-beta.5`, master source `5bdbdce78f6de06a74aac566cc962aa57a4eb78e`.
4
+
5
+ - Artifact: https://cdn.dancf.com/packages/gaoding/gd-tracker/2.21.0-beta.5/node.mjs
6
+ - SHA-256: `71c0ee126aae06386084ca2f955376122375f9448d623ed9f0dc2b07494f1387`
7
+ - Declarations: unmodified `types/node.d.ts` from that SDK source, saved as `.d.mts` for the ESM entry.
8
+ - Distribution contract: https://git.intra.gaoding.com/gaoding/gd-tracker/-/blob/master/website/docs/sdk/node-sdk.md
9
+
10
+ The build verifies and copies the standalone artifact into `dist/vendor`. Both public CLI tarballs include it. End-user installation and command execution never download executable SDK code or install private SDK dependencies. Upgrade the version, hash and declarations together.