@insmind/cli 1.3.1 → 1.4.0

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.
@@ -1,4 +1,5 @@
1
1
  // Private one-task process; not a public CLI command or a resident service.
2
+ import { reportProcessError } from "../src/telemetry/process-errors.js";
2
3
  import { once } from "node:events";
3
4
  import { Readable } from "node:stream";
4
5
  import { gaodingProduct, insmindProduct } from "../src/product/config.js";
@@ -16,19 +17,30 @@ else {
16
17
  if (process.connected)
17
18
  process.send?.(message, () => undefined);
18
19
  };
20
+ let currentJob;
19
21
  try {
20
22
  const [job] = await once(process, "message");
23
+ currentJob = job;
21
24
  const product = job.product === "insmind" ? insmindProduct : gaodingProduct;
22
25
  const endpoints = { ...product.endpoints };
23
26
  for (const key of Object.keys(endpoints))
24
27
  endpoints[key] = new URL(job.endpoints[key]);
25
28
  const runtime = createProductionRuntime({
29
+ processRole: "agent_worker",
30
+ ...(job.telemetryVersion ? { telemetryVersion: job.telemetryVersion } : {}),
31
+ ...(job.telemetryTrackingUrl ? { telemetryTrackingUrl: new URL(job.telemetryTrackingUrl) } : {}),
32
+ ...(job.telemetryEnvironment ? { telemetryEnvironment: job.telemetryEnvironment } : {}),
26
33
  product, endpoints, homeDirectory: job.homeDirectory, locale: job.locale,
27
34
  io: { input: Readable.from([]), stdout: { write() { } }, stderr: { write() { } } }
28
35
  });
29
36
  await runAgentWorker({ runtime, job, signal: controller.signal, send });
30
37
  }
31
- catch {
38
+ catch (error) {
39
+ await reportProcessError(error, { operation: "bootstrap", processRole: "agent_worker",
40
+ stateDirectory: currentJob?.product === "insmind" ? ".insmind" : ".gd",
41
+ ...(currentJob?.telemetryTrackingUrl ? { trackingUrl: new URL(currentJob.telemetryTrackingUrl) } : {}),
42
+ ...(currentJob?.telemetryEnvironment ? { environment: currentJob.telemetryEnvironment } : {}),
43
+ ...(currentJob?.homeDirectory ? { homeDirectory: currentJob.homeDirectory } : {}) });
32
44
  send({ type: "error", failure: { code: "TASK_WORKER_UNAVAILABLE", message: "The background task could not start. Check task list/get before submitting again." }, exitCode: 1 });
33
45
  process.exitCode = 1;
34
46
  }
@@ -4,6 +4,7 @@ import { localeOption } from "../src/product/locale.js";
4
4
  const controller = new AbortController();
5
5
  const interrupt = () => controller.abort(new Error("SIGINT"));
6
6
  process.once("SIGINT", interrupt);
7
+ process.once("SIGTERM", interrupt);
7
8
  let runtime;
8
9
  let mapCliError;
9
10
  let redact;
@@ -34,6 +35,11 @@ try {
34
35
  });
35
36
  }
36
37
  catch (error) {
38
+ try {
39
+ const { reportProcessError } = await import("../src/telemetry/process-errors.js");
40
+ await reportProcessError(error, { operation: "bootstrap", stateDirectory: ".insmind" });
41
+ }
42
+ catch { /* Retain startup error output even if diagnostic modules cannot load. */ }
37
43
  if (mapCliError === undefined || redact === undefined) {
38
44
  process.stderr.write("INTERNAL_ERROR: CLI failed to start.\n");
39
45
  process.exitCode = 1;
@@ -57,4 +63,5 @@ catch (error) {
57
63
  }
58
64
  finally {
59
65
  process.removeListener("SIGINT", interrupt);
66
+ process.removeListener("SIGTERM", interrupt);
60
67
  }
@@ -1,3 +1,5 @@
1
+ import { reportProcessError } from "../src/telemetry/process-errors.js";
2
+ import { cleanText } from "../src/telemetry/sanitize.js";
1
3
  import { fileURLToPath } from "node:url";
2
4
  import { dirname, resolve } from "node:path";
3
5
  import { loadBundledSkills } from "../src/features/skill/bundled-skills.js";
@@ -19,12 +21,16 @@ export async function runPostinstall(options = {}) {
19
21
  const env = options.env ?? process.env;
20
22
  if (!isSupportedGlobalLifecycle(env))
21
23
  return;
24
+ const reportError = options.reportError ?? (options.env ? async () => undefined : (error) => reportProcessError(error, {
25
+ operation: "postinstall", processRole: "postinstall", stateDirectory: env.npm_package_name === "@insmind/cli" ? ".insmind" : ".gd"
26
+ }));
22
27
  const writeError = options.writeError ?? ((text) => process.stderr.write(text));
23
28
  let skills;
24
29
  try {
25
30
  skills = (options.loadSkills ?? loadBundledSkills)(options.startFile ?? fileURLToPath(import.meta.url));
26
31
  }
27
32
  catch (error) {
33
+ await reportError(error);
28
34
  if (env.GD_CLI_INSTALL_OWNER === "workbuddy") {
29
35
  throw new Error("无法确认当前安装的 package。");
30
36
  }
@@ -51,18 +57,21 @@ export async function runPostinstall(options = {}) {
51
57
  });
52
58
  }
53
59
  catch (error) {
60
+ await reportError(error);
54
61
  writeError(`警告: ${oneLineMessage(error)}\n`);
55
62
  }
56
63
  }
57
64
  function oneLineMessage(error) {
58
65
  const value = error instanceof Error ? error.message : String(error);
59
- return value.replace(/\s+/gu, " ").trim() || "Agent Skill 自动安装失败";
66
+ return cleanText(value).replace(/\s+/gu, " ").trim() || "Agent Skill 自动安装失败";
60
67
  }
61
68
  const entryPath = process.argv[1];
62
69
  const isDirectEntry = entryPath !== undefined
63
70
  && resolve(entryPath) === fileURLToPath(import.meta.url);
64
71
  if (isDirectEntry || process.env.npm_lifecycle_event === "postinstall") {
65
- void runPostinstall().catch((error) => {
72
+ void runPostinstall().catch(async (error) => {
73
+ await reportProcessError(error, { operation: "postinstall", processRole: "postinstall",
74
+ stateDirectory: process.env.npm_package_name === "@insmind/cli" ? ".insmind" : ".gd" });
66
75
  process.stderr.write(`${oneLineMessage(error)}\n`);
67
76
  process.exitCode = 1;
68
77
  });
@@ -14,6 +14,7 @@ import { registerCreditsCommand } from "../cli/credits-command.js";
14
14
  import { redact } from "../platform/redact.js";
15
15
  export { assertAllLeafCommandsBound, bindAction } from "../cli/action-binding.js";
16
16
  export function createCli(runtime, options) {
17
+ runtime.telemetry.useSignal(options.signal);
17
18
  const program = new Command()
18
19
  .name(runtime.product.commandName)
19
20
  .description(runtime.product.description)
@@ -69,6 +70,8 @@ export async function executeCli(options) {
69
70
  }
70
71
  return 0;
71
72
  }
73
+ if (!options.telemetry.selected)
74
+ options.telemetry.select({ operation: "unknown" });
72
75
  if (options.telemetry.selected && error instanceof CommanderError) {
73
76
  try {
74
77
  await options.telemetry.stage("input", () => { throw error; });
@@ -78,17 +81,22 @@ export async function executeCli(options) {
78
81
  }
79
82
  }
80
83
  const outcome = redact(mapCliError(error, {
81
- aborted: options.signal.aborted,
84
+ aborted: options.signal.aborted && (error === options.signal.reason || error instanceof Error && error.name === "AbortError"),
82
85
  ...(options.product ? { product: options.product } : {})
83
86
  }));
84
- const telemetryError = classifyTelemetryError(error);
87
+ const telemetryError = classifyTelemetryError(error, { aborted: options.signal.aborted && (error === options.signal.reason || error instanceof Error && error.name === "AbortError"), ...(options.product ? { product: options.product } : {}) });
85
88
  const traceId = options.telemetry.selected
86
89
  ? options.telemetry.traceId
87
90
  : undefined;
88
- options.presenter.error(outcome, {
89
- json: options.argv.includes("--json"),
90
- ...(traceId ? { traceId } : {})
91
- });
91
+ try {
92
+ options.presenter.error(outcome, {
93
+ json: options.argv.includes("--json"),
94
+ ...(traceId ? { traceId } : {})
95
+ });
96
+ }
97
+ catch (presenterError) {
98
+ await options.telemetry.stage("output", () => { throw presenterError; }).catch(() => undefined);
99
+ }
92
100
  await sendFinished(options, outcome.kind === "interrupted"
93
101
  ? { outcome: "interrupted", error }
94
102
  : {
@@ -120,5 +128,5 @@ async function checkUpdateNotification(updateNotification, signal) {
120
128
  async function sendFinished(options, completion) {
121
129
  const events = options.telemetry.finish(completion);
122
130
  if (events.length > 0)
123
- await options.telemetrySink.send(events);
131
+ await options.telemetrySink.send(events).catch(() => undefined);
124
132
  }
@@ -79,21 +79,22 @@ export function createProductionRuntime(options = {}) {
79
79
  "X-Legal-Region": locale.legalRegion
80
80
  } : undefined;
81
81
  const now = options.now ?? (() => new Date());
82
+ const telemetryEnvironment = options.telemetryEnvironment ?? (env.CLI_TELEMETRY_ENV === "test" ? "test" : "production");
83
+ const telemetrySink = options.telemetrySink ?? createSlsTelemetrySink({
84
+ fetch, trackingUrl: options.telemetryTrackingUrl ?? product.telemetryUrl,
85
+ background: options.telemetryBackground ?? true,
86
+ directory: join(options.homeDirectory ?? homedir(), product.stateDirectory, "telemetry"),
87
+ now: () => now().getTime()
88
+ });
82
89
  const telemetry = createTelemetryInvocation({
83
- cliVersion: primarySkill.version,
90
+ cliVersion: primarySkill.version, cliName: product.commandName, env: telemetryEnvironment,
91
+ processRole: options.processRole ?? "cli",
84
92
  now: () => now().getTime(),
85
93
  traceIdFactory: () => randomBytes(16).toString("hex"),
86
94
  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
95
+ runtime: { os: process.platform, arch: process.arch, nodeMajor: Number.parseInt(process.versions.node, 10) },
96
+ classifyError: error => classifyTelemetryError(error, { product }),
97
+ onEvent: async (event) => { await telemetrySink.enqueue?.([event]); }
97
98
  });
98
99
  const rawIo = options.io ?? {
99
100
  input: process.stdin,
@@ -183,7 +184,9 @@ export function createProductionRuntime(options = {}) {
183
184
  await delay(milliseconds, undefined, { signal });
184
185
  }
185
186
  });
186
- const storage = options.objectStorage ?? createObjectStorageUploader({ fetch, now });
187
+ const storage = options.objectStorage ?? createObjectStorageUploader({ fetch, now,
188
+ reportError: error => telemetry.stage("upload.attempt", () => { throw error; }).catch(() => undefined)
189
+ });
187
190
  const credits = createCreditsUseCases({
188
191
  transport: creditsTransport,
189
192
  billingUnit: product.billingUnit
@@ -276,6 +279,14 @@ export function createProductionRuntime(options = {}) {
276
279
  }) };
277
280
  };
278
281
  const tasks = createTaskUseCases({
282
+ telemetry,
283
+ ...(options.telemetryVersion ? { creationVersion: options.telemetryVersion } : {}),
284
+ validateResult: result => {
285
+ if ("message" in result)
286
+ validators.agentSendOutput(result);
287
+ else
288
+ validators.toolCallOutput(result);
289
+ },
279
290
  store: createTaskStore({
280
291
  ...(options.homeDirectory ? { homeDirectory: options.homeDirectory } : {}),
281
292
  stateDirectory: product.stateDirectory,
@@ -318,8 +329,10 @@ export function createProductionRuntime(options = {}) {
318
329
  });
319
330
  if (response.state === "pending")
320
331
  return { state: "running", note: text("原 Tool 查询尚未返回最终结果。", "The original Tool is still processing.") };
321
- if (response.state === "failed")
332
+ if (response.state === "failed") {
333
+ await telemetry.stage("task.recover", () => { throw response.error; }).catch(() => undefined);
322
334
  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.") };
335
+ }
323
336
  return { state: "completed", result: await authorizeTaskResult(toolOutputWithBillingUnit({
324
337
  content: response.content, usage: progress.toolUsage
325
338
  }, product.billingUnit), state, signal) };
@@ -393,6 +406,7 @@ export function createProductionRuntime(options = {}) {
393
406
  }
394
407
  };
395
408
  const updateNotification = createUpdateNotificationService({
409
+ reportError: error => telemetry.stage("update_check", () => { throw error; }).catch(() => undefined),
396
410
  currentVersion: primarySkill.version,
397
411
  fetch,
398
412
  now,
@@ -423,8 +437,13 @@ export function createProductionRuntime(options = {}) {
423
437
  startAgentTask: (input, signal) => (options.agentBackground ?? createAgentBackgroundLauncher({
424
438
  workerPath: join(packageRoot, "dist", "bin", "agent-worker.js"), env
425
439
  })).submit({ ...input, product: product.id, homeDirectory: options.homeDirectory ?? homedir(),
440
+ telemetryEnvironment, telemetryVersion: primarySkill.version,
441
+ telemetryTrackingUrl: String(options.telemetryTrackingUrl ?? product.telemetryUrl),
426
442
  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}`))),
443
+ }, signal, task => {
444
+ telemetry.annotate({ cli_task_id: task.taskId, execution_mode: "async", result_state: task.state });
445
+ 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}`));
446
+ }),
428
447
  editor,
429
448
  dam,
430
449
  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,8 +174,8 @@ 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
@@ -184,7 +184,7 @@ export function classifyTelemetryError(error) {
184
184
  return {
185
185
  outcome: outcome.kind === "interrupted" ? "interrupted" : "failure",
186
186
  ...(outcome.kind === "failure" ? { errorCode: outcome.failure.code } : {}),
187
- ...(error instanceof RemoteRequestError && error.status !== undefined
187
+ ...((error instanceof RemoteRequestError || error instanceof SsoRequestError) && error.status !== undefined
188
188
  ? { httpStatus: error.status }
189
189
  : {}),
190
190
  ...(remoteError?.remoteCode === undefined
@@ -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,
@@ -2,8 +2,8 @@ import { normalizeScope } from "./state.js";
2
2
  import { signBindOrganization } from "../../platform/signature.js";
3
3
  export class SsoRequestError extends Error {
4
4
  status;
5
- constructor(status) {
6
- super(status === undefined ? "无法连接稿定登录服务。" : `稿定登录服务请求失败(HTTP ${status})。`);
5
+ constructor(status, cause) {
6
+ super(status === undefined ? "无法连接稿定登录服务。" : `稿定登录服务请求失败(HTTP ${status})。`, { cause });
7
7
  this.name = "SsoRequestError";
8
8
  this.status = status;
9
9
  }
@@ -36,10 +36,10 @@ export function createSsoService(options) {
36
36
  ])
37
37
  });
38
38
  }
39
- catch {
39
+ catch (cause) {
40
40
  if (signal.aborted)
41
41
  throw signal.reason;
42
- throw new SsoRequestError();
42
+ throw new SsoRequestError(undefined, cause);
43
43
  }
44
44
  }
45
45
  return {
@@ -73,7 +73,7 @@ export function createAuthUseCases(dependencies) {
73
73
  await input.interaction.showAuthorization(authorizationUrl);
74
74
  if (!input.noBrowser) {
75
75
  try {
76
- await input.interaction.openBrowser(authorizationUrl);
76
+ await dependencies.telemetry.stage("browser", () => input.interaction.openBrowser(authorizationUrl));
77
77
  }
78
78
  catch {
79
79
  input.interaction.warn(insmind
@@ -3,8 +3,8 @@ import { access, mkdir, open, rename, rm } from "node:fs/promises";
3
3
  import { extname, resolve } from "node:path";
4
4
  import { parseSafeRemoteAssetUrl } from "../../platform/url-safety.js";
5
5
  export class DamDownloadError extends Error {
6
- constructor() {
7
- super("素材下载失败。");
6
+ constructor(cause) {
7
+ super("素材下载失败。", { cause });
8
8
  this.name = "DamDownloadError";
9
9
  }
10
10
  }
@@ -42,8 +42,8 @@ function safeDownloadUrl(value) {
42
42
  throw new Error("HTTPS required");
43
43
  return url;
44
44
  }
45
- catch {
46
- throw new DamDownloadError();
45
+ catch (cause) {
46
+ throw new DamDownloadError(cause);
47
47
  }
48
48
  }
49
49
  function decodedFilename(value) {
@@ -98,10 +98,10 @@ async function fetchDownload(initial, fetch, signal) {
98
98
  try {
99
99
  response = await fetch(url, { method: "GET", redirect: "manual", signal });
100
100
  }
101
- catch {
101
+ catch (cause) {
102
102
  if (signal.aborted)
103
103
  throw signal.reason;
104
- throw new DamDownloadError();
104
+ throw new DamDownloadError(cause);
105
105
  }
106
106
  signal.throwIfAborted();
107
107
  if (!redirectStatuses.has(response.status)) {
@@ -3,8 +3,8 @@ import { createReadStream } from "node:fs";
3
3
  import { stat } from "node:fs/promises";
4
4
  import OSS from "ali-oss";
5
5
  export class ObjectStorageUploadError extends Error {
6
- constructor() {
7
- super("素材上传失败。");
6
+ constructor(cause) {
7
+ super("素材上传失败。", { cause });
8
8
  this.name = "ObjectStorageUploadError";
9
9
  }
10
10
  }
@@ -90,11 +90,12 @@ async function attemptOss(input, dependencies) {
90
90
  catch (error) {
91
91
  if (input.signal.aborted)
92
92
  throw input.signal.reason;
93
+ await dependencies.reportError?.(error).catch(() => undefined);
93
94
  if (!input.authorizationV4 && isUnsupportedAuthorization(error)) {
94
95
  return "unsupported-authorization";
95
96
  }
96
97
  if (!isTransient(error))
97
- throw new ObjectStorageUploadError();
98
+ throw new ObjectStorageUploadError(error);
98
99
  if (attempt === 1)
99
100
  return "transient-exhausted";
100
101
  await dependencies.sleep(300, input.signal);
@@ -156,12 +157,13 @@ async function uploadObs(input, dependencies) {
156
157
  throw input.signal.reason;
157
158
  if (error instanceof ObjectStorageUploadError)
158
159
  throw error;
159
- throw new ObjectStorageUploadError();
160
+ throw new ObjectStorageUploadError(error);
160
161
  }
161
162
  }
162
163
  export function createObjectStorageUploader(options = {}) {
163
164
  const dependencies = {
164
165
  putOss: options.putOss ?? defaultPutOss,
166
+ ...(options.reportError ? { reportError: options.reportError } : {}),
165
167
  fetch: options.fetch ?? globalThis.fetch,
166
168
  sleep: options.sleep ?? sleepWithSignal,
167
169
  now: options.now ?? (() => new Date())
@@ -1,3 +1,4 @@
1
+ import { reportProcessError } from "../../telemetry/process-errors.js";
1
2
  import { spawn as nodeSpawn } from "node:child_process";
2
3
  import { resolve } from "node:path";
3
4
  import { fileURLToPath } from "node:url";
@@ -14,9 +15,9 @@ export async function runEditorBridgeProcess(targetOrigin, options = {}) {
14
15
  ? {}
15
16
  : { stateDirectory: options.stateDirectory })
16
17
  });
17
- const bridge = await (options.startBridge ?? startEditorBridge)({ targetOrigin });
18
+ const bridge = await (options.startBridge ?? startEditorBridge)({ targetOrigin, ...(options.reportError ? { reportError: options.reportError } : {}) });
18
19
  const shutdown = () => {
19
- void bridge.close().catch(() => undefined);
20
+ void bridge.close().catch(error => options.reportError?.(error));
20
21
  };
21
22
  let signalListenersInstalled = false;
22
23
  const removeSignalListeners = () => {
@@ -215,14 +216,19 @@ if (process.argv[1] && resolve(process.argv[1]) === resolve(ownPath)) {
215
216
  const targetOrigin = process.argv[2];
216
217
  const homeDirectory = process.argv[3] || undefined;
217
218
  const stateDirectory = process.argv[4];
219
+ const reportError = (error) => reportProcessError(error, { operation: "editor.bridge", processRole: "editor_bridge",
220
+ ...(stateDirectory ? { stateDirectory } : {}), ...(homeDirectory ? { homeDirectory } : {}) });
218
221
  if (!targetOrigin) {
222
+ void reportError(new Error("Editor Bridge target missing."));
219
223
  process.exitCode = 1;
220
224
  }
221
225
  else {
222
226
  void runEditorBridgeProcess(targetOrigin, {
227
+ reportError,
223
228
  ...(homeDirectory === undefined ? {} : { homeDirectory }),
224
229
  ...(stateDirectory === undefined ? {} : { stateDirectory })
225
- }).catch(() => {
230
+ }).catch(async (error) => {
231
+ await reportError(error);
226
232
  process.exitCode = 1;
227
233
  });
228
234
  }
@@ -20,7 +20,8 @@ export async function startEditorBridge(options) {
20
20
  resolveClosed = resolve;
21
21
  });
22
22
  const http = createServer((request, response) => {
23
- void handleRequest(request, response).catch(() => {
23
+ void handleRequest(request, response).catch(error => {
24
+ void options.reportError?.(error).catch(() => undefined);
24
25
  sendError(response, 500, "SERVER_ERROR", "Editor Bridge request failed.");
25
26
  });
26
27
  });
@@ -175,7 +176,8 @@ export async function startEditorBridge(options) {
175
176
  sendError(current.response, 503, "EDITOR_DISCONNECTED", "The Editor page disconnected.");
176
177
  });
177
178
  }
178
- catch {
179
+ catch (error) {
180
+ void options.reportError?.(error).catch(() => undefined);
179
181
  const current = takePending(requestId);
180
182
  if (current) {
181
183
  sendError(current.response, 503, "EDITOR_DISCONNECTED", "The Editor page disconnected.");
@@ -1,3 +1,4 @@
1
+ import { withFileLock } from "../../platform/file-lock.js";
1
2
  import { createHash } from "node:crypto";
2
3
  import { readdir, lstat } from "node:fs/promises";
3
4
  import { homedir } from "node:os";
@@ -56,8 +57,38 @@ export function createTaskStore(options) {
56
57
  }
57
58
  },
58
59
  async write(scope, record) {
59
- options.validate(record.task);
60
- await file(scope, record.task.taskId).writeTextAtomically(`${JSON.stringify(record)}\n`);
60
+ file(scope, record.task.taskId);
61
+ await withFileLock(join(root, scope, `${record.task.taskId}.lock`), async () => {
62
+ const previous = await store.read(scope, record.task.taskId);
63
+ if (previous) {
64
+ record.progress = { ...previous.progress, ...record.progress };
65
+ for (const key of ["accepted", "submissionStarted", "detached"]) {
66
+ if (previous.progress[key])
67
+ record.progress[key] = true;
68
+ }
69
+ if (previous.task.state === "completed" || (previous.task.state === "failed" && record.task.state !== "completed"))
70
+ record.task = previous.task;
71
+ if (previous.telemetry)
72
+ record.telemetry = {
73
+ ...record.telemetry, ...previous.telemetry,
74
+ context: previous.telemetry.request_sent ? previous.telemetry.context : record.telemetry?.context ?? previous.telemetry.context
75
+ };
76
+ }
77
+ options.validate(record.task);
78
+ await file(scope, record.task.taskId).writeTextAtomically(`${JSON.stringify(record)}\n`);
79
+ });
80
+ },
81
+ async update(scope, id, change) {
82
+ file(scope, id);
83
+ return withFileLock(join(root, scope, `${id}.lock`), async () => {
84
+ const record = await store.read(scope, id);
85
+ if (!record)
86
+ throw new LocalFileError(undefined);
87
+ change(record);
88
+ options.validate(record.task);
89
+ await file(scope, id).writeTextAtomically(`${JSON.stringify(record)}\n`);
90
+ return record;
91
+ });
61
92
  },
62
93
  async list(scope) {
63
94
  let names;
@@ -90,6 +121,7 @@ export function createTaskStore(options) {
90
121
  }
91
122
  }
92
123
  return {
124
+ update: (scope, id, change) => access(() => store.update(scope, id, change)),
93
125
  read: (scope, id) => access(() => store.read(scope, id)),
94
126
  write: (scope, record) => access(() => store.write(scope, record)),
95
127
  list: scope => access(() => store.list(scope))