@alan-ai-hq/agent-manager-darwin-arm64 0.1.176 → 0.1.178

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.
package/alan-agent.cjs CHANGED
@@ -22412,6 +22412,7 @@ var init_problem = __esm({
22412
22412
  "cli.process.not_found",
22413
22413
  "cli.process.nonzero_exit",
22414
22414
  "cli.process.signal",
22415
+ "cli.process.out_of_memory",
22415
22416
  "cli.process.timeout",
22416
22417
  "cli.tool.failed",
22417
22418
  "cli.unknown"
@@ -22586,6 +22587,21 @@ var init_cli_usage = __esm({
22586
22587
  }
22587
22588
  });
22588
22589
 
22590
+ // ../shared/src/schema/conversations/agent-runs-contracts.ts
22591
+ var agentRunOutcomeEnum;
22592
+ var init_agent_runs_contracts = __esm({
22593
+ "../shared/src/schema/conversations/agent-runs-contracts.ts"() {
22594
+ "use strict";
22595
+ agentRunOutcomeEnum = [
22596
+ "completed",
22597
+ "aborted",
22598
+ "interrupted",
22599
+ "rejected",
22600
+ "failed"
22601
+ ];
22602
+ }
22603
+ });
22604
+
22589
22605
  // ../shared/src/runtime-v2/run-log.ts
22590
22606
  function isRunLifecycleKind(sessionUpdate2) {
22591
22607
  return RUN_LIFECYCLE_KINDS.has(sessionUpdate2);
@@ -22593,18 +22609,20 @@ function isRunLifecycleKind(sessionUpdate2) {
22593
22609
  function alignedLength(bytes) {
22594
22610
  return bytes.lastIndexOf(RUN_LOG_RECORD_SEPARATOR) + 1;
22595
22611
  }
22596
- var RUN_LOG_PROTOCOL, RUN_LOG_PROTOCOL_HEADER, RUN_LOG_RECORD_SEPARATOR, RUN_STEERS_MAX, runAcceptedUpdateSchema, runStartedUpdateSchema, runCodexRateLimitsUpdateSchema, runWorkspaceRelocatedUpdateSchema, runOutcomeSchema, runRejectionCodeSchema, runEndedUpdateSchema, runLifecycleUpdateSchema, RUN_LIFECYCLE_KINDS, runLogRecordSchema;
22612
+ var RUN_LOG_PROTOCOL, RUN_LOG_PROTOCOL_HEADER, RUN_LOG_RECORD_SEPARATOR, RUN_STEERS_MAX, HOLDER_LOST_RUN_MESSAGE, runAcceptedUpdateSchema, runStartedUpdateSchema, runCodexRateLimitsUpdateSchema, runWorkspaceRelocatedUpdateSchema, runOutcomeSchema, runRejectionCodeSchema, runEndedUpdateSchema, runLifecycleUpdateSchema, RUN_LIFECYCLE_KINDS, runLogRecordSchema;
22597
22613
  var init_run_log = __esm({
22598
22614
  "../shared/src/runtime-v2/run-log.ts"() {
22599
22615
  "use strict";
22600
22616
  init_zod();
22601
22617
  init_problem();
22602
22618
  init_cli_usage();
22619
+ init_agent_runs_contracts();
22603
22620
  init_ids();
22604
22621
  RUN_LOG_PROTOCOL = 2;
22605
22622
  RUN_LOG_PROTOCOL_HEADER = "x-alan-log-protocol";
22606
22623
  RUN_LOG_RECORD_SEPARATOR = 10;
22607
22624
  RUN_STEERS_MAX = 100;
22625
+ HOLDER_LOST_RUN_MESSAGE = "The computer stopped mid-turn";
22608
22626
  runAcceptedUpdateSchema = external_exports.object({
22609
22627
  sessionUpdate: external_exports.literal("_alan/run.accepted"),
22610
22628
  machineId: machineIdSchema,
@@ -22632,13 +22650,7 @@ var init_run_log = __esm({
22632
22650
  previousPath: external_exports.string().min(1).max(4096),
22633
22651
  canonicalPath: external_exports.string().min(1).max(4096)
22634
22652
  });
22635
- runOutcomeSchema = external_exports.enum([
22636
- "completed",
22637
- "failed",
22638
- "aborted",
22639
- "interrupted",
22640
- "rejected"
22641
- ]);
22653
+ runOutcomeSchema = external_exports.enum(agentRunOutcomeEnum);
22642
22654
  runRejectionCodeSchema = external_exports.enum([
22643
22655
  "capacity",
22644
22656
  "maintenance",
@@ -22728,6 +22740,7 @@ var init_holder_protocol = __esm({
22728
22740
  startedAtMs: external_exports.number().int().nonnegative(),
22729
22741
  /** Wall clock, epoch ms; null while a turn runs. */
22730
22742
  idleSinceMs: external_exports.number().int().nonnegative().nullable(),
22743
+ hasBackgroundWork: external_exports.boolean().default(false),
22731
22744
  holderRssBytes: external_exports.number().int().nonnegative(),
22732
22745
  /** The live provider CLI; null when none is running. */
22733
22746
  cliPid: external_exports.number().int().positive().nullable(),
@@ -24141,7 +24154,7 @@ var init_kinds = __esm({
24141
24154
  recoveryClass: "needs_env"
24142
24155
  },
24143
24156
  out_of_memory: {
24144
- message: "Out of memory on the runtime. Close other work or use a larger machine, then retry.",
24157
+ message: "The agent ran out of memory on this machine and was stopped. Free memory or use a larger machine, then send Continue.",
24145
24158
  recoveryClass: "needs_env"
24146
24159
  },
24147
24160
  provider_error: {
@@ -24658,7 +24671,7 @@ var init_problem2 = __esm({
24658
24671
  history_rejected: "cli.resume_failed",
24659
24672
  permission_denied: "cli.tool.failed",
24660
24673
  interpreter_missing: "cli.process.not_found",
24661
- out_of_memory: "cli.process.nonzero_exit",
24674
+ out_of_memory: "cli.process.out_of_memory",
24662
24675
  provider_error: "cli.unknown",
24663
24676
  subagent_parent_exited: "cli.process.nonzero_exit",
24664
24677
  tool_call_invalid: "cli.tool.failed",
@@ -25247,10 +25260,33 @@ var init_line_splitter = __esm({
25247
25260
  }
25248
25261
  });
25249
25262
 
25263
+ // ../agent-core/src/process/oom-kills.ts
25264
+ function parseOomKills(vmstat) {
25265
+ const match = /^oom_kill\s+(\d+)$/m.exec(vmstat);
25266
+ return match?.[1] === void 0 ? null : Number(match[1]);
25267
+ }
25268
+ function systemOomKillCounter(platform3 = process.platform) {
25269
+ if (platform3 !== "linux") return () => Promise.resolve(null);
25270
+ return async () => {
25271
+ try {
25272
+ return parseOomKills(await (0, import_promises20.readFile)("/proc/vmstat", "utf8"));
25273
+ } catch {
25274
+ return null;
25275
+ }
25276
+ };
25277
+ }
25278
+ var import_promises20;
25279
+ var init_oom_kills = __esm({
25280
+ "../agent-core/src/process/oom-kills.ts"() {
25281
+ "use strict";
25282
+ import_promises20 = require("fs/promises");
25283
+ }
25284
+ });
25285
+
25250
25286
  // ../agent-core/src/process/process-identity.ts
25251
25287
  async function linuxStartTicks(pid) {
25252
25288
  try {
25253
- const stat25 = await (0, import_promises20.readFile)(`/proc/${pid}/stat`, "utf8");
25289
+ const stat25 = await (0, import_promises21.readFile)(`/proc/${pid}/stat`, "utf8");
25254
25290
  const fields = stat25.slice(stat25.lastIndexOf(")") + 2).split(" ");
25255
25291
  return fields[19];
25256
25292
  } catch {
@@ -25274,12 +25310,12 @@ async function captureProcessIdentity(pid, platform3 = process.platform) {
25274
25310
  const startedAt = await readProcessStartTime(pid, platform3);
25275
25311
  return startedAt === void 0 ? void 0 : { pid, startedAt };
25276
25312
  }
25277
- var import_node_child_process10, import_promises20;
25313
+ var import_node_child_process10, import_promises21;
25278
25314
  var init_process_identity = __esm({
25279
25315
  "../agent-core/src/process/process-identity.ts"() {
25280
25316
  "use strict";
25281
25317
  import_node_child_process10 = require("child_process");
25282
- import_promises20 = require("fs/promises");
25318
+ import_promises21 = require("fs/promises");
25283
25319
  }
25284
25320
  });
25285
25321
 
@@ -25580,7 +25616,7 @@ async function waitForWindowsJob(child, command, options = {}) {
25580
25616
  try {
25581
25617
  while (systemClock2.monotonic() < deadline) {
25582
25618
  options.signal?.throwIfAborted();
25583
- const providerPid = await (0, import_promises21.readFile)(status.path, "utf8").catch(() => void 0);
25619
+ const providerPid = await (0, import_promises22.readFile)(status.path, "utf8").catch(() => void 0);
25584
25620
  if (providerPid !== void 0) {
25585
25621
  requireStartedProvider(providerPid, command);
25586
25622
  return;
@@ -25603,17 +25639,17 @@ async function waitForWindowsJob(child, command, options = {}) {
25603
25639
  throw new CoreFault("spawn_failed", `Could not start ${command} (Windows helper timed out)`);
25604
25640
  } finally {
25605
25641
  statuses.delete(child);
25606
- await (0, import_promises21.rm)(status.directory, { recursive: true, force: true });
25642
+ await (0, import_promises22.rm)(status.directory, { recursive: true, force: true });
25607
25643
  }
25608
25644
  }
25609
- var import_node_child_process13, import_node_crypto13, import_node_fs12, import_promises21, import_node_os2, import_node_path20, statuses, START_TIMEOUT_MS;
25645
+ var import_node_child_process13, import_node_crypto13, import_node_fs12, import_promises22, import_node_os2, import_node_path20, statuses, START_TIMEOUT_MS;
25610
25646
  var init_windows_helper = __esm({
25611
25647
  "../agent-core/src/process/windows-helper.ts"() {
25612
25648
  "use strict";
25613
25649
  import_node_child_process13 = require("child_process");
25614
25650
  import_node_crypto13 = require("crypto");
25615
25651
  import_node_fs12 = require("fs");
25616
- import_promises21 = require("fs/promises");
25652
+ import_promises22 = require("fs/promises");
25617
25653
  import_node_os2 = require("os");
25618
25654
  import_node_path20 = require("path");
25619
25655
  init_kernel();
@@ -25772,6 +25808,7 @@ var init_process = __esm({
25772
25808
  init_flag_probe();
25773
25809
  init_flag_probe_store();
25774
25810
  init_line_splitter();
25811
+ init_oom_kills();
25775
25812
  init_process_identity();
25776
25813
  init_process_list();
25777
25814
  init_process_tree();
@@ -29353,15 +29390,24 @@ var init_protocol = __esm({
29353
29390
  });
29354
29391
 
29355
29392
  // ../agent-core/src/session/process-host.ts
29393
+ function outOfMemoryOutcome() {
29394
+ return { status: "failed", error: specForErrorKind("out_of_memory") };
29395
+ }
29356
29396
  function hostProcess(child, tree, options, handlers) {
29357
29397
  const writer = createNdjsonWriter(child.stdin);
29398
+ const oomKills = options.oomKills ?? systemOomKillCounter();
29399
+ const oomKillsAtStart = oomKills();
29358
29400
  const flags = {
29401
+ terminated: false,
29359
29402
  closing: false,
29360
29403
  outputClosedEarly: false,
29361
29404
  lastScan: Number.NEGATIVE_INFINITY,
29362
29405
  lastOutputAt: void 0
29363
29406
  };
29364
- const terminate2 = () => tree.terminate({ graceMs: options.terminateGraceMs });
29407
+ const terminate2 = () => {
29408
+ flags.terminated = true;
29409
+ return tree.terminate({ graceMs: options.terminateGraceMs });
29410
+ };
29365
29411
  const heard = () => {
29366
29412
  flags.lastOutputAt = options.clock.monotonic();
29367
29413
  };
@@ -29378,8 +29424,16 @@ function hostProcess(child, tree, options, handlers) {
29378
29424
  child.stderr.on("data", (chunk) => stderr.push(chunk));
29379
29425
  child.stderr.once("end", () => stderr.flush());
29380
29426
  const processExit = new Promise((resolve16) => {
29381
- child.once("exit", (code, signal) => resolve16({ code, signal }));
29427
+ child.once(
29428
+ "exit",
29429
+ (code, signal) => resolve16({ code, signal, signalledByHost: flags.terminated })
29430
+ );
29382
29431
  });
29432
+ const killedForMemory = async ({ signal, signalledByHost }) => {
29433
+ if (signal !== "SIGKILL" || signalledByHost) return false;
29434
+ const [before, after] = await Promise.all([oomKillsAtStart, oomKills()]);
29435
+ return before !== null && after !== null && after > before;
29436
+ };
29383
29437
  const outputEnded = new Promise((resolve16) => {
29384
29438
  child.stdout.once("close", () => resolve16());
29385
29439
  });
@@ -29398,12 +29452,14 @@ function hostProcess(child, tree, options, handlers) {
29398
29452
  log.warn(`${name}.stdout_held_after_exit`, { pid: child.pid });
29399
29453
  await terminate2();
29400
29454
  }
29401
- const exit = await processExit;
29455
+ const raw = await processExit;
29456
+ const oomKilled = await killedForMemory(raw);
29402
29457
  await terminate2();
29403
29458
  child.stdout.destroy();
29404
29459
  child.stderr.destroy();
29405
29460
  child.stdin.destroy();
29406
- handlers.onExit(exit, flags.outputClosedEarly);
29461
+ if (oomKilled) log.warn(`${name}.oom_killed`, { pid: child.pid });
29462
+ handlers.onExit({ code: raw.code, signal: raw.signal, oomKilled }, flags.outputClosedEarly);
29407
29463
  };
29408
29464
  return {
29409
29465
  pid: child.pid,
@@ -29427,6 +29483,7 @@ function hostProcess(child, tree, options, handlers) {
29427
29483
  var init_process_host = __esm({
29428
29484
  "../agent-core/src/session/process-host.ts"() {
29429
29485
  "use strict";
29486
+ init_classify2();
29430
29487
  init_process();
29431
29488
  init_protocol();
29432
29489
  init_ladder();
@@ -29622,7 +29679,10 @@ var init_per_turn = __esm({
29622
29679
  }
29623
29680
  this.#latchSessionId(reader.providerSessionId);
29624
29681
  log.info(`${name}.exited`, { code: exit.code, signal: exit.signal });
29625
- const outcome2 = active.cancelRequested ? { status: "cancelled" } : startupTimedOut ? { status: "failed", error: silentStartError(name, this.#options.startupTimeoutMs) } : reader.finish({ ...exit, stderrTail: stderr.join("\n") });
29682
+ const outcome2 = active.cancelRequested ? { status: "cancelled" } : exit.oomKilled ? outOfMemoryOutcome() : startupTimedOut ? {
29683
+ status: "failed",
29684
+ error: silentStartError(name, this.#options.startupTimeoutMs)
29685
+ } : reader.finish({ ...exit, stderrTail: stderr.join("\n") });
29626
29686
  void (launch.cleanup?.() ?? Promise.resolve()).catch((error62) => log.warn(`${name}.cleanup_failed`, { error: error62 })).finally(() => finish(outcome2));
29627
29687
  }
29628
29688
  }
@@ -29876,7 +29936,7 @@ function within(root, path4) {
29876
29936
  }
29877
29937
  async function resolveReal(path4) {
29878
29938
  try {
29879
- return await (0, import_promises22.realpath)(path4);
29939
+ return await (0, import_promises23.realpath)(path4);
29880
29940
  } catch {
29881
29941
  const parent = (0, import_node_path23.dirname)(path4);
29882
29942
  if (parent === path4) return path4;
@@ -29905,23 +29965,23 @@ function createWorkspaceFs(roots, writable) {
29905
29965
  return {
29906
29966
  read: async (params) => {
29907
29967
  const path4 = await confined(params);
29908
- const bytes = await (0, import_promises22.readFile)(path4);
29968
+ const bytes = await (0, import_promises23.readFile)(path4);
29909
29969
  if (bytes.byteLength > MAX_READ_BYTES) throw new FsDenied(`${path4} is too large to read`);
29910
29970
  return { content: sliceLines(bytes.toString("utf8"), params) };
29911
29971
  },
29912
29972
  write: async (params) => {
29913
29973
  if (!writable) throw new FsDenied("This session is read-only");
29914
29974
  const path4 = await confined(params);
29915
- await (0, import_promises22.writeFile)(path4, asString(params.content));
29975
+ await (0, import_promises23.writeFile)(path4, asString(params.content));
29916
29976
  return {};
29917
29977
  }
29918
29978
  };
29919
29979
  }
29920
- var import_promises22, import_node_path23, MAX_READ_BYTES, FsDenied;
29980
+ var import_promises23, import_node_path23, MAX_READ_BYTES, FsDenied;
29921
29981
  var init_fs = __esm({
29922
29982
  "../agent-core/src/providers/acp/fs.ts"() {
29923
29983
  "use strict";
29924
- import_promises22 = require("fs/promises");
29984
+ import_promises23 = require("fs/promises");
29925
29985
  import_node_path23 = require("path");
29926
29986
  init_kernel();
29927
29987
  MAX_READ_BYTES = 10 * 1024 * 1024;
@@ -30068,24 +30128,24 @@ var init_names = __esm({
30068
30128
 
30069
30129
  // ../agent-core/src/mcp/secret-file.ts
30070
30130
  async function writeSecretFile(name, contents) {
30071
- const dir = await (0, import_promises23.mkdtemp)((0, import_node_path24.join)((0, import_node_os3.tmpdir)(), "alan-mcp-"));
30131
+ const dir = await (0, import_promises24.mkdtemp)((0, import_node_path24.join)((0, import_node_os3.tmpdir)(), "alan-mcp-"));
30072
30132
  const path4 = (0, import_node_path24.join)(dir, name);
30073
30133
  const remove = async () => {
30074
- await (0, import_promises23.rm)(dir, { recursive: true, force: true });
30134
+ await (0, import_promises24.rm)(dir, { recursive: true, force: true });
30075
30135
  };
30076
30136
  try {
30077
- await (0, import_promises23.writeFile)(path4, contents, { mode: 384, flag: "wx" });
30137
+ await (0, import_promises24.writeFile)(path4, contents, { mode: 384, flag: "wx" });
30078
30138
  } catch (error62) {
30079
30139
  await remove();
30080
30140
  throw error62;
30081
30141
  }
30082
30142
  return { path: path4, remove, [Symbol.asyncDispose]: remove };
30083
30143
  }
30084
- var import_promises23, import_node_os3, import_node_path24;
30144
+ var import_promises24, import_node_os3, import_node_path24;
30085
30145
  var init_secret_file = __esm({
30086
30146
  "../agent-core/src/mcp/secret-file.ts"() {
30087
30147
  "use strict";
30088
- import_promises23 = require("fs/promises");
30148
+ import_promises24 = require("fs/promises");
30089
30149
  import_node_os3 = require("os");
30090
30150
  import_node_path24 = require("path");
30091
30151
  }
@@ -31290,8 +31350,9 @@ var init_session2 = __esm({
31290
31350
  reason: this.#closing ? { kind: "suspended" } : { kind: "exited", exitCode: code, signal }
31291
31351
  });
31292
31352
  }
31293
- #exitOutcome(active, { code, signal }) {
31353
+ #exitOutcome(active, { code, signal, oomKilled }) {
31294
31354
  if (active.cancelRequested) return { status: "cancelled" };
31355
+ if (oomKilled) return outOfMemoryOutcome();
31295
31356
  const cause = active.turn.failure ?? this.stderrTail;
31296
31357
  const recognised = cause ? recogniseAcpText(cause) : void 0;
31297
31358
  if (recognised) return { status: "failed", error: recognised };
@@ -32467,6 +32528,10 @@ function cloudExecutionSection(spec) {
32467
32528
  "The user may explicitly override this delivery workflow, including requesting local-only work or a direct push to main. Do not infer an override from urgency, simplicity, or change size. Creating a PR does not itself authorize merging, deployment, destructive actions, or scope expansion; active mode, role restrictions, and tool permissions still apply.",
32468
32529
  "If a required delivery step is blocked, complete remaining independent work and report the precise blocker and what remains unfinished. Never describe local-only work as fully delivered."
32469
32530
  );
32531
+ if (spec.agentId !== SETUP_AGENT_ID)
32532
+ lines2.push(
32533
+ "Persist task-discovered system requirements so future cloud sessions can reproduce the work: a system package, OS library, toolchain or runtime service the repository does not already provide. Use the alan-environment-setup skill's maintenance path when installed; keep the session's working branch and existing PR, follow its validation requirements, and report any tool or authorization blocker. A package added to a manifest and lockfile is not a system requirement; the existing install already consumes it, so leave environment scripts and the image build alone."
32534
+ );
32470
32535
  }
32471
32536
  lines2.push(
32472
32537
  "## Installed skills",
@@ -32684,7 +32749,7 @@ async function acpTurnInput(run2, context) {
32684
32749
  const encoded = await Promise.all(
32685
32750
  images.map(async (image) => ({
32686
32751
  mimeType: image.mimeType,
32687
- data: (await (0, import_promises24.readFile)(image.path)).toString("base64")
32752
+ data: (await (0, import_promises25.readFile)(image.path)).toString("base64")
32688
32753
  }))
32689
32754
  );
32690
32755
  return {
@@ -32693,12 +32758,12 @@ async function acpTurnInput(run2, context) {
32693
32758
  ...encoded.length ? { images: encoded, imagePaths: images.map((image) => image.path) } : {}
32694
32759
  };
32695
32760
  }
32696
- var import_node_crypto18, import_promises24, ACP_MODES;
32761
+ var import_node_crypto18, import_promises25, ACP_MODES;
32697
32762
  var init_run = __esm({
32698
32763
  "../agent-core/src/providers/acp/run.ts"() {
32699
32764
  "use strict";
32700
32765
  import_node_crypto18 = require("crypto");
32701
- import_promises24 = require("fs/promises");
32766
+ import_promises25 = require("fs/promises");
32702
32767
  init_agent2();
32703
32768
  init_mcp2();
32704
32769
  init_prompt();
@@ -32870,6 +32935,8 @@ function createPersistentDriver(provider4, options) {
32870
32935
  if (current.key === key && !current.session.recycleBeforeNextTurn) return current.session;
32871
32936
  log.info("holder.session_respawn", { harness: provider4.harness, runId: spec.runId });
32872
32937
  await current.session.suspend();
32938
+ live.sessionEvents?.[Symbol.dispose]();
32939
+ live.sessionEvents = void 0;
32873
32940
  return void 0;
32874
32941
  };
32875
32942
  const resumeNotice = (spec, session, sink) => {
@@ -32905,6 +32972,14 @@ function createPersistentDriver(provider4, options) {
32905
32972
  }
32906
32973
  const opened = await provider4.open(planned.spec);
32907
32974
  live.current = { session: opened.session, key: planned.key };
32975
+ live.sessionEvents?.[Symbol.dispose]();
32976
+ live.sessionEvents = opened.session.onEvent((event) => {
32977
+ if (event.type === "session_id") live.providerSessionId = event.providerSessionId;
32978
+ if (event.type !== "update" || !event.turnId || live.turn?.runId === event.turnId) return;
32979
+ for (const listener of live.backgroundListeners?.get(event.turnId) ?? []) {
32980
+ listener(event.update, opened.session.providerSessionId);
32981
+ }
32982
+ });
32908
32983
  log.info("holder.session_opened", {
32909
32984
  harness: provider4.harness,
32910
32985
  pid: opened.session.pid,
@@ -33138,6 +33213,23 @@ function createPersistentDriver(provider4, options) {
33138
33213
  },
33139
33214
  suspend: async () => {
33140
33215
  await live.current?.session.suspend();
33216
+ live.sessionEvents?.[Symbol.dispose]();
33217
+ live.sessionEvents = void 0;
33218
+ },
33219
+ hasBackgroundWork: (runId) => live.current?.session.hasBackgroundWork?.(runId) ?? false,
33220
+ onBackgroundEvent: (spec, listener) => {
33221
+ const runId = spec.runId;
33222
+ const listeners = live.backgroundListeners ?? /* @__PURE__ */ new Map();
33223
+ live.backgroundListeners = listeners;
33224
+ const forRun = listeners.get(runId) ?? /* @__PURE__ */ new Set();
33225
+ forRun.add(listener);
33226
+ listeners.set(runId, forRun);
33227
+ return {
33228
+ [Symbol.dispose]: () => {
33229
+ forRun.delete(listener);
33230
+ if (forRun.size === 0) listeners.delete(runId);
33231
+ }
33232
+ };
33141
33233
  },
33142
33234
  respond,
33143
33235
  steer,
@@ -33829,7 +33921,7 @@ function parseJsonc(text3) {
33829
33921
  async function inheritedMcpServerNames(configDirectory) {
33830
33922
  const names = /* @__PURE__ */ new Set();
33831
33923
  for (const file2 of ["config.json", "opencode.json", "opencode.jsonc"]) {
33832
- const text3 = await (0, import_promises25.readFile)((0, import_node_path27.join)(configDirectory, file2), "utf8").catch(() => null);
33924
+ const text3 = await (0, import_promises26.readFile)((0, import_node_path27.join)(configDirectory, file2), "utf8").catch(() => null);
33833
33925
  if (text3 === null) continue;
33834
33926
  const parsed = parseJsonc(text3);
33835
33927
  const mcp = parsed !== null && typeof parsed === "object" ? parsed.mcp : void 0;
@@ -33843,15 +33935,15 @@ async function writePlugin(directory, apiOrigin) {
33843
33935
  const origin = (0, import_node_crypto19.createHash)("sha256").update(apiOrigin).digest("hex").slice(0, 12);
33844
33936
  const target = (0, import_node_path27.join)(directory, `engine-plugin-v${ALAN_CODE_ENGINE_PLUGIN_VERSION}-${origin}.mjs`);
33845
33937
  const temporary = `${target}.${(0, import_node_crypto19.randomUUID)()}.tmp`;
33846
- await (0, import_promises25.mkdir)(directory, { recursive: true, mode: 448 });
33847
- await (0, import_promises25.writeFile)(temporary, alanCodeEnginePluginSource(apiOrigin), { mode: 384 });
33848
- await (0, import_promises25.rename)(temporary, target);
33938
+ await (0, import_promises26.mkdir)(directory, { recursive: true, mode: 448 });
33939
+ await (0, import_promises26.writeFile)(temporary, alanCodeEnginePluginSource(apiOrigin), { mode: 384 });
33940
+ await (0, import_promises26.rename)(temporary, target);
33849
33941
  return (0, import_node_url2.pathToFileURL)(target).href;
33850
33942
  }
33851
33943
  async function prepareAlanCodeProfile(input2) {
33852
33944
  const directories = Object.values(alanCodeEngineDirectories(input2.engineRoot));
33853
33945
  await Promise.all(
33854
- directories.map((directory) => (0, import_promises25.mkdir)(directory, { recursive: true, mode: 448 }))
33946
+ directories.map((directory) => (0, import_promises26.mkdir)(directory, { recursive: true, mode: 448 }))
33855
33947
  );
33856
33948
  const [pluginUrl, models, inheritedMcpServers] = await Promise.all([
33857
33949
  writePlugin((0, import_node_path27.join)(input2.engineRoot, "plugin"), input2.access.apiOrigin),
@@ -33870,12 +33962,12 @@ async function prepareAlanCodeProfile(input2) {
33870
33962
  model: { providerID: ALAN_CODE_ENGINE_PROVIDER_ID, modelID: modelId }
33871
33963
  };
33872
33964
  }
33873
- var import_node_crypto19, import_promises25, import_node_path27, import_node_url2;
33965
+ var import_node_crypto19, import_promises26, import_node_path27, import_node_url2;
33874
33966
  var init_prepare = __esm({
33875
33967
  "../agent-core/src/providers/alan-code/prepare.ts"() {
33876
33968
  "use strict";
33877
33969
  import_node_crypto19 = require("crypto");
33878
- import_promises25 = require("fs/promises");
33970
+ import_promises26 = require("fs/promises");
33879
33971
  import_node_path27 = require("path");
33880
33972
  import_node_url2 = require("url");
33881
33973
  init_mcp2();
@@ -35735,7 +35827,7 @@ var init_session3 = __esm({
35735
35827
  if (active) {
35736
35828
  const how = signal ? `signal ${signal}` : `exit code ${code}`;
35737
35829
  active.finish(
35738
- active.cancelRequested ? { status: "cancelled" } : {
35830
+ active.cancelRequested ? { status: "cancelled" } : exit.oomKilled ? outOfMemoryOutcome() : {
35739
35831
  status: "interrupted",
35740
35832
  reason: `The ${this.#options.engine.label} server stopped mid-turn (${how}).`
35741
35833
  }
@@ -35887,7 +35979,7 @@ async function sameDirectory(left, right) {
35887
35979
  }
35888
35980
  async function canonicalDirectory(directory) {
35889
35981
  try {
35890
- return await (0, import_promises26.realpath)(directory);
35982
+ return await (0, import_promises27.realpath)(directory);
35891
35983
  } catch {
35892
35984
  return (0, import_node_path30.resolve)(directory);
35893
35985
  }
@@ -36061,12 +36153,12 @@ function createOpenCodeDriver(options = {}) {
36061
36153
  }
36062
36154
  };
36063
36155
  }
36064
- var import_node_crypto21, import_promises26, import_node_path30, DEFAULTS2, STORE_LOCKED, NON_INTERACTIVE_RULES;
36156
+ var import_node_crypto21, import_promises27, import_node_path30, DEFAULTS2, STORE_LOCKED, NON_INTERACTIVE_RULES;
36065
36157
  var init_driver3 = __esm({
36066
36158
  "../agent-core/src/providers/opencode/driver.ts"() {
36067
36159
  "use strict";
36068
36160
  import_node_crypto21 = require("crypto");
36069
- import_promises26 = require("fs/promises");
36161
+ import_promises27 = require("fs/promises");
36070
36162
  import_node_path30 = require("path");
36071
36163
  init_agent2();
36072
36164
  init_acp2();
@@ -37200,8 +37292,26 @@ var init_task_records = __esm({
37200
37292
  get(taskId) {
37201
37293
  return this.#records.get(taskId);
37202
37294
  }
37295
+ hasRunningBackgroundTask(turnId) {
37296
+ return [...this.#records.values()].some(
37297
+ (record2) => record2.meta.backgrounded && isRunningTask(record2) && (turnId === void 0 || record2.ownerTurnId === turnId)
37298
+ );
37299
+ }
37300
+ ownerOf(taskId) {
37301
+ return this.#records.get(taskId)?.ownerTurnId;
37302
+ }
37303
+ coversActiveBackgroundTasks(active) {
37304
+ if (active.size === 0) return false;
37305
+ const covered = /* @__PURE__ */ new Set();
37306
+ for (const record2 of this.#records.values()) {
37307
+ if (!record2.meta.backgrounded || !isRunningTask(record2)) continue;
37308
+ covered.add(record2.meta.taskId);
37309
+ if (record2.launcherToolUseId) covered.add(record2.launcherToolUseId);
37310
+ }
37311
+ return [...active].every((id) => covered.has(id));
37312
+ }
37203
37313
  /** Registers or refreshes a task from Claude's `task_started`. */
37204
- track(event, launcherToolUseId) {
37314
+ track(event, launcherToolUseId, ownerTurnId) {
37205
37315
  const taskId = nonEmpty(event.task_id);
37206
37316
  if (!taskId) return;
37207
37317
  const existing = this.#records.get(taskId);
@@ -37225,6 +37335,7 @@ var init_task_records = __esm({
37225
37335
  status: existing?.meta.status ?? "running"
37226
37336
  },
37227
37337
  launcherToolUseId: launcherToolUseId ?? existing?.launcherToolUseId,
37338
+ ownerTurnId: ownerTurnId ?? existing?.ownerTurnId,
37228
37339
  userStopRequested: existing?.userStopRequested ?? false
37229
37340
  });
37230
37341
  }
@@ -37795,7 +37906,7 @@ var init_turn3 = __esm({
37795
37906
  if (subtype === "compact_boundary") this.#noteCompaction(event);
37796
37907
  if (subtype === "task_started") {
37797
37908
  this.tasks.registerRecord(event, parentToolUseId(event));
37798
- this.taskRecords.track(event, this.tasks.resolveToolUseId(event));
37909
+ this.taskRecords.track(event, this.tasks.resolveToolUseId(event), this.#options.turnId);
37799
37910
  const updates = backgroundTaskIdentity(event, this.tasks);
37800
37911
  return updates.length ? updates : [unlinkedTaskEvent(event)];
37801
37912
  }
@@ -37936,6 +38047,10 @@ var init_turn3 = __esm({
37936
38047
  return;
37937
38048
  }
37938
38049
  if (this.tasks.size > 0) {
38050
+ if (this.taskRecords.coversActiveBackgroundTasks(this.tasks.active)) {
38051
+ this.#finalized = true;
38052
+ return;
38053
+ }
37939
38054
  this.#deferredOnBackground = true;
37940
38055
  return;
37941
38056
  }
@@ -38045,8 +38160,10 @@ function stopTaskResult(response) {
38045
38160
  const message2 = response.error ?? "Claude Code could not stop the task.";
38046
38161
  return { ok: false, reason: UNSUPPORTED_STOP.test(message2) ? "unsupported" : "failed", message: message2 };
38047
38162
  }
38048
- function exitOutcome2(turn, stderrTail, { code, signal }, outputClosedEarly) {
38163
+ function exitOutcome2(turn, stderrTail, exit, outputClosedEarly) {
38164
+ const { code, signal } = exit;
38049
38165
  if (turn.cancelRequested) return { status: "cancelled" };
38166
+ if (exit.oomKilled) return outOfMemoryOutcome();
38050
38167
  if (outputClosedEarly) return { status: "interrupted", reason: OUTPUT_CLOSED_REASON };
38051
38168
  const recognised = stderrTail ? classifyProviderTerminalText(stderrTail) : void 0;
38052
38169
  if (recognised && !turn.turn.resultSeen) return { status: "failed", error: recognised };
@@ -38129,6 +38246,8 @@ var init_driver4 = __esm({
38129
38246
  #stderr = [];
38130
38247
  #replaysUserMessages;
38131
38248
  #taskRecords;
38249
+ #backgroundTurns = /* @__PURE__ */ new Map();
38250
+ #lateSynthesisOwners = [];
38132
38251
  #taskStops = /* @__PURE__ */ new Map();
38133
38252
  #state = "idle";
38134
38253
  #current;
@@ -38169,6 +38288,9 @@ var init_driver4 = __esm({
38169
38288
  get lastOutputAt() {
38170
38289
  return this.#host.lastOutputAt;
38171
38290
  }
38291
+ hasBackgroundWork(turnId) {
38292
+ return this.#taskRecords.hasRunningBackgroundTask(turnId) || (turnId === void 0 ? this.#lateSynthesisOwners.length > 0 : this.#lateSynthesisOwners.includes(turnId));
38293
+ }
38172
38294
  get backgroundTasks() {
38173
38295
  return this.#taskRecords.running;
38174
38296
  }
@@ -38183,6 +38305,7 @@ var init_driver4 = __esm({
38183
38305
  const resumedSessionId = this.#turnsStarted === 0 ? this.#resumeId : void 0;
38184
38306
  this.#turnsStarted += 1;
38185
38307
  const turn = new ClaudeTurn({
38308
+ turnId: input2.turnId,
38186
38309
  selectedModel: this.#selectedModel,
38187
38310
  resumedSessionId,
38188
38311
  model: this.#lastTurn.grammar.model,
@@ -38328,6 +38451,7 @@ var init_driver4 = __esm({
38328
38451
  if (this.#current?.id !== id) return;
38329
38452
  this.#current = void 0;
38330
38453
  this.#lastTurn = turn;
38454
+ if (this.#taskRecords.hasRunningBackgroundTask(id)) this.#backgroundTurns.set(id, turn);
38331
38455
  if (this.#state === "busy") this.#state = "idle";
38332
38456
  this.#emit({ type: "turn_ended", turnId: id, outcome: outcome2 });
38333
38457
  resolve16({ turnId: id, outcome: outcome2, providerSessionId: this.#providerSessionId });
@@ -38390,15 +38514,43 @@ var init_driver4 = __esm({
38390
38514
  for (const held of active.early.splice(0)) this.#read(void 0, held);
38391
38515
  }
38392
38516
  #read(active, line) {
38393
- const parser = active?.turn ?? this.#lastTurn;
38394
- for (const update of parser.readLine(line)) {
38395
- this.#emit({ type: "update", turnId: active?.id, update });
38396
- }
38517
+ const record2 = line.kind === "record" ? line.record : void 0;
38518
+ const owner = this.#taskNotificationOwner(record2);
38519
+ const lateOwner = active ? void 0 : this.#lateSynthesisOwners[0];
38520
+ const backgroundOwner = owner ?? lateOwner;
38521
+ const backgroundTurn = backgroundOwner === active?.id ? void 0 : this.#backgroundTurns.get(backgroundOwner ?? "");
38522
+ const parser = backgroundTurn ?? active?.turn ?? this.#lastTurn;
38523
+ const updates = parser.readLine(line);
38524
+ this.#noteBackgroundTaskSettlement(owner, backgroundTurn, record2);
38525
+ for (const update of updates) {
38526
+ this.#emit({ type: "update", turnId: backgroundTurn ? backgroundOwner : active?.id, update });
38527
+ }
38528
+ this.#finishLateSynthesis(backgroundTurn, lateOwner, record2);
38397
38529
  this.#noteSessionId(parser.sessionId);
38398
- if (!active) return;
38530
+ if (!active || backgroundTurn) return;
38399
38531
  if (line.kind === "record" && line.record.type === "result") active.lastResult = line.record;
38400
38532
  this.#settle(active, line);
38401
38533
  }
38534
+ #taskNotificationOwner(record2) {
38535
+ if (record2?.type !== "system" || record2.subtype !== "task_notification") return void 0;
38536
+ return this.#taskRecords.ownerOf(asString(record2.task_id));
38537
+ }
38538
+ #noteBackgroundTaskSettlement(owner, backgroundTurn, record2) {
38539
+ if (!backgroundTurn || !owner || this.#taskRecords.hasRunningBackgroundTask(owner)) return;
38540
+ const stoppedByUser = this.#taskRecords.get(asString(record2?.task_id))?.userStopRequested;
38541
+ if (stoppedByUser) this.#backgroundTurns.delete(owner);
38542
+ else if (!this.#lateSynthesisOwners.includes(owner)) this.#lateSynthesisOwners.push(owner);
38543
+ }
38544
+ #finishLateSynthesis(backgroundTurn, owner, record2) {
38545
+ if (!backgroundTurn || !owner || record2?.type !== "result") return;
38546
+ this.#lateSynthesisOwners.shift();
38547
+ this.#backgroundTurns.delete(owner);
38548
+ this.#emit({
38549
+ type: "update",
38550
+ turnId: owner,
38551
+ update: { sessionUpdate: "state_update", state: "idle" }
38552
+ });
38553
+ }
38402
38554
  #settle(active, line) {
38403
38555
  this.#host.scanDescendants(false);
38404
38556
  const isResult = line.kind === "record" && line.record.type === "result";
@@ -38582,17 +38734,17 @@ async function claudeTurnInput(run2, context) {
38582
38734
  const encoded = await Promise.all(
38583
38735
  images.map(async (image) => ({
38584
38736
  mimeType: image.mimeType,
38585
- data: (await (0, import_promises27.readFile)(image.path)).toString("base64")
38737
+ data: (await (0, import_promises28.readFile)(image.path)).toString("base64")
38586
38738
  }))
38587
38739
  );
38588
38740
  return { turnId: run2.runId, text: text3, ...encoded.length ? { images: encoded } : {} };
38589
38741
  }
38590
- var import_node_crypto24, import_promises27, READ_ONLY_DISALLOWED_TOOLS, DEFAULT_MCP_TIMEOUT_MS, CLOUD_SKILL_LISTING_MAX_DESCRIPTION_CHARS;
38742
+ var import_node_crypto24, import_promises28, READ_ONLY_DISALLOWED_TOOLS, DEFAULT_MCP_TIMEOUT_MS, CLOUD_SKILL_LISTING_MAX_DESCRIPTION_CHARS;
38591
38743
  var init_run3 = __esm({
38592
38744
  "../agent-core/src/providers/claude/run.ts"() {
38593
38745
  "use strict";
38594
38746
  import_node_crypto24 = require("crypto");
38595
- import_promises27 = require("fs/promises");
38747
+ import_promises28 = require("fs/promises");
38596
38748
  init_agent2();
38597
38749
  init_mcp2();
38598
38750
  init_prompt();
@@ -40774,6 +40926,7 @@ var STDERR_TAIL_LINES4, MAX_BETWEEN_UPDATES2, UNSUPPORTED_REQUEST, DECLINED_ELIC
40774
40926
  var init_session4 = __esm({
40775
40927
  "../agent-core/src/providers/codex/session.ts"() {
40776
40928
  "use strict";
40929
+ init_acp();
40777
40930
  init_acp2();
40778
40931
  init_classify2();
40779
40932
  init_kernel();
@@ -40803,6 +40956,8 @@ var init_session4 = __esm({
40803
40956
  #approvals = /* @__PURE__ */ new Map();
40804
40957
  /** Session-level updates (thread start warnings, MCP startup) that open the next turn's log. */
40805
40958
  #between = [];
40959
+ #backgroundLaunchers = /* @__PURE__ */ new Map();
40960
+ #workerOwners = /* @__PURE__ */ new Map();
40806
40961
  #config = { approvals: "ask" };
40807
40962
  #threadId;
40808
40963
  #rolloutPath;
@@ -40847,6 +41002,19 @@ var init_session4 = __esm({
40847
41002
  get lastOutputAt() {
40848
41003
  return this.#host.lastOutputAt;
40849
41004
  }
41005
+ hasBackgroundWork(turnId) {
41006
+ return turnId === void 0 ? this.#backgroundLaunchers.size > 0 : [...this.#backgroundLaunchers.values()].includes(turnId);
41007
+ }
41008
+ #trackBackground(updates, ownerTurnId) {
41009
+ for (const update of updates) {
41010
+ if (!isUpdate(update, "tool_call_update")) continue;
41011
+ if (ownerTurnId && update._meta?.[SUBAGENT_LAUNCHER_META] === true && update.status === "in_progress") {
41012
+ this.#backgroundLaunchers.set(update.toolCallId, ownerTurnId);
41013
+ } else if (this.#backgroundLaunchers.has(update.toolCallId) && (update.status === "completed" || update.status === "failed" || update.status === "cancelled")) {
41014
+ this.#backgroundLaunchers.delete(update.toolCallId);
41015
+ }
41016
+ }
41017
+ }
40850
41018
  get exited() {
40851
41019
  return this.#host.exited;
40852
41020
  }
@@ -41015,7 +41183,11 @@ var init_session4 = __esm({
41015
41183
  /** Notifications from another turn (a late one after an interrupt) go out as session records. */
41016
41184
  #ownerOf(notification) {
41017
41185
  const active = this.#current;
41018
- if (this.#memory.workers.has(asString(notification.params.threadId))) return active;
41186
+ const workerThreadId = asString(notification.params.threadId);
41187
+ if (this.#memory.workers.has(workerThreadId)) {
41188
+ const owner = this.#workerOwners.get(workerThreadId);
41189
+ return owner === void 0 || owner === active?.id ? active : void 0;
41190
+ }
41019
41191
  const turnId = asString(notification.params.turnId) || asString(asRecord(notification.params.turn)?.id);
41020
41192
  if (!active || !turnId) return active;
41021
41193
  const known = active.turn.codexTurnId;
@@ -41030,11 +41202,19 @@ var init_session4 = __esm({
41030
41202
  const active = this.#ownerOf(notification);
41031
41203
  const reader = active?.turn ?? this.#lastTurn;
41032
41204
  const updates = reader.read(notification);
41205
+ const workerThreadId = asString(notification.params.threadId);
41206
+ const ownerTurnId = active?.id ?? this.#workerOwners.get(workerThreadId);
41207
+ if (active) {
41208
+ for (const workerThreadId2 of this.#memory.workers.keys()) {
41209
+ if (!this.#workerOwners.has(workerThreadId2))
41210
+ this.#workerOwners.set(workerThreadId2, active.id);
41211
+ }
41212
+ }
41033
41213
  if (!active) {
41034
- this.#between.push(...updates);
41035
- this.#between.splice(0, Math.max(0, this.#between.length - MAX_BETWEEN_UPDATES2));
41214
+ this.#betweenNotification(updates, ownerTurnId);
41036
41215
  return;
41037
41216
  }
41217
+ this.#trackBackground(updates, ownerTurnId);
41038
41218
  if (active.turn.codexTurnId) active.identify(active.turn.codexTurnId);
41039
41219
  this.#emitUpdates(active, [...active.images.drain(), ...active.images.admit(updates)]);
41040
41220
  this.#host.scanDescendants(false);
@@ -41052,6 +41232,20 @@ var init_session4 = __esm({
41052
41232
  void this.#stopTurn(active);
41053
41233
  }
41054
41234
  }
41235
+ #betweenNotification(updates, ownerTurnId) {
41236
+ const backgroundWasRunning = this.hasBackgroundWork();
41237
+ const previousOwners = new Map(this.#backgroundLaunchers);
41238
+ this.#trackBackground(updates, ownerTurnId);
41239
+ if (!backgroundWasRunning) {
41240
+ this.#between.push(...updates);
41241
+ this.#between.splice(0, Math.max(0, this.#between.length - MAX_BETWEEN_UPDATES2));
41242
+ return;
41243
+ }
41244
+ for (const update of updates) {
41245
+ const updateOwner = isUpdate(update, "tool_call_update") ? previousOwners.get(update.toolCallId) ?? ownerTurnId : ownerTurnId;
41246
+ this.#emit({ type: "update", turnId: updateOwner, update });
41247
+ }
41248
+ }
41055
41249
  #recordRateLimits(updates) {
41056
41250
  const active = this.#current;
41057
41251
  if (active) this.#emitUpdates(active, updates);
@@ -41214,7 +41408,7 @@ var init_session4 = __esm({
41214
41408
  this.#emitUpdates(active, active.images.settle());
41215
41409
  const how = signal ? `signal ${signal}` : `exit code ${code}`;
41216
41410
  active.finish(
41217
- active.failFast ? { status: "failed", error: active.failFast } : active.cancelRequested ? { status: "cancelled" } : { status: "interrupted", reason: `The Codex app-server stopped mid-turn (${how}).` }
41411
+ active.failFast ? { status: "failed", error: active.failFast } : active.cancelRequested ? { status: "cancelled" } : exit.oomKilled ? outOfMemoryOutcome() : { status: "interrupted", reason: `The Codex app-server stopped mid-turn (${how}).` }
41218
41412
  );
41219
41413
  }
41220
41414
  this.#options.log.info("codex.exited", { code, signal, suspended: this.#closing });
@@ -43351,7 +43545,7 @@ var init_session5 = __esm({
43351
43545
  if (active) {
43352
43546
  const how = signal ? `signal ${signal}` : `exit code ${code}`;
43353
43547
  active.finish(
43354
- active.cancelRequested ? { status: "cancelled" } : { status: "interrupted", reason: `Droid stopped mid-turn (${how}).` }
43548
+ active.cancelRequested ? { status: "cancelled" } : exit.oomKilled ? outOfMemoryOutcome() : { status: "interrupted", reason: `Droid stopped mid-turn (${how}).` }
43355
43549
  );
43356
43550
  }
43357
43551
  this.#options.log.info("droid.exited", { code, signal, suspended: this.#closing });
@@ -43581,17 +43775,17 @@ async function droidTurnInput(run2, context) {
43581
43775
  const encoded = await Promise.all(
43582
43776
  images.map(async (image) => ({
43583
43777
  mimeType: image.mimeType,
43584
- data: (await (0, import_promises28.readFile)(image.path)).toString("base64")
43778
+ data: (await (0, import_promises29.readFile)(image.path)).toString("base64")
43585
43779
  }))
43586
43780
  );
43587
43781
  return { turnId: run2.runId, text: text3, ...encoded.length ? { images: encoded } : {} };
43588
43782
  }
43589
- var import_node_crypto30, import_promises28;
43783
+ var import_node_crypto30, import_promises29;
43590
43784
  var init_run5 = __esm({
43591
43785
  "../agent-core/src/providers/droid/run.ts"() {
43592
43786
  "use strict";
43593
43787
  import_node_crypto30 = require("crypto");
43594
- import_promises28 = require("fs/promises");
43788
+ import_promises29 = require("fs/promises");
43595
43789
  init_agent2();
43596
43790
  init_mcp2();
43597
43791
  init_prompt();
@@ -43721,7 +43915,7 @@ function settingsPath(env) {
43721
43915
  async function readSettings(path4) {
43722
43916
  let raw;
43723
43917
  try {
43724
- raw = (await (0, import_promises29.readFile)(path4, "utf8")).trim();
43918
+ raw = (await (0, import_promises30.readFile)(path4, "utf8")).trim();
43725
43919
  } catch {
43726
43920
  return {};
43727
43921
  }
@@ -43739,15 +43933,15 @@ async function selectAntigravityApiKeyMode(env) {
43739
43933
  const settings2 = await readSettings(path4);
43740
43934
  if (settings2 === "malformed") return "malformed";
43741
43935
  if (settings2.modelProvider === "gemini") return "already_selected";
43742
- await (0, import_promises29.mkdir)((0, import_node_path33.dirname)(path4), { recursive: true });
43743
- await (0, import_promises29.writeFile)(path4, JSON.stringify({ ...settings2, modelProvider: "gemini" }), { mode: 384 });
43936
+ await (0, import_promises30.mkdir)((0, import_node_path33.dirname)(path4), { recursive: true });
43937
+ await (0, import_promises30.writeFile)(path4, JSON.stringify({ ...settings2, modelProvider: "gemini" }), { mode: 384 });
43744
43938
  return "selected";
43745
43939
  }
43746
- var import_promises29, import_node_path33;
43940
+ var import_promises30, import_node_path33;
43747
43941
  var init_api_key_mode = __esm({
43748
43942
  "../agent-core/src/providers/antigravity/api-key-mode.ts"() {
43749
43943
  "use strict";
43750
- import_promises29 = require("fs/promises");
43944
+ import_promises30 = require("fs/promises");
43751
43945
  import_node_path33 = require("path");
43752
43946
  init_type_guards();
43753
43947
  }
@@ -44990,7 +45184,7 @@ function parseConfig(raw) {
44990
45184
  }
44991
45185
  async function writeCommandCodeProjectMcp(cwd, mcp) {
44992
45186
  const path4 = (0, import_node_path36.join)(cwd, ".mcp.json");
44993
- const original = await (0, import_promises30.readFile)(path4, "utf8").catch(() => null);
45187
+ const original = await (0, import_promises31.readFile)(path4, "utf8").catch(() => null);
44994
45188
  const config2 = parseConfig(original);
44995
45189
  const next = {
44996
45190
  ...config2,
@@ -45007,19 +45201,19 @@ async function writeCommandCodeProjectMcp(cwd, mcp) {
45007
45201
  }
45008
45202
  }
45009
45203
  };
45010
- await (0, import_promises30.mkdir)(cwd, { recursive: true });
45011
- await (0, import_promises30.writeFile)(path4, `${JSON.stringify(next, null, 2)}
45204
+ await (0, import_promises31.mkdir)(cwd, { recursive: true });
45205
+ await (0, import_promises31.writeFile)(path4, `${JSON.stringify(next, null, 2)}
45012
45206
  `);
45013
45207
  return async () => {
45014
- if (original === null) await (0, import_promises30.rm)(path4, { force: true });
45015
- else await (0, import_promises30.writeFile)(path4, original);
45208
+ if (original === null) await (0, import_promises31.rm)(path4, { force: true });
45209
+ else await (0, import_promises31.writeFile)(path4, original);
45016
45210
  };
45017
45211
  }
45018
- var import_promises30, import_node_path36;
45212
+ var import_promises31, import_node_path36;
45019
45213
  var init_project_mcp = __esm({
45020
45214
  "../agent-core/src/providers/command-code/project-mcp.ts"() {
45021
45215
  "use strict";
45022
- import_promises30 = require("fs/promises");
45216
+ import_promises31 = require("fs/promises");
45023
45217
  import_node_path36 = require("path");
45024
45218
  init_agent2();
45025
45219
  init_runtime_v2();
@@ -60505,7 +60699,7 @@ var import_node_worker_threads2 = require("worker_threads");
60505
60699
  // package.json
60506
60700
  var package_default = {
60507
60701
  name: "@alan-ai-hq/agent-manager",
60508
- version: "0.1.176",
60702
+ version: "0.1.178",
60509
60703
  private: true,
60510
60704
  type: "module",
60511
60705
  description: "Alan machine runtime (alan-agent): identity, link, reconciler, session holders, run log, uploader, local API",
@@ -60847,13 +61041,19 @@ function createLog(level, clock, sink) {
60847
61041
  function openFileLog(path4, level, clock) {
60848
61042
  (0, import_node_fs2.mkdirSync)((0, import_node_path2.dirname)(path4), { recursive: true, mode: 448 });
60849
61043
  const fd = (0, import_node_fs2.openSync)(path4, "a", 384);
61044
+ let closed = false;
60850
61045
  const log = createLog(level, clock, (entry) => {
61046
+ if (closed) return;
60851
61047
  (0, import_node_fs2.writeSync)(fd, `${JSON.stringify(entry)}
60852
61048
  `);
60853
61049
  });
60854
61050
  return {
60855
61051
  ...log,
60856
- [Symbol.dispose]: () => (0, import_node_fs2.closeSync)(fd)
61052
+ [Symbol.dispose]: () => {
61053
+ if (closed) return;
61054
+ closed = true;
61055
+ (0, import_node_fs2.closeSync)(fd);
61056
+ }
60857
61057
  };
60858
61058
  }
60859
61059
  function createMemoryLog(level, clock) {
@@ -64477,7 +64677,7 @@ function startWakeClock(options) {
64477
64677
  }
64478
64678
 
64479
64679
  // src/cli/commands/activity-lease-producer.ts
64480
- var import_promises75 = require("fs/promises");
64680
+ var import_promises76 = require("fs/promises");
64481
64681
  var import_node_path90 = require("path");
64482
64682
  init_runtime_v2();
64483
64683
 
@@ -64579,15 +64779,22 @@ function writeMessage(socket, message2) {
64579
64779
 
64580
64780
  // src/holder/control-client.ts
64581
64781
  var REQUEST_TIMEOUT_MS7 = 3e4;
64782
+ var READY_TIMEOUT_MS = 15e3;
64582
64783
  var HOLDER_ALREADY_STARTED = "already_started";
64583
64784
  function isReply(message2) {
64584
64785
  return message2.type === "ack" || message2.type === "error" || message2.type === "status" || message2.type === "responded" || message2.type === "steered" || message2.type === "task_stopped";
64585
64786
  }
64586
- async function connectHolder(endpoint, token, onEvent) {
64787
+ async function connectHolder(endpoint, token, onEvent, readyTimeoutMs = READY_TIMEOUT_MS) {
64587
64788
  const socket = (0, import_node_net.connect)(endpoint);
64588
64789
  const pending = /* @__PURE__ */ new Map();
64589
64790
  const closed = new Promise((resolve16) => socket.once("close", () => resolve16()));
64791
+ const deadline = AbortSignal.timeout(readyTimeoutMs);
64590
64792
  const ready = new Promise((resolve16, reject) => {
64793
+ deadline.addEventListener(
64794
+ "abort",
64795
+ () => reject(new RuntimeFault("io_failed", "Holder did not become ready")),
64796
+ { once: true }
64797
+ );
64591
64798
  socket.once("error", reject);
64592
64799
  socket.once(
64593
64800
  "close",
@@ -64607,7 +64814,10 @@ async function connectHolder(endpoint, token, onEvent) {
64607
64814
  });
64608
64815
  socket.once("connect", () => writeMessage(socket, { type: "auth", token }));
64609
64816
  });
64610
- const pid = await ready;
64817
+ const pid = await ready.catch((error62) => {
64818
+ socket.destroy();
64819
+ throw error62;
64820
+ });
64611
64821
  const request2 = (body) => {
64612
64822
  const id = (0, import_node_crypto11.randomUUID)();
64613
64823
  return new Promise((resolve16, reject) => {
@@ -64654,7 +64864,7 @@ var GitFault = class extends Error {
64654
64864
  };
64655
64865
 
64656
64866
  // src/capabilities/git/remote.ts
64657
- var import_promises31 = require("fs/promises");
64867
+ var import_promises32 = require("fs/promises");
64658
64868
  var import_node_path37 = require("path");
64659
64869
  var import_node_url5 = require("url");
64660
64870
  var SUPPORTED_REMOTE_PROTOCOLS = /* @__PURE__ */ new Set([
@@ -64668,7 +64878,7 @@ async function canonicalPathWithMissingTail(path4) {
64668
64878
  let cursor = (0, import_node_path37.resolve)(path4);
64669
64879
  for (; ; ) {
64670
64880
  try {
64671
- return (0, import_node_path37.join)(await (0, import_promises31.realpath)(cursor), ...missing);
64881
+ return (0, import_node_path37.join)(await (0, import_promises32.realpath)(cursor), ...missing);
64672
64882
  } catch (error62) {
64673
64883
  if (errnoCode(error62) !== "ENOENT" && errnoCode(error62) !== "ENOTDIR") throw error62;
64674
64884
  const parent = (0, import_node_path37.dirname)(cursor);
@@ -64762,11 +64972,11 @@ async function inspectedRemoteUrl(git, repoRoot, remote, signal) {
64762
64972
  }
64763
64973
 
64764
64974
  // src/capabilities/git/repository.ts
64765
- var import_promises32 = require("fs/promises");
64975
+ var import_promises33 = require("fs/promises");
64766
64976
  var import_node_path38 = require("path");
64767
64977
  async function isDirectory2(path4) {
64768
64978
  try {
64769
- return (await (0, import_promises32.stat)(path4)).isDirectory();
64979
+ return (await (0, import_promises33.stat)(path4)).isDirectory();
64770
64980
  } catch {
64771
64981
  return false;
64772
64982
  }
@@ -64787,7 +64997,7 @@ async function resolveRepositoryRoot(git, path4, signal) {
64787
64997
  "The selected folder is not inside a Git repository"
64788
64998
  );
64789
64999
  }
64790
- return (0, import_promises32.realpath)((0, import_node_path38.resolve)(root));
65000
+ return (0, import_promises33.realpath)((0, import_node_path38.resolve)(root));
64791
65001
  }
64792
65002
  async function listWorktrees(git, repoRoot, signal) {
64793
65003
  const output2 = await git.ok(
@@ -64851,12 +65061,12 @@ async function repositoryCommonDir(git, repoRoot, signal) {
64851
65061
  signal,
64852
65062
  "git_operation_failed"
64853
65063
  );
64854
- return (0, import_promises32.realpath)(commonDir);
65064
+ return (0, import_promises33.realpath)(commonDir);
64855
65065
  }
64856
65066
 
64857
65067
  // src/capabilities/git/status.ts
64858
65068
  var import_node_crypto33 = require("crypto");
64859
- var import_promises33 = require("fs/promises");
65069
+ var import_promises34 = require("fs/promises");
64860
65070
  var import_node_path39 = require("path");
64861
65071
  var BRANCH_LABEL_MAX_LENGTH = 256;
64862
65072
  var HASH_OBJECT_BATCH = 128;
@@ -64936,8 +65146,8 @@ async function readWorkspaceStatus(context) {
64936
65146
  };
64937
65147
  }
64938
65148
  async function proposedTreeSha(context, headSha) {
64939
- await (0, import_promises33.mkdir)(context.tmpDir, { recursive: true, mode: 448 });
64940
- const tempDir = await (0, import_promises33.mkdtemp)((0, import_node_path39.join)(context.tmpDir, "index-"));
65149
+ await (0, import_promises34.mkdir)(context.tmpDir, { recursive: true, mode: 448 });
65150
+ const tempDir = await (0, import_promises34.mkdtemp)((0, import_node_path39.join)(context.tmpDir, "index-"));
64941
65151
  const env = { GIT_INDEX_FILE: (0, import_node_path39.join)(tempDir, "index") };
64942
65152
  const run2 = (args) => context.git.ok({ cwd: context.repoRoot, args, env }, context.signal, "git_status_unreadable");
64943
65153
  try {
@@ -64947,7 +65157,7 @@ async function proposedTreeSha(context, headSha) {
64947
65157
  assertCommitSha(tree, "proposedTreeSha");
64948
65158
  return tree;
64949
65159
  } finally {
64950
- await (0, import_promises33.rm)(tempDir, { recursive: true, force: true });
65160
+ await (0, import_promises34.rm)(tempDir, { recursive: true, force: true });
64951
65161
  }
64952
65162
  }
64953
65163
  function updateLengthPrefixed(hash2, value2) {
@@ -65144,7 +65354,7 @@ async function verifyHead(context, request2) {
65144
65354
  }
65145
65355
 
65146
65356
  // src/capabilities/git/checkpoint.ts
65147
- var import_promises34 = require("fs/promises");
65357
+ var import_promises35 = require("fs/promises");
65148
65358
  var import_node_path40 = require("path");
65149
65359
  init_runtime_v2();
65150
65360
  function sourceChanged(message2) {
@@ -65152,7 +65362,7 @@ function sourceChanged(message2) {
65152
65362
  }
65153
65363
  async function createLockFile(path4) {
65154
65364
  try {
65155
- await (0, import_promises34.writeFile)(path4, "", { flag: "wx" });
65365
+ await (0, import_promises35.writeFile)(path4, "", { flag: "wx" });
65156
65366
  return true;
65157
65367
  } catch {
65158
65368
  return false;
@@ -65166,13 +65376,13 @@ async function acquireHeadLock(locks) {
65166
65376
  }
65167
65377
  async function releaseHeadLock(locks) {
65168
65378
  if (!locks.headLockHeld) return;
65169
- await (0, import_promises34.rm)(locks.headLockPath, { force: true });
65379
+ await (0, import_promises35.rm)(locks.headLockPath, { force: true });
65170
65380
  locks.headLockHeld = false;
65171
65381
  }
65172
65382
  async function releaseLocks(locks) {
65173
65383
  await releaseHeadLock(locks);
65174
65384
  if (locks.indexLockHeld) {
65175
- await (0, import_promises34.rm)(locks.indexLockPath, { force: true });
65385
+ await (0, import_promises35.rm)(locks.indexLockPath, { force: true });
65176
65386
  locks.indexLockHeld = false;
65177
65387
  }
65178
65388
  }
@@ -65216,8 +65426,8 @@ async function assertHead(context, expectedRef, expectedHeadSha) {
65216
65426
  }
65217
65427
  }
65218
65428
  async function createIndexBaseline(context, sha) {
65219
- await (0, import_promises34.mkdir)(context.tmpDir, { recursive: true, mode: 448 });
65220
- const tempDir = await (0, import_promises34.mkdtemp)((0, import_node_path40.join)(context.tmpDir, "checkpoint-index-"));
65429
+ await (0, import_promises35.mkdir)(context.tmpDir, { recursive: true, mode: 448 });
65430
+ const tempDir = await (0, import_promises35.mkdtemp)((0, import_node_path40.join)(context.tmpDir, "checkpoint-index-"));
65221
65431
  const indexPath = (0, import_node_path40.join)(tempDir, "index");
65222
65432
  try {
65223
65433
  await context.git.ok(
@@ -65227,14 +65437,14 @@ async function createIndexBaseline(context, sha) {
65227
65437
  );
65228
65438
  return { indexPath, tempDir };
65229
65439
  } catch (error62) {
65230
- await (0, import_promises34.rm)(tempDir, { recursive: true, force: true });
65440
+ await (0, import_promises35.rm)(tempDir, { recursive: true, force: true });
65231
65441
  throw error62;
65232
65442
  }
65233
65443
  }
65234
65444
  async function installIndexBaseline(locks, baselinePath) {
65235
65445
  try {
65236
- await (0, import_promises34.copyFile)(baselinePath, locks.indexLockPath);
65237
- await (0, import_promises34.rename)(locks.indexLockPath, locks.indexPath);
65446
+ await (0, import_promises35.copyFile)(baselinePath, locks.indexLockPath);
65447
+ await (0, import_promises35.rename)(locks.indexLockPath, locks.indexPath);
65238
65448
  locks.indexLockHeld = false;
65239
65449
  } catch (error62) {
65240
65450
  throw new GitFault(
@@ -65262,7 +65472,7 @@ async function replayCheckpoint(context, expectedRef, headSha) {
65262
65472
  return { repoRoot: context.repoRoot, sha: headSha, replayed: true };
65263
65473
  } finally {
65264
65474
  if (locks) await releaseLocks(locks);
65265
- await (0, import_promises34.rm)(baseline.tempDir, { recursive: true, force: true });
65475
+ await (0, import_promises35.rm)(baseline.tempDir, { recursive: true, force: true });
65266
65476
  }
65267
65477
  }
65268
65478
  async function commitApprovedTree(context, request2) {
@@ -65393,7 +65603,7 @@ async function finalize2(context, expectedRef, previousSha, sha) {
65393
65603
  );
65394
65604
  }
65395
65605
  if (locks) await releaseLocks(locks);
65396
- await (0, import_promises34.rm)(baseline.tempDir, { recursive: true, force: true });
65606
+ await (0, import_promises35.rm)(baseline.tempDir, { recursive: true, force: true });
65397
65607
  }
65398
65608
  }
65399
65609
 
@@ -65664,7 +65874,7 @@ function createGitRunner(options) {
65664
65874
 
65665
65875
  // src/capabilities/git/checkout-freshness.ts
65666
65876
  var import_node_crypto34 = require("crypto");
65667
- var import_promises35 = require("fs/promises");
65877
+ var import_promises36 = require("fs/promises");
65668
65878
  var import_node_path41 = require("path");
65669
65879
  init_zod();
65670
65880
  var REMOTE = "origin";
@@ -65827,14 +66037,14 @@ async function moveSnapshotTo(git, cwd, snapshot, tip, signal) {
65827
66037
  return moved.exitCode === 0 && back.exitCode === 0;
65828
66038
  }
65829
66039
  async function isCheckout(path4) {
65830
- return (0, import_promises35.stat)((0, import_node_path41.join)(path4, ".git")).then(
66040
+ return (0, import_promises36.stat)((0, import_node_path41.join)(path4, ".git")).then(
65831
66041
  () => true,
65832
66042
  () => false
65833
66043
  );
65834
66044
  }
65835
66045
  async function checkoutsUnder(root) {
65836
66046
  if (await isCheckout(root)) return [root];
65837
- const entries = await (0, import_promises35.readdir)(root, { withFileTypes: true }).catch(() => []);
66047
+ const entries = await (0, import_promises36.readdir)(root, { withFileTypes: true }).catch(() => []);
65838
66048
  const found = await Promise.all(
65839
66049
  entries.filter((entry) => entry.isDirectory()).map(
65840
66050
  async (entry) => await isCheckout((0, import_node_path41.join)(root, entry.name)) ? (0, import_node_path41.join)(root, entry.name) : null
@@ -65880,13 +66090,13 @@ async function readCheckoutFreshness(dir, path4) {
65880
66090
 
65881
66091
  // src/capabilities/git/commit-attribution.ts
65882
66092
  var import_node_crypto35 = require("crypto");
65883
- var import_promises37 = require("fs/promises");
66093
+ var import_promises38 = require("fs/promises");
65884
66094
  var import_node_path43 = require("path");
65885
66095
  init_runtime_v2();
65886
66096
 
65887
66097
  // src/capabilities/providers/commands.ts
65888
66098
  var import_node_fs21 = require("fs");
65889
- var import_promises36 = require("fs/promises");
66099
+ var import_promises37 = require("fs/promises");
65890
66100
  var import_node_path42 = require("path");
65891
66101
  var PROVIDER_COMMANDS = [
65892
66102
  // The engine, not a CLI of its own: `resolveProviderExecutable` finds the bundled one first.
@@ -65922,8 +66132,8 @@ function pathDelimiter(platform3) {
65922
66132
  }
65923
66133
  async function isRunnable(path4, platform3) {
65924
66134
  try {
65925
- if (!(await (0, import_promises36.stat)(path4)).isFile()) return false;
65926
- if (platform3 !== "win32") await (0, import_promises36.access)(path4, import_node_fs21.constants.X_OK);
66135
+ if (!(await (0, import_promises37.stat)(path4)).isFile()) return false;
66136
+ if (platform3 !== "win32") await (0, import_promises37.access)(path4, import_node_fs21.constants.X_OK);
65927
66137
  return true;
65928
66138
  } catch {
65929
66139
  return false;
@@ -65961,13 +66171,13 @@ function shellQuote(value2) {
65961
66171
  }
65962
66172
  async function replaceFile(path4, content, mode) {
65963
66173
  const temp = `${path4}.${(0, import_node_crypto35.randomUUID)()}.tmp`;
65964
- await (0, import_promises37.writeFile)(temp, content, { mode });
65965
- await (0, import_promises37.rename)(temp, path4);
66174
+ await (0, import_promises38.writeFile)(temp, content, { mode });
66175
+ await (0, import_promises38.rename)(temp, path4);
65966
66176
  }
65967
66177
  async function replaceSymlink(path4, target) {
65968
66178
  const temp = `${path4}.${(0, import_node_crypto35.randomUUID)()}.tmp`;
65969
- await (0, import_promises37.symlink)(target, temp);
65970
- await (0, import_promises37.rename)(temp, path4);
66179
+ await (0, import_promises38.symlink)(target, temp);
66180
+ await (0, import_promises38.rename)(temp, path4);
65971
66181
  }
65972
66182
  async function installCommitAttribution(input2) {
65973
66183
  if (input2.platform === "win32") return null;
@@ -65977,8 +66187,8 @@ async function installCommitAttribution(input2) {
65977
66187
  const path4 = envValue(input2.env, "PATH").split(delimiter2).filter((entry) => entry.length > 0 && entry !== binDir).join(delimiter2);
65978
66188
  const realGit = await resolveCommandOnPath("git", { ...input2.env, PATH: path4 }, input2.platform);
65979
66189
  if (realGit === null) return null;
65980
- await (0, import_promises37.mkdir)(binDir, { recursive: true, mode: 493 });
65981
- await (0, import_promises37.mkdir)(hooksDir, { recursive: true, mode: 493 });
66190
+ await (0, import_promises38.mkdir)(binDir, { recursive: true, mode: 493 });
66191
+ await (0, import_promises38.mkdir)(hooksDir, { recursive: true, mode: 493 });
65982
66192
  await replaceFile((0, import_node_path43.join)(input2.dir, COMMIT_ATTRIBUTION_SCRIPT), commitAttributionScript(), 493);
65983
66193
  for (const hook of COMMIT_ATTRIBUTION_HOOKS) {
65984
66194
  await replaceSymlink((0, import_node_path43.join)(hooksDir, hook), (0, import_node_path43.join)("..", COMMIT_ATTRIBUTION_SCRIPT));
@@ -65995,7 +66205,7 @@ exec ${shellQuote(realGit)} -c core.hooksPath=${shellQuote(hooksDir)} "$@"
65995
66205
  env: { ...input2.env, PATH: path4 === "" ? binDir : `${binDir}${delimiter2}${path4}` },
65996
66206
  setCoAuthor: async (coAuthor) => {
65997
66207
  if (coAuthor === void 0) {
65998
- await (0, import_promises37.rm)(coAuthorPath, { force: true });
66208
+ await (0, import_promises38.rm)(coAuthorPath, { force: true });
65999
66209
  return;
66000
66210
  }
66001
66211
  const value2 = coAuthorTrailer(coAuthor).replace(/^Co-Authored-By: /, "");
@@ -66127,7 +66337,7 @@ var GIT_CREDENTIAL_QUIT = "quit=1\n";
66127
66337
 
66128
66338
  // src/capabilities/git/credential-server.ts
66129
66339
  var import_node_crypto36 = require("crypto");
66130
- var import_promises38 = require("fs/promises");
66340
+ var import_promises39 = require("fs/promises");
66131
66341
  var import_node_net2 = require("net");
66132
66342
 
66133
66343
  // src/capabilities/git/credential-socket.ts
@@ -66314,7 +66524,7 @@ async function startGitCredentialServer(options) {
66314
66524
  closing.abort();
66315
66525
  await new Promise((resolve16) => server.close(() => resolve16()));
66316
66526
  removeStaleEndpoint(options.endpoint);
66317
- await (0, import_promises38.rm)(options.tokenPath, { force: true });
66527
+ await (0, import_promises39.rm)(options.tokenPath, { force: true });
66318
66528
  }
66319
66529
  };
66320
66530
  }
@@ -66364,7 +66574,7 @@ function createGit(options) {
66364
66574
  // src/capabilities/github-proxy/certificates.ts
66365
66575
  var import_node_child_process16 = require("child_process");
66366
66576
  var import_node_crypto37 = require("crypto");
66367
- var import_promises39 = require("fs/promises");
66577
+ var import_promises40 = require("fs/promises");
66368
66578
  var import_node_path45 = require("path");
66369
66579
  var OPENSSL_TIMEOUT_MS = 1e4;
66370
66580
  var VALIDITY_DAYS = "30";
@@ -66402,13 +66612,13 @@ function openssl(args, cwd) {
66402
66612
  }
66403
66613
  async function createGitHubProxyCertificates(stateDir) {
66404
66614
  const work = (0, import_node_path45.join)(stateDir, "github-proxy");
66405
- await (0, import_promises39.rm)(work, { recursive: true, force: true });
66406
- await (0, import_promises39.mkdir)(work, { recursive: true, mode: 448 });
66615
+ await (0, import_promises40.rm)(work, { recursive: true, force: true });
66616
+ await (0, import_promises40.mkdir)(work, { recursive: true, mode: 448 });
66407
66617
  try {
66408
- await (0, import_promises39.writeFile)((0, import_node_path45.join)(work, "ca.cnf"), opensslConfig("Alan sandbox GitHub proxy CA"), {
66618
+ await (0, import_promises40.writeFile)((0, import_node_path45.join)(work, "ca.cnf"), opensslConfig("Alan sandbox GitHub proxy CA"), {
66409
66619
  mode: 384
66410
66620
  });
66411
- await (0, import_promises39.writeFile)((0, import_node_path45.join)(work, "leaf.cnf"), opensslConfig("github.com"), { mode: 384 });
66621
+ await (0, import_promises40.writeFile)((0, import_node_path45.join)(work, "leaf.cnf"), opensslConfig("github.com"), { mode: 384 });
66412
66622
  const curve = ["ecparam", "-name", "prime256v1", "-genkey", "-noout"];
66413
66623
  await openssl([...curve, "-out", "ca.key"], work);
66414
66624
  await openssl(
@@ -66432,19 +66642,19 @@ async function createGitHubProxyCertificates(stateDir) {
66432
66642
  work
66433
66643
  );
66434
66644
  const caPath = (0, import_node_path45.join)(stateDir, "github-ca.pem");
66435
- await (0, import_promises39.writeFile)(caPath, await (0, import_promises39.readFile)((0, import_node_path45.join)(work, "ca.pem")), { mode: 384 });
66645
+ await (0, import_promises40.writeFile)(caPath, await (0, import_promises40.readFile)((0, import_node_path45.join)(work, "ca.pem")), { mode: 384 });
66436
66646
  return {
66437
66647
  caPath,
66438
- leafKeyPem: await (0, import_promises39.readFile)((0, import_node_path45.join)(work, "leaf.key"), "utf8"),
66439
- leafCertPem: await (0, import_promises39.readFile)((0, import_node_path45.join)(work, "leaf.pem"), "utf8")
66648
+ leafKeyPem: await (0, import_promises40.readFile)((0, import_node_path45.join)(work, "leaf.key"), "utf8"),
66649
+ leafCertPem: await (0, import_promises40.readFile)((0, import_node_path45.join)(work, "leaf.pem"), "utf8")
66440
66650
  };
66441
66651
  } finally {
66442
- await (0, import_promises39.rm)(work, { recursive: true, force: true });
66652
+ await (0, import_promises40.rm)(work, { recursive: true, force: true });
66443
66653
  }
66444
66654
  }
66445
66655
 
66446
66656
  // src/capabilities/github-proxy/config.ts
66447
- var import_promises40 = require("fs/promises");
66657
+ var import_promises41 = require("fs/promises");
66448
66658
  var import_node_path46 = require("path");
66449
66659
  init_runtime_v2();
66450
66660
  var GITHUB_URL = "https://github.com/";
@@ -66461,10 +66671,10 @@ function withGhConfigKey(yaml, key, value2) {
66461
66671
  `;
66462
66672
  }
66463
66673
  async function configureGh(ghConfigDir, socketPath) {
66464
- await (0, import_promises40.mkdir)(ghConfigDir, { recursive: true, mode: 448 });
66674
+ await (0, import_promises41.mkdir)(ghConfigDir, { recursive: true, mode: 448 });
66465
66675
  const path4 = (0, import_node_path46.join)(ghConfigDir, "config.yml");
66466
- const current = await (0, import_promises40.readFile)(path4, "utf8").catch(() => "");
66467
- await (0, import_promises40.writeFile)(path4, withGhConfigKey(current, GH_SOCKET_KEY, socketPath), { mode: 384 });
66676
+ const current = await (0, import_promises41.readFile)(path4, "utf8").catch(() => "");
66677
+ await (0, import_promises41.writeFile)(path4, withGhConfigKey(current, GH_SOCKET_KEY, socketPath), { mode: 384 });
66468
66678
  }
66469
66679
  async function configureGit(input2, git) {
66470
66680
  const run2 = async (args, allowedExitCodes = [0]) => {
@@ -66477,13 +66687,15 @@ async function configureGit(input2, git) {
66477
66687
  }
66478
66688
  return output2;
66479
66689
  };
66480
- const rewrites = await run2(
66481
- ["config", "--global", "--get-regexp", "^url\\..*\\.insteadof$", `^${GITHUB_URL}`],
66482
- [0, 1]
66483
- );
66484
- for (const line of rewrites.stdout.split("\n")) {
66485
- const key = line.split(" ")[0];
66486
- if (key) await run2(["config", "--global", "--unset-all", key, `^${GITHUB_URL}`], [0, 5]);
66690
+ for (const githubUrl of [GITHUB_URL, "https://www.github.com/"]) {
66691
+ const rewrites = await run2(
66692
+ ["config", "--global", "--get-regexp", "^url\\..*\\.insteadof$", `^${githubUrl}`],
66693
+ [0, 1]
66694
+ );
66695
+ for (const line of rewrites.stdout.split("\n")) {
66696
+ const key = line.split(" ")[0];
66697
+ if (key) await run2(["config", "--global", "--unset-all", key, `^${githubUrl}`], [0, 5]);
66698
+ }
66487
66699
  }
66488
66700
  await run2(["config", "--global", `http.${GITHUB_URL}.proxy`, git.proxyUrl]);
66489
66701
  await run2(["config", "--global", `http.${GITHUB_URL}.sslCAInfo`, git.caPath]);
@@ -66494,7 +66706,7 @@ async function configureGitHubProxyClients(input2) {
66494
66706
  }
66495
66707
 
66496
66708
  // src/capabilities/github-proxy/server.ts
66497
- var import_promises41 = require("fs/promises");
66709
+ var import_promises42 = require("fs/promises");
66498
66710
  var import_node_http5 = require("http");
66499
66711
  var import_node_tls = require("tls");
66500
66712
  init_runtime_v2();
@@ -66636,7 +66848,7 @@ async function startGitHubProxy(options) {
66636
66848
  });
66637
66849
  removeStaleEndpoint(options.socketPath);
66638
66850
  await listen(gh, options.socketPath);
66639
- await (0, import_promises41.chmod)(options.socketPath, 384);
66851
+ await (0, import_promises42.chmod)(options.socketPath, 384);
66640
66852
  const git = options.certificates === null ? null : await startGitListener(options.certificates, relay);
66641
66853
  options.log.info("github_proxy.listening", {
66642
66854
  socketPath: options.socketPath,
@@ -66655,7 +66867,7 @@ async function startGitHubProxy(options) {
66655
66867
 
66656
66868
  // src/capabilities/mcp-config/mcp-config.ts
66657
66869
  var import_node_crypto38 = require("crypto");
66658
- var import_promises42 = require("fs/promises");
66870
+ var import_promises43 = require("fs/promises");
66659
66871
  var import_node_path47 = require("path");
66660
66872
 
66661
66873
  // ../../node_modules/smol-toml/dist/error.js
@@ -67715,7 +67927,7 @@ function isCredentialFreeAlanEntry(entry, endpoint) {
67715
67927
  }
67716
67928
  async function isInstalled(cli, home) {
67717
67929
  try {
67718
- return (await (0, import_promises42.stat)((0, import_node_path47.join)(home, cli.guardDir))).isDirectory();
67930
+ return (await (0, import_promises43.stat)((0, import_node_path47.join)(home, cli.guardDir))).isDirectory();
67719
67931
  } catch (error62) {
67720
67932
  if (errorCode2(error62) === "ENOENT") return false;
67721
67933
  throw error62;
@@ -67723,7 +67935,7 @@ async function isInstalled(cli, home) {
67723
67935
  }
67724
67936
  async function readText3(path4) {
67725
67937
  try {
67726
- return await (0, import_promises42.readFile)(path4, "utf8");
67938
+ return await (0, import_promises43.readFile)(path4, "utf8");
67727
67939
  } catch (error62) {
67728
67940
  if (errorCode2(error62) === "ENOENT") return null;
67729
67941
  throw error62;
@@ -67750,10 +67962,10 @@ async function readConfig(cli, home) {
67750
67962
  async function writeConfig(path4, text3) {
67751
67963
  const temporary = `${path4}.alan-${(0, import_node_crypto38.randomUUID)()}.tmp`;
67752
67964
  try {
67753
- await (0, import_promises42.writeFile)(temporary, text3, { encoding: "utf8", mode: 384, flag: "wx" });
67754
- await (0, import_promises42.rename)(temporary, path4);
67965
+ await (0, import_promises43.writeFile)(temporary, text3, { encoding: "utf8", mode: 384, flag: "wx" });
67966
+ await (0, import_promises43.rename)(temporary, path4);
67755
67967
  } finally {
67756
- await (0, import_promises42.rm)(temporary, { force: true });
67968
+ await (0, import_promises43.rm)(temporary, { force: true });
67757
67969
  }
67758
67970
  }
67759
67971
  async function editCli(cli, home, endpoint, edit) {
@@ -67831,7 +68043,7 @@ async function inspectAlanMcp(options) {
67831
68043
  }
67832
68044
 
67833
68045
  // src/capabilities/models/opencode-models.ts
67834
- var import_promises43 = require("fs/promises");
68046
+ var import_promises44 = require("fs/promises");
67835
68047
  var import_node_path48 = require("path");
67836
68048
  init_runtime_v2();
67837
68049
  init_zod();
@@ -68147,7 +68359,7 @@ async function readOpenCodeCatalogueCache(env) {
68147
68359
  const home = env.HOME?.trim();
68148
68360
  const cacheHome = env.XDG_CACHE_HOME?.trim() || (home ? (0, import_node_path48.join)(home, ".cache") : "");
68149
68361
  if (cacheHome === "") return null;
68150
- const text3 = await (0, import_promises43.readFile)((0, import_node_path48.join)(cacheHome, ...CATALOGUE_CACHE_SEGMENTS), "utf8").catch(
68362
+ const text3 = await (0, import_promises44.readFile)((0, import_node_path48.join)(cacheHome, ...CATALOGUE_CACHE_SEGMENTS), "utf8").catch(
68151
68363
  () => void 0
68152
68364
  );
68153
68365
  if (text3 === void 0) return null;
@@ -68266,7 +68478,7 @@ async function discoverModels(backendKind, executable, env, capture) {
68266
68478
  }
68267
68479
 
68268
68480
  // src/capabilities/models/opencode-entitlement.ts
68269
- var import_promises44 = require("fs/promises");
68481
+ var import_promises45 = require("fs/promises");
68270
68482
  var import_node_os6 = require("os");
68271
68483
  var import_node_path49 = require("path");
68272
68484
  init_agent2();
@@ -68276,7 +68488,7 @@ async function readOpenCodeZenCredential(env) {
68276
68488
  const injected = env.OPENCODE_AUTH_CONTENT?.trim();
68277
68489
  if (injected) return readZenCredentialFromAuthDocument(injected);
68278
68490
  const dataHome = env.XDG_DATA_HOME?.trim() || (0, import_node_path49.join)(env.HOME?.trim() || (0, import_node_os6.homedir)(), ".local", "share");
68279
- const document2 = await (0, import_promises44.readFile)((0, import_node_path49.join)(dataHome, "opencode", "auth.json"), "utf8").catch(
68491
+ const document2 = await (0, import_promises45.readFile)((0, import_node_path49.join)(dataHome, "opencode", "auth.json"), "utf8").catch(
68280
68492
  () => void 0
68281
68493
  );
68282
68494
  return readZenCredentialFromAuthDocument(document2);
@@ -68719,7 +68931,7 @@ function nextAlanBoundary(entry, inFlightFrom) {
68719
68931
  }
68720
68932
 
68721
68933
  // src/capabilities/native-ingest/pass.ts
68722
- var import_promises46 = require("fs/promises");
68934
+ var import_promises47 = require("fs/promises");
68723
68935
 
68724
68936
  // src/capabilities/native-ingest/ports.ts
68725
68937
  var NativeRequestFailure = class extends Error {
@@ -68857,7 +69069,7 @@ function reconcileTranscriptIdentity(entry, transcriptPath, identity, size) {
68857
69069
 
68858
69070
  // src/capabilities/native-ingest/transcript-window.ts
68859
69071
  var import_node_crypto39 = require("crypto");
68860
- var import_promises45 = require("fs/promises");
69072
+ var import_promises46 = require("fs/promises");
68861
69073
  init_acp2();
68862
69074
  init_claude();
68863
69075
  init_codex();
@@ -68912,7 +69124,7 @@ async function findRecordEnd(handle, from, size) {
68912
69124
  return null;
68913
69125
  }
68914
69126
  async function readTranscriptWindow(path4, offset, limits) {
68915
- const handle = await (0, import_promises45.open)(path4, "r");
69127
+ const handle = await (0, import_promises46.open)(path4, "r");
68916
69128
  try {
68917
69129
  const stats = await handle.stat({ bigint: true });
68918
69130
  const size = Number(stats.size);
@@ -69379,7 +69591,7 @@ async function runPass(ctx, worker) {
69379
69591
  });
69380
69592
  if (signal.ending) ctx.log.info("native_ingest.closed", workerFields(worker));
69381
69593
  }
69382
- const current = await (0, import_promises46.stat)(worker.latest.transcriptPath).catch(() => void 0);
69594
+ const current = await (0, import_promises47.stat)(worker.latest.transcriptPath).catch(() => void 0);
69383
69595
  return { grewDuringPass: current !== void 0 && current.size > state.lastSize };
69384
69596
  }
69385
69597
 
@@ -69912,7 +70124,7 @@ function captureProbe(command, args, options) {
69912
70124
  }
69913
70125
 
69914
70126
  // src/capabilities/providers/inventory.ts
69915
- var import_promises47 = require("fs/promises");
70127
+ var import_promises48 = require("fs/promises");
69916
70128
  var import_node_os7 = require("os");
69917
70129
  init_runtime_v2();
69918
70130
 
@@ -70374,8 +70586,8 @@ async function executablesFingerprint(env, platform3) {
70374
70586
  const executable = await resolveProviderExecutable(provider4, env, platform3);
70375
70587
  if (executable === null) return `${provider4.backendKind}:-`;
70376
70588
  try {
70377
- const target = await (0, import_promises47.realpath)(executable);
70378
- const { size, mtimeMs } = await (0, import_promises47.stat)(target);
70589
+ const target = await (0, import_promises48.realpath)(executable);
70590
+ const { size, mtimeMs } = await (0, import_promises48.stat)(target);
70379
70591
  return `${provider4.backendKind}:${target}:${size}:${mtimeMs}`;
70380
70592
  } catch {
70381
70593
  return `${provider4.backendKind}:${executable}:?`;
@@ -70684,7 +70896,7 @@ async function openCliEnvironment(options) {
70684
70896
 
70685
70897
  // src/capabilities/providers/managed.ts
70686
70898
  var import_node_crypto41 = require("crypto");
70687
- var import_promises48 = require("fs/promises");
70899
+ var import_promises49 = require("fs/promises");
70688
70900
  var import_node_path60 = require("path");
70689
70901
  init_process();
70690
70902
  init_zod();
@@ -70706,7 +70918,7 @@ async function cleanFailedInstall(staged, error62) {
70706
70918
  throw new Error(`${error62.message}; retained staging directory: ${staged}`, { cause: error62 });
70707
70919
  }
70708
70920
  try {
70709
- await (0, import_promises48.rm)(staged, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
70921
+ await (0, import_promises49.rm)(staged, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
70710
70922
  } catch (cleanupError) {
70711
70923
  const message2 = error62 instanceof Error ? error62.message : String(error62);
70712
70924
  throw new AggregateError(
@@ -70719,7 +70931,7 @@ async function cleanFailedInstall(staged, error62) {
70719
70931
  }
70720
70932
  async function readManagedProviderVersion(file2, backendKind) {
70721
70933
  try {
70722
- const selected = selectedSchema.parse(JSON.parse(await (0, import_promises48.readFile)(file2, "utf8")));
70934
+ const selected = selectedSchema.parse(JSON.parse(await (0, import_promises49.readFile)(file2, "utf8")));
70723
70935
  const version2 = selected[backendKind];
70724
70936
  return version2 !== void 0 && VERSION.test(version2) ? version2 : null;
70725
70937
  } catch {
@@ -70786,7 +70998,7 @@ function selection(root, backendKind, version2) {
70786
70998
  };
70787
70999
  }
70788
71000
  async function runnable(file2) {
70789
- return (0, import_promises48.stat)(file2).then(
71001
+ return (0, import_promises49.stat)(file2).then(
70790
71002
  (value2) => value2.isFile(),
70791
71003
  () => false
70792
71004
  );
@@ -70829,13 +71041,13 @@ function createManagedProviderClis(options) {
70829
71041
  return next;
70830
71042
  };
70831
71043
  const persist = async () => {
70832
- await (0, import_promises48.mkdir)(options.root, { recursive: true, mode: 448 });
71044
+ await (0, import_promises49.mkdir)(options.root, { recursive: true, mode: 448 });
70833
71045
  const staged = `${file2}.${(0, import_node_crypto41.randomUUID)()}`;
70834
71046
  try {
70835
- await (0, import_promises48.writeFile)(staged, JSON.stringify(state), { mode: 384 });
70836
- await (0, import_promises48.rename)(staged, file2);
71047
+ await (0, import_promises49.writeFile)(staged, JSON.stringify(state), { mode: 384 });
71048
+ await (0, import_promises49.rename)(staged, file2);
70837
71049
  } finally {
70838
- await (0, import_promises48.rm)(staged, { force: true });
71050
+ await (0, import_promises49.rm)(staged, { force: true });
70839
71051
  }
70840
71052
  };
70841
71053
  const activate = async (backendKind, version2, signal) => {
@@ -70858,7 +71070,7 @@ function createManagedProviderClis(options) {
70858
71070
  return {
70859
71071
  selectionFile: file2,
70860
71072
  load: async () => {
70861
- const raw = await (0, import_promises48.readFile)(file2, "utf8").catch((error62) => {
71073
+ const raw = await (0, import_promises49.readFile)(file2, "utf8").catch((error62) => {
70862
71074
  if (error62 instanceof Error && "code" in error62 && error62.code === "ENOENT") return "{}";
70863
71075
  throw error62;
70864
71076
  });
@@ -70866,7 +71078,7 @@ function createManagedProviderClis(options) {
70866
71078
  try {
70867
71079
  parsed = selectedSchema.parse(JSON.parse(raw));
70868
71080
  } catch {
70869
- await (0, import_promises48.rename)(file2, `${file2}.invalid.${(0, import_node_crypto41.randomUUID)()}`).catch(() => void 0);
71081
+ await (0, import_promises49.rename)(file2, `${file2}.invalid.${(0, import_node_crypto41.randomUUID)()}`).catch(() => void 0);
70870
71082
  return;
70871
71083
  }
70872
71084
  for (const [backendKind, version2] of Object.entries(parsed)) {
@@ -70886,7 +71098,7 @@ function createManagedProviderClis(options) {
70886
71098
  const groups = await Promise.all(
70887
71099
  Object.keys(PACKAGES).map(async (backendKind) => {
70888
71100
  const directory = (0, import_node_path60.join)(options.root, "versions", backendKind);
70889
- const versions = await (0, import_promises48.readdir)(directory).catch((error62) => {
71101
+ const versions = await (0, import_promises49.readdir)(directory).catch((error62) => {
70890
71102
  if (error62 instanceof Error && "code" in error62 && error62.code === "ENOENT") return [];
70891
71103
  throw error62;
70892
71104
  });
@@ -70924,7 +71136,7 @@ function createManagedProviderClis(options) {
70924
71136
  const target = (0, import_node_path60.join)(options.root, "versions", backendKind, exact);
70925
71137
  const existing = selection(options.root, backendKind, exact);
70926
71138
  if (!await runnable(existing.executable) || !await options.probe(existing.executable, backendKind, signal)) {
70927
- await (0, import_promises48.mkdir)((0, import_node_path60.dirname)(target), { recursive: true, mode: 448 });
71139
+ await (0, import_promises49.mkdir)((0, import_node_path60.dirname)(target), { recursive: true, mode: 448 });
70928
71140
  const staged = `${target}.${(0, import_node_crypto41.randomUUID)()}`;
70929
71141
  try {
70930
71142
  await options.installPackage(provider4.name, exact, staged, provider4.command, signal);
@@ -70933,8 +71145,8 @@ function createManagedProviderClis(options) {
70933
71145
  throw new Error(`${backendKind}@${exact} failed its executable probe`);
70934
71146
  }
70935
71147
  signal?.throwIfAborted();
70936
- await (0, import_promises48.rm)(target, { recursive: true, force: true });
70937
- await (0, import_promises48.rename)(staged, target);
71148
+ await (0, import_promises49.rm)(target, { recursive: true, force: true });
71149
+ await (0, import_promises49.rename)(staged, target);
70938
71150
  } catch (error62) {
70939
71151
  await cleanFailedInstall(staged, error62);
70940
71152
  }
@@ -71043,23 +71255,23 @@ ${help.stderr}`);
71043
71255
  }
71044
71256
 
71045
71257
  // src/capabilities/skills/legacy-cleanup.ts
71046
- var import_promises49 = require("fs/promises");
71258
+ var import_promises50 = require("fs/promises");
71047
71259
  var import_node_path61 = require("path");
71048
71260
  var LEGACY_FOLDER = /--(?:alan-(?:production|staging|local(?:-[0-9a-f]{12})?)|[0-9a-f]{8})$/;
71049
71261
  var MANAGED_MARKER = ".alan-managed.json";
71050
71262
  var COMPATIBILITY_MARKER = ".alan-compatibility.json";
71051
71263
  async function listEntries(directory) {
71052
- return (0, import_promises49.readdir)(directory, { withFileTypes: true }).catch(() => []);
71264
+ return (0, import_promises50.readdir)(directory, { withFileTypes: true }).catch(() => []);
71053
71265
  }
71054
71266
  async function isRegularFile(path4) {
71055
- return (0, import_promises49.lstat)(path4).then(
71267
+ return (0, import_promises50.lstat)(path4).then(
71056
71268
  (stats) => stats.isFile(),
71057
71269
  () => false
71058
71270
  );
71059
71271
  }
71060
71272
  async function isMissing(path4) {
71061
71273
  try {
71062
- await (0, import_promises49.lstat)(path4);
71274
+ await (0, import_promises50.lstat)(path4);
71063
71275
  return false;
71064
71276
  } catch (error62) {
71065
71277
  return errnoCode(error62) === "ENOENT";
@@ -71067,15 +71279,15 @@ async function isMissing(path4) {
71067
71279
  }
71068
71280
  async function removeLink(path4) {
71069
71281
  try {
71070
- await (0, import_promises49.unlink)(path4);
71282
+ await (0, import_promises50.unlink)(path4);
71071
71283
  } catch (error62) {
71072
71284
  const code = errnoCode(error62);
71073
71285
  if (code !== "EPERM" && code !== "EISDIR") throw error62;
71074
- await (0, import_promises49.rmdir)(path4);
71286
+ await (0, import_promises50.rmdir)(path4);
71075
71287
  }
71076
71288
  }
71077
71289
  async function isOrphanedLegacyLink(agentsDir, path4, removed) {
71078
- const target = await (0, import_promises49.readlink)(path4).catch(() => null);
71290
+ const target = await (0, import_promises50.readlink)(path4).catch(() => null);
71079
71291
  if (target === null) return false;
71080
71292
  const absolute = (0, import_node_path61.resolve)((0, import_node_path61.dirname)(path4), target);
71081
71293
  return (0, import_node_path61.dirname)(absolute) === agentsDir && (removed.has(absolute) || LEGACY_FOLDER.test((0, import_node_path61.basename)(absolute))) && await isMissing(absolute);
@@ -71085,7 +71297,7 @@ async function removeLegacyPackages(agentsDir, attempt2) {
71085
71297
  for (const entry of await listEntries(agentsDir)) {
71086
71298
  const path4 = (0, import_node_path61.join)(agentsDir, entry.name);
71087
71299
  if (!entry.isDirectory() || !await isRegularFile((0, import_node_path61.join)(path4, MANAGED_MARKER))) continue;
71088
- if (await attempt2(path4, () => (0, import_promises49.rm)(path4, { recursive: true, force: true }))) removed.push(path4);
71300
+ if (await attempt2(path4, () => (0, import_promises50.rm)(path4, { recursive: true, force: true }))) removed.push(path4);
71089
71301
  }
71090
71302
  return removed;
71091
71303
  }
@@ -71099,7 +71311,7 @@ async function removeLegacyClaudeEntries(claudeDir, agentsDir, removedPackages,
71099
71311
  for (const entry of await listEntries(claudeDir)) {
71100
71312
  const path4 = (0, import_node_path61.join)(claudeDir, entry.name);
71101
71313
  if (!await isLegacyClaudeEntry(agentsDir, path4, entry, removedSet)) continue;
71102
- const remove = entry.isSymbolicLink() ? () => removeLink(path4) : () => (0, import_promises49.rm)(path4, { recursive: true, force: true });
71314
+ const remove = entry.isSymbolicLink() ? () => removeLink(path4) : () => (0, import_promises50.rm)(path4, { recursive: true, force: true });
71103
71315
  if (await attempt2(path4, remove)) removed.push(path4);
71104
71316
  }
71105
71317
  return removed;
@@ -71124,18 +71336,18 @@ async function removeLegacySkillFolders(home) {
71124
71336
  attempt2
71125
71337
  );
71126
71338
  const profiles = (0, import_node_path61.join)(home, ".alan", "skills", "profiles");
71127
- const profilesRemoved = !await isMissing(profiles) && await attempt2(profiles, () => (0, import_promises49.rm)(profiles, { recursive: true, force: true }));
71339
+ const profilesRemoved = !await isMissing(profiles) && await attempt2(profiles, () => (0, import_promises50.rm)(profiles, { recursive: true, force: true }));
71128
71340
  return { packages, links, profilesRemoved, failed };
71129
71341
  }
71130
71342
 
71131
71343
  // src/capabilities/skills/local-preview.ts
71132
- var import_promises54 = require("fs/promises");
71344
+ var import_promises55 = require("fs/promises");
71133
71345
  var import_node_path66 = __toESM(require("path"));
71134
71346
 
71135
71347
  // ../shared/src/node/skill-package.ts
71136
71348
  var import_node_buffer = require("buffer");
71137
71349
  var import_node_crypto42 = require("crypto");
71138
- var import_promises50 = require("fs/promises");
71350
+ var import_promises51 = require("fs/promises");
71139
71351
  var import_node_path62 = require("path");
71140
71352
  var import_yaml = __toESM(require_dist(), 1);
71141
71353
  init_contracts();
@@ -71242,11 +71454,11 @@ async function readSkillPackageFile(packageRoot, path4, expectedSha256) {
71242
71454
  if (!normalizedPath || normalizedPath !== path4 || normalizedPath.includes("\\") || components.some((component) => !component || component === "." || component === "..")) {
71243
71455
  throw new SkillPackageError("INVALID_PATH", `Invalid Skill package path: ${path4}`, path4);
71244
71456
  }
71245
- const absolutePath = await (0, import_promises50.realpath)((0, import_node_path62.resolve)(root, ...components)).catch(() => null);
71457
+ const absolutePath = await (0, import_promises51.realpath)((0, import_node_path62.resolve)(root, ...components)).catch(() => null);
71246
71458
  if (!absolutePath || normalizeRelativePath(root, absolutePath) !== normalizedPath) {
71247
71459
  throw new SkillPackageError("INVALID_PATH", `Skill package file was not found: ${path4}`, path4);
71248
71460
  }
71249
- const entryStat = await (0, import_promises50.lstat)(absolutePath);
71461
+ const entryStat = await (0, import_promises51.lstat)(absolutePath);
71250
71462
  if (!entryStat.isFile()) {
71251
71463
  throw new SkillPackageError(
71252
71464
  "SPECIAL_FILE_BLOCKED",
@@ -71267,11 +71479,11 @@ async function readSkillPackageFile(packageRoot, path4, expectedSha256) {
71267
71479
  return { file: read.manifest, bytes: read.bytes };
71268
71480
  }
71269
71481
  async function requirePackageRoot(packageRoot) {
71270
- const root = await (0, import_promises50.realpath)((0, import_node_path62.resolve)(packageRoot)).catch(() => null);
71482
+ const root = await (0, import_promises51.realpath)((0, import_node_path62.resolve)(packageRoot)).catch(() => null);
71271
71483
  if (!root) {
71272
71484
  throw new SkillPackageError("INVALID_PACKAGE_ROOT", "Skill package directory does not exist");
71273
71485
  }
71274
- const rootStat = await (0, import_promises50.lstat)(root);
71486
+ const rootStat = await (0, import_promises51.lstat)(root);
71275
71487
  if (!rootStat.isDirectory()) {
71276
71488
  throw new SkillPackageError("INVALID_PACKAGE_ROOT", "Skill package root must be a directory");
71277
71489
  }
@@ -71297,12 +71509,12 @@ async function walkPackage(root, ignoredPaths) {
71297
71509
  }
71298
71510
  return files;
71299
71511
  async function walkDirectory(directory) {
71300
- const entries = await (0, import_promises50.readdir)(directory, { withFileTypes: true });
71512
+ const entries = await (0, import_promises51.readdir)(directory, { withFileTypes: true });
71301
71513
  for (const entry of entries) {
71302
71514
  const absolutePath = (0, import_node_path62.resolve)(directory, entry.name);
71303
71515
  const normalizedPath = normalizeRelativePath(root, absolutePath);
71304
71516
  if (isIgnored(normalizedPath, entry.name, entry.isDirectory(), ignored2)) continue;
71305
- const entryStat = await (0, import_promises50.lstat)(absolutePath);
71517
+ const entryStat = await (0, import_promises51.lstat)(absolutePath);
71306
71518
  if (entryStat.isSymbolicLink()) {
71307
71519
  throw new SkillPackageError(
71308
71520
  "SYMLINK_BLOCKED",
@@ -71428,7 +71640,7 @@ function isSecretPath(path4) {
71428
71640
  return name.endsWith(".private-key.pem") || name.endsWith(".private-key.key");
71429
71641
  }
71430
71642
  async function readPackageFile(file2) {
71431
- const bytes = await (0, import_promises50.readFile)(file2.absolutePath);
71643
+ const bytes = await (0, import_promises51.readFile)(file2.absolutePath);
71432
71644
  return {
71433
71645
  bytes,
71434
71646
  manifest: {
@@ -71613,13 +71825,13 @@ function uint642(value2) {
71613
71825
 
71614
71826
  // src/capabilities/skills/local-sources.ts
71615
71827
  var import_node_crypto44 = require("crypto");
71616
- var import_promises52 = require("fs/promises");
71828
+ var import_promises53 = require("fs/promises");
71617
71829
  var import_node_path64 = __toESM(require("path"));
71618
71830
  init_type_guards();
71619
71831
 
71620
71832
  // src/capabilities/skills/local-scan.ts
71621
71833
  var import_node_crypto43 = require("crypto");
71622
- var import_promises51 = require("fs/promises");
71834
+ var import_promises52 = require("fs/promises");
71623
71835
  var import_node_path63 = __toESM(require("path"));
71624
71836
  var MAX_CANDIDATES = 2e3;
71625
71837
  var MAX_DIAGNOSTICS = 100;
@@ -71740,7 +71952,7 @@ function invalid(resolvedRoot, name, error62) {
71740
71952
  }
71741
71953
  async function scanRootAsPackage(pass, resolvedRoot) {
71742
71954
  if (!await exists3(import_node_path63.default.join(resolvedRoot.directory, "SKILL.md"))) return null;
71743
- const canonical = await (0, import_promises51.realpath)(resolvedRoot.directory).catch(() => resolvedRoot.directory);
71955
+ const canonical = await (0, import_promises52.realpath)(resolvedRoot.directory).catch(() => resolvedRoot.directory);
71744
71956
  if (isManaged(pass, canonical)) return { candidates: [], diagnostics: [], incomplete: false };
71745
71957
  try {
71746
71958
  const inspected = await inspectCached(pass, canonical, null);
@@ -71770,7 +71982,7 @@ async function scanRoot(pass, resolvedRoot) {
71770
71982
  if (asPackage !== null) return asPackage;
71771
71983
  let entries;
71772
71984
  try {
71773
- entries = await (0, import_promises51.readdir)(resolvedRoot.directory, { withFileTypes: true });
71985
+ entries = await (0, import_promises52.readdir)(resolvedRoot.directory, { withFileTypes: true });
71774
71986
  } catch (error62) {
71775
71987
  const code = errnoCode(error62);
71776
71988
  if (code === "ENOENT" || code === "ENOTDIR") {
@@ -71788,7 +72000,7 @@ async function scanRoot(pass, resolvedRoot) {
71788
72000
  incomplete: true
71789
72001
  };
71790
72002
  }
71791
- const canonicalRoot = await (0, import_promises51.realpath)(resolvedRoot.directory).catch(() => resolvedRoot.directory);
72003
+ const canonicalRoot = await (0, import_promises52.realpath)(resolvedRoot.directory).catch(() => resolvedRoot.directory);
71792
72004
  const scan = { candidates: [], diagnostics: [], incomplete: false };
71793
72005
  for (const entry of entries) {
71794
72006
  if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;
@@ -71800,7 +72012,7 @@ async function scanRoot(pass, resolvedRoot) {
71800
72012
  }
71801
72013
  async function scanEntry(pass, resolvedRoot, canonicalRoot, name) {
71802
72014
  const rootLabel = resolvedRoot.root.label;
71803
- const canonical = await (0, import_promises51.realpath)(import_node_path63.default.join(resolvedRoot.directory, name)).catch(() => null);
72015
+ const canonical = await (0, import_promises52.realpath)(import_node_path63.default.join(resolvedRoot.directory, name)).catch(() => null);
71804
72016
  if (canonical === null) {
71805
72017
  const message2 = `Could not resolve Skill ${name}`;
71806
72018
  return { kind: "diagnostic", diagnostic: { code: "SOURCE_UNREADABLE", message: message2, rootLabel } };
@@ -71885,12 +72097,12 @@ function deduplicateByContent(candidates2) {
71885
72097
  async function fingerprintPackage(root) {
71886
72098
  const hash2 = (0, import_node_crypto43.createHash)("sha256").update("alan-skill-stat-fingerprint-v1\0");
71887
72099
  const visit2 = async (directory, relativeDirectory) => {
71888
- const entries = await (0, import_promises51.readdir)(directory, { withFileTypes: true });
72100
+ const entries = await (0, import_promises52.readdir)(directory, { withFileTypes: true });
71889
72101
  entries.sort((left, right) => Buffer.compare(Buffer.from(left.name), Buffer.from(right.name)));
71890
72102
  for (const entry of entries) {
71891
72103
  const relative6 = relativeDirectory ? `${relativeDirectory}/${entry.name}` : entry.name;
71892
72104
  const absolute = import_node_path63.default.join(directory, entry.name);
71893
- const metadata = await (0, import_promises51.lstat)(absolute);
72105
+ const metadata = await (0, import_promises52.lstat)(absolute);
71894
72106
  const kind = entryKind(entry);
71895
72107
  hash2.update(relative6.normalize("NFC")).update(`\0${kind}\0${metadata.size}\0${metadata.mtimeMs}\0${metadata.mode & 511}\0`);
71896
72108
  if (entry.isDirectory()) await visit2(absolute, relative6);
@@ -71906,7 +72118,7 @@ function entryKind(entry) {
71906
72118
  }
71907
72119
  async function canonicalDirectories(directories) {
71908
72120
  const canonical = await Promise.all(
71909
- directories.map((directory) => (0, import_promises51.realpath)(directory).catch(() => directory))
72121
+ directories.map((directory) => (0, import_promises52.realpath)(directory).catch(() => directory))
71910
72122
  );
71911
72123
  return [...new Set(canonical)];
71912
72124
  }
@@ -71919,7 +72131,7 @@ function isWithinDirectory2(parent, candidate) {
71919
72131
  }
71920
72132
  async function exists3(candidate) {
71921
72133
  try {
71922
- await (0, import_promises51.access)(candidate);
72134
+ await (0, import_promises52.access)(candidate);
71923
72135
  return true;
71924
72136
  } catch {
71925
72137
  return false;
@@ -71927,7 +72139,7 @@ async function exists3(candidate) {
71927
72139
  }
71928
72140
  async function isDirectory3(candidate) {
71929
72141
  try {
71930
- return (await (0, import_promises51.lstat)(candidate)).isDirectory();
72142
+ return (await (0, import_promises52.lstat)(candidate)).isDirectory();
71931
72143
  } catch {
71932
72144
  return false;
71933
72145
  }
@@ -72015,7 +72227,7 @@ async function resolveLocalScanInput(home, context, mode) {
72015
72227
  async function readSkillSourceConfig(home) {
72016
72228
  let content;
72017
72229
  try {
72018
- content = await (0, import_promises52.readFile)(skillSourceConfigPath(home), "utf8");
72230
+ content = await (0, import_promises53.readFile)(skillSourceConfigPath(home), "utf8");
72019
72231
  } catch (error62) {
72020
72232
  if (errnoCode(error62) !== "ENOENT") {
72021
72233
  return { kind: "invalid_config", diagnostic: "~/.alan/config.toml could not be read" };
@@ -72132,7 +72344,7 @@ async function scanLocalSkills(home, context, cache2, mode = "incremental", mana
72132
72344
  }
72133
72345
 
72134
72346
  // src/capabilities/skills/store.ts
72135
- var import_promises53 = require("fs/promises");
72347
+ var import_promises54 = require("fs/promises");
72136
72348
  var import_node_path65 = require("path");
72137
72349
 
72138
72350
  // ../shared/src/node/alan-skill-identity.ts
@@ -72203,7 +72415,7 @@ function writeLocalSkills(layout, file2) {
72203
72415
  async function isLocalSkillCurrent(entry, contentHash, ignoredPaths) {
72204
72416
  if (entry.contentHash !== contentHash) return false;
72205
72417
  try {
72206
- if (await (0, import_promises53.realpath)(entry.path) !== entry.path) return false;
72418
+ if (await (0, import_promises54.realpath)(entry.path) !== entry.path) return false;
72207
72419
  const inspected = await inspectSkillPackage(entry.path, { expectedName: null, ignoredPaths });
72208
72420
  return inspected.contentHash === contentHash;
72209
72421
  } catch {
@@ -72218,7 +72430,7 @@ async function resolveLocalSkill(local, invocation) {
72218
72430
  }
72219
72431
  async function hasSkillFile(directory) {
72220
72432
  try {
72221
- return (await (0, import_promises53.stat)((0, import_node_path65.join)(directory, "SKILL.md"))).isFile();
72433
+ return (await (0, import_promises54.stat)((0, import_node_path65.join)(directory, "SKILL.md"))).isFile();
72222
72434
  } catch {
72223
72435
  return false;
72224
72436
  }
@@ -72275,7 +72487,7 @@ async function resolveSkillInvocations(layout, invocations, baked = "any") {
72275
72487
  async function nativeCandidates(layout) {
72276
72488
  const nativeDir = layout.nativeDir;
72277
72489
  if (nativeDir === null) return [];
72278
- const entries = await (0, import_promises53.readdir)(nativeDir, { withFileTypes: true }).catch(() => []);
72490
+ const entries = await (0, import_promises54.readdir)(nativeDir, { withFileTypes: true }).catch(() => []);
72279
72491
  return entries.filter((entry) => entry.isDirectory() || entry.isSymbolicLink()).map((entry) => ({ directory: (0, import_node_path65.join)(nativeDir, entry.name) }));
72280
72492
  }
72281
72493
  async function availableSkillIndex(layout, sources = { synced: true, native: true }) {
@@ -72373,7 +72585,7 @@ async function readLocalSkillFile(layout, ref) {
72373
72585
  }
72374
72586
  async function isDirectory4(candidate) {
72375
72587
  try {
72376
- return (await (0, import_promises54.stat)(candidate)).isDirectory();
72588
+ return (await (0, import_promises55.stat)(candidate)).isDirectory();
72377
72589
  } catch {
72378
72590
  return false;
72379
72591
  }
@@ -72386,21 +72598,21 @@ async function addSkillSource(home, input2) {
72386
72598
  return { state: "invalid", diagnostic: `${sourcePath} is not a folder` };
72387
72599
  }
72388
72600
  const configPath = skillSourceConfigPath(home);
72389
- await (0, import_promises54.mkdir)(import_node_path66.default.dirname(configPath), { recursive: true, mode: 448 });
72390
- await (0, import_promises54.writeFile)(configPath, DEFAULT_SKILL_CONFIG, { flag: "wx", mode: 384 }).catch(
72601
+ await (0, import_promises55.mkdir)(import_node_path66.default.dirname(configPath), { recursive: true, mode: 448 });
72602
+ await (0, import_promises55.writeFile)(configPath, DEFAULT_SKILL_CONFIG, { flag: "wx", mode: 384 }).catch(
72391
72603
  (error62) => {
72392
72604
  if (errnoCode(error62) !== "EEXIST") throw error62;
72393
72605
  }
72394
72606
  );
72395
72607
  const loaded = await readSkillSourceConfig(home);
72396
72608
  if (loaded.kind === "invalid_config") return { state: "invalid", diagnostic: loaded.diagnostic };
72397
- const canonical = await (0, import_promises54.realpath)(sourcePath).catch(() => sourcePath);
72609
+ const canonical = await (0, import_promises55.realpath)(sourcePath).catch(() => sourcePath);
72398
72610
  for (const source of loaded.config.sources) {
72399
- if (await (0, import_promises54.realpath)(source.path).catch(() => source.path) === canonical) {
72611
+ if (await (0, import_promises55.realpath)(source.path).catch(() => source.path) === canonical) {
72400
72612
  return { state: "already_present", label: source.label };
72401
72613
  }
72402
72614
  }
72403
- const current = await (0, import_promises54.readFile)(configPath, "utf8");
72615
+ const current = await (0, import_promises55.readFile)(configPath, "utf8");
72404
72616
  const block2 = [
72405
72617
  "",
72406
72618
  "[[skills.sources]]",
@@ -72408,7 +72620,7 @@ async function addSkillSource(home, input2) {
72408
72620
  `label = ${JSON.stringify(label)}`,
72409
72621
  ""
72410
72622
  ].join("\n");
72411
- await (0, import_promises54.writeFile)(configPath, `${current.replace(/\n*$/, "\n")}${block2}`, { mode: 384 });
72623
+ await (0, import_promises55.writeFile)(configPath, `${current.replace(/\n*$/, "\n")}${block2}`, { mode: 384 });
72412
72624
  const reloaded = await readSkillSourceConfig(home);
72413
72625
  if (reloaded.kind === "invalid_config") {
72414
72626
  return { state: "invalid", diagnostic: reloaded.diagnostic };
@@ -72417,12 +72629,12 @@ async function addSkillSource(home, input2) {
72417
72629
  }
72418
72630
 
72419
72631
  // src/capabilities/skills/local-upload.ts
72420
- var import_promises56 = require("fs/promises");
72632
+ var import_promises57 = require("fs/promises");
72421
72633
 
72422
72634
  // ../shared/src/node/skill-bundle.ts
72423
72635
  var import_node_buffer2 = require("buffer");
72424
72636
  var import_node_crypto46 = require("crypto");
72425
- var import_promises55 = require("fs/promises");
72637
+ var import_promises56 = require("fs/promises");
72426
72638
  var import_node_path67 = require("path");
72427
72639
  var import_node_stream = require("stream");
72428
72640
  var import_node_zlib = require("zlib");
@@ -72433,7 +72645,7 @@ async function createSkillBundle(packageRoot, options = {}) {
72433
72645
  const archive = (0, import_tar_stream.pack)();
72434
72646
  const tarPromise = collectStream(archive);
72435
72647
  for (const file2 of before.files) {
72436
- const bytes2 = await (0, import_promises55.readFile)((0, import_node_path67.join)(packageRoot, ...file2.path.split("/")));
72648
+ const bytes2 = await (0, import_promises56.readFile)((0, import_node_path67.join)(packageRoot, ...file2.path.split("/")));
72437
72649
  await addArchiveEntry(
72438
72650
  archive,
72439
72651
  {
@@ -72469,7 +72681,7 @@ async function extractSkillBundle(archiveBytes, destination, expected) {
72469
72681
  throw new Error("Skill archive hash does not match the expected immutable Version");
72470
72682
  }
72471
72683
  const tarBytes = await decompressBounded(archiveBytes);
72472
- await (0, import_promises55.mkdir)(destination, { recursive: false, mode: 448 });
72684
+ await (0, import_promises56.mkdir)(destination, { recursive: false, mode: 448 });
72473
72685
  try {
72474
72686
  await extractTar(tarBytes, destination);
72475
72687
  const inspected = await inspectSkillPackage(destination, { expectedName: null });
@@ -72477,7 +72689,7 @@ async function extractSkillBundle(archiveBytes, destination, expected) {
72477
72689
  throw new Error("Extracted Skill package hash does not match the expected immutable Version");
72478
72690
  }
72479
72691
  } catch (error62) {
72480
- await (0, import_promises55.rm)(destination, { recursive: true, force: true });
72692
+ await (0, import_promises56.rm)(destination, { recursive: true, force: true });
72481
72693
  throw error62;
72482
72694
  }
72483
72695
  }
@@ -72555,8 +72767,8 @@ async function extractEntry(header, stream, destination, limits) {
72555
72767
  throw new Error(`Skill archive file size is invalid: ${path4}`);
72556
72768
  }
72557
72769
  const outputPath = (0, import_node_path67.join)(destination, ...path4.split("/"));
72558
- await (0, import_promises55.mkdir)((0, import_node_path67.dirname)(outputPath), { recursive: true, mode: 448 });
72559
- await (0, import_promises55.writeFile)(outputPath, bytes, { mode: (header.mode ?? 420) & 73 ? 493 : 420 });
72770
+ await (0, import_promises56.mkdir)((0, import_node_path67.dirname)(outputPath), { recursive: true, mode: 448 });
72771
+ await (0, import_promises56.writeFile)(outputPath, bytes, { mode: (header.mode ?? 420) & 73 ? 493 : 420 });
72560
72772
  }
72561
72773
  function requireSafeArchivePath(value2) {
72562
72774
  const normalized2 = value2.replaceAll("\\", "/").normalize("NFC");
@@ -72582,8 +72794,8 @@ async function publishLocalSkill(options) {
72582
72794
  if (Date.parse(request2.uploadGrant.expiresAt) <= (options.now ?? Date.now())) {
72583
72795
  throw new RuntimeFault("invalid_file", "Skill upload grant expired");
72584
72796
  }
72585
- const folder = await (0, import_promises56.lstat)(entry.path);
72586
- if (!folder.isDirectory() || await (0, import_promises56.realpath)(entry.path) !== entry.path) {
72797
+ const folder = await (0, import_promises57.lstat)(entry.path);
72798
+ if (!folder.isDirectory() || await (0, import_promises57.realpath)(entry.path) !== entry.path) {
72587
72799
  throw new RuntimeFault("invalid_file", "Skill folder moved since the last scan");
72588
72800
  }
72589
72801
  const bundle = await createSkillBundle(entry.path, {
@@ -72612,7 +72824,7 @@ async function publishLocalSkill(options) {
72612
72824
  // src/capabilities/skills/native-index.ts
72613
72825
  var import_node_crypto47 = require("crypto");
72614
72826
  var import_node_fs28 = require("fs");
72615
- var import_promises57 = require("fs/promises");
72827
+ var import_promises58 = require("fs/promises");
72616
72828
  var import_node_path68 = require("path");
72617
72829
  var ALAN_SKILLS_PLUGIN_NAME = "alan";
72618
72830
  var PLUGIN_MANIFEST = `${JSON.stringify(
@@ -72626,32 +72838,32 @@ var PLUGIN_MANIFEST = `${JSON.stringify(
72626
72838
  `;
72627
72839
  async function entryKind2(path4) {
72628
72840
  try {
72629
- return (await (0, import_promises57.lstat)(path4)).isSymbolicLink() ? "link" : "other";
72841
+ return (await (0, import_promises58.lstat)(path4)).isSymbolicLink() ? "link" : "other";
72630
72842
  } catch (error62) {
72631
72843
  if (errnoCode(error62) === "ENOENT") return "missing";
72632
72844
  throw error62;
72633
72845
  }
72634
72846
  }
72635
72847
  async function linkTarget(path4) {
72636
- return (0, import_promises57.readlink)(path4).catch(() => null);
72848
+ return (0, import_promises58.readlink)(path4).catch(() => null);
72637
72849
  }
72638
72850
  async function removeLink2(path4) {
72639
72851
  try {
72640
- await (0, import_promises57.unlink)(path4);
72852
+ await (0, import_promises58.unlink)(path4);
72641
72853
  } catch (error62) {
72642
72854
  const code = errnoCode(error62);
72643
72855
  if (code === "ENOENT") return;
72644
72856
  if (code !== "EPERM" && code !== "EISDIR") throw error62;
72645
- await (0, import_promises57.rmdir)(path4);
72857
+ await (0, import_promises58.rmdir)(path4);
72646
72858
  }
72647
72859
  }
72648
72860
  async function placeLink(plan2, platform3) {
72649
72861
  if (await linkTarget(plan2.path) === plan2.target) return false;
72650
72862
  const staged = (0, import_node_path68.join)((0, import_node_path68.dirname)(plan2.path), `.${(0, import_node_path68.basename)(plan2.path)}.${(0, import_node_crypto47.randomUUID)()}.tmp`);
72651
- await (0, import_promises57.symlink)(plan2.target, staged, platform3 === "win32" ? "junction" : "dir");
72863
+ await (0, import_promises58.symlink)(plan2.target, staged, platform3 === "win32" ? "junction" : "dir");
72652
72864
  try {
72653
72865
  if (platform3 === "win32") await removeLink2(plan2.path);
72654
- await (0, import_promises57.rename)(staged, plan2.path);
72866
+ await (0, import_promises58.rename)(staged, plan2.path);
72655
72867
  } catch (error62) {
72656
72868
  await removeLink2(staged).catch(() => void 0);
72657
72869
  throw error62;
@@ -72664,14 +72876,14 @@ function versionTarget(layout, versionId, platform3) {
72664
72876
  }
72665
72877
  async function writeManifest(layout) {
72666
72878
  const manifest = (0, import_node_path68.join)(layout.pluginDir, ".claude-plugin", "plugin.json");
72667
- if (await (0, import_promises57.readFile)(manifest, "utf8").catch(() => null) === PLUGIN_MANIFEST) return;
72668
- await (0, import_promises57.mkdir)((0, import_node_path68.dirname)(manifest), { recursive: true, mode: 448 });
72879
+ if (await (0, import_promises58.readFile)(manifest, "utf8").catch(() => null) === PLUGIN_MANIFEST) return;
72880
+ await (0, import_promises58.mkdir)((0, import_node_path68.dirname)(manifest), { recursive: true, mode: 448 });
72669
72881
  const staged = `${manifest}.${(0, import_node_crypto47.randomUUID)()}.tmp`;
72670
- await (0, import_promises57.writeFile)(staged, PLUGIN_MANIFEST, { mode: 384 });
72671
- await (0, import_promises57.rename)(staged, manifest);
72882
+ await (0, import_promises58.writeFile)(staged, PLUGIN_MANIFEST, { mode: 384 });
72883
+ await (0, import_promises58.rename)(staged, manifest);
72672
72884
  }
72673
72885
  async function reconcilePluginSkills(layout, installed, platform3) {
72674
- await (0, import_promises57.mkdir)(layout.pluginSkillsDir, { recursive: true, mode: 448 });
72886
+ await (0, import_promises58.mkdir)(layout.pluginSkillsDir, { recursive: true, mode: 448 });
72675
72887
  const wanted = new Map(installed.map((skill) => [skill.slug, skill]));
72676
72888
  let linked = 0;
72677
72889
  for (const skill of installed) {
@@ -72680,16 +72892,16 @@ async function reconcilePluginSkills(layout, installed, platform3) {
72680
72892
  target: versionTarget(layout, skill.versionId, platform3)
72681
72893
  };
72682
72894
  if (await entryKind2(plan2.path) === "other") {
72683
- await (0, import_promises57.rm)(plan2.path, { recursive: true, force: true });
72895
+ await (0, import_promises58.rm)(plan2.path, { recursive: true, force: true });
72684
72896
  }
72685
72897
  if (await placeLink(plan2, platform3)) linked += 1;
72686
72898
  }
72687
72899
  let unlinked = 0;
72688
- for (const name of await (0, import_promises57.readdir)(layout.pluginSkillsDir)) {
72900
+ for (const name of await (0, import_promises58.readdir)(layout.pluginSkillsDir)) {
72689
72901
  if (wanted.has(name)) continue;
72690
72902
  const path4 = (0, import_node_path68.join)(layout.pluginSkillsDir, name);
72691
72903
  if (await entryKind2(path4) === "link") await removeLink2(path4);
72692
- else await (0, import_promises57.rm)(path4, { recursive: true, force: true });
72904
+ else await (0, import_promises58.rm)(path4, { recursive: true, force: true });
72693
72905
  unlinked += 1;
72694
72906
  }
72695
72907
  return { linked, unlinked };
@@ -72701,9 +72913,9 @@ async function isOwnCodexLink(layout, path4) {
72701
72913
  return isWithinDirectory2(layout.pluginSkillsDir, absolute);
72702
72914
  }
72703
72915
  async function isForeignPackage(layout, path4) {
72704
- const resolved = await (0, import_promises57.realpath)(path4).catch(() => null);
72916
+ const resolved = await (0, import_promises58.realpath)(path4).catch(() => null);
72705
72917
  if (resolved === null) return false;
72706
- const root = await (0, import_promises57.realpath)(layout.root).catch(() => layout.root);
72918
+ const root = await (0, import_promises58.realpath)(layout.root).catch(() => layout.root);
72707
72919
  return !isWithinDirectory2(root, resolved);
72708
72920
  }
72709
72921
  async function codexSlot(layout, path4, slug) {
@@ -72720,7 +72932,7 @@ async function codexSlot(layout, path4, slug) {
72720
72932
  }
72721
72933
  async function unlinkStaleCodexEntries(layout, codexSkillsDir2, wanted) {
72722
72934
  let unlinked = 0;
72723
- for (const name of await (0, import_promises57.readdir)(codexSkillsDir2)) {
72935
+ for (const name of await (0, import_promises58.readdir)(codexSkillsDir2)) {
72724
72936
  const path4 = (0, import_node_path68.join)(codexSkillsDir2, name);
72725
72937
  if (wanted.has(name) && !name.endsWith(".tmp")) continue;
72726
72938
  if (await entryKind2(path4) !== "link" || !await isOwnCodexLink(layout, path4)) continue;
@@ -72730,7 +72942,7 @@ async function unlinkStaleCodexEntries(layout, codexSkillsDir2, wanted) {
72730
72942
  return unlinked;
72731
72943
  }
72732
72944
  async function reconcileCodexSkills(layout, installed, codexSkillsDir2, platform3) {
72733
- await (0, import_promises57.mkdir)(codexSkillsDir2, { recursive: true, mode: 448 });
72945
+ await (0, import_promises58.mkdir)(codexSkillsDir2, { recursive: true, mode: 448 });
72734
72946
  const report2 = { linked: 0, unlinked: 0, skipped: [] };
72735
72947
  for (const skill of installed) {
72736
72948
  const path4 = (0, import_node_path68.join)(codexSkillsDir2, skill.slug);
@@ -72767,7 +72979,7 @@ function installedSkillFolders(layout) {
72767
72979
 
72768
72980
  // src/capabilities/skills/sync.ts
72769
72981
  var import_node_crypto48 = require("crypto");
72770
- var import_promises58 = require("fs/promises");
72982
+ var import_promises59 = require("fs/promises");
72771
72983
  var import_node_path69 = require("path");
72772
72984
  init_zod();
72773
72985
  var SKILL_PREPARE_WAIT_MS = 15e3;
@@ -72775,28 +72987,28 @@ var FIRST_INSTALL_WAIT_MS = 5e3;
72775
72987
  var RETIRED_VERSION_RETENTION_MS = 24 * 60 * 60 * 1e3;
72776
72988
  async function makeFilesReadOnly(directory, platform3) {
72777
72989
  if (platform3 === "win32") return;
72778
- for (const entry of await (0, import_promises58.readdir)(directory, { withFileTypes: true })) {
72990
+ for (const entry of await (0, import_promises59.readdir)(directory, { withFileTypes: true })) {
72779
72991
  const path4 = (0, import_node_path69.join)(directory, entry.name);
72780
72992
  if (entry.isDirectory()) await makeFilesReadOnly(path4, platform3);
72781
72993
  else if (entry.isFile()) {
72782
- const executable = ((await (0, import_promises58.lstat)(path4)).mode & 64) !== 0;
72783
- await (0, import_promises58.chmod)(path4, executable ? 365 : 292);
72994
+ const executable = ((await (0, import_promises59.lstat)(path4)).mode & 64) !== 0;
72995
+ await (0, import_promises59.chmod)(path4, executable ? 365 : 292);
72784
72996
  }
72785
72997
  }
72786
72998
  }
72787
72999
  async function install(env, skill, download, signal) {
72788
73000
  const { layout, source, platform: platform3 } = env;
72789
73001
  const bytes = await source.download(download.url, signal);
72790
- await (0, import_promises58.mkdir)(layout.tmpDir, { recursive: true, mode: 448 });
73002
+ await (0, import_promises59.mkdir)(layout.tmpDir, { recursive: true, mode: 448 });
72791
73003
  const staging = (0, import_node_path69.join)(layout.tmpDir, (0, import_node_crypto48.randomUUID)());
72792
73004
  await extractSkillBundle(Buffer.from(bytes), staging, {
72793
73005
  expectedArchiveHash: download.archiveHash,
72794
73006
  expectedContentHash: skill.contentHash
72795
73007
  });
72796
73008
  const target = packageDirectory(layout, skill.versionId);
72797
- await (0, import_promises58.mkdir)(layout.versionsDir, { recursive: true, mode: 448 });
72798
- await (0, import_promises58.rm)(target, { recursive: true, force: true });
72799
- await (0, import_promises58.rename)(staging, target);
73009
+ await (0, import_promises59.mkdir)(layout.versionsDir, { recursive: true, mode: 448 });
73010
+ await (0, import_promises59.rm)(target, { recursive: true, force: true });
73011
+ await (0, import_promises59.rename)(staging, target);
72800
73012
  await makeFilesReadOnly(target, platform3);
72801
73013
  }
72802
73014
  var retiredFileSchema = external_exports.record(external_exports.string(), external_exports.number());
@@ -72808,14 +73020,14 @@ async function sweep(env, keep) {
72808
73020
  const now = env.now();
72809
73021
  const stillRetired = {};
72810
73022
  const expired = [];
72811
- for (const name of await (0, import_promises58.readdir)(layout.versionsDir).catch(() => [])) {
73023
+ for (const name of await (0, import_promises59.readdir)(layout.versionsDir).catch(() => [])) {
72812
73024
  if (kept.has(name)) continue;
72813
73025
  const since = retired[name] ?? now;
72814
73026
  if (now - since >= RETIRED_VERSION_RETENTION_MS) expired.push(name);
72815
73027
  else stillRetired[name] = since;
72816
73028
  }
72817
73029
  const results = await Promise.allSettled(
72818
- expired.map((name) => (0, import_promises58.rm)((0, import_node_path69.join)(layout.versionsDir, name), { recursive: true, force: true }))
73030
+ expired.map((name) => (0, import_promises59.rm)((0, import_node_path69.join)(layout.versionsDir, name), { recursive: true, force: true }))
72819
73031
  );
72820
73032
  results.forEach((result, index) => {
72821
73033
  const name = expired[index];
@@ -72824,7 +73036,7 @@ async function sweep(env, keep) {
72824
73036
  if (JSON.stringify(stillRetired) !== JSON.stringify(retired)) {
72825
73037
  await writeJsonFileAtomic(layout.retiredFile, stillRetired);
72826
73038
  }
72827
- await (0, import_promises58.rm)(layout.tmpDir, { recursive: true, force: true });
73039
+ await (0, import_promises59.rm)(layout.tmpDir, { recursive: true, force: true });
72828
73040
  return results.filter((result) => result.status === "fulfilled").length;
72829
73041
  }
72830
73042
  var INSTALL_CONCURRENCY = 4;
@@ -73170,7 +73382,7 @@ var import_node_path74 = require("path");
73170
73382
  init_runtime_v2();
73171
73383
 
73172
73384
  // src/capabilities/workspace/approved-paths.ts
73173
- var import_promises59 = require("fs/promises");
73385
+ var import_promises60 = require("fs/promises");
73174
73386
  init_zod();
73175
73387
 
73176
73388
  // src/capabilities/workspace/paths.ts
@@ -73208,7 +73420,7 @@ var storeSchema = external_exports.object({
73208
73420
  });
73209
73421
  async function realpathOrNull(path4) {
73210
73422
  try {
73211
- return await (0, import_promises59.realpath)(path4);
73423
+ return await (0, import_promises60.realpath)(path4);
73212
73424
  } catch (error62) {
73213
73425
  const code = errnoCode(error62);
73214
73426
  if (code === "ENOENT" || code === "ENOTDIR" || code === "EACCES" || code === "EPERM") {
@@ -73267,12 +73479,12 @@ async function openApprovedPaths(options) {
73267
73479
  }
73268
73480
 
73269
73481
  // src/capabilities/workspace/files/read.ts
73270
- var import_promises60 = require("fs/promises");
73482
+ var import_promises61 = require("fs/promises");
73271
73483
  var BINARY_SNIFF_BYTES = 8e3;
73272
73484
  async function readFileValue(path4, maxBytes) {
73273
73485
  let size;
73274
73486
  try {
73275
- const info = await (0, import_promises60.stat)(path4);
73487
+ const info = await (0, import_promises61.stat)(path4);
73276
73488
  if (!info.isFile()) return { kind: "not_file" };
73277
73489
  size = info.size;
73278
73490
  } catch {
@@ -73281,7 +73493,7 @@ async function readFileValue(path4, maxBytes) {
73281
73493
  if (size > maxBytes) return { kind: "too_large", size };
73282
73494
  let handle;
73283
73495
  try {
73284
- handle = await (0, import_promises60.open)(path4, "r");
73496
+ handle = await (0, import_promises61.open)(path4, "r");
73285
73497
  } catch {
73286
73498
  return { kind: "not_file" };
73287
73499
  }
@@ -73303,7 +73515,7 @@ async function readFileValue(path4, maxBytes) {
73303
73515
  }
73304
73516
 
73305
73517
  // src/capabilities/workspace/files/tree.ts
73306
- var import_promises61 = require("fs/promises");
73518
+ var import_promises62 = require("fs/promises");
73307
73519
  var import_node_path71 = require("path");
73308
73520
  var MAX_TREE_FILES = 2e5;
73309
73521
  var IGNORED_FOLDER_NAMES = /* @__PURE__ */ new Set([
@@ -73345,7 +73557,7 @@ async function gitListing(git, root, dirs, signal) {
73345
73557
  }
73346
73558
  async function entriesOf(path4) {
73347
73559
  try {
73348
- return await (0, import_promises61.readdir)(path4, { withFileTypes: true });
73560
+ return await (0, import_promises62.readdir)(path4, { withFileTypes: true });
73349
73561
  } catch {
73350
73562
  return [];
73351
73563
  }
@@ -73409,7 +73621,7 @@ function foldersOf(files) {
73409
73621
 
73410
73622
  // src/capabilities/workspace/files/watch.ts
73411
73623
  var import_node_fs29 = require("fs");
73412
- var import_promises62 = require("fs/promises");
73624
+ var import_promises63 = require("fs/promises");
73413
73625
  var import_node_path72 = require("path");
73414
73626
  init_runtime_v2();
73415
73627
  var WATCH_DEBOUNCE_MS = 250;
@@ -73582,7 +73794,7 @@ var RootWatch = class {
73582
73794
  }
73583
73795
  async kindOf(relative6) {
73584
73796
  try {
73585
- return (await (0, import_promises62.lstat)((0, import_node_path72.join)(this.root, relative6))).isDirectory() ? "folder" : "file";
73797
+ return (await (0, import_promises63.lstat)((0, import_node_path72.join)(this.root, relative6))).isDirectory() ? "folder" : "file";
73586
73798
  } catch (error62) {
73587
73799
  const code = errnoCode(error62);
73588
73800
  return code === "ENOENT" || code === "ENOTDIR" ? "gone" : "unreadable";
@@ -73636,7 +73848,7 @@ var RootWatch = class {
73636
73848
  if (!this.watchFolder(folder)) continue;
73637
73849
  let entries;
73638
73850
  try {
73639
- entries = await (0, import_promises62.readdir)((0, import_node_path72.join)(this.root, folder), { withFileTypes: true });
73851
+ entries = await (0, import_promises63.readdir)((0, import_node_path72.join)(this.root, folder), { withFileTypes: true });
73640
73852
  } catch {
73641
73853
  continue;
73642
73854
  }
@@ -73828,7 +74040,7 @@ function openWorkspaceFiles(options) {
73828
74040
 
73829
74041
  // src/capabilities/workspace/locks.ts
73830
74042
  var import_node_crypto49 = require("crypto");
73831
- var import_promises63 = require("fs/promises");
74043
+ var import_promises64 = require("fs/promises");
73832
74044
  var import_node_path73 = require("path");
73833
74045
  init_zod();
73834
74046
  var LOCK_FORMAT = 1;
@@ -73849,7 +74061,7 @@ function repositoryLockKey(commonDir, platform3) {
73849
74061
  async function readOwner2(path4) {
73850
74062
  let text3;
73851
74063
  try {
73852
- text3 = await (0, import_promises63.readFile)(path4, "utf8");
74064
+ text3 = await (0, import_promises64.readFile)(path4, "utf8");
73853
74065
  } catch (error62) {
73854
74066
  if (errnoCode(error62) === "ENOENT") return { kind: "missing" };
73855
74067
  return { kind: "unreadable" };
@@ -73870,7 +74082,7 @@ async function removeIfSame(path4, expected) {
73870
74082
  if (current.kind !== "owner" || current.owner.since !== expected.since) return;
73871
74083
  if (current.owner.pid !== expected.pid || current.owner.holder !== expected.holder) return;
73872
74084
  }
73873
- await (0, import_promises63.unlink)(path4).catch((error62) => {
74085
+ await (0, import_promises64.unlink)(path4).catch((error62) => {
73874
74086
  if (errnoCode(error62) !== "ENOENT") throw error62;
73875
74087
  });
73876
74088
  }
@@ -73895,7 +74107,7 @@ function openRepositoryLocks(options) {
73895
74107
  await removeIfSame(path4, read.owner);
73896
74108
  return null;
73897
74109
  }
73898
- const age = await (0, import_promises63.stat)(path4).then(
74110
+ const age = await (0, import_promises64.stat)(path4).then(
73899
74111
  (info) => clock.now() - info.mtimeMs,
73900
74112
  () => 0
73901
74113
  );
@@ -73910,12 +74122,12 @@ function openRepositoryLocks(options) {
73910
74122
  const folder = async (commonDir) => {
73911
74123
  const key = repositoryLockKey(commonDir, platform3);
73912
74124
  const dir = (0, import_node_path73.join)(options.dir, key);
73913
- await (0, import_promises63.mkdir)(dir, { recursive: true, mode: 448 });
74125
+ await (0, import_promises64.mkdir)(dir, { recursive: true, mode: 448 });
73914
74126
  return { key, dir };
73915
74127
  };
73916
74128
  const createExclusive = async (path4, owner) => {
73917
74129
  try {
73918
- const handle = await (0, import_promises63.open)(path4, "wx", 384);
74130
+ const handle = await (0, import_promises64.open)(path4, "wx", 384);
73919
74131
  try {
73920
74132
  await handle.writeFile(JSON.stringify(owner));
73921
74133
  } finally {
@@ -73928,7 +74140,7 @@ function openRepositoryLocks(options) {
73928
74140
  }
73929
74141
  };
73930
74142
  const liveRun = async (dir) => {
73931
- const entries = await (0, import_promises63.readdir)(dir);
74143
+ const entries = await (0, import_promises64.readdir)(dir);
73932
74144
  for (const entry of entries) {
73933
74145
  if (!entry.startsWith(RUN_FILE_PREFIX)) continue;
73934
74146
  const holder = await heldBy((0, import_node_path73.join)(dir, entry));
@@ -74225,7 +74437,14 @@ function isActive(activity) {
74225
74437
  function selectDriver(persistent, fallback) {
74226
74438
  const drivers = /* @__PURE__ */ new Set([...Object.values(persistent), fallback]);
74227
74439
  return {
74228
- runTurn: (spec, sink, signal, inputs) => (persistent[spec.backendKind] ?? fallback).runTurn(spec, sink, signal, inputs),
74440
+ hasBackgroundWork: (runId) => [...drivers].some((driver) => driver.hasBackgroundWork?.(runId) ?? false),
74441
+ onBackgroundEvent: (spec, listener) => (persistent[spec.backendKind] ?? fallback).onBackgroundEvent?.(spec, listener) ?? {
74442
+ [Symbol.dispose]: () => {
74443
+ }
74444
+ },
74445
+ runTurn: (spec, sink, signal, inputs) => {
74446
+ return (persistent[spec.backendKind] ?? fallback).runTurn(spec, sink, signal, inputs);
74447
+ },
74229
74448
  suspend: async () => {
74230
74449
  await Promise.all([...drivers].map((driver) => driver.suspend?.()));
74231
74450
  },
@@ -74276,18 +74495,40 @@ function createLazyValue(load) {
74276
74495
  }
74277
74496
  function createLazyDriver(load) {
74278
74497
  const loaded = {};
74498
+ const backgroundListeners = /* @__PURE__ */ new Set();
74279
74499
  const driver = () => {
74280
- loaded.driver ??= load().then((value2) => {
74281
- loaded.resolved = value2;
74282
- return value2;
74500
+ loaded.driver ??= load().then((resolved) => {
74501
+ loaded.resolved = resolved;
74502
+ return resolved;
74283
74503
  });
74284
74504
  return loaded.driver;
74285
74505
  };
74286
74506
  return {
74287
- runTurn: async (spec, sink, signal, inputs) => (await driver()).runTurn(spec, sink, signal, inputs),
74507
+ runTurn: async (spec, sink, signal, inputs) => {
74508
+ const resolved = await driver();
74509
+ for (const entry of backgroundListeners) {
74510
+ entry.subscription ??= resolved.onBackgroundEvent?.(entry.spec, entry.listener);
74511
+ }
74512
+ return resolved.runTurn(spec, sink, signal, inputs);
74513
+ },
74288
74514
  suspend: async () => {
74289
74515
  if (loaded.driver !== void 0) await (await loaded.driver).suspend?.();
74290
74516
  },
74517
+ hasBackgroundWork: (runId) => loaded.resolved?.hasBackgroundWork?.(runId) ?? false,
74518
+ onBackgroundEvent: (spec, listener) => {
74519
+ const entry = {
74520
+ spec,
74521
+ listener,
74522
+ subscription: loaded.resolved?.onBackgroundEvent?.(spec, listener)
74523
+ };
74524
+ backgroundListeners.add(entry);
74525
+ return {
74526
+ [Symbol.dispose]: () => {
74527
+ backgroundListeners.delete(entry);
74528
+ entry.subscription?.[Symbol.dispose]();
74529
+ }
74530
+ };
74531
+ },
74291
74532
  respond: async (request2) => {
74292
74533
  if (loaded.driver === void 0) return "unknown_run";
74293
74534
  return await (await loaded.driver).respond?.(request2) ?? "unknown_run";
@@ -74476,17 +74717,17 @@ function createConversationMcpAuthorization(options) {
74476
74717
  }
74477
74718
 
74478
74719
  // src/holder/mcp-helper-access.ts
74479
- var import_promises64 = require("fs/promises");
74720
+ var import_promises65 = require("fs/promises");
74480
74721
  function createHelperMcpAccess(options) {
74481
74722
  return {
74482
74723
  [Symbol.asyncDispose]: async () => {
74483
- await (0, import_promises64.rm)(options.credentialPath, { force: true });
74724
+ await (0, import_promises65.rm)(options.credentialPath, { force: true });
74484
74725
  },
74485
74726
  url: options.managedMcp.url,
74486
74727
  authorization: async (signal) => {
74487
74728
  const authorization = await options.managedMcp.authorization(signal);
74488
74729
  if (authorization === void 0 || signal.aborted) {
74489
- await (0, import_promises64.rm)(options.credentialPath, { force: true });
74730
+ await (0, import_promises65.rm)(options.credentialPath, { force: true });
74490
74731
  return void 0;
74491
74732
  }
74492
74733
  const credential = {
@@ -74501,7 +74742,7 @@ function createHelperMcpAccess(options) {
74501
74742
  }
74502
74743
 
74503
74744
  // src/holder/run-inputs.ts
74504
- var import_promises65 = require("fs/promises");
74745
+ var import_promises66 = require("fs/promises");
74505
74746
  var import_node_path77 = require("path");
74506
74747
  init_src();
74507
74748
  var NO_RUN_INPUTS = {
@@ -74539,7 +74780,7 @@ async function prepareRunInputs(spec, { source, tmpDir, signal, skills = [], com
74539
74780
  await commitAttribution?.setCoAuthor(spec.gitCoAuthor);
74540
74781
  const dir = (0, import_node_path77.join)(tmpDir, "runs", spec.runId);
74541
74782
  const cleanup = async () => {
74542
- await (0, import_promises65.rm)(dir, { recursive: true, force: true });
74783
+ await (0, import_promises66.rm)(dir, { recursive: true, force: true });
74543
74784
  };
74544
74785
  try {
74545
74786
  const credential = await source.fetchProviderCredential(spec.runId, signal);
@@ -74547,8 +74788,8 @@ async function prepareRunInputs(spec, { source, tmpDir, signal, skills = [], com
74547
74788
  for (const [index, attachment] of (spec.attachments ?? []).entries()) {
74548
74789
  const bytes = await source.downloadAttachment(spec.runId, attachment.id, signal);
74549
74790
  const path4 = attachmentPath(spec, attachment, index, dir);
74550
- await (0, import_promises65.mkdir)((0, import_node_path77.dirname)(path4), { recursive: true, mode: 448 });
74551
- await (0, import_promises65.writeFile)(path4, bytes, { mode: 384 });
74791
+ await (0, import_promises66.mkdir)((0, import_node_path77.dirname)(path4), { recursive: true, mode: 448 });
74792
+ await (0, import_promises66.writeFile)(path4, bytes, { mode: 384 });
74552
74793
  const imageMimeType = attachment.kind === "image" ? detectImageMimeType(Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)) : null;
74553
74794
  attachments.push({
74554
74795
  id: attachment.id,
@@ -74586,7 +74827,7 @@ init_runtime_v2();
74586
74827
 
74587
74828
  // src/holder/admission.ts
74588
74829
  var import_node_fs32 = require("fs");
74589
- var import_promises69 = require("fs/promises");
74830
+ var import_promises70 = require("fs/promises");
74590
74831
  var import_node_os11 = require("os");
74591
74832
  var import_node_path83 = require("path");
74592
74833
  init_constants();
@@ -74600,11 +74841,11 @@ function resolveAlanDefaultWorkspacePath(homeDirectory = (0, import_node_os10.ho
74600
74841
  }
74601
74842
 
74602
74843
  // src/holder/agent-context.ts
74603
- var import_promises66 = require("fs/promises");
74844
+ var import_promises67 = require("fs/promises");
74604
74845
  var import_node_path79 = require("path");
74605
74846
  init_prompt();
74606
74847
  async function readText4(path4) {
74607
- return (0, import_promises66.readFile)(path4, "utf8").then(
74848
+ return (0, import_promises67.readFile)(path4, "utf8").then(
74608
74849
  (text3) => text3.trim(),
74609
74850
  () => null
74610
74851
  );
@@ -74650,12 +74891,12 @@ var import_node_path82 = require("path");
74650
74891
 
74651
74892
  // src/holder/claim-once.ts
74652
74893
  var import_node_crypto50 = require("crypto");
74653
- var import_promises67 = require("fs/promises");
74894
+ var import_promises68 = require("fs/promises");
74654
74895
  var import_node_path80 = require("path");
74655
74896
  async function claimOnce(dir, name) {
74656
74897
  try {
74657
- await (0, import_promises67.mkdir)(dir, { recursive: true, mode: 448 });
74658
- await (await (0, import_promises67.open)((0, import_node_path80.join)(dir, name), "wx")).close();
74898
+ await (0, import_promises68.mkdir)(dir, { recursive: true, mode: 448 });
74899
+ await (await (0, import_promises68.open)((0, import_node_path80.join)(dir, name), "wx")).close();
74659
74900
  return true;
74660
74901
  } catch {
74661
74902
  return false;
@@ -74666,7 +74907,7 @@ function claimFirstLease(freshnessDir, path4) {
74666
74907
  }
74667
74908
 
74668
74909
  // src/holder/requested-checkout.ts
74669
- var import_promises68 = require("fs/promises");
74910
+ var import_promises69 = require("fs/promises");
74670
74911
  var import_node_path81 = require("path");
74671
74912
  var REMOTE2 = "origin";
74672
74913
  var REASON_MAX_CHARS = 200;
@@ -74689,7 +74930,7 @@ function notSwitched(checkout, current, reason) {
74689
74930
  }
74690
74931
  async function clone2(checkout, deps, signal) {
74691
74932
  const parent = (0, import_node_path81.dirname)(checkout.path);
74692
- await (0, import_promises68.mkdir)(parent, { recursive: true });
74933
+ await (0, import_promises69.mkdir)(parent, { recursive: true });
74693
74934
  await assertValidBranch(deps.git, parent, checkout.branch, signal);
74694
74935
  const output2 = await deps.git.run(
74695
74936
  {
@@ -74997,7 +75238,7 @@ function volumeRoot(path4) {
74997
75238
  }
74998
75239
  async function exists4(path4) {
74999
75240
  try {
75000
- await (0, import_promises69.stat)(path4);
75241
+ await (0, import_promises70.stat)(path4);
75001
75242
  return true;
75002
75243
  } catch {
75003
75244
  return false;
@@ -75005,10 +75246,10 @@ async function exists4(path4) {
75005
75246
  }
75006
75247
  async function inspectReadiness(path4) {
75007
75248
  try {
75008
- if (!(await (0, import_promises69.stat)(path4)).isDirectory()) {
75249
+ if (!(await (0, import_promises70.stat)(path4)).isDirectory()) {
75009
75250
  return { ready: false, missing: true, message: MESSAGES.missing };
75010
75251
  }
75011
- await (0, import_promises69.access)(path4, import_node_fs32.constants.R_OK | import_node_fs32.constants.W_OK | import_node_fs32.constants.X_OK);
75252
+ await (0, import_promises70.access)(path4, import_node_fs32.constants.R_OK | import_node_fs32.constants.W_OK | import_node_fs32.constants.X_OK);
75012
75253
  return { ready: true };
75013
75254
  } catch (error62) {
75014
75255
  const code = errnoCode(error62) ?? "";
@@ -75052,8 +75293,8 @@ async function admitDefaultWorkspace(spec, context, skills) {
75052
75293
  const { env } = context;
75053
75294
  const path4 = resolveAlanDefaultWorkspacePath(env.HOME || env.USERPROFILE || (0, import_node_os11.homedir)());
75054
75295
  try {
75055
- await (0, import_promises69.mkdir)(path4, { recursive: true, mode: 448 });
75056
- await (0, import_promises69.access)(path4, import_node_fs32.constants.R_OK | import_node_fs32.constants.W_OK | import_node_fs32.constants.X_OK);
75296
+ await (0, import_promises70.mkdir)(path4, { recursive: true, mode: 448 });
75297
+ await (0, import_promises70.access)(path4, import_node_fs32.constants.R_OK | import_node_fs32.constants.W_OK | import_node_fs32.constants.X_OK);
75057
75298
  return { kind: "admitted", spec: { ...spec, projectPath: path4 }, skills };
75058
75299
  } catch (error62) {
75059
75300
  const code = errnoCode(error62);
@@ -75181,7 +75422,7 @@ async function respondToTurn(runningRunId, driver, request2) {
75181
75422
  }
75182
75423
 
75183
75424
  // src/holder/session-facts.ts
75184
- var import_promises70 = require("fs/promises");
75425
+ var import_promises71 = require("fs/promises");
75185
75426
  var CLI_RSS_CACHE_MS = 1e4;
75186
75427
  var LOGIN_PROBLEM_PREFIX = "cli.auth.";
75187
75428
  function isLoginFailure(result) {
@@ -75201,14 +75442,15 @@ function createSessionFacts(options) {
75201
75442
  managedVersion: null,
75202
75443
  identified: Promise.resolve(),
75203
75444
  loginFailed: false,
75204
- rss: null
75445
+ rss: null,
75446
+ driver: null
75205
75447
  };
75206
75448
  const identify2 = async (command) => {
75207
75449
  const path4 = await resolveCommandOnPath(command, env, platform3);
75208
75450
  if (path4 === null) return null;
75209
75451
  try {
75210
- const real = await (0, import_promises70.realpath)(path4);
75211
- const info = await (0, import_promises70.stat)(real);
75452
+ const real = await (0, import_promises71.realpath)(path4);
75453
+ const info = await (0, import_promises71.stat)(real);
75212
75454
  return { command, key: `${real}:${info.ino}:${info.size}:${info.mtimeMs}` };
75213
75455
  } catch {
75214
75456
  return null;
@@ -75250,30 +75492,33 @@ function createSessionFacts(options) {
75250
75492
  return current?.key !== spawned.key;
75251
75493
  };
75252
75494
  return {
75253
- observe: (driver) => ({
75254
- ...driver,
75255
- runTurn: async (spec, sink, signal, inputs) => {
75256
- state.idleSinceMs = null;
75257
- try {
75258
- const result = await driver.runTurn(
75259
- spec,
75260
- {
75261
- onEvent: (event) => sink.onEvent(event),
75262
- onSpawned: (pid) => {
75263
- state.identified = noteSpawned(spec, pid);
75264
- sink.onSpawned(pid);
75265
- }
75266
- },
75267
- signal,
75268
- inputs
75269
- );
75270
- state.loginFailed = isLoginFailure(result);
75271
- return result;
75272
- } finally {
75273
- state.idleSinceMs = clock.now();
75495
+ observe: (driver) => {
75496
+ state.driver = driver;
75497
+ return {
75498
+ ...driver,
75499
+ runTurn: async (spec, sink, signal, inputs) => {
75500
+ state.idleSinceMs = null;
75501
+ try {
75502
+ const result = await driver.runTurn(
75503
+ spec,
75504
+ {
75505
+ onEvent: (event) => sink.onEvent(event),
75506
+ onSpawned: (pid) => {
75507
+ state.identified = noteSpawned(spec, pid);
75508
+ sink.onSpawned(pid);
75509
+ }
75510
+ },
75511
+ signal,
75512
+ inputs
75513
+ );
75514
+ state.loginFailed = isLoginFailure(result);
75515
+ return result;
75516
+ } finally {
75517
+ state.idleSinceMs = clock.now();
75518
+ }
75274
75519
  }
75275
- }
75276
- }),
75520
+ };
75521
+ },
75277
75522
  snapshot: async () => {
75278
75523
  await state.identified;
75279
75524
  const cliRssBytes = await liveCliRss();
@@ -75281,6 +75526,7 @@ function createSessionFacts(options) {
75281
75526
  return {
75282
75527
  startedAtMs: state.startedAtMs,
75283
75528
  idleSinceMs: state.idleSinceMs,
75529
+ hasBackgroundWork: state.driver?.hasBackgroundWork?.() ?? false,
75284
75530
  holderRssBytes: readOwnRss(),
75285
75531
  cliPid: cliAlive ? state.cliPid : null,
75286
75532
  cliRssBytes,
@@ -75302,12 +75548,12 @@ async function steerTurn(runningRunId, driver, request2) {
75302
75548
  init_acp2();
75303
75549
 
75304
75550
  // src/run-log/archive.ts
75305
- var import_promises71 = require("fs/promises");
75551
+ var import_promises72 = require("fs/promises");
75306
75552
  var import_node_path84 = require("path");
75307
75553
  init_runtime_v2();
75308
75554
  async function openRunArchive(runsDir) {
75309
75555
  const path4 = (0, import_node_path84.join)((0, import_node_path84.dirname)(runsDir), "archived-runs.txt");
75310
- const text3 = await (0, import_promises71.readFile)(path4, "utf8").catch((error62) => {
75556
+ const text3 = await (0, import_promises72.readFile)(path4, "utf8").catch((error62) => {
75311
75557
  if (errnoCode(error62) === "ENOENT") return "";
75312
75558
  throw error62;
75313
75559
  });
@@ -75321,7 +75567,7 @@ async function openRunArchive(runsDir) {
75321
75567
  add: async (runIds) => {
75322
75568
  const added = runIds.filter((runId) => !archived.has(runId));
75323
75569
  if (added.length === 0) return;
75324
- await (0, import_promises71.appendFile)(path4, `
75570
+ await (0, import_promises72.appendFile)(path4, `
75325
75571
  ${added.join("\n")}
75326
75572
  `, { mode: 384 });
75327
75573
  for (const runId of added) archived.add(runId);
@@ -75335,7 +75581,7 @@ var import_node_fs33 = require("fs");
75335
75581
  var import_node_path86 = require("path");
75336
75582
 
75337
75583
  // src/run-log/directory.ts
75338
- var import_promises72 = require("fs/promises");
75584
+ var import_promises73 = require("fs/promises");
75339
75585
  var import_node_path85 = require("path");
75340
75586
  init_runtime_v2();
75341
75587
  init_zod();
@@ -75372,7 +75618,7 @@ function runDirectory(runsDir, runId) {
75372
75618
  }
75373
75619
  async function isRunClaimed(runsDir, runId) {
75374
75620
  try {
75375
- return (await (0, import_promises72.stat)(runDirectory(runsDir, runId).log)).size > 0;
75621
+ return (await (0, import_promises73.stat)(runDirectory(runsDir, runId).log)).size > 0;
75376
75622
  } catch (error62) {
75377
75623
  if (errnoCode(error62) === "ENOENT") return false;
75378
75624
  throw error62;
@@ -75410,7 +75656,7 @@ async function writeCompleteRunLog(runsDir, meta3, records) {
75410
75656
  }
75411
75657
 
75412
75658
  // src/run-log/conversation-index.ts
75413
- var import_promises73 = require("fs/promises");
75659
+ var import_promises74 = require("fs/promises");
75414
75660
  var import_node_path87 = require("path");
75415
75661
  init_runtime_v2();
75416
75662
  init_zod();
@@ -75443,8 +75689,8 @@ async function indexConversationRun(runsDir, conversationId, ordinal, assistantO
75443
75689
  const nextOrdinal = assistantOrdinal + 1;
75444
75690
  if (nextOrdinal <= ordinal) throw new Error("Assistant order must follow the prompt");
75445
75691
  const path4 = shardPath(runsDir, conversationId, ordinal);
75446
- await (0, import_promises73.mkdir)((0, import_node_path87.dirname)(path4), { recursive: true, mode: 448 });
75447
- await (0, import_promises73.appendFile)(path4, `${JSON.stringify({ ordinal, nextOrdinal, runId })}
75692
+ await (0, import_promises74.mkdir)((0, import_node_path87.dirname)(path4), { recursive: true, mode: 448 });
75693
+ await (0, import_promises74.appendFile)(path4, `${JSON.stringify({ ordinal, nextOrdinal, runId })}
75448
75694
  `, { mode: 384 });
75449
75695
  const coveragePath = (0, import_node_path87.join)((0, import_node_path87.dirname)((0, import_node_path87.dirname)(path4)), "coverage.json");
75450
75696
  const coverage = await readJsonFile(coveragePath, coverageSchema);
@@ -75467,7 +75713,7 @@ async function readConversationIndexCoverage(runsDir, conversationId) {
75467
75713
  }
75468
75714
  async function readConversationRunIndex(runsDir, conversationId, before, limit) {
75469
75715
  const directory = indexDirectory(runsDir, conversationId);
75470
- const names = await (0, import_promises73.readdir)(directory).catch((error62) => {
75716
+ const names = await (0, import_promises74.readdir)(directory).catch((error62) => {
75471
75717
  if (error62.code === "ENOENT") return [];
75472
75718
  throw error62;
75473
75719
  });
@@ -75476,7 +75722,7 @@ async function readConversationRunIndex(runsDir, conversationId, before, limit)
75476
75722
  ).sort((left, right) => right - left);
75477
75723
  const selected = [];
75478
75724
  for (const shard of shards) {
75479
- const text3 = await (0, import_promises73.readFile)((0, import_node_path87.join)(directory, `${shard}.jsonl`), "utf8");
75725
+ const text3 = await (0, import_promises74.readFile)((0, import_node_path87.join)(directory, `${shard}.jsonl`), "utf8");
75480
75726
  const records = text3.split("\n").flatMap((line) => {
75481
75727
  if (!line) return [];
75482
75728
  const parsed = indexRecordSchema.parse(JSON.parse(line));
@@ -75501,7 +75747,7 @@ async function readIndexableRun(runsDir, name) {
75501
75747
  return { conversationId: meta3.conversationId, ordinal, assistantOrdinal, runId: runId.data };
75502
75748
  }
75503
75749
  async function readIndexableRuns(runsDir) {
75504
- const names = await (0, import_promises73.readdir)(runsDir).catch(() => []);
75750
+ const names = await (0, import_promises74.readdir)(runsDir).catch(() => []);
75505
75751
  const byConversation = /* @__PURE__ */ new Map();
75506
75752
  let next = 0;
75507
75753
  const worker = async () => {
@@ -75531,21 +75777,21 @@ async function writeConversationIndex(directory, runs) {
75531
75777
  else lines2.push(line);
75532
75778
  coverage = nextCoverage(coverage, run2.ordinal, nextOrdinal) ?? coverage;
75533
75779
  }
75534
- await (0, import_promises73.mkdir)((0, import_node_path87.join)(directory, "turn-index"), { recursive: true, mode: 448 });
75780
+ await (0, import_promises74.mkdir)((0, import_node_path87.join)(directory, "turn-index"), { recursive: true, mode: 448 });
75535
75781
  for (const [shard, lines2] of shards) {
75536
- await (0, import_promises73.writeFile)((0, import_node_path87.join)(directory, "turn-index", `${shard}.jsonl`), `${lines2.join("\n")}
75782
+ await (0, import_promises74.writeFile)((0, import_node_path87.join)(directory, "turn-index", `${shard}.jsonl`), `${lines2.join("\n")}
75537
75783
  `, {
75538
75784
  mode: 384
75539
75785
  });
75540
75786
  }
75541
- await (0, import_promises73.writeFile)((0, import_node_path87.join)(directory, "coverage.json"), `${JSON.stringify(coverage)}
75787
+ await (0, import_promises74.writeFile)((0, import_node_path87.join)(directory, "coverage.json"), `${JSON.stringify(coverage)}
75542
75788
  `, {
75543
75789
  mode: 384
75544
75790
  });
75545
75791
  }
75546
75792
  async function rebuildConversationIndexes(runsDir) {
75547
75793
  const root = conversationsDirectory(runsDir);
75548
- const exists6 = await (0, import_promises73.stat)(root).then(
75794
+ const exists6 = await (0, import_promises74.stat)(root).then(
75549
75795
  () => true,
75550
75796
  (error62) => {
75551
75797
  if (errnoCode(error62) === "ENOENT") return false;
@@ -75554,18 +75800,18 @@ async function rebuildConversationIndexes(runsDir) {
75554
75800
  );
75555
75801
  if (exists6) return 0;
75556
75802
  const building = `${root}.rebuilding`;
75557
- await (0, import_promises73.rm)(building, { recursive: true, force: true });
75558
- await (0, import_promises73.mkdir)(building, { recursive: true, mode: 448 });
75803
+ await (0, import_promises74.rm)(building, { recursive: true, force: true });
75804
+ await (0, import_promises74.mkdir)(building, { recursive: true, mode: 448 });
75559
75805
  const byConversation = await readIndexableRuns(runsDir);
75560
75806
  for (const [conversationId, runs] of byConversation) {
75561
75807
  await writeConversationIndex((0, import_node_path87.join)(building, conversationId), runs);
75562
75808
  }
75563
- await (0, import_promises73.rename)(building, root);
75809
+ await (0, import_promises74.rename)(building, root);
75564
75810
  return byConversation.size;
75565
75811
  }
75566
75812
 
75567
75813
  // src/run-log/reader.ts
75568
- var import_promises74 = require("fs/promises");
75814
+ var import_promises75 = require("fs/promises");
75569
75815
  init_runtime_v2();
75570
75816
 
75571
75817
  // src/run-log/tail.ts
@@ -75603,7 +75849,7 @@ function firstRecordLength(bytes) {
75603
75849
  return bytes.indexOf(RUN_LOG_RECORD_SEPARATOR) + 1;
75604
75850
  }
75605
75851
  async function openRunLogReader(path4) {
75606
- const handle = await (0, import_promises74.open)(path4, "r");
75852
+ const handle = await (0, import_promises75.open)(path4, "r");
75607
75853
  const readAt = async (position, length) => {
75608
75854
  const buffer = Buffer.alloc(length);
75609
75855
  const { bytesRead } = await handle.read(buffer, 0, length, position);
@@ -75637,7 +75883,7 @@ async function openRunLogReader(path4) {
75637
75883
  };
75638
75884
  }
75639
75885
  async function readLastRecord(path4) {
75640
- const handle = await (0, import_promises74.open)(path4, "r").catch(() => null);
75886
+ const handle = await (0, import_promises75.open)(path4, "r").catch(() => null);
75641
75887
  if (handle === null) return null;
75642
75888
  try {
75643
75889
  const { size } = await handle.stat();
@@ -75655,6 +75901,7 @@ async function readLastRecord(path4) {
75655
75901
  }
75656
75902
 
75657
75903
  // src/run-log/records.ts
75904
+ init_runtime_v2();
75658
75905
  function runAccepted(machineId, acceptedAt) {
75659
75906
  return { sessionUpdate: "_alan/run.accepted", machineId, acceptedAt };
75660
75907
  }
@@ -75665,6 +75912,22 @@ function runEnded(input2) {
75665
75912
  return { sessionUpdate: "_alan/run.ended", ...input2 };
75666
75913
  }
75667
75914
  var decoder = new TextDecoder();
75915
+ function decodeRunLogChunk(bytes) {
75916
+ const text3 = decoder.decode(bytes);
75917
+ if (text3.length === 0) return [];
75918
+ if (!text3.endsWith("\n")) {
75919
+ throw new RuntimeFault("invalid_file", "Run log chunk does not end on a record boundary");
75920
+ }
75921
+ return text3.slice(0, -1).split("\n").map((line, index) => {
75922
+ const parsed = runLogRecordSchema.safeParse(JSON.parse(line));
75923
+ if (!parsed.success) {
75924
+ throw new RuntimeFault("invalid_file", `Run log line ${index + 1} is not a record`, {
75925
+ cause: parsed.error
75926
+ });
75927
+ }
75928
+ return parsed.data;
75929
+ });
75930
+ }
75668
75931
 
75669
75932
  // src/run-log/writer.ts
75670
75933
  var import_node_fs34 = require("fs");
@@ -75868,99 +76131,136 @@ async function claimRun(spec, context) {
75868
76131
  }
75869
76132
  var RUN_END_RETRY_MS = 5e3;
75870
76133
  var RUN_END_DEADLINE_MS = 10 * 6e4;
75871
- async function runClaimedTurn(spec, claimed, context, signal) {
75872
- var _stack = [];
75873
- try {
75874
- const log = __using(_stack, claimed);
75875
- const reported = { error: false };
75876
- const writeFailed = new AbortController();
75877
- let writeError;
75878
- const append = (update, sessionId) => {
75879
- if (writeError !== void 0) return;
75880
- if (update.sessionUpdate === "notice" && update.severity === "error") reported.error = true;
76134
+ function resultEndUpdate(result, outcome2) {
76135
+ return runEnded({
76136
+ outcome: outcome2,
76137
+ ...result.providerSessionId === void 0 ? {} : { providerSessionId: result.providerSessionId },
76138
+ ...result.message === void 0 ? {} : { message: result.message },
76139
+ ...result.problem === void 0 ? {} : { problem: result.problem },
76140
+ ...result.rejection === void 0 ? {} : { rejection: result.rejection },
76141
+ ...result.unansweredSteerIds === void 0 ? {} : { unansweredSteerIds: [...result.unansweredSteerIds] }
76142
+ });
76143
+ }
76144
+ async function writeRunEnd(updates, log, spec, context) {
76145
+ const deadline = context.clock.monotonic() + RUN_END_DEADLINE_MS;
76146
+ for (const update of updates) {
76147
+ for (; ; ) {
75881
76148
  let offset;
75882
76149
  try {
75883
- offset = log.append(update, sessionId);
76150
+ offset = log.append(update);
75884
76151
  } catch (error62) {
75885
- writeError = error62;
75886
- context.log.error("holder.run_log_write_failed", { runId: spec.runId, error: error62 });
75887
- writeFailed.abort();
75888
- return;
75889
- }
75890
- context.onAppended(spec.runId, offset);
75891
- };
75892
- const endRun = async (updates2) => {
75893
- const deadline = context.clock.monotonic() + RUN_END_DEADLINE_MS;
75894
- for (const update of updates2) {
75895
- for (; ; ) {
75896
- let offset;
75897
- try {
75898
- offset = log.append(update);
75899
- } catch (error62) {
75900
- context.log.warn("holder.run_end_write_failed", { runId: spec.runId, error: error62 });
75901
- if (context.clock.monotonic() >= deadline) {
75902
- throw new RuntimeFault("io_failed", `Run ${spec.runId} could not be ended`, {
75903
- cause: error62
75904
- });
75905
- }
75906
- await context.clock.sleep(RUN_END_RETRY_MS, new AbortController().signal);
75907
- continue;
75908
- }
75909
- context.onAppended(spec.runId, offset);
75910
- break;
76152
+ context.log.warn("holder.run_end_write_failed", { runId: spec.runId, error: error62 });
76153
+ if (context.clock.monotonic() >= deadline) {
76154
+ throw new RuntimeFault("io_failed", `Run ${spec.runId} could not be ended`, {
76155
+ cause: error62
76156
+ });
75911
76157
  }
76158
+ await context.clock.sleep(RUN_END_RETRY_MS, new AbortController().signal);
76159
+ continue;
75912
76160
  }
75913
- };
75914
- const fail = async (message2) => {
75915
- await endRun([
75916
- noticeUpdate("error", "run_failed", message2),
75917
- runEnded({ outcome: "failed", message: message2 })
75918
- ]);
75919
- return "failed";
75920
- };
75921
- let result;
76161
+ context.onAppended(spec.runId, offset);
76162
+ break;
76163
+ }
76164
+ }
76165
+ }
76166
+ async function completeClaimedTurn(result, spec, context, signal, log, events, reportedError, state) {
76167
+ const outcome2 = result.outcome === "aborted" && signal.reason === "interrupted" ? "interrupted" : result.outcome;
76168
+ const updates = [];
76169
+ if (outcome2 === "failed" && !reportedError && result.message !== void 0) {
76170
+ updates.push(noticeUpdate("error", "run_failed", result.message));
76171
+ }
76172
+ const ended = resultEndUpdate(result, outcome2);
76173
+ state.ended = ended;
76174
+ updates.push(ended);
76175
+ const pendingBackground = Boolean(events && context.driver.hasBackgroundWork?.(spec.runId));
76176
+ if (pendingBackground) updates.push({ sessionUpdate: "_alan/background.pending" });
76177
+ try {
76178
+ await writeRunEnd(updates, log, spec, context);
76179
+ state.foregroundEnded = true;
76180
+ state.retainedForBackground = Boolean(
76181
+ pendingBackground && context.driver.hasBackgroundWork?.(spec.runId)
76182
+ );
76183
+ if (pendingBackground && !state.retainedForBackground) {
76184
+ await writeRunEnd([ended], log, spec, context);
76185
+ }
76186
+ } finally {
76187
+ if (!state.retainedForBackground) {
76188
+ events?.[Symbol.dispose]();
76189
+ log[Symbol.dispose]();
76190
+ }
76191
+ }
76192
+ context.log.info("holder.turn_ended", { runId: spec.runId, outcome: outcome2 });
76193
+ return outcome2;
76194
+ }
76195
+ async function runClaimedTurn(spec, claimed, context, signal) {
76196
+ const log = claimed;
76197
+ const reported = { error: false };
76198
+ const endState = { foregroundEnded: false, retainedForBackground: false };
76199
+ const writeFailed = new AbortController();
76200
+ let writeError;
76201
+ const append = (update, sessionId) => {
76202
+ if (writeError !== void 0) return;
76203
+ if (update.sessionUpdate === "notice" && update.severity === "error") reported.error = true;
76204
+ let offset;
75922
76205
  try {
75923
- result = await admitAndRun(
75924
- spec,
75925
- context,
75926
- {
75927
- onSpawned: (pid) => append(runStarted({ pid })),
75928
- // Base64 media in provider payloads and tool output never reaches the log (main 13590db369).
75929
- onEvent: (event) => append(fitForRunLog(withoutInlineMedia(event.update)), event.sessionId)
75930
- },
75931
- AbortSignal.any([signal, writeFailed.signal])
75932
- );
76206
+ offset = log.append(update, sessionId);
75933
76207
  } catch (error62) {
75934
- context.log.error("holder.turn_threw", { runId: spec.runId, error: error62 });
76208
+ writeError = error62;
76209
+ context.log.error("holder.run_log_write_failed", { runId: spec.runId, error: error62 });
76210
+ writeFailed.abort();
76211
+ return;
76212
+ }
76213
+ context.onAppended(spec.runId, offset);
76214
+ };
76215
+ const endRun = (updates) => writeRunEnd(updates, log, spec, context);
76216
+ const fail = async (message2) => {
76217
+ await endRun([
76218
+ noticeUpdate("error", "run_failed", message2),
76219
+ runEnded({ outcome: "failed", message: message2 })
76220
+ ]);
76221
+ return "failed";
76222
+ };
76223
+ const events = context.driver.onBackgroundEvent?.(spec, (update, sessionId) => {
76224
+ append(fitForRunLog(withoutInlineMedia(update)), sessionId);
76225
+ log.syncIfDirty();
76226
+ if (!endState.foregroundEnded || !endState.retainedForBackground || context.driver.hasBackgroundWork?.(spec.runId))
76227
+ return;
76228
+ if (endState.ended) append(endState.ended);
76229
+ events?.[Symbol.dispose]();
76230
+ log[Symbol.dispose]();
76231
+ endState.retainedForBackground = false;
76232
+ });
76233
+ let result;
76234
+ try {
76235
+ result = await admitAndRun(
76236
+ spec,
76237
+ context,
76238
+ {
76239
+ onSpawned: (pid) => append(runStarted({ pid })),
76240
+ // Base64 media in provider payloads and tool output never reaches the log (main 13590db369).
76241
+ onEvent: (event) => append(fitForRunLog(withoutInlineMedia(event.update)), event.sessionId)
76242
+ },
76243
+ AbortSignal.any([signal, writeFailed.signal])
76244
+ );
76245
+ } catch (error62) {
76246
+ context.log.error("holder.turn_threw", { runId: spec.runId, error: error62 });
76247
+ try {
75935
76248
  return await fail(error62 instanceof Error ? error62.message : String(error62));
76249
+ } finally {
76250
+ events?.[Symbol.dispose]();
76251
+ log[Symbol.dispose]();
75936
76252
  }
75937
- if (writeError !== void 0) {
75938
- const reason = writeError instanceof Error ? writeError.message : String(writeError);
76253
+ }
76254
+ if (writeError !== void 0) {
76255
+ const reason = writeError instanceof Error ? writeError.message : String(writeError);
76256
+ try {
75939
76257
  return await fail(`This run's log could not be written: ${reason}`);
76258
+ } finally {
76259
+ events?.[Symbol.dispose]();
76260
+ log[Symbol.dispose]();
75940
76261
  }
75941
- const outcome2 = result.outcome === "aborted" && signal.reason === "interrupted" ? "interrupted" : result.outcome;
75942
- const updates = [];
75943
- if (outcome2 === "failed" && !reported.error && result.message !== void 0) {
75944
- updates.push(noticeUpdate("error", "run_failed", result.message));
75945
- }
75946
- updates.push(
75947
- runEnded({
75948
- outcome: outcome2,
75949
- ...result.providerSessionId === void 0 ? {} : { providerSessionId: result.providerSessionId },
75950
- ...result.message === void 0 ? {} : { message: result.message },
75951
- ...result.problem === void 0 ? {} : { problem: result.problem },
75952
- ...result.rejection === void 0 ? {} : { rejection: result.rejection },
75953
- ...result.unansweredSteerIds === void 0 ? {} : { unansweredSteerIds: [...result.unansweredSteerIds] }
75954
- })
75955
- );
75956
- await endRun(updates);
75957
- context.log.info("holder.turn_ended", { runId: spec.runId, outcome: outcome2 });
75958
- return outcome2;
75959
- } catch (_) {
75960
- var _error = _, _hasError = true;
75961
- } finally {
75962
- __callDispose(_stack, _error, _hasError);
75963
76262
  }
76263
+ return completeClaimedTurn(result, spec, context, signal, log, events, reported.error, endState);
75964
76264
  }
75965
76265
 
75966
76266
  // src/holder/serve.ts
@@ -76248,11 +76548,11 @@ function delta(current, previous) {
76248
76548
  return previous === void 0 ? 0 : Math.max(0, Math.round(current - previous));
76249
76549
  }
76250
76550
  async function lastOutputAtMs(runsDir, run2) {
76251
- const info = await (0, import_promises75.stat)(runDirectory(runsDir, run2.runId).log).catch(() => null);
76551
+ const info = await (0, import_promises76.stat)(runDirectory(runsDir, run2.runId).log).catch(() => null);
76252
76552
  return info === null ? null : Math.floor(info.mtimeMs);
76253
76553
  }
76254
76554
  async function readHolderActivities(sessionsDir) {
76255
- const names = await (0, import_promises75.readdir)(sessionsDir).catch(() => []);
76555
+ const names = await (0, import_promises76.readdir)(sessionsDir).catch(() => []);
76256
76556
  const found = [];
76257
76557
  for (const name of names) {
76258
76558
  const parsed = conversationIdSchema.safeParse(name);
@@ -76537,7 +76837,7 @@ async function runActivityLeaseWorker(rawData, port) {
76537
76837
 
76538
76838
  // src/cli/commands/compat.ts
76539
76839
  var import_node_crypto54 = require("crypto");
76540
- var import_promises79 = require("fs/promises");
76840
+ var import_promises80 = require("fs/promises");
76541
76841
  init_runtime_v2();
76542
76842
  init_zod();
76543
76843
 
@@ -76828,7 +77128,7 @@ var mcpConfigResultSchema = external_exports.object({
76828
77128
  });
76829
77129
 
76830
77130
  // src/client/runtime-client.ts
76831
- var import_promises76 = require("fs/promises");
77131
+ var import_promises77 = require("fs/promises");
76832
77132
  init_acp();
76833
77133
  init_runtime_v2();
76834
77134
 
@@ -76891,7 +77191,7 @@ var DEFAULT_BACKOFF = { initialMs: 250, maxMs: 3e4 };
76891
77191
  async function readDiscovery(path4) {
76892
77192
  let text3;
76893
77193
  try {
76894
- text3 = await (0, import_promises76.readFile)(path4, "utf8");
77194
+ text3 = await (0, import_promises77.readFile)(path4, "utf8");
76895
77195
  } catch (error62) {
76896
77196
  throw new RuntimeClientError("unavailable", "The runtime is not running", { cause: error62 });
76897
77197
  }
@@ -77300,7 +77600,7 @@ async function sendNativeHookSignal(discoveryPath, hookSignal, signal) {
77300
77600
 
77301
77601
  // src/sessions/index.ts
77302
77602
  var import_node_crypto53 = require("crypto");
77303
- var import_promises77 = require("fs/promises");
77603
+ var import_promises78 = require("fs/promises");
77304
77604
  var import_node_path93 = require("path");
77305
77605
  init_runtime_v2();
77306
77606
 
@@ -77320,7 +77620,8 @@ function runOccupancy(held, reserved, exclude = null) {
77320
77620
  var DEFAULT_SUSPEND_POLICY = { idleMs: 30 * 6e4 };
77321
77621
  function idleSince(holder, opened) {
77322
77622
  const { idleSinceMs } = holder.facts;
77323
- if (holder.state !== "idle" || holder.runId !== null || idleSinceMs === null) return null;
77623
+ if (holder.state !== "idle" || holder.runId !== null || idleSinceMs === null || holder.facts.hasBackgroundWork)
77624
+ return null;
77324
77625
  const openedAtMs = opened?.conversationId === holder.conversationId ? opened.atMs : 0;
77325
77626
  return Math.max(idleSinceMs, openedAtMs);
77326
77627
  }
@@ -77341,13 +77642,20 @@ function planSuspends(holders, policy, nowMs, opened = null) {
77341
77642
 
77342
77643
  // src/sessions/index.ts
77343
77644
  var HOLDER_READY_TIMEOUT_MS = 15e3;
77645
+ function endInChunk(bytes) {
77646
+ for (const record2 of decodeRunLogChunk(bytes)) {
77647
+ const parsed = runEndedUpdateSchema.safeParse(record2.update);
77648
+ if (parsed.success) return parsed.data;
77649
+ }
77650
+ return null;
77651
+ }
77344
77652
  var HOLDER_READY_POLL_MS = 50;
77345
77653
  var HOLDER_EXIT_GRACE_MS = 2e3;
77346
77654
  var DEFAULT_MAX_ACTIVE_RUNS = 32;
77347
77655
  var HOLDER_BUSY = "busy";
77348
77656
  async function listIds(dir, schema) {
77349
77657
  const ids = [];
77350
- for (const name of await (0, import_promises77.readdir)(dir).catch(() => [])) {
77658
+ for (const name of await (0, import_promises78.readdir)(dir).catch(() => [])) {
77351
77659
  const parsed = schema.safeParse(name);
77352
77660
  if (parsed.success) ids.push(parsed.data);
77353
77661
  }
@@ -77372,9 +77680,9 @@ async function removeHolderFiles(files) {
77372
77680
  sessionActivityPath(files.dir)
77373
77681
  ];
77374
77682
  for (const path4 of holderWritten) {
77375
- await (0, import_promises77.rm)(path4, { force: true });
77683
+ await (0, import_promises78.rm)(path4, { force: true });
77376
77684
  }
77377
- await (0, import_promises77.rmdir)(files.dir).catch((error62) => {
77685
+ await (0, import_promises78.rmdir)(files.dir).catch((error62) => {
77378
77686
  if (!["ENOENT", "ENOTEMPTY", "EEXIST"].includes(errnoCode(error62) ?? "")) throw error62;
77379
77687
  });
77380
77688
  }
@@ -77391,6 +77699,34 @@ async function openSessions(deps) {
77391
77699
  const suspendPolicy = deps.suspendPolicy ?? DEFAULT_SUSPEND_POLICY;
77392
77700
  const admitted = /* @__PURE__ */ new Set();
77393
77701
  let admitting = Promise.resolve();
77702
+ const foregroundEnds = /* @__PURE__ */ new Map();
77703
+ const foregroundEnd = async (runId, logPath) => {
77704
+ var _stack = [];
77705
+ try {
77706
+ const cached2 = foregroundEnds.get(runId);
77707
+ if (cached2?.ended) return cached2.ended;
77708
+ const reader = __using(_stack, await openRunLogReader(logPath), true);
77709
+ const size = await reader.size();
77710
+ let offset = cached2?.offset ?? 0;
77711
+ if (offset > size) offset = 0;
77712
+ let ended = null;
77713
+ while (offset < size) {
77714
+ const chunk = await reader.readFrom(toByteOffset(offset), 64 * 1024);
77715
+ if (chunk.bytes.length === 0) break;
77716
+ ended = endInChunk(chunk.bytes) ?? ended;
77717
+ offset = chunk.to;
77718
+ }
77719
+ const latest = foregroundEnds.get(runId);
77720
+ const durableEnd = ended ?? latest?.ended ?? null;
77721
+ foregroundEnds.set(runId, { offset: Math.max(offset, latest?.offset ?? 0), ended: durableEnd });
77722
+ return durableEnd;
77723
+ } catch (_) {
77724
+ var _error = _, _hasError = true;
77725
+ } finally {
77726
+ var _promise2 = __callDispose(_stack, _error, _hasError);
77727
+ _promise2 && await _promise2;
77728
+ }
77729
+ };
77394
77730
  const onEvent = (event) => {
77395
77731
  if (event.type === "appended") deps.onAppended(event.runId);
77396
77732
  else deps.onTurnEnded(event.runId);
@@ -77398,11 +77734,18 @@ async function openSessions(deps) {
77398
77734
  const markInterrupted = async (runId) => {
77399
77735
  var _stack = [];
77400
77736
  try {
77401
- const last = await readLastRecord(runDirectory(paths.runs, runId).log);
77737
+ const logPath = runDirectory(paths.runs, runId).log;
77738
+ const last = await readLastRecord(logPath);
77402
77739
  if (last === null || last.update.sessionUpdate === "_alan/run.ended") return;
77403
- const writer = __using(_stack, openRunLog(runDirectory(paths.runs, runId).log, clock));
77404
- writer.append(runEnded({ outcome: "interrupted", message: "The computer stopped mid-turn" }));
77405
- log.warn("sessions.run_interrupted", { runId, droppedTailBytes: writer.droppedTailBytes });
77740
+ const previousEnd = await foregroundEnd(runId, logPath);
77741
+ const meta3 = await readRunMeta(runDirectory(paths.runs, runId).meta);
77742
+ if (previousEnd && meta3 !== null && connections.has(meta3.conversationId)) return;
77743
+ const writer = __using(_stack, openRunLog(logPath, clock));
77744
+ writer.append(
77745
+ previousEnd ?? runEnded({ outcome: "interrupted", message: HOLDER_LOST_RUN_MESSAGE })
77746
+ );
77747
+ if (previousEnd) log.info("sessions.background_log_finalized", { runId });
77748
+ else log.warn("sessions.run_interrupted", { runId, droppedTailBytes: writer.droppedTailBytes });
77406
77749
  deps.onAppended(runId);
77407
77750
  } catch (_) {
77408
77751
  var _error = _, _hasError = true;
@@ -77439,7 +77782,12 @@ async function openSessions(deps) {
77439
77782
  }
77440
77783
  };
77441
77784
  const attach = async (conversationId, launch) => {
77442
- const connection = await connectHolder(launch.endpoint, launch.token, onEvent);
77785
+ const connection = await connectHolder(
77786
+ launch.endpoint,
77787
+ launch.token,
77788
+ onEvent,
77789
+ deps.holderReadyTimeoutMs
77790
+ );
77443
77791
  connections.set(conversationId, connection);
77444
77792
  void connection.closed().then(() => {
77445
77793
  if (connections.get(conversationId) !== connection) return;
@@ -77456,7 +77804,11 @@ async function openSessions(deps) {
77456
77804
  const dir = runDirectory(paths.runs, runId);
77457
77805
  if ((await readRunMeta(dir.meta))?.conversationId !== conversationId) continue;
77458
77806
  const last = await readLastRecord(dir.log);
77459
- found.push({ runId, ended: last?.update.sessionUpdate === "_alan/run.ended" });
77807
+ found.push({
77808
+ runId,
77809
+ // A legacy holder still owns the background child until its final end record.
77810
+ ended: last?.update.sessionUpdate === "_alan/run.ended"
77811
+ });
77460
77812
  }
77461
77813
  return found;
77462
77814
  };
@@ -77512,8 +77864,12 @@ async function openSessions(deps) {
77512
77864
  log.info("sessions.reattached", { conversationId });
77513
77865
  return;
77514
77866
  }
77515
- if (alive) await removeHolderFiles(files);
77516
- else await discardSession(conversationId);
77867
+ if (alive) {
77868
+ log.warn("sessions.live_holder_unattachable", { conversationId });
77869
+ return;
77870
+ }
77871
+ await discardSession(conversationId);
77872
+ for (const runId of await unendedRunsOf(conversationId)) await markInterrupted(runId);
77517
77873
  };
77518
77874
  const busyRunIds = async () => {
77519
77875
  const busy = /* @__PURE__ */ new Set();
@@ -77523,23 +77879,30 @@ async function openSessions(deps) {
77523
77879
  }
77524
77880
  return busy;
77525
77881
  };
77526
- const scan = async () => {
77527
- for (const conversationId of await listIds(paths.sessions, conversationIdSchema)) {
77528
- await reattachOrRetire(conversationId).catch(
77529
- (error62) => log.warn("sessions.reattach_failed", { conversationId, error: error62 })
77530
- );
77531
- }
77882
+ const scanRunLogs = async (live) => {
77532
77883
  const busy = new Set(await busyRunIds());
77533
77884
  for (const conversationId of legacy.keys()) {
77534
77885
  for (const runId of await unendedRunsOf(conversationId)) busy.add(runId);
77535
77886
  }
77536
77887
  for (const runId of await recentRunIds()) {
77537
- if (busy.has(runId)) continue;
77888
+ const meta3 = await readRunMeta(runDirectory(paths.runs, runId).meta);
77889
+ if (busy.has(runId) || meta3 !== null && live.has(meta3.conversationId)) continue;
77538
77890
  await markInterrupted(runId).catch(
77539
77891
  (error62) => log.warn("sessions.interrupt_failed", { runId, error: error62 })
77540
77892
  );
77541
77893
  }
77542
77894
  };
77895
+ const scan = async () => {
77896
+ const live = /* @__PURE__ */ new Set();
77897
+ for (const conversationId of await listIds(paths.sessions, conversationIdSchema)) {
77898
+ await reattachOrRetire(conversationId).catch(
77899
+ (error62) => log.warn("sessions.reattach_failed", { conversationId, error: error62 })
77900
+ );
77901
+ if (connections.has(conversationId) || await isHolderAlive(sessionFiles(paths, conversationId)))
77902
+ live.add(conversationId);
77903
+ }
77904
+ await scanRunLogs(live);
77905
+ };
77543
77906
  const spawn11 = async (conversationId) => {
77544
77907
  const files = sessionFiles(paths, conversationId);
77545
77908
  const launch = {
@@ -77573,7 +77936,7 @@ async function openSessions(deps) {
77573
77936
  const meta3 = await readRunMeta(dir.meta);
77574
77937
  const last = await readLastRecord(dir.log);
77575
77938
  if (meta3 === null || last === null) return null;
77576
- const logged = await (0, import_promises77.stat)(dir.log).catch((error62) => {
77939
+ const logged = await (0, import_promises78.stat)(dir.log).catch((error62) => {
77577
77940
  if (errnoCode(error62) === "ENOENT") return null;
77578
77941
  throw error62;
77579
77942
  });
@@ -77581,10 +77944,10 @@ async function openSessions(deps) {
77581
77944
  const held = {
77582
77945
  runId,
77583
77946
  conversationId: meta3.conversationId,
77584
- state: last.update.sessionUpdate === "_alan/run.ended" ? "ended" : "running",
77947
+ state: last.update.sessionUpdate === "_alan/run.ended" || last.update.sessionUpdate === "_alan/background.pending" || await foregroundEnd(runId, dir.log) !== null ? "ended" : "running",
77585
77948
  loggedBytes: toByteOffset(logged.size)
77586
77949
  };
77587
- if (held.state === "ended") endedRuns.set(runId, held);
77950
+ if (last.update.sessionUpdate === "_alan/run.ended") endedRuns.set(runId, held);
77588
77951
  return held;
77589
77952
  };
77590
77953
  const launchedNotLogged = (logged) => {
@@ -77595,13 +77958,17 @@ async function openSessions(deps) {
77595
77958
  }
77596
77959
  return held;
77597
77960
  };
77961
+ const forgetRemovedRuns = (onDisk) => {
77962
+ for (const runId of endedRuns.keys()) if (!onDisk.has(runId)) endedRuns.delete(runId);
77963
+ for (const runId of foregroundEnds.keys()) if (!onDisk.has(runId)) foregroundEnds.delete(runId);
77964
+ };
77598
77965
  const heldRuns = async () => {
77599
77966
  const held = [...starting.values()].map(
77600
77967
  ({ run: run2 }) => notLoggedRun(run2.runId, run2.conversationId)
77601
77968
  );
77602
77969
  const logged = /* @__PURE__ */ new Set();
77603
77970
  const onDisk = new Set(await recentRunIds());
77604
- for (const runId of endedRuns.keys()) if (!onDisk.has(runId)) endedRuns.delete(runId);
77971
+ forgetRemovedRuns(onDisk);
77605
77972
  for (const runId of onDisk) {
77606
77973
  const run2 = starting.has(runId) ? null : await loggedRun(runId);
77607
77974
  if (run2 === null) continue;
@@ -77705,6 +78072,10 @@ async function openSessions(deps) {
77705
78072
  return "waiting";
77706
78073
  }
77707
78074
  try {
78075
+ if (!connections.has(run2.conversationId) && await isHolderAlive(sessionFiles(paths, run2.conversationId))) {
78076
+ log.info("sessions.live_holder_unattachable", { conversationId: run2.conversationId });
78077
+ return "busy";
78078
+ }
77708
78079
  if (!connections.has(run2.conversationId)) await spawn11(run2.conversationId);
77709
78080
  const connection = connections.get(run2.conversationId);
77710
78081
  if (connection === void 0) {
@@ -78001,7 +78372,7 @@ function takeEnrollmentCodeFromEnv(env = process.env) {
78001
78372
  }
78002
78373
 
78003
78374
  // src/cli/context.ts
78004
- var import_promises78 = require("fs/promises");
78375
+ var import_promises79 = require("fs/promises");
78005
78376
  var import_node_os13 = require("os");
78006
78377
  var import_node_path95 = require("path");
78007
78378
  var DESKTOP_BUNDLE_IDS = {
@@ -78051,7 +78422,7 @@ async function installedServiceSpec(ctx) {
78051
78422
  const spec = serviceSpec(ctx);
78052
78423
  if (ctx.config.host === "app") return spec;
78053
78424
  const layout = installLayout(ctx.config.installDir, ctx.config.profile);
78054
- const installed = await (0, import_promises78.access)(layout.launcher).then(
78425
+ const installed = await (0, import_promises79.access)(layout.launcher).then(
78055
78426
  () => true,
78056
78427
  () => false
78057
78428
  );
@@ -78182,7 +78553,7 @@ var manifestRevisionSchema = external_exports.object({ revision: external_export
78182
78553
  async function manifestRevision(path4) {
78183
78554
  let raw;
78184
78555
  try {
78185
- raw = JSON.parse(await (0, import_promises79.readFile)(path4, "utf8"));
78556
+ raw = JSON.parse(await (0, import_promises80.readFile)(path4, "utf8"));
78186
78557
  } catch (error62) {
78187
78558
  throw new RuntimeFault("invalid_file", `Cannot read the skill manifest at ${path4}`, {
78188
78559
  cause: error62
@@ -78236,7 +78607,7 @@ async function runSkills(argv) {
78236
78607
  }
78237
78608
 
78238
78609
  // src/cli/commands/doctor.ts
78239
- var import_promises82 = require("fs/promises");
78610
+ var import_promises83 = require("fs/promises");
78240
78611
  var import_node_path99 = require("path");
78241
78612
  init_runtime_v2();
78242
78613
 
@@ -78445,7 +78816,7 @@ async function authorizeDevice(input2) {
78445
78816
  }
78446
78817
 
78447
78818
  // src/identity/enroll.ts
78448
- var import_promises80 = require("fs/promises");
78819
+ var import_promises81 = require("fs/promises");
78449
78820
  init_runtime_v2();
78450
78821
  async function enrollMachine(input2) {
78451
78822
  const machineId = input2.machineId ?? (await readMachineFile(input2.paths))?.machineId ?? (await readInstallation(input2.paths))?.machineId;
@@ -78528,12 +78899,12 @@ async function enrollFromGrantFile(input2) {
78528
78899
  clock: input2.clock,
78529
78900
  access: input2.access
78530
78901
  });
78531
- await (0, import_promises80.rm)(input2.grantPath, { force: true });
78902
+ await (0, import_promises81.rm)(input2.grantPath, { force: true });
78532
78903
  return machine;
78533
78904
  }
78534
78905
 
78535
78906
  // src/identity/migrate-v1.ts
78536
- var import_promises81 = require("fs/promises");
78907
+ var import_promises82 = require("fs/promises");
78537
78908
  var import_node_path97 = require("path");
78538
78909
  init_runtime_v2();
78539
78910
  init_zod();
@@ -78619,12 +78990,12 @@ async function scrubLegacyInstall(install2) {
78619
78990
  const scrubbed = { ...install2.config, migratedToRuntimeV2: true };
78620
78991
  for (const key of SCRUBBED_KEYS) delete scrubbed[key];
78621
78992
  await writeJsonFileAtomic(`${install2.configPath}.migrated-v1`, scrubbed);
78622
- await (0, import_promises81.rm)(install2.configPath, { force: true });
78623
- await (0, import_promises81.rm)(install2.ownerLeasePath, { force: true });
78993
+ await (0, import_promises82.rm)(install2.configPath, { force: true });
78994
+ await (0, import_promises82.rm)(install2.ownerLeasePath, { force: true });
78624
78995
  }
78625
78996
  async function retireLegacyInstall(install2) {
78626
- await (0, import_promises81.rename)(install2.configPath, `${install2.configPath}.retired-v1`);
78627
- await (0, import_promises81.rm)(install2.ownerLeasePath, { force: true });
78997
+ await (0, import_promises82.rename)(install2.configPath, `${install2.configPath}.retired-v1`);
78998
+ await (0, import_promises82.rm)(install2.ownerLeasePath, { force: true });
78628
78999
  }
78629
79000
  async function exchangeCredential(deps) {
78630
79001
  const { config: config2 } = deps.install;
@@ -79038,7 +79409,7 @@ async function probeHolder(dir, conversationId) {
79038
79409
  }
79039
79410
  }
79040
79411
  async function holdersCheck(ctx) {
79041
- const names = await (0, import_promises82.readdir)(ctx.paths.sessions).catch(() => []);
79412
+ const names = await (0, import_promises83.readdir)(ctx.paths.sessions).catch(() => []);
79042
79413
  const holders = (await Promise.all(names.map((name) => probeHolder((0, import_node_path99.join)(ctx.paths.sessions, name), name)))).filter((facts) => facts !== null);
79043
79414
  const dead = holders.filter((holder) => !holder.alive).length;
79044
79415
  return check2(
@@ -79050,7 +79421,7 @@ async function holdersCheck(ctx) {
79050
79421
  }
79051
79422
  async function freeBytesAt(path4) {
79052
79423
  try {
79053
- const stats = await (0, import_promises82.statfs)(path4);
79424
+ const stats = await (0, import_promises83.statfs)(path4);
79054
79425
  return { path: path4, freeBytes: stats.bavail * stats.bsize };
79055
79426
  } catch (error62) {
79056
79427
  const parent = (0, import_node_path99.dirname)(path4);
@@ -79189,7 +79560,7 @@ async function runDoctor(argv, context = cliContext) {
79189
79560
  }
79190
79561
 
79191
79562
  // src/cli/commands/git-credential.ts
79192
- var import_promises83 = require("fs/promises");
79563
+ var import_promises84 = require("fs/promises");
79193
79564
  var import_node_net4 = require("net");
79194
79565
  var MAX_RESPONSE_BYTES = 64 * 1024;
79195
79566
  async function readAll2(stream) {
@@ -79306,7 +79677,7 @@ async function configure(argv) {
79306
79677
  }
79307
79678
  async function configureGitGateway(config2, gatewayUrl, signal) {
79308
79679
  const { launcher } = installLayout(config2.installDir, config2.profile);
79309
- const installed = await (0, import_promises83.access)(launcher).then(
79680
+ const installed = await (0, import_promises84.access)(launcher).then(
79310
79681
  () => true,
79311
79682
  () => false
79312
79683
  );
@@ -79556,7 +79927,7 @@ async function runHook(argv, overrides = {}) {
79556
79927
  }
79557
79928
 
79558
79929
  // src/cli/commands/ingestion-hooks.ts
79559
- var import_promises84 = require("fs/promises");
79930
+ var import_promises85 = require("fs/promises");
79560
79931
  var CODEX_TRUST_NOTE = "Codex runs new hooks only after you review them: open /hooks in Codex.";
79561
79932
  function isAction(value2) {
79562
79933
  return value2 === "enable" || value2 === "disable" || value2 === "status";
@@ -79579,7 +79950,7 @@ function errorMessage2(error62) {
79579
79950
  return error62 instanceof Error ? error62.message : String(error62);
79580
79951
  }
79581
79952
  async function exists5(path4) {
79582
- return (0, import_promises84.access)(path4).then(
79953
+ return (0, import_promises85.access)(path4).then(
79583
79954
  () => true,
79584
79955
  () => false
79585
79956
  );
@@ -79962,7 +80333,7 @@ async function runToken(argv, signal) {
79962
80333
  }
79963
80334
 
79964
80335
  // src/cli/commands/logout.ts
79965
- var import_promises85 = require("fs/promises");
80336
+ var import_promises86 = require("fs/promises");
79966
80337
  var import_node_path105 = require("path");
79967
80338
  init_runtime_v2();
79968
80339
  var RUNTIME_EXIT_WAIT_MS = 35e3;
@@ -80022,7 +80393,7 @@ async function stopHolder(launch, deps, outcome2) {
80022
80393
  }
80023
80394
  async function stopHeldRuns(ctx, deps, outcome2 = "aborted") {
80024
80395
  const stopped = [];
80025
- for (const name of await (0, import_promises85.readdir)(ctx.paths.sessions).catch(() => [])) {
80396
+ for (const name of await (0, import_promises86.readdir)(ctx.paths.sessions).catch(() => [])) {
80026
80397
  const launch = await readJsonFile(
80027
80398
  (0, import_node_path105.join)(ctx.paths.sessions, name, "launch.json"),
80028
80399
  holderLaunchSchema
@@ -80061,7 +80432,7 @@ async function forgetMachineLocally(ctx) {
80061
80432
  const machine = await readMachineFile(ctx.paths);
80062
80433
  if (machine === null) return;
80063
80434
  await credentialStoreFor(ctx.paths, machine.credentialStore, ctx.access).clear();
80064
- await (0, import_promises85.rm)(ctx.paths.machine, { force: true });
80435
+ await (0, import_promises86.rm)(ctx.paths.machine, { force: true });
80065
80436
  }
80066
80437
  async function runLogout(argv, signal) {
80067
80438
  var _stack = [];
@@ -80163,7 +80534,7 @@ function createRunAppends() {
80163
80534
 
80164
80535
  // src/local-api/server.ts
80165
80536
  var import_node_crypto57 = require("crypto");
80166
- var import_promises86 = require("fs/promises");
80537
+ var import_promises87 = require("fs/promises");
80167
80538
  var import_node_http6 = require("http");
80168
80539
  var import_node_path106 = require("path");
80169
80540
 
@@ -81270,7 +81641,7 @@ async function serveLocalApi(deps) {
81270
81641
  await watchedStatus[Symbol.asyncDispose]();
81271
81642
  const current = await readJsonFile(discoveryPath, localApiDiscoverySchema);
81272
81643
  if (current.kind === "ok" && current.value.token === token) {
81273
- await (0, import_promises86.rm)(discoveryPath, { force: true });
81644
+ await (0, import_promises87.rm)(discoveryPath, { force: true });
81274
81645
  }
81275
81646
  await closeServer(server);
81276
81647
  log.info("local_api.closed", {});
@@ -81278,34 +81649,22 @@ async function serveLocalApi(deps) {
81278
81649
  };
81279
81650
  }
81280
81651
 
81281
- // src/cli/commands/app-gone.ts
81282
- var APP_GONE_CHECK_MS = 1e3;
81283
- var APP_GONE_GRACE_MS = 1e4;
81284
- function watchAppGone(options) {
81652
+ // src/cli/commands/app-quit.ts
81653
+ var APP_QUIT_CHECK_MS = 1e3;
81654
+ function watchAppQuit(options) {
81285
81655
  const { appAttachments, clock, lifecycle, log } = options;
81286
- const graceMs = options.graceMs ?? APP_GONE_GRACE_MS;
81287
81656
  const stop = new AbortController();
81288
- const goneFor = () => {
81289
- const lostSinceMs = appAttachments.lostSinceMs();
81290
- return lostSinceMs === null ? null : clock.monotonic() - lostSinceMs;
81291
- };
81292
81657
  const check3 = async (signal) => {
81293
- if (stop.signal.aborted) return;
81294
- const quit2 = appAttachments.quitRequested();
81295
- const gone = goneFor();
81296
- if (!quit2 && (gone === null || gone < graceMs)) return;
81297
- const stopped = await lifecycle.exclusive("stop_app_gone", async () => {
81298
- if (!quit2 && goneFor() === null) return false;
81658
+ if (stop.signal.aborted || !appAttachments.quitRequested()) return;
81659
+ await lifecycle.exclusive("stop_app_quit", async () => {
81299
81660
  await options.interruptAllRuns(signal);
81300
- return true;
81301
81661
  });
81302
- if (!stopped) return;
81303
- log.info(quit2 ? "runtime.app_quit" : "runtime.app_gone_stop", { goneMs: gone });
81662
+ log.info("runtime.app_quit");
81304
81663
  stop.abort();
81305
81664
  };
81306
81665
  const maintenance = startMaintenance({
81307
- everyMs: options.everyMs ?? APP_GONE_CHECK_MS,
81308
- jobs: [{ name: "runtime.app_gone_check", run: check3 }],
81666
+ everyMs: options.everyMs ?? APP_QUIT_CHECK_MS,
81667
+ jobs: [{ name: "runtime.app_quit_check", run: check3 }],
81309
81668
  clock,
81310
81669
  log
81311
81670
  });
@@ -85026,7 +85385,7 @@ function refusalFailure(refusal2) {
85026
85385
  }
85027
85386
 
85028
85387
  // src/link/probe.ts
85029
- var import_promises87 = require("dns/promises");
85388
+ var import_promises88 = require("dns/promises");
85030
85389
  var import_node_net5 = require("net");
85031
85390
  var import_node_tls2 = require("tls");
85032
85391
  var PROBE_TIMEOUT_MS4 = 5e3;
@@ -85062,7 +85421,7 @@ async function connectOnce(url3, clock) {
85062
85421
  }
85063
85422
  async function probeEndpoint(url3, clock) {
85064
85423
  try {
85065
- await (0, import_promises87.lookup)(url3.hostname);
85424
+ await (0, import_promises88.lookup)(url3.hostname);
85066
85425
  } catch (error62) {
85067
85426
  const reason = classifyTransportFailure(error62);
85068
85427
  return reason === "other" ? "dns" : reason;
@@ -85667,7 +86026,7 @@ function createReconciler(host, lifecycle, log, signal, clock = systemClock) {
85667
86026
  }
85668
86027
 
85669
86028
  // src/uploader/index.ts
85670
- var import_promises88 = require("fs/promises");
86029
+ var import_promises89 = require("fs/promises");
85671
86030
  init_runtime_v2();
85672
86031
  init_zod();
85673
86032
  var RETRY_DELAYS_MS = [250, 500, 1e3, 2e3, 5e3, 1e4, 3e4];
@@ -85957,13 +86316,13 @@ function startUploader({
85957
86316
  const isDone = (runId) => sealed.has(runId) || archive?.has(runId) === true;
85958
86317
  const unsealedRunIds = async () => {
85959
86318
  const runIds = [];
85960
- for (const name of await (0, import_promises88.readdir)(runsDir).catch(() => [])) {
86319
+ for (const name of await (0, import_promises89.readdir)(runsDir).catch(() => [])) {
85961
86320
  const runId = runIdSchema.safeParse(name);
85962
86321
  if (runId.success && !isDone(runId.data)) runIds.push(runId.data);
85963
86322
  }
85964
86323
  return runIds;
85965
86324
  };
85966
- const hasProgress = async (runId) => await (0, import_promises88.stat)(runDirectory(runsDir, runId).upload).catch(() => null) !== null;
86325
+ const hasProgress = async (runId) => await (0, import_promises89.stat)(runDirectory(runsDir, runId).upload).catch(() => null) !== null;
85967
86326
  const sweep2 = async () => {
85968
86327
  for (const runId of await unsealedRunIds()) {
85969
86328
  if (!await hasProgress(runId)) run2(runId);
@@ -85979,13 +86338,13 @@ function startUploader({
85979
86338
  const dir = runDirectory(runsDir, runId);
85980
86339
  const progress = await readJsonFile(dir.upload, uploadProgressSchema);
85981
86340
  if (progress.kind !== "ok" || !progress.value.sealed) return false;
85982
- const sealedAt = (await (0, import_promises88.stat)(dir.upload)).mtimeMs;
86341
+ const sealedAt = (await (0, import_promises89.stat)(dir.upload)).mtimeMs;
85983
86342
  if (clock.now() - sealedAt < options.sealedForMs) return false;
85984
86343
  return (await readLastRecord(dir.log))?.update.sessionUpdate === "_alan/run.ended";
85985
86344
  };
85986
86345
  const archivable = async (options) => {
85987
86346
  const found = [];
85988
- for (const name of await (0, import_promises88.readdir)(runsDir).catch(() => [])) {
86347
+ for (const name of await (0, import_promises89.readdir)(runsDir).catch(() => [])) {
85989
86348
  const runId = runIdSchema.safeParse(name);
85990
86349
  if (!runId.success || archive?.has(runId.data)) continue;
85991
86350
  try {
@@ -86205,24 +86564,35 @@ async function startGitHubProxySidecar(deps) {
86205
86564
  function createCapabilityPublisher(deps) {
86206
86565
  const { inventory, log } = deps;
86207
86566
  let stored = null;
86567
+ let closed = false;
86208
86568
  const publish = async (scanned, onlyChanges) => {
86209
86569
  const capabilities = await scanned;
86570
+ if (closed) return;
86210
86571
  if (onlyChanges && stored !== null && sameCapabilities(stored, capabilities)) return;
86211
86572
  if (await deps.push(capabilities)) stored = capabilities;
86212
86573
  };
86213
- const report2 = (error62) => log.warn("capabilities.publish_failed", { error: error62 });
86574
+ const report2 = (error62) => {
86575
+ if (!closed) log.warn("capabilities.publish_failed", { error: error62 });
86576
+ };
86577
+ const start2 = (scanned, onlyChanges) => {
86578
+ if (closed) return Promise.resolve();
86579
+ return publish(scanned, onlyChanges).catch(report2);
86580
+ };
86214
86581
  return {
86215
86582
  connected: () => {
86216
- publish(inventory.latest(), false).catch(report2);
86583
+ void start2(inventory.latest(), false);
86217
86584
  },
86218
86585
  rescan: () => {
86219
- publish(inventory.scan({ refresh: true }), true).catch(report2);
86586
+ void start2(inventory.scan({ refresh: true }), true);
86220
86587
  },
86221
- rescanIfChanged: () => publish(inventory.rescanIfChanged(), true).catch(report2),
86588
+ rescanIfChanged: () => start2(inventory.rescanIfChanged(), true),
86222
86589
  answerScan: async (request2) => {
86223
86590
  const capabilities = await inventory.scan({ refresh: request2.refresh === true });
86224
86591
  stored = capabilities;
86225
86592
  return capabilities;
86593
+ },
86594
+ close: async () => {
86595
+ closed = true;
86226
86596
  }
86227
86597
  };
86228
86598
  }
@@ -86896,6 +87266,7 @@ async function startMachinePlane(deps) {
86896
87266
  push: (scanned) => link.pushCapabilities(scanned),
86897
87267
  log
86898
87268
  });
87269
+ stack.use({ [Symbol.asyncDispose]: () => capabilities.close() });
86899
87270
  stack.use(
86900
87271
  startMaintenance({
86901
87272
  everyMs: CAPABILITY_CHECK_MS,
@@ -87458,7 +87829,7 @@ async function runService(argv, stop, restart = new AbortController().signal) {
87458
87829
  clock,
87459
87830
  log
87460
87831
  }), true);
87461
- const appGone = __using(_stack, watchAppGone({
87832
+ const appQuit = __using(_stack, watchAppQuit({
87462
87833
  appAttachments: localApi.appAttachments,
87463
87834
  lifecycle,
87464
87835
  interruptAllRuns: (signal) => machine.interruptAllRuns(signal),
@@ -87473,7 +87844,7 @@ async function runService(argv, stop, restart = new AbortController().signal) {
87473
87844
  });
87474
87845
  return await awaitRuntimeExit(
87475
87846
  {
87476
- stop: AbortSignal.any([stop, stopForUpdate.signal, appGone.stopRequested]),
87847
+ stop: AbortSignal.any([stop, stopForUpdate.signal, appQuit.stopRequested]),
87477
87848
  restart: AbortSignal.any([
87478
87849
  restart,
87479
87850
  updateInstalled.signal,
@@ -87529,17 +87900,17 @@ async function runServiceCommand(argv, ctx = cliContext()) {
87529
87900
  }
87530
87901
 
87531
87902
  // src/cli/commands/upgrade.ts
87532
- var import_promises89 = require("fs/promises");
87903
+ var import_promises90 = require("fs/promises");
87533
87904
  var import_node_path111 = require("path");
87534
87905
  function isNotNewer(version2, installed) {
87535
87906
  return installed !== null && isReleaseVersion(version2) && isReleaseVersion(installed) && compareVersions(version2, installed) <= 0;
87536
87907
  }
87537
87908
  async function installFromSource(source) {
87538
87909
  const { layout, from, ifNewer } = source;
87539
- const isTarball = (await (0, import_promises89.stat)(from)).isFile();
87910
+ const isTarball = (await (0, import_promises90.stat)(from)).isFile();
87540
87911
  const downloads = (0, import_node_path111.join)(layout.root, ".downloads");
87541
- if (isTarball) await (0, import_promises89.mkdir)(downloads, { recursive: true, mode: 448 });
87542
- const scratch = isTarball ? await (0, import_promises89.mkdtemp)((0, import_node_path111.join)(downloads, "upgrade-")) : null;
87912
+ if (isTarball) await (0, import_promises90.mkdir)(downloads, { recursive: true, mode: 448 });
87913
+ const scratch = isTarball ? await (0, import_promises90.mkdtemp)((0, import_node_path111.join)(downloads, "upgrade-")) : null;
87543
87914
  try {
87544
87915
  const sourceDir = scratch === null ? from : await extractPackageTarball(from, scratch);
87545
87916
  const version2 = await readPackageVersion(sourceDir);
@@ -87547,7 +87918,7 @@ async function installFromSource(source) {
87547
87918
  if (ifNewer && isNotNewer(version2, installed)) return { kind: "skipped", version: version2, installed };
87548
87919
  return { kind: "installed", ...await installVersion(layout, sourceDir) };
87549
87920
  } finally {
87550
- if (scratch !== null) await (0, import_promises89.rm)(scratch, { recursive: true, force: true });
87921
+ if (scratch !== null) await (0, import_promises90.rm)(scratch, { recursive: true, force: true });
87551
87922
  }
87552
87923
  }
87553
87924
  async function runUpgrade(argv) {