@insmind/cli 1.5.7 → 1.5.8

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.
@@ -3,8 +3,8 @@ import { join } from "node:path";
3
3
  import { withFileLock } from "../platform/file-lock.js";
4
4
  import { createLocalJsonFile } from "../platform/local-json-file.js";
5
5
  export async function loadAnalyticsDevice(directory, now) {
6
- return withFileLock(join(directory, "analytics-device.lock"), async () => {
7
- const file = createLocalJsonFile({ directory, filename: "analytics-device.json" });
6
+ const file = createLocalJsonFile({ directory, filename: "analytics-device.json" });
7
+ async function read() {
8
8
  const text = await file.readText();
9
9
  if (text !== null) {
10
10
  const device = JSON.parse(text);
@@ -13,6 +13,16 @@ export async function loadAnalyticsDevice(directory, now) {
13
13
  }
14
14
  return device;
15
15
  }
16
+ return null;
17
+ }
18
+ // The installation identity is immutable. Only creation needs a writer lock.
19
+ const previous = await read();
20
+ if (previous)
21
+ return previous;
22
+ return withFileLock(join(directory, "analytics-device.lock"), async () => {
23
+ const existing = await read();
24
+ if (existing)
25
+ return existing;
16
26
  const device = { id: randomUUID(), createdAt: now() };
17
27
  await file.writeTextAtomically(`${JSON.stringify(device)}\n`);
18
28
  return device;
@@ -1,7 +1,47 @@
1
1
  import { loadAnalyticsDevice, isFirstDay } from "./device.js";
2
+ const DELIVERY_BUDGET_MS = 1_500;
3
+ const SHUTDOWN_BUDGET_MS = 2_000;
4
+ export class WindAnalyticsError extends Error {
5
+ code;
6
+ status;
7
+ constructor(code, status, message = code, cause) {
8
+ super(message, { cause });
9
+ this.code = code;
10
+ this.status = status;
11
+ this.name = "WindAnalyticsError";
12
+ }
13
+ }
14
+ // A fetch implementation may ignore cancellation. Still settle the SDK request
15
+ // at its existing deadline, and let native fetch release resources via the signal.
16
+ async function abortableFetch(fetch, input, init) {
17
+ const signal = init?.signal;
18
+ if (!signal)
19
+ return fetch(input, init);
20
+ signal.throwIfAborted();
21
+ let onAbort;
22
+ const aborted = new Promise((_resolve, reject) => {
23
+ onAbort = () => reject(signal.reason);
24
+ signal.addEventListener("abort", onAbort, { once: true });
25
+ });
26
+ try {
27
+ return await Promise.race([fetch(input, init), aborted]);
28
+ }
29
+ finally {
30
+ signal.removeEventListener("abort", onAbort);
31
+ }
32
+ }
33
+ function networkCode(error) {
34
+ for (let depth = 0; error instanceof Error && depth < 10; depth++, error = error.cause) {
35
+ if ("code" in error && typeof error.code === "string"
36
+ && /^(?:E[A-Z0-9_]{1,40}|UND_ERR_[A-Z0-9_]{1,40})$/u.test(error.code))
37
+ return error.code;
38
+ }
39
+ return undefined;
40
+ }
2
41
  /** One application adapter owns SDK identity and lifecycle. No SLS payloads enter Wind. */
3
42
  export function createWindAnalytics(options) {
4
43
  const trackers = new Set();
44
+ const pending = new Set();
5
45
  const insmind = options.product === "insmind";
6
46
  const project = insmind ? "insmind_cli" : "gd_cli";
7
47
  return {
@@ -13,10 +53,37 @@ export function createWindAnalytics(options) {
13
53
  const device = await loadAnalyticsDevice(options.directory, options.now);
14
54
  const { CliWindTracker, createNodeAdapters } = await import("../../vendor/gd-tracker-node.mjs");
15
55
  const tracker = new CliWindTracker();
56
+ const adapters = createNodeAdapters({ fetch: options.fetch, deliveryBudgetMs: DELIVERY_BUDGET_MS });
57
+ adapters.transport = {
58
+ async send(payload, signal) {
59
+ let cause;
60
+ let requestSignal;
61
+ // Keep the official encoding/endpoint/budget behavior. A per-request
62
+ // fetch closure preserves the cause without mixing concurrent events.
63
+ const transport = createNodeAdapters({ deliveryBudgetMs: DELIVERY_BUDGET_MS,
64
+ fetch: async (input, init) => {
65
+ requestSignal = init?.signal;
66
+ try {
67
+ return await abortableFetch(options.fetch, input, init);
68
+ }
69
+ catch (error) {
70
+ cause = error;
71
+ throw error;
72
+ }
73
+ } }).transport;
74
+ const result = await transport.send(payload, signal);
75
+ const reason = requestSignal?.reason;
76
+ const abortReason = requestSignal?.aborted
77
+ ? reason instanceof Error && reason.message === "delivery budget exceeded" ? "delivery_timeout"
78
+ : reason instanceof Error && reason.message === "flush/shutdown timeout" ? "shutdown_timeout" : "aborted"
79
+ : undefined;
80
+ return { ...result, ...(cause === undefined ? {} : { cause }), ...(abortReason ? { abortReason } : {}) };
81
+ }
82
+ };
16
83
  await tracker.setup({ mode: "cli", project, version: options.version, env: options.environment,
17
84
  region: insmind ? "US" : "CHINA", deviceId: device.id,
18
85
  userAgent: `${insmind ? "insmind-cli" : "gd-cli"}/${options.version}`,
19
- adapters: createNodeAdapters({ fetch: options.fetch, deliveryBudgetMs: 1_500 }) });
86
+ adapters });
20
87
  tracker.set("common", { user_id: identity.userId, is_login: 1,
21
88
  organization: { org_id: identity.organizationId,
22
89
  ...(!insmind ? { uc_id: identity.userId } : {}) },
@@ -25,16 +92,23 @@ export function createWindAnalytics(options) {
25
92
  return {
26
93
  context: { ...identity, deviceId: device.id, version: options.version, project },
27
94
  track(event, details) {
28
- void options.stage("wind.send", async () => {
95
+ const evidence = { wind_event: event, wind_event_id: event === "started" ? 37010 : 37011 };
96
+ const delivery = options.stage("wind.send", async () => {
29
97
  tracker.set("common", { is_first_day: isFirstDay(device.createdAt, options.now()) });
30
98
  // Explicit whitelist: command parameters and diagnostics are never spread into details.
31
99
  const payload = { event_id: event === "started" ? 37010 : 37011,
32
100
  tool_type: details.tool_type, tool_name: details.tool_name,
33
101
  ...(details.model_name ? { model_name: details.model_name } : {}) };
34
102
  const result = await tracker.trackEvent(event === "started" ? "tool_conflate_start" : "tool_conflate_completed", payload);
103
+ Object.assign(evidence, { wind_accepted: result.accepted, wind_retryable: result.retryable,
104
+ ...(result.status === undefined ? {} : { http_status: result.status }),
105
+ ...(result.abortReason ? { wind_abort_reason: result.abortReason } : {}),
106
+ ...(networkCode(result.cause) ? { wind_network_code: networkCode(result.cause) } : {}) });
35
107
  if (!result.accepted)
36
- throw new Error(result.errorCode ?? "WIND_DELIVERY_FAILED");
37
- }).catch(() => undefined);
108
+ throw new WindAnalyticsError(result.errorCode ?? "WIND_DELIVERY_FAILED", result.status, result.message ?? (result.status ? `Wind delivery failed (HTTP ${result.status}).` : "Wind delivery failed."), result.cause);
109
+ }, () => evidence).catch(() => undefined);
110
+ pending.add(delivery);
111
+ void delivery.then(() => pending.delete(delivery));
38
112
  }
39
113
  };
40
114
  });
@@ -44,12 +118,25 @@ export function createWindAnalytics(options) {
44
118
  }
45
119
  },
46
120
  async shutdown() {
47
- await Promise.all([...trackers].map(tracker => options.stage("wind.shutdown", async () => {
48
- const summary = await tracker.shutdown({ timeoutMs: 500 });
49
- if (!summary.flushed)
50
- throw new Error(summary.errorCode ?? "WIND_FLUSH_TIMEOUT");
51
- }).catch(() => undefined)));
52
- trackers.clear();
121
+ if (!trackers.size)
122
+ return;
123
+ let timer;
124
+ try {
125
+ await options.stage("wind.shutdown", () => new Promise((resolve, reject) => {
126
+ timer = setTimeout(() => reject(new WindAnalyticsError("GD_TRACKER_FLUSH_TIMEOUT")), SHUTDOWN_BUDGET_MS);
127
+ void (async () => {
128
+ const summaries = await Promise.all([...trackers].map(tracker => tracker.shutdown({ timeoutMs: SHUTDOWN_BUDGET_MS })));
129
+ // SDK flush waits for transport; the CLI also owns the diagnostic stages.
130
+ await Promise.allSettled([...pending]);
131
+ if (summaries.some(summary => !summary.flushed))
132
+ throw new WindAnalyticsError("GD_TRACKER_FLUSH_TIMEOUT");
133
+ })().then(resolve, reject);
134
+ })).catch(() => undefined);
135
+ }
136
+ finally {
137
+ clearTimeout(timer);
138
+ trackers.clear();
139
+ }
53
140
  }
54
141
  };
55
142
  }
@@ -138,9 +138,8 @@ async function checkUpdateNotification(updateNotification, signal) {
138
138
  }
139
139
  }
140
140
  async function sendFinished(options, completion) {
141
+ await analyticsShutdown.get(options.program)?.().catch(() => undefined);
141
142
  const events = options.telemetry.finish(completion);
142
- await Promise.all([
143
- events.length > 0 ? options.telemetrySink.send(events).catch(() => undefined) : undefined,
144
- analyticsShutdown.get(options.program)?.().catch(() => undefined)
145
- ]);
143
+ if (events.length > 0)
144
+ await options.telemetrySink.send(events).catch(() => undefined);
146
145
  }
@@ -106,7 +106,7 @@ export function createProductionRuntime(options = {}) {
106
106
  directory: join(options.homeDirectory ?? homedir(), product.stateDirectory),
107
107
  environment: telemetryEnvironment === "production" ? "prod" : "dev", fetch: options.windFetch ?? fetch,
108
108
  now: () => now().getTime(),
109
- stage: (name, run) => telemetry.stage(name, run)
109
+ stage: (name, run, details) => telemetry.stage(name, run, details)
110
110
  }) : undefined);
111
111
  const rawIo = options.io ?? {
112
112
  input: process.stdin,
@@ -50,9 +50,7 @@ export async function runTaskWorker(options) {
50
50
  send({ type: "error", failure: outcome.failure, exitCode: outcome.exitCode });
51
51
  }
52
52
  finally {
53
- await Promise.all([
54
- runtime.telemetrySink.send(runtime.telemetry.finish(completion)).catch(() => undefined),
55
- runtime.analytics?.shutdown().catch(() => undefined)
56
- ]);
53
+ await runtime.analytics?.shutdown().catch(() => undefined);
54
+ await runtime.telemetrySink.send(runtime.telemetry.finish(completion)).catch(() => undefined);
57
55
  }
58
56
  }
@@ -26,6 +26,7 @@ import { LocalFileError } from "../platform/local-json-file.js";
26
26
  import { redactSensitiveText } from "../platform/redact.js";
27
27
  import { EditorNotReadyError, EditorSessionNotFoundError, EditorTargetError } from "../features/editor/session.js";
28
28
  import { UpdateError } from "../features/update/update-service.js";
29
+ import { WindAnalyticsError } from "../analytics/wind.js";
29
30
  export class CliUsageError extends Error {
30
31
  constructor() {
31
32
  super("命令或参数无效。");
@@ -220,6 +221,9 @@ function isInsufficientCreditsError(error) {
220
221
  || error instanceof ToolTaskFailedError) && error.remoteCode === INSUFFICIENT_CREDITS_REMOTE_CODE;
221
222
  }
222
223
  export function classifyTelemetryError(error, options = {}) {
224
+ if (error instanceof WindAnalyticsError)
225
+ return { outcome: "failure", errorCode: error.code,
226
+ ...(error.status === undefined ? {} : { httpStatus: error.status }) };
223
227
  const outcome = mapCliError(error, { ...options, aborted: options.aborted === true });
224
228
  let remoteError;
225
229
  for (let cause = error, depth = 0; cause instanceof Error && depth < 10; cause = cause.cause, depth++) {
@@ -2,7 +2,6 @@ import { isInterruption } from "../../platform/interruption.js";
2
2
  import { createHash } from "node:crypto";
3
3
  import { createReadStream } from "node:fs";
4
4
  import { setTimeout as delay } from "node:timers/promises";
5
- import sharp from "sharp";
6
5
  import { RemoteRequestError } from "../../platform/signed-http-transport.js";
7
6
  import { projectDamAssetDetail } from "./asset-projection.js";
8
7
  import { DamOperationUnconfirmedError } from "./operation-executor.js";
@@ -89,6 +88,7 @@ export function createDamRegisteredUploader(dependencies) {
89
88
  const sleep = dependencies.sleep ?? defaultSleep;
90
89
  const imageMetadata = dependencies.imageMetadata
91
90
  ?? (async (filePath) => {
91
+ const { default: sharp } = await import("sharp");
92
92
  const metadata = await sharp(filePath).metadata();
93
93
  return { width: metadata.width, height: metadata.height };
94
94
  });
@@ -1,10 +1,39 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import * as nodeFileSystem from "node:fs/promises";
3
- import { join } from "node:path";
3
+ import { join, resolve } from "node:path";
4
4
  import { setTimeout as delay } from "node:timers/promises";
5
- /** Local bakery lock: unique owner files avoid deleting a new owner's lock
6
- * when several processes simultaneously recover a dead writer. */
5
+ const localTurns = new Map();
6
+ /** Same-process waiters queue before creating bakery owners. Separate processes
7
+ * still coordinate through unique owner files and retain the two-second budget. */
7
8
  export async function withFileLock(path, run, options = {}) {
9
+ const deadline = Math.min(options.deadline ?? Infinity, Date.now() + 2_000);
10
+ if (Date.now() >= deadline)
11
+ throw new Error("Local state lock timed out.");
12
+ const key = resolve(path);
13
+ const previous = localTurns.get(key) ?? Promise.resolve();
14
+ let release;
15
+ const turn = new Promise(resolve => { release = resolve; });
16
+ const tail = previous.then(() => turn);
17
+ localTurns.set(key, tail);
18
+ let timer;
19
+ try {
20
+ await new Promise((ready, reject) => {
21
+ timer = setTimeout(() => reject(new Error("Local state lock timed out.")), Math.max(0, deadline - Date.now()));
22
+ void previous.then(ready);
23
+ });
24
+ clearTimeout(timer);
25
+ return await acquireFileLock(path, run, { ...options, deadline });
26
+ }
27
+ finally {
28
+ clearTimeout(timer);
29
+ release();
30
+ // A timed-out waiter cannot let a new caller bypass a still-active predecessor.
31
+ void tail.then(() => { if (localTurns.get(key) === tail)
32
+ localTurns.delete(key); });
33
+ }
34
+ }
35
+ /** Unique owners avoid deleting a new writer during concurrent crash recovery. */
36
+ async function acquireFileLock(path, run, options) {
8
37
  const fileSystem = options.fileSystem ?? nodeFileSystem;
9
38
  const { mkdir, open, readFile, readdir, unlink, chmod, rename } = fileSystem;
10
39
  const deadline = Math.min(options.deadline ?? Infinity, Date.now() + 2_000);
@@ -16,16 +16,32 @@ export function createLocalJsonFile(options) {
16
16
  const path = join(options.directory, options.filename);
17
17
  return {
18
18
  async readText() {
19
+ let handle;
20
+ let failed = false;
21
+ let primaryError;
19
22
  try {
20
23
  await fileSystem.chmod(options.directory, 0o700);
21
- await fileSystem.chmod(path, 0o600);
22
- return await fileSystem.readFile(path, "utf8");
24
+ handle = await fileSystem.open(path, "r");
25
+ await handle.chmod(0o600);
26
+ return await handle.readFile("utf8");
23
27
  }
24
28
  catch (cause) {
25
- if (isMissing(cause))
29
+ if (!handle && isMissing(cause))
26
30
  return null;
31
+ failed = true;
32
+ primaryError = cause;
27
33
  throw new LocalFileError(cause, options.filename);
28
34
  }
35
+ finally {
36
+ try {
37
+ await handle?.close();
38
+ }
39
+ catch (cause) {
40
+ throw new LocalFileError(failed
41
+ ? new AggregateError([primaryError, cause], "Cannot read and close local state.", { cause: primaryError })
42
+ : cause, options.filename);
43
+ }
44
+ }
29
45
  },
30
46
  async writeTextAtomically(value) {
31
47
  const temporaryPath = join(options.directory, `${options.filename}.tmp-${randomUUID()}`);
@@ -34,11 +50,11 @@ export function createLocalJsonFile(options) {
34
50
  await fileSystem.mkdir(options.directory, { mode: 0o700, recursive: true });
35
51
  await fileSystem.chmod(options.directory, 0o700);
36
52
  handle = await fileSystem.open(temporaryPath, "wx", 0o600);
53
+ await handle.chmod(0o600);
37
54
  await handle.writeFile(value, "utf8");
38
55
  await handle.sync();
39
56
  await handle.close();
40
57
  handle = undefined;
41
- await fileSystem.chmod(temporaryPath, 0o600);
42
58
  await fileSystem.rename(temporaryPath, path);
43
59
  }
44
60
  catch (cause) {
@@ -74,21 +74,21 @@ export function createTelemetryInvocation(options) {
74
74
  return cleanDiagnostic({ ...snapshot, mode: "execute" });
75
75
  },
76
76
  async emit(event) { await publish(remember(event)); },
77
- async stage(name, run) {
77
+ async stage(name, run, details) {
78
78
  const start = options.now();
79
79
  const allowed = detailedStages[definition?.mode ? `${definition.operation}:${definition.mode()}` : definition?.operation ?? ""];
80
80
  try {
81
81
  const result = await run();
82
- if (definition && allowed?.has(name))
82
+ if (definition && (allowed?.has(name) || details))
83
83
  remember({ ...base(), event_name: "stage_finished",
84
- stage: name, outcome: "success", duration_ms: Math.max(0, options.now() - start) });
84
+ stage: name, outcome: "success", duration_ms: Math.max(0, options.now() - start), ...details?.() });
85
85
  return result;
86
86
  }
87
87
  catch (error) {
88
88
  failures.push({ name, error });
89
89
  const event = remember({ ...base(), event_name: "stage_finished", stage: name,
90
90
  outcome: classify(error).outcome,
91
- duration_ms: Math.max(0, options.now() - start), ...errorFields(error) });
91
+ duration_ms: Math.max(0, options.now() - start), ...errorFields(error), ...details?.() });
92
92
  await publish(event);
93
93
  throw error;
94
94
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@insmind/cli",
3
- "version": "1.5.7",
3
+ "version": "1.5.8",
4
4
  "description": "insMind command-line interface for agents and people.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -46,8 +46,8 @@
46
46
  "@gaoding/cli": "workspace:*"
47
47
  },
48
48
  "gaodingRelease": {
49
- "sourceCommit": "2757c808d8c6d0a525d31be149f0a51477c35e68",
50
- "pipelineId": "205097",
51
- "pipelineUrl": "https://git.intra.gaoding.com/gtt/gaoding-cli/-/pipelines/205097"
49
+ "sourceCommit": "4d09717c363ed49e1dffea3f71a671cc3b406423",
50
+ "pipelineId": "211435",
51
+ "pipelineUrl": "https://git.intra.gaoding.com/gtt/gaoding-cli/-/pipelines/211435"
52
52
  }
53
53
  }