@insmind/cli 1.5.7 → 1.5.9

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,
@@ -1,6 +1,7 @@
1
1
  import { requireUserIdentity } from "../features/auth/state.js";
2
2
  import { isInterruption } from "../platform/interruption.js";
3
- import { mapCliError } from "../cli/errors.js";
3
+ import { taskWorkerDiagnostics } from "../features/task/task-background.js";
4
+ import { classifyTelemetryError, mapCliError } from "../cli/errors.js";
4
5
  import { redact } from "../platform/redact.js";
5
6
  export async function runTaskWorker(options) {
6
7
  const runtime = options.runtime;
@@ -47,12 +48,11 @@ export async function runTaskWorker(options) {
47
48
  completion = outcome.kind === "interrupted" ? { outcome: "interrupted", error }
48
49
  : { outcome: "failure", error, errorCode: outcome.failure.code, errorMessage: outcome.failure.message };
49
50
  if (outcome.kind === "failure")
50
- send({ type: "error", failure: outcome.failure, exitCode: outcome.exitCode });
51
+ send({ type: "error", failure: outcome.failure, exitCode: outcome.exitCode,
52
+ diagnostics: taskWorkerDiagnostics(error, classifyTelemetryError(error, { product: runtime.product }), runtime.telemetry.failureStage(error)) });
51
53
  }
52
54
  finally {
53
- await Promise.all([
54
- runtime.telemetrySink.send(runtime.telemetry.finish(completion)).catch(() => undefined),
55
- runtime.analytics?.shutdown().catch(() => undefined)
56
- ]);
55
+ await runtime.analytics?.shutdown().catch(() => undefined);
56
+ await runtime.telemetrySink.send(runtime.telemetry.finish(completion)).catch(() => undefined);
57
57
  }
58
58
  }
@@ -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,7 +221,20 @@ 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 });
228
+ if (error instanceof TaskBackgroundError) {
229
+ const diagnostics = error.diagnostics;
230
+ return { outcome: outcome.kind === "interrupted" ? "interrupted" : "failure",
231
+ ...(outcome.kind === "failure" ? { errorCode: outcome.failure.code } : {}),
232
+ ...(diagnostics?.error_type ? { errorType: diagnostics.error_type } : {}),
233
+ ...(diagnostics?.failure_stage ? { failureStage: diagnostics.failure_stage } : {}),
234
+ ...(diagnostics?.http_status === undefined ? {} : { httpStatus: diagnostics.http_status }),
235
+ ...(diagnostics?.remote_error_code ? { remoteErrorCode: diagnostics.remote_error_code } : {}),
236
+ ...(diagnostics?.diagnostic_reason ? { diagnosticReason: diagnostics.diagnostic_reason } : {}) };
237
+ }
224
238
  let remoteError;
225
239
  for (let cause = error, depth = 0; cause instanceof Error && depth < 10; cause = cause.cause, depth++) {
226
240
  if (cause instanceof RemoteRequestError || cause instanceof RemoteProtocolError || cause instanceof ToolTaskFailedError
@@ -240,7 +254,9 @@ export function classifyTelemetryError(error, options = {}) {
240
254
  : { remoteErrorCode: remoteError.remoteCode }),
241
255
  ...(remoteError?.remoteBody === undefined
242
256
  ? {}
243
- : { remoteErrorBody: remoteError.remoteBody })
257
+ : { remoteErrorBody: remoteError.remoteBody }),
258
+ ...((remoteError instanceof RemoteRequestError || remoteError instanceof RemoteProtocolError) && remoteError.diagnosticReason
259
+ ? { diagnosticReason: remoteError.diagnosticReason } : {})
244
260
  };
245
261
  }
246
262
  function failure(code, message, exitCode, nextSteps, details) {
@@ -11,7 +11,7 @@ export function createCreativeAgentAdapter(dependencies) {
11
11
  }
12
12
  : { localMessageId: dependencies.idFactory() };
13
13
  await observe?.({ localMessageId: ids.localMessageId, ...(message.contextId ? { contextId: message.contextId } : {}) });
14
- const streamed = await dependencies.telemetry.stage("execute", async () => {
14
+ const { streamed, contextId } = await dependencies.telemetry.stage("execute", async () => {
15
15
  await observe?.({ submissionStarted: true });
16
16
  const stream = await dependencies.transport.postStream({
17
17
  path: "/ai-agent/v1/thread/completion",
@@ -23,9 +23,9 @@ export function createCreativeAgentAdapter(dependencies) {
23
23
  signal
24
24
  });
25
25
  await observe?.({ accepted: true });
26
- return parseCreativeStream(stream, signal, observe ? async (contextId) => observe({ contextId }) : undefined);
26
+ const streamed = await parseCreativeStream(stream, signal, observe ? async (contextId) => observe({ contextId }) : undefined);
27
+ return { streamed, contextId: creativeContextId(streamed) };
27
28
  });
28
- const contextId = creativeContextId(streamed);
29
29
  return dependencies.telemetry.stage("result", async () => {
30
30
  const messages = await dependencies.transport.getJson({
31
31
  path: `/ai-agent/v1/thread/${encodeURIComponent(contextId)}/messages`,
@@ -1,4 +1,5 @@
1
1
  import { RemoteProtocolError } from "../../platform/remote-protocol.js";
2
+ import { RemoteRequestError } from "../../platform/signed-http-transport.js";
2
3
  export function buildCreativeRequest(message, ids) {
3
4
  const prompt = [];
4
5
  const textParts = [];
@@ -104,20 +105,27 @@ function parseJson(value) {
104
105
  function nonEmptyString(value) {
105
106
  return typeof value === "string" && value.trim() !== "" ? value : undefined;
106
107
  }
107
- function fail() {
108
- throw new RemoteProtocolError();
108
+ function fail(diagnosticReason, summary) {
109
+ throw new RemoteProtocolError(summary === undefined ? {} : { remoteBody: JSON.stringify(summary) }, undefined, diagnosticReason);
109
110
  }
110
111
  export function creativeContextId(messages) {
111
- if (messages.some((message) => message.event === "system_error"))
112
- return fail();
113
112
  const contextId = messages
114
113
  .map((message) => nonEmptyString(message.thread_id))
115
114
  .find((value) => value !== undefined);
116
- return contextId ?? fail();
115
+ const systemErrorCount = messages.filter((message) => message.event === "system_error").length;
116
+ const summary = { messageCount: messages.length, contextIdPresent: contextId !== undefined, systemErrorCount };
117
+ if (systemErrorCount > 0) {
118
+ throw new RemoteRequestError(undefined, false, { remoteBody: JSON.stringify(summary) }, undefined, "AGENT_SYSTEM_ERROR");
119
+ }
120
+ return contextId ?? fail("AGENT_CONTEXT_ID_MISSING", summary);
117
121
  }
118
122
  export function creativeTurnMessages(value, localMessageId) {
119
- if (!Array.isArray(value) || !value.every((message) => record(message) !== undefined)) {
120
- return fail();
123
+ if (!Array.isArray(value)) {
124
+ return fail("AGENT_MESSAGES_NOT_ARRAY", { valueType: value === null ? "null" : typeof value });
125
+ }
126
+ const invalidMessageCount = value.filter((message) => record(message) === undefined).length;
127
+ if (invalidMessageCount > 0) {
128
+ return fail("AGENT_MESSAGE_INVALID", { messageCount: value.length, invalidMessageCount });
121
129
  }
122
130
  const messages = value;
123
131
  const start = messages.findIndex((message) => {
@@ -125,8 +133,12 @@ export function creativeTurnMessages(value, localMessageId) {
125
133
  return false;
126
134
  return message.role === "user" || contentOf(message)?.type === "function_response";
127
135
  });
128
- if (start < 0)
129
- return fail();
136
+ if (start < 0) {
137
+ const matchingLocalMessageCount = messages.filter((message) => message.local_message_id === localMessageId).length;
138
+ return fail(matchingLocalMessageCount > 0 ? "AGENT_TURN_ANCHOR_INVALID" : "AGENT_TURN_ANCHOR_MISSING", {
139
+ messageCount: messages.length, matchingLocalMessageCount
140
+ });
141
+ }
130
142
  const nextInput = messages.findIndex((message, index) => index > start
131
143
  && typeof message.local_message_id === "string" && message.local_message_id !== ""
132
144
  && message.local_message_id !== localMessageId
@@ -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,12 +1,64 @@
1
1
  import { fork } from "node:child_process";
2
+ function diagnosticToken(value, pattern) {
3
+ return typeof value === "string" && pattern.test(value) ? value : undefined;
4
+ }
5
+ function safeDiagnostics(value) {
6
+ if (!value || typeof value !== "object" || Array.isArray(value))
7
+ return undefined;
8
+ const record = value;
9
+ const error_type = diagnosticToken(record.error_type, /^(?:[A-Za-z][A-Za-z0-9_]{0,79}|object|string|number|undefined)$/u);
10
+ const remote_error_code = diagnosticToken(record.remote_error_code, /^(?:-?\d{1,16}|[A-Z][A-Z0-9_.:-]{0,79})$/u);
11
+ const diagnostic_reason = diagnosticToken(record.diagnostic_reason, /^[A-Z][A-Z0-9_]{0,79}$/u);
12
+ const failure_stage = diagnosticToken(record.failure_stage, /^[a-z][a-z0-9_.-]{0,79}$/u);
13
+ const http_status = typeof record.http_status === "number" && Number.isInteger(record.http_status)
14
+ && record.http_status >= 100 && record.http_status <= 599 ? record.http_status : undefined;
15
+ const causes = Array.isArray(record.causes) ? record.causes.slice(0, 10).flatMap(cause => {
16
+ if (!cause || typeof cause !== "object" || Array.isArray(cause))
17
+ return [];
18
+ const item = cause;
19
+ const error_type = diagnosticToken(item.error_type, /^[A-Za-z][A-Za-z0-9_]{0,79}$/u);
20
+ const system_code = diagnosticToken(item.system_code, /^(?:E[A-Z0-9_]{1,40}|UND_ERR_[A-Z0-9_]{1,40})$/u);
21
+ return error_type ? [{ error_type, ...(system_code ? { system_code } : {}) }] : [];
22
+ }) : undefined;
23
+ return {
24
+ ...(error_type ? { error_type } : {}), ...(http_status === undefined ? {} : { http_status }),
25
+ ...(remote_error_code ? { remote_error_code } : {}), ...(diagnostic_reason ? { diagnostic_reason } : {}),
26
+ ...(failure_stage ? { failure_stage } : {}), ...(causes?.length ? { causes } : {})
27
+ };
28
+ }
29
+ export function taskWorkerDiagnostics(error, classification, failureStage) {
30
+ const causes = [];
31
+ const seen = new Set();
32
+ for (let cause = error; cause instanceof Error && causes.length < 10 && !seen.has(cause); cause = cause.cause) {
33
+ seen.add(cause);
34
+ causes.push({ error_type: cause.name, ...("code" in cause && typeof cause.code === "string" ? { system_code: cause.code } : {}) });
35
+ }
36
+ return safeDiagnostics({ error_type: error instanceof Error ? error.name : typeof error,
37
+ http_status: classification.httpStatus, remote_error_code: classification.remoteErrorCode,
38
+ diagnostic_reason: classification.diagnosticReason, failure_stage: failureStage, causes }) ?? {};
39
+ }
40
+ function diagnosticCause(diagnostics) {
41
+ let cause;
42
+ for (const item of [...diagnostics?.causes ?? []].reverse()) {
43
+ const error = new Error("Background task failure.", { cause });
44
+ error.name = item.error_type;
45
+ if (item.system_code)
46
+ Object.assign(error, { code: item.system_code });
47
+ cause = error;
48
+ }
49
+ return cause;
50
+ }
2
51
  export class TaskBackgroundError extends Error {
3
52
  failure;
4
53
  exitCode;
5
- constructor(failure, exitCode = 1) {
6
- super(failure.message);
54
+ diagnostics;
55
+ constructor(failure, exitCode = 1, diagnostics) {
56
+ const safe = safeDiagnostics(diagnostics);
57
+ super(failure.message, { cause: diagnosticCause(safe) });
7
58
  this.failure = failure;
8
59
  this.exitCode = exitCode;
9
60
  this.name = "TaskBackgroundError";
61
+ this.diagnostics = safe;
10
62
  }
11
63
  }
12
64
  export function createTaskBackgroundLauncher(options) {
@@ -53,7 +105,7 @@ export function createTaskBackgroundLauncher(options) {
53
105
  else if (message.type === "accepted")
54
106
  finish(message.task);
55
107
  else if (message.type === "error")
56
- finish(new TaskBackgroundError(message.failure, message.exitCode));
108
+ finish(new TaskBackgroundError(message.failure, message.exitCode, message.diagnostics));
57
109
  });
58
110
  signal.addEventListener("abort", aborted, { once: true });
59
111
  child.send(job, error => { if (error)
@@ -1,6 +1,7 @@
1
1
  import { redactSensitiveText } from "../../platform/redact.js";
2
2
  import { TaskStoreError, taskScope } from "./store.js";
3
3
  import { LocalFileError } from "../../platform/local-json-file.js";
4
+ import { ToolTaskFailedError } from "../tool/tool-api-adapter.js";
4
5
  export class TaskNotFoundError extends Error {
5
6
  constructor(message) { super(message); this.name = "TaskNotFoundError"; }
6
7
  }
@@ -50,11 +51,14 @@ export function createTaskUseCases(dependencies) {
50
51
  if (!telemetry || !record.telemetry)
51
52
  return;
52
53
  let context = record.telemetry.context;
53
- if (name === "request_sent") {
54
+ if (name === "request_sent" && !record.telemetry.request_sent) {
54
55
  const current = telemetry.creationContext();
55
56
  context = { ...context,
56
57
  ...(current.tool_name ? { tool_name: current.tool_name } : {}),
57
58
  ...(current.model_id ? { model_id: current.model_id } : {}) };
59
+ // Fix the creation identity at dispatch even if the fact cannot be saved.
60
+ // Later completion and recovery must not use mutable command annotations.
61
+ record.telemetry.context = Object.freeze(context);
58
62
  }
59
63
  const candidate = { ...context, event_name: name, occurred_at_ms: at,
60
64
  record_seq: name === "request_sent" ? 1 : 2 };
@@ -224,10 +228,13 @@ export function createTaskUseCases(dependencies) {
224
228
  clearInterval(timer);
225
229
  if (record.task.state !== "completed") {
226
230
  const mayBeRunning = dispatched || record.progress.submissionStarted;
227
- record.task.state = mayBeRunning ? "unknown" : "failed";
228
- record.task.note = mayBeRunning
229
- ? text("CLI 未取得完整回执或结果;远端可能仍在执行。查询原任务,不自动重新生成。", "The CLI did not receive a complete receipt or result; the service may still be running. Query this task instead of submitting again.")
230
- : text("CLI 在提交创作前结束;具体错误见原命令。", "The CLI stopped before submitting the creation. See the original command for the error.");
231
+ const confirmedFailure = error instanceof ToolTaskFailedError;
232
+ record.task.state = confirmedFailure || !mayBeRunning ? "failed" : "unknown";
233
+ record.task.note = confirmedFailure
234
+ ? text("服务已明确返回本次 Tool 任务失败;具体错误见原命令。", "The service explicitly reported that this Tool task failed. See the original command for the error.")
235
+ : mayBeRunning
236
+ ? text("CLI 未取得完整回执或结果;远端可能仍在执行。查询原任务,不自动重新生成。", "The CLI did not receive a complete receipt or result; the service may still be running. Query this task instead of submitting again.")
237
+ : text("CLI 在提交创作前结束;具体错误见原命令。", "The CLI stopped before submitting the creation. See the original command for the error.");
231
238
  }
232
239
  const detail = dependencies.failureNote?.(error);
233
240
  if (detail)
@@ -174,8 +174,14 @@ function isJsonRpcError(value) {
174
174
  || !isRecord(value.error)) {
175
175
  return false;
176
176
  }
177
- return typeof value.error.code === "number"
178
- && Number.isInteger(value.error.code)
177
+ const code = value.error.code;
178
+ // Some Tool backends serialize JSON-RPC integer codes as decimal strings.
179
+ // Normalize only at this error boundary; malformed envelopes remain errors.
180
+ const numericCode = typeof code === "string" && /^-?(?:0|[1-9]\d*)$/u.test(code)
181
+ ? Number(code)
182
+ : code;
183
+ return typeof numericCode === "number"
184
+ && Number.isSafeInteger(numericCode)
179
185
  && typeof value.error.message === "string"
180
186
  && value.error.message.trim() !== "";
181
187
  }
@@ -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) {
@@ -1,10 +1,12 @@
1
1
  export class RemoteProtocolError extends Error {
2
2
  remoteCode;
3
3
  remoteBody;
4
- constructor(evidence = {}, cause) {
4
+ diagnosticReason;
5
+ constructor(evidence = {}, cause, diagnosticReason) {
5
6
  super("稿定服务响应与当前 CLI 不兼容。", { cause });
6
7
  this.name = "RemoteProtocolError";
7
8
  this.remoteCode = evidence.remoteCode;
8
9
  this.remoteBody = evidence.remoteBody;
10
+ this.diagnosticReason = diagnosticReason;
9
11
  }
10
12
  }
@@ -7,13 +7,15 @@ export class RemoteRequestError extends Error {
7
7
  transient;
8
8
  remoteCode;
9
9
  remoteBody;
10
- constructor(status, transient = false, evidence = {}, cause) {
10
+ diagnosticReason;
11
+ constructor(status, transient = false, evidence = {}, cause, diagnosticReason) {
11
12
  super(status === undefined ? "无法连接稿定服务。" : `稿定服务请求失败(HTTP ${status})。`, { cause });
12
13
  this.name = "RemoteRequestError";
13
14
  this.status = status;
14
15
  this.transient = transient;
15
16
  this.remoteCode = evidence.remoteCode;
16
17
  this.remoteBody = evidence.remoteBody;
18
+ this.diagnosticReason = diagnosticReason;
17
19
  }
18
20
  }
19
21
  const TRANSIENT_NETWORK_CODES = new Set([
@@ -45,6 +47,7 @@ export function createSignedHttpTransport(options) {
45
47
  const baseUrl = new URL(options.baseUrl);
46
48
  if (!baseUrl.pathname.endsWith("/"))
47
49
  baseUrl.pathname += "/";
50
+ const seenResponses = new WeakSet();
48
51
  async function send(method, request, accept, body, timeout) {
49
52
  request.signal.throwIfAborted();
50
53
  const url = new URL(request.path.replace(/^\//, ""), baseUrl);
@@ -89,6 +92,16 @@ export function createSignedHttpTransport(options) {
89
92
  headers,
90
93
  ...(body === undefined ? {} : { body }),
91
94
  signal
95
+ }).then(response => {
96
+ // Capture ownership facts before waiting for unrelated dispatch diagnostics.
97
+ const received = {
98
+ response,
99
+ bodyUsedAtReceipt: response.bodyUsed,
100
+ bodyLockedAtReceipt: response.body?.locked ?? false,
101
+ reusedResponse: seenResponses.has(response)
102
+ };
103
+ seenResponses.add(response);
104
+ return received;
92
105
  });
93
106
  }
94
107
  finally {
@@ -97,8 +110,8 @@ export function createSignedHttpTransport(options) {
97
110
  }
98
111
  catch { /* Diagnostic only. */ }
99
112
  }
100
- const [response] = await Promise.all([pending, dispatched]);
101
- return response;
113
+ const [received] = await Promise.all([pending, dispatched]);
114
+ return received;
102
115
  }
103
116
  catch (error) {
104
117
  if (isInterruption(error, request.signal))
@@ -106,14 +119,29 @@ export function createSignedHttpTransport(options) {
106
119
  throw new RemoteRequestError(undefined, isTransientNetworkFailure(error), {}, error);
107
120
  }
108
121
  }
109
- async function json(response) {
110
- let body;
122
+ async function readText(received) {
123
+ const { response } = received;
124
+ const summary = {
125
+ bodyUsedAtReceipt: received.bodyUsedAtReceipt,
126
+ bodyLockedAtReceipt: received.bodyLockedAtReceipt,
127
+ bodyUsedBeforeRead: response.bodyUsed,
128
+ bodyLockedBeforeRead: response.body?.locked ?? false,
129
+ reusedResponse: received.reusedResponse
130
+ };
111
131
  try {
112
- body = await response.text();
132
+ return await response.text();
113
133
  }
114
134
  catch (error) {
115
- throw new RemoteRequestError(response.status, false, {}, error);
135
+ const diagnosticReason = summary.bodyUsedBeforeRead ? "RESPONSE_BODY_ALREADY_USED"
136
+ : summary.bodyLockedBeforeRead ? "RESPONSE_BODY_LOCKED" : "RESPONSE_BODY_READ_FAILED";
137
+ throw new RemoteRequestError(response.status, false, {
138
+ remoteBody: JSON.stringify(summary)
139
+ }, error, diagnosticReason);
116
140
  }
141
+ }
142
+ async function json(received) {
143
+ const { response } = received;
144
+ const body = await readText(received);
117
145
  const evidence = remoteErrorEvidence(body);
118
146
  if (!response.ok)
119
147
  throw new RemoteRequestError(response.status, false, evidence);
@@ -121,12 +149,12 @@ export function createSignedHttpTransport(options) {
121
149
  return JSON.parse(body);
122
150
  }
123
151
  catch (error) {
124
- throw new RemoteProtocolError(evidence, error);
152
+ throw new RemoteProtocolError(evidence, error, "RESPONSE_JSON_INVALID");
125
153
  }
126
154
  }
127
155
  async function getJsonResponse(request) {
128
- const response = await send("GET", request, "application/json", undefined, true);
129
- return { body: await json(response), headers: response.headers };
156
+ const received = await send("GET", request, "application/json", undefined, true);
157
+ return { body: await json(received), headers: received.response.headers };
130
158
  }
131
159
  return {
132
160
  async getJson(request) {
@@ -140,15 +168,10 @@ export function createSignedHttpTransport(options) {
140
168
  return json(await send("PUT", request, "application/json", JSON.stringify(request.body), true));
141
169
  },
142
170
  async postStream(request) {
143
- const response = await send("POST", request, request.accept, JSON.stringify(request.body), false);
171
+ const received = await send("POST", request, request.accept, JSON.stringify(request.body), false);
172
+ const { response } = received;
144
173
  if (!response.ok) {
145
- let body;
146
- try {
147
- body = await response.text();
148
- }
149
- catch (error) {
150
- throw new RemoteRequestError(response.status, false, {}, error);
151
- }
174
+ const body = await readText(received);
152
175
  throw new RemoteRequestError(response.status, false, remoteErrorEvidence(body));
153
176
  }
154
177
  if (!response.body)
@@ -33,10 +33,20 @@ export function createTelemetryInvocation(options) {
33
33
  function errorFields(error) {
34
34
  const c = classify(error);
35
35
  return { ...errorEvidence(error),
36
+ ...(c.errorType === undefined ? {} : { error_type: c.errorType }),
36
37
  ...(c.errorCode === undefined ? {} : { error_code: c.errorCode }),
37
38
  ...(c.httpStatus === undefined ? {} : { http_status: c.httpStatus }),
38
39
  ...(c.remoteErrorCode === undefined ? {} : { remote_error_code: c.remoteErrorCode }),
39
- ...(c.remoteErrorBody === undefined ? {} : { remote_error_body: c.remoteErrorBody }) };
40
+ ...(c.remoteErrorBody === undefined ? {} : { remote_error_body: c.remoteErrorBody }),
41
+ ...(c.diagnosticReason === undefined ? {} : { diagnostic_reason: c.diagnosticReason }) };
42
+ }
43
+ function failureStage(error) {
44
+ const causes = [];
45
+ for (let depth = 0; error !== undefined && depth < 10 && !causes.includes(error); depth++) {
46
+ causes.push(error);
47
+ error = error instanceof Error ? error.cause : undefined;
48
+ }
49
+ return failures.find(f => causes.includes(f.error))?.name;
40
50
  }
41
51
  function remember(event) {
42
52
  const safe = cleanDiagnostic(event);
@@ -74,41 +84,34 @@ export function createTelemetryInvocation(options) {
74
84
  return cleanDiagnostic({ ...snapshot, mode: "execute" });
75
85
  },
76
86
  async emit(event) { await publish(remember(event)); },
77
- async stage(name, run) {
87
+ async stage(name, run, details) {
78
88
  const start = options.now();
79
89
  const allowed = detailedStages[definition?.mode ? `${definition.operation}:${definition.mode()}` : definition?.operation ?? ""];
80
90
  try {
81
91
  const result = await run();
82
- if (definition && allowed?.has(name))
92
+ if (definition && (allowed?.has(name) || details))
83
93
  remember({ ...base(), event_name: "stage_finished",
84
- stage: name, outcome: "success", duration_ms: Math.max(0, options.now() - start) });
94
+ stage: name, outcome: "success", duration_ms: Math.max(0, options.now() - start), ...details?.() });
85
95
  return result;
86
96
  }
87
97
  catch (error) {
88
98
  failures.push({ name, error });
89
99
  const event = remember({ ...base(), event_name: "stage_finished", stage: name,
90
100
  outcome: classify(error).outcome,
91
- duration_ms: Math.max(0, options.now() - start), ...errorFields(error) });
101
+ duration_ms: Math.max(0, options.now() - start), ...errorFields(error), ...details?.() });
92
102
  await publish(event);
93
103
  throw error;
94
104
  }
95
105
  },
106
+ failureStage,
96
107
  finish(completion) {
97
108
  if (finished || !definition)
98
109
  return [];
99
110
  finished = true;
100
- const causes = [];
101
- if (completion.outcome !== "success") {
102
- let error = completion.error;
103
- for (let depth = 0; error !== undefined && depth < 10 && !causes.includes(error); depth++) {
104
- causes.push(error);
105
- error = error instanceof Error ? error.cause : undefined;
106
- }
107
- }
108
111
  remember({ ...base(), event_name: "command_finished", outcome: completion.outcome,
109
112
  duration_ms: Math.max(0, options.now() - startedAt),
110
113
  ...(completion.outcome === "success" ? {} : {
111
- failure_stage: failures.find(f => causes.includes(f.error))?.name ?? "unknown"
114
+ failure_stage: classify(completion.error).failureStage ?? failureStage(completion.error) ?? "unknown"
112
115
  }),
113
116
  ...(completion.outcome === "failure" ? errorFields(completion.error) : completion.outcome === "interrupted" && completion.error !== undefined ? errorEvidence(completion.error) : {}),
114
117
  ...(completion.outcome === "failure" ? {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@insmind/cli",
3
- "version": "1.5.7",
3
+ "version": "1.5.9",
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": "02995b31afa98a9a6682fec8dc57cd25b709ca61",
50
+ "pipelineId": "213097",
51
+ "pipelineUrl": "https://git.intra.gaoding.com/gtt/gaoding-cli/-/pipelines/213097"
52
52
  }
53
53
  }