@alan-ai-hq/agent-manager-darwin-arm64 0.1.151 → 0.1.152

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.
Files changed (3) hide show
  1. package/alan-agent.cjs +468 -920
  2. package/alan-holder.cjs +243 -744
  3. package/package.json +1 -1
package/alan-agent.cjs CHANGED
@@ -22720,7 +22720,7 @@ function plan(command, args, options) {
22720
22720
  function captureOutput(command, args, options) {
22721
22721
  const launch = plan(command, args, options);
22722
22722
  if (launch === void 0) return Promise.resolve(NEVER_STARTED);
22723
- return new Promise((resolve14) => {
22723
+ return new Promise((resolve13) => {
22724
22724
  (0, import_child_process.execFile)(
22725
22725
  launch.file,
22726
22726
  [...launch.args],
@@ -22734,7 +22734,7 @@ function captureOutput(command, args, options) {
22734
22734
  },
22735
22735
  (error61, stdout, stderr) => {
22736
22736
  const code = error61 && typeof error61.code === "number" ? error61.code : error61 ? void 0 : 0;
22737
- resolve14({ stdout, stderr, exitCode: code });
22737
+ resolve13({ stdout, stderr, exitCode: code });
22738
22738
  }
22739
22739
  );
22740
22740
  });
@@ -22776,18 +22776,18 @@ function decode3(bytes, start, end) {
22776
22776
  }
22777
22777
  async function linuxStartTicks(pid) {
22778
22778
  try {
22779
- const stat23 = await (0, import_promises9.readFile)(`/proc/${pid}/stat`, "utf8");
22780
- const fields = stat23.slice(stat23.lastIndexOf(")") + 2).split(" ");
22779
+ const stat22 = await (0, import_promises9.readFile)(`/proc/${pid}/stat`, "utf8");
22780
+ const fields = stat22.slice(stat22.lastIndexOf(")") + 2).split(" ");
22781
22781
  return fields[19];
22782
22782
  } catch {
22783
22783
  return void 0;
22784
22784
  }
22785
22785
  }
22786
22786
  function psStartTime(pid) {
22787
- return new Promise((resolve14) => {
22787
+ return new Promise((resolve13) => {
22788
22788
  (0, import_child_process2.execFile)("ps", ["-o", "lstart=", "-p", String(pid)], { timeout: 2e3 }, (error61, stdout) => {
22789
22789
  const text3 = stdout.trim();
22790
- resolve14(error61 || !text3 ? void 0 : text3);
22790
+ resolve13(error61 || !text3 ? void 0 : text3);
22791
22791
  });
22792
22792
  });
22793
22793
  }
@@ -22816,12 +22816,12 @@ function parseProcessList(text3) {
22816
22816
  }
22817
22817
  function listProcesses(platform3 = process.platform) {
22818
22818
  if (platform3 === "win32") return Promise.resolve([]);
22819
- return new Promise((resolve14) => {
22819
+ return new Promise((resolve13) => {
22820
22820
  (0, import_child_process3.execFile)(
22821
22821
  "ps",
22822
22822
  ["-A", "-o", "pid=,ppid=,pgid=,lstart="],
22823
22823
  { timeout: 5e3, maxBuffer: 8 * 1024 * 1024 },
22824
- (error61, stdout) => resolve14(error61 ? [] : parseProcessList(stdout))
22824
+ (error61, stdout) => resolve13(error61 ? [] : parseProcessList(stdout))
22825
22825
  );
22826
22826
  });
22827
22827
  }
@@ -22861,11 +22861,11 @@ async function taskkill(pid, options) {
22861
22861
  stdio: "ignore",
22862
22862
  windowsHide: true
22863
22863
  });
22864
- const exited = new Promise((resolve14) => {
22865
- killer.once("error", (error210) => resolve14(error210));
22864
+ const exited = new Promise((resolve13) => {
22865
+ killer.once("error", (error210) => resolve13(error210));
22866
22866
  killer.once(
22867
22867
  "exit",
22868
- (code, signal) => resolve14(code === 0 ? void 0 : new Error(`taskkill failed: exit ${code}, signal ${signal}`))
22868
+ (code, signal) => resolve13(code === 0 ? void 0 : new Error(`taskkill failed: exit ${code}, signal ${signal}`))
22869
22869
  );
22870
22870
  });
22871
22871
  const timedOut = clock.sleep(options.timeoutMs ?? DEFAULT_TASKKILL_TIMEOUT_MS, timeout.signal).then(() => new Error("taskkill timed out")).catch(() => void 0);
@@ -22908,9 +22908,9 @@ function signalGroup(pgid, signal, onError) {
22908
22908
  if (!isAlreadyDead(error61)) onError?.("group", error61);
22909
22909
  }
22910
22910
  }
22911
- function liveEscapedGroups(snapshot2, rootPid, remembered) {
22912
- const leaders = new Map(snapshot2.map((entry) => [entry.pid, entry.startedAt]));
22913
- const groups = new Set(escapedGroups(snapshot2, rootPid).map((group) => group.pgid));
22911
+ function liveEscapedGroups(snapshot, rootPid, remembered) {
22912
+ const leaders = new Map(snapshot.map((entry) => [entry.pid, entry.startedAt]));
22913
+ const groups = new Set(escapedGroups(snapshot, rootPid).map((group) => group.pgid));
22914
22914
  for (const [pgid, startedAt] of remembered) {
22915
22915
  if (leaders.get(pgid) === startedAt) groups.add(pgid);
22916
22916
  }
@@ -23121,10 +23121,10 @@ function spawnCli(options) {
23121
23121
  function waitForSpawn(child, command) {
23122
23122
  if (isWindowsJob(child)) return waitForWindowsJob(child, command);
23123
23123
  if (child.pid !== void 0) return Promise.resolve();
23124
- return new Promise((resolve14, reject) => {
23124
+ return new Promise((resolve13, reject) => {
23125
23125
  const onSpawn = () => {
23126
23126
  child.off("error", onError);
23127
- resolve14();
23127
+ resolve13();
23128
23128
  };
23129
23129
  const onError = (error61) => {
23130
23130
  child.off("spawn", onSpawn);
@@ -24903,6 +24903,7 @@ function settleOpenToolCalls(state) {
24903
24903
  if (outlivesTheTurn(entry))
24904
24904
  continue;
24905
24905
  entry.status = "cancelled";
24906
+ entry.lastUpdateIndex = state.updateCount;
24906
24907
  }
24907
24908
  }
24908
24909
  function applyTool(state, index, update) {
@@ -26780,8 +26781,8 @@ function readMediaFiles(candidates2, cwd, mimeByExt, maxBytes) {
26780
26781
  seen.add(path4);
26781
26782
  const mimeType = mimeByExt[(0, import_path3.extname)(path4).toLowerCase()];
26782
26783
  if (!mimeType) continue;
26783
- const stat23 = (0, import_fs4.statSync)(path4);
26784
- if (!stat23.isFile() || stat23.size <= 0 || stat23.size > maxBytes) continue;
26784
+ const stat22 = (0, import_fs4.statSync)(path4);
26785
+ if (!stat22.isFile() || stat22.size <= 0 || stat22.size > maxBytes) continue;
26785
26786
  files.push({ path: path4, mimeType, buffer: (0, import_fs4.readFileSync)(path4) });
26786
26787
  }
26787
26788
  return files;
@@ -26856,8 +26857,8 @@ function createJsonRpcPeer(writer, handlers) {
26856
26857
  },
26857
26858
  request: (method, params = {}) => {
26858
26859
  const id = counter.next++;
26859
- return new Promise((resolve14, reject) => {
26860
- pending.set(id, { method, resolve: resolve14, reject });
26860
+ return new Promise((resolve13, reject) => {
26861
+ pending.set(id, { method, resolve: resolve13, reject });
26861
26862
  writer.write({ id, method, params }).catch((error61) => {
26862
26863
  pending.delete(id);
26863
26864
  reject(error61 instanceof Error ? error61 : new Error(String(error61)));
@@ -26970,7 +26971,7 @@ function createNdjsonWriter(stream) {
26970
26971
  get writable() {
26971
26972
  return stream.writable && !stream.destroyed && failure6.error === void 0;
26972
26973
  },
26973
- write: (value2) => new Promise((resolve14, reject) => {
26974
+ write: (value2) => new Promise((resolve13, reject) => {
26974
26975
  if (failure6.error) {
26975
26976
  reject(failure6.error);
26976
26977
  return;
@@ -26982,7 +26983,7 @@ function createNdjsonWriter(stream) {
26982
26983
  stream.write(`${JSON.stringify(value2)}
26983
26984
  `, (error61) => {
26984
26985
  if (error61) reject(error61);
26985
- else resolve14();
26986
+ else resolve13();
26986
26987
  });
26987
26988
  }),
26988
26989
  end: () => {
@@ -27014,11 +27015,11 @@ function hostProcess(child, tree, options, handlers) {
27014
27015
  });
27015
27016
  child.stderr.on("data", (chunk) => stderr.push(chunk));
27016
27017
  child.stderr.once("end", () => stderr.flush());
27017
- const processExit = new Promise((resolve14) => {
27018
- child.once("exit", (code, signal) => resolve14({ code, signal }));
27018
+ const processExit = new Promise((resolve13) => {
27019
+ child.once("exit", (code, signal) => resolve13({ code, signal }));
27019
27020
  });
27020
- const outputEnded = new Promise((resolve14) => {
27021
- child.stdout.once("close", () => resolve14());
27021
+ const outputEnded = new Promise((resolve13) => {
27022
+ child.stdout.once("close", () => resolve13());
27022
27023
  });
27023
27024
  const watch = async () => {
27024
27025
  const { clock, stdoutDrainMs, log, name } = options;
@@ -27315,13 +27316,13 @@ var init_chunk_A2TG6ROT = __esm({
27315
27316
  const turnId = input2.turnId;
27316
27317
  let finish = () => {
27317
27318
  };
27318
- const done = new Promise((resolve14) => {
27319
+ const done = new Promise((resolve13) => {
27319
27320
  finish = (outcome2) => {
27320
27321
  if (this.#current?.id !== turnId) return;
27321
27322
  this.#current = void 0;
27322
27323
  if (this.#state === "busy") this.#state = "idle";
27323
27324
  this.#emit({ type: "turn_ended", turnId, outcome: outcome2 });
27324
- resolve14({ turnId, outcome: outcome2, providerSessionId: this.#sessionId });
27325
+ resolve13({ turnId, outcome: outcome2, providerSessionId: this.#sessionId });
27325
27326
  };
27326
27327
  });
27327
27328
  const pending = {
@@ -27619,18 +27620,18 @@ function environmentInstructions(environment, cwd) {
27619
27620
  }
27620
27621
  return lines2;
27621
27622
  }
27622
- function instructionsFor(snapshot2) {
27623
- const cwd = snapshot2.workspace.cwd ?? snapshot2.workspace.root ?? "the workspace";
27623
+ function instructionsFor(snapshot) {
27624
+ const cwd = snapshot.workspace.cwd ?? snapshot.workspace.root ?? "the workspace";
27624
27625
  return [
27625
- ...snapshot2.session.trigger === "image_build" ? ["Alan sent this turn, not the user: it reports an image build result."] : [],
27626
- ...snapshot2.environment ? environmentInstructions(snapshot2.environment, cwd) : []
27626
+ ...snapshot.session.trigger === "image_build" ? ["Alan sent this turn, not the user: it reports an image build result."] : [],
27627
+ ...snapshot.environment ? environmentInstructions(snapshot.environment, cwd) : []
27627
27628
  ];
27628
27629
  }
27629
- function startingInstructions(snapshot2) {
27630
- const cwd = snapshot2.workspace.cwd ?? snapshot2.workspace.root;
27630
+ function startingInstructions(snapshot) {
27631
+ const cwd = snapshot.workspace.cwd ?? snapshot.workspace.root;
27631
27632
  return [
27632
27633
  ...cwd ? [`Work from ${cwd}.`] : [],
27633
- ...snapshot2.workspace.repositories.flatMap(repositoryInstructions)
27634
+ ...snapshot.workspace.repositories.flatMap(repositoryInstructions)
27634
27635
  ];
27635
27636
  }
27636
27637
  function sessionKind(input2, context) {
@@ -27653,17 +27654,17 @@ function environmentOf(input2, context) {
27653
27654
  ...start ? { start: start.state === "not_configured" ? start : { ...start, log: input2.startLogPath } } : {}
27654
27655
  };
27655
27656
  }
27656
- function knownContext(snapshot2) {
27657
- const organizationId = snapshot2?.session.organizationId;
27658
- if (!snapshot2 || !organizationId) return void 0;
27659
- const environment = snapshot2.environment;
27657
+ function knownContext(snapshot) {
27658
+ const organizationId = snapshot?.session.organizationId;
27659
+ if (!snapshot || !organizationId) return void 0;
27660
+ const environment = snapshot.environment;
27660
27661
  return {
27661
- kind: snapshot2.session.kind,
27662
+ kind: snapshot.session.kind,
27662
27663
  trigger: "user",
27663
27664
  organizationId,
27664
- ...snapshot2.task ? { taskWorkingBranch: snapshot2.task.workingBranch } : {},
27665
- ...snapshot2.pullRequest ? { pullRequest: snapshot2.pullRequest } : {},
27666
- repositories: snapshot2.workspace.repositories.flatMap(
27665
+ ...snapshot.task ? { taskWorkingBranch: snapshot.task.workingBranch } : {},
27666
+ ...snapshot.pullRequest ? { pullRequest: snapshot.pullRequest } : {},
27667
+ repositories: snapshot.workspace.repositories.flatMap(
27667
27668
  ({ path: path4, name, url: url3, branch, branchSource, base }) => name && url3 && branch && branchSource && base ? [{ path: path4, name, url: url3, branch, branchSource, base }] : []
27668
27669
  ),
27669
27670
  ...environment ? {
@@ -27790,15 +27791,15 @@ function updateBody(previous, next) {
27790
27791
  if (Object.keys(facts).length === 0) return void 0;
27791
27792
  return next.session.trigger === "user" ? facts : { session: { trigger: next.session.trigger }, ...facts };
27792
27793
  }
27793
- function renderAgentContext(snapshot2, previous) {
27794
+ function renderAgentContext(snapshot, previous) {
27794
27795
  const full = block("alan_agent_context", {
27795
- ...snapshot2,
27796
- ...snapshot2.environment ? { environment: withCommandPreviews(snapshot2.environment) } : {},
27797
- instructions: [...startingInstructions(snapshot2), ...snapshot2.instructions]
27796
+ ...snapshot,
27797
+ ...snapshot.environment ? { environment: withCommandPreviews(snapshot.environment) } : {},
27798
+ instructions: [...startingInstructions(snapshot), ...snapshot.instructions]
27798
27799
  });
27799
- const update = previous ? updateBody(previous, snapshot2) : void 0;
27800
+ const update = previous ? updateBody(previous, snapshot) : void 0;
27800
27801
  return {
27801
- snapshot: snapshot2,
27802
+ snapshot,
27802
27803
  full,
27803
27804
  ...update ? { update: block("alan_agent_context_update", update) } : {}
27804
27805
  };
@@ -29218,18 +29219,24 @@ function realCwd(cwd) {
29218
29219
  return cwd;
29219
29220
  }
29220
29221
  }
29222
+ function projectDirs(projectsRoot) {
29223
+ try {
29224
+ return (0, import_fs5.readdirSync)(projectsRoot, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
29225
+ } catch {
29226
+ return [];
29227
+ }
29228
+ }
29221
29229
  function claudeSessionLogExists(query) {
29222
29230
  if (!query.sessionId || !query.cwd) return false;
29223
- for (const cwd of /* @__PURE__ */ new Set([query.cwd, realCwd(query.cwd)])) {
29224
- const log = (0, import_path5.join)(
29225
- query.claudeHome,
29226
- "projects",
29227
- encodeProjectDir(cwd),
29228
- `${query.sessionId}.jsonl`
29229
- );
29230
- if ((0, import_fs5.existsSync)(log)) return true;
29231
- }
29232
- return false;
29231
+ const projectsRoot = (0, import_path5.join)(query.claudeHome, "projects");
29232
+ const fileName = `${query.sessionId}.jsonl`;
29233
+ const here = new Set([query.cwd, realCwd(query.cwd)].map(encodeProjectDir));
29234
+ for (const dir of here) {
29235
+ if ((0, import_fs5.existsSync)((0, import_path5.join)(projectsRoot, dir, fileName))) return true;
29236
+ }
29237
+ return projectDirs(projectsRoot).some(
29238
+ (dir) => !here.has(dir) && (0, import_fs5.existsSync)((0, import_path5.join)(projectsRoot, dir, fileName))
29239
+ );
29233
29240
  }
29234
29241
  function envDigest(env) {
29235
29242
  const hash2 = (0, import_crypto7.createHash)("sha256");
@@ -30231,8 +30238,8 @@ var init_claude = __esm({
30231
30238
  }
30232
30239
  async #awaitTaskStop(requestId, taskId) {
30233
30240
  const timer = new AbortController();
30234
- const answered = new Promise((resolve14) => {
30235
- this.#taskStops.set(requestId, resolve14);
30241
+ const answered = new Promise((resolve13) => {
30242
+ this.#taskStops.set(requestId, resolve13);
30236
30243
  });
30237
30244
  const timeoutMs = this.#options.stopTaskTimeoutMs;
30238
30245
  const timedOut = this.#options.clock.sleep(timeoutMs, timer.signal).then(
@@ -30305,17 +30312,17 @@ var init_claude = __esm({
30305
30312
  };
30306
30313
  let markStarted = () => {
30307
30314
  };
30308
- const whenStarted = new Promise((resolve14) => {
30309
- markStarted = resolve14;
30315
+ const whenStarted = new Promise((resolve13) => {
30316
+ markStarted = resolve13;
30310
30317
  });
30311
- const done = new Promise((resolve14) => {
30318
+ const done = new Promise((resolve13) => {
30312
30319
  finish = (outcome2) => {
30313
30320
  if (this.#current?.id !== id) return;
30314
30321
  this.#current = void 0;
30315
30322
  this.#lastTurn = turn;
30316
30323
  if (this.#state === "busy") this.#state = "idle";
30317
30324
  this.#emit({ type: "turn_ended", turnId: id, outcome: outcome2 });
30318
- resolve14({ turnId: id, outcome: outcome2, providerSessionId: this.#providerSessionId });
30325
+ resolve13({ turnId: id, outcome: outcome2, providerSessionId: this.#providerSessionId });
30319
30326
  };
30320
30327
  });
30321
30328
  const active = {
@@ -30433,8 +30440,8 @@ var init_claude = __esm({
30433
30440
  void removeLaunchFiles(this.#launchFiles).catch((error61) => {
30434
30441
  this.#options.log.warn("claude.launch_files_cleanup_failed", { error: error61 });
30435
30442
  });
30436
- for (const resolve14 of this.#taskStops.values()) {
30437
- resolve14({ ok: false, reason: "runtime_unavailable", message: "Claude Code exited." });
30443
+ for (const resolve13 of this.#taskStops.values()) {
30444
+ resolve13({ ok: false, reason: "runtime_unavailable", message: "Claude Code exited." });
30438
30445
  }
30439
30446
  const active = this.#current;
30440
30447
  if (active) {
@@ -32575,7 +32582,7 @@ var init_codex = __esm({
32575
32582
  const buckets = asRecord(response?.rateLimitsByLimitId);
32576
32583
  if (buckets) {
32577
32584
  return Object.entries(buckets).flatMap(
32578
- ([limitId, snapshot2]) => this.#update(snapshot2, limitId)
32585
+ ([limitId, snapshot]) => this.#update(snapshot, limitId)
32579
32586
  );
32580
32587
  }
32581
32588
  return this.#update(response?.rateLimits);
@@ -32584,16 +32591,16 @@ var init_codex = __esm({
32584
32591
  return this.#update(params.rateLimits);
32585
32592
  }
32586
32593
  #update(value2, bucketId) {
32587
- const snapshot2 = asRecord(value2);
32588
- if (!snapshot2) return [];
32589
- const primary = windowPatch(snapshot2.primary);
32590
- const secondary = windowPatch(snapshot2.secondary);
32591
- const spend = spendPatch(snapshot2.individualLimit, snapshot2.spendControlReached);
32592
- const credits = creditsPatch(snapshot2.credits);
32593
- const planType = snapshot2.planType === null ? null : asString(snapshot2.planType) || void 0;
32594
+ const snapshot = asRecord(value2);
32595
+ if (!snapshot) return [];
32596
+ const primary = windowPatch(snapshot.primary);
32597
+ const secondary = windowPatch(snapshot.secondary);
32598
+ const spend = spendPatch(snapshot.individualLimit, snapshot.spendControlReached);
32599
+ const credits = creditsPatch(snapshot.credits);
32600
+ const planType = snapshot.planType === null ? null : asString(snapshot.planType) || void 0;
32594
32601
  const parsed = runCodexRateLimitsUpdateSchema.safeParse({
32595
32602
  sessionUpdate: "_alan/codex.rate_limits",
32596
- limitId: bucketId ?? (asString(snapshot2.limitId) || "codex"),
32603
+ limitId: bucketId ?? (asString(snapshot.limitId) || "codex"),
32597
32604
  ...primary === void 0 ? {} : { primary },
32598
32605
  ...secondary === void 0 ? {} : { secondary },
32599
32606
  ...spend === void 0 ? {} : { spend },
@@ -33039,10 +33046,10 @@ var init_codex = __esm({
33039
33046
  };
33040
33047
  let identify = () => {
33041
33048
  };
33042
- const identified = new Promise((resolve14) => {
33043
- identify = resolve14;
33049
+ const identified = new Promise((resolve13) => {
33050
+ identify = resolve13;
33044
33051
  });
33045
- const done = new Promise((resolve14) => {
33052
+ const done = new Promise((resolve13) => {
33046
33053
  finish = (outcome2) => {
33047
33054
  if (this.#current?.id !== id) return;
33048
33055
  this.#current = void 0;
@@ -33050,7 +33057,7 @@ var init_codex = __esm({
33050
33057
  if (this.#state === "busy") this.#state = "idle";
33051
33058
  this.#host.scanDescendants(true);
33052
33059
  this.#emit({ type: "turn_ended", turnId: id, outcome: outcome2 });
33053
- resolve14({ turnId: id, outcome: outcome2, providerSessionId: this.#threadId });
33060
+ resolve13({ turnId: id, outcome: outcome2, providerSessionId: this.#threadId });
33054
33061
  };
33055
33062
  });
33056
33063
  const active = {
@@ -33606,7 +33613,7 @@ function alanCodeConfigContent(existing, input2) {
33606
33613
  });
33607
33614
  }
33608
33615
  function readBody2(response) {
33609
- return new Promise((resolve14, reject) => {
33616
+ return new Promise((resolve13, reject) => {
33610
33617
  const chunks = [];
33611
33618
  let size = 0;
33612
33619
  response.on("data", (chunk) => {
@@ -33614,7 +33621,7 @@ function readBody2(response) {
33614
33621
  if (size > MAX_CATALOG_BYTES) response.destroy(new Error("catalog too large"));
33615
33622
  else chunks.push(chunk);
33616
33623
  });
33617
- response.on("end", () => resolve14(Buffer.concat(chunks).toString("utf8")));
33624
+ response.on("end", () => resolve13(Buffer.concat(chunks).toString("utf8")));
33618
33625
  response.on("error", reject);
33619
33626
  });
33620
33627
  }
@@ -33630,13 +33637,13 @@ function parseResponseBody(text3, status) {
33630
33637
  }
33631
33638
  function getJson(url3, headers, timeout, signal) {
33632
33639
  const request2 = url3.protocol === "https:" ? import_https.request : import_http9.request;
33633
- return new Promise((resolve14, reject) => {
33640
+ return new Promise((resolve13, reject) => {
33634
33641
  const outgoing = request2(url3, { method: "GET", headers, timeout, signal }, (response) => {
33635
33642
  const status = response.statusCode ?? 0;
33636
33643
  readBody2(response).then((text3) => {
33637
33644
  const body = parseResponseBody(text3, status);
33638
33645
  if (status < 200 || status >= 300) reject(new CatalogResponseError(status, body));
33639
- else resolve14(body);
33646
+ else resolve13(body);
33640
33647
  }).catch(reject);
33641
33648
  });
33642
33649
  outgoing.on("timeout", () => outgoing.destroy(new Error("catalog timed out")));
@@ -42513,8 +42520,8 @@ var require_streamx = __commonJS({
42513
42520
  return this;
42514
42521
  },
42515
42522
  next() {
42516
- return new Promise(function(resolve14, reject) {
42517
- promiseResolve = resolve14;
42523
+ return new Promise(function(resolve13, reject) {
42524
+ promiseResolve = resolve13;
42518
42525
  promiseReject = reject;
42519
42526
  const data = stream.read();
42520
42527
  if (data !== null) ondata(data);
@@ -42547,11 +42554,11 @@ var require_streamx = __commonJS({
42547
42554
  }
42548
42555
  function destroy(err) {
42549
42556
  stream.destroy(err);
42550
- return new Promise((resolve14, reject) => {
42551
- if (stream._duplexState & DESTROYED) return resolve14({ value: void 0, done: true });
42557
+ return new Promise((resolve13, reject) => {
42558
+ if (stream._duplexState & DESTROYED) return resolve13({ value: void 0, done: true });
42552
42559
  stream.once("close", function() {
42553
42560
  if (err) reject(err);
42554
- else resolve14({ value: void 0, done: true });
42561
+ else resolve13({ value: void 0, done: true });
42555
42562
  });
42556
42563
  });
42557
42564
  }
@@ -42595,8 +42602,8 @@ var require_streamx = __commonJS({
42595
42602
  const writes = pending + (ws._duplexState & WRITE_WRITING ? 1 : 0);
42596
42603
  if (writes === 0) return Promise.resolve(true);
42597
42604
  if (state.drains === null) state.drains = [];
42598
- return new Promise((resolve14) => {
42599
- state.drains.push({ writes, resolve: resolve14 });
42605
+ return new Promise((resolve13) => {
42606
+ state.drains.push({ writes, resolve: resolve13 });
42600
42607
  });
42601
42608
  }
42602
42609
  write(data) {
@@ -42701,10 +42708,10 @@ var require_streamx = __commonJS({
42701
42708
  cb(null);
42702
42709
  }
42703
42710
  function pipelinePromise(...streams) {
42704
- return new Promise((resolve14, reject) => {
42711
+ return new Promise((resolve13, reject) => {
42705
42712
  return pipeline(...streams, (err) => {
42706
42713
  if (err) return reject(err);
42707
- resolve14();
42714
+ resolve13();
42708
42715
  });
42709
42716
  });
42710
42717
  }
@@ -43376,16 +43383,16 @@ var require_extract = __commonJS({
43376
43383
  entryCallback = null;
43377
43384
  cb(err);
43378
43385
  }
43379
- function onnext(resolve14, reject) {
43386
+ function onnext(resolve13, reject) {
43380
43387
  if (error61) {
43381
43388
  return reject(error61);
43382
43389
  }
43383
43390
  if (entryStream) {
43384
- resolve14({ value: entryStream, done: false });
43391
+ resolve13({ value: entryStream, done: false });
43385
43392
  entryStream = null;
43386
43393
  return;
43387
43394
  }
43388
- promiseResolve = resolve14;
43395
+ promiseResolve = resolve13;
43389
43396
  promiseReject = reject;
43390
43397
  consumeCallback(null);
43391
43398
  if (extract2._finished && promiseResolve) {
@@ -43413,11 +43420,11 @@ var require_extract = __commonJS({
43413
43420
  function destroy(err) {
43414
43421
  extract2.destroy(err);
43415
43422
  consumeCallback(err);
43416
- return new Promise((resolve14, reject) => {
43417
- if (extract2.destroyed) return resolve14({ value: void 0, done: true });
43423
+ return new Promise((resolve13, reject) => {
43424
+ if (extract2.destroyed) return resolve13({ value: void 0, done: true });
43418
43425
  extract2.once("close", function() {
43419
43426
  if (err) reject(err);
43420
- else resolve14({ value: void 0, done: true });
43427
+ else resolve13({ value: void 0, done: true });
43421
43428
  });
43422
43429
  });
43423
43430
  }
@@ -44305,12 +44312,12 @@ function shellStart(update, sessionId) {
44305
44312
  ];
44306
44313
  }
44307
44314
  function shellEnd(update) {
44308
- const snapshot2 = asRecord(update.task_snapshot);
44309
- const taskId = optional2(snapshot2?.task_id);
44310
- if (!snapshot2 || !taskId) return [];
44311
- const killed = snapshot2.explicitly_killed === true;
44312
- const exitCode = snapshot2.exit_code;
44313
- const failed = typeof exitCode === "number" && exitCode !== 0 || optional2(snapshot2.signal) !== void 0;
44315
+ const snapshot = asRecord(update.task_snapshot);
44316
+ const taskId = optional2(snapshot?.task_id);
44317
+ if (!snapshot || !taskId) return [];
44318
+ const killed = snapshot.explicitly_killed === true;
44319
+ const exitCode = snapshot.exit_code;
44320
+ const failed = typeof exitCode === "number" && exitCode !== 0 || optional2(snapshot.signal) !== void 0;
44314
44321
  const ending = killed ? "stopped" : failed ? "failed" : "completed";
44315
44322
  return [{ type: "end", taskId, ending }];
44316
44323
  }
@@ -44982,7 +44989,7 @@ var init_acp3 = __esm({
44982
44989
  const turn = new AcpTurn(`acp-${this.#turns}-${id}`, this.#profile);
44983
44990
  let finish = () => {
44984
44991
  };
44985
- const done = new Promise((resolve14) => {
44992
+ const done = new Promise((resolve13) => {
44986
44993
  finish = (outcome2) => {
44987
44994
  if (this.#current?.id !== id) return;
44988
44995
  this.#current = void 0;
@@ -44990,7 +44997,7 @@ var init_acp3 = __esm({
44990
44997
  if (this.#state === "busy") this.#state = "idle";
44991
44998
  this.#host.scanDescendants(true);
44992
44999
  this.#emit({ type: "turn_ended", turnId: id, outcome: outcome2 });
44993
- resolve14({ turnId: id, outcome: outcome2, providerSessionId: this.#sessionId });
45000
+ resolve13({ turnId: id, outcome: outcome2, providerSessionId: this.#sessionId });
44994
45001
  };
44995
45002
  });
44996
45003
  const active = { id, turn, done, finish, cancelRequested: false };
@@ -45575,12 +45582,11 @@ function createPersistentDriver(provider4, options) {
45575
45582
  log.warn("holder.history_rejected", { harness: provider4.harness });
45576
45583
  await session.suspend();
45577
45584
  };
45578
- const respond = async (request2, mayWrite) => {
45585
+ const respond = async (request2) => {
45579
45586
  const turn = live.turn;
45580
45587
  if (turn === void 0 || turn.runId !== request2.runId) return "unknown_run";
45581
45588
  const isWaiting = () => live.turn === turn && turn.waiting.has(request2.toolCallId);
45582
45589
  if (!isWaiting() || turn.session.respond === void 0) return "not_waiting";
45583
- if (!await mayWrite() || !isWaiting()) return "not_waiting";
45584
45590
  turn.waiting.delete(request2.toolCallId);
45585
45591
  try {
45586
45592
  await turn.session.respond(request2.toolCallId, request2.answer);
@@ -47806,8 +47812,8 @@ function createDroidPeer(writer, handlers) {
47806
47812
  },
47807
47813
  request: (method, params = {}) => {
47808
47814
  const id = `alan-${counter.next++}`;
47809
- return new Promise((resolve14, reject) => {
47810
- pending.set(id, { method, resolve: resolve14, reject });
47815
+ return new Promise((resolve13, reject) => {
47816
+ pending.set(id, { method, resolve: resolve13, reject });
47811
47817
  writer.write(envelope("request", { id, method, params })).catch((error61) => {
47812
47818
  pending.delete(id);
47813
47819
  reject(error61 instanceof Error ? error61 : new Error(String(error61)));
@@ -48435,14 +48441,14 @@ var init_droid = __esm({
48435
48441
  const turn = new DroidTurn(sessionId, this.#memory);
48436
48442
  let finish = () => {
48437
48443
  };
48438
- const done = new Promise((resolve14) => {
48444
+ const done = new Promise((resolve13) => {
48439
48445
  finish = (outcome2) => {
48440
48446
  if (this.#current?.id !== id) return;
48441
48447
  this.#current = void 0;
48442
48448
  if (this.#state === "busy") this.#state = "idle";
48443
48449
  this.#host.scanDescendants(true);
48444
48450
  this.#emit({ type: "turn_ended", turnId: id, outcome: outcome2 });
48445
- resolve14({ turnId: id, outcome: outcome2, providerSessionId: this.#sessionId });
48451
+ resolve13({ turnId: id, outcome: outcome2, providerSessionId: this.#sessionId });
48446
48452
  };
48447
48453
  });
48448
48454
  const active = { id, turn, done, finish, cancelRequested: false };
@@ -55368,7 +55374,7 @@ var require_websocket_server = __commonJS({
55368
55374
  // package.json
55369
55375
  var package_default = {
55370
55376
  name: "@alan-ai-hq/agent-manager",
55371
- version: "0.1.151",
55377
+ version: "0.1.152",
55372
55378
  private: true,
55373
55379
  type: "module",
55374
55380
  description: "Alan machine runtime (alan-agent): identity, link, reconciler, session holders, run log, uploader, local API",
@@ -55418,7 +55424,7 @@ var package_default = {
55418
55424
 
55419
55425
  // src/cli/commands/compat.ts
55420
55426
  var import_node_crypto32 = require("crypto");
55421
- var import_promises71 = require("fs/promises");
55427
+ var import_promises69 = require("fs/promises");
55422
55428
  init_runtime_v2();
55423
55429
  init_zod();
55424
55430
 
@@ -55577,8 +55583,8 @@ async function writeJsonFileAtomic(path4, value2) {
55577
55583
  var LIFECYCLE_DRAIN_MS = 5e3;
55578
55584
  function createGate() {
55579
55585
  const opened = {};
55580
- const promise2 = new Promise((resolve14) => {
55581
- opened.resolve = resolve14;
55586
+ const promise2 = new Promise((resolve13) => {
55587
+ opened.resolve = resolve13;
55582
55588
  });
55583
55589
  return { promise: promise2, open: () => opened.resolve?.() };
55584
55590
  }
@@ -55805,7 +55811,7 @@ function transportFailure(request2, error61) {
55805
55811
  });
55806
55812
  }
55807
55813
  function readBody(incoming, url3, maxBytes) {
55808
- return new Promise((resolve14, reject) => {
55814
+ return new Promise((resolve13, reject) => {
55809
55815
  const declared = Number(incoming.headers["content-length"] ?? "0");
55810
55816
  if (maxBytes !== void 0 && declared > maxBytes) {
55811
55817
  incoming.destroy();
@@ -55824,7 +55830,7 @@ function readBody(incoming, url3, maxBytes) {
55824
55830
  chunks.push(chunk);
55825
55831
  });
55826
55832
  incoming.on("error", reject);
55827
- incoming.on("end", () => resolve14(Buffer.concat(chunks)));
55833
+ incoming.on("end", () => resolve13(Buffer.concat(chunks)));
55828
55834
  });
55829
55835
  }
55830
55836
  function isConnectionReset(error61) {
@@ -55832,7 +55838,7 @@ function isConnectionReset(error61) {
55832
55838
  }
55833
55839
  function exchange(request2, agents, attempt2 = 0) {
55834
55840
  const { signal, url: url3 } = request2;
55835
- return new Promise((resolve14, reject) => {
55841
+ return new Promise((resolve13, reject) => {
55836
55842
  if (signal.aborted) {
55837
55843
  reject(signal.reason);
55838
55844
  return;
@@ -55859,7 +55865,7 @@ function exchange(request2, agents, attempt2 = 0) {
55859
55865
  const stale = outgoing.reusedSocket && !responded && isConnectionReset(error61);
55860
55866
  if (stale && attempt2 < STALE_SOCKET_RETRIES && !signal.aborted) {
55861
55867
  settle();
55862
- resolve14(exchange(request2, agents, attempt2 + 1));
55868
+ resolve13(exchange(request2, agents, attempt2 + 1));
55863
55869
  return;
55864
55870
  }
55865
55871
  fail(error61);
@@ -55872,7 +55878,7 @@ function exchange(request2, agents, attempt2 = 0) {
55872
55878
  readBody(incoming, url3, isRedirect(status) ? void 0 : request2.maxBodyBytes).then(
55873
55879
  (body) => {
55874
55880
  settle();
55875
- resolve14({ status, headers: incoming.headers, body });
55881
+ resolve13({ status, headers: incoming.headers, body });
55876
55882
  },
55877
55883
  fail
55878
55884
  );
@@ -56117,8 +56123,8 @@ function isBodyless(method) {
56117
56123
  return method === "GET" || method === "HEAD";
56118
56124
  }
56119
56125
  function exchange2(send2, options, input2) {
56120
- return new Promise((resolve14, reject) => {
56121
- const outgoing = send2({ ...options, method: input2.method, signal: input2.signal }, resolve14);
56126
+ return new Promise((resolve13, reject) => {
56127
+ const outgoing = send2({ ...options, method: input2.method, signal: input2.signal }, resolve13);
56122
56128
  outgoing.on("error", reject);
56123
56129
  if (isBodyless(input2.method)) {
56124
56130
  input2.body.resume();
@@ -57604,7 +57610,7 @@ function createGitRunner(options) {
57604
57610
  }
57605
57611
  await killProcessTree(child.pid, { signal: "SIGKILL", child, platform: platform3 });
57606
57612
  };
57607
- return new Promise((resolve14, reject) => {
57613
+ return new Promise((resolve13, reject) => {
57608
57614
  let ending = null;
57609
57615
  const stop = (next) => {
57610
57616
  if (ending !== null) return;
@@ -57629,7 +57635,7 @@ function createGitRunner(options) {
57629
57635
  signal.removeEventListener("abort", onAbort);
57630
57636
  const final = ending ?? last;
57631
57637
  if (final.kind === "exited") {
57632
- resolve14({ exitCode: final.exitCode, stdout: stdout.text(), stderr: stderr.text() });
57638
+ resolve13({ exitCode: final.exitCode, stdout: stdout.text(), stderr: stderr.text() });
57633
57639
  } else {
57634
57640
  reject(faultFor(final, command));
57635
57641
  }
@@ -57771,35 +57777,35 @@ async function checkOne(path4, deps, signal) {
57771
57777
  await write({ state: "checking", path: path4 });
57772
57778
  const read = await readSnapshot(deps.git, path4, signal);
57773
57779
  if (read.kind !== "snapshot") return write({ state: read.kind, path: path4, reason: read.reason });
57774
- const { snapshot: snapshot2 } = read;
57780
+ const { snapshot } = read;
57775
57781
  const advertised = await deps.git.run(
57776
57782
  {
57777
57783
  cwd: path4,
57778
- args: ["ls-remote", "--exit-code", REMOTE, `refs/heads/${snapshot2.base}`],
57784
+ args: ["ls-remote", "--exit-code", REMOTE, `refs/heads/${snapshot.base}`],
57779
57785
  network: true,
57780
57786
  readOnly: true
57781
57787
  },
57782
57788
  signal
57783
57789
  );
57784
57790
  if (advertised.exitCode !== 0) {
57785
- return write({ state: "failed", path: path4, snapshot: snapshot2, reason: gitError(advertised, "ls-remote") });
57791
+ return write({ state: "failed", path: path4, snapshot, reason: gitError(advertised, "ls-remote") });
57786
57792
  }
57787
57793
  const tip = advertised.stdout.split(/\s+/)[0] ?? "";
57788
- if (tip === snapshot2.head) return write({ state: "current", path: path4, snapshot: snapshot2 });
57789
- if (tip === snapshot2.published) {
57790
- return write({ state: "behind", path: path4, snapshot: snapshot2, tip, fetched: true });
57794
+ if (tip === snapshot.head) return write({ state: "current", path: path4, snapshot });
57795
+ if (tip === snapshot.published) {
57796
+ return write({ state: "behind", path: path4, snapshot, tip, fetched: true });
57791
57797
  }
57792
- await write({ state: "behind", path: path4, snapshot: snapshot2, tip, fetched: false });
57793
- const depth = snapshot2.shallow ? ["--depth=1"] : [];
57798
+ await write({ state: "behind", path: path4, snapshot, tip, fetched: false });
57799
+ const depth = snapshot.shallow ? ["--depth=1"] : [];
57794
57800
  const fetched = await deps.git.run(
57795
57801
  {
57796
57802
  cwd: path4,
57797
- args: ["fetch", "--no-tags", "--quiet", ...depth, REMOTE, snapshot2.base],
57803
+ args: ["fetch", "--no-tags", "--quiet", ...depth, REMOTE, snapshot.base],
57798
57804
  network: true
57799
57805
  },
57800
57806
  signal
57801
57807
  );
57802
- return fetched.exitCode === 0 ? write({ state: "behind", path: path4, snapshot: snapshot2, tip, fetched: true }) : write({ state: "failed", path: path4, snapshot: snapshot2, reason: gitError(fetched, "fetch") });
57808
+ return fetched.exitCode === 0 ? write({ state: "behind", path: path4, snapshot, tip, fetched: true }) : write({ state: "failed", path: path4, snapshot, reason: gitError(fetched, "fetch") });
57803
57809
  }
57804
57810
  async function isCheckout(path4) {
57805
57811
  return (0, import_promises11.stat)((0, import_node_path7.join)(path4, ".git")).then(
@@ -58167,9 +58173,9 @@ function isProcessAlive(pid) {
58167
58173
  }
58168
58174
  }
58169
58175
  async function linuxStartTime(pid) {
58170
- const stat23 = await (0, import_promises13.readFile)(`/proc/${pid}/stat`, "utf8").catch(() => null);
58171
- if (stat23 === null) return null;
58172
- const fields = stat23.slice(stat23.lastIndexOf(")") + 2).split(" ");
58176
+ const stat22 = await (0, import_promises13.readFile)(`/proc/${pid}/stat`, "utf8").catch(() => null);
58177
+ if (stat22 === null) return null;
58178
+ const fields = stat22.slice(stat22.lastIndexOf(")") + 2).split(" ");
58173
58179
  return fields[19] ?? null;
58174
58180
  }
58175
58181
  async function linuxCommand(pid) {
@@ -59149,7 +59155,7 @@ function statusOf(error61) {
59149
59155
  }
59150
59156
  return 1;
59151
59157
  }
59152
- var systemExec = (request2) => new Promise((resolve14) => {
59158
+ var systemExec = (request2) => new Promise((resolve13) => {
59153
59159
  const child = (0, import_node_child_process6.execFile)(
59154
59160
  request2.command,
59155
59161
  [...request2.args],
@@ -59160,7 +59166,7 @@ var systemExec = (request2) => new Promise((resolve14) => {
59160
59166
  windowsHide: true
59161
59167
  },
59162
59168
  (error61, stdout, stderr) => {
59163
- resolve14({ status: statusOf(error61), stdout, stderr });
59169
+ resolve13({ status: statusOf(error61), stdout, stderr });
59164
59170
  }
59165
59171
  );
59166
59172
  child.stdin?.on("error", () => {
@@ -60354,11 +60360,11 @@ async function startGitCredentialServer(options) {
60354
60360
  });
60355
60361
  });
60356
60362
  removeStaleEndpoint(options.endpoint);
60357
- await new Promise((resolve14, reject) => {
60363
+ await new Promise((resolve13, reject) => {
60358
60364
  server.once("error", reject);
60359
60365
  server.listen(options.endpoint, () => {
60360
60366
  server.off("error", reject);
60361
- resolve14();
60367
+ resolve13();
60362
60368
  });
60363
60369
  });
60364
60370
  options.log.info("git.credential_server_listening", { endpoint: options.endpoint });
@@ -60366,7 +60372,7 @@ async function startGitCredentialServer(options) {
60366
60372
  endpoint: options.endpoint,
60367
60373
  [Symbol.asyncDispose]: async () => {
60368
60374
  closing.abort();
60369
- await new Promise((resolve14) => server.close(() => resolve14()));
60375
+ await new Promise((resolve13) => server.close(() => resolve13()));
60370
60376
  removeStaleEndpoint(options.endpoint);
60371
60377
  }
60372
60378
  };
@@ -60440,13 +60446,13 @@ authorityKeyIdentifier = keyid
60440
60446
  `;
60441
60447
  }
60442
60448
  function openssl(args, cwd) {
60443
- return new Promise((resolve14, reject) => {
60449
+ return new Promise((resolve13, reject) => {
60444
60450
  (0, import_node_child_process9.execFile)(
60445
60451
  "openssl",
60446
60452
  [...args],
60447
60453
  { cwd, timeout: OPENSSL_TIMEOUT_MS },
60448
60454
  (error61, _stdout, stderr) => {
60449
- if (error61 === null) resolve14();
60455
+ if (error61 === null) resolve13();
60450
60456
  else
60451
60457
  reject(new Error(`openssl ${args[0] ?? ""} failed: ${stderr.trim() || error61.message}`));
60452
60458
  }
@@ -60623,21 +60629,21 @@ function relayTo(forward, log) {
60623
60629
  };
60624
60630
  }
60625
60631
  function listen(server, target) {
60626
- return new Promise((resolve14, reject) => {
60632
+ return new Promise((resolve13, reject) => {
60627
60633
  server.once("error", reject);
60628
60634
  const done = () => {
60629
60635
  server.off("error", reject);
60630
- resolve14();
60636
+ resolve13();
60631
60637
  };
60632
60638
  if (typeof target === "string") server.listen(target, done);
60633
60639
  else server.listen(target.port, target.host, done);
60634
60640
  });
60635
60641
  }
60636
60642
  function close(server, sockets = /* @__PURE__ */ new Set()) {
60637
- return new Promise((resolve14) => {
60643
+ return new Promise((resolve13) => {
60638
60644
  for (const socket of sockets) socket.destroy();
60639
60645
  server.closeAllConnections();
60640
- server.close(() => resolve14());
60646
+ server.close(() => resolve13());
60641
60647
  });
60642
60648
  }
60643
60649
  function portOf(server) {
@@ -62771,8 +62777,8 @@ async function openNativeSessionStore(stateDir, maxEntries = MAX_NATIVE_SESSION_
62771
62777
  sessions.delete(sessionKey(entry.provider, entry.externalSessionId));
62772
62778
  }
62773
62779
  }
62774
- const snapshot2 = { version: 1, sessions: [...sessions.values()] };
62775
- writing = writing.catch(() => void 0).then(() => writeJsonFileAtomic(path4, snapshot2));
62780
+ const snapshot = { version: 1, sessions: [...sessions.values()] };
62781
+ writing = writing.catch(() => void 0).then(() => writeJsonFileAtomic(path4, snapshot));
62776
62782
  return writing;
62777
62783
  };
62778
62784
  return {
@@ -63420,7 +63426,7 @@ async function startNativeIngest(deps) {
63420
63426
  };
63421
63427
  const settleIdle = () => {
63422
63428
  if (workers.size > 0) return;
63423
- for (const resolve14 of idleWaiters) resolve14();
63429
+ for (const resolve13 of idleWaiters) resolve13();
63424
63430
  idleWaiters.clear();
63425
63431
  };
63426
63432
  const retryDelay = (worker) => {
@@ -63663,7 +63669,7 @@ async function startNativeIngest(deps) {
63663
63669
  sweep: sweep2,
63664
63670
  whenIdle: () => {
63665
63671
  if (workers.size === 0) return Promise.resolve();
63666
- return new Promise((resolve14) => idleWaiters.add(resolve14));
63672
+ return new Promise((resolve13) => idleWaiters.add(resolve13));
63667
63673
  },
63668
63674
  [Symbol.asyncDispose]: async () => {
63669
63675
  shutdown.abort();
@@ -63811,7 +63817,7 @@ function captureProbe(command, args, options) {
63811
63817
  const launch = directLaunch(command, args, options);
63812
63818
  if (launch === void 0) return Promise.resolve({ stdout: "", stderr: "", exitCode: void 0 });
63813
63819
  const env = platform3 === "win32" ? withWindowsHelper(canonicalWindowsEnvironment(options.env)) : options.env;
63814
- return new Promise((resolve14) => {
63820
+ return new Promise((resolve13) => {
63815
63821
  const limit = options.maxBufferBytes ?? DEFAULT_MAX_BYTES;
63816
63822
  const stdout = [];
63817
63823
  const stderr = [];
@@ -63846,7 +63852,7 @@ function captureProbe(command, args, options) {
63846
63852
  settled2 = true;
63847
63853
  deadlineController.abort();
63848
63854
  options.signal?.removeEventListener("abort", abort);
63849
- resolve14({
63855
+ resolve13({
63850
63856
  stdout: Buffer.concat(stdout).toString("utf8"),
63851
63857
  stderr: Buffer.concat(stderr).toString("utf8"),
63852
63858
  exitCode
@@ -63979,7 +63985,7 @@ function cursorAccountLabel(output2) {
63979
63985
  function waitForAbort(signal) {
63980
63986
  if (signal.aborted) return Promise.resolve();
63981
63987
  return new Promise(
63982
- (resolve14) => signal.addEventListener("abort", () => resolve14(), { once: true })
63988
+ (resolve13) => signal.addEventListener("abort", () => resolve13(), { once: true })
63983
63989
  );
63984
63990
  }
63985
63991
  function idlePrompt(signal) {
@@ -64057,14 +64063,14 @@ async function codexLabel(executable, env) {
64057
64063
  windowsVerbatimArguments: launch.windowsVerbatimArguments
64058
64064
  });
64059
64065
  const timeout = AbortSignal.timeout(ACCOUNT_TIMEOUT_MS);
64060
- return new Promise((resolve14) => {
64066
+ return new Promise((resolve13) => {
64061
64067
  let finished = false;
64062
64068
  let buffer = "";
64063
64069
  const finish = (label) => {
64064
64070
  if (finished) return;
64065
64071
  finished = true;
64066
64072
  child.kill();
64067
- resolve14(label);
64073
+ resolve13(label);
64068
64074
  };
64069
64075
  const send2 = (value2) => {
64070
64076
  child.stdin.write(`${JSON.stringify(value2)}
@@ -64207,7 +64213,7 @@ function createProbeQueue(capture, env, limit) {
64207
64213
  active += 1;
64208
64214
  return Promise.resolve();
64209
64215
  }
64210
- return new Promise((resolve14) => waiting.push(resolve14));
64216
+ return new Promise((resolve13) => waiting.push(resolve13));
64211
64217
  };
64212
64218
  const release2 = () => {
64213
64219
  const next = waiting.shift();
@@ -64647,11 +64653,11 @@ async function resolveCliEnvironment(options) {
64647
64653
  }
64648
64654
  async function openCliEnvironment(options) {
64649
64655
  const decorate = options.decorate ?? ((env) => env);
64650
- const resolve14 = async () => {
64656
+ const resolve13 = async () => {
64651
64657
  const resolved = await resolveCliEnvironmentDetailed(options);
64652
64658
  return { env: decorate(resolved.env), source: resolved.source };
64653
64659
  };
64654
- let state = await resolve14();
64660
+ let state = await resolve13();
64655
64661
  let retryAt = options.clock.now() + DEGRADED_RETRY_MS;
64656
64662
  return {
64657
64663
  current: () => state.env,
@@ -64660,7 +64666,7 @@ async function openCliEnvironment(options) {
64660
64666
  if (state.source === "login_shell" || options.platform === "win32") return false;
64661
64667
  if (options.clock.now() < retryAt) return false;
64662
64668
  retryAt = options.clock.now() + DEGRADED_RETRY_MS;
64663
- const next = await resolve14();
64669
+ const next = await resolve13();
64664
64670
  const changed2 = envValue(next.env, "PATH") !== envValue(state.env, "PATH");
64665
64671
  state = next;
64666
64672
  return changed2;
@@ -64737,11 +64743,11 @@ async function installVersion2(backendKind, requested, options, signal) {
64737
64743
  }
64738
64744
  return exact;
64739
64745
  }
64740
- const resolve14 = options.resolveVersion;
64741
- if (resolve14 === void 0) throw new Error("Latest version lookup is unavailable");
64746
+ const resolve13 = options.resolveVersion;
64747
+ if (resolve13 === void 0) throw new Error("Latest version lookup is unavailable");
64742
64748
  const packageName = packageFor(backendKind).name;
64743
64749
  return checkedVersion(
64744
- await resolve14(backendKind === "opencode_serve" ? `${packageName}@1` : packageName, signal)
64750
+ await resolve13(backendKind === "opencode_serve" ? `${packageName}@1` : packageName, signal)
64745
64751
  );
64746
64752
  }
64747
64753
  function selection(root, backendKind, version2) {
@@ -66308,8 +66314,8 @@ async function collectStream(stream) {
66308
66314
  return import_node_buffer2.Buffer.concat(chunks);
66309
66315
  }
66310
66316
  function addArchiveEntry(archive, header, bytes) {
66311
- return new Promise((resolve14, reject) => {
66312
- archive.entry(header, bytes, (error61) => error61 ? reject(error61) : resolve14());
66317
+ return new Promise((resolve13, reject) => {
66318
+ archive.entry(header, bytes, (error61) => error61 ? reject(error61) : resolve13());
66313
66319
  });
66314
66320
  }
66315
66321
  async function decompressBounded(archiveBytes) {
@@ -66335,7 +66341,7 @@ async function extractTar(tarBytes, destination) {
66335
66341
  const extractor = (0, import_tar_stream.extract)();
66336
66342
  let fileCount = 0;
66337
66343
  let totalBytes = 0;
66338
- const completion = new Promise((resolve14, reject) => {
66344
+ const completion = new Promise((resolve13, reject) => {
66339
66345
  extractor.on("entry", (header, stream, next) => {
66340
66346
  void extractEntry(header, stream, destination, {
66341
66347
  addFile(size) {
@@ -66350,7 +66356,7 @@ async function extractTar(tarBytes, destination) {
66350
66356
  }
66351
66357
  }).then(next, (error61) => extractor.destroy(error61 instanceof Error ? error61 : new Error(String(error61))));
66352
66358
  });
66353
- extractor.once("finish", resolve14);
66359
+ extractor.once("finish", resolve13);
66354
66360
  extractor.once("error", reject);
66355
66361
  });
66356
66362
  import_node_stream.Readable.from(tarBytes).pipe(extractor);
@@ -66833,9 +66839,9 @@ async function syncOnce(env, local, onRecorded, signal) {
66833
66839
  return report2;
66834
66840
  }
66835
66841
  function aborted2(signal) {
66836
- return new Promise((resolve14) => {
66837
- if (signal.aborted) resolve14(null);
66838
- else signal.addEventListener("abort", () => resolve14(null), { once: true });
66842
+ return new Promise((resolve13) => {
66843
+ if (signal.aborted) resolve13(null);
66844
+ else signal.addEventListener("abort", () => resolve13(null), { once: true });
66839
66845
  });
66840
66846
  }
66841
66847
  function openMachineSkills(options) {
@@ -66924,11 +66930,11 @@ function openMachineSkills(options) {
66924
66930
  if ((await resolveSkillInvocations(layout, named, "exact")).kind === "resolved") return;
66925
66931
  }
66926
66932
  };
66927
- const recordedUntilResolved = (named, until) => new Promise((resolve14) => {
66933
+ const recordedUntilResolved = (named, until) => new Promise((resolve13) => {
66928
66934
  const done = () => {
66929
66935
  recordWatchers.delete(check3);
66930
66936
  until.removeEventListener("abort", done);
66931
- resolve14();
66937
+ resolve13();
66932
66938
  };
66933
66939
  const check3 = () => {
66934
66940
  void resolveSkillInvocations(layout, named, "exact").then((resolution) => {
@@ -66936,7 +66942,7 @@ function openMachineSkills(options) {
66936
66942
  });
66937
66943
  };
66938
66944
  if (until.aborted) {
66939
- resolve14();
66945
+ resolve13();
66940
66946
  return;
66941
66947
  }
66942
66948
  recordWatchers.add(check3);
@@ -67432,7 +67438,7 @@ async function openWorkspaces(options) {
67432
67438
 
67433
67439
  // src/cli/config.ts
67434
67440
  var import_node_os11 = require("os");
67435
- var import_node_path70 = require("path");
67441
+ var import_node_path68 = require("path");
67436
67442
  init_zod();
67437
67443
 
67438
67444
  // src/client/contract.ts
@@ -67850,8 +67856,8 @@ function nextOffsetOf(response) {
67850
67856
  async function pause(ms, signal) {
67851
67857
  const either = AbortSignal.any([signal, AbortSignal.timeout(ms)]);
67852
67858
  if (either.aborted) return;
67853
- await new Promise((resolve14) => {
67854
- either.addEventListener("abort", () => resolve14(), { once: true });
67859
+ await new Promise((resolve13) => {
67860
+ either.addEventListener("abort", () => resolve13(), { once: true });
67855
67861
  });
67856
67862
  }
67857
67863
  function jittered(backoff, failures) {
@@ -68160,9 +68166,9 @@ async function sendNativeHookSignal(discoveryPath, hookSignal, signal) {
68160
68166
 
68161
68167
  // src/sessions/index.ts
68162
68168
  var import_node_crypto31 = require("crypto");
68163
- var import_promises69 = require("fs/promises");
68169
+ var import_promises67 = require("fs/promises");
68164
68170
  var import_node_os10 = require("os");
68165
- var import_node_path69 = require("path");
68171
+ var import_node_path67 = require("path");
68166
68172
  init_runtime_v2();
68167
68173
 
68168
68174
  // src/holder/control-client.ts
@@ -68213,8 +68219,8 @@ function isReply(message2) {
68213
68219
  async function connectHolder(endpoint, token, onEvent) {
68214
68220
  const socket = (0, import_node_net2.connect)(endpoint);
68215
68221
  const pending = /* @__PURE__ */ new Map();
68216
- const closed = new Promise((resolve14) => socket.once("close", () => resolve14()));
68217
- const ready = new Promise((resolve14, reject) => {
68222
+ const closed = new Promise((resolve13) => socket.once("close", () => resolve13()));
68223
+ const ready = new Promise((resolve13, reject) => {
68218
68224
  socket.once("error", reject);
68219
68225
  socket.once(
68220
68226
  "close",
@@ -68222,7 +68228,7 @@ async function connectHolder(endpoint, token, onEvent) {
68222
68228
  );
68223
68229
  readMessages(socket, holderMessageSchema, {
68224
68230
  onMessage: (message2) => {
68225
- if (message2.type === "ready") resolve14(message2.pid);
68231
+ if (message2.type === "ready") resolve13(message2.pid);
68226
68232
  else if (isReply(message2)) {
68227
68233
  const id = message2.id;
68228
68234
  if (id === null) return;
@@ -68237,13 +68243,13 @@ async function connectHolder(endpoint, token, onEvent) {
68237
68243
  const pid = await ready;
68238
68244
  const request2 = (body) => {
68239
68245
  const id = (0, import_node_crypto26.randomUUID)();
68240
- return new Promise((resolve14, reject) => {
68246
+ return new Promise((resolve13, reject) => {
68241
68247
  const timer = AbortSignal.timeout(REQUEST_TIMEOUT_MS7);
68242
68248
  timer.addEventListener("abort", () => {
68243
68249
  pending.delete(id);
68244
68250
  reject(new RuntimeFault("io_failed", "Holder did not answer"));
68245
68251
  });
68246
- pending.set(id, resolve14);
68252
+ pending.set(id, resolve13);
68247
68253
  writeMessage(socket, { ...body, id });
68248
68254
  });
68249
68255
  };
@@ -68274,9 +68280,9 @@ function selectDriver(persistent, fallback) {
68274
68280
  suspend: async () => {
68275
68281
  await Promise.all([...drivers].map((driver) => driver.suspend?.()));
68276
68282
  },
68277
- respond: async (request2, mayWrite) => {
68283
+ respond: async (request2) => {
68278
68284
  for (const driver of drivers) {
68279
- const status = await driver.respond?.(request2, mayWrite);
68285
+ const status = await driver.respond?.(request2);
68280
68286
  if (status !== void 0 && status !== "unknown_run") return status;
68281
68287
  }
68282
68288
  return "unknown_run";
@@ -68316,9 +68322,9 @@ function createLazyDriver(load) {
68316
68322
  suspend: async () => {
68317
68323
  if (loaded.driver !== void 0) await (await loaded.driver).suspend?.();
68318
68324
  },
68319
- respond: async (request2, mayWrite) => {
68325
+ respond: async (request2) => {
68320
68326
  if (loaded.driver === void 0) return "unknown_run";
68321
- return await (await loaded.driver).respond?.(request2, mayWrite) ?? "unknown_run";
68327
+ return await (await loaded.driver).respond?.(request2) ?? "unknown_run";
68322
68328
  },
68323
68329
  stopTask: async (taskId) => {
68324
68330
  if (loaded.driver === void 0) return TASK_NOT_FOUND;
@@ -68580,14 +68586,14 @@ async function prepareRunInputs(spec, { source, tmpDir, signal, skills = [] }) {
68580
68586
  var import_node_crypto30 = require("crypto");
68581
68587
  var import_node_fs22 = require("fs");
68582
68588
  var import_node_net3 = require("net");
68583
- var import_node_path68 = require("path");
68589
+ var import_node_path66 = require("path");
68584
68590
  init_runtime_v2();
68585
68591
 
68586
68592
  // src/holder/admission.ts
68587
68593
  var import_node_fs19 = require("fs");
68588
- var import_promises63 = require("fs/promises");
68594
+ var import_promises61 = require("fs/promises");
68589
68595
  var import_node_os9 = require("os");
68590
- var import_node_path62 = require("path");
68596
+ var import_node_path60 = require("path");
68591
68597
  init_constants();
68592
68598
 
68593
68599
  // ../shared/dist/node/local-workspace.js
@@ -68598,88 +68604,16 @@ function resolveAlanDefaultWorkspacePath(homeDirectory = (0, import_node_os8.hom
68598
68604
  return (0, import_node_path55.join)(homeDirectory, ".alan", "workspace");
68599
68605
  }
68600
68606
 
68601
- // src/holder/admission-relocation.ts
68607
+ // src/holder/agent-context.ts
68602
68608
  var import_promises58 = require("fs/promises");
68603
68609
  var import_node_path56 = require("path");
68604
- var MAX_RELOCATION_CANDIDATES = 200;
68605
- var RELOCATION_BUDGET_MS = 2e4;
68606
- function repositoryIdentity(url3) {
68607
- const trimmed4 = url3.trim().replace(/\/+$/, "").replace(/\.git$/i, "");
68608
- if (trimmed4.length === 0) return null;
68609
- const scp = /^(?:[^@/]+@)?([^:/]+):(.+)$/.exec(trimmed4);
68610
- if (scp !== null && !trimmed4.includes("://")) {
68611
- return `${scp[1]}/${scp[2]}`.toLowerCase();
68612
- }
68613
- try {
68614
- const parsed = new URL(trimmed4);
68615
- return `${parsed.hostname}${parsed.pathname}`.replace(/\/+$/, "").toLowerCase();
68616
- } catch {
68617
- return null;
68618
- }
68619
- }
68620
- function repositoryIdentities(urls) {
68621
- return new Set(
68622
- urls.map(repositoryIdentity).filter((identity) => identity !== null)
68623
- );
68624
- }
68625
- async function originIdentity(git, path4, signal) {
68626
- try {
68627
- const output2 = await git.run(
68628
- { cwd: path4, args: ["config", "--get", "remote.origin.url"], readOnly: true },
68629
- signal
68630
- );
68631
- return output2.exitCode === 0 ? repositoryIdentity(output2.stdout) : null;
68632
- } catch {
68633
- return null;
68634
- }
68635
- }
68636
- async function childDirectories(parent, limit) {
68637
- try {
68638
- const entries = await (0, import_promises58.readdir)(parent, { withFileTypes: true });
68639
- return entries.filter((entry) => entry.isDirectory()).slice(0, limit).map((entry) => (0, import_node_path56.join)(parent, entry.name));
68640
- } catch {
68641
- return [];
68642
- }
68643
- }
68644
- async function candidateFolders(search) {
68645
- const roots = /* @__PURE__ */ new Map();
68646
- for (const path4 of [search.missingPath, ...search.approvedWorkspacePaths]) {
68647
- const parent = (0, import_node_path56.dirname)((0, import_node_path56.resolve)(path4));
68648
- roots.set(comparablePath(parent, search.platform), parent);
68649
- }
68650
- const candidates2 = /* @__PURE__ */ new Map();
68651
- for (const root of roots.values()) {
68652
- const remaining = MAX_RELOCATION_CANDIDATES - candidates2.size;
68653
- if (remaining <= 0) break;
68654
- for (const child of await childDirectories(root, remaining)) {
68655
- candidates2.set(comparablePath(child, search.platform), child);
68656
- }
68657
- }
68658
- return [...candidates2.values()];
68659
- }
68660
- async function discoverRelocatedWorkspace(search) {
68661
- if (search.expected.size === 0) return null;
68662
- const signal = AbortSignal.any([search.signal, AbortSignal.timeout(RELOCATION_BUDGET_MS)]);
68663
- const matches = [];
68664
- for (const candidate of await candidateFolders(search)) {
68665
- if (signal.aborted) return null;
68666
- const identity = await originIdentity(search.git, candidate, signal);
68667
- if (identity !== null && search.expected.has(identity)) matches.push(candidate);
68668
- if (matches.length > 1) return null;
68669
- }
68670
- return matches[0] ?? null;
68671
- }
68672
-
68673
- // src/holder/agent-context.ts
68674
- var import_promises59 = require("fs/promises");
68675
- var import_node_path57 = require("path");
68676
68610
 
68677
68611
  // ../agent-core/dist/prompt.js
68678
68612
  init_chunk_GI3ZGXTY();
68679
68613
 
68680
68614
  // src/holder/agent-context.ts
68681
68615
  async function readText4(path4) {
68682
- return (0, import_promises59.readFile)(path4, "utf8").then(
68616
+ return (0, import_promises58.readFile)(path4, "utf8").then(
68683
68617
  (text3) => text3.trim(),
68684
68618
  () => null
68685
68619
  );
@@ -68694,15 +68628,15 @@ async function startCommandState(statusPath) {
68694
68628
  return code === 0 ? { state: "exited_ok" } : { state: "failed", exitCode: code };
68695
68629
  }
68696
68630
  function createAgentContext(deps) {
68697
- const statusPath = (0, import_node_path57.join)(deps.homeDir, ".alan", "start-commands.status");
68698
- const logPath = (0, import_node_path57.join)(deps.homeDir, ".alan", "start-commands.log");
68631
+ const statusPath = (0, import_node_path56.join)(deps.homeDir, ".alan", "start-commands.status");
68632
+ const logPath = (0, import_node_path56.join)(deps.homeDir, ".alan", "start-commands.log");
68699
68633
  return async (spec, problems) => {
68700
- const file2 = (0, import_node_path57.join)(deps.dir, `${spec.conversationId}.json`);
68634
+ const file2 = (0, import_node_path56.join)(deps.dir, `${spec.conversationId}.json`);
68701
68635
  const saved = await readJsonFile(file2, agentContextSnapshotSchema);
68702
68636
  const known = saved.kind === "ok" ? saved.value : void 0;
68703
68637
  const hasEnvironment = (spec.agentContext ?? known)?.environment !== void 0;
68704
68638
  const start = hasEnvironment ? await startCommandState(statusPath) : void 0;
68705
- const snapshot2 = agentContextSnapshot({
68639
+ const snapshot = agentContextSnapshot({
68706
68640
  spec,
68707
68641
  ...spec.approvedWorkspacePaths?.[0] ? { workspaceRoot: spec.approvedWorkspacePaths[0] } : {},
68708
68642
  problems,
@@ -68710,39 +68644,39 @@ function createAgentContext(deps) {
68710
68644
  startLogPath: logPath,
68711
68645
  ...known ? { known } : {}
68712
68646
  });
68713
- if (snapshot2 === null) return void 0;
68714
- const rendered = renderAgentContext(snapshot2, known);
68647
+ if (snapshot === null) return void 0;
68648
+ const rendered = renderAgentContext(snapshot, known);
68715
68649
  return {
68716
68650
  full: rendered.full,
68717
68651
  ...rendered.update ? { update: rendered.update } : {},
68718
- save: () => writeJsonFileAtomic(file2, snapshot2)
68652
+ save: () => writeJsonFileAtomic(file2, snapshot)
68719
68653
  };
68720
68654
  };
68721
68655
  }
68722
68656
 
68723
68657
  // src/holder/checkout-refresh.ts
68724
- var import_node_path60 = require("path");
68658
+ var import_node_path59 = require("path");
68725
68659
 
68726
68660
  // src/holder/claim-once.ts
68727
68661
  var import_node_crypto28 = require("crypto");
68728
- var import_promises60 = require("fs/promises");
68729
- var import_node_path58 = require("path");
68662
+ var import_promises59 = require("fs/promises");
68663
+ var import_node_path57 = require("path");
68730
68664
  async function claimOnce(dir, name) {
68731
68665
  try {
68732
- await (0, import_promises60.mkdir)(dir, { recursive: true, mode: 448 });
68733
- await (await (0, import_promises60.open)((0, import_node_path58.join)(dir, name), "wx")).close();
68666
+ await (0, import_promises59.mkdir)(dir, { recursive: true, mode: 448 });
68667
+ await (await (0, import_promises59.open)((0, import_node_path57.join)(dir, name), "wx")).close();
68734
68668
  return true;
68735
68669
  } catch {
68736
68670
  return false;
68737
68671
  }
68738
68672
  }
68739
68673
  function claimFirstLease(freshnessDir, path4) {
68740
- return claimOnce((0, import_node_path58.join)(freshnessDir, "leased"), (0, import_node_crypto28.createHash)("sha256").update(path4).digest("hex"));
68674
+ return claimOnce((0, import_node_path57.join)(freshnessDir, "leased"), (0, import_node_crypto28.createHash)("sha256").update(path4).digest("hex"));
68741
68675
  }
68742
68676
 
68743
68677
  // src/holder/requested-checkout.ts
68744
- var import_promises61 = require("fs/promises");
68745
- var import_node_path59 = require("path");
68678
+ var import_promises60 = require("fs/promises");
68679
+ var import_node_path58 = require("path");
68746
68680
  var REMOTE2 = "origin";
68747
68681
  var REASON_MAX_CHARS = 200;
68748
68682
  function firstLine3(text3) {
@@ -68763,8 +68697,8 @@ function notSwitched(checkout, current, reason) {
68763
68697
  );
68764
68698
  }
68765
68699
  async function clone2(checkout, deps, signal) {
68766
- const parent = (0, import_node_path59.dirname)(checkout.path);
68767
- await (0, import_promises61.mkdir)(parent, { recursive: true });
68700
+ const parent = (0, import_node_path58.dirname)(checkout.path);
68701
+ await (0, import_promises60.mkdir)(parent, { recursive: true });
68768
68702
  await assertValidBranch(deps.git, parent, checkout.branch, signal);
68769
68703
  const output2 = await deps.git.run(
68770
68704
  {
@@ -68916,9 +68850,9 @@ async function applyRequestedCheckout(checkout, spec, deps, signal) {
68916
68850
  function short(sha) {
68917
68851
  return sha.slice(0, 12);
68918
68852
  }
68919
- function staleCheckout(path4, snapshot2, tip) {
68920
- const checkout = snapshot2 === void 0 ? "is the environment snapshot's checkout" : `is the environment snapshot's checkout of ${snapshot2.branch} (commit ${short(snapshot2.head)})`;
68921
- const base = snapshot2 === void 0 ? "its upstream" : `origin/${snapshot2.base}`;
68853
+ function staleCheckout(path4, snapshot, tip) {
68854
+ const checkout = snapshot === void 0 ? "is the environment snapshot's checkout" : `is the environment snapshot's checkout of ${snapshot.branch} (commit ${short(snapshot.head)})`;
68855
+ const base = snapshot === void 0 ? "its upstream" : `origin/${snapshot.base}`;
68922
68856
  const remote = tip === void 0 ? "may be ahead" : `is ahead at ${short(tip)}`;
68923
68857
  return {
68924
68858
  path: path4,
@@ -68929,18 +68863,18 @@ function staleCheckout(path4, snapshot2, tip) {
68929
68863
  async function fastForward(freshness, operationId, deps, signal) {
68930
68864
  var _stack = [];
68931
68865
  try {
68932
- const { path: cwd, snapshot: snapshot2, tip } = freshness;
68933
- const attempt2 = await deps.locks.tryExclusive(snapshot2.commonDir, operationId);
68866
+ const { path: cwd, snapshot, tip } = freshness;
68867
+ const attempt2 = await deps.locks.tryExclusive(snapshot.commonDir, operationId);
68934
68868
  if (attempt2.kind === "busy") return false;
68935
68869
  const _lock = __using(_stack, attempt2.lock, true);
68936
68870
  const now = await readCheckoutStatus(deps.git, cwd, signal);
68937
- if (now === null || now.dirty || now.head !== snapshot2.head || now.branch !== snapshot2.branch) {
68871
+ if (now === null || now.dirty || now.head !== snapshot.head || now.branch !== snapshot.branch) {
68938
68872
  return false;
68939
68873
  }
68940
68874
  const git = (args) => deps.git.run({ cwd, args }, signal);
68941
68875
  if ((await git(["switch", "--quiet", "--detach", tip])).exitCode !== 0) return false;
68942
- const moved = await git(["update-ref", `refs/heads/${snapshot2.branch}`, tip, snapshot2.head]);
68943
- const back = await git(["switch", "--quiet", snapshot2.branch]);
68876
+ const moved = await git(["update-ref", `refs/heads/${snapshot.branch}`, tip, snapshot.head]);
68877
+ const back = await git(["switch", "--quiet", snapshot.branch]);
68944
68878
  return moved.exitCode === 0 && back.exitCode === 0;
68945
68879
  } catch (_) {
68946
68880
  var _error = _, _hasError = true;
@@ -68972,9 +68906,8 @@ function problemFor(freshness) {
68972
68906
  return staleCheckout(freshness.path, void 0);
68973
68907
  }
68974
68908
  }
68975
- async function checkoutsOf(spec, leaseTargets) {
68976
- if (leaseTargets.length > 0 || spec.projectPath === void 0) return [...leaseTargets];
68977
- return checkoutsUnder(spec.projectPath);
68909
+ async function checkoutsOf(spec) {
68910
+ return spec.projectPath === void 0 ? [] : checkoutsUnder(spec.projectPath);
68978
68911
  }
68979
68912
  function requestedCheckoutsOf(spec, log) {
68980
68913
  const roots = spec.approvedWorkspacePaths ?? [];
@@ -69002,7 +68935,7 @@ async function applyRequestedCheckouts(spec, deps, signal) {
69002
68935
  ...outcome2.kind === "moved" ? { how: outcome2.how } : {}
69003
68936
  });
69004
68937
  if (outcome2.kind === "on_branch") continue;
69005
- settled2.add((0, import_node_path60.resolve)(checkout.path));
68938
+ settled2.add((0, import_node_path59.resolve)(checkout.path));
69006
68939
  if (outcome2.kind === "noted") {
69007
68940
  problems.push({ path: checkout.path, problem: outcome2.problem, action: outcome2.action });
69008
68941
  }
@@ -69012,7 +68945,7 @@ async function applyRequestedCheckouts(spec, deps, signal) {
69012
68945
  async function refreshSnapshotCheckouts(spec, targets, settled2, deps, signal) {
69013
68946
  const problems = [];
69014
68947
  for (const target of targets) {
69015
- if (settled2.has((0, import_node_path60.resolve)(target))) continue;
68948
+ if (settled2.has((0, import_node_path59.resolve)(target))) continue;
69016
68949
  const freshness = await readCheckoutFreshness(deps.dir, target);
69017
68950
  if (freshness === null) continue;
69018
68951
  const outcome2 = await atFirstLease(freshness, spec, deps, signal).catch(
@@ -69029,11 +68962,11 @@ async function refreshSnapshotCheckouts(spec, targets, settled2, deps, signal) {
69029
68962
  return problems;
69030
68963
  }
69031
68964
  function createCheckoutRefresh(deps) {
69032
- return async (spec, leaseTargets, signal) => {
68965
+ return async (spec, signal) => {
69033
68966
  if (spec.providerSessionId !== void 0) return [];
69034
- if (!await claimOnce((0, import_node_path60.join)(deps.dir, "conversations"), spec.conversationId)) return [];
68967
+ if (!await claimOnce((0, import_node_path59.join)(deps.dir, "conversations"), spec.conversationId)) return [];
69035
68968
  const requested = await applyRequestedCheckouts(spec, deps, signal);
69036
- const targets = await checkoutsOf(spec, leaseTargets);
68969
+ const targets = await checkoutsOf(spec);
69037
68970
  return [
69038
68971
  ...requested.problems,
69039
68972
  ...await refreshSnapshotCheckouts(spec, targets, requested.settled, deps, signal)
@@ -69041,207 +68974,6 @@ function createCheckoutRefresh(deps) {
69041
68974
  };
69042
68975
  }
69043
68976
 
69044
- // src/holder/lease.ts
69045
- var import_promises62 = require("fs/promises");
69046
- var import_node_path61 = require("path");
69047
- var LEASE_CHECK_EVERY_MS = 5e3;
69048
- var MAX_TRANSIENT_FAILURES = 3;
69049
- var BACKOFF_BASE_MS = 1e3;
69050
- var BACKOFF_MAX_MS = 15e3;
69051
- var MESSAGES = {
69052
- workspace_lease_unavailable: "The workspace or Git checkout became unavailable while the run was active. Restore it and start a new run.",
69053
- workspace_lease_path_changed: "The selected workspace folder changed while the run was active. The run stopped before continuing; choose the correct folder and start a new run.",
69054
- workspace_lease_repository_changed: "The workspace now points to a different repository or worktree. The run stopped before continuing; restore the original checkout and start a new run."
69055
- };
69056
- function identityFailure(code, workspacePath) {
69057
- return { code, problemCode: "app.workspace.missing", message: MESSAGES[code], workspacePath };
69058
- }
69059
- async function fileIdentity(path4) {
69060
- const canonical = await (0, import_promises62.realpath)(path4);
69061
- const info = await (0, import_promises62.stat)(canonical, { bigint: true });
69062
- return `${canonical}:${info.dev}:${info.ino}`;
69063
- }
69064
- async function snapshot(git, path4, signal) {
69065
- try {
69066
- const output2 = await git.run(
69067
- {
69068
- cwd: path4,
69069
- args: ["rev-parse", "--path-format=absolute", "--git-dir", "--git-common-dir"],
69070
- readOnly: true
69071
- },
69072
- signal
69073
- );
69074
- const [gitDir, commonDir] = output2.stdout.trim().split("\n");
69075
- if (output2.exitCode !== 0 || !gitDir || !commonDir) return null;
69076
- return {
69077
- workspace: await fileIdentity(path4),
69078
- repository: await fileIdentity(commonDir),
69079
- worktree: await fileIdentity(gitDir),
69080
- commonDir: await (0, import_promises62.realpath)(commonDir)
69081
- };
69082
- } catch {
69083
- return null;
69084
- }
69085
- }
69086
- async function gitValue(git, path4, args, signal) {
69087
- const output2 = await git.run({ cwd: path4, args, readOnly: true }, signal).catch(() => null);
69088
- const value2 = output2?.exitCode === 0 ? output2.stdout.trim() : "";
69089
- return value2.length > 0 ? value2 : null;
69090
- }
69091
- async function pathExists(path4) {
69092
- try {
69093
- await (0, import_promises62.stat)(path4);
69094
- return true;
69095
- } catch (error61) {
69096
- return errnoCode(error61) !== "ENOENT" && errnoCode(error61) !== "ENOTDIR";
69097
- }
69098
- }
69099
- async function hasGitMarker(path4) {
69100
- let directory;
69101
- try {
69102
- directory = await (0, import_promises62.realpath)(path4);
69103
- } catch {
69104
- return true;
69105
- }
69106
- for (; ; ) {
69107
- try {
69108
- await (0, import_promises62.stat)((0, import_node_path61.join)(directory, ".git"));
69109
- return true;
69110
- } catch (error61) {
69111
- const code = errnoCode(error61);
69112
- if (code !== "ENOENT" && code !== "ENOTDIR") return true;
69113
- }
69114
- const parent = (0, import_node_path61.dirname)(directory);
69115
- if (parent === directory) return false;
69116
- directory = parent;
69117
- }
69118
- }
69119
- async function probeCheckout(git, path4, captured, signal) {
69120
- const current = await snapshot(git, path4, signal);
69121
- if (current === null) {
69122
- const failure6 = identityFailure("workspace_lease_unavailable", path4);
69123
- return await pathExists(path4) ? { kind: "transient", failure: failure6 } : { kind: "failed", failure: failure6 };
69124
- }
69125
- if (current.workspace !== captured.workspace) {
69126
- return { kind: "failed", failure: identityFailure("workspace_lease_path_changed", path4) };
69127
- }
69128
- if (current.repository !== captured.repository || current.worktree !== captured.worktree) {
69129
- return { kind: "failed", failure: identityFailure("workspace_lease_repository_changed", path4) };
69130
- }
69131
- return { kind: "ok" };
69132
- }
69133
- async function releaseAll(locks) {
69134
- for (const lock of locks) await lock[Symbol.asyncDispose]();
69135
- }
69136
- async function captureOne(git, path4, signal) {
69137
- const identity = await snapshot(git, path4, signal);
69138
- if (identity === null) return identityFailure("workspace_lease_unavailable", path4);
69139
- const branch = await gitValue(git, path4, ["symbolic-ref", "-q", "--short", "HEAD"], signal);
69140
- const head = await gitValue(git, path4, ["rev-parse", "-q", "--verify", "HEAD"], signal);
69141
- return { path: path4, identity, checkout: { path: path4, commonDir: identity.commonDir, branch, head } };
69142
- }
69143
- async function captureWorkspaceLease(runId, paths, deps, signal) {
69144
- const captured = [];
69145
- const locks = [];
69146
- const locked = /* @__PURE__ */ new Set();
69147
- for (const path4 of paths) {
69148
- const one = await captureOne(deps.git, path4, signal);
69149
- if (!("identity" in one)) {
69150
- await releaseAll(locks);
69151
- return { kind: "failed", failure: one };
69152
- }
69153
- const key = comparablePath(one.identity.commonDir, deps.platform);
69154
- if (!locked.has(key)) {
69155
- const attempt2 = await deps.locks.tryShared(one.identity.commonDir, runId);
69156
- if (attempt2.kind === "busy") {
69157
- await releaseAll(locks);
69158
- return {
69159
- kind: "failed",
69160
- failure: {
69161
- code: "workspace_busy",
69162
- problemCode: null,
69163
- message: "Alan is committing or pushing in this repository for a checkout switch. Try again when it finishes.",
69164
- workspacePath: path4
69165
- }
69166
- };
69167
- }
69168
- locked.add(key);
69169
- locks.push(attempt2.lock);
69170
- }
69171
- captured.push(one);
69172
- }
69173
- return { kind: "held", lease: holdLease(captured, locks, deps) };
69174
- }
69175
- function holdLease(captured, locks, deps) {
69176
- const lifetime = new AbortController();
69177
- const lost = new AbortController();
69178
- const state = { failure: null, inFlight: null, transientStreak: 0, nextCheckAt: 0 };
69179
- const probeOnce = async () => {
69180
- for (const { path: path4, identity } of captured) {
69181
- const probe = await probeCheckout(deps.git, path4, identity, lifetime.signal);
69182
- if (probe.kind !== "ok") return probe;
69183
- }
69184
- return { kind: "ok" };
69185
- };
69186
- const lose = (failure6) => {
69187
- if (state.failure !== null) return;
69188
- state.failure = failure6;
69189
- deps.log.warn("holder.workspace_lease_lost", {
69190
- code: failure6.code,
69191
- workspacePath: failure6.workspacePath
69192
- });
69193
- lost.abort(failure6);
69194
- };
69195
- const apply = (probe) => {
69196
- if (probe.kind === "ok") {
69197
- state.transientStreak = 0;
69198
- state.nextCheckAt = 0;
69199
- } else if (probe.kind === "failed") {
69200
- lose(probe.failure);
69201
- } else {
69202
- state.transientStreak += 1;
69203
- if (state.transientStreak >= MAX_TRANSIENT_FAILURES) lose(probe.failure);
69204
- else {
69205
- const backoff = BACKOFF_BASE_MS * 2 ** (state.transientStreak - 1);
69206
- state.nextCheckAt = deps.clock.monotonic() + Math.min(backoff, BACKOFF_MAX_MS);
69207
- }
69208
- }
69209
- return state.failure === null;
69210
- };
69211
- const check3 = () => {
69212
- if (state.failure !== null) return Promise.resolve(false);
69213
- state.inFlight ??= probeOnce().then((probe) => lifetime.signal.aborted ? state.failure === null : apply(probe)).finally(() => {
69214
- state.inFlight = null;
69215
- });
69216
- return state.inFlight;
69217
- };
69218
- const monitor = captured.length === 0 ? null : startMaintenance({
69219
- everyMs: deps.everyMs ?? LEASE_CHECK_EVERY_MS,
69220
- jobs: [
69221
- {
69222
- name: "holder.workspace_lease",
69223
- run: async () => {
69224
- if (state.failure !== null || deps.clock.monotonic() < state.nextCheckAt) return;
69225
- await check3();
69226
- }
69227
- }
69228
- ],
69229
- clock: deps.clock,
69230
- log: deps.log
69231
- });
69232
- return {
69233
- checkouts: captured.map((entry) => entry.checkout),
69234
- lost: lost.signal,
69235
- failure: () => state.failure,
69236
- verify: check3,
69237
- [Symbol.asyncDispose]: async () => {
69238
- lifetime.abort();
69239
- await monitor?.[Symbol.asyncDispose]();
69240
- await releaseAll(locks);
69241
- }
69242
- };
69243
- }
69244
-
69245
68977
  // src/holder/admission.ts
69246
68978
  var VOLUME_ERRORS = /* @__PURE__ */ new Set([
69247
68979
  "EIO",
@@ -69250,13 +68982,12 @@ var VOLUME_ERRORS = /* @__PURE__ */ new Set([
69250
68982
  "ENXIO",
69251
68983
  "ESTALE"
69252
68984
  ]);
69253
- var MESSAGES2 = {
68985
+ var MESSAGES = {
69254
68986
  missing: "This project folder was moved or removed. Locate it before starting the run.",
69255
68987
  permission: "Alan needs permission to access this project folder.",
69256
68988
  volume: "The drive containing this project is unavailable. Connect it and try again.",
69257
68989
  pinnedMissing: "This run must use exactly this project folder, and it was moved or removed. Restore it or choose another folder.",
69258
- notApproved: "This folder is not one of the workspaces approved on this computer.",
69259
- mismatch: "This folder belongs to a different repository. Choose the correct project folder and try again."
68990
+ notApproved: "This folder is not one of the workspaces approved on this computer."
69260
68991
  };
69261
68992
  function rejected(rejection2, message2) {
69262
68993
  return { kind: "rejected", rejection: rejection2, message: message2 };
@@ -69275,7 +69006,7 @@ function volumeRoot(path4) {
69275
69006
  }
69276
69007
  async function exists4(path4) {
69277
69008
  try {
69278
- await (0, import_promises63.stat)(path4);
69009
+ await (0, import_promises61.stat)(path4);
69279
69010
  return true;
69280
69011
  } catch {
69281
69012
  return false;
@@ -69283,30 +69014,23 @@ async function exists4(path4) {
69283
69014
  }
69284
69015
  async function inspectReadiness(path4) {
69285
69016
  try {
69286
- if (!(await (0, import_promises63.stat)(path4)).isDirectory()) {
69287
- return { ready: false, missing: true, message: MESSAGES2.missing };
69017
+ if (!(await (0, import_promises61.stat)(path4)).isDirectory()) {
69018
+ return { ready: false, missing: true, message: MESSAGES.missing };
69288
69019
  }
69289
- await (0, import_promises63.access)(path4, import_node_fs19.constants.R_OK | import_node_fs19.constants.W_OK | import_node_fs19.constants.X_OK);
69020
+ await (0, import_promises61.access)(path4, import_node_fs19.constants.R_OK | import_node_fs19.constants.W_OK | import_node_fs19.constants.X_OK);
69290
69021
  return { ready: true };
69291
69022
  } catch (error61) {
69292
69023
  const code = errnoCode(error61) ?? "";
69293
69024
  if (code === "EACCES" || code === "EPERM") {
69294
- return { ready: false, missing: false, message: MESSAGES2.permission };
69025
+ return { ready: false, missing: false, message: MESSAGES.permission };
69295
69026
  }
69296
69027
  const root = volumeRoot(path4);
69297
69028
  if (VOLUME_ERRORS.has(code) || code === "ENOENT" && root !== null && !await exists4(root)) {
69298
- return { ready: false, missing: false, message: MESSAGES2.volume };
69029
+ return { ready: false, missing: false, message: MESSAGES.volume };
69299
69030
  }
69300
- return { ready: false, missing: true, message: MESSAGES2.missing };
69031
+ return { ready: false, missing: true, message: MESSAGES.missing };
69301
69032
  }
69302
69033
  }
69303
- function expectedRepositoryUrls(spec, projectPath, platform3) {
69304
- const folder = comparablePath(projectPath, platform3);
69305
- return [
69306
- ...(spec.repoLocalPaths ?? []).filter((repo) => comparablePath(repo.localPath, platform3) === folder).map((repo) => repo.repoUrl),
69307
- ...spec.localRepoUrls ?? []
69308
- ];
69309
- }
69310
69034
  function resolveSelectedSkills(spec, context) {
69311
69035
  const invocations = spec.skillInvocations ?? [];
69312
69036
  if (context.skills === void 0) {
@@ -69333,51 +69057,18 @@ async function checkProvider(spec, context) {
69333
69057
  `The ${provider4.name} CLI (\`${provider4.command}\`) is not installed on this computer, or it is not on the PATH Alan uses. Install it and try again.`
69334
69058
  );
69335
69059
  }
69336
- async function locateWorkspace(spec, projectPath, expected, context, signal) {
69337
- const readiness2 = await inspectReadiness(projectPath);
69338
- if (readiness2.ready) return { cwd: projectPath, relocated: null };
69339
- if (!readiness2.missing) return rejected("workspace_unavailable", readiness2.message);
69340
- if (spec.workspacePathPinned === true) {
69341
- return rejected("workspace_pinned_missing", MESSAGES2.pinnedMissing);
69342
- }
69343
- const found = await discoverRelocatedWorkspace({
69344
- missingPath: projectPath,
69345
- approvedWorkspacePaths: spec.approvedWorkspacePaths ?? [],
69346
- expected,
69347
- git: context.git,
69348
- platform: context.platform,
69349
- signal
69350
- });
69351
- if (found === null) return rejected("workspace_unavailable", readiness2.message);
69352
- const moved = await inspectReadiness(found);
69353
- if (!moved.ready) return rejected("workspace_unavailable", moved.message);
69354
- return {
69355
- cwd: found,
69356
- relocated: {
69357
- sessionUpdate: "_alan/run.workspace_relocated",
69358
- previousPath: projectPath,
69359
- canonicalPath: found
69360
- }
69361
- };
69362
- }
69363
69060
  async function admitDefaultWorkspace(spec, context, skills) {
69364
69061
  const { env } = context;
69365
69062
  const path4 = resolveAlanDefaultWorkspacePath(env.HOME || env.USERPROFILE || (0, import_node_os9.homedir)());
69366
69063
  try {
69367
- await (0, import_promises63.mkdir)(path4, { recursive: true, mode: 448 });
69368
- await (0, import_promises63.access)(path4, import_node_fs19.constants.R_OK | import_node_fs19.constants.W_OK | import_node_fs19.constants.X_OK);
69369
- return {
69370
- kind: "admitted",
69371
- spec: { ...spec, projectPath: path4 },
69372
- relocated: null,
69373
- leaseTargets: [],
69374
- skills
69375
- };
69064
+ await (0, import_promises61.mkdir)(path4, { recursive: true, mode: 448 });
69065
+ await (0, import_promises61.access)(path4, import_node_fs19.constants.R_OK | import_node_fs19.constants.W_OK | import_node_fs19.constants.X_OK);
69066
+ return { kind: "admitted", spec: { ...spec, projectPath: path4 }, skills };
69376
69067
  } catch (error61) {
69377
69068
  const code = errnoCode(error61);
69378
69069
  return rejected(
69379
69070
  "workspace_unavailable",
69380
- code === "EACCES" || code === "EPERM" ? MESSAGES2.permission : MESSAGES2.missing
69071
+ code === "EACCES" || code === "EPERM" ? MESSAGES.permission : MESSAGES.missing
69381
69072
  );
69382
69073
  }
69383
69074
  }
@@ -69391,7 +69082,7 @@ async function withInstalledCloudSkills(spec, context) {
69391
69082
  }
69392
69083
  };
69393
69084
  }
69394
- async function admitRun(spec, context, signal) {
69085
+ async function admitRun(spec, context) {
69395
69086
  const provider4 = await checkProvider(spec, context);
69396
69087
  if (provider4 !== null) return provider4;
69397
69088
  const selected = await resolveSelectedSkills(spec, context);
@@ -69404,50 +69095,30 @@ async function admitRun(spec, context, signal) {
69404
69095
  const skills = selected.skills;
69405
69096
  spec = await withInstalledCloudSkills(spec, context);
69406
69097
  const projectPath = spec.projectPath;
69407
- if (projectPath === void 0) {
69408
- return { kind: "admitted", spec, relocated: null, leaseTargets: [], skills };
69409
- }
69098
+ if (projectPath === void 0) return { kind: "admitted", spec, skills };
69410
69099
  if (isAlanDefaultWorkspace(projectPath)) return admitDefaultWorkspace(spec, context, skills);
69411
- const { platform: platform3 } = context;
69412
- const expected = repositoryIdentities(expectedRepositoryUrls(spec, projectPath, platform3));
69413
- const located = await locateWorkspace(spec, projectPath, expected, context, signal);
69414
- if ("kind" in located) return located;
69415
- const { cwd, relocated } = located;
69100
+ const readiness2 = await inspectReadiness(projectPath);
69101
+ if (!readiness2.ready) {
69102
+ return readiness2.missing && spec.workspacePathPinned === true ? rejected("workspace_pinned_missing", MESSAGES.pinnedMissing) : rejected("workspace_unavailable", readiness2.message);
69103
+ }
69416
69104
  const roots = [
69417
69105
  ...await context.approvedRoots(),
69418
69106
  projectPath,
69419
69107
  ...spec.approvedWorkspacePaths ?? [],
69420
- ...(spec.repoLocalPaths ?? []).map((repo) => repo.localPath),
69421
- ...relocated === null ? [] : [relocated.canonicalPath]
69108
+ ...(spec.repoLocalPaths ?? []).map((repo) => repo.localPath)
69422
69109
  ];
69423
- if (!await isApprovedPath(cwd, roots, platform3)) {
69424
- return rejected("workspace_unavailable", MESSAGES2.notApproved);
69425
- }
69426
- if (expected.size > 0) {
69427
- const identity = await originIdentity(context.git, cwd, signal);
69428
- if (identity === null || !expected.has(identity)) {
69429
- return rejected("workspace_repository_mismatch", MESSAGES2.mismatch);
69430
- }
69110
+ if (!await isApprovedPath(projectPath, roots, context.platform)) {
69111
+ return rejected("workspace_unavailable", MESSAGES.notApproved);
69431
69112
  }
69432
- return {
69433
- kind: "admitted",
69434
- spec: relocated === null ? spec : { ...spec, projectPath: cwd },
69435
- relocated,
69436
- leaseTargets: await hasGitMarker(cwd) ? [cwd] : [],
69437
- skills
69438
- };
69113
+ return { kind: "admitted", spec, skills };
69439
69114
  }
69440
- var PROBE_TIMEOUT_MS2 = 5e3;
69441
69115
  var CHECKOUT_LOCAL_TIMEOUT_MS = 6e4;
69442
69116
  var CHECKOUT_NETWORK_TIMEOUT_MS = 12e4;
69443
69117
  function createHolderWorkspace(machine, clock, log) {
69444
69118
  const platform3 = machine.platform ?? process.platform;
69445
- const git = createGitRunner({ env: machine.env, platform: platform3, localTimeoutMs: PROBE_TIMEOUT_MS2 });
69446
- const locks = openRepositoryLocks({ dir: (0, import_node_path62.join)(machine.stateDir, "locks"), clock, platform: platform3 });
69447
69119
  return {
69448
69120
  admission: {
69449
69121
  env: machine.env,
69450
- git,
69451
69122
  platform: platform3,
69452
69123
  skills: skillsLayout(
69453
69124
  machine.stateDir,
@@ -69455,14 +69126,13 @@ function createHolderWorkspace(machine, clock, log) {
69455
69126
  ),
69456
69127
  approvedRoots: async () => {
69457
69128
  const approved = await openApprovedPaths({
69458
- file: (0, import_node_path62.join)(machine.stateDir, "workspaces.json"),
69129
+ file: (0, import_node_path60.join)(machine.stateDir, "workspaces.json"),
69459
69130
  log,
69460
69131
  platform: platform3
69461
69132
  });
69462
69133
  return approved.roots();
69463
69134
  }
69464
69135
  },
69465
- lease: { git, locks, clock, log, platform: platform3 },
69466
69136
  ...machine.refreshesFirstCheckout === true ? {
69467
69137
  refreshFirstCheckout: createCheckoutRefresh({
69468
69138
  git: createGitRunner({
@@ -69471,12 +69141,12 @@ function createHolderWorkspace(machine, clock, log) {
69471
69141
  localTimeoutMs: CHECKOUT_LOCAL_TIMEOUT_MS,
69472
69142
  networkTimeoutMs: CHECKOUT_NETWORK_TIMEOUT_MS
69473
69143
  }),
69474
- locks,
69144
+ locks: openRepositoryLocks({ dir: (0, import_node_path60.join)(machine.stateDir, "locks"), clock, platform: platform3 }),
69475
69145
  log,
69476
- dir: (0, import_node_path62.join)(machine.stateDir, "checkout-freshness")
69146
+ dir: (0, import_node_path60.join)(machine.stateDir, "checkout-freshness")
69477
69147
  }),
69478
69148
  prepareAgentContext: createAgentContext({
69479
- dir: (0, import_node_path62.join)(machine.stateDir, "agent-context"),
69149
+ dir: (0, import_node_path60.join)(machine.stateDir, "agent-context"),
69480
69150
  homeDir: machine.env.HOME || (0, import_node_os9.homedir)()
69481
69151
  })
69482
69152
  } : {}
@@ -69484,28 +69154,14 @@ function createHolderWorkspace(machine, clock, log) {
69484
69154
  }
69485
69155
 
69486
69156
  // src/holder/respond.ts
69487
- function createAnswerGate() {
69488
- const state = { lease: null };
69489
- return {
69490
- allows: () => state.lease?.verify() ?? Promise.resolve(true),
69491
- guard: (lease) => {
69492
- state.lease = lease;
69493
- return {
69494
- [Symbol.dispose]: () => {
69495
- if (state.lease === lease) state.lease = null;
69496
- }
69497
- };
69498
- }
69499
- };
69500
- }
69501
- async function respondToTurn(runningRunId, gate, driver, request2) {
69157
+ async function respondToTurn(runningRunId, driver, request2) {
69502
69158
  if (runningRunId !== request2.runId) return "unknown_run";
69503
69159
  if (driver.respond === void 0) return "not_waiting";
69504
- return driver.respond(request2, () => gate.allows());
69160
+ return driver.respond(request2);
69505
69161
  }
69506
69162
 
69507
69163
  // src/holder/session-facts.ts
69508
- var import_promises64 = require("fs/promises");
69164
+ var import_promises62 = require("fs/promises");
69509
69165
  var CLI_RSS_CACHE_MS = 1e4;
69510
69166
  var LOGIN_PROBLEM_PREFIX = "cli.auth.";
69511
69167
  function isLoginFailure(result) {
@@ -69531,8 +69187,8 @@ function createSessionFacts(options) {
69531
69187
  const path4 = await resolveCommandOnPath(command, env, platform3);
69532
69188
  if (path4 === null) return null;
69533
69189
  try {
69534
- const real = await (0, import_promises64.realpath)(path4);
69535
- const info = await (0, import_promises64.stat)(real);
69190
+ const real = await (0, import_promises62.realpath)(path4);
69191
+ const info = await (0, import_promises62.stat)(real);
69536
69192
  return { command, key: `${real}:${info.ino}:${info.size}:${info.mtimeMs}` };
69537
69193
  } catch {
69538
69194
  return null;
@@ -69619,12 +69275,12 @@ function createSessionFacts(options) {
69619
69275
  init_acp2();
69620
69276
 
69621
69277
  // src/run-log/archive.ts
69622
- var import_promises65 = require("fs/promises");
69623
- var import_node_path63 = require("path");
69278
+ var import_promises63 = require("fs/promises");
69279
+ var import_node_path61 = require("path");
69624
69280
  init_runtime_v2();
69625
69281
  async function openRunArchive(runsDir) {
69626
- const path4 = (0, import_node_path63.join)((0, import_node_path63.dirname)(runsDir), "archived-runs.txt");
69627
- const text3 = await (0, import_promises65.readFile)(path4, "utf8").catch((error61) => {
69282
+ const path4 = (0, import_node_path61.join)((0, import_node_path61.dirname)(runsDir), "archived-runs.txt");
69283
+ const text3 = await (0, import_promises63.readFile)(path4, "utf8").catch((error61) => {
69628
69284
  if (errnoCode(error61) === "ENOENT") return "";
69629
69285
  throw error61;
69630
69286
  });
@@ -69638,7 +69294,7 @@ async function openRunArchive(runsDir) {
69638
69294
  add: async (runIds) => {
69639
69295
  const added = runIds.filter((runId) => !archived.has(runId));
69640
69296
  if (added.length === 0) return;
69641
- await (0, import_promises65.appendFile)(path4, `
69297
+ await (0, import_promises63.appendFile)(path4, `
69642
69298
  ${added.join("\n")}
69643
69299
  `, { mode: 384 });
69644
69300
  for (const runId of added) archived.add(runId);
@@ -69649,11 +69305,11 @@ ${added.join("\n")}
69649
69305
  // src/run-log/complete.ts
69650
69306
  var import_node_crypto29 = require("crypto");
69651
69307
  var import_node_fs20 = require("fs");
69652
- var import_node_path65 = require("path");
69308
+ var import_node_path63 = require("path");
69653
69309
 
69654
69310
  // src/run-log/directory.ts
69655
- var import_promises66 = require("fs/promises");
69656
- var import_node_path64 = require("path");
69311
+ var import_promises64 = require("fs/promises");
69312
+ var import_node_path62 = require("path");
69657
69313
  init_runtime_v2();
69658
69314
  init_zod();
69659
69315
  var runMetaSchema = external_exports.object({
@@ -69679,17 +69335,17 @@ async function readRunMeta(path4) {
69679
69335
  return read.kind === "ok" ? read.value : null;
69680
69336
  }
69681
69337
  function runDirectory(runsDir, runId) {
69682
- const dir = (0, import_node_path64.join)(runsDir, runId);
69338
+ const dir = (0, import_node_path62.join)(runsDir, runId);
69683
69339
  return {
69684
69340
  dir,
69685
- log: (0, import_node_path64.join)(dir, "log.jsonl"),
69686
- upload: (0, import_node_path64.join)(dir, "upload.json"),
69687
- meta: (0, import_node_path64.join)(dir, "run.json")
69341
+ log: (0, import_node_path62.join)(dir, "log.jsonl"),
69342
+ upload: (0, import_node_path62.join)(dir, "upload.json"),
69343
+ meta: (0, import_node_path62.join)(dir, "run.json")
69688
69344
  };
69689
69345
  }
69690
69346
  async function isRunClaimed(runsDir, runId) {
69691
69347
  try {
69692
- return (await (0, import_promises66.stat)(runDirectory(runsDir, runId).log)).size > 0;
69348
+ return (await (0, import_promises64.stat)(runDirectory(runsDir, runId).log)).size > 0;
69693
69349
  } catch (error61) {
69694
69350
  if (errnoCode(error61) === "ENOENT") return false;
69695
69351
  throw error61;
@@ -69698,7 +69354,7 @@ async function isRunClaimed(runsDir, runId) {
69698
69354
 
69699
69355
  // src/run-log/complete.ts
69700
69356
  function writeLogFile(path4, dir, text3) {
69701
- const temp = (0, import_node_path65.join)(dir, `.log.${(0, import_node_crypto29.randomUUID)()}.tmp`);
69357
+ const temp = (0, import_node_path63.join)(dir, `.log.${(0, import_node_crypto29.randomUUID)()}.tmp`);
69702
69358
  const fd = (0, import_node_fs20.openSync)(temp, "wx", 384);
69703
69359
  try {
69704
69360
  (0, import_node_fs20.writeSync)(fd, text3);
@@ -69727,8 +69383,8 @@ async function writeCompleteRunLog(runsDir, meta3, records) {
69727
69383
  }
69728
69384
 
69729
69385
  // src/run-log/conversation-index.ts
69730
- var import_promises67 = require("fs/promises");
69731
- var import_node_path66 = require("path");
69386
+ var import_promises65 = require("fs/promises");
69387
+ var import_node_path64 = require("path");
69732
69388
  init_runtime_v2();
69733
69389
  init_zod();
69734
69390
  var ORDINALS_PER_SHARD = 1e3;
@@ -69745,13 +69401,13 @@ var coverageSchema = external_exports.object({
69745
69401
  nextExpectedOrdinal: external_exports.number().int().positive()
69746
69402
  });
69747
69403
  function conversationsDirectory(runsDir) {
69748
- return (0, import_node_path66.join)((0, import_node_path66.dirname)(runsDir), "conversations");
69404
+ return (0, import_node_path64.join)((0, import_node_path64.dirname)(runsDir), "conversations");
69749
69405
  }
69750
69406
  function indexDirectory(runsDir, conversationId) {
69751
- return (0, import_node_path66.join)(conversationsDirectory(runsDir), conversationId, "turn-index");
69407
+ return (0, import_node_path64.join)(conversationsDirectory(runsDir), conversationId, "turn-index");
69752
69408
  }
69753
69409
  function shardPath(runsDir, conversationId, ordinal) {
69754
- return (0, import_node_path66.join)(
69410
+ return (0, import_node_path64.join)(
69755
69411
  indexDirectory(runsDir, conversationId),
69756
69412
  `${Math.floor(ordinal / ORDINALS_PER_SHARD)}.jsonl`
69757
69413
  );
@@ -69760,10 +69416,10 @@ async function indexConversationRun(runsDir, conversationId, ordinal, assistantO
69760
69416
  const nextOrdinal = assistantOrdinal + 1;
69761
69417
  if (nextOrdinal <= ordinal) throw new Error("Assistant order must follow the prompt");
69762
69418
  const path4 = shardPath(runsDir, conversationId, ordinal);
69763
- await (0, import_promises67.mkdir)((0, import_node_path66.dirname)(path4), { recursive: true, mode: 448 });
69764
- await (0, import_promises67.appendFile)(path4, `${JSON.stringify({ ordinal, nextOrdinal, runId })}
69419
+ await (0, import_promises65.mkdir)((0, import_node_path64.dirname)(path4), { recursive: true, mode: 448 });
69420
+ await (0, import_promises65.appendFile)(path4, `${JSON.stringify({ ordinal, nextOrdinal, runId })}
69765
69421
  `, { mode: 384 });
69766
- const coveragePath = (0, import_node_path66.join)((0, import_node_path66.dirname)((0, import_node_path66.dirname)(path4)), "coverage.json");
69422
+ const coveragePath = (0, import_node_path64.join)((0, import_node_path64.dirname)((0, import_node_path64.dirname)(path4)), "coverage.json");
69767
69423
  const coverage = await readJsonFile(coveragePath, coverageSchema);
69768
69424
  const current = coverage.kind === "ok" ? coverage.value : null;
69769
69425
  const next = nextCoverage(current, ordinal, nextOrdinal);
@@ -69778,13 +69434,13 @@ function nextCoverage(current, ordinal, nextOrdinal) {
69778
69434
  return null;
69779
69435
  }
69780
69436
  async function readConversationIndexCoverage(runsDir, conversationId) {
69781
- const path4 = (0, import_node_path66.join)((0, import_node_path66.dirname)(indexDirectory(runsDir, conversationId)), "coverage.json");
69437
+ const path4 = (0, import_node_path64.join)((0, import_node_path64.dirname)(indexDirectory(runsDir, conversationId)), "coverage.json");
69782
69438
  const result = await readJsonFile(path4, coverageSchema);
69783
69439
  return result.kind === "ok" ? result.value : null;
69784
69440
  }
69785
69441
  async function readConversationRunIndex(runsDir, conversationId, before, limit) {
69786
69442
  const directory = indexDirectory(runsDir, conversationId);
69787
- const names = await (0, import_promises67.readdir)(directory).catch((error61) => {
69443
+ const names = await (0, import_promises65.readdir)(directory).catch((error61) => {
69788
69444
  if (error61.code === "ENOENT") return [];
69789
69445
  throw error61;
69790
69446
  });
@@ -69793,7 +69449,7 @@ async function readConversationRunIndex(runsDir, conversationId, before, limit)
69793
69449
  ).sort((left, right) => right - left);
69794
69450
  const selected = [];
69795
69451
  for (const shard of shards) {
69796
- const text3 = await (0, import_promises67.readFile)((0, import_node_path66.join)(directory, `${shard}.jsonl`), "utf8");
69452
+ const text3 = await (0, import_promises65.readFile)((0, import_node_path64.join)(directory, `${shard}.jsonl`), "utf8");
69797
69453
  const records = text3.split("\n").flatMap((line) => {
69798
69454
  if (!line) return [];
69799
69455
  const parsed = indexRecordSchema.parse(JSON.parse(line));
@@ -69818,7 +69474,7 @@ async function readIndexableRun(runsDir, name) {
69818
69474
  return { conversationId: meta3.conversationId, ordinal, assistantOrdinal, runId: runId.data };
69819
69475
  }
69820
69476
  async function readIndexableRuns(runsDir) {
69821
- const names = await (0, import_promises67.readdir)(runsDir).catch(() => []);
69477
+ const names = await (0, import_promises65.readdir)(runsDir).catch(() => []);
69822
69478
  const byConversation = /* @__PURE__ */ new Map();
69823
69479
  let next = 0;
69824
69480
  const worker = async () => {
@@ -69848,21 +69504,21 @@ async function writeConversationIndex(directory, runs) {
69848
69504
  else lines2.push(line);
69849
69505
  coverage = nextCoverage(coverage, run2.ordinal, nextOrdinal) ?? coverage;
69850
69506
  }
69851
- await (0, import_promises67.mkdir)((0, import_node_path66.join)(directory, "turn-index"), { recursive: true, mode: 448 });
69507
+ await (0, import_promises65.mkdir)((0, import_node_path64.join)(directory, "turn-index"), { recursive: true, mode: 448 });
69852
69508
  for (const [shard, lines2] of shards) {
69853
- await (0, import_promises67.writeFile)((0, import_node_path66.join)(directory, "turn-index", `${shard}.jsonl`), `${lines2.join("\n")}
69509
+ await (0, import_promises65.writeFile)((0, import_node_path64.join)(directory, "turn-index", `${shard}.jsonl`), `${lines2.join("\n")}
69854
69510
  `, {
69855
69511
  mode: 384
69856
69512
  });
69857
69513
  }
69858
- await (0, import_promises67.writeFile)((0, import_node_path66.join)(directory, "coverage.json"), `${JSON.stringify(coverage)}
69514
+ await (0, import_promises65.writeFile)((0, import_node_path64.join)(directory, "coverage.json"), `${JSON.stringify(coverage)}
69859
69515
  `, {
69860
69516
  mode: 384
69861
69517
  });
69862
69518
  }
69863
69519
  async function rebuildConversationIndexes(runsDir) {
69864
69520
  const root = conversationsDirectory(runsDir);
69865
- const exists6 = await (0, import_promises67.stat)(root).then(
69521
+ const exists6 = await (0, import_promises65.stat)(root).then(
69866
69522
  () => true,
69867
69523
  (error61) => {
69868
69524
  if (errnoCode(error61) === "ENOENT") return false;
@@ -69871,18 +69527,18 @@ async function rebuildConversationIndexes(runsDir) {
69871
69527
  );
69872
69528
  if (exists6) return 0;
69873
69529
  const building = `${root}.rebuilding`;
69874
- await (0, import_promises67.rm)(building, { recursive: true, force: true });
69875
- await (0, import_promises67.mkdir)(building, { recursive: true, mode: 448 });
69530
+ await (0, import_promises65.rm)(building, { recursive: true, force: true });
69531
+ await (0, import_promises65.mkdir)(building, { recursive: true, mode: 448 });
69876
69532
  const byConversation = await readIndexableRuns(runsDir);
69877
69533
  for (const [conversationId, runs] of byConversation) {
69878
- await writeConversationIndex((0, import_node_path66.join)(building, conversationId), runs);
69534
+ await writeConversationIndex((0, import_node_path64.join)(building, conversationId), runs);
69879
69535
  }
69880
- await (0, import_promises67.rename)(building, root);
69536
+ await (0, import_promises65.rename)(building, root);
69881
69537
  return byConversation.size;
69882
69538
  }
69883
69539
 
69884
69540
  // src/run-log/reader.ts
69885
- var import_promises68 = require("fs/promises");
69541
+ var import_promises66 = require("fs/promises");
69886
69542
  init_runtime_v2();
69887
69543
 
69888
69544
  // src/run-log/tail.ts
@@ -69905,7 +69561,7 @@ function firstRecordLength(bytes) {
69905
69561
  return bytes.indexOf(RUN_LOG_RECORD_SEPARATOR) + 1;
69906
69562
  }
69907
69563
  async function openRunLogReader(path4) {
69908
- const handle = await (0, import_promises68.open)(path4, "r");
69564
+ const handle = await (0, import_promises66.open)(path4, "r");
69909
69565
  const readAt = async (position, length) => {
69910
69566
  const buffer = Buffer.alloc(length);
69911
69567
  const { bytesRead } = await handle.read(buffer, 0, length, position);
@@ -69939,7 +69595,7 @@ async function openRunLogReader(path4) {
69939
69595
  };
69940
69596
  }
69941
69597
  async function readLastRecord(path4) {
69942
- const handle = await (0, import_promises68.open)(path4, "r").catch(() => null);
69598
+ const handle = await (0, import_promises66.open)(path4, "r").catch(() => null);
69943
69599
  if (handle === null) return null;
69944
69600
  try {
69945
69601
  const { size } = await handle.stat();
@@ -69973,7 +69629,7 @@ var decoder = new TextDecoder();
69973
69629
 
69974
69630
  // src/run-log/writer.ts
69975
69631
  var import_node_fs21 = require("fs");
69976
- var import_node_path67 = require("path");
69632
+ var import_node_path65 = require("path");
69977
69633
  init_runtime_v2();
69978
69634
  function lastSeq(fd, size) {
69979
69635
  for (const length of tailWindows(size)) {
@@ -69989,7 +69645,7 @@ function lastSeq(fd, size) {
69989
69645
  throw new RuntimeFault("record_too_large", "Run log tail record is larger than any record");
69990
69646
  }
69991
69647
  function openRunLog(path4, clock) {
69992
- (0, import_node_fs21.mkdirSync)((0, import_node_path67.dirname)(path4), { recursive: true, mode: 448 });
69648
+ (0, import_node_fs21.mkdirSync)((0, import_node_path65.dirname)(path4), { recursive: true, mode: 448 });
69993
69649
  const fd = (0, import_node_fs21.openSync)(path4, "a+", 384);
69994
69650
  let size = (0, import_node_fs21.fstatSync)(fd).size;
69995
69651
  let seq = lastSeq(fd, size);
@@ -70026,107 +69682,6 @@ function openRunLog(path4, clock) {
70026
69682
  };
70027
69683
  }
70028
69684
 
70029
- // src/holder/lease-gate.ts
70030
- init_acp();
70031
- var READ_ONLY_TOOL_KINDS = /* @__PURE__ */ new Set([
70032
- "read",
70033
- "search",
70034
- "think",
70035
- "fetch",
70036
- "switch_mode"
70037
- ]);
70038
- function gateWorkspaceWrites(sink, lease) {
70039
- const kinds = /* @__PURE__ */ new Map();
70040
- const state = { tail: Promise.resolve(), pending: 0, gate: null, blocked: 0 };
70041
- const writesFiles = (update) => {
70042
- if (!isUpdate(update, "tool_call_update")) return false;
70043
- if (typeof update.kind === "string") kinds.set(update.toolCallId, update.kind);
70044
- const kind = kinds.get(update.toolCallId);
70045
- return kind === void 0 || !READ_ONLY_TOOL_KINDS.has(kind);
70046
- };
70047
- const deliver = (event) => {
70048
- if (lease.failure() === null) {
70049
- sink.onEvent(event);
70050
- return;
70051
- }
70052
- if (event.update.sessionUpdate === "tool_call_update") state.blocked += 1;
70053
- };
70054
- const enqueue = (event, gate) => {
70055
- state.pending += 1;
70056
- state.tail = state.tail.then(async () => {
70057
- if (gate === null || await gate) deliver(event);
70058
- else if (event.update.sessionUpdate === "tool_call_update") state.blocked += 1;
70059
- }).finally(() => {
70060
- state.pending -= 1;
70061
- if (state.pending === 0) state.gate = null;
70062
- });
70063
- };
70064
- return {
70065
- onSpawned: (pid) => sink.onSpawned(pid),
70066
- onEvent: (event) => {
70067
- const write = writesFiles(event.update);
70068
- if (!write && state.pending === 0) {
70069
- deliver(event);
70070
- return;
70071
- }
70072
- if (write) state.gate ??= lease.verify();
70073
- enqueue(event, state.gate);
70074
- },
70075
- drain: async () => {
70076
- while (state.pending > 0) await state.tail;
70077
- },
70078
- blocked: () => state.blocked
70079
- };
70080
- }
70081
-
70082
- // src/holder/lease-turn.ts
70083
- function leaseNotice(failure6, blocked) {
70084
- const withheld = blocked === 0 ? "" : ` ${blocked} tool ${blocked === 1 ? "update was" : "updates were"} withheld.`;
70085
- return {
70086
- sessionUpdate: "notice",
70087
- severity: "error",
70088
- title: "The workspace changed while the agent was working",
70089
- description: `${failure6.message}${withheld}`,
70090
- _meta: {
70091
- "alan.dev/noticeKind": "workspace_lease_lost",
70092
- ...failure6.problemCode === null ? {} : { "alan.dev/problem": { domain: "application", code: failure6.problemCode } }
70093
- }
70094
- };
70095
- }
70096
- async function runLeased(spec, paths, turn, sink, signal, run2) {
70097
- var _stack = [];
70098
- try {
70099
- const capture = await captureWorkspaceLease(spec.runId, paths, turn.lease, signal);
70100
- if (capture.kind === "failed") {
70101
- turn.log.warn("holder.workspace_lease_refused", {
70102
- runId: spec.runId,
70103
- code: capture.failure.code
70104
- });
70105
- return { outcome: "failed", message: capture.failure.message };
70106
- }
70107
- const lease = __using(_stack, capture.lease, true);
70108
- const _answers = __using(_stack, turn.answerGate?.guard(lease));
70109
- turn.log.info("holder.workspace_leased", { runId: spec.runId, checkouts: lease.checkouts });
70110
- const gated = gateWorkspaceWrites(sink, lease);
70111
- const result = await run2(gated, AbortSignal.any([signal, lease.lost]));
70112
- await gated.drain();
70113
- const failure6 = lease.failure();
70114
- if (failure6 === null) return result;
70115
- sink.onEvent({ seq: 0, at: turn.clock.now(), update: leaseNotice(failure6, gated.blocked()) });
70116
- await turn.driver.suspend?.().catch((error61) => turn.log.warn("holder.driver_suspend_failed", { error: error61 }));
70117
- return {
70118
- outcome: "failed",
70119
- message: failure6.message,
70120
- ...result.providerSessionId === void 0 ? {} : { providerSessionId: result.providerSessionId }
70121
- };
70122
- } catch (_) {
70123
- var _error = _, _hasError = true;
70124
- } finally {
70125
- var _promise2 = __callDispose(_stack, _error, _hasError);
70126
- _promise2 && await _promise2;
70127
- }
70128
- }
70129
-
70130
69685
  // src/holder/record-fit.ts
70131
69686
  init_acp2();
70132
69687
  init_runtime_v2();
@@ -70164,11 +69719,11 @@ function fitForRunLog(update) {
70164
69719
  }
70165
69720
 
70166
69721
  // src/holder/turn.ts
70167
- async function runWithInputs({ spec, leaseTargets, skills }, context, sink, signal) {
69722
+ async function runWithInputs({ spec, skills }, context, sink, signal) {
70168
69723
  var _stack = [];
70169
69724
  try {
70170
69725
  const workspace = context.workspace;
70171
- const sessionContext = (workspace?.refreshFirstCheckout?.(spec, leaseTargets, signal) ?? Promise.resolve([])).catch((error61) => {
69726
+ const sessionContext = (workspace?.refreshFirstCheckout?.(spec, signal) ?? Promise.resolve([])).catch((error61) => {
70172
69727
  context.log.warn("workspace.refresh_failed", { runId: spec.runId, error: error61 });
70173
69728
  return [];
70174
69729
  }).then((problems) => workspace?.prepareAgentContext?.(spec, problems)).catch((error61) => {
@@ -70187,35 +69742,24 @@ async function runWithInputs({ spec, leaseTargets, skills }, context, sink, sign
70187
69742
  }
70188
69743
  const agentContext = await sessionContext;
70189
69744
  const prepared = __using(_stack, inputs, true);
70190
- const run2 = async (turnSink, turnSignal) => {
70191
- const result = await context.driver.runTurn(
70192
- spec,
70193
- turnSink,
70194
- turnSignal,
70195
- agentContext === void 0 ? prepared : {
70196
- ...prepared,
70197
- agentContext: {
70198
- full: agentContext.full,
70199
- ...agentContext.update ? { update: agentContext.update } : {}
70200
- }
70201
- }
70202
- );
70203
- if (agentContext !== void 0 && result.outcome !== "rejected") {
70204
- await agentContext.save().catch((error61) => {
70205
- context.log.warn("holder.agent_context_save_failed", { runId: spec.runId, error: error61 });
70206
- });
70207
- }
70208
- return result;
70209
- };
70210
- if (workspace === void 0) return await run2(sink, signal);
70211
- return await runLeased(
69745
+ const result = await context.driver.runTurn(
70212
69746
  spec,
70213
- leaseTargets,
70214
- { ...context, lease: workspace.lease },
70215
69747
  sink,
70216
69748
  signal,
70217
- run2
69749
+ agentContext === void 0 ? prepared : {
69750
+ ...prepared,
69751
+ agentContext: {
69752
+ full: agentContext.full,
69753
+ ...agentContext.update ? { update: agentContext.update } : {}
69754
+ }
69755
+ }
70218
69756
  );
69757
+ if (agentContext !== void 0 && result.outcome !== "rejected") {
69758
+ await agentContext.save().catch((error61) => {
69759
+ context.log.warn("holder.agent_context_save_failed", { runId: spec.runId, error: error61 });
69760
+ });
69761
+ }
69762
+ return result;
70219
69763
  } catch (_) {
70220
69764
  var _error = _, _hasError = true;
70221
69765
  } finally {
@@ -70223,7 +69767,7 @@ async function runWithInputs({ spec, leaseTargets, skills }, context, sink, sign
70223
69767
  _promise2 && await _promise2;
70224
69768
  }
70225
69769
  }
70226
- async function admitAndRun(spec, context, append, sink, signal) {
69770
+ async function admitAndRun(spec, context, sink, signal) {
70227
69771
  if (context.workspace === void 0) {
70228
69772
  if (spec.skillInvocations?.length) {
70229
69773
  return {
@@ -70232,14 +69776,13 @@ async function admitAndRun(spec, context, append, sink, signal) {
70232
69776
  message: "Selected skills need this computer's skill sync, which this holder does not have."
70233
69777
  };
70234
69778
  }
70235
- return runWithInputs({ spec, leaseTargets: [], skills: [] }, context, sink, signal);
69779
+ return runWithInputs({ spec, skills: [] }, context, sink, signal);
70236
69780
  }
70237
- const admission = await admitRun(spec, context.workspace.admission, signal);
69781
+ const admission = await admitRun(spec, context.workspace.admission);
70238
69782
  if (admission.kind === "rejected") {
70239
69783
  context.log.info("holder.run_rejected", { runId: spec.runId, rejection: admission.rejection });
70240
69784
  return { outcome: "rejected", rejection: admission.rejection, message: admission.message };
70241
69785
  }
70242
- if (admission.relocated !== null) append(admission.relocated);
70243
69786
  return runWithInputs(admission, context, sink, signal);
70244
69787
  }
70245
69788
  async function claimRun(spec, context) {
@@ -70286,7 +69829,6 @@ async function runClaimedTurn(spec, claimed, context, signal) {
70286
69829
  result = await admitAndRun(
70287
69830
  spec,
70288
69831
  context,
70289
- append,
70290
69832
  {
70291
69833
  onSpawned: (pid) => append(runStarted({ pid })),
70292
69834
  // Base64 media in provider payloads and tool output never reaches the log (main 13590db369).
@@ -70349,12 +69891,11 @@ async function runHolder({
70349
69891
  try {
70350
69892
  const identity = await readProcessIdentity(process.pid);
70351
69893
  if (identity === null) throw new RuntimeFault("internal", "Cannot read own process identity");
70352
- const _engines = __using(_stack, recordSpawnedEngines(engineRecordsPath((0, import_node_path68.dirname)(launch.statusPath)), clock, log));
69894
+ const _engines = __using(_stack, recordSpawnedEngines(engineRecordsPath((0, import_node_path66.dirname)(launch.statusPath)), clock, log));
70353
69895
  const holder = {
70354
69896
  state: "idle",
70355
69897
  runId: null,
70356
69898
  turn: null,
70357
- answerGate: createAnswerGate(),
70358
69899
  clients: /* @__PURE__ */ new Set()
70359
69900
  };
70360
69901
  const exit = new AbortController();
@@ -70412,8 +69953,7 @@ async function runHolder({
70412
69953
  log,
70413
69954
  onAppended: (runId, offset) => broadcast({ type: "appended", runId, offset }),
70414
69955
  ...inputs === void 0 ? {} : { inputs },
70415
- ...workspace === void 0 ? {} : { workspace },
70416
- answerGate: holder.answerGate
69956
+ ...workspace === void 0 ? {} : { workspace }
70417
69957
  };
70418
69958
  claimRun(spec, context).then(
70419
69959
  (claimed) => {
@@ -70445,7 +69985,7 @@ async function runHolder({
70445
69985
  );
70446
69986
  };
70447
69987
  const respond = (request2, client) => {
70448
- respondToTurn(holder.runId, holder.answerGate, driver, request2).then((status) => {
69988
+ respondToTurn(holder.runId, driver, request2).then((status) => {
70449
69989
  log.info("holder.responded", { runId: request2.runId, status });
70450
69990
  writeMessage(client, { type: "responded", id: request2.id, status });
70451
69991
  }).catch((error61) => {
@@ -70491,12 +70031,12 @@ async function runHolder({
70491
70031
  return;
70492
70032
  case "status":
70493
70033
  void facts.snapshot().then(
70494
- (snapshot2) => writeMessage(client, {
70034
+ (snapshot) => writeMessage(client, {
70495
70035
  type: "status",
70496
70036
  id: request2.id,
70497
70037
  state: holder.state,
70498
70038
  runId: holder.runId,
70499
- facts: snapshot2
70039
+ facts: snapshot
70500
70040
  })
70501
70041
  );
70502
70042
  return;
@@ -70545,16 +70085,16 @@ async function runHolder({
70545
70085
  client.on("error", () => holder.clients.delete(client));
70546
70086
  });
70547
70087
  removeStaleEndpoint(launch.endpoint);
70548
- await new Promise((resolve14, reject) => {
70088
+ await new Promise((resolve13, reject) => {
70549
70089
  server.once("error", reject);
70550
- server.listen(launch.endpoint, () => resolve14());
70090
+ server.listen(launch.endpoint, () => resolve13());
70551
70091
  });
70552
70092
  await writeStatus();
70553
70093
  log.info("holder.ready", { conversationId: launch.conversationId, pid: identity.pid });
70554
- await new Promise((resolve14) => exit.signal.addEventListener("abort", () => resolve14()));
70094
+ await new Promise((resolve13) => exit.signal.addEventListener("abort", () => resolve13()));
70555
70095
  await driver.suspend?.().catch((error61) => log.warn("holder.driver_suspend_failed", { error: error61 }));
70556
70096
  for (const client of holder.clients) client.end();
70557
- await new Promise((resolve14) => server.close(() => resolve14()));
70097
+ await new Promise((resolve13) => server.close(() => resolve13()));
70558
70098
  (0, import_node_fs22.rmSync)(launch.statusPath, { force: true });
70559
70099
  log.info("holder.suspended", { conversationId: launch.conversationId });
70560
70100
  } catch (_) {
@@ -70643,7 +70183,7 @@ var DEFAULT_MAX_ACTIVE_RUNS = 32;
70643
70183
  var HOLDER_BUSY = "busy";
70644
70184
  async function listIds(dir, schema) {
70645
70185
  const ids = [];
70646
- for (const name of await (0, import_promises69.readdir)(dir).catch(() => [])) {
70186
+ for (const name of await (0, import_promises67.readdir)(dir).catch(() => [])) {
70647
70187
  const parsed = schema.safeParse(name);
70648
70188
  if (parsed.success) ids.push(parsed.data);
70649
70189
  }
@@ -70657,14 +70197,14 @@ function holderIdentity(status) {
70657
70197
  return command === void 0 ? { pid, startedAt } : { pid, startedAt, command };
70658
70198
  }
70659
70199
  function sessionFiles(paths, conversationId) {
70660
- const dir = (0, import_node_path69.join)(paths.sessions, conversationId);
70661
- return { dir, launch: (0, import_node_path69.join)(dir, "launch.json"), status: (0, import_node_path69.join)(dir, "holder.json") };
70200
+ const dir = (0, import_node_path67.join)(paths.sessions, conversationId);
70201
+ return { dir, launch: (0, import_node_path67.join)(dir, "launch.json"), status: (0, import_node_path67.join)(dir, "holder.json") };
70662
70202
  }
70663
70203
  async function removeHolderFiles(files) {
70664
70204
  for (const path4 of [files.launch, files.status, engineRecordsPath(files.dir)]) {
70665
- await (0, import_promises69.rm)(path4, { force: true });
70205
+ await (0, import_promises67.rm)(path4, { force: true });
70666
70206
  }
70667
- await (0, import_promises69.rmdir)(files.dir).catch((error61) => {
70207
+ await (0, import_promises67.rmdir)(files.dir).catch((error61) => {
70668
70208
  if (!["ENOENT", "ENOTEMPTY", "EEXIST"].includes(errnoCode(error61) ?? "")) throw error61;
70669
70209
  });
70670
70210
  }
@@ -70854,7 +70394,7 @@ async function openSessions(deps) {
70854
70394
  const meta3 = await readRunMeta(dir.meta);
70855
70395
  const last = await readLastRecord(dir.log);
70856
70396
  if (meta3 === null || last === null) return null;
70857
- const logged = await (0, import_promises69.stat)(dir.log).catch((error61) => {
70397
+ const logged = await (0, import_promises67.stat)(dir.log).catch((error61) => {
70858
70398
  if (errnoCode(error61) === "ENOENT") return null;
70859
70399
  throw error61;
70860
70400
  });
@@ -71166,7 +70706,7 @@ function loadRuntimeConfig(env = process.env, totalMemoryBytes = (0, import_node
71166
70706
  providerProbes: ALAN_RUNTIME_PROVIDER_PROBES === "on",
71167
70707
  providerToolchain: ALAN_RUNTIME_PROVIDER_NODE !== void 0 && ALAN_RUNTIME_PROVIDER_NPM_CLI !== void 0 ? { node: ALAN_RUNTIME_PROVIDER_NODE, npmCli: ALAN_RUNTIME_PROVIDER_NPM_CLI } : null,
71168
70708
  home,
71169
- configHome: XDG_CONFIG_HOME ?? (0, import_node_path70.join)(home, ".config"),
70709
+ configHome: XDG_CONFIG_HOME ?? (0, import_node_path68.join)(home, ".config"),
71170
70710
  codexHome: resolveCodexHome(CODEX_HOME, home),
71171
70711
  ...githubProxyConfig({ ALAN_RUNTIME_GITHUB_PROXY, XDG_CONFIG_HOME, GH_CONFIG_DIR }, home),
71172
70712
  gitGatewayUrl: ALAN_RUNTIME_GIT_GATEWAY_URL ?? null,
@@ -71176,13 +70716,13 @@ function loadRuntimeConfig(env = process.env, totalMemoryBytes = (0, import_node
71176
70716
  };
71177
70717
  }
71178
70718
  function resolveCodexHome(configuredHome, home) {
71179
- return configuredHome ?? (0, import_node_path70.join)(home, ".codex");
70719
+ return configuredHome ?? (0, import_node_path68.join)(home, ".codex");
71180
70720
  }
71181
70721
  function githubProxyConfig(env, home) {
71182
- const configHome = env.XDG_CONFIG_HOME ?? (0, import_node_path70.join)(home, ".config");
70722
+ const configHome = env.XDG_CONFIG_HOME ?? (0, import_node_path68.join)(home, ".config");
71183
70723
  return {
71184
70724
  githubProxy: env.ALAN_RUNTIME_GITHUB_PROXY === "on",
71185
- ghConfigDir: env.GH_CONFIG_DIR ?? (0, import_node_path70.join)(configHome, "gh")
70725
+ ghConfigDir: env.GH_CONFIG_DIR ?? (0, import_node_path68.join)(configHome, "gh")
71186
70726
  };
71187
70727
  }
71188
70728
  function serviceEnvironment2(env, profile) {
@@ -71240,9 +70780,9 @@ function takeEnrollmentCodeFromEnv(env = process.env) {
71240
70780
  }
71241
70781
 
71242
70782
  // src/cli/context.ts
71243
- var import_promises70 = require("fs/promises");
70783
+ var import_promises68 = require("fs/promises");
71244
70784
  var import_node_os12 = require("os");
71245
- var import_node_path71 = require("path");
70785
+ var import_node_path69 = require("path");
71246
70786
  var DESKTOP_BUNDLE_IDS = {
71247
70787
  production: ["com.alan-ai.desktop"],
71248
70788
  staging: ["com.alan-ai.desktop.staging"],
@@ -71282,7 +70822,7 @@ function serviceSpec({ config: config2, paths, self }) {
71282
70822
  profile: config2.profile,
71283
70823
  program: serviceCommand(config2.host, self, launcher),
71284
70824
  environment: config2.serviceEnvironment,
71285
- logPath: (0, import_node_path71.join)(paths.logs, "service.log"),
70825
+ logPath: (0, import_node_path69.join)(paths.logs, "service.log"),
71286
70826
  associatedBundleIds: DESKTOP_BUNDLE_IDS[config2.profile]
71287
70827
  };
71288
70828
  }
@@ -71290,7 +70830,7 @@ async function installedServiceSpec(ctx) {
71290
70830
  const spec = serviceSpec(ctx);
71291
70831
  if (ctx.config.host === "app") return spec;
71292
70832
  const layout = installLayout(ctx.config.installDir, ctx.config.profile);
71293
- const installed = await (0, import_promises70.access)(layout.launcher).then(
70833
+ const installed = await (0, import_promises68.access)(layout.launcher).then(
71294
70834
  () => true,
71295
70835
  () => false
71296
70836
  );
@@ -71418,7 +70958,7 @@ var manifestRevisionSchema = external_exports.object({ revision: external_export
71418
70958
  async function manifestRevision(path4) {
71419
70959
  let raw;
71420
70960
  try {
71421
- raw = JSON.parse(await (0, import_promises71.readFile)(path4, "utf8"));
70961
+ raw = JSON.parse(await (0, import_promises69.readFile)(path4, "utf8"));
71422
70962
  } catch (error61) {
71423
70963
  throw new RuntimeFault("invalid_file", `Cannot read the skill manifest at ${path4}`, {
71424
70964
  cause: error61
@@ -71472,8 +71012,8 @@ async function runSkills(argv) {
71472
71012
  }
71473
71013
 
71474
71014
  // src/cli/commands/doctor.ts
71475
- var import_promises74 = require("fs/promises");
71476
- var import_node_path75 = require("path");
71015
+ var import_promises72 = require("fs/promises");
71016
+ var import_node_path73 = require("path");
71477
71017
  init_runtime_v2();
71478
71018
 
71479
71019
  // src/identity/credential.ts
@@ -71482,7 +71022,7 @@ init_zod();
71482
71022
 
71483
71023
  // src/identity/installation.ts
71484
71024
  var import_node_crypto33 = require("crypto");
71485
- var import_node_path72 = require("path");
71025
+ var import_node_path70 = require("path");
71486
71026
  init_runtime_v2();
71487
71027
  init_zod();
71488
71028
  var installationFileSchema = external_exports.object({
@@ -71490,7 +71030,7 @@ var installationFileSchema = external_exports.object({
71490
71030
  machineId: machineIdSchema.optional()
71491
71031
  });
71492
71032
  function installationPath(paths) {
71493
- return (0, import_node_path72.join)(paths.stateDir, "installation.json");
71033
+ return (0, import_node_path70.join)(paths.stateDir, "installation.json");
71494
71034
  }
71495
71035
  async function readInstallation(paths) {
71496
71036
  const result = await readJsonFile(installationPath(paths), installationFileSchema);
@@ -71681,7 +71221,7 @@ async function authorizeDevice(input2) {
71681
71221
  }
71682
71222
 
71683
71223
  // src/identity/enroll.ts
71684
- var import_promises72 = require("fs/promises");
71224
+ var import_promises70 = require("fs/promises");
71685
71225
  init_runtime_v2();
71686
71226
  async function enrollMachine(input2) {
71687
71227
  const machineId = input2.machineId ?? (await readMachineFile(input2.paths))?.machineId ?? (await readInstallation(input2.paths))?.machineId;
@@ -71764,13 +71304,13 @@ async function enrollFromGrantFile(input2) {
71764
71304
  clock: input2.clock,
71765
71305
  access: input2.access
71766
71306
  });
71767
- await (0, import_promises72.rm)(input2.grantPath, { force: true });
71307
+ await (0, import_promises70.rm)(input2.grantPath, { force: true });
71768
71308
  return machine;
71769
71309
  }
71770
71310
 
71771
71311
  // src/identity/migrate-v1.ts
71772
- var import_promises73 = require("fs/promises");
71773
- var import_node_path73 = require("path");
71312
+ var import_promises71 = require("fs/promises");
71313
+ var import_node_path71 = require("path");
71774
71314
  init_runtime_v2();
71775
71315
  init_zod();
71776
71316
  var EXIT_POLL_MS = 200;
@@ -71791,11 +71331,11 @@ var ownerLeaseSchema = external_exports.looseObject({ pid: external_exports.numb
71791
71331
  function legacyConfigPath(home, profile) {
71792
71332
  switch (profile) {
71793
71333
  case "production":
71794
- return (0, import_node_path73.join)(home, ".alan", "agent", "config.json");
71334
+ return (0, import_node_path71.join)(home, ".alan", "agent", "config.json");
71795
71335
  case "staging":
71796
- return (0, import_node_path73.join)(home, ".alan-staging", "agent", "config.json");
71336
+ return (0, import_node_path71.join)(home, ".alan-staging", "agent", "config.json");
71797
71337
  default:
71798
- return (0, import_node_path73.join)(home, ".alan-dev", "agent", "config.json");
71338
+ return (0, import_node_path71.join)(home, ".alan-dev", "agent", "config.json");
71799
71339
  }
71800
71340
  }
71801
71341
  async function findLegacyInstall(home, profile) {
@@ -71820,8 +71360,8 @@ async function scrubLegacyInstall(install2) {
71820
71360
  const scrubbed = { ...install2.config, migratedToRuntimeV2: true };
71821
71361
  for (const key of SCRUBBED_KEYS) delete scrubbed[key];
71822
71362
  await writeJsonFileAtomic(`${install2.configPath}.migrated-v1`, scrubbed);
71823
- await (0, import_promises73.rm)(install2.configPath, { force: true });
71824
- await (0, import_promises73.rm)(install2.ownerLeasePath, { force: true });
71363
+ await (0, import_promises71.rm)(install2.configPath, { force: true });
71364
+ await (0, import_promises71.rm)(install2.ownerLeasePath, { force: true });
71825
71365
  }
71826
71366
  async function exchangeCredential(deps) {
71827
71367
  const { config: config2 } = deps.install;
@@ -71930,7 +71470,7 @@ async function loadIdentity(paths, options = {}) {
71930
71470
  }
71931
71471
 
71932
71472
  // src/cli/commands/status.ts
71933
- var import_node_path74 = require("path");
71473
+ var import_node_path72 = require("path");
71934
71474
  async function serviceStatus(ctx) {
71935
71475
  try {
71936
71476
  return await createServiceManager(ctx.host, ctx.config.profile).status();
@@ -71957,7 +71497,7 @@ async function runtimeState(ctx) {
71957
71497
  const running = await readRunningRuntime(ctx.paths.lock);
71958
71498
  if (running === null) return { state: "offline", pid: null, localApi: null };
71959
71499
  const discovery = await readJsonFile(
71960
- (0, import_node_path74.join)(ctx.paths.stateDir, LOCAL_API_DISCOVERY_FILE),
71500
+ (0, import_node_path72.join)(ctx.paths.stateDir, LOCAL_API_DISCOVERY_FILE),
71961
71501
  localApiDiscoverySchema
71962
71502
  );
71963
71503
  const localApi = discovery.kind === "ok" && discovery.value.pid === running.pid ? {
@@ -72002,7 +71542,7 @@ async function runStatus(argv, ctx = cliContext()) {
72002
71542
  }
72003
71543
 
72004
71544
  // src/cli/commands/doctor.ts
72005
- var PROBE_TIMEOUT_MS3 = 1e4;
71545
+ var PROBE_TIMEOUT_MS2 = 1e4;
72006
71546
  var LOCAL_TIMEOUT_MS = 3e3;
72007
71547
  var DISK_WARN_BYTES = 1024 ** 3;
72008
71548
  var DISK_FAIL_BYTES = 100 * 1024 ** 2;
@@ -72094,7 +71634,7 @@ async function credentialCheck(ctx) {
72094
71634
  async function serverCheck(facts) {
72095
71635
  const api = createApiClient({ apiUrl: facts.apiUrl, accessToken: () => facts.accessToken });
72096
71636
  try {
72097
- const desired = await api.fetchDesired(AbortSignal.timeout(PROBE_TIMEOUT_MS3));
71637
+ const desired = await api.fetchDesired(AbortSignal.timeout(PROBE_TIMEOUT_MS2));
72098
71638
  return check2("server", "ok", `${facts.apiUrl} accepts this machine's credential`, {
72099
71639
  machineId: facts.machineId,
72100
71640
  desiredRuns: desired.runs.length
@@ -72120,7 +71660,7 @@ function isStale(machine, now) {
72120
71660
  async function machinesCheck(facts) {
72121
71661
  const api = createApiClient({ apiUrl: facts.apiUrl, accessToken: () => facts.accessToken });
72122
71662
  try {
72123
- const machines = await api.listSiblings(AbortSignal.timeout(PROBE_TIMEOUT_MS3));
71663
+ const machines = await api.listSiblings(AbortSignal.timeout(PROBE_TIMEOUT_MS2));
72124
71664
  if (machines === null) {
72125
71665
  return check2("machines", "skipped", `${facts.apiUrl} does not list machines`);
72126
71666
  }
@@ -72150,7 +71690,7 @@ async function releaseCheck(ctx, facts) {
72150
71690
  const apiUrl = facts?.apiUrl ?? ctx.config.apiUrl;
72151
71691
  const api = createApiClient({ apiUrl, accessToken: () => facts?.accessToken ?? "" });
72152
71692
  try {
72153
- const release2 = await api.currentRelease(AbortSignal.timeout(PROBE_TIMEOUT_MS3));
71693
+ const release2 = await api.currentRelease(AbortSignal.timeout(PROBE_TIMEOUT_MS2));
72154
71694
  const layout = installLayout(ctx.config.installDir, ctx.config.profile);
72155
71695
  const plan2 = planUpdate({
72156
71696
  current: package_default.version,
@@ -72178,7 +71718,7 @@ async function runtimeCheck(ctx, status) {
72178
71718
  return check2("runtime", "warn", "No runtime is running for this profile");
72179
71719
  }
72180
71720
  const client = createRuntimeClient({
72181
- discoveryPath: (0, import_node_path75.join)(ctx.paths.stateDir, LOCAL_API_DISCOVERY_FILE)
71721
+ discoveryPath: (0, import_node_path73.join)(ctx.paths.stateDir, LOCAL_API_DISCOVERY_FILE)
72182
71722
  });
72183
71723
  try {
72184
71724
  const live = await client.status(AbortSignal.timeout(LOCAL_TIMEOUT_MS));
@@ -72205,7 +71745,7 @@ async function runtimeCheck(ctx, status) {
72205
71745
  }
72206
71746
  }
72207
71747
  async function probeHolder(dir, conversationId) {
72208
- const launch = await readJsonFile((0, import_node_path75.join)(dir, "launch.json"), holderLaunchSchema);
71748
+ const launch = await readJsonFile((0, import_node_path73.join)(dir, "launch.json"), holderLaunchSchema);
72209
71749
  if (launch.kind !== "ok") return null;
72210
71750
  try {
72211
71751
  const reply2 = await withTimeout(
@@ -72230,8 +71770,8 @@ async function probeHolder(dir, conversationId) {
72230
71770
  }
72231
71771
  }
72232
71772
  async function holdersCheck(ctx) {
72233
- const names = await (0, import_promises74.readdir)(ctx.paths.sessions).catch(() => []);
72234
- const holders = (await Promise.all(names.map((name) => probeHolder((0, import_node_path75.join)(ctx.paths.sessions, name), name)))).filter((facts) => facts !== null);
71773
+ const names = await (0, import_promises72.readdir)(ctx.paths.sessions).catch(() => []);
71774
+ const holders = (await Promise.all(names.map((name) => probeHolder((0, import_node_path73.join)(ctx.paths.sessions, name), name)))).filter((facts) => facts !== null);
72235
71775
  const dead = holders.filter((holder) => !holder.alive).length;
72236
71776
  return check2(
72237
71777
  "holders",
@@ -72242,10 +71782,10 @@ async function holdersCheck(ctx) {
72242
71782
  }
72243
71783
  async function freeBytesAt(path4) {
72244
71784
  try {
72245
- const stats = await (0, import_promises74.statfs)(path4);
71785
+ const stats = await (0, import_promises72.statfs)(path4);
72246
71786
  return { path: path4, freeBytes: stats.bavail * stats.bsize };
72247
71787
  } catch (error61) {
72248
- const parent = (0, import_node_path75.dirname)(path4);
71788
+ const parent = (0, import_node_path73.dirname)(path4);
72249
71789
  if (parent === path4) throw error61;
72250
71790
  return freeBytesAt(parent);
72251
71791
  }
@@ -72263,9 +71803,9 @@ async function diskCheck(ctx) {
72263
71803
  }
72264
71804
  }
72265
71805
  var resolveFromLoginShell = (own2) => resolveCliEnvironment({ env: own2, platform: process.platform });
72266
- async function cliDiscoveryCheck(resolve14) {
71806
+ async function cliDiscoveryCheck(resolve13) {
72267
71807
  const own2 = readCliEnvironment();
72268
- const env = await resolve14(own2);
71808
+ const env = await resolve13(own2);
72269
71809
  const delimiter = process.platform === "win32" ? ";" : ":";
72270
71810
  const ownDirs = new Set((own2.PATH ?? "").split(delimiter));
72271
71811
  const added = (env.PATH ?? "").split(delimiter).filter((dir) => dir.length > 0 && !ownDirs.has(dir));
@@ -72381,7 +71921,7 @@ async function runDoctor(argv, context = cliContext) {
72381
71921
  }
72382
71922
 
72383
71923
  // src/cli/commands/git-credential.ts
72384
- var import_promises75 = require("fs/promises");
71924
+ var import_promises73 = require("fs/promises");
72385
71925
  var import_node_net4 = require("net");
72386
71926
  var MAX_RESPONSE_BYTES = 64 * 1024;
72387
71927
  async function readAll(stream) {
@@ -72399,7 +71939,7 @@ function processIo() {
72399
71939
  };
72400
71940
  }
72401
71941
  function askGitCredentialSocket(endpoint, request2, signal) {
72402
- return new Promise((resolve14, reject) => {
71942
+ return new Promise((resolve13, reject) => {
72403
71943
  const socket = (0, import_node_net4.createConnection)(endpoint);
72404
71944
  let buffered = "";
72405
71945
  const fail = (error61) => {
@@ -72426,7 +71966,7 @@ function askGitCredentialSocket(endpoint, request2, signal) {
72426
71966
  signal.removeEventListener("abort", onAbort);
72427
71967
  try {
72428
71968
  const line = buffered.split("\n", 1)[0] ?? "";
72429
- resolve14(gitCredentialSocketResponseSchema.parse(JSON.parse(line)));
71969
+ resolve13(gitCredentialSocketResponseSchema.parse(JSON.parse(line)));
72430
71970
  } catch (error61) {
72431
71971
  reject(
72432
71972
  new RuntimeFault("io_failed", "the Alan runtime sent an invalid reply", { cause: error61 })
@@ -72491,7 +72031,7 @@ async function configure(argv) {
72491
72031
  }
72492
72032
  async function configureGitGateway(config2, gatewayUrl, signal) {
72493
72033
  const { launcher } = installLayout(config2.installDir, config2.profile);
72494
- const installed = await (0, import_promises75.access)(launcher).then(
72034
+ const installed = await (0, import_promises73.access)(launcher).then(
72495
72035
  () => true,
72496
72036
  () => false
72497
72037
  );
@@ -72518,7 +72058,7 @@ async function runGitCredential(argv) {
72518
72058
  }
72519
72059
 
72520
72060
  // src/cli/commands/hold.ts
72521
- var import_node_path76 = require("path");
72061
+ var import_node_path74 = require("path");
72522
72062
  init_agent2();
72523
72063
  init_runtime_v2();
72524
72064
  async function machineAccess(paths, log, conversationId, transport) {
@@ -72576,7 +72116,7 @@ async function runHold(argv) {
72576
72116
  const config2 = loadRuntimeConfig();
72577
72117
  const paths = runtimePaths(config2.stateDir);
72578
72118
  const log = __using(_stack, openFileLog(
72579
- (0, import_node_path76.join)(paths.logs, `holder-${launch.value.conversationId}.jsonl`),
72119
+ (0, import_node_path74.join)(paths.logs, `holder-${launch.value.conversationId}.jsonl`),
72580
72120
  config2.logLevel,
72581
72121
  systemClock
72582
72122
  ));
@@ -72587,7 +72127,7 @@ async function runHold(argv) {
72587
72127
  );
72588
72128
  const transport = __using(_stack, createHttpTransport());
72589
72129
  const access7 = await machineAccess(paths, log, launch.value.conversationId, transport);
72590
- const credentialPath = (0, import_node_path76.join)(paths.tmp, "mcp", `${launch.value.conversationId}.json`);
72130
+ const credentialPath = (0, import_node_path74.join)(paths.tmp, "mcp", `${launch.value.conversationId}.json`);
72591
72131
  const managedMcp = __using(_stack, access7.managedMcp === void 0 ? void 0 : createHelperMcpAccess({
72592
72132
  managedMcp: access7.managedMcp,
72593
72133
  conversationId: launch.value.conversationId,
@@ -72628,7 +72168,7 @@ async function runHold(argv) {
72628
72168
  }
72629
72169
 
72630
72170
  // src/cli/commands/hook.ts
72631
- var import_node_path77 = require("path");
72171
+ var import_node_path75 = require("path");
72632
72172
  var RUNTIME_ANSWER_MS = 2e3;
72633
72173
  var DEBUG_VARIABLE = "ALAN_HOOK_DEBUG";
72634
72174
  function flag(argv, name) {
@@ -72660,7 +72200,7 @@ async function forwardHook(argv, io) {
72660
72200
  return "transcript outside provider root";
72661
72201
  }
72662
72202
  const verdict = await io.send(
72663
- (0, import_node_path77.join)(io.stateDir, LOCAL_API_DISCOVERY_FILE),
72203
+ (0, import_node_path75.join)(io.stateDir, LOCAL_API_DISCOVERY_FILE),
72664
72204
  hookSignal,
72665
72205
  AbortSignal.timeout(RUNTIME_ANSWER_MS)
72666
72206
  );
@@ -72696,7 +72236,7 @@ async function runHook(argv, overrides = {}) {
72696
72236
  }
72697
72237
 
72698
72238
  // src/cli/commands/ingestion-hooks.ts
72699
- var import_promises76 = require("fs/promises");
72239
+ var import_promises74 = require("fs/promises");
72700
72240
  var CODEX_TRUST_NOTE = "Codex runs new hooks only after you review them: open /hooks in Codex.";
72701
72241
  function isAction(value2) {
72702
72242
  return value2 === "enable" || value2 === "disable" || value2 === "status";
@@ -72719,7 +72259,7 @@ function errorMessage2(error61) {
72719
72259
  return error61 instanceof Error ? error61.message : String(error61);
72720
72260
  }
72721
72261
  async function exists5(path4) {
72722
- return (0, import_promises76.access)(path4).then(
72262
+ return (0, import_promises74.access)(path4).then(
72723
72263
  () => true,
72724
72264
  () => false
72725
72265
  );
@@ -72822,10 +72362,10 @@ async function runIntegrationsCommand(argv) {
72822
72362
  }
72823
72363
 
72824
72364
  // src/cli/commands/legacy.ts
72825
- var import_node_path79 = require("path");
72365
+ var import_node_path77 = require("path");
72826
72366
 
72827
72367
  // src/cli/commands/setup.ts
72828
- var import_node_path78 = require("path");
72368
+ var import_node_path76 = require("path");
72829
72369
  init_zod();
72830
72370
 
72831
72371
  // src/cli/legacy.ts
@@ -72907,7 +72447,7 @@ async function grantFileCredential(argv, grantPath, ctx, deps) {
72907
72447
  return enrollFromGrantFile({
72908
72448
  paths: ctx.paths,
72909
72449
  storeKind: credentialStoreFlag(argv) ?? ctx.config.credentialStore,
72910
- grantPath: (0, import_node_path78.resolve)(grantPath),
72450
+ grantPath: (0, import_node_path76.resolve)(grantPath),
72911
72451
  clock: deps.clock,
72912
72452
  access: ctx.access
72913
72453
  });
@@ -72983,7 +72523,7 @@ async function runSetup(argv, signal) {
72983
72523
  var _stack = [];
72984
72524
  try {
72985
72525
  const ctx = cliContext();
72986
- const log = __using(_stack, openFileLog((0, import_node_path78.join)(ctx.paths.logs, "cli.jsonl"), ctx.config.logLevel, systemClock));
72526
+ const log = __using(_stack, openFileLog((0, import_node_path76.join)(ctx.paths.logs, "cli.jsonl"), ctx.config.logLevel, systemClock));
72987
72527
  const result = await setupMachine(argv, ctx, {
72988
72528
  enrollment: (apiUrl) => createEnrollmentClient({ apiUrl }),
72989
72529
  isProcessAlive,
@@ -73066,7 +72606,7 @@ async function runToken(argv, signal) {
73066
72606
  );
73067
72607
  }
73068
72608
  const ctx = cliContext();
73069
- const log = __using(_stack, openFileLog((0, import_node_path79.join)(ctx.paths.logs, "cli.jsonl"), ctx.config.logLevel, systemClock));
72609
+ const log = __using(_stack, openFileLog((0, import_node_path77.join)(ctx.paths.logs, "cli.jsonl"), ctx.config.logLevel, systemClock));
73070
72610
  const result = await rotateMachineCredential(ctx, { clock: systemClock, log, signal });
73071
72611
  process.stdout.write(`${rotationMessage(result)}
73072
72612
  `);
@@ -73078,8 +72618,8 @@ async function runToken(argv, signal) {
73078
72618
  }
73079
72619
 
73080
72620
  // src/cli/commands/logout.ts
73081
- var import_promises77 = require("fs/promises");
73082
- var import_node_path80 = require("path");
72621
+ var import_promises75 = require("fs/promises");
72622
+ var import_node_path78 = require("path");
73083
72623
  init_runtime_v2();
73084
72624
  var RUNTIME_EXIT_WAIT_MS = 35e3;
73085
72625
  var TURN_END_WAIT_MS = 3e4;
@@ -73138,9 +72678,9 @@ async function stopHolder(launch, deps, outcome2) {
73138
72678
  }
73139
72679
  async function stopHeldRuns(ctx, deps, outcome2 = "aborted") {
73140
72680
  const stopped = [];
73141
- for (const name of await (0, import_promises77.readdir)(ctx.paths.sessions).catch(() => [])) {
72681
+ for (const name of await (0, import_promises75.readdir)(ctx.paths.sessions).catch(() => [])) {
73142
72682
  const launch = await readJsonFile(
73143
- (0, import_node_path80.join)(ctx.paths.sessions, name, "launch.json"),
72683
+ (0, import_node_path78.join)(ctx.paths.sessions, name, "launch.json"),
73144
72684
  holderLaunchSchema
73145
72685
  );
73146
72686
  if (launch.kind !== "ok") continue;
@@ -73177,13 +72717,13 @@ async function forgetMachineLocally(ctx) {
73177
72717
  const machine = await readMachineFile(ctx.paths);
73178
72718
  if (machine === null) return;
73179
72719
  await credentialStoreFor(ctx.paths, machine.credentialStore, ctx.access).clear();
73180
- await (0, import_promises77.rm)(ctx.paths.machine, { force: true });
72720
+ await (0, import_promises75.rm)(ctx.paths.machine, { force: true });
73181
72721
  }
73182
72722
  async function runLogout(argv, signal) {
73183
72723
  var _stack = [];
73184
72724
  try {
73185
72725
  const ctx = cliContext();
73186
- const log = __using(_stack, openFileLog((0, import_node_path80.join)(ctx.paths.logs, "cli.jsonl"), ctx.config.logLevel, systemClock));
72726
+ const log = __using(_stack, openFileLog((0, import_node_path78.join)(ctx.paths.logs, "cli.jsonl"), ctx.config.logLevel, systemClock));
73187
72727
  const result = await logoutMachine(argv, ctx, {
73188
72728
  api: (apiUrl, accessToken) => createApiClient({ apiUrl, accessToken }),
73189
72729
  stopHeldRuns,
@@ -73201,7 +72741,7 @@ async function runLogout(argv, signal) {
73201
72741
 
73202
72742
  // src/cli/commands/run.ts
73203
72743
  var import_node_fs24 = require("fs");
73204
- var import_node_path84 = require("path");
72744
+ var import_node_path82 = require("path");
73205
72745
 
73206
72746
  // src/local-api/app-attachments.ts
73207
72747
  function createAppAttachments(clock) {
@@ -73241,7 +72781,7 @@ function createRunAppends() {
73241
72781
  const pending = waiters.get(runId);
73242
72782
  if (pending === void 0) return;
73243
72783
  waiters.delete(runId);
73244
- for (const resolve14 of pending) resolve14();
72784
+ for (const resolve13 of pending) resolve13();
73245
72785
  };
73246
72786
  return {
73247
72787
  notify: wake,
@@ -73259,13 +72799,13 @@ function createRunAppends() {
73259
72799
  },
73260
72800
  nextAppend: (runId, signal) => {
73261
72801
  if (signal.aborted) return Promise.resolve();
73262
- return new Promise((resolve14) => {
72802
+ return new Promise((resolve13) => {
73263
72803
  const done = () => {
73264
72804
  signal.removeEventListener("abort", done);
73265
72805
  const pending2 = waiters.get(runId);
73266
72806
  pending2?.delete(done);
73267
72807
  if (pending2?.size === 0) waiters.delete(runId);
73268
- resolve14();
72808
+ resolve13();
73269
72809
  };
73270
72810
  const pending = waiters.get(runId) ?? /* @__PURE__ */ new Set();
73271
72811
  pending.add(done);
@@ -73278,9 +72818,9 @@ function createRunAppends() {
73278
72818
 
73279
72819
  // src/local-api/server.ts
73280
72820
  var import_node_crypto35 = require("crypto");
73281
- var import_promises78 = require("fs/promises");
72821
+ var import_promises76 = require("fs/promises");
73282
72822
  var import_node_http4 = require("http");
73283
- var import_node_path81 = require("path");
72823
+ var import_node_path79 = require("path");
73284
72824
 
73285
72825
  // src/local-api/guard.ts
73286
72826
  var import_node_crypto34 = require("crypto");
@@ -73357,11 +72897,11 @@ id: ${event.id}
73357
72897
  ${data}
73358
72898
  `);
73359
72899
  if (accepted || res.destroyed) return;
73360
- await new Promise((resolve14) => {
72900
+ await new Promise((resolve13) => {
73361
72901
  const done = () => {
73362
72902
  res.off("drain", done);
73363
72903
  res.off("close", done);
73364
- resolve14();
72904
+ resolve13();
73365
72905
  };
73366
72906
  res.once("drain", done);
73367
72907
  res.once("close", done);
@@ -73467,7 +73007,7 @@ async function openLocalTurnProjection(runsDir, runId, conversationId, ordinal)
73467
73007
  if (!reader) return null;
73468
73008
  let offset = toByteOffset(0);
73469
73009
  let ended = false;
73470
- let snapshot2;
73010
+ let snapshot;
73471
73011
  let prepared;
73472
73012
  const merge2 = /* @__PURE__ */ new Map();
73473
73013
  const decoder3 = new TextDecoder();
@@ -73479,13 +73019,13 @@ async function openLocalTurnProjection(runsDir, runId, conversationId, ordinal)
73479
73019
  if (applyLogChunk(decoder3.decode(chunk.bytes), assistantMessageId, state)) ended = true;
73480
73020
  offset = chunk.to;
73481
73021
  }
73482
- if (offset === priorOffset && snapshot2) return snapshot2;
73022
+ if (offset === priorOffset && snapshot) return snapshot;
73483
73023
  if (ended) state.state = "idle";
73484
- snapshot2 = mergeTranscriptMessages(
73024
+ snapshot = mergeTranscriptMessages(
73485
73025
  [{ messageId: assistantMessageId, turnOrdinal: ordinal, role: "assistant", state }],
73486
73026
  merge2
73487
73027
  );
73488
- return snapshot2;
73028
+ return snapshot;
73489
73029
  };
73490
73030
  return {
73491
73031
  runId,
@@ -73589,9 +73129,9 @@ async function readChangedTurn(deps, conversationId, runId, slot) {
73589
73129
  }
73590
73130
  async function nextChangedRuns(bell, signal) {
73591
73131
  if (bell.pending.size === 0) {
73592
- await new Promise((resolve14) => {
73593
- bell.wake = resolve14;
73594
- if (signal.aborted || bell.pending.size > 0) resolve14();
73132
+ await new Promise((resolve13) => {
73133
+ bell.wake = resolve13;
73134
+ if (signal.aborted || bell.pending.size > 0) resolve13();
73595
73135
  });
73596
73136
  bell.wake = void 0;
73597
73137
  }
@@ -73891,12 +73431,12 @@ function activeRunIds(runs) {
73891
73431
  var streamStatus = async ({ feed, appAttachments }, { res, signal }) => {
73892
73432
  var _stack = [];
73893
73433
  try {
73894
- const snapshot2 = await feed.refresh(signal);
73434
+ const snapshot = await feed.refresh(signal);
73895
73435
  const _attachment = __using(_stack, appAttachments.attach());
73896
73436
  startEventStream(res);
73897
73437
  const send2 = (name, event) => writeEvent(res, { name, id: String(event.seq), dataLines: [JSON.stringify(event)] });
73898
73438
  let latest = null;
73899
- let writing = send2("snapshot", snapshot2);
73439
+ let writing = send2("snapshot", snapshot);
73900
73440
  const flush = async () => {
73901
73441
  while (latest !== null && !res.destroyed) {
73902
73442
  const next = latest;
@@ -73908,9 +73448,9 @@ var streamStatus = async ({ feed, appAttachments }, { res, signal }) => {
73908
73448
  latest = event;
73909
73449
  writing = writing.then(flush);
73910
73450
  }));
73911
- await new Promise((resolve14) => {
73912
- if (signal.aborted) resolve14();
73913
- signal.addEventListener("abort", () => resolve14(), { once: true });
73451
+ await new Promise((resolve13) => {
73452
+ if (signal.aborted) resolve13();
73453
+ signal.addEventListener("abort", () => resolve13(), { once: true });
73914
73454
  });
73915
73455
  await writing;
73916
73456
  } catch (_) {
@@ -74233,11 +73773,11 @@ function localRequestSignal(path4, closed) {
74233
73773
  ]);
74234
73774
  }
74235
73775
  async function listenOnLoopback(server) {
74236
- await new Promise((resolve14, reject) => {
73776
+ await new Promise((resolve13, reject) => {
74237
73777
  server.once("error", reject);
74238
73778
  server.listen(0, "127.0.0.1", () => {
74239
73779
  server.off("error", reject);
74240
- resolve14();
73780
+ resolve13();
74241
73781
  });
74242
73782
  }).catch((error61) => {
74243
73783
  throw new RuntimeFault("io_failed", "The local API could not listen on loopback", {
@@ -74252,7 +73792,7 @@ async function listenOnLoopback(server) {
74252
73792
  }
74253
73793
  async function closeServer(server) {
74254
73794
  server.closeAllConnections();
74255
- await new Promise((resolve14) => server.close(() => resolve14()));
73795
+ await new Promise((resolve13) => server.close(() => resolve13()));
74256
73796
  }
74257
73797
  async function serveLocalApi(deps) {
74258
73798
  const limits = { ...DEFAULT_LIMITS, ...deps.limits };
@@ -74323,7 +73863,7 @@ async function serveLocalApi(deps) {
74323
73863
  startedAtMs,
74324
73864
  runtimeVersion: deps.runtimeVersion
74325
73865
  };
74326
- const discoveryPath = (0, import_node_path81.join)(deps.stateDir, LOCAL_API_DISCOVERY_FILE);
73866
+ const discoveryPath = (0, import_node_path79.join)(deps.stateDir, LOCAL_API_DISCOVERY_FILE);
74327
73867
  await writeJsonFileAtomic(discoveryPath, discovery);
74328
73868
  const followers = startMaintenance({
74329
73869
  everyMs: limits.refreshEveryMs,
@@ -74357,7 +73897,7 @@ async function serveLocalApi(deps) {
74357
73897
  await watchedStatus[Symbol.asyncDispose]();
74358
73898
  const current = await readJsonFile(discoveryPath, localApiDiscoverySchema);
74359
73899
  if (current.kind === "ok" && current.value.token === token) {
74360
- await (0, import_promises78.rm)(discoveryPath, { force: true });
73900
+ await (0, import_promises76.rm)(discoveryPath, { force: true });
74361
73901
  }
74362
73902
  await closeServer(server);
74363
73903
  log.info("local_api.closed", {});
@@ -74442,7 +73982,7 @@ function machineFeatureActions(deps) {
74442
73982
  }
74443
73983
 
74444
73984
  // src/cli/commands/machine-plane.ts
74445
- var import_node_path83 = require("path");
73985
+ var import_node_path81 = require("path");
74446
73986
 
74447
73987
  // src/link/index.ts
74448
73988
  init_runtime_v2();
@@ -77009,9 +76549,9 @@ var Socket2 = class extends Emitter {
77009
76549
  * @return a Promise that will be fulfilled when the server acknowledges the event
77010
76550
  */
77011
76551
  emitWithAck(ev, ...args) {
77012
- return new Promise((resolve14, reject) => {
76552
+ return new Promise((resolve13, reject) => {
77013
76553
  const fn = (arg1, arg2) => {
77014
- return arg1 ? reject(arg1) : resolve14(arg2);
76554
+ return arg1 ? reject(arg1) : resolve13(arg2);
77015
76555
  };
77016
76556
  fn.withError = true;
77017
76557
  args.push(fn);
@@ -78110,10 +77650,10 @@ function refusalFailure(refusal2) {
78110
77650
  }
78111
77651
 
78112
77652
  // src/link/probe.ts
78113
- var import_promises79 = require("dns/promises");
77653
+ var import_promises77 = require("dns/promises");
78114
77654
  var import_node_net5 = require("net");
78115
77655
  var import_node_tls2 = require("tls");
78116
- var PROBE_TIMEOUT_MS4 = 5e3;
77656
+ var PROBE_TIMEOUT_MS3 = 5e3;
78117
77657
  function openSocket(url3) {
78118
77658
  const secure = url3.protocol === "https:" || url3.protocol === "wss:";
78119
77659
  const host = url3.hostname;
@@ -78130,11 +77670,11 @@ async function connectOnce(url3, clock) {
78130
77670
  const timer = new AbortController();
78131
77671
  try {
78132
77672
  return await Promise.race([
78133
- new Promise((resolve14) => {
78134
- socket.once(ready, () => resolve14(null));
78135
- socket.once("error", (error61) => resolve14(classifyTransportFailure(error61)));
77673
+ new Promise((resolve13) => {
77674
+ socket.once(ready, () => resolve13(null));
77675
+ socket.once("error", (error61) => resolve13(classifyTransportFailure(error61)));
78136
77676
  }),
78137
- clock.sleep(PROBE_TIMEOUT_MS4, timer.signal).then(
77677
+ clock.sleep(PROBE_TIMEOUT_MS3, timer.signal).then(
78138
77678
  () => "connection_timeout",
78139
77679
  () => null
78140
77680
  )
@@ -78146,7 +77686,7 @@ async function connectOnce(url3, clock) {
78146
77686
  }
78147
77687
  async function probeEndpoint(url3, clock) {
78148
77688
  try {
78149
- await (0, import_promises79.lookup)(url3.hostname);
77689
+ await (0, import_promises77.lookup)(url3.hostname);
78150
77690
  } catch (error61) {
78151
77691
  const reason = classifyTransportFailure(error61);
78152
77692
  return reason === "other" ? "dns" : reason;
@@ -78433,13 +77973,13 @@ function connectLink(options) {
78433
77973
  socket.disconnect();
78434
77974
  socket.connect();
78435
77975
  };
78436
- const hearsServer = (timeoutMs) => new Promise((resolve14) => {
77976
+ const hearsServer = (timeoutMs) => new Promise((resolve13) => {
78437
77977
  const waiting = new AbortController();
78438
77978
  const settle = (alive) => {
78439
77979
  waiting.abort();
78440
77980
  socket.io.off("ping", onPing);
78441
77981
  socket.off("disconnect", onDrop);
78442
- resolve14(alive);
77982
+ resolve13(alive);
78443
77983
  };
78444
77984
  const onPing = () => settle(true);
78445
77985
  const onDrop = () => settle(false);
@@ -78637,7 +78177,7 @@ function createReconciler(host, lifecycle, log, signal) {
78637
78177
  }
78638
78178
 
78639
78179
  // src/uploader/index.ts
78640
- var import_promises80 = require("fs/promises");
78180
+ var import_promises78 = require("fs/promises");
78641
78181
  init_runtime_v2();
78642
78182
  init_zod();
78643
78183
  var RETRY_DELAYS_MS = [250, 500, 1e3, 2e3, 5e3, 1e4, 3e4];
@@ -78657,6 +78197,7 @@ function startUploader({ api, runsDir, clock, log, archive }) {
78657
78197
  const active = /* @__PURE__ */ new Map();
78658
78198
  const again = /* @__PURE__ */ new Set();
78659
78199
  const sealed = /* @__PURE__ */ new Set();
78200
+ const receiptBackoff = /* @__PURE__ */ new Map();
78660
78201
  const reject = async (runId, progressPath, progress, rejection2) => {
78661
78202
  log.error("upload.rejected", { runId, status: rejection2.status, message: rejection2.message });
78662
78203
  if (rejection2.status === UNAUTHORIZED) return;
@@ -78670,6 +78211,7 @@ function startUploader({ api, runsDir, clock, log, archive }) {
78670
78211
  const receipt = await api.readReceipt(target, controller.signal);
78671
78212
  switch (receipt.kind) {
78672
78213
  case "read": {
78214
+ receiptBackoff.delete(runId);
78673
78215
  log.debug("upload.resumed", {
78674
78216
  runId,
78675
78217
  admittedOffset: receipt.receipt?.admittedOffset ?? 0
@@ -78681,8 +78223,12 @@ function startUploader({ api, runsDir, clock, log, archive }) {
78681
78223
  case "rejected":
78682
78224
  await reject(runId, path4, progressFromReceipt(null), receipt);
78683
78225
  return null;
78684
- case "retry":
78226
+ case "retry": {
78227
+ const failures = (receiptBackoff.get(runId)?.failures ?? 0) + 1;
78228
+ const delayMs = RETRY_DELAYS_MS[Math.min(failures, RETRY_DELAYS_MS.length - 1)] ?? 3e4;
78229
+ receiptBackoff.set(runId, { failures, notBefore: clock.now() + delayMs });
78685
78230
  throw new RuntimeFault("io_failed", `Receipt request failed: ${receipt.status}`);
78231
+ }
78686
78232
  default:
78687
78233
  return assertNever2(receipt);
78688
78234
  }
@@ -78757,6 +78303,8 @@ function startUploader({ api, runsDir, clock, log, archive }) {
78757
78303
  const meta3 = await readRunMeta(dir.meta);
78758
78304
  if (meta3 === null) return;
78759
78305
  const target = { conversationId: meta3.conversationId, runId };
78306
+ const backoff = receiptBackoff.get(runId);
78307
+ if (backoff !== void 0 && backoff.notBefore > clock.now()) return;
78760
78308
  const progress = await progressOf(runId, target, dir.upload);
78761
78309
  if (progress?.sealed) sealed.add(runId);
78762
78310
  if (progress === null || progress.sealed) return;
@@ -78785,7 +78333,7 @@ function startUploader({ api, runsDir, clock, log, archive }) {
78785
78333
  };
78786
78334
  const unsealedRunIds = async () => {
78787
78335
  const runIds = [];
78788
- for (const name of await (0, import_promises80.readdir)(runsDir).catch(() => [])) {
78336
+ for (const name of await (0, import_promises78.readdir)(runsDir).catch(() => [])) {
78789
78337
  const runId = runIdSchema.safeParse(name);
78790
78338
  if (runId.success && !sealed.has(runId.data) && !archive?.has(runId.data))
78791
78339
  runIds.push(runId.data);
@@ -78800,13 +78348,13 @@ function startUploader({ api, runsDir, clock, log, archive }) {
78800
78348
  const dir = runDirectory(runsDir, runId);
78801
78349
  const progress = await readJsonFile(dir.upload, uploadProgressSchema);
78802
78350
  if (progress.kind !== "ok" || !progress.value.sealed) return false;
78803
- const sealedAt = (await (0, import_promises80.stat)(dir.upload)).mtimeMs;
78351
+ const sealedAt = (await (0, import_promises78.stat)(dir.upload)).mtimeMs;
78804
78352
  if (clock.now() - sealedAt < options.sealedForMs) return false;
78805
78353
  return (await readLastRecord(dir.log))?.update.sessionUpdate === "_alan/run.ended";
78806
78354
  };
78807
78355
  const archivable = async (options) => {
78808
78356
  const found = [];
78809
- for (const name of await (0, import_promises80.readdir)(runsDir).catch(() => [])) {
78357
+ for (const name of await (0, import_promises78.readdir)(runsDir).catch(() => [])) {
78810
78358
  const runId = runIdSchema.safeParse(name);
78811
78359
  if (!runId.success || archive?.has(runId.data)) continue;
78812
78360
  try {
@@ -79008,12 +78556,12 @@ async function startMachineNativeIngest(deps) {
79008
78556
  }
79009
78557
 
79010
78558
  // src/cli/commands/run-updates.ts
79011
- var import_node_path82 = require("path");
78559
+ var import_node_path80 = require("path");
79012
78560
  init_runtime_v2();
79013
78561
  var UPDATE_CHECK_EVERY_MS = 6 * 60 * 60 * 1e3;
79014
78562
  var DEFERRED_RETRY_MS = 5 * 60 * 1e3;
79015
78563
  function isInstalledBundle(layout, bundlePath) {
79016
- return (0, import_node_path82.resolve)((0, import_node_path82.dirname)((0, import_node_path82.dirname)(bundlePath))) === (0, import_node_path82.resolve)(layout.versions);
78564
+ return (0, import_node_path80.resolve)((0, import_node_path80.dirname)((0, import_node_path80.dirname)(bundlePath))) === (0, import_node_path80.resolve)(layout.versions);
79017
78565
  }
79018
78566
  async function settleUpgradeOnStart({
79019
78567
  layout,
@@ -79120,7 +78668,7 @@ function startRuntimeUpdates(options) {
79120
78668
  layout,
79121
78669
  release: npmRelease,
79122
78670
  tarball: await options.downloader.download(npmRelease.dist.tarball, signal),
79123
- tmpDir: (0, import_node_path82.join)(layout.root, ".downloads")
78671
+ tmpDir: (0, import_node_path80.join)(layout.root, ".downloads")
79124
78672
  });
79125
78673
  await lifecycle.exclusive("upgrade", async () => {
79126
78674
  await recordPendingUpgrade(layout, currentVersion2, version2, clock.now());
@@ -79353,7 +78901,7 @@ async function startMachinePlane(deps) {
79353
78901
  [ALAN_MANAGED_SESSION_ENV]: "1"
79354
78902
  },
79355
78903
  cwd: paths.stateDir,
79356
- outputPath: (0, import_node_path83.join)(paths.logs, "holders.log")
78904
+ outputPath: (0, import_node_path81.join)(paths.logs, "holders.log")
79357
78905
  },
79358
78906
  deps.holderIsolation
79359
78907
  );
@@ -79390,7 +78938,7 @@ async function startMachinePlane(deps) {
79390
78938
  }),
79391
78939
  local: { home: config2.home, machineId: identity.machineId },
79392
78940
  // Only a cloud sandbox's runtime has a git gateway; a person's own ~/.codex is theirs.
79393
- ...config2.gitGatewayUrl === null ? {} : { codexSkillsDir: (0, import_node_path83.join)(config2.codexHome, "skills") },
78941
+ ...config2.gitGatewayUrl === null ? {} : { codexSkillsDir: (0, import_node_path81.join)(config2.codexHome, "skills") },
79394
78942
  log
79395
78943
  })
79396
78944
  );
@@ -79592,7 +79140,7 @@ async function startMachinePlane(deps) {
79592
79140
  git: createGitRunner({ env: cliEnvironment }),
79593
79141
  clock,
79594
79142
  log,
79595
- dir: (0, import_node_path83.join)(paths.stateDir, "checkout-freshness")
79143
+ dir: (0, import_node_path81.join)(paths.stateDir, "checkout-freshness")
79596
79144
  },
79597
79145
  stopped.signal
79598
79146
  );
@@ -79855,11 +79403,11 @@ function createMachineSlot(deps) {
79855
79403
 
79856
79404
  // src/cli/commands/run-exit.ts
79857
79405
  function firstAborted(signals) {
79858
- return new Promise((resolve14) => {
79406
+ return new Promise((resolve13) => {
79859
79407
  for (const reason of ["stop", "restart"]) {
79860
79408
  const signal = signals[reason];
79861
- if (signal.aborted) resolve14(reason);
79862
- signal.addEventListener("abort", () => resolve14(reason), { once: true });
79409
+ if (signal.aborted) resolve13(reason);
79410
+ signal.addEventListener("abort", () => resolve13(reason), { once: true });
79863
79411
  }
79864
79412
  });
79865
79413
  }
@@ -79887,7 +79435,7 @@ function lockWaitMs(argv) {
79887
79435
  }
79888
79436
  async function openManagedProviders(config2, paths) {
79889
79437
  const providerEnv = readCliEnvironment();
79890
- const bundledNpm = (0, import_node_path84.join)((0, import_node_path84.dirname)(process.execPath), "npm", "bin", "npm-cli.js");
79438
+ const bundledNpm = (0, import_node_path82.join)((0, import_node_path82.dirname)(process.execPath), "npm", "bin", "npm-cli.js");
79891
79439
  const providerToolchain = config2.providerToolchain ?? (process.platform === "win32" && (0, import_node_fs24.existsSync)(bundledNpm) ? { node: process.execPath, npmCli: bundledNpm } : null);
79892
79440
  const npmPath = providerToolchain?.node ?? await resolveCommandOnPath("npm", providerEnv, process.platform);
79893
79441
  const npmOptions = npmPath === null || process.platform === "win32" && providerToolchain === null ? null : {
@@ -79895,7 +79443,7 @@ async function openManagedProviders(config2, paths) {
79895
79443
  ...providerToolchain === null ? {} : { argsBeforeNpm: [providerToolchain.npmCli] },
79896
79444
  env: providerEnv
79897
79445
  };
79898
- const providerNodeDir = providerToolchain?.node === void 0 ? void 0 : (0, import_node_path84.dirname)(providerToolchain.node);
79446
+ const providerNodeDir = providerToolchain?.node === void 0 ? void 0 : (0, import_node_path82.dirname)(providerToolchain.node);
79899
79447
  const probeEnv = providerNodeDir === void 0 ? providerEnv : {
79900
79448
  ...providerEnv,
79901
79449
  PATH: `${providerNodeDir}${pathDelimiter(process.platform)}${envValue(providerEnv, "PATH")}`
@@ -79905,7 +79453,7 @@ async function openManagedProviders(config2, paths) {
79905
79453
  throw new Error("Provider installer is unavailable on this computer");
79906
79454
  };
79907
79455
  const managed = createManagedProviderClis({
79908
- root: (0, import_node_path84.join)(paths.stateDir, "provider-clis"),
79456
+ root: (0, import_node_path82.join)(paths.stateDir, "provider-clis"),
79909
79457
  resolveVersion: npmOptions === null ? unavailable : createNpmVersionResolver(npmOptions),
79910
79458
  installPackage: npmOptions === null ? unavailable : createNpmPackageInstaller(npmOptions),
79911
79459
  probe: (executable, backendKind) => probeManagedProvider(executable, backendKind, canonicalProbeEnv)
@@ -79937,7 +79485,7 @@ async function runService(argv, stop, restart = new AbortController().signal) {
79937
79485
  waitMs: lockWaitMs(argv),
79938
79486
  signal: stop
79939
79487
  }));
79940
- const log = __using(_stack, openFileLog((0, import_node_path84.join)(paths.logs, "runtime.jsonl"), config2.logLevel, clock));
79488
+ const log = __using(_stack, openFileLog((0, import_node_path82.join)(paths.logs, "runtime.jsonl"), config2.logLevel, clock));
79941
79489
  const lifecycle = createLifecycleQueue({ clock, log });
79942
79490
  const install2 = installLayout(config2.installDir, config2.profile);
79943
79491
  const bundlePath = process.argv[1] ?? "";
@@ -79971,7 +79519,7 @@ async function runService(argv, stop, restart = new AbortController().signal) {
79971
79519
  openCliEnvironment({
79972
79520
  env: readCliEnvironment(),
79973
79521
  platform: process.platform,
79974
- lastKnownGoodFile: (0, import_node_path84.join)(paths.stateDir, "login-path.json"),
79522
+ lastKnownGoodFile: (0, import_node_path82.join)(paths.stateDir, "login-path.json"),
79975
79523
  clock,
79976
79524
  decorate: (env) => withPackagedAlanCodeEngine(env, bundlePath, process.platform)
79977
79525
  })
@@ -80148,17 +79696,17 @@ async function runServiceCommand(argv, ctx = cliContext()) {
80148
79696
  }
80149
79697
 
80150
79698
  // src/cli/commands/upgrade.ts
80151
- var import_promises81 = require("fs/promises");
80152
- var import_node_path85 = require("path");
79699
+ var import_promises79 = require("fs/promises");
79700
+ var import_node_path83 = require("path");
80153
79701
  function isNotNewer(version2, installed) {
80154
79702
  return installed !== null && isReleaseVersion(version2) && isReleaseVersion(installed) && compareVersions(version2, installed) <= 0;
80155
79703
  }
80156
79704
  async function installFromSource(source) {
80157
79705
  const { layout, from, ifNewer } = source;
80158
- const isTarball = (await (0, import_promises81.stat)(from)).isFile();
80159
- const downloads = (0, import_node_path85.join)(layout.root, ".downloads");
80160
- if (isTarball) await (0, import_promises81.mkdir)(downloads, { recursive: true, mode: 448 });
80161
- const scratch = isTarball ? await (0, import_promises81.mkdtemp)((0, import_node_path85.join)(downloads, "upgrade-")) : null;
79706
+ const isTarball = (await (0, import_promises79.stat)(from)).isFile();
79707
+ const downloads = (0, import_node_path83.join)(layout.root, ".downloads");
79708
+ if (isTarball) await (0, import_promises79.mkdir)(downloads, { recursive: true, mode: 448 });
79709
+ const scratch = isTarball ? await (0, import_promises79.mkdtemp)((0, import_node_path83.join)(downloads, "upgrade-")) : null;
80162
79710
  try {
80163
79711
  const sourceDir = scratch === null ? from : await extractPackageTarball(from, scratch);
80164
79712
  const version2 = await readPackageVersion(sourceDir);
@@ -80166,7 +79714,7 @@ async function installFromSource(source) {
80166
79714
  if (ifNewer && isNotNewer(version2, installed)) return { kind: "skipped", version: version2, installed };
80167
79715
  return { kind: "installed", ...await installVersion(layout, sourceDir) };
80168
79716
  } finally {
80169
- if (scratch !== null) await (0, import_promises81.rm)(scratch, { recursive: true, force: true });
79717
+ if (scratch !== null) await (0, import_promises79.rm)(scratch, { recursive: true, force: true });
80170
79718
  }
80171
79719
  }
80172
79720
  async function runUpgrade(argv) {
@@ -80178,7 +79726,7 @@ async function runUpgrade(argv) {
80178
79726
  const layout = installLayout(config2.installDir, config2.profile);
80179
79727
  const outcome2 = await installFromSource({
80180
79728
  layout,
80181
- from: (0, import_node_path85.resolve)(from),
79729
+ from: (0, import_node_path83.resolve)(from),
80182
79730
  ifNewer: hasFlag(argv, "--if-newer")
80183
79731
  });
80184
79732
  if (outcome2.kind === "skipped") {