@alan-ai-hq/agent-manager-darwin-arm64 0.1.177 → 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
@@ -22609,7 +22609,7 @@ function isRunLifecycleKind(sessionUpdate2) {
22609
22609
  function alignedLength(bytes) {
22610
22610
  return bytes.lastIndexOf(RUN_LOG_RECORD_SEPARATOR) + 1;
22611
22611
  }
22612
- 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;
22613
22613
  var init_run_log = __esm({
22614
22614
  "../shared/src/runtime-v2/run-log.ts"() {
22615
22615
  "use strict";
@@ -22622,6 +22622,7 @@ var init_run_log = __esm({
22622
22622
  RUN_LOG_PROTOCOL_HEADER = "x-alan-log-protocol";
22623
22623
  RUN_LOG_RECORD_SEPARATOR = 10;
22624
22624
  RUN_STEERS_MAX = 100;
22625
+ HOLDER_LOST_RUN_MESSAGE = "The computer stopped mid-turn";
22625
22626
  runAcceptedUpdateSchema = external_exports.object({
22626
22627
  sessionUpdate: external_exports.literal("_alan/run.accepted"),
22627
22628
  machineId: machineIdSchema,
@@ -22739,6 +22740,7 @@ var init_holder_protocol = __esm({
22739
22740
  startedAtMs: external_exports.number().int().nonnegative(),
22740
22741
  /** Wall clock, epoch ms; null while a turn runs. */
22741
22742
  idleSinceMs: external_exports.number().int().nonnegative().nullable(),
22743
+ hasBackgroundWork: external_exports.boolean().default(false),
22742
22744
  holderRssBytes: external_exports.number().int().nonnegative(),
22743
22745
  /** The live provider CLI; null when none is running. */
22744
22746
  cliPid: external_exports.number().int().positive().nullable(),
@@ -32933,6 +32935,8 @@ function createPersistentDriver(provider4, options) {
32933
32935
  if (current.key === key && !current.session.recycleBeforeNextTurn) return current.session;
32934
32936
  log.info("holder.session_respawn", { harness: provider4.harness, runId: spec.runId });
32935
32937
  await current.session.suspend();
32938
+ live.sessionEvents?.[Symbol.dispose]();
32939
+ live.sessionEvents = void 0;
32936
32940
  return void 0;
32937
32941
  };
32938
32942
  const resumeNotice = (spec, session, sink) => {
@@ -32968,6 +32972,14 @@ function createPersistentDriver(provider4, options) {
32968
32972
  }
32969
32973
  const opened = await provider4.open(planned.spec);
32970
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
+ });
32971
32983
  log.info("holder.session_opened", {
32972
32984
  harness: provider4.harness,
32973
32985
  pid: opened.session.pid,
@@ -33201,6 +33213,23 @@ function createPersistentDriver(provider4, options) {
33201
33213
  },
33202
33214
  suspend: async () => {
33203
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
+ };
33204
33233
  },
33205
33234
  respond,
33206
33235
  steer,
@@ -37263,8 +37292,26 @@ var init_task_records = __esm({
37263
37292
  get(taskId) {
37264
37293
  return this.#records.get(taskId);
37265
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
+ }
37266
37313
  /** Registers or refreshes a task from Claude's `task_started`. */
37267
- track(event, launcherToolUseId) {
37314
+ track(event, launcherToolUseId, ownerTurnId) {
37268
37315
  const taskId = nonEmpty(event.task_id);
37269
37316
  if (!taskId) return;
37270
37317
  const existing = this.#records.get(taskId);
@@ -37288,6 +37335,7 @@ var init_task_records = __esm({
37288
37335
  status: existing?.meta.status ?? "running"
37289
37336
  },
37290
37337
  launcherToolUseId: launcherToolUseId ?? existing?.launcherToolUseId,
37338
+ ownerTurnId: ownerTurnId ?? existing?.ownerTurnId,
37291
37339
  userStopRequested: existing?.userStopRequested ?? false
37292
37340
  });
37293
37341
  }
@@ -37858,7 +37906,7 @@ var init_turn3 = __esm({
37858
37906
  if (subtype === "compact_boundary") this.#noteCompaction(event);
37859
37907
  if (subtype === "task_started") {
37860
37908
  this.tasks.registerRecord(event, parentToolUseId(event));
37861
- this.taskRecords.track(event, this.tasks.resolveToolUseId(event));
37909
+ this.taskRecords.track(event, this.tasks.resolveToolUseId(event), this.#options.turnId);
37862
37910
  const updates = backgroundTaskIdentity(event, this.tasks);
37863
37911
  return updates.length ? updates : [unlinkedTaskEvent(event)];
37864
37912
  }
@@ -37999,6 +38047,10 @@ var init_turn3 = __esm({
37999
38047
  return;
38000
38048
  }
38001
38049
  if (this.tasks.size > 0) {
38050
+ if (this.taskRecords.coversActiveBackgroundTasks(this.tasks.active)) {
38051
+ this.#finalized = true;
38052
+ return;
38053
+ }
38002
38054
  this.#deferredOnBackground = true;
38003
38055
  return;
38004
38056
  }
@@ -38194,6 +38246,8 @@ var init_driver4 = __esm({
38194
38246
  #stderr = [];
38195
38247
  #replaysUserMessages;
38196
38248
  #taskRecords;
38249
+ #backgroundTurns = /* @__PURE__ */ new Map();
38250
+ #lateSynthesisOwners = [];
38197
38251
  #taskStops = /* @__PURE__ */ new Map();
38198
38252
  #state = "idle";
38199
38253
  #current;
@@ -38234,6 +38288,9 @@ var init_driver4 = __esm({
38234
38288
  get lastOutputAt() {
38235
38289
  return this.#host.lastOutputAt;
38236
38290
  }
38291
+ hasBackgroundWork(turnId) {
38292
+ return this.#taskRecords.hasRunningBackgroundTask(turnId) || (turnId === void 0 ? this.#lateSynthesisOwners.length > 0 : this.#lateSynthesisOwners.includes(turnId));
38293
+ }
38237
38294
  get backgroundTasks() {
38238
38295
  return this.#taskRecords.running;
38239
38296
  }
@@ -38248,6 +38305,7 @@ var init_driver4 = __esm({
38248
38305
  const resumedSessionId = this.#turnsStarted === 0 ? this.#resumeId : void 0;
38249
38306
  this.#turnsStarted += 1;
38250
38307
  const turn = new ClaudeTurn({
38308
+ turnId: input2.turnId,
38251
38309
  selectedModel: this.#selectedModel,
38252
38310
  resumedSessionId,
38253
38311
  model: this.#lastTurn.grammar.model,
@@ -38393,6 +38451,7 @@ var init_driver4 = __esm({
38393
38451
  if (this.#current?.id !== id) return;
38394
38452
  this.#current = void 0;
38395
38453
  this.#lastTurn = turn;
38454
+ if (this.#taskRecords.hasRunningBackgroundTask(id)) this.#backgroundTurns.set(id, turn);
38396
38455
  if (this.#state === "busy") this.#state = "idle";
38397
38456
  this.#emit({ type: "turn_ended", turnId: id, outcome: outcome2 });
38398
38457
  resolve16({ turnId: id, outcome: outcome2, providerSessionId: this.#providerSessionId });
@@ -38455,15 +38514,43 @@ var init_driver4 = __esm({
38455
38514
  for (const held of active.early.splice(0)) this.#read(void 0, held);
38456
38515
  }
38457
38516
  #read(active, line) {
38458
- const parser = active?.turn ?? this.#lastTurn;
38459
- for (const update of parser.readLine(line)) {
38460
- this.#emit({ type: "update", turnId: active?.id, update });
38461
- }
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);
38462
38529
  this.#noteSessionId(parser.sessionId);
38463
- if (!active) return;
38530
+ if (!active || backgroundTurn) return;
38464
38531
  if (line.kind === "record" && line.record.type === "result") active.lastResult = line.record;
38465
38532
  this.#settle(active, line);
38466
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
+ }
38467
38554
  #settle(active, line) {
38468
38555
  this.#host.scanDescendants(false);
38469
38556
  const isResult = line.kind === "record" && line.record.type === "result";
@@ -40839,6 +40926,7 @@ var STDERR_TAIL_LINES4, MAX_BETWEEN_UPDATES2, UNSUPPORTED_REQUEST, DECLINED_ELIC
40839
40926
  var init_session4 = __esm({
40840
40927
  "../agent-core/src/providers/codex/session.ts"() {
40841
40928
  "use strict";
40929
+ init_acp();
40842
40930
  init_acp2();
40843
40931
  init_classify2();
40844
40932
  init_kernel();
@@ -40868,6 +40956,8 @@ var init_session4 = __esm({
40868
40956
  #approvals = /* @__PURE__ */ new Map();
40869
40957
  /** Session-level updates (thread start warnings, MCP startup) that open the next turn's log. */
40870
40958
  #between = [];
40959
+ #backgroundLaunchers = /* @__PURE__ */ new Map();
40960
+ #workerOwners = /* @__PURE__ */ new Map();
40871
40961
  #config = { approvals: "ask" };
40872
40962
  #threadId;
40873
40963
  #rolloutPath;
@@ -40912,6 +41002,19 @@ var init_session4 = __esm({
40912
41002
  get lastOutputAt() {
40913
41003
  return this.#host.lastOutputAt;
40914
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
+ }
40915
41018
  get exited() {
40916
41019
  return this.#host.exited;
40917
41020
  }
@@ -41080,7 +41183,11 @@ var init_session4 = __esm({
41080
41183
  /** Notifications from another turn (a late one after an interrupt) go out as session records. */
41081
41184
  #ownerOf(notification) {
41082
41185
  const active = this.#current;
41083
- 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
+ }
41084
41191
  const turnId = asString(notification.params.turnId) || asString(asRecord(notification.params.turn)?.id);
41085
41192
  if (!active || !turnId) return active;
41086
41193
  const known = active.turn.codexTurnId;
@@ -41095,11 +41202,19 @@ var init_session4 = __esm({
41095
41202
  const active = this.#ownerOf(notification);
41096
41203
  const reader = active?.turn ?? this.#lastTurn;
41097
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
+ }
41098
41213
  if (!active) {
41099
- this.#between.push(...updates);
41100
- this.#between.splice(0, Math.max(0, this.#between.length - MAX_BETWEEN_UPDATES2));
41214
+ this.#betweenNotification(updates, ownerTurnId);
41101
41215
  return;
41102
41216
  }
41217
+ this.#trackBackground(updates, ownerTurnId);
41103
41218
  if (active.turn.codexTurnId) active.identify(active.turn.codexTurnId);
41104
41219
  this.#emitUpdates(active, [...active.images.drain(), ...active.images.admit(updates)]);
41105
41220
  this.#host.scanDescendants(false);
@@ -41117,6 +41232,20 @@ var init_session4 = __esm({
41117
41232
  void this.#stopTurn(active);
41118
41233
  }
41119
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
+ }
41120
41249
  #recordRateLimits(updates) {
41121
41250
  const active = this.#current;
41122
41251
  if (active) this.#emitUpdates(active, updates);
@@ -60570,7 +60699,7 @@ var import_node_worker_threads2 = require("worker_threads");
60570
60699
  // package.json
60571
60700
  var package_default = {
60572
60701
  name: "@alan-ai-hq/agent-manager",
60573
- version: "0.1.177",
60702
+ version: "0.1.178",
60574
60703
  private: true,
60575
60704
  type: "module",
60576
60705
  description: "Alan machine runtime (alan-agent): identity, link, reconciler, session holders, run log, uploader, local API",
@@ -60912,13 +61041,19 @@ function createLog(level, clock, sink) {
60912
61041
  function openFileLog(path4, level, clock) {
60913
61042
  (0, import_node_fs2.mkdirSync)((0, import_node_path2.dirname)(path4), { recursive: true, mode: 448 });
60914
61043
  const fd = (0, import_node_fs2.openSync)(path4, "a", 384);
61044
+ let closed = false;
60915
61045
  const log = createLog(level, clock, (entry) => {
61046
+ if (closed) return;
60916
61047
  (0, import_node_fs2.writeSync)(fd, `${JSON.stringify(entry)}
60917
61048
  `);
60918
61049
  });
60919
61050
  return {
60920
61051
  ...log,
60921
- [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
+ }
60922
61057
  };
60923
61058
  }
60924
61059
  function createMemoryLog(level, clock) {
@@ -64644,15 +64779,22 @@ function writeMessage(socket, message2) {
64644
64779
 
64645
64780
  // src/holder/control-client.ts
64646
64781
  var REQUEST_TIMEOUT_MS7 = 3e4;
64782
+ var READY_TIMEOUT_MS = 15e3;
64647
64783
  var HOLDER_ALREADY_STARTED = "already_started";
64648
64784
  function isReply(message2) {
64649
64785
  return message2.type === "ack" || message2.type === "error" || message2.type === "status" || message2.type === "responded" || message2.type === "steered" || message2.type === "task_stopped";
64650
64786
  }
64651
- async function connectHolder(endpoint, token, onEvent) {
64787
+ async function connectHolder(endpoint, token, onEvent, readyTimeoutMs = READY_TIMEOUT_MS) {
64652
64788
  const socket = (0, import_node_net.connect)(endpoint);
64653
64789
  const pending = /* @__PURE__ */ new Map();
64654
64790
  const closed = new Promise((resolve16) => socket.once("close", () => resolve16()));
64791
+ const deadline = AbortSignal.timeout(readyTimeoutMs);
64655
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
+ );
64656
64798
  socket.once("error", reject);
64657
64799
  socket.once(
64658
64800
  "close",
@@ -64672,7 +64814,10 @@ async function connectHolder(endpoint, token, onEvent) {
64672
64814
  });
64673
64815
  socket.once("connect", () => writeMessage(socket, { type: "auth", token }));
64674
64816
  });
64675
- const pid = await ready;
64817
+ const pid = await ready.catch((error62) => {
64818
+ socket.destroy();
64819
+ throw error62;
64820
+ });
64676
64821
  const request2 = (body) => {
64677
64822
  const id = (0, import_node_crypto11.randomUUID)();
64678
64823
  return new Promise((resolve16, reject) => {
@@ -66542,13 +66687,15 @@ async function configureGit(input2, git) {
66542
66687
  }
66543
66688
  return output2;
66544
66689
  };
66545
- const rewrites = await run2(
66546
- ["config", "--global", "--get-regexp", "^url\\..*\\.insteadof$", `^${GITHUB_URL}`],
66547
- [0, 1]
66548
- );
66549
- for (const line of rewrites.stdout.split("\n")) {
66550
- const key = line.split(" ")[0];
66551
- 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
+ }
66552
66699
  }
66553
66700
  await run2(["config", "--global", `http.${GITHUB_URL}.proxy`, git.proxyUrl]);
66554
66701
  await run2(["config", "--global", `http.${GITHUB_URL}.sslCAInfo`, git.caPath]);
@@ -74290,7 +74437,14 @@ function isActive(activity) {
74290
74437
  function selectDriver(persistent, fallback) {
74291
74438
  const drivers = /* @__PURE__ */ new Set([...Object.values(persistent), fallback]);
74292
74439
  return {
74293
- 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
+ },
74294
74448
  suspend: async () => {
74295
74449
  await Promise.all([...drivers].map((driver) => driver.suspend?.()));
74296
74450
  },
@@ -74341,18 +74495,40 @@ function createLazyValue(load) {
74341
74495
  }
74342
74496
  function createLazyDriver(load) {
74343
74497
  const loaded = {};
74498
+ const backgroundListeners = /* @__PURE__ */ new Set();
74344
74499
  const driver = () => {
74345
- loaded.driver ??= load().then((value2) => {
74346
- loaded.resolved = value2;
74347
- return value2;
74500
+ loaded.driver ??= load().then((resolved) => {
74501
+ loaded.resolved = resolved;
74502
+ return resolved;
74348
74503
  });
74349
74504
  return loaded.driver;
74350
74505
  };
74351
74506
  return {
74352
- 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
+ },
74353
74514
  suspend: async () => {
74354
74515
  if (loaded.driver !== void 0) await (await loaded.driver).suspend?.();
74355
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
+ },
74356
74532
  respond: async (request2) => {
74357
74533
  if (loaded.driver === void 0) return "unknown_run";
74358
74534
  return await (await loaded.driver).respond?.(request2) ?? "unknown_run";
@@ -75266,7 +75442,8 @@ function createSessionFacts(options) {
75266
75442
  managedVersion: null,
75267
75443
  identified: Promise.resolve(),
75268
75444
  loginFailed: false,
75269
- rss: null
75445
+ rss: null,
75446
+ driver: null
75270
75447
  };
75271
75448
  const identify2 = async (command) => {
75272
75449
  const path4 = await resolveCommandOnPath(command, env, platform3);
@@ -75315,30 +75492,33 @@ function createSessionFacts(options) {
75315
75492
  return current?.key !== spawned.key;
75316
75493
  };
75317
75494
  return {
75318
- observe: (driver) => ({
75319
- ...driver,
75320
- runTurn: async (spec, sink, signal, inputs) => {
75321
- state.idleSinceMs = null;
75322
- try {
75323
- const result = await driver.runTurn(
75324
- spec,
75325
- {
75326
- onEvent: (event) => sink.onEvent(event),
75327
- onSpawned: (pid) => {
75328
- state.identified = noteSpawned(spec, pid);
75329
- sink.onSpawned(pid);
75330
- }
75331
- },
75332
- signal,
75333
- inputs
75334
- );
75335
- state.loginFailed = isLoginFailure(result);
75336
- return result;
75337
- } finally {
75338
- 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
+ }
75339
75519
  }
75340
- }
75341
- }),
75520
+ };
75521
+ },
75342
75522
  snapshot: async () => {
75343
75523
  await state.identified;
75344
75524
  const cliRssBytes = await liveCliRss();
@@ -75346,6 +75526,7 @@ function createSessionFacts(options) {
75346
75526
  return {
75347
75527
  startedAtMs: state.startedAtMs,
75348
75528
  idleSinceMs: state.idleSinceMs,
75529
+ hasBackgroundWork: state.driver?.hasBackgroundWork?.() ?? false,
75349
75530
  holderRssBytes: readOwnRss(),
75350
75531
  cliPid: cliAlive ? state.cliPid : null,
75351
75532
  cliRssBytes,
@@ -75720,6 +75901,7 @@ async function readLastRecord(path4) {
75720
75901
  }
75721
75902
 
75722
75903
  // src/run-log/records.ts
75904
+ init_runtime_v2();
75723
75905
  function runAccepted(machineId, acceptedAt) {
75724
75906
  return { sessionUpdate: "_alan/run.accepted", machineId, acceptedAt };
75725
75907
  }
@@ -75730,6 +75912,22 @@ function runEnded(input2) {
75730
75912
  return { sessionUpdate: "_alan/run.ended", ...input2 };
75731
75913
  }
75732
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
+ }
75733
75931
 
75734
75932
  // src/run-log/writer.ts
75735
75933
  var import_node_fs34 = require("fs");
@@ -75933,99 +76131,136 @@ async function claimRun(spec, context) {
75933
76131
  }
75934
76132
  var RUN_END_RETRY_MS = 5e3;
75935
76133
  var RUN_END_DEADLINE_MS = 10 * 6e4;
75936
- async function runClaimedTurn(spec, claimed, context, signal) {
75937
- var _stack = [];
75938
- try {
75939
- const log = __using(_stack, claimed);
75940
- const reported = { error: false };
75941
- const writeFailed = new AbortController();
75942
- let writeError;
75943
- const append = (update, sessionId) => {
75944
- if (writeError !== void 0) return;
75945
- 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 (; ; ) {
75946
76148
  let offset;
75947
76149
  try {
75948
- offset = log.append(update, sessionId);
76150
+ offset = log.append(update);
75949
76151
  } catch (error62) {
75950
- writeError = error62;
75951
- context.log.error("holder.run_log_write_failed", { runId: spec.runId, error: error62 });
75952
- writeFailed.abort();
75953
- return;
75954
- }
75955
- context.onAppended(spec.runId, offset);
75956
- };
75957
- const endRun = async (updates2) => {
75958
- const deadline = context.clock.monotonic() + RUN_END_DEADLINE_MS;
75959
- for (const update of updates2) {
75960
- for (; ; ) {
75961
- let offset;
75962
- try {
75963
- offset = log.append(update);
75964
- } catch (error62) {
75965
- context.log.warn("holder.run_end_write_failed", { runId: spec.runId, error: error62 });
75966
- if (context.clock.monotonic() >= deadline) {
75967
- throw new RuntimeFault("io_failed", `Run ${spec.runId} could not be ended`, {
75968
- cause: error62
75969
- });
75970
- }
75971
- await context.clock.sleep(RUN_END_RETRY_MS, new AbortController().signal);
75972
- continue;
75973
- }
75974
- context.onAppended(spec.runId, offset);
75975
- 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
+ });
75976
76157
  }
76158
+ await context.clock.sleep(RUN_END_RETRY_MS, new AbortController().signal);
76159
+ continue;
75977
76160
  }
75978
- };
75979
- const fail = async (message2) => {
75980
- await endRun([
75981
- noticeUpdate("error", "run_failed", message2),
75982
- runEnded({ outcome: "failed", message: message2 })
75983
- ]);
75984
- return "failed";
75985
- };
75986
- 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;
75987
76205
  try {
75988
- result = await admitAndRun(
75989
- spec,
75990
- context,
75991
- {
75992
- onSpawned: (pid) => append(runStarted({ pid })),
75993
- // Base64 media in provider payloads and tool output never reaches the log (main 13590db369).
75994
- onEvent: (event) => append(fitForRunLog(withoutInlineMedia(event.update)), event.sessionId)
75995
- },
75996
- AbortSignal.any([signal, writeFailed.signal])
75997
- );
76206
+ offset = log.append(update, sessionId);
75998
76207
  } catch (error62) {
75999
- 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 {
76000
76248
  return await fail(error62 instanceof Error ? error62.message : String(error62));
76249
+ } finally {
76250
+ events?.[Symbol.dispose]();
76251
+ log[Symbol.dispose]();
76001
76252
  }
76002
- if (writeError !== void 0) {
76003
- 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 {
76004
76257
  return await fail(`This run's log could not be written: ${reason}`);
76258
+ } finally {
76259
+ events?.[Symbol.dispose]();
76260
+ log[Symbol.dispose]();
76005
76261
  }
76006
- const outcome2 = result.outcome === "aborted" && signal.reason === "interrupted" ? "interrupted" : result.outcome;
76007
- const updates = [];
76008
- if (outcome2 === "failed" && !reported.error && result.message !== void 0) {
76009
- updates.push(noticeUpdate("error", "run_failed", result.message));
76010
- }
76011
- updates.push(
76012
- runEnded({
76013
- outcome: outcome2,
76014
- ...result.providerSessionId === void 0 ? {} : { providerSessionId: result.providerSessionId },
76015
- ...result.message === void 0 ? {} : { message: result.message },
76016
- ...result.problem === void 0 ? {} : { problem: result.problem },
76017
- ...result.rejection === void 0 ? {} : { rejection: result.rejection },
76018
- ...result.unansweredSteerIds === void 0 ? {} : { unansweredSteerIds: [...result.unansweredSteerIds] }
76019
- })
76020
- );
76021
- await endRun(updates);
76022
- context.log.info("holder.turn_ended", { runId: spec.runId, outcome: outcome2 });
76023
- return outcome2;
76024
- } catch (_) {
76025
- var _error = _, _hasError = true;
76026
- } finally {
76027
- __callDispose(_stack, _error, _hasError);
76028
76262
  }
76263
+ return completeClaimedTurn(result, spec, context, signal, log, events, reported.error, endState);
76029
76264
  }
76030
76265
 
76031
76266
  // src/holder/serve.ts
@@ -77385,7 +77620,8 @@ function runOccupancy(held, reserved, exclude = null) {
77385
77620
  var DEFAULT_SUSPEND_POLICY = { idleMs: 30 * 6e4 };
77386
77621
  function idleSince(holder, opened) {
77387
77622
  const { idleSinceMs } = holder.facts;
77388
- 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;
77389
77625
  const openedAtMs = opened?.conversationId === holder.conversationId ? opened.atMs : 0;
77390
77626
  return Math.max(idleSinceMs, openedAtMs);
77391
77627
  }
@@ -77406,6 +77642,13 @@ function planSuspends(holders, policy, nowMs, opened = null) {
77406
77642
 
77407
77643
  // src/sessions/index.ts
77408
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
+ }
77409
77652
  var HOLDER_READY_POLL_MS = 50;
77410
77653
  var HOLDER_EXIT_GRACE_MS = 2e3;
77411
77654
  var DEFAULT_MAX_ACTIVE_RUNS = 32;
@@ -77456,6 +77699,34 @@ async function openSessions(deps) {
77456
77699
  const suspendPolicy = deps.suspendPolicy ?? DEFAULT_SUSPEND_POLICY;
77457
77700
  const admitted = /* @__PURE__ */ new Set();
77458
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
+ };
77459
77730
  const onEvent = (event) => {
77460
77731
  if (event.type === "appended") deps.onAppended(event.runId);
77461
77732
  else deps.onTurnEnded(event.runId);
@@ -77463,11 +77734,18 @@ async function openSessions(deps) {
77463
77734
  const markInterrupted = async (runId) => {
77464
77735
  var _stack = [];
77465
77736
  try {
77466
- const last = await readLastRecord(runDirectory(paths.runs, runId).log);
77737
+ const logPath = runDirectory(paths.runs, runId).log;
77738
+ const last = await readLastRecord(logPath);
77467
77739
  if (last === null || last.update.sessionUpdate === "_alan/run.ended") return;
77468
- const writer = __using(_stack, openRunLog(runDirectory(paths.runs, runId).log, clock));
77469
- writer.append(runEnded({ outcome: "interrupted", message: "The computer stopped mid-turn" }));
77470
- 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 });
77471
77749
  deps.onAppended(runId);
77472
77750
  } catch (_) {
77473
77751
  var _error = _, _hasError = true;
@@ -77504,7 +77782,12 @@ async function openSessions(deps) {
77504
77782
  }
77505
77783
  };
77506
77784
  const attach = async (conversationId, launch) => {
77507
- 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
+ );
77508
77791
  connections.set(conversationId, connection);
77509
77792
  void connection.closed().then(() => {
77510
77793
  if (connections.get(conversationId) !== connection) return;
@@ -77521,7 +77804,11 @@ async function openSessions(deps) {
77521
77804
  const dir = runDirectory(paths.runs, runId);
77522
77805
  if ((await readRunMeta(dir.meta))?.conversationId !== conversationId) continue;
77523
77806
  const last = await readLastRecord(dir.log);
77524
- 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
+ });
77525
77812
  }
77526
77813
  return found;
77527
77814
  };
@@ -77577,8 +77864,12 @@ async function openSessions(deps) {
77577
77864
  log.info("sessions.reattached", { conversationId });
77578
77865
  return;
77579
77866
  }
77580
- if (alive) await removeHolderFiles(files);
77581
- 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);
77582
77873
  };
77583
77874
  const busyRunIds = async () => {
77584
77875
  const busy = /* @__PURE__ */ new Set();
@@ -77588,23 +77879,30 @@ async function openSessions(deps) {
77588
77879
  }
77589
77880
  return busy;
77590
77881
  };
77591
- const scan = async () => {
77592
- for (const conversationId of await listIds(paths.sessions, conversationIdSchema)) {
77593
- await reattachOrRetire(conversationId).catch(
77594
- (error62) => log.warn("sessions.reattach_failed", { conversationId, error: error62 })
77595
- );
77596
- }
77882
+ const scanRunLogs = async (live) => {
77597
77883
  const busy = new Set(await busyRunIds());
77598
77884
  for (const conversationId of legacy.keys()) {
77599
77885
  for (const runId of await unendedRunsOf(conversationId)) busy.add(runId);
77600
77886
  }
77601
77887
  for (const runId of await recentRunIds()) {
77602
- 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;
77603
77890
  await markInterrupted(runId).catch(
77604
77891
  (error62) => log.warn("sessions.interrupt_failed", { runId, error: error62 })
77605
77892
  );
77606
77893
  }
77607
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
+ };
77608
77906
  const spawn11 = async (conversationId) => {
77609
77907
  const files = sessionFiles(paths, conversationId);
77610
77908
  const launch = {
@@ -77646,10 +77944,10 @@ async function openSessions(deps) {
77646
77944
  const held = {
77647
77945
  runId,
77648
77946
  conversationId: meta3.conversationId,
77649
- 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",
77650
77948
  loggedBytes: toByteOffset(logged.size)
77651
77949
  };
77652
- if (held.state === "ended") endedRuns.set(runId, held);
77950
+ if (last.update.sessionUpdate === "_alan/run.ended") endedRuns.set(runId, held);
77653
77951
  return held;
77654
77952
  };
77655
77953
  const launchedNotLogged = (logged) => {
@@ -77660,13 +77958,17 @@ async function openSessions(deps) {
77660
77958
  }
77661
77959
  return held;
77662
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
+ };
77663
77965
  const heldRuns = async () => {
77664
77966
  const held = [...starting.values()].map(
77665
77967
  ({ run: run2 }) => notLoggedRun(run2.runId, run2.conversationId)
77666
77968
  );
77667
77969
  const logged = /* @__PURE__ */ new Set();
77668
77970
  const onDisk = new Set(await recentRunIds());
77669
- for (const runId of endedRuns.keys()) if (!onDisk.has(runId)) endedRuns.delete(runId);
77971
+ forgetRemovedRuns(onDisk);
77670
77972
  for (const runId of onDisk) {
77671
77973
  const run2 = starting.has(runId) ? null : await loggedRun(runId);
77672
77974
  if (run2 === null) continue;
@@ -77770,6 +78072,10 @@ async function openSessions(deps) {
77770
78072
  return "waiting";
77771
78073
  }
77772
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
+ }
77773
78079
  if (!connections.has(run2.conversationId)) await spawn11(run2.conversationId);
77774
78080
  const connection = connections.get(run2.conversationId);
77775
78081
  if (connection === void 0) {
@@ -81343,34 +81649,22 @@ async function serveLocalApi(deps) {
81343
81649
  };
81344
81650
  }
81345
81651
 
81346
- // src/cli/commands/app-gone.ts
81347
- var APP_GONE_CHECK_MS = 1e3;
81348
- var APP_GONE_GRACE_MS = 1e4;
81349
- function watchAppGone(options) {
81652
+ // src/cli/commands/app-quit.ts
81653
+ var APP_QUIT_CHECK_MS = 1e3;
81654
+ function watchAppQuit(options) {
81350
81655
  const { appAttachments, clock, lifecycle, log } = options;
81351
- const graceMs = options.graceMs ?? APP_GONE_GRACE_MS;
81352
81656
  const stop = new AbortController();
81353
- const goneFor = () => {
81354
- const lostSinceMs = appAttachments.lostSinceMs();
81355
- return lostSinceMs === null ? null : clock.monotonic() - lostSinceMs;
81356
- };
81357
81657
  const check3 = async (signal) => {
81358
- if (stop.signal.aborted) return;
81359
- const quit2 = appAttachments.quitRequested();
81360
- const gone = goneFor();
81361
- if (!quit2 && (gone === null || gone < graceMs)) return;
81362
- const stopped = await lifecycle.exclusive("stop_app_gone", async () => {
81363
- if (!quit2 && goneFor() === null) return false;
81658
+ if (stop.signal.aborted || !appAttachments.quitRequested()) return;
81659
+ await lifecycle.exclusive("stop_app_quit", async () => {
81364
81660
  await options.interruptAllRuns(signal);
81365
- return true;
81366
81661
  });
81367
- if (!stopped) return;
81368
- log.info(quit2 ? "runtime.app_quit" : "runtime.app_gone_stop", { goneMs: gone });
81662
+ log.info("runtime.app_quit");
81369
81663
  stop.abort();
81370
81664
  };
81371
81665
  const maintenance = startMaintenance({
81372
- everyMs: options.everyMs ?? APP_GONE_CHECK_MS,
81373
- 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 }],
81374
81668
  clock,
81375
81669
  log
81376
81670
  });
@@ -86270,24 +86564,35 @@ async function startGitHubProxySidecar(deps) {
86270
86564
  function createCapabilityPublisher(deps) {
86271
86565
  const { inventory, log } = deps;
86272
86566
  let stored = null;
86567
+ let closed = false;
86273
86568
  const publish = async (scanned, onlyChanges) => {
86274
86569
  const capabilities = await scanned;
86570
+ if (closed) return;
86275
86571
  if (onlyChanges && stored !== null && sameCapabilities(stored, capabilities)) return;
86276
86572
  if (await deps.push(capabilities)) stored = capabilities;
86277
86573
  };
86278
- 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
+ };
86279
86581
  return {
86280
86582
  connected: () => {
86281
- publish(inventory.latest(), false).catch(report2);
86583
+ void start2(inventory.latest(), false);
86282
86584
  },
86283
86585
  rescan: () => {
86284
- publish(inventory.scan({ refresh: true }), true).catch(report2);
86586
+ void start2(inventory.scan({ refresh: true }), true);
86285
86587
  },
86286
- rescanIfChanged: () => publish(inventory.rescanIfChanged(), true).catch(report2),
86588
+ rescanIfChanged: () => start2(inventory.rescanIfChanged(), true),
86287
86589
  answerScan: async (request2) => {
86288
86590
  const capabilities = await inventory.scan({ refresh: request2.refresh === true });
86289
86591
  stored = capabilities;
86290
86592
  return capabilities;
86593
+ },
86594
+ close: async () => {
86595
+ closed = true;
86291
86596
  }
86292
86597
  };
86293
86598
  }
@@ -86961,6 +87266,7 @@ async function startMachinePlane(deps) {
86961
87266
  push: (scanned) => link.pushCapabilities(scanned),
86962
87267
  log
86963
87268
  });
87269
+ stack.use({ [Symbol.asyncDispose]: () => capabilities.close() });
86964
87270
  stack.use(
86965
87271
  startMaintenance({
86966
87272
  everyMs: CAPABILITY_CHECK_MS,
@@ -87523,7 +87829,7 @@ async function runService(argv, stop, restart = new AbortController().signal) {
87523
87829
  clock,
87524
87830
  log
87525
87831
  }), true);
87526
- const appGone = __using(_stack, watchAppGone({
87832
+ const appQuit = __using(_stack, watchAppQuit({
87527
87833
  appAttachments: localApi.appAttachments,
87528
87834
  lifecycle,
87529
87835
  interruptAllRuns: (signal) => machine.interruptAllRuns(signal),
@@ -87538,7 +87844,7 @@ async function runService(argv, stop, restart = new AbortController().signal) {
87538
87844
  });
87539
87845
  return await awaitRuntimeExit(
87540
87846
  {
87541
- stop: AbortSignal.any([stop, stopForUpdate.signal, appGone.stopRequested]),
87847
+ stop: AbortSignal.any([stop, stopForUpdate.signal, appQuit.stopRequested]),
87542
87848
  restart: AbortSignal.any([
87543
87849
  restart,
87544
87850
  updateInstalled.signal,