usebeeline 0.1.34 → 0.1.36

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 (2) hide show
  1. package/dist/usebeeline.mjs +804 -570
  2. package/package.json +1 -1
@@ -212,8 +212,8 @@ async function runSquireBrokerLink(options) {
212
212
  const pending = /* @__PURE__ */ new Map();
213
213
  const queued = [];
214
214
  let resolveDone;
215
- const done = new Promise((resolve52) => {
216
- resolveDone = resolve52;
215
+ const done = new Promise((resolve53) => {
216
+ resolveDone = resolve53;
217
217
  });
218
218
  const failResponse = (id) => `${JSON.stringify({
219
219
  jsonrpc: "2.0",
@@ -4891,12 +4891,24 @@ async function notify(fields) {
4891
4891
  async function extendSystemdStartTimeout(ms) {
4892
4892
  await notify([`EXTEND_TIMEOUT_USEC=${Math.max(0, Math.round(ms)) * 1e3}`]).catch(() => void 0);
4893
4893
  }
4894
- function startLocalWatchdog(notifier, status, intervalMs = 6e4, env = process.env) {
4894
+ function startLocalWatchdog(notifier, status, workLoopProgress, intervalMs = 6e4, env = process.env) {
4895
4895
  if (!env.WATCHDOG_USEC)
4896
4896
  return () => void 0;
4897
- const timer = setInterval(() => void notifier.progress(status()).catch((error) => console.error("[thin-core] watchdog notification failed:", error)), intervalMs);
4897
+ let pending = false;
4898
+ let stopped = false;
4899
+ const timer = setInterval(() => {
4900
+ if (pending || stopped)
4901
+ return;
4902
+ pending = true;
4903
+ void workLoopProgress().then((progressed) => stopped || progressed === false ? void 0 : notifier.progress(status(), true)).catch((error) => console.error("[thin-core] watchdog notification failed:", error)).finally(() => {
4904
+ pending = false;
4905
+ });
4906
+ }, intervalMs);
4898
4907
  timer.unref?.();
4899
- return () => clearInterval(timer);
4908
+ return () => {
4909
+ stopped = true;
4910
+ clearInterval(timer);
4911
+ };
4900
4912
  }
4901
4913
  var execFileAsync, DELIBERATE_REMOVAL_EXIT_STATUS, DAEMON_DISTRESS_EXIT_STATUS, UNKNOWN_AGENT_EXIT_STATUS, SYSTEMD_UNIT_NAME, SYSTEMD_HELPER_UNIT_NAME, NO_AGENTS_EXIT_STATUS, SYSTEMD_COMMAND_TIMEOUT_MS, SYSTEMD_RESTART_WAIT_MS, AGENT_SERVICE, runSystemctl, SystemdNotifier;
4902
4914
  var init_systemd = __esm({
@@ -4924,8 +4936,8 @@ var init_systemd = __esm({
4924
4936
  async ready(status) {
4925
4937
  await notify(["--ready", `--status=${status}`]);
4926
4938
  }
4927
- async progress(status) {
4928
- await notify(["WATCHDOG=1", `STATUS=${status}`]);
4939
+ async progress(status, watchdog = false) {
4940
+ await notify([...watchdog ? ["WATCHDOG=1"] : [], `STATUS=${status}`]);
4929
4941
  }
4930
4942
  async stopping(status) {
4931
4943
  await notify(["STOPPING=1", `STATUS=${status}`]);
@@ -13894,7 +13906,7 @@ function configureNetworkFamilyDefaults(network = net) {
13894
13906
  configureNetworkFamilyDefaults();
13895
13907
 
13896
13908
  // apps/body/dist/cli.js
13897
- import { dirname as dirname32, resolve as resolve51 } from "node:path";
13909
+ import { dirname as dirname32, resolve as resolve52 } from "node:path";
13898
13910
  import { stdin as stdin4, stdout as stdout5 } from "node:process";
13899
13911
 
13900
13912
  // node_modules/@clack/core/dist/index.mjs
@@ -15334,7 +15346,7 @@ function parseCursorModelsOutput(output) {
15334
15346
  };
15335
15347
  }
15336
15348
  async function enumerateCursorModels(env = process.env) {
15337
- return new Promise((resolve52) => {
15349
+ return new Promise((resolve53) => {
15338
15350
  const child = spawn2("cursor-agent", ["models"], {
15339
15351
  env,
15340
15352
  stdio: ["ignore", "pipe", "ignore"]
@@ -15348,11 +15360,11 @@ async function enumerateCursorModels(env = process.env) {
15348
15360
  });
15349
15361
  child.on("error", () => {
15350
15362
  clearTimeout(timer);
15351
- resolve52(void 0);
15363
+ resolve53(void 0);
15352
15364
  });
15353
15365
  child.on("close", (code) => {
15354
15366
  clearTimeout(timer);
15355
- resolve52(code === 0 ? parseCursorModelsOutput(output) : void 0);
15367
+ resolve53(code === 0 ? parseCursorModelsOutput(output) : void 0);
15356
15368
  });
15357
15369
  });
15358
15370
  }
@@ -15779,13 +15791,13 @@ var CursorAcpServer = class {
15779
15791
  consumeLine(line);
15780
15792
  });
15781
15793
  try {
15782
- const { code, signal } = await new Promise((resolve52) => {
15794
+ const { code, signal } = await new Promise((resolve53) => {
15783
15795
  let settled = false;
15784
15796
  const finish = (exitCode, exitSignal) => {
15785
15797
  if (settled)
15786
15798
  return;
15787
15799
  settled = true;
15788
- resolve52({ code: exitCode, signal: exitSignal });
15800
+ resolve53({ code: exitCode, signal: exitSignal });
15789
15801
  };
15790
15802
  child.once("error", (error) => {
15791
15803
  spawnError = error instanceof Error ? error.message : String(error);
@@ -15930,10 +15942,10 @@ function releaseSquireConnectSession(log2, owner = "") {
15930
15942
  function squireChromeProfileDir() {
15931
15943
  return process.env.TRUSTY_SQUIRE_PROFILE_DIR ?? squireHostPaths(homedir2()).profileDir;
15932
15944
  }
15933
- var defaultShellRunner = (command, args) => new Promise((resolve52) => {
15945
+ var defaultShellRunner = (command, args) => new Promise((resolve53) => {
15934
15946
  execFile(command, [...args], { timeout: 12e4, maxBuffer: 4 * 1024 * 1024, encoding: "utf8" }, (error, stdout6, stderr) => {
15935
15947
  const code = error?.code;
15936
- resolve52({
15948
+ resolve53({
15937
15949
  code: typeof code === "number" ? code : error ? 1 : 0,
15938
15950
  stdout: String(stdout6 ?? ""),
15939
15951
  stderr: String(stderr ?? "")
@@ -15958,7 +15970,7 @@ function killConnectTree(child) {
15958
15970
  }
15959
15971
  child.kill();
15960
15972
  }
15961
- var defaultStreamedRunner = (command, args, env, owner = "") => new Promise((resolve52) => {
15973
+ var defaultStreamedRunner = (command, args, env, owner = "") => new Promise((resolve53) => {
15962
15974
  const child = spawn5(command, args, {
15963
15975
  stdio: ["ignore", "pipe", "pipe"],
15964
15976
  env: env ?? squireConnectProcessEnv(),
@@ -15972,7 +15984,7 @@ var defaultStreamedRunner = (command, args, env, owner = "") => new Promise((res
15972
15984
  const safetyTimer = setTimeout(() => {
15973
15985
  if (!resolved) {
15974
15986
  resolved = true;
15975
- resolve52({ stdout: stdout6, stderr, pid: child.pid ?? void 0, report, abort: () => {
15987
+ resolve53({ stdout: stdout6, stderr, pid: child.pid ?? void 0, report, abort: () => {
15976
15988
  } });
15977
15989
  }
15978
15990
  killConnectTree(child);
@@ -16007,7 +16019,7 @@ var defaultStreamedRunner = (command, args, env, owner = "") => new Promise((res
16007
16019
  const finish = (result) => {
16008
16020
  if (!resolved) {
16009
16021
  resolved = true;
16010
- resolve52(result);
16022
+ resolve53(result);
16011
16023
  }
16012
16024
  };
16013
16025
  const settle = (result) => {
@@ -16499,13 +16511,13 @@ var StdioSquireMcpClient = class {
16499
16511
  const child = this.child;
16500
16512
  if (!child)
16501
16513
  return Promise.reject(new Error("Squire MCP session is not running"));
16502
- return new Promise((resolve52, reject) => {
16514
+ return new Promise((resolve53, reject) => {
16503
16515
  const timeoutMs = method === "initialize" ? INITIALIZE_TIMEOUT_MS : CALL_TIMEOUT_MS;
16504
16516
  const timer = setTimeout(() => {
16505
16517
  this.pending.delete(id);
16506
16518
  reject(new Error(`${toolName2 ?? method} timed out after ${timeoutMs}ms`));
16507
16519
  }, timeoutMs);
16508
- this.pending.set(id, { resolve: resolve52, reject, timer });
16520
+ this.pending.set(id, { resolve: resolve53, reject, timer });
16509
16521
  child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id, method, params })}
16510
16522
  `);
16511
16523
  });
@@ -16796,9 +16808,9 @@ var SquireTaskRelay = class {
16796
16808
  response.writeHead(400, { "content-type": "application/json" }).end(JSON.stringify({ error: error instanceof Error ? error.message : "Squire relay failed" }));
16797
16809
  }
16798
16810
  });
16799
- await new Promise((resolve52, reject) => {
16811
+ await new Promise((resolve53, reject) => {
16800
16812
  server.once("error", reject);
16801
- server.listen(0, "127.0.0.1", resolve52);
16813
+ server.listen(0, "127.0.0.1", resolve53);
16802
16814
  });
16803
16815
  this.server = server;
16804
16816
  const address = server.address();
@@ -17904,11 +17916,11 @@ var RegistryMcpHostBroker = class {
17904
17916
  })();
17905
17917
  });
17906
17918
  });
17907
- await new Promise((resolve52, reject) => {
17919
+ await new Promise((resolve53, reject) => {
17908
17920
  this.server.once("error", reject);
17909
17921
  this.server.listen(this.socketPath, () => {
17910
17922
  this.server.off("error", reject);
17911
- resolve52();
17923
+ resolve53();
17912
17924
  });
17913
17925
  });
17914
17926
  chmodSync(this.socketPath, 384);
@@ -17917,12 +17929,12 @@ var RegistryMcpHostBroker = class {
17917
17929
  const server = this.server;
17918
17930
  this.server = void 0;
17919
17931
  if (server)
17920
- await new Promise((resolve52) => server.close(() => resolve52()));
17932
+ await new Promise((resolve53) => server.close(() => resolve53()));
17921
17933
  rmSync2(this.socketPath, { force: true });
17922
17934
  }
17923
17935
  };
17924
17936
  async function brokerRequest(socketPath, request) {
17925
- return new Promise((resolve52, reject) => {
17937
+ return new Promise((resolve53, reject) => {
17926
17938
  const socket = createConnection3(socketPath);
17927
17939
  let output = "";
17928
17940
  socket.setEncoding("utf8");
@@ -17939,7 +17951,7 @@ async function brokerRequest(socketPath, request) {
17939
17951
  throw new Error(parsed.error);
17940
17952
  if (!Array.isArray(parsed.messages) || !parsed.messages.every((entry) => typeof entry === "string"))
17941
17953
  throw new Error("Registry MCP broker returned an invalid response");
17942
- resolve52(parsed.messages);
17954
+ resolve53(parsed.messages);
17943
17955
  } catch (error) {
17944
17956
  reject(error);
17945
17957
  }
@@ -18738,6 +18750,7 @@ var AgentChannel = class {
18738
18750
  #registered = false;
18739
18751
  /** A register frame is in flight on the current socket. */
18740
18752
  #pending = false;
18753
+ #refused = false;
18741
18754
  #registeredAt;
18742
18755
  #failures = 0;
18743
18756
  #retry;
@@ -18762,7 +18775,7 @@ var AgentChannel = class {
18762
18775
  return () => this.#openListeners.delete(listener);
18763
18776
  }
18764
18777
  start() {
18765
- if (this.#wanted)
18778
+ if (this.#wanted || this.#refused)
18766
18779
  return;
18767
18780
  this.#wanted = true;
18768
18781
  this.machine.want(this);
@@ -18795,7 +18808,7 @@ var AgentChannel = class {
18795
18808
  }
18796
18809
  /** The socket opened: ask the server to take this agent. */
18797
18810
  register() {
18798
- if (!this.#wanted || this.#registered || this.#pending)
18811
+ if (!this.#wanted || this.#registered || this.#pending || this.#refused)
18799
18812
  return;
18800
18813
  clearTimeout(this.#retry);
18801
18814
  this.#retry = void 0;
@@ -18828,11 +18841,20 @@ var AgentChannel = class {
18828
18841
  return;
18829
18842
  }
18830
18843
  if (event.type === "register-refused") {
18844
+ if (this.#refused)
18845
+ return;
18831
18846
  this.#pending = false;
18832
18847
  const code = typeof event.code === "string" ? event.code : "refused";
18833
18848
  console.warn(`[machine-link] server refused agent ${this.agentId}: ${code}`);
18849
+ this.#refused = ["daemon_token_required", "agent_removed", "too_many_agents"].includes(code);
18834
18850
  this.handlers.onRefused?.(code);
18835
- this.#retryLater();
18851
+ if (this.#refused) {
18852
+ this.#wanted = false;
18853
+ clearTimeout(this.#retry);
18854
+ this.#retry = void 0;
18855
+ this.machine.unwant(this);
18856
+ } else
18857
+ this.#retryLater();
18836
18858
  return;
18837
18859
  }
18838
18860
  if (event.type === "unregistered") {
@@ -18982,12 +19004,9 @@ var MachineLink = class {
18982
19004
  if (!value || typeof value !== "object")
18983
19005
  return;
18984
19006
  const event = value;
18985
- if (event.type === "force-update" && typeof event.minVersion === "string") {
18986
- this.link.requireUpdate(event.minVersion);
18987
- return;
18988
- }
18989
- if (typeof event.agentId === "string") {
18990
- this.#channels.get(event.agentId)?.receive(event);
19007
+ if (event.type === "force-update") {
19008
+ if (typeof event.minVersion === "string")
19009
+ this.link.requireUpdate(event.minVersion);
18991
19010
  return;
18992
19011
  }
18993
19012
  if (event.type === "helper-release") {
@@ -18997,6 +19016,10 @@ var MachineLink = class {
18997
19016
  this.#broadcast(event);
18998
19017
  return;
18999
19018
  }
19019
+ if (typeof event.agentId === "string" && event.agentId.length > 0) {
19020
+ this.#channels.get(event.agentId)?.receive(event);
19021
+ return;
19022
+ }
19000
19023
  if (event.type !== "hello" && event.type !== "force-update")
19001
19024
  this.#logUnknown(event.type);
19002
19025
  }
@@ -19461,7 +19484,7 @@ var AgentSignIn = class {
19461
19484
  };
19462
19485
  for (const name of ISOLATION_VARIABLES)
19463
19486
  delete env[name];
19464
- return new Promise((resolve52, reject) => {
19487
+ return new Promise((resolve53, reject) => {
19465
19488
  let output = "";
19466
19489
  let answered = false;
19467
19490
  let child;
@@ -19502,7 +19525,7 @@ var AgentSignIn = class {
19502
19525
  return;
19503
19526
  answered = true;
19504
19527
  clearTimeout(linkTimer);
19505
- resolve52(link2);
19528
+ resolve53(link2);
19506
19529
  };
19507
19530
  child.stdout?.on("data", read2);
19508
19531
  child.stderr?.on("data", read2);
@@ -28390,19 +28413,19 @@ function wellKnownExecutableDirs(env = process.env) {
28390
28413
  return [...versioned, resolve7(home, ".local", "bin"), "/usr/local/bin", "/opt/homebrew/bin"];
28391
28414
  }
28392
28415
  function augmentedSearchDirectories(env = process.env) {
28393
- const directories = [];
28416
+ const directories2 = [];
28394
28417
  const pushAll = (paths) => {
28395
28418
  for (const directory of paths) {
28396
- if (directory && !directories.includes(directory))
28397
- directories.push(directory);
28419
+ if (directory && !directories2.includes(directory))
28420
+ directories2.push(directory);
28398
28421
  }
28399
28422
  };
28400
28423
  pushAll((env.PATH ?? "").split(delimiter));
28401
28424
  if (env.BEELINE_HARNESS_PATH_AUGMENT === "0")
28402
- return directories;
28425
+ return directories2;
28403
28426
  pushAll(wellKnownExecutableDirs(env));
28404
28427
  pushAll((env.BEELINE_LAUNCHER_PATH ?? "").split(delimiter));
28405
- return directories;
28428
+ return directories2;
28406
28429
  }
28407
28430
  function describeExecutableSearch(env = process.env) {
28408
28431
  return augmentedSearchDirectories(env).join(", ");
@@ -29351,13 +29374,13 @@ var RoomSupervisor = class {
29351
29374
  */
29352
29375
  retryDelay(failures, signal, since = this.#wakes) {
29353
29376
  const delay = this.delaysMs[failures - 1];
29354
- return new Promise((resolve52) => {
29377
+ return new Promise((resolve53) => {
29355
29378
  let timer;
29356
29379
  const done = () => {
29357
29380
  clearTimeout(timer);
29358
29381
  this.#parked.delete(done);
29359
29382
  signal?.removeEventListener("abort", done);
29360
- resolve52();
29383
+ resolve53();
29361
29384
  };
29362
29385
  this.#parked.add(done);
29363
29386
  signal?.addEventListener("abort", done, { once: true });
@@ -29542,12 +29565,12 @@ async function retryBeforeReady(work, options) {
29542
29565
  if (wait2 <= 0)
29543
29566
  break;
29544
29567
  await options.extendStartTimeout(wait2 + 15e3);
29545
- await new Promise((resolve52) => {
29568
+ await new Promise((resolve53) => {
29546
29569
  const timer = setTimeout(done, wait2);
29547
29570
  function done() {
29548
29571
  clearTimeout(timer);
29549
29572
  options.signal?.removeEventListener("abort", done);
29550
- resolve52();
29573
+ resolve53();
29551
29574
  }
29552
29575
  wake = done;
29553
29576
  options.signal?.addEventListener("abort", done, { once: true });
@@ -31271,9 +31294,9 @@ async function runStartCommand(args, interactiveUi, dependencyOverrides = {}) {
31271
31294
  // apps/body/dist/connect-command.js
31272
31295
  import { spawn as spawn13 } from "node:child_process";
31273
31296
  import { createHash as createHash9, randomUUID as randomUUID9 } from "node:crypto";
31274
- import { chmod as chmod6, mkdir as mkdir16, readFile as readFile20, unlink as unlink5, writeFile as writeFile13 } from "node:fs/promises";
31297
+ import { chmod as chmod6, mkdir as mkdir16, readFile as readFile21, unlink as unlink5, writeFile as writeFile13 } from "node:fs/promises";
31275
31298
  import { homedir as homedir12, hostname } from "node:os";
31276
- import { dirname as dirname17, resolve as resolve22 } from "node:path";
31299
+ import { dirname as dirname17, resolve as resolve23 } from "node:path";
31277
31300
  import { stdin as stdin3, stdout as stdout4 } from "node:process";
31278
31301
 
31279
31302
  // packages/api-contract/dist/phone-types.js
@@ -32340,11 +32363,11 @@ var AcpClient = class extends EventEmitter {
32340
32363
  }, timeoutMs);
32341
32364
  } catch (error) {
32342
32365
  if (launch && /EPIPE/.test(String(error)) && this.child?.exitCode === null) {
32343
- await new Promise((resolve52) => {
32344
- const timer = setTimeout(resolve52, 250);
32366
+ await new Promise((resolve53) => {
32367
+ const timer = setTimeout(resolve53, 250);
32345
32368
  this.child?.once("close", () => {
32346
32369
  clearTimeout(timer);
32347
- resolve52();
32370
+ resolve53();
32348
32371
  });
32349
32372
  });
32350
32373
  }
@@ -32390,8 +32413,8 @@ ${String(error)}`);
32390
32413
  try {
32391
32414
  oomKilled = await Promise.race([
32392
32415
  this.oomKills.consume().catch(() => false),
32393
- new Promise((resolve52) => {
32394
- diagnosticTimer = setTimeout(() => resolve52(false), 100);
32416
+ new Promise((resolve53) => {
32417
+ diagnosticTimer = setTimeout(() => resolve53(false), 100);
32395
32418
  })
32396
32419
  ]);
32397
32420
  } finally {
@@ -32823,7 +32846,7 @@ ${String(error)}`);
32823
32846
  const current = this.activeRunIds.get(sessionId);
32824
32847
  if (current)
32825
32848
  return Promise.resolve(current);
32826
- return new Promise((resolve52, reject) => {
32849
+ return new Promise((resolve53, reject) => {
32827
32850
  const onUpdate = (update) => {
32828
32851
  if (update.sessionId !== sessionId)
32829
32852
  return;
@@ -32831,7 +32854,7 @@ ${String(error)}`);
32831
32854
  if (!runId)
32832
32855
  return;
32833
32856
  cleanup();
32834
- resolve52(runId);
32857
+ resolve53(runId);
32835
32858
  };
32836
32859
  const timer = setTimeout(() => {
32837
32860
  cleanup();
@@ -32910,14 +32933,14 @@ ${String(error)}`);
32910
32933
  }
32911
32934
  const id = this.nextId++;
32912
32935
  const payload = { jsonrpc: "2.0", id, method, params };
32913
- return new Promise((resolve52, reject) => {
32936
+ return new Promise((resolve53, reject) => {
32914
32937
  const timer = backstop ? void 0 : setTimeout(() => {
32915
32938
  this.pending.delete(id);
32916
32939
  reject(new AcpRequestTimeoutError(method, timeoutMs, this.stderrTail, false, detail));
32917
32940
  }, timeoutMs);
32918
32941
  const sessionId = params?.sessionId;
32919
32942
  this.pending.set(id, {
32920
- resolve: resolve52,
32943
+ resolve: resolve53,
32921
32944
  reject,
32922
32945
  timer,
32923
32946
  method,
@@ -33973,18 +33996,145 @@ async function pairDevice(grant, options = {}) {
33973
33996
  }
33974
33997
 
33975
33998
  // apps/body/dist/openrouter-routing.js
33976
- import { mkdir as mkdir14, readFile as readFile18, writeFile as writeFile11 } from "node:fs/promises";
33999
+ import { mkdir as mkdir14, readFile as readFile19, writeFile as writeFile11 } from "node:fs/promises";
34000
+ import { resolve as resolve21 } from "node:path";
34001
+
34002
+ // apps/body/dist/openrouter-history.js
34003
+ import { createReadStream as createReadStream2 } from "node:fs";
34004
+ import { lstat as lstat5, readFile as readFile18, readdir as readdir6 } from "node:fs/promises";
33977
34005
  import { resolve as resolve20 } from "node:path";
34006
+ import { createInterface as createInterface6 } from "node:readline";
34007
+ var OPENROUTER_HISTORY_WINDOW_MS = 7 * 24 * 60 * 60 * 1e3;
34008
+ var OPENROUTER_GENERATION_URL = "https://openrouter.ai/api/v1/generation";
34009
+ function openRouterTraffic(observations) {
34010
+ const totals = /* @__PURE__ */ new Map();
34011
+ for (const observation2 of observations) {
34012
+ if (observation2.promptTokens <= 0)
34013
+ continue;
34014
+ const total = totals.get(observation2.provider) ?? { calls: 0, promptTokens: 0, cachedTokens: 0 };
34015
+ total.calls++;
34016
+ total.promptTokens += observation2.promptTokens;
34017
+ total.cachedTokens += Math.min(observation2.promptTokens, Math.max(0, observation2.cachedTokens));
34018
+ totals.set(observation2.provider, total);
34019
+ }
34020
+ return [...totals].map(([provider, total]) => ({ ...total, provider, cacheShare: total.cachedTokens / total.promptTokens }));
34021
+ }
34022
+ async function directories(root) {
34023
+ return (await readdir6(root, { withFileTypes: true }).catch(() => [])).filter((entry) => entry.isDirectory()).map((entry) => resolve20(root, entry.name));
34024
+ }
34025
+ async function openRouterGenerationIds(roomsDir, model, now2) {
34026
+ const ids = /* @__PURE__ */ new Map();
34027
+ for (const room of await directories(roomsDir)) {
34028
+ const ordinary = await Promise.all(["agent-home", "agent-home/pi", "agent-home/pi/sessions"].map(async (path) => {
34029
+ const stat14 = await lstat5(resolve20(room, path)).catch(() => void 0);
34030
+ return stat14?.isDirectory() && !stat14.isSymbolicLink();
34031
+ }));
34032
+ if (!ordinary.every(Boolean))
34033
+ continue;
34034
+ for (const project of await directories(resolve20(room, "agent-home/pi/sessions"))) {
34035
+ const files = await readdir6(project, { withFileTypes: true }).catch(() => []);
34036
+ for (const file of files) {
34037
+ if (!file.isFile() || !file.name.endsWith(".jsonl"))
34038
+ continue;
34039
+ const stream = createReadStream2(resolve20(project, file.name), { encoding: "utf8" });
34040
+ const lines = createInterface6({ input: stream, crlfDelay: Infinity });
34041
+ try {
34042
+ for await (const line of lines) {
34043
+ try {
34044
+ const { message } = JSON.parse(line);
34045
+ if (message?.role !== "assistant" || message.model !== model || typeof message.responseId !== "string")
34046
+ continue;
34047
+ const timestamp = message.timestamp;
34048
+ if (typeof timestamp === "number" && timestamp >= now2 - OPENROUTER_HISTORY_WINDOW_MS && timestamp <= now2) {
34049
+ ids.set(message.responseId, timestamp);
34050
+ }
34051
+ } catch {
34052
+ }
34053
+ }
34054
+ } catch {
34055
+ } finally {
34056
+ lines.close();
34057
+ stream.destroy();
34058
+ }
34059
+ }
34060
+ }
34061
+ }
34062
+ return ids;
34063
+ }
34064
+ function observation(value) {
34065
+ if (!value || typeof value !== "object")
34066
+ return void 0;
34067
+ const row = value;
34068
+ if (typeof row.id !== "string" || typeof row.provider !== "string" || typeof row.timestamp !== "number" || !Number.isFinite(row.timestamp) || typeof row.promptTokens !== "number" || !Number.isFinite(row.promptTokens) || row.promptTokens < 0 || typeof row.cachedTokens !== "number" || !Number.isFinite(row.cachedTokens) || row.cachedTokens < 0)
34069
+ return void 0;
34070
+ return {
34071
+ id: row.id,
34072
+ provider: row.provider,
34073
+ timestamp: row.timestamp,
34074
+ promptTokens: row.promptTokens,
34075
+ cachedTokens: Math.min(row.cachedTokens, row.promptTokens),
34076
+ ...typeof row.sessionId === "string" ? { sessionId: row.sessionId } : {}
34077
+ };
34078
+ }
34079
+ async function readOpenRouterTraffic(input) {
34080
+ const path = resolve20(input.cacheDir, `${input.model.replace(/[^A-Za-z0-9._-]+/g, "_")}.generations.json`);
34081
+ let cached = [];
34082
+ try {
34083
+ const value = JSON.parse(await readFile18(path, "utf8"));
34084
+ const record5 = value;
34085
+ if (record5?.model === input.model && Array.isArray(record5.observations)) {
34086
+ cached = record5.observations.map(observation).filter((row) => Boolean(row));
34087
+ }
34088
+ } catch {
34089
+ }
34090
+ const cutoff = input.now - OPENROUTER_HISTORY_WINDOW_MS;
34091
+ const records = new Map(cached.filter((row) => row.timestamp >= cutoff && row.timestamp <= input.now).map((row) => [row.id, row]));
34092
+ const ids = input.roomsDir ? await openRouterGenerationIds(input.roomsDir, input.model, input.now) : /* @__PURE__ */ new Map();
34093
+ const missing = [...ids].filter(([id]) => !records.has(id));
34094
+ let cursor3 = 0;
34095
+ await Promise.all(Array.from({ length: Math.min(6, missing.length) }, async () => {
34096
+ while (cursor3 < missing.length) {
34097
+ const [id, timestamp] = missing[cursor3++];
34098
+ try {
34099
+ const response = await (input.fetchImpl ?? fetch)(`${OPENROUTER_GENERATION_URL}?id=${encodeURIComponent(id)}`, {
34100
+ headers: { authorization: `Bearer ${input.apiKey}` },
34101
+ signal: AbortSignal.timeout(input.timeoutMs ?? 1e4)
34102
+ });
34103
+ if (!response.ok)
34104
+ continue;
34105
+ const { data } = await response.json();
34106
+ if (!data || data.id !== id)
34107
+ continue;
34108
+ const row = observation({
34109
+ id,
34110
+ timestamp,
34111
+ provider: data.provider_name,
34112
+ promptTokens: data.native_tokens_prompt,
34113
+ cachedTokens: data.native_tokens_cached ?? 0,
34114
+ sessionId: data.session_id
34115
+ });
34116
+ if (row)
34117
+ records.set(id, row);
34118
+ } catch {
34119
+ }
34120
+ }
34121
+ }));
34122
+ await writePrivateFileAtomically(path, `${JSON.stringify({ model: input.model, observations: [...records.values()] })}
34123
+ `).catch(() => void 0);
34124
+ return openRouterTraffic([...records.values()]);
34125
+ }
34126
+
34127
+ // apps/body/dist/openrouter-routing.js
33978
34128
  var OPENROUTER_ENDPOINTS_BASE_URL = "https://openrouter.ai/api/v1/models";
33979
34129
  var OPENROUTER_COMPLETIONS_URL = "https://openrouter.ai/api/v1/chat/completions";
33980
34130
  var OPENROUTER_ROUTING_CACHE_TTL_MS = 24 * 60 * 60 * 1e3;
33981
34131
  var OPENROUTER_ROUTING_FETCH_TIMEOUT_MS = 1e4;
33982
- var OPENROUTER_PROBE_CACHE_TTL_MS = 6 * 60 * 60 * 1e3;
33983
34132
  var OPENROUTER_PROBE_MAX_CANDIDATES = 6;
33984
34133
  var OPENROUTER_PROBE_TIMEOUT_MS = 2e4;
33985
34134
  var OPENROUTER_UPTIME_BAR = 98;
33986
34135
  var OPENROUTER_UPTIME_BAR_RELAXED = 95;
33987
34136
  var OPENROUTER_MIN_PROVIDERS = 2;
34137
+ var ROUTING_POLICY = "cache-sticky-v1";
33988
34138
  var OPENROUTER_MAX_OUTPUT_TOKENS = 32768;
33989
34139
  var OPENROUTER_FALLBACK_PROVIDERS = ["deepinfra", "novita"];
33990
34140
  function openRouterModelId(model, env = {}) {
@@ -34016,12 +34166,19 @@ function parseOpenRouterEndpoints(payload) {
34016
34166
  const contextLength = typeof endpoint2.context_length === "number" ? endpoint2.context_length : 0;
34017
34167
  const maxCompletionTokens = typeof endpoint2.max_completion_tokens === "number" ? endpoint2.max_completion_tokens : 0;
34018
34168
  const supported = Array.isArray(endpoint2.supported_parameters) ? endpoint2.supported_parameters : [];
34169
+ const pricing = endpoint2.pricing && typeof endpoint2.pricing === "object" ? endpoint2.pricing : {};
34170
+ const promptPrice = tokenPrice(pricing.prompt);
34171
+ const cacheReadPrice = tokenPrice(pricing.input_cache_read);
34019
34172
  endpoints.push({
34020
34173
  provider,
34021
34174
  uptime,
34022
34175
  contextLength,
34023
34176
  maxCompletionTokens,
34024
- tools: supported.includes("tools")
34177
+ tools: supported.includes("tools"),
34178
+ ...typeof endpoint2.provider_name === "string" ? { providerName: endpoint2.provider_name } : {},
34179
+ ...promptPrice === void 0 ? {} : { promptPrice },
34180
+ ...cacheReadPrice === void 0 ? {} : { cacheReadPrice },
34181
+ discountedCacheRead: promptPrice !== void 0 && cacheReadPrice !== void 0 && cacheReadPrice < promptPrice
34025
34182
  });
34026
34183
  }
34027
34184
  const architecture = record5.architecture && typeof record5.architecture === "object" ? record5.architecture : {};
@@ -34032,6 +34189,30 @@ function parseOpenRouterEndpoints(payload) {
34032
34189
  inputModalities: modalities?.length ? modalities : void 0
34033
34190
  };
34034
34191
  }
34192
+ function rankOpenRouterProviders(endpoints, contextLength, traffic, answered) {
34193
+ const shares2 = traffic.filter((row) => row.promptTokens > 0).map((row) => row.cacheShare).sort((a2, b) => a2 - b);
34194
+ const middle = Math.floor(shares2.length / 2);
34195
+ const medianShare = shares2.length ? (shares2[middle] + shares2[Math.floor((shares2.length - 1) / 2)]) / 2 : 0;
34196
+ const normalize2 = (name) => name.toLowerCase().replace(/[^a-z0-9]/g, "");
34197
+ const ranked = /* @__PURE__ */ new Map();
34198
+ for (const endpoint2 of endpoints) {
34199
+ if (!endpoint2.tools || endpoint2.uptime < OPENROUTER_UPTIME_BAR_RELAXED || contextLength !== void 0 && endpoint2.contextLength < contextLength || !answered.includes(endpoint2.provider) || endpoint2.promptPrice === void 0)
34200
+ continue;
34201
+ const measured = traffic.find((row2) => normalize2(row2.provider) === normalize2(endpoint2.providerName ?? endpoint2.provider));
34202
+ const cacheShare = measured?.cacheShare ?? medianShare;
34203
+ const effectiveInputPrice = endpoint2.promptPrice * (1 - cacheShare) + (endpoint2.cacheReadPrice ?? endpoint2.promptPrice) * cacheShare;
34204
+ const row = { provider: endpoint2.provider, cacheShare, measuredCalls: measured?.calls ?? 0, effectiveInputPrice };
34205
+ if (!ranked.has(row.provider) || effectiveInputPrice < ranked.get(row.provider).effectiveInputPrice)
34206
+ ranked.set(row.provider, row);
34207
+ }
34208
+ return [...ranked.values()].sort((a2, b) => a2.effectiveInputPrice - b.effectiveInputPrice || a2.provider.localeCompare(b.provider));
34209
+ }
34210
+ function tokenPrice(value) {
34211
+ if (typeof value !== "number" && (typeof value !== "string" || !value.trim()))
34212
+ return void 0;
34213
+ const price = Number(value);
34214
+ return Number.isFinite(price) && price >= 0 ? price : void 0;
34215
+ }
34035
34216
  function piInputModalities(modalities) {
34036
34217
  if (!modalities)
34037
34218
  return void 0;
@@ -34061,12 +34242,14 @@ function advertisedContextLength(endpoints) {
34061
34242
  }
34062
34243
  function selectReliableOpenRouterProviders(endpoints, contextLength) {
34063
34244
  const eligible = endpoints.filter((endpoint2) => endpoint2.tools && (contextLength === void 0 || endpoint2.contextLength >= contextLength));
34245
+ const caching = eligible.filter((endpoint2) => endpoint2.discountedCacheRead && endpoint2.uptime >= OPENROUTER_UPTIME_BAR_RELAXED);
34246
+ const candidates = caching.length ? caching : eligible;
34064
34247
  const atBar = (bar) => {
34065
34248
  const seen = /* @__PURE__ */ new Set();
34066
- return eligible.filter((endpoint2) => endpoint2.uptime >= bar).sort((left, right) => right.uptime - left.uptime).map((endpoint2) => endpoint2.provider).filter((provider) => seen.has(provider) ? false : (seen.add(provider), true));
34249
+ return candidates.filter((endpoint2) => endpoint2.uptime >= bar).sort((left, right) => right.uptime - left.uptime).map((endpoint2) => endpoint2.provider).filter((provider) => seen.has(provider) ? false : (seen.add(provider), true));
34067
34250
  };
34068
34251
  const strict = atBar(OPENROUTER_UPTIME_BAR);
34069
- if (strict.length >= OPENROUTER_MIN_PROVIDERS) {
34252
+ if (strict.length >= OPENROUTER_MIN_PROVIDERS && (caching.length === 0 || caching.every((endpoint2) => endpoint2.uptime >= OPENROUTER_UPTIME_BAR))) {
34070
34253
  return { providers: strict, bar: OPENROUTER_UPTIME_BAR, contextLength };
34071
34254
  }
34072
34255
  const relaxed = atBar(OPENROUTER_UPTIME_BAR_RELAXED);
@@ -34088,20 +34271,24 @@ function openRouterModelLimits(endpoints, providers) {
34088
34271
  function openRouterRoutingFor(providers, allowFallbacks = true) {
34089
34272
  return {
34090
34273
  only: [...providers],
34091
- order: [...providers],
34274
+ // provider.order disables OpenRouter's session stickiness. Pi already
34275
+ // sends its session id; OpenRouter keeps the successful cache provider
34276
+ // and falls back on failure, within `only`, without bouncing to the old
34277
+ // first choice on every request. A recovery override remains explicit.
34278
+ ...allowFallbacks ? {} : { order: [...providers] },
34092
34279
  allow_fallbacks: allowFallbacks,
34093
34280
  require_parameters: false
34094
34281
  };
34095
34282
  }
34096
34283
  function openRouterRoutingCacheDir(runtimeDir) {
34097
- return resolve20(runtimeDir, "openrouter-routing");
34284
+ return resolve21(runtimeDir, "openrouter-routing");
34098
34285
  }
34099
34286
  function cachePath(cacheDir, model) {
34100
- return resolve20(cacheDir, `${model.replace(/[^A-Za-z0-9._-]+/g, "_")}.json`);
34287
+ return resolve21(cacheDir, `${model.replace(/[^A-Za-z0-9._-]+/g, "_")}.json`);
34101
34288
  }
34102
34289
  async function readCache(cacheDir, model) {
34103
34290
  try {
34104
- const parsed = JSON.parse(await readFile18(cachePath(cacheDir, model), "utf8"));
34291
+ const parsed = JSON.parse(await readFile19(cachePath(cacheDir, model), "utf8"));
34105
34292
  if (!parsed || typeof parsed !== "object")
34106
34293
  return void 0;
34107
34294
  const cached = parsed;
@@ -34111,6 +34298,7 @@ async function readCache(cacheDir, model) {
34111
34298
  const input = Array.isArray(cached.input) ? cached.input.filter((value) => value === "text" || value === "image") : cached.input === null ? null : void 0;
34112
34299
  const limits = cached.limits === null ? null : cachedLimits(cached.limits);
34113
34300
  return {
34301
+ policy: typeof cached.policy === "string" ? cached.policy : void 0,
34114
34302
  model,
34115
34303
  fetchedAt: cached.fetchedAt,
34116
34304
  providers: cached.providers,
@@ -34139,41 +34327,6 @@ async function writeCache(cacheDir, value) {
34139
34327
  mode: 384
34140
34328
  });
34141
34329
  }
34142
- function probeCachePath(cacheDir, model) {
34143
- return resolve20(cacheDir, `${model.replace(/[^A-Za-z0-9._-]+/g, "_")}.probe.json`);
34144
- }
34145
- async function readProbeCache(cacheDir, model) {
34146
- try {
34147
- const parsed = JSON.parse(await readFile18(probeCachePath(cacheDir, model), "utf8"));
34148
- if (!parsed || typeof parsed !== "object")
34149
- return void 0;
34150
- const cached = parsed;
34151
- if (cached.model !== model || typeof cached.fetchedAt !== "number")
34152
- return void 0;
34153
- if (!Array.isArray(cached.answered))
34154
- return void 0;
34155
- const answered = [];
34156
- for (const entry of cached.answered) {
34157
- if (!entry || typeof entry !== "object")
34158
- return void 0;
34159
- const { provider, latencyMs } = entry;
34160
- if (typeof provider !== "string" || !provider || typeof latencyMs !== "number") {
34161
- return void 0;
34162
- }
34163
- answered.push({ provider, latencyMs });
34164
- }
34165
- return { model, fetchedAt: cached.fetchedAt, answered };
34166
- } catch {
34167
- return void 0;
34168
- }
34169
- }
34170
- async function writeProbeCache(cacheDir, value) {
34171
- await mkdir14(cacheDir, { recursive: true, mode: 448 });
34172
- await writeFile11(probeCachePath(cacheDir, value.model), `${JSON.stringify(value, null, 2)}
34173
- `, {
34174
- mode: 384
34175
- });
34176
- }
34177
34330
  var PROBE_TOOL = {
34178
34331
  type: "function",
34179
34332
  function: {
@@ -34259,7 +34412,7 @@ async function probeOpenRouterProviders(input) {
34259
34412
  function decision(model, providers, bar, source, note, allowFallbacks = true, input, limits) {
34260
34413
  const criteria = bar === null ? "fallback pair" : `uptime \u2265${bar}%, tools`;
34261
34414
  const suffix = [
34262
- bar === OPENROUTER_UPTIME_BAR_RELAXED ? "bar lowered: fewer than 2 providers at 98%" : "",
34415
+ bar === OPENROUTER_UPTIME_BAR_RELAXED && !note?.startsWith("daily") ? "bar lowered: reliability fallback or cache continuity" : "",
34263
34416
  source === "cache" ? "cached" : "",
34264
34417
  source === "stale-cache" ? "stale cache" : "",
34265
34418
  note ?? ""
@@ -34278,7 +34431,7 @@ function decision(model, providers, bar, source, note, allowFallbacks = true, in
34278
34431
  async function resolveUptimeRouting(input) {
34279
34432
  const now2 = input.now ?? Date.now;
34280
34433
  const cached = await readCache(input.cacheDir, input.model);
34281
- if (cached?.input !== void 0 && cached.limits !== void 0 && now2() - cached.fetchedAt < OPENROUTER_ROUTING_CACHE_TTL_MS) {
34434
+ if (cached?.policy === ROUTING_POLICY && cached?.input !== void 0 && cached.limits !== void 0 && now2() - cached.fetchedAt < OPENROUTER_ROUTING_CACHE_TTL_MS) {
34282
34435
  return decision(input.model, cached.providers, cached.bar, "cache", void 0, true, cached.input ?? void 0, cached.limits ?? void 0);
34283
34436
  }
34284
34437
  let failure;
@@ -34297,8 +34450,16 @@ async function resolveUptimeRouting(input) {
34297
34450
  if (selected.providers.length === 0) {
34298
34451
  return decision(input.model, OPENROUTER_FALLBACK_PROVIDERS, null, "fallback", "no provider met the bar", true, modelInput);
34299
34452
  }
34453
+ if (cached?.policy === ROUTING_POLICY) {
34454
+ const retained = cached.providers.filter((provider) => selected.providers.includes(provider));
34455
+ selected.providers = [
34456
+ ...retained,
34457
+ ...selected.providers.filter((provider) => !retained.includes(provider))
34458
+ ];
34459
+ }
34300
34460
  const limits = openRouterModelLimits(endpoints, selected.providers);
34301
34461
  await writeCache(input.cacheDir, {
34462
+ policy: ROUTING_POLICY,
34302
34463
  model: input.model,
34303
34464
  fetchedAt: now2(),
34304
34465
  providers: selected.providers,
@@ -34316,62 +34477,106 @@ async function resolveUptimeRouting(input) {
34316
34477
  }
34317
34478
  return decision(input.model, OPENROUTER_FALLBACK_PROVIDERS, null, "fallback", `api unreachable: ${failure}`);
34318
34479
  }
34319
- var inFlightProbes = /* @__PURE__ */ new Map();
34320
- function answeringProviders(probe, candidates) {
34321
- return probe.answered.map((entry) => entry.provider).filter((provider) => candidates.includes(provider));
34480
+ function dailyCachePath(input) {
34481
+ return resolve21(input.cacheDir, `${input.model.replace(/[^A-Za-z0-9._-]+/g, "_")}.daily.json`);
34322
34482
  }
34323
- async function refreshAnswerProbe(input, base, apiKey) {
34324
- const now2 = input.now ?? Date.now;
34325
- const results = await probeOpenRouterProviders({
34326
- model: input.model,
34327
- providers: base.providers,
34328
- apiKey,
34329
- ...input.fetchImpl ? { fetchImpl: input.fetchImpl } : {},
34330
- ...input.now ? { now: input.now } : {},
34331
- ...input.probeTimeoutMs === void 0 ? {} : { timeoutMs: input.probeTimeoutMs },
34332
- ...input.probeMaxCandidates === void 0 ? {} : { maxCandidates: input.probeMaxCandidates }
34333
- });
34334
- const answered = results.filter((result) => result.answered).sort((left, right) => left.latencyMs - right.latencyMs).map((result) => ({ provider: result.provider, latencyMs: result.latencyMs }));
34335
- const silent = results.filter((result) => !result.answered);
34336
- if (answered.length === 0) {
34483
+ async function readDailyRouting(input) {
34484
+ try {
34485
+ const row = JSON.parse(await readFile19(dailyCachePath(input), "utf8"));
34486
+ if (row.policy !== "cost-daily-v1" || row.model !== input.model || !Number.isFinite(row.fetchedAt) || !Array.isArray(row.providers) || !row.providers.length || row.providers.length > 3 || !row.providers.every((provider) => typeof provider === "string" && provider.length > 0) || !Array.isArray(row.ranking) || !row.ranking.every((entry) => entry && typeof entry.provider === "string" && Number.isFinite(entry.effectiveInputPrice) && entry.effectiveInputPrice >= 0 && Number.isFinite(entry.cacheShare) && entry.cacheShare >= 0 && entry.cacheShare <= 1) || !row.providers.every((provider) => row.ranking.some((entry) => entry.provider === provider)))
34487
+ return void 0;
34488
+ return {
34489
+ policy: "cost-daily-v1",
34490
+ model: row.model,
34491
+ fetchedAt: row.fetchedAt,
34492
+ providers: row.providers,
34493
+ ranking: row.ranking,
34494
+ ...Array.isArray(row.input) ? { input: row.input.filter((value) => value === "text" || value === "image") } : {},
34495
+ ...cachedLimits(row.limits) ? { limits: cachedLimits(row.limits) } : {}
34496
+ };
34497
+ } catch {
34337
34498
  return void 0;
34338
34499
  }
34339
- await writeProbeCache(input.cacheDir, {
34500
+ }
34501
+ function dailyDecision(row, source) {
34502
+ return decision(row.model, row.providers, OPENROUTER_UPTIME_BAR_RELAXED, source, "daily effective input cost; seven-day cache shares; answer-probed", true, row.input, row.limits);
34503
+ }
34504
+ async function buildDailyRouting(input) {
34505
+ const now2 = input.now ?? Date.now;
34506
+ const response = await (input.fetchImpl ?? fetch)(`${OPENROUTER_ENDPOINTS_BASE_URL}/${input.model}/endpoints`, {
34507
+ signal: AbortSignal.timeout(input.timeoutMs ?? OPENROUTER_ROUTING_FETCH_TIMEOUT_MS)
34508
+ });
34509
+ if (!response.ok)
34510
+ throw new Error(`HTTP ${response.status}`);
34511
+ const { endpoints, contextLength, inputModalities } = parseOpenRouterEndpoints(await response.json());
34512
+ const eligible = [...new Set(endpoints.filter((endpoint2) => endpoint2.tools && endpoint2.uptime >= OPENROUTER_UPTIME_BAR_RELAXED && endpoint2.promptPrice !== void 0 && (contextLength === void 0 || endpoint2.contextLength >= contextLength)).map((endpoint2) => endpoint2.provider))];
34513
+ if (!eligible.length)
34514
+ throw new Error("no priced provider met the tools/context/95% gate");
34515
+ const [traffic, probes] = await Promise.all([
34516
+ readOpenRouterTraffic({
34517
+ model: input.model,
34518
+ cacheDir: input.cacheDir,
34519
+ ...input.historyRoomsDir ? { roomsDir: input.historyRoomsDir } : {},
34520
+ apiKey: input.apiKey,
34521
+ now: now2(),
34522
+ fetchImpl: input.fetchImpl,
34523
+ timeoutMs: input.timeoutMs
34524
+ }),
34525
+ probeOpenRouterProviders({
34526
+ model: input.model,
34527
+ providers: eligible,
34528
+ apiKey: input.apiKey,
34529
+ fetchImpl: input.fetchImpl,
34530
+ now: input.now,
34531
+ timeoutMs: input.probeTimeoutMs,
34532
+ // Gate every eligible provider once per day, rather than using the old
34533
+ // uptime-first six as a proxy for the cheapest qualified set.
34534
+ maxCandidates: input.probeMaxCandidates ?? eligible.length
34535
+ })
34536
+ ]);
34537
+ const ranking = rankOpenRouterProviders(endpoints, contextLength, traffic, probes.filter((probe) => probe.answered).map((probe) => probe.provider));
34538
+ if (!ranking.length)
34539
+ throw new Error("no eligible provider answered the text probe");
34540
+ const providers = ranking.slice(0, 3).map((row2) => row2.provider);
34541
+ const row = {
34542
+ policy: "cost-daily-v1",
34340
34543
  model: input.model,
34341
34544
  fetchedAt: now2(),
34342
- answered
34343
- }).catch(() => void 0);
34344
- const dropped = silent.length ? `dropped ${silent.map((result) => `${result.provider} (${result.note ?? "no answer"})`).join(", ")}` : "every candidate answered";
34345
- return decision(input.model, answered.map((entry) => entry.provider), base.bar, base.source, `answer-probed, fastest first; ${dropped}`, true, base.input, base.limits);
34545
+ providers,
34546
+ ranking,
34547
+ input: piInputModalities(inputModalities),
34548
+ limits: openRouterModelLimits(endpoints, providers)
34549
+ };
34550
+ await writePrivateFileAtomically(dailyCachePath(input), `${JSON.stringify(row, null, 2)}
34551
+ `).catch(() => void 0);
34552
+ return row;
34346
34553
  }
34554
+ var dailyAttempts = /* @__PURE__ */ new Map();
34347
34555
  async function resolveOpenRouterRouting(input) {
34348
- const base = await resolveUptimeRouting(input);
34556
+ const cached = await readDailyRouting(input);
34349
34557
  const override = input.providerOverride?.trim();
34350
34558
  if (override) {
34559
+ const base = cached ? dailyDecision(cached, "cache") : await resolveUptimeRouting(input);
34351
34560
  return decision(input.model, [override], base.bar, base.source, "pinned to one provider after an empty completion", false, base.input, base.limits);
34352
34561
  }
34353
- const apiKey = input.apiKey?.trim();
34354
- if (!apiKey || base.providers.length < 2)
34355
- return base;
34562
+ if (!input.apiKey?.trim())
34563
+ return resolveUptimeRouting(input);
34356
34564
  const now2 = input.now ?? Date.now;
34357
- const probe = await readProbeCache(input.cacheDir, input.model);
34358
- if (probe && now2() - probe.fetchedAt < OPENROUTER_PROBE_CACHE_TTL_MS) {
34359
- const answered = answeringProviders(probe, base.providers);
34360
- if (answered.length > 0) {
34361
- return decision(input.model, answered, base.bar, base.source, "answer-probed, cached", true, base.input, base.limits);
34362
- }
34363
- }
34565
+ if (cached && now2() - cached.fetchedAt < OPENROUTER_ROUTING_CACHE_TTL_MS)
34566
+ return dailyDecision(cached, "cache");
34364
34567
  const key = `${input.cacheDir}\0${input.model}`;
34365
- let refresh2 = inFlightProbes.get(key);
34366
- if (!refresh2) {
34367
- const tracked = refreshAnswerProbe(input, base, apiKey).catch(() => void 0).finally(() => {
34368
- if (inFlightProbes.get(key) === tracked)
34369
- inFlightProbes.delete(key);
34568
+ let attempt = dailyAttempts.get(key);
34569
+ if (!attempt || now2() - attempt.startedAt >= OPENROUTER_ROUTING_CACHE_TTL_MS) {
34570
+ const result = buildDailyRouting(input).then((row) => dailyDecision(row, "live")).catch(async (error) => {
34571
+ const base = cached ? dailyDecision(cached, "stale-cache") : await resolveUptimeRouting(input);
34572
+ return { ...base, line: `${base.line}; daily ranking unavailable: ${error instanceof Error ? error.message : String(error)}` };
34370
34573
  });
34371
- inFlightProbes.set(key, tracked);
34372
- refresh2 = tracked;
34574
+ attempt = { startedAt: now2(), result };
34575
+ dailyAttempts.set(key, attempt);
34373
34576
  }
34374
- return { ...base, refresh: refresh2 };
34577
+ if (cached)
34578
+ return { ...dailyDecision(cached, "stale-cache"), refresh: attempt.result };
34579
+ return attempt.result;
34375
34580
  }
34376
34581
  function withOpenRouterModelRouting(value, pin) {
34377
34582
  const root = value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
@@ -34422,7 +34627,7 @@ function openRouterRoutingInput(config, selection, fetchImpl, extra) {
34422
34627
  openRouterRouting: {
34423
34628
  model,
34424
34629
  cacheDir: config.openRouterRoutingCacheDir,
34425
- ...apiKey ? { apiKey } : {},
34630
+ ...apiKey ? { apiKey, historyRoomsDir: resolve21(config.openRouterRoutingCacheDir, "../rooms") } : {},
34426
34631
  ...fetchImpl ? { fetchImpl } : {},
34427
34632
  ...extra?.providerOverride ? { providerOverride: extra.providerOverride } : {},
34428
34633
  ...extra?.onDecision ? { onDecision: extra.onDecision } : {}
@@ -34431,9 +34636,9 @@ function openRouterRoutingInput(config, selection, fetchImpl, extra) {
34431
34636
  }
34432
34637
 
34433
34638
  // apps/body/dist/provider-key-store.js
34434
- import { chmod as chmod5, mkdir as mkdir15, readFile as readFile19, writeFile as writeFile12 } from "node:fs/promises";
34639
+ import { chmod as chmod5, mkdir as mkdir15, readFile as readFile20, writeFile as writeFile12 } from "node:fs/promises";
34435
34640
  import { homedir as homedir11 } from "node:os";
34436
- import { dirname as dirname16, resolve as resolve21 } from "node:path";
34641
+ import { dirname as dirname16, resolve as resolve22 } from "node:path";
34437
34642
  var PROVIDER_KEY_ENV_VARS = {
34438
34643
  openrouter: "OPENROUTER_API_KEY",
34439
34644
  openai: "OPENAI_API_KEY",
@@ -34443,12 +34648,12 @@ var PROVIDER_KEY_ENV_VARS = {
34443
34648
  };
34444
34649
  var GOOGLE_ENV_ALIAS = "GEMINI_API_KEY";
34445
34650
  function providerKeyStorePath(env = process.env) {
34446
- const configRoot = env.XDG_CONFIG_HOME?.trim() || resolve21(homedir11(), ".config");
34447
- return resolve21(configRoot, "beeline", "providers.json");
34651
+ const configRoot = env.XDG_CONFIG_HOME?.trim() || resolve22(homedir11(), ".config");
34652
+ return resolve22(configRoot, "beeline", "providers.json");
34448
34653
  }
34449
34654
  async function readProviderKeyStore(env = process.env) {
34450
34655
  const path = providerKeyStorePath(env);
34451
- const raw = await readFile19(path, "utf8").catch(() => void 0);
34656
+ const raw = await readFile20(path, "utf8").catch(() => void 0);
34452
34657
  if (!raw)
34453
34658
  return {};
34454
34659
  try {
@@ -34822,12 +35027,12 @@ function parseConnectSubscriptions(value) {
34822
35027
  ];
34823
35028
  }
34824
35029
  async function readMachineId(env = process.env) {
34825
- const configDir = resolve22(env.XDG_CONFIG_HOME ?? resolve22(homedir12(), ".config"), "beeline");
34826
- const machineIdPath = resolve22(configDir, "machine-id");
35030
+ const configDir = resolve23(env.XDG_CONFIG_HOME ?? resolve23(homedir12(), ".config"), "beeline");
35031
+ const machineIdPath = resolve23(configDir, "machine-id");
34827
35032
  let machineId;
34828
35033
  let machineName = hostname();
34829
35034
  try {
34830
- const existing = await readFile20(machineIdPath, "utf8");
35035
+ const existing = await readFile21(machineIdPath, "utf8");
34831
35036
  machineId = existing.trim();
34832
35037
  if (!/^[0-9a-f-]{32,}$/.test(machineId))
34833
35038
  throw new Error("invalid persisted machine id");
@@ -34896,7 +35101,7 @@ async function installCurrentRelease(fetchImpl) {
34896
35101
  });
34897
35102
  await activateRelease(layout, releaseId);
34898
35103
  return {
34899
- binary: resolve22(layout.binDir, "beeline"),
35104
+ binary: resolve23(layout.binDir, "beeline"),
34900
35105
  version: published.version ?? releaseId
34901
35106
  };
34902
35107
  }
@@ -34928,7 +35133,7 @@ async function writeProviderEnv(selection, agentPubkey) {
34928
35133
  const values = providerEnvironment(selection);
34929
35134
  if (Object.keys(values).length === 0)
34930
35135
  return void 0;
34931
- const path = resolve22(defaultSupervisorRoot(process.env), "beeline", "connect", `${agentPubkey}.env`);
35136
+ const path = resolve23(defaultSupervisorRoot(process.env), "beeline", "connect", `${agentPubkey}.env`);
34932
35137
  await mkdir16(dirname17(path), { recursive: true, mode: 448 });
34933
35138
  const contents = Object.entries(values).map(([key, value]) => `${key}=${JSON.stringify(value)}`).join("\n");
34934
35139
  await writeFile13(path, `${contents}
@@ -34998,7 +35203,7 @@ async function runConnectWizard(code, fetchImpl, eventSubscriptions, accessPolic
34998
35203
  await finishConnectedAgentPairing(baseUrl, pairingCode, grant.workspace_joined, eventSubscriptions, fetchImpl);
34999
35204
  const installedRelease = await brassSpinner("Installing the Beeline daemon\u2026", () => installCurrentRelease(fetchImpl), (release) => `Installed Beeline helper ${release.version}`);
35000
35205
  const llmEnvFile = await writeProviderEnv(selection, grant.agent_pubkey);
35001
- const grantPath = resolve22(defaultSupervisorRoot(process.env), "beeline", "connect", `grant-${process.pid}-${Date.now()}.json`);
35206
+ const grantPath = resolve23(defaultSupervisorRoot(process.env), "beeline", "connect", `grant-${process.pid}-${Date.now()}.json`);
35002
35207
  await writePrivateJson(grantPath, {
35003
35208
  agentSecretKey: grant.agent_secret_key,
35004
35209
  bodySecretKey: grant.body_secret_key,
@@ -35083,12 +35288,12 @@ async function runConnectFinishCommand(path) {
35083
35288
  throw new Error("connect-finish may run only from the canonical installed Beeline launcher");
35084
35289
  }
35085
35290
  try {
35086
- const grant = JSON.parse(await readFile20(resolve22(path), "utf8"));
35291
+ const grant = JSON.parse(await readFile21(resolve23(path), "utf8"));
35087
35292
  if (!isDevicePairingGrant(grant))
35088
35293
  throw new Error("device connection grant is invalid");
35089
35294
  const connected = await completeDevicePairing(grant);
35090
- await unlink5(resolve22(path));
35091
- const providerEnv = grant.llmEnvFile ? await readFile20(grant.llmEnvFile, "utf8").catch(() => "") : "";
35295
+ await unlink5(resolve23(path));
35296
+ const providerEnv = grant.llmEnvFile ? await readFile21(grant.llmEnvFile, "utf8").catch(() => "") : "";
35092
35297
  const apiKey = (/^OPENROUTER_API_KEY=(\S+)/m.exec(providerEnv)?.[1] ?? "").replace(/^["']|["']$/g, "");
35093
35298
  const model = openRouterModelId(grant.model, { OPENROUTER_API_KEY: apiKey });
35094
35299
  if (model) {
@@ -35114,11 +35319,11 @@ init_self_update();
35114
35319
  // apps/body/dist/machine-helper.js
35115
35320
  import { mkdir as mkdir30, rename as rename14, stat as stat12, writeFile as writeFile23 } from "node:fs/promises";
35116
35321
  import { homedir as homedir19 } from "node:os";
35117
- import { dirname as dirname31, resolve as resolve49 } from "node:path";
35322
+ import { dirname as dirname31, resolve as resolve50 } from "node:path";
35118
35323
 
35119
35324
  // apps/body/dist/agent-runtime.js
35120
35325
  import { homedir as homedir18 } from "node:os";
35121
- import { dirname as dirname30, join as join22, resolve as resolve47 } from "node:path";
35326
+ import { dirname as dirname30, join as join22, resolve as resolve48 } from "node:path";
35122
35327
 
35123
35328
  // apps/body/dist/model-availability.js
35124
35329
  var SECRET_VALUE = /(?:token|key|secret|password)=?[^\s,;]*/gi;
@@ -35180,8 +35385,8 @@ async function applyRuntimeModelPreflight(config, agent, selection, validate = v
35180
35385
 
35181
35386
  // apps/body/dist/model-catalog-sync.js
35182
35387
  import { createHash as createHash10 } from "node:crypto";
35183
- import { readFile as readFile21, writeFile as writeFile14 } from "node:fs/promises";
35184
- import { resolve as resolve23 } from "node:path";
35388
+ import { readFile as readFile22, writeFile as writeFile14 } from "node:fs/promises";
35389
+ import { resolve as resolve24 } from "node:path";
35185
35390
  var MODEL_CATALOG_PROBE_TIMEOUT_MS = 3e4;
35186
35391
  var MODEL_CATALOG_HASH_FILE = "model-catalog.sha256";
35187
35392
  function modelCatalogHash(options, selection, startupUnavailable) {
@@ -35206,7 +35411,7 @@ async function withTimeout(work, timeoutMs, what) {
35206
35411
  async function syncAgentModelCatalog(input) {
35207
35412
  const log2 = input.log ?? ((line) => console.log(line));
35208
35413
  const fetchCatalog = input.fetchCatalog ?? fetchAgentModelCatalog;
35209
- const hashPath = resolve23(input.runtimeDir, MODEL_CATALOG_HASH_FILE);
35414
+ const hashPath = resolve24(input.runtimeDir, MODEL_CATALOG_HASH_FILE);
35210
35415
  try {
35211
35416
  const configuration = await input.api.execute("getAgentConfiguration", {
35212
35417
  agentId: input.agentId
@@ -35218,7 +35423,7 @@ async function syncAgentModelCatalog(input) {
35218
35423
  const { catalog } = await withTimeout(fetchCatalog(input.agent, input.agentEnv, input.startupUnavailable ? void 0 : selection), input.timeoutMs ?? MODEL_CATALOG_PROBE_TIMEOUT_MS, "model catalog probe");
35219
35424
  const effectiveCatalog = input.startupUnavailable ? catalog : withEffectiveCurrentValues(catalog, selection);
35220
35425
  const hash = modelCatalogHash(effectiveCatalog, selection, input.startupUnavailable);
35221
- const previous = await readFile21(hashPath, "utf8").catch(() => "");
35426
+ const previous = await readFile22(hashPath, "utf8").catch(() => "");
35222
35427
  if (!input.force && previous.trim() === hash)
35223
35428
  return "unchanged";
35224
35429
  await input.api.execute("postAgentModelCatalog", {
@@ -35252,10 +35457,10 @@ var LOGIN_URL = /https:\/\/login\.tailscale\.com\/[A-Za-z0-9_/-]+/u;
35252
35457
  function clipped(value) {
35253
35458
  return value.length <= OUTPUT_LIMIT ? value : value.slice(value.length - OUTPUT_LIMIT);
35254
35459
  }
35255
- var runTailscaleCommand = (command, args) => new Promise((resolve52) => {
35460
+ var runTailscaleCommand = (command, args) => new Promise((resolve53) => {
35256
35461
  execFile9(command, [...args], { timeout: COMMAND_TIMEOUT_MS, maxBuffer: OUTPUT_LIMIT * 2 }, (error, stdout6, stderr) => {
35257
35462
  const code = error && "code" in error && typeof error.code === "number" ? error.code : error ? null : 0;
35258
- resolve52({ code, stdout: clipped(stdout6), stderr: clipped(stderr) });
35463
+ resolve53({ code, stdout: clipped(stdout6), stderr: clipped(stderr) });
35259
35464
  });
35260
35465
  });
35261
35466
  function loginUrlFrom(status, output) {
@@ -36027,8 +36232,8 @@ import { dirname as dirname18 } from "node:path";
36027
36232
  // apps/body/dist/browser-share.js
36028
36233
  var shares = /* @__PURE__ */ new Map();
36029
36234
  function opened(socket) {
36030
- return new Promise((resolve52, reject) => {
36031
- socket.once("open", resolve52);
36235
+ return new Promise((resolve53, reject) => {
36236
+ socket.once("open", resolve53);
36032
36237
  socket.once("error", reject);
36033
36238
  });
36034
36239
  }
@@ -36204,18 +36409,18 @@ var BrowserShareHost = class {
36204
36409
  })().catch((error) => socket.end(JSON.stringify({ error: error instanceof Error ? error.message : String(error) })));
36205
36410
  });
36206
36411
  });
36207
- await new Promise((resolve52, reject) => {
36412
+ await new Promise((resolve53, reject) => {
36208
36413
  this.server.once("error", reject);
36209
36414
  this.server.listen(this.socketPath, () => {
36210
36415
  this.server.off("error", reject);
36211
- resolve52();
36416
+ resolve53();
36212
36417
  });
36213
36418
  });
36214
36419
  chmodSync2(this.socketPath, 384);
36215
36420
  }
36216
36421
  async stop() {
36217
36422
  if (this.server)
36218
- await new Promise((resolve52) => this.server.close(() => resolve52()));
36423
+ await new Promise((resolve53) => this.server.close(() => resolve53()));
36219
36424
  this.server = void 0;
36220
36425
  rmSync3(this.socketPath, { force: true });
36221
36426
  }
@@ -36225,16 +36430,16 @@ var BrowserShareHost = class {
36225
36430
  import { execFile as execFile19 } from "node:child_process";
36226
36431
  import { createHash as createHash17 } from "node:crypto";
36227
36432
  import { existsSync as existsSync10, mkdirSync as mkdirSync4 } from "node:fs";
36228
- import { lstat as lstat9, mkdir as mkdir28, readdir as readdir13, realpath as realpath4, rm as rm20 } from "node:fs/promises";
36229
- import { dirname as dirname28, relative as relative4, resolve as resolve42, sep as sep4 } from "node:path";
36433
+ import { lstat as lstat10, mkdir as mkdir28, readdir as readdir14, realpath as realpath4, rm as rm20 } from "node:fs/promises";
36434
+ import { dirname as dirname28, relative as relative4, resolve as resolve43, sep as sep4 } from "node:path";
36230
36435
  import { promisify as promisify13 } from "node:util";
36231
36436
 
36232
36437
  // apps/body/dist/grant-runner.js
36233
36438
  import { execFile as execFile11 } from "node:child_process";
36234
36439
  import { createHash as createHash11, randomBytes as randomBytes9, randomUUID as randomUUID11 } from "node:crypto";
36235
- import { chmod as chmod7, mkdir as mkdir17, readFile as readFile22, readdir as readdir6, rename as rename9, rm as rm13, rmdir, stat as stat9, writeFile as writeFile15 } from "node:fs/promises";
36440
+ import { chmod as chmod7, mkdir as mkdir17, readFile as readFile23, readdir as readdir7, rename as rename9, rm as rm13, rmdir, stat as stat9, writeFile as writeFile15 } from "node:fs/promises";
36236
36441
  import { createServer as createServer4 } from "node:http";
36237
- import { dirname as dirname20, resolve as resolve25 } from "node:path";
36442
+ import { dirname as dirname20, resolve as resolve26 } from "node:path";
36238
36443
 
36239
36444
  // packages/api-contract/dist/surface-capabilities.js
36240
36445
  var SURFACE_CAPABILITY_TABLE = {
@@ -36265,7 +36470,7 @@ function surfaceAllows(surface, capability) {
36265
36470
  import { execFile as execFile10, spawnSync } from "node:child_process";
36266
36471
  import { lstatSync as lstatSync3, readdirSync as readdirSync3, readFileSync as readFileSync8, rmSync as rmSync4, writeFileSync as writeFileSync3 } from "node:fs";
36267
36472
  import { homedir as homedir13 } from "node:os";
36268
- import { basename as basename7, dirname as dirname19, isAbsolute as isAbsolute3, relative, resolve as resolve24, sep } from "node:path";
36473
+ import { basename as basename7, dirname as dirname19, isAbsolute as isAbsolute3, relative, resolve as resolve25, sep } from "node:path";
36269
36474
  var DEFAULT_SANDBOX_POLICY = "bwrap";
36270
36475
  function isSandboxPolicy(value) {
36271
36476
  return value === "bwrap" || value === "off";
@@ -36310,7 +36515,7 @@ function harnessHomeStateDirs(agentCommand, home = homedir13()) {
36310
36515
  return [];
36311
36516
  for (const { match, dirs } of HARNESS_HOME_STATE_DIRS) {
36312
36517
  if (match.test(agentCommand))
36313
- return dirs.map((dir) => resolve24(home, dir));
36518
+ return dirs.map((dir) => resolve25(home, dir));
36314
36519
  }
36315
36520
  return [];
36316
36521
  }
@@ -36330,10 +36535,10 @@ function credentialMaskPaths(extraPaths, home = homedir13(), stat14 = (path) =>
36330
36535
  return void 0;
36331
36536
  }
36332
36537
  }, requiredPaths = []) {
36333
- const required = new Set(requiredPaths.map((path) => resolve24(path)));
36538
+ const required = new Set(requiredPaths.map((path) => resolve25(path)));
36334
36539
  const candidates = [
36335
- ...KNOWN_CREDENTIAL_MASK_PATHS.map((entry) => resolve24(home, entry)),
36336
- ...(extraPaths ?? []).map((entry) => resolve24(entry))
36540
+ ...KNOWN_CREDENTIAL_MASK_PATHS.map((entry) => resolve25(home, entry)),
36541
+ ...(extraPaths ?? []).map((entry) => resolve25(entry))
36337
36542
  ];
36338
36543
  const seen = /* @__PURE__ */ new Set();
36339
36544
  const masks = [];
@@ -36358,10 +36563,10 @@ function siblingAgentMaskPaths(ownRuntimeDir, listAgentDirs = (agentsRoot) => {
36358
36563
  return [];
36359
36564
  }
36360
36565
  }) {
36361
- const own = resolve24(ownRuntimeDir);
36566
+ const own = resolve25(ownRuntimeDir);
36362
36567
  const agentsRoot = dirname19(own);
36363
36568
  const ownName = basename7(own).toLowerCase();
36364
- return listAgentDirs(agentsRoot).filter((name) => name.toLowerCase() !== ownName).map((name) => ({ path: resolve24(agentsRoot, name), kind: "dir" })).sort((a2, b) => a2.path.localeCompare(b.path));
36569
+ return listAgentDirs(agentsRoot).filter((name) => name.toLowerCase() !== ownName).map((name) => ({ path: resolve25(agentsRoot, name), kind: "dir" })).sort((a2, b) => a2.path.localeCompare(b.path));
36365
36570
  }
36366
36571
  var DEFAULT_SANDBOX_DEVICES = ["/dev/kvm"];
36367
36572
  function grantedSandboxDevices(result) {
@@ -36391,7 +36596,7 @@ function sandboxDevicePath(target) {
36391
36596
  const trimmed = target.trim();
36392
36597
  if (!isAbsolute3(trimmed))
36393
36598
  return void 0;
36394
- const path = resolve24(trimmed);
36599
+ const path = resolve25(trimmed);
36395
36600
  return path.startsWith("/dev/") ? path : void 0;
36396
36601
  }
36397
36602
  function isUnderTmp(path) {
@@ -36403,7 +36608,7 @@ function normalize(paths) {
36403
36608
  for (const path of paths) {
36404
36609
  if (!path)
36405
36610
  continue;
36406
- seen.add(resolve24(path));
36611
+ seen.add(resolve25(path));
36407
36612
  }
36408
36613
  return Array.from(seen).sort();
36409
36614
  }
@@ -36440,14 +36645,14 @@ function sandboxMountPlan(spec) {
36440
36645
  const requiredMounts = [];
36441
36646
  const boundaryMasks = [];
36442
36647
  if (shared) {
36443
- const assetRoot = resolve24(shared.assetRoot);
36444
- const agentsRoot = dirname19(resolve24(shared.agentRuntimeDir));
36648
+ const assetRoot = resolve25(shared.assetRoot);
36649
+ const agentsRoot = dirname19(resolve25(shared.agentRuntimeDir));
36445
36650
  const workspacesRoot = dirname19(dirname19(assetRoot));
36446
36651
  boundaryMasks.push({ path: workspacesRoot, kind: "dir" }, { path: agentsRoot, kind: "dir" });
36447
36652
  const add = (path, mode, target = path) => {
36448
- requiredMounts.push({ source: resolve24(path), target: resolve24(target), mode });
36653
+ requiredMounts.push({ source: resolve25(path), target: resolve25(target), mode });
36449
36654
  };
36450
- const cwd = resolve24(spec.cwd);
36655
+ const cwd = resolve25(spec.cwd);
36451
36656
  const relativeCwd = relative(agentsRoot, cwd);
36452
36657
  if (relativeCwd === "" || relativeCwd !== ".." && !relativeCwd.startsWith(`..${sep}`) && !isAbsolute3(relativeCwd))
36453
36658
  add(cwd, spec.mode === "edit" ? "bind" : "ro-bind");
@@ -36456,34 +36661,34 @@ function sandboxMountPlan(spec) {
36456
36661
  add(shared.privateRoot, "bind");
36457
36662
  if (shared.privateAssetRoot && shared.isolatedCategories?.length)
36458
36663
  add(shared.privateAssetRoot, "bind");
36459
- add(resolve24(shared.agentRuntimeDir, "runtime.json"), "ro-bind");
36664
+ add(resolve25(shared.agentRuntimeDir, "runtime.json"), "ro-bind");
36460
36665
  for (const path of spec.additionalWritablePaths ?? []) {
36461
- const rel = relative(cwd, resolve24(path));
36666
+ const rel = relative(cwd, resolve25(path));
36462
36667
  if (rel && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute3(rel))
36463
36668
  add(path, "bind");
36464
36669
  }
36465
- add(resolve24(assetRoot, "cache"), "bind");
36466
- const source = (category, suffix) => shared.privateAssetRoot && shared.isolatedCategories?.includes(category) ? resolve24(shared.privateAssetRoot, suffix) : resolve24(assetRoot, suffix);
36670
+ add(resolve25(assetRoot, "cache"), "bind");
36671
+ const source = (category, suffix) => shared.privateAssetRoot && shared.isolatedCategories?.includes(category) ? resolve25(shared.privateAssetRoot, suffix) : resolve25(assetRoot, suffix);
36467
36672
  if (shared.privateAssetRoot) {
36468
36673
  for (const suffix of shared.isolatedCategories?.includes("package-cache") ? PACKAGE_CACHE_DIRS : [])
36469
- add(resolve24(shared.privateAssetRoot, "cache", suffix), "bind", resolve24(assetRoot, "cache", suffix));
36674
+ add(resolve25(shared.privateAssetRoot, "cache", suffix), "bind", resolve25(assetRoot, "cache", suffix));
36470
36675
  for (const [category, suffix] of [
36471
36676
  ["codex-download-cache", "cache/codex/download"],
36472
36677
  ["codex-plugin-cache", "cache/codex/plugins"]
36473
36678
  ]) {
36474
36679
  if (shared.isolatedCategories?.includes(category))
36475
- add(resolve24(shared.privateAssetRoot, suffix), "bind", resolve24(assetRoot, suffix));
36680
+ add(resolve25(shared.privateAssetRoot, suffix), "bind", resolve25(assetRoot, suffix));
36476
36681
  }
36477
36682
  }
36478
36683
  if (shared.codexHome) {
36479
- add(source("codex-download-cache", "cache/codex/download"), "bind", resolve24(shared.codexHome, "cache"));
36480
- add(source("codex-plugin-cache", "cache/codex/plugins"), "bind", resolve24(shared.codexHome, "plugins/cache"));
36684
+ add(source("codex-download-cache", "cache/codex/download"), "bind", resolve25(shared.codexHome, "cache"));
36685
+ add(source("codex-plugin-cache", "cache/codex/plugins"), "bind", resolve25(shared.codexHome, "plugins/cache"));
36481
36686
  }
36482
36687
  if (shared.packageHome) {
36483
- add(source("package-cache", "cache/cargo/registry"), "bind", resolve24(shared.packageHome, ".cargo/registry"));
36688
+ add(source("package-cache", "cache/cargo/registry"), "bind", resolve25(shared.packageHome, ".cargo/registry"));
36484
36689
  }
36485
36690
  for (const name of ["tools", "avd-base"])
36486
- add(resolve24(assetRoot, name), "ro-bind");
36691
+ add(resolve25(assetRoot, name), "ro-bind");
36487
36692
  }
36488
36693
  return {
36489
36694
  ...spec.mode === "edit" ? { rootWritable: true } : {},
@@ -36491,7 +36696,7 @@ function sandboxMountPlan(spec) {
36491
36696
  writable,
36492
36697
  quotaTmpfs: spec.workbench ? [
36493
36698
  {
36494
- target: resolve24(spec.workbench.dir),
36699
+ target: resolve25(spec.workbench.dir),
36495
36700
  maxBytes: spec.workbench.maxBytes,
36496
36701
  maxInodes: spec.workbench.maxInodes,
36497
36702
  blockGit: true
@@ -36555,7 +36760,7 @@ function buildBwrapArgv(input) {
36555
36760
  for (const binding of quotaTmpfs) {
36556
36761
  args.push("--dir", binding.target, "--size", String(binding.maxBytes), "--tmpfs", binding.target);
36557
36762
  if (binding.blockGit)
36558
- args.push("--ro-bind", "/dev/null", resolve24(binding.target, ".git"));
36763
+ args.push("--ro-bind", "/dev/null", resolve25(binding.target, ".git"));
36559
36764
  }
36560
36765
  args.push("--chdir", input.cwd);
36561
36766
  args.push("--die-with-parent");
@@ -36627,7 +36832,7 @@ var INSTALL_RETRY_AFTER_HOURS = 24;
36627
36832
  var INSTALL_RETRY_AFTER_MS = INSTALL_RETRY_AFTER_HOURS * 60 * 6e4;
36628
36833
  var INSTALL_FAILURE_MARKER = "bubblewrap-install-failed";
36629
36834
  function installFailureMarker(stateDir) {
36630
- return resolve24(stateDir, INSTALL_FAILURE_MARKER);
36835
+ return resolve25(stateDir, INSTALL_FAILURE_MARKER);
36631
36836
  }
36632
36837
  function readInstallFailure(stateDir) {
36633
36838
  if (!stateDir)
@@ -36656,7 +36861,7 @@ function clearInstallFailure(stateDir) {
36656
36861
  } catch {
36657
36862
  }
36658
36863
  }
36659
- var runSandboxInstallCommand = (command, args) => new Promise((resolve52) => {
36864
+ var runSandboxInstallCommand = (command, args) => new Promise((resolve53) => {
36660
36865
  execFile10(command, [...args], {
36661
36866
  timeout: INSTALL_TIMEOUT_MS,
36662
36867
  maxBuffer: INSTALL_OUTPUT_LIMIT * 2,
@@ -36666,7 +36871,7 @@ var runSandboxInstallCommand = (command, args) => new Promise((resolve52) => {
36666
36871
  }, (error, stdout6, stderr) => {
36667
36872
  const code = error && "code" in error && typeof error.code === "number" ? error.code : error ? null : 0;
36668
36873
  const output = [stdout6, stderr].join("").trim();
36669
- resolve52({ code, output: output || (error ? error.message : "") });
36874
+ resolve53({ code, output: output || (error ? error.message : "") });
36670
36875
  });
36671
36876
  });
36672
36877
  function lastLine2(output, fallback) {
@@ -36775,10 +36980,10 @@ var SANDBOX_STARTED_SCRIPT = ['printf "%s\\n" "$1" >&2', "shift", 'exec "$@"'].j
36775
36980
  var ROOM_SANDBOX_UNAVAILABLE = "this Room cannot run granted commands: a Room promises a read-only filesystem and that promise is enforced by bubblewrap, which is not usable on this host. Open a corner with open_corner and run it there, where writes belong.";
36776
36981
  var ROOM_WRITE_REFUSED_NOTE = "[beeline] the Room filesystem is read-only outside your scratch directory, so this write was refused by the kernel. Open a corner with open_corner to change files.";
36777
36982
  function operatorSecretsPath(env = process.env) {
36778
- return resolve25(dirname20(providerKeyStorePath(env)), "secrets.json");
36983
+ return resolve26(dirname20(providerKeyStorePath(env)), "secrets.json");
36779
36984
  }
36780
36985
  async function readOperatorSecrets(env = process.env) {
36781
- const raw = await readFile22(operatorSecretsPath(env), "utf8").catch(() => void 0);
36986
+ const raw = await readFile23(operatorSecretsPath(env), "utf8").catch(() => void 0);
36782
36987
  if (!raw)
36783
36988
  return {};
36784
36989
  try {
@@ -36991,7 +37196,7 @@ ${ROOM_WRITE_REFUSED_NOTE}` : outcome.output, secrets), cap);
36991
37196
  return;
36992
37197
  let bytes;
36993
37198
  for (const candidate of candidates) {
36994
- bytes = await readFile22(candidate).catch(() => void 0);
37199
+ bytes = await readFile23(candidate).catch(() => void 0);
36995
37200
  if (bytes)
36996
37201
  break;
36997
37202
  }
@@ -37011,8 +37216,8 @@ function scriptCandidates(cwd, scratch, argv) {
37011
37216
  if (!argument)
37012
37217
  return [];
37013
37218
  const paths = [
37014
- resolve25(cwd, argument.path),
37015
- ...scratch ? [resolve25(scratch, argument.path)] : []
37219
+ resolve26(cwd, argument.path),
37220
+ ...scratch ? [resolve26(scratch, argument.path)] : []
37016
37221
  ];
37017
37222
  return [...new Set(paths)];
37018
37223
  }
@@ -37194,13 +37399,13 @@ function captureConnectionUsage(recorder, turn, calls) {
37194
37399
  }
37195
37400
 
37196
37401
  // apps/body/dist/model-context-window.js
37197
- import { readFile as readFile23 } from "node:fs/promises";
37402
+ import { readFile as readFile24 } from "node:fs/promises";
37198
37403
  import { join as join12 } from "node:path";
37199
37404
  async function modelContextWindowTokens(model, piHome) {
37200
37405
  if (!model || !piHome)
37201
37406
  return void 0;
37202
37407
  try {
37203
- const catalog = JSON.parse(await readFile23(join12(piHome, "models.json"), "utf8"));
37408
+ const catalog = JSON.parse(await readFile24(join12(piHome, "models.json"), "utf8"));
37204
37409
  const parts = model.split("/");
37205
37410
  const preferredProvider = parts.length > 2 ? parts.shift() : void 0;
37206
37411
  const modelId = parts.join("/");
@@ -37216,11 +37421,11 @@ async function modelContextWindowTokens(model, piHome) {
37216
37421
  }
37217
37422
 
37218
37423
  // apps/body/dist/turn-usage.js
37219
- import { readFile as readFile25 } from "node:fs/promises";
37424
+ import { readFile as readFile26 } from "node:fs/promises";
37220
37425
 
37221
37426
  // apps/body/dist/pi-turn-record.js
37222
- import { readdir as readdir7, readFile as readFile24 } from "node:fs/promises";
37223
- import { resolve as resolve26 } from "node:path";
37427
+ import { readdir as readdir8, readFile as readFile25 } from "node:fs/promises";
37428
+ import { resolve as resolve27 } from "node:path";
37224
37429
  function summarizeProviderError(errorMessage2) {
37225
37430
  const trimmed = errorMessage2.trim();
37226
37431
  const statusMatch = /^(\d{3}):\s*([\s\S]*)$/.exec(trimmed);
@@ -37247,7 +37452,7 @@ async function piSessionFilePath(agentEnv, sessionId) {
37247
37452
  }
37248
37453
  async function sessionFileFromMap(home, sessionId) {
37249
37454
  try {
37250
- const raw = await readFile24(resolve26(home, ".pi", "pi-acp", "session-map.json"), "utf8");
37455
+ const raw = await readFile25(resolve27(home, ".pi", "pi-acp", "session-map.json"), "utf8");
37251
37456
  const map = JSON.parse(raw);
37252
37457
  const file = map.sessions?.[sessionId]?.sessionFile;
37253
37458
  return typeof file === "string" && file ? file : void 0;
@@ -37256,25 +37461,25 @@ async function sessionFileFromMap(home, sessionId) {
37256
37461
  }
37257
37462
  }
37258
37463
  async function sessionFileFromLayout(piDir, sessionId) {
37259
- const sessionsRoot = resolve26(piDir, "sessions");
37464
+ const sessionsRoot = resolve27(piDir, "sessions");
37260
37465
  const suffix = `_${sessionId}.jsonl`;
37261
37466
  let projects;
37262
37467
  try {
37263
- projects = await readdir7(sessionsRoot);
37468
+ projects = await readdir8(sessionsRoot);
37264
37469
  } catch {
37265
37470
  return void 0;
37266
37471
  }
37267
37472
  for (const project of projects) {
37268
- const dir = resolve26(sessionsRoot, project);
37473
+ const dir = resolve27(sessionsRoot, project);
37269
37474
  let files;
37270
37475
  try {
37271
- files = await readdir7(dir);
37476
+ files = await readdir8(dir);
37272
37477
  } catch {
37273
37478
  continue;
37274
37479
  }
37275
37480
  const match = files.find((file) => file.endsWith(suffix));
37276
37481
  if (match)
37277
- return resolve26(dir, match);
37482
+ return resolve27(dir, match);
37278
37483
  }
37279
37484
  return void 0;
37280
37485
  }
@@ -37289,7 +37494,7 @@ async function readPiTurnRecord(input) {
37289
37494
  return void 0;
37290
37495
  let raw;
37291
37496
  try {
37292
- raw = await readFile24(file, "utf8");
37497
+ raw = await readFile25(file, "utf8");
37293
37498
  } catch {
37294
37499
  return void 0;
37295
37500
  }
@@ -37348,7 +37553,7 @@ async function readUsageCalls(input, latestTurn) {
37348
37553
  const file = await piSessionFilePath(input.agentEnv, input.sessionId);
37349
37554
  if (!file)
37350
37555
  return latestTurn ? void 0 : [];
37351
- const raw = await readFile25(file, "utf8").catch(() => void 0);
37556
+ const raw = await readFile26(file, "utf8").catch(() => void 0);
37352
37557
  if (raw === void 0)
37353
37558
  return void 0;
37354
37559
  const calls = [];
@@ -37576,11 +37781,11 @@ async function runServerCommandIntake(options) {
37576
37781
  if (attempt === 3)
37577
37782
  throw error;
37578
37783
  const waitMs = Math.max(250 * 2 ** attempt, error instanceof DaemonApiError ? error.retryAfterMs ?? 0 : 0);
37579
- await new Promise((resolve52) => {
37784
+ await new Promise((resolve53) => {
37580
37785
  const done = () => {
37581
37786
  clearTimeout(timer);
37582
37787
  signal?.removeEventListener("abort", done);
37583
- resolve52();
37788
+ resolve53();
37584
37789
  };
37585
37790
  const timer = setTimeout(done, waitMs);
37586
37791
  signal?.addEventListener("abort", done, { once: true });
@@ -37682,11 +37887,11 @@ async function runServerCommandIntake(options) {
37682
37887
  }
37683
37888
  }
37684
37889
  options.onPoll?.();
37685
- const reconcile = await new Promise((resolve52) => {
37890
+ const reconcile = await new Promise((resolve53) => {
37686
37891
  const done = (needed) => {
37687
37892
  signal?.removeEventListener("abort", aborted);
37688
37893
  wake = void 0;
37689
- resolve52(needed);
37894
+ resolve53(needed);
37690
37895
  };
37691
37896
  const aborted = () => done(false);
37692
37897
  wake = done;
@@ -37729,9 +37934,9 @@ async function runServerCommandIntake(options) {
37729
37934
  import { execFile as execFile17 } from "node:child_process";
37730
37935
  import { createHash as createHash16 } from "node:crypto";
37731
37936
  import { existsSync as existsSync9 } from "node:fs";
37732
- import { mkdir as mkdir27, readFile as readFile32, writeFile as writeFile21 } from "node:fs/promises";
37937
+ import { mkdir as mkdir27, readFile as readFile33, writeFile as writeFile21 } from "node:fs/promises";
37733
37938
  import { homedir as homedir17, hostname as hostname4 } from "node:os";
37734
- import { dirname as dirname26, join as join20, resolve as resolve40 } from "node:path";
37939
+ import { dirname as dirname26, join as join20, resolve as resolve41 } from "node:path";
37735
37940
  import { promisify as promisify11 } from "node:util";
37736
37941
 
37737
37942
  // apps/body/dist/machine-host.js
@@ -37739,16 +37944,16 @@ import { execFile as execFile12 } from "node:child_process";
37739
37944
  import { hostname as hostname2 } from "node:os";
37740
37945
  async function machineHost() {
37741
37946
  const local = hostname2();
37742
- const tailscaleName = await new Promise((resolve52) => {
37947
+ const tailscaleName = await new Promise((resolve53) => {
37743
37948
  execFile12("tailscale", ["status", "--json"], { timeout: 1500, maxBuffer: 64 * 1024 }, (error, stdout6) => {
37744
37949
  if (error)
37745
- return resolve52(void 0);
37950
+ return resolve53(void 0);
37746
37951
  try {
37747
37952
  const status = JSON.parse(stdout6);
37748
37953
  const name = status.BackendState === "Running" ? status.Self?.DNSName?.replace(/\.$/, "") : void 0;
37749
- resolve52(name || void 0);
37954
+ resolve53(name || void 0);
37750
37955
  } catch {
37751
- resolve52(void 0);
37956
+ resolve53(void 0);
37752
37957
  }
37753
37958
  });
37754
37959
  });
@@ -38555,9 +38760,9 @@ function stringify(obj, { maxDepth = 1e3, numbersAsFloat = false } = {}) {
38555
38760
 
38556
38761
  // apps/body/dist/agent-home.js
38557
38762
  import { createHash as createHash13, randomUUID as randomUUID13 } from "node:crypto";
38558
- import { chmod as chmod8, copyFile, lstat as lstat5, mkdir as mkdir19, readFile as readFile26, readlink, readdir as readdir8, realpath as realpath2, rename as rename10, rm as rm14, symlink as symlink2, unlink as unlink6, writeFile as writeFile17 } from "node:fs/promises";
38763
+ import { chmod as chmod8, copyFile, lstat as lstat6, mkdir as mkdir19, readFile as readFile27, readlink, readdir as readdir9, realpath as realpath2, rename as rename10, rm as rm14, symlink as symlink2, unlink as unlink6, writeFile as writeFile17 } from "node:fs/promises";
38559
38764
  import { homedir as homedir14 } from "node:os";
38560
- import { basename as basename8, dirname as dirname22, join as join15, relative as relative2, resolve as resolve30, sep as sep2 } from "node:path";
38765
+ import { basename as basename8, dirname as dirname22, join as join15, relative as relative2, resolve as resolve31, sep as sep2 } from "node:path";
38561
38766
 
38562
38767
  // apps/body/dist/draw-avatar-skill.js
38563
38768
  var DRAW_AVATAR_SKILL_NAME = "draw-avatar";
@@ -38647,7 +38852,7 @@ set_avatar renders bounded geometry to durable image bytes and replaces your cur
38647
38852
  // apps/body/dist/android-agent-env.js
38648
38853
  import { createHash as createHash12 } from "node:crypto";
38649
38854
  import { existsSync as existsSync7 } from "node:fs";
38650
- import { delimiter as delimiter2, resolve as resolve27 } from "node:path";
38855
+ import { delimiter as delimiter2, resolve as resolve28 } from "node:path";
38651
38856
  var ANDROID_FIRST_EMULATOR_PORT = 5600;
38652
38857
  var ANDROID_PORT_SLOTS = 100;
38653
38858
  function androidAgentEnv(input) {
@@ -38655,25 +38860,25 @@ function androidAgentEnv(input) {
38655
38860
  const sdk = [
38656
38861
  env.ANDROID_HOME,
38657
38862
  env.ANDROID_SDK_ROOT,
38658
- resolve27(input.operatorHome, "android-sdk"),
38659
- resolve27(input.operatorHome, "Android/Sdk")
38660
- ].find((path) => path && existsSync7(resolve27(path, "platform-tools/adb")));
38863
+ resolve28(input.operatorHome, "android-sdk"),
38864
+ resolve28(input.operatorHome, "Android/Sdk")
38865
+ ].find((path) => path && existsSync7(resolve28(path, "platform-tools/adb")));
38661
38866
  if (!sdk)
38662
38867
  return {};
38663
- const emulatorHome = env.ANDROID_EMULATOR_HOME ?? resolve27(input.operatorHome, ".android");
38664
- const slot = createHash12("sha256").update(resolve27(input.root)).digest().readUInt32BE(0) % ANDROID_PORT_SLOTS;
38868
+ const emulatorHome = env.ANDROID_EMULATOR_HOME ?? resolve28(input.operatorHome, ".android");
38869
+ const slot = createHash12("sha256").update(resolve28(input.root)).digest().readUInt32BE(0) % ANDROID_PORT_SLOTS;
38665
38870
  const emulatorPort = ANDROID_FIRST_EMULATOR_PORT + slot * 4;
38666
38871
  return {
38667
38872
  ANDROID_HOME: sdk,
38668
38873
  ANDROID_SDK_ROOT: sdk,
38669
38874
  ANDROID_EMULATOR_HOME: emulatorHome,
38670
- ANDROID_AVD_HOME: env.ANDROID_AVD_HOME ?? resolve27(emulatorHome, "avd"),
38875
+ ANDROID_AVD_HOME: env.ANDROID_AVD_HOME ?? resolve28(emulatorHome, "avd"),
38671
38876
  ANDROID_ADB_SERVER_PORT: String(emulatorPort + 2),
38672
38877
  ADB_EMU: "0",
38673
38878
  BEELINE_ANDROID_EMULATOR_PORT: String(emulatorPort),
38674
38879
  PATH: [
38675
- resolve27(sdk, "platform-tools"),
38676
- resolve27(sdk, "emulator"),
38880
+ resolve28(sdk, "platform-tools"),
38881
+ resolve28(sdk, "emulator"),
38677
38882
  input.inheritedPath ?? env.PATH
38678
38883
  ].filter(Boolean).join(delimiter2)
38679
38884
  };
@@ -38681,7 +38886,7 @@ function androidAgentEnv(input) {
38681
38886
 
38682
38887
  // apps/body/dist/beeline-skill.js
38683
38888
  import { readFileSync as readFileSync9 } from "node:fs";
38684
- import { resolve as resolve28 } from "node:path";
38889
+ import { resolve as resolve29 } from "node:path";
38685
38890
  var USING_BEELINE_SKILL_NAME = "using-beeline";
38686
38891
  var BEELINE_TRIAGE_SKILL_NAME = "beeline-triage";
38687
38892
  var BEELINE_REVIEW_SKILL_NAME = "beeline-review";
@@ -38700,7 +38905,7 @@ function runningBeelineReleaseId(env = process.env, read2 = (path) => readFileSy
38700
38905
  const lib = env.BEELINE_LIB_DIR;
38701
38906
  if (!lib)
38702
38907
  return "source";
38703
- const manifest = JSON.parse(read2(resolve28(lib, "bundle.json")));
38908
+ const manifest = JSON.parse(read2(resolve29(lib, "bundle.json")));
38704
38909
  return [manifest.version, manifest.commit].filter(Boolean).join("-") || "source";
38705
38910
  } catch {
38706
38911
  return "source";
@@ -39061,7 +39266,7 @@ var SQUIRE_GOVERNED_TOOLS = [
39061
39266
  var SQUIRE_GOVERNED_TOOL_SET = new Set(SQUIRE_GOVERNED_TOOLS);
39062
39267
 
39063
39268
  // apps/body/dist/host-mcp-route.js
39064
- import { join as join14, resolve as resolve29 } from "node:path";
39269
+ import { join as join14, resolve as resolve30 } from "node:path";
39065
39270
  var import_yaml = __toESM(require_dist(), 1);
39066
39271
  init_squire_host();
39067
39272
  function grantedMcpServerNames(grants) {
@@ -39116,7 +39321,7 @@ function grantedSquireHostRouteNames(granted, declarations = {}) {
39116
39321
  });
39117
39322
  }
39118
39323
  function hostRouteEnv(hostHome) {
39119
- return { XDG_CONFIG_HOME: join14(resolve29(hostHome), ".config") };
39324
+ return { XDG_CONFIG_HOME: join14(resolve30(hostHome), ".config") };
39120
39325
  }
39121
39326
  function rewriteHostMcpDeclaration(name, declaration, hostHome, resourceAuthFile, squireScope) {
39122
39327
  const next = { ...declaration };
@@ -39510,7 +39715,7 @@ async function withSharedClaudeLoginLock(shared, write2) {
39510
39715
  } catch (error) {
39511
39716
  if (error.code !== "EEXIST")
39512
39717
  throw error;
39513
- const held = await lstat5(lock).catch(() => void 0);
39718
+ const held = await lstat6(lock).catch(() => void 0);
39514
39719
  if (held && Date.now() - held.mtimeMs > CLAUDE_LOGIN_LOCK_STALE_MS) {
39515
39720
  await rm14(lock, { force: true });
39516
39721
  continue;
@@ -39527,13 +39732,13 @@ async function withSharedClaudeLoginLock(shared, write2) {
39527
39732
  }
39528
39733
  }
39529
39734
  async function writeBackDetachedClaudeLogin(target, source) {
39530
- const detached = await readFile26(target, "utf8");
39735
+ const detached = await readFile27(target, "utf8");
39531
39736
  const detachedExpiresAt = claudeLoginExpiresAt(detached);
39532
39737
  if (detachedExpiresAt === void 0)
39533
39738
  return "not-newer";
39534
39739
  const shared = await realpath2(source);
39535
39740
  const isNewer = async () => {
39536
- const sharedExpiresAt = claudeLoginExpiresAt(await readFile26(shared, "utf8"));
39741
+ const sharedExpiresAt = claudeLoginExpiresAt(await readFile27(shared, "utf8"));
39537
39742
  return sharedExpiresAt !== void 0 && detachedExpiresAt > sharedExpiresAt;
39538
39743
  };
39539
39744
  if (!await isNewer())
@@ -39556,7 +39761,7 @@ async function writeBackDetachedClaudeLogin(target, source) {
39556
39761
  return "busy";
39557
39762
  if (!written)
39558
39763
  return "not-newer";
39559
- if (await readFile26(target, "utf8") !== detached)
39764
+ if (await readFile27(target, "utf8") !== detached)
39560
39765
  return "busy";
39561
39766
  const link2 = `${target}.beeline-link-${randomUUID13()}`;
39562
39767
  await symlink2(source, link2);
@@ -39564,22 +39769,22 @@ async function writeBackDetachedClaudeLogin(target, source) {
39564
39769
  return "linked";
39565
39770
  }
39566
39771
  async function repairRoomAgentCredentialLinks(input) {
39567
- const root = resolve30(input.root);
39772
+ const root = resolve31(input.root);
39568
39773
  const operatorHome = input.operatorHome ?? homedir14();
39569
39774
  for (const credential of SHARED_CREDENTIALS) {
39570
- const source = resolve30(operatorHome, credential.source);
39775
+ const source = resolve31(operatorHome, credential.source);
39571
39776
  if (!existsSync8(source))
39572
39777
  continue;
39573
- const target = resolve30(root, credential.dir, credential.target);
39778
+ const target = resolve31(root, credential.dir, credential.target);
39574
39779
  await mkdir19(dirname22(target), { recursive: true, mode: 448 });
39575
- const stats = await lstat5(target).catch((error) => {
39780
+ const stats = await lstat6(target).catch((error) => {
39576
39781
  if (isMissingPathError(error))
39577
39782
  return void 0;
39578
39783
  throw error;
39579
39784
  });
39580
39785
  if (stats?.isSymbolicLink()) {
39581
39786
  const linked = await readlink(target);
39582
- if (resolve30(dirname22(target), linked) === source)
39787
+ if (resolve31(dirname22(target), linked) === source)
39583
39788
  continue;
39584
39789
  }
39585
39790
  if (stats) {
@@ -39596,20 +39801,20 @@ async function repairRoomAgentCredentialLinks(input) {
39596
39801
  }
39597
39802
  async function writeBackRoomClaudeLogin(input) {
39598
39803
  const claude = SHARED_CREDENTIALS.find((credential) => credential.dir === "claude");
39599
- const source = resolve30(input.operatorHome ?? homedir14(), claude.source);
39804
+ const source = resolve31(input.operatorHome ?? homedir14(), claude.source);
39600
39805
  if (!existsSync8(source))
39601
39806
  return;
39602
- const target = resolve30(input.root, claude.dir, claude.target);
39603
- const stats = await lstat5(target).catch(() => void 0);
39807
+ const target = resolve31(input.root, claude.dir, claude.target);
39808
+ const stats = await lstat6(target).catch(() => void 0);
39604
39809
  if (!stats?.isFile())
39605
39810
  return;
39606
39811
  await writeBackDetachedClaudeLogin(target, source);
39607
39812
  }
39608
39813
  function watchRoomClaudeLogin(input) {
39609
39814
  const claude = SHARED_CREDENTIALS.find((credential) => credential.dir === "claude");
39610
- if (!existsSync8(resolve30(input.operatorHome ?? homedir14(), claude.source)))
39815
+ if (!existsSync8(resolve31(input.operatorHome ?? homedir14(), claude.source)))
39611
39816
  return void 0;
39612
- const dir = resolve30(input.root, claude.dir);
39817
+ const dir = resolve31(input.root, claude.dir);
39613
39818
  let pass = Promise.resolve();
39614
39819
  let watcher;
39615
39820
  try {
@@ -39632,23 +39837,23 @@ function watchRoomClaudeLogin(input) {
39632
39837
  return watcher;
39633
39838
  }
39634
39839
  async function prepareRoomAgentHome(input) {
39635
- const root = resolve30(input.root);
39840
+ const root = resolve31(input.root);
39636
39841
  const operatorHome = input.operatorHome ?? homedir14();
39637
39842
  let tmpLinkReady = false;
39638
39843
  try {
39639
39844
  await mkdir19(root, { recursive: true, mode: 448 });
39640
- const rootStats = await lstat5(root);
39845
+ const rootStats = await lstat6(root);
39641
39846
  if (!rootStats.isDirectory() || rootStats.isSymbolicLink()) {
39642
39847
  throw new AgentHomeSecurityError(`agent home root is not an ordinary directory: ${root}`);
39643
39848
  }
39644
39849
  for (const subdir of HOME_SUBDIRS) {
39645
- const path = resolve30(root, subdir);
39850
+ const path = resolve31(root, subdir);
39646
39851
  await mkdir19(path, { recursive: true, mode: 448 });
39647
39852
  await assertRealContainedDirectory(path, root);
39648
39853
  }
39649
39854
  try {
39650
39855
  const tmpLink = roomSessionTmpDir(root);
39651
- const tmpTarget = resolve30(root, "tmp");
39856
+ const tmpTarget = resolve31(root, "tmp");
39652
39857
  if (await readlink(tmpLink).catch(() => void 0) !== tmpTarget) {
39653
39858
  await rm14(tmpLink, { recursive: true, force: true });
39654
39859
  await symlink2(tmpTarget, tmpLink);
@@ -39683,7 +39888,7 @@ async function prepareRoomAgentHome(input) {
39683
39888
  if (agentHomeProvisionQueues.get(root) === provision)
39684
39889
  agentHomeProvisionQueues.delete(root);
39685
39890
  }
39686
- const env = tmpLinkReady ? roomAgentHomeEnv(root) : { ...roomAgentHomeEnv(root), TMPDIR: resolve30(root, "tmp") };
39891
+ const env = tmpLinkReady ? roomAgentHomeEnv(root) : { ...roomAgentHomeEnv(root), TMPDIR: resolve31(root, "tmp") };
39687
39892
  return {
39688
39893
  ...env,
39689
39894
  ...androidAgentEnv({
@@ -39702,11 +39907,11 @@ async function provisionAgentSkillsAndMcp(root, operatorHome, skillReleaseId, fa
39702
39907
  ...isReviewer ? [{ name: BEELINE_REVIEW_SKILL_NAME, content: beelineReviewSkillMarkdown(skillReleaseId) }] : []
39703
39908
  ];
39704
39909
  const shared = await resolveSharedSkillSources(operatorHome, sharedSkills);
39705
- await provisionManagedSkillsDir(resolve30(root, skillDir, "skills"), managedSkills, shared, sharedSkills.length === 0);
39910
+ await provisionManagedSkillsDir(resolve31(root, skillDir, "skills"), managedSkills, shared, sharedSkills.length === 0);
39706
39911
  for (const config of HARNESS_MCP_CONFIGS) {
39707
39912
  try {
39708
- const source = resolve30(operatorHome, config.toml);
39709
- const target = resolve30(root, config.dir, "config.toml");
39913
+ const source = resolve31(operatorHome, config.toml);
39914
+ const target = resolve31(root, config.dir, "config.toml");
39710
39915
  const mcpSection = existsSync8(source) ? localHarnessMcpToml(readFileSync10(source, "utf8")) : void 0;
39711
39916
  const section = config.dir === "codex" ? [CODEX_ROOM_AGENT_LOCKDOWN_TOML, CODEX_ROOM_WEB_SEARCH_TOML, mcpSection].filter(Boolean).join("\n") : mcpSection;
39712
39917
  if (!section) {
@@ -39721,11 +39926,11 @@ async function provisionAgentSkillsAndMcp(root, operatorHome, skillReleaseId, fa
39721
39926
  }
39722
39927
  }
39723
39928
  try {
39724
- const gooseConfigDir = resolve30(root, "goose", "config");
39929
+ const gooseConfigDir = resolve31(root, "goose", "config");
39725
39930
  await mkdir19(gooseConfigDir, { recursive: true, mode: 448 });
39726
39931
  for (const name of GOOSE_SHARED_CONFIG_FILES) {
39727
- const source = resolve30(operatorHome, ".config", "goose", name);
39728
- const target = resolve30(gooseConfigDir, name);
39932
+ const source = resolve31(operatorHome, ".config", "goose", name);
39933
+ const target = resolve31(gooseConfigDir, name);
39729
39934
  if (existsSync8(source)) {
39730
39935
  const body = readFileSync10(source, "utf8");
39731
39936
  await writeIsolatedHarnessFile(target, name === "config.yaml" ? localGooseConfig(body) : body);
@@ -39739,8 +39944,8 @@ async function provisionAgentSkillsAndMcp(root, operatorHome, skillReleaseId, fa
39739
39944
  console.warn("[body] operator Goose configuration passthrough failed:", error);
39740
39945
  }
39741
39946
  try {
39742
- const claudeJson = resolve30(operatorHome, ".claude.json");
39743
- const claudeTarget = resolve30(root, "claude", ".claude.json");
39947
+ const claudeJson = resolve31(operatorHome, ".claude.json");
39948
+ const claudeTarget = resolve31(root, "claude", ".claude.json");
39744
39949
  const mcpServers = existsSync8(claudeJson) ? readClaudeUserScopeMcpServers(claudeJson) : void 0;
39745
39950
  if (mcpServers && Object.keys(mcpServers).length > 0) {
39746
39951
  await writeIsolatedHarnessFile(claudeTarget, `${JSON.stringify({ mcpServers }, null, 2)}
@@ -39754,8 +39959,8 @@ async function provisionAgentSkillsAndMcp(root, operatorHome, skillReleaseId, fa
39754
39959
  console.warn("[body] operator MCP passthrough failed for claude:", error);
39755
39960
  }
39756
39961
  try {
39757
- const piJson = resolve30(operatorHome, PI_MCP_CONFIG.source);
39758
- const piTarget = resolve30(root, "pi", PI_MCP_CONFIG.target);
39962
+ const piJson = resolve31(operatorHome, PI_MCP_CONFIG.source);
39963
+ const piTarget = resolve31(root, "pi", PI_MCP_CONFIG.target);
39759
39964
  const mcpServers = existsSync8(piJson) ? localMcpServers(recordValue2(readJsonObject2(piJson)?.mcpServers) ?? {}) : void 0;
39760
39965
  if (mcpServers && Object.keys(mcpServers).length > 0) {
39761
39966
  await writeIsolatedHarnessFile(piTarget, `${JSON.stringify({ mcpServers }, null, 2)}
@@ -39770,7 +39975,7 @@ async function provisionAgentSkillsAndMcp(root, operatorHome, skillReleaseId, fa
39770
39975
  }
39771
39976
  try {
39772
39977
  const settings2 = { permissions: { allow: ["WebSearch", "WebFetch"] } };
39773
- await writeIsolatedHarnessFile(resolve30(root, "claude", "settings.json"), `${JSON.stringify(settings2, null, 2)}
39978
+ await writeIsolatedHarnessFile(resolve31(root, "claude", "settings.json"), `${JSON.stringify(settings2, null, 2)}
39774
39979
  `);
39775
39980
  } catch (error) {
39776
39981
  if (failClosed)
@@ -39784,7 +39989,7 @@ async function provisionAgentSkillsAndMcp(root, operatorHome, skillReleaseId, fa
39784
39989
  httpIdleTimeoutMs: 3e5,
39785
39990
  retry: { enabled: true, maxRetries: 3, baseDelayMs: 2e3 }
39786
39991
  };
39787
- await writeIsolatedHarnessFile(resolve30(root, "pi", "settings.json"), `${JSON.stringify(settings2, null, 2)}
39992
+ await writeIsolatedHarnessFile(resolve31(root, "pi", "settings.json"), `${JSON.stringify(settings2, null, 2)}
39788
39993
  `);
39789
39994
  }
39790
39995
  }
@@ -39804,7 +40009,7 @@ async function applyGrantedHostRoutes(root, operatorHome, granted, agentKind, fa
39804
40009
  const routes = routesFor(config.dir);
39805
40010
  if (Object.keys(routes).length === 0)
39806
40011
  continue;
39807
- const target = resolve30(root, config.dir, "config.toml");
40012
+ const target = resolve31(root, config.dir, "config.toml");
39808
40013
  const existing = existsSync8(target) ? readFileSync10(target, "utf8") : void 0;
39809
40014
  const merged = mergeTomlHostRoutes(existing, routes);
39810
40015
  if (merged)
@@ -39813,9 +40018,9 @@ async function applyGrantedHostRoutes(root, operatorHome, granted, agentKind, fa
39813
40018
  if (appliesToHarness(agentKind, "goose")) {
39814
40019
  const routes = routesFor("goose");
39815
40020
  if (Object.keys(routes).length > 0) {
39816
- const gooseConfigDir = resolve30(root, "goose", "config");
40021
+ const gooseConfigDir = resolve31(root, "goose", "config");
39817
40022
  await mkdir19(gooseConfigDir, { recursive: true, mode: 448 });
39818
- const target = resolve30(gooseConfigDir, "config.yaml");
40023
+ const target = resolve31(gooseConfigDir, "config.yaml");
39819
40024
  const existing = existsSync8(target) ? readFileSync10(target, "utf8") : void 0;
39820
40025
  const merged = mergeGooseHostRoutes(existing, routes);
39821
40026
  if (merged)
@@ -39825,7 +40030,7 @@ async function applyGrantedHostRoutes(root, operatorHome, granted, agentKind, fa
39825
40030
  if (appliesToHarness(agentKind, "claude")) {
39826
40031
  const routes = routesFor("claude");
39827
40032
  if (Object.keys(routes).length > 0) {
39828
- const target = resolve30(root, "claude", ".claude.json");
40033
+ const target = resolve31(root, "claude", ".claude.json");
39829
40034
  const parsed = existsSync8(target) ? readJsonObject2(target) : void 0;
39830
40035
  const merged = mergeJsonHostRoutes(recordValue2(parsed?.mcpServers), routes);
39831
40036
  if (merged && Object.keys(merged).length > 0) {
@@ -39837,7 +40042,7 @@ async function applyGrantedHostRoutes(root, operatorHome, granted, agentKind, fa
39837
40042
  if (appliesToHarness(agentKind, "pi")) {
39838
40043
  const routes = routesFor("pi");
39839
40044
  if (Object.keys(routes).length > 0) {
39840
- const target = resolve30(root, "pi", PI_MCP_CONFIG.target);
40045
+ const target = resolve31(root, "pi", PI_MCP_CONFIG.target);
39841
40046
  const parsed = existsSync8(target) ? readJsonObject2(target) : void 0;
39842
40047
  const merged = mergeJsonHostRoutes(recordValue2(parsed?.mcpServers), routes);
39843
40048
  if (merged && Object.keys(merged).length > 0) {
@@ -39853,8 +40058,8 @@ async function applyGrantedHostRoutes(root, operatorHome, granted, agentKind, fa
39853
40058
  }
39854
40059
  }
39855
40060
  async function provisionPiCustomModelConfig(root, operatorHome, failClosed, openRouterRouting) {
39856
- const source = resolve30(operatorHome, PI_CUSTOM_MODEL_CONFIG.source);
39857
- const target = resolve30(root, "pi", PI_CUSTOM_MODEL_CONFIG.target);
40061
+ const source = resolve31(operatorHome, PI_CUSTOM_MODEL_CONFIG.source);
40062
+ const target = resolve31(root, "pi", PI_CUSTOM_MODEL_CONFIG.target);
39858
40063
  let decision2;
39859
40064
  if (openRouterRouting) {
39860
40065
  decision2 = await resolveOpenRouterRouting(openRouterRouting);
@@ -39878,7 +40083,7 @@ async function provisionPiCustomModelConfig(root, operatorHome, failClosed, open
39878
40083
  limits: decision2.limits ?? { maxTokens: OPENROUTER_MAX_OUTPUT_TOKENS }
39879
40084
  } : void 0;
39880
40085
  try {
39881
- const sourceStats = await lstat5(source).catch(() => void 0);
40086
+ const sourceStats = await lstat6(source).catch(() => void 0);
39882
40087
  if (!sourceStats) {
39883
40088
  await writeIsolatedHarnessFile(target, `${JSON.stringify(withOpenRouterModelRouting({}, pin), null, 2)}
39884
40089
  `);
@@ -39968,19 +40173,19 @@ function mountedImportedMcpServerNames(input = {}) {
39968
40173
  const home = env.HOME ?? input.operatorHome ?? homedir14();
39969
40174
  const kind = input.agentKind;
39970
40175
  if (!kind || kind === "codex") {
39971
- addTomlMcpNames(names, resolve30(env.CODEX_HOME ?? resolve30(home, ".codex"), "config.toml"));
40176
+ addTomlMcpNames(names, resolve31(env.CODEX_HOME ?? resolve31(home, ".codex"), "config.toml"));
39972
40177
  }
39973
40178
  if (!kind || kind === "grok") {
39974
- addTomlMcpNames(names, resolve30(env.GROK_HOME ?? resolve30(home, ".grok"), "config.toml"));
40179
+ addTomlMcpNames(names, resolve31(env.GROK_HOME ?? resolve31(home, ".grok"), "config.toml"));
39975
40180
  }
39976
40181
  if (!kind || kind === "claude") {
39977
- addClaudeMcpNames(names, resolve30(env.CLAUDE_CONFIG_DIR ?? home, ".claude.json"));
40182
+ addClaudeMcpNames(names, resolve31(env.CLAUDE_CONFIG_DIR ?? home, ".claude.json"));
39978
40183
  }
39979
40184
  if (!kind || kind === "goose") {
39980
- addGooseExtensionNames(names, env.GOOSE_PATH_ROOT ? resolve30(env.GOOSE_PATH_ROOT, "config/config.yaml") : resolve30(home, ".config/goose/config.yaml"));
40185
+ addGooseExtensionNames(names, env.GOOSE_PATH_ROOT ? resolve31(env.GOOSE_PATH_ROOT, "config/config.yaml") : resolve31(home, ".config/goose/config.yaml"));
39981
40186
  }
39982
40187
  if (!kind || kind === "pi") {
39983
- addClaudeMcpNames(names, resolve30(env.PI_CODING_AGENT_DIR ?? resolve30(home, ".pi/agent"), PI_MCP_CONFIG.target));
40188
+ addClaudeMcpNames(names, resolve31(env.PI_CODING_AGENT_DIR ?? resolve31(home, ".pi/agent"), PI_MCP_CONFIG.target));
39984
40189
  }
39985
40190
  } else {
39986
40191
  collectImportedMcpNames(input.operatorHome ?? homedir14(), names, input.agentKind);
@@ -40000,17 +40205,17 @@ function hostImportedMcpDeclarations(input = {}) {
40000
40205
  }
40001
40206
  };
40002
40207
  if (!kind || kind === "codex")
40003
- add(readTomlMcpServers(resolve30(operatorHome, ".codex/config.toml")));
40208
+ add(readTomlMcpServers(resolve31(operatorHome, ".codex/config.toml")));
40004
40209
  if (!kind || kind === "grok")
40005
- add(readTomlMcpServers(resolve30(operatorHome, ".grok/config.toml")));
40210
+ add(readTomlMcpServers(resolve31(operatorHome, ".grok/config.toml")));
40006
40211
  if (!kind || kind === "claude") {
40007
- add(recordValue2(readJsonObject2(resolve30(operatorHome, ".claude.json"))?.mcpServers));
40212
+ add(recordValue2(readJsonObject2(resolve31(operatorHome, ".claude.json"))?.mcpServers));
40008
40213
  }
40009
40214
  if (!kind || kind === "goose") {
40010
- add(readGooseExtensions(resolve30(operatorHome, ".config/goose/config.yaml")));
40215
+ add(readGooseExtensions(resolve31(operatorHome, ".config/goose/config.yaml")));
40011
40216
  }
40012
40217
  if (!kind || kind === "pi") {
40013
- add(recordValue2(readJsonObject2(resolve30(operatorHome, PI_MCP_CONFIG.source))?.mcpServers));
40218
+ add(recordValue2(readJsonObject2(resolve31(operatorHome, PI_MCP_CONFIG.source))?.mcpServers));
40014
40219
  }
40015
40220
  return declarations;
40016
40221
  }
@@ -40042,19 +40247,19 @@ function expectedMountedImportedMcpServerNames(input) {
40042
40247
  }
40043
40248
  function collectImportedMcpNames(operatorHome, names, kind) {
40044
40249
  if (!kind || kind === "codex") {
40045
- addLocalMcpNames(names, readTomlMcpServers(resolve30(operatorHome, ".codex/config.toml")));
40250
+ addLocalMcpNames(names, readTomlMcpServers(resolve31(operatorHome, ".codex/config.toml")));
40046
40251
  }
40047
40252
  if (!kind || kind === "grok") {
40048
- addLocalMcpNames(names, readTomlMcpServers(resolve30(operatorHome, ".grok/config.toml")));
40253
+ addLocalMcpNames(names, readTomlMcpServers(resolve31(operatorHome, ".grok/config.toml")));
40049
40254
  }
40050
40255
  if (!kind || kind === "claude") {
40051
- addLocalMcpNames(names, recordValue2(readJsonObject2(resolve30(operatorHome, ".claude.json"))?.mcpServers));
40256
+ addLocalMcpNames(names, recordValue2(readJsonObject2(resolve31(operatorHome, ".claude.json"))?.mcpServers));
40052
40257
  }
40053
40258
  if (!kind || kind === "goose") {
40054
- addLocalMcpNames(names, readGooseExtensions(resolve30(operatorHome, ".config/goose/config.yaml")));
40259
+ addLocalMcpNames(names, readGooseExtensions(resolve31(operatorHome, ".config/goose/config.yaml")));
40055
40260
  }
40056
40261
  if (!kind || kind === "pi") {
40057
- addLocalMcpNames(names, recordValue2(readJsonObject2(resolve30(operatorHome, PI_MCP_CONFIG.source))?.mcpServers));
40262
+ addLocalMcpNames(names, recordValue2(readJsonObject2(resolve31(operatorHome, PI_MCP_CONFIG.source))?.mcpServers));
40058
40263
  }
40059
40264
  }
40060
40265
  function addLocalMcpNames(names, servers) {
@@ -40126,19 +40331,19 @@ async function provisionManagedSkillsDir(target, managedSkills, sharedSkills, op
40126
40331
  const plan = await planManagedSkills(managedSkills, sharedSkills, optionalShares);
40127
40332
  if (await materializedSkillManifest(target) === plan.manifest)
40128
40333
  return;
40129
- const staged = resolve30(parent, `.skills.${process.pid}.${randomUUID13()}.tmp`);
40334
+ const staged = resolve31(parent, `.skills.${process.pid}.${randomUUID13()}.tmp`);
40130
40335
  await mkdir19(staged, { mode: 448 });
40131
40336
  try {
40132
40337
  for (const entry of plan.entries) {
40133
40338
  if (entry.kind === "managed") {
40134
- const skillDir = resolve30(staged, entry.name);
40339
+ const skillDir = resolve31(staged, entry.name);
40135
40340
  await mkdir19(skillDir, { recursive: true });
40136
- await writeIsolatedHarnessFile(resolve30(skillDir, "SKILL.md"), entry.content);
40341
+ await writeIsolatedHarnessFile(resolve31(skillDir, "SKILL.md"), entry.content);
40137
40342
  } else {
40138
- await copySafeSkillTree(entry.source, resolve30(staged, entry.name), entry.source);
40343
+ await copySafeSkillTree(entry.source, resolve31(staged, entry.name), entry.source);
40139
40344
  }
40140
40345
  }
40141
- const existing = await lstat5(target).catch(() => void 0);
40346
+ const existing = await lstat6(target).catch(() => void 0);
40142
40347
  if (existing)
40143
40348
  await rm14(target, { recursive: existing.isDirectory(), force: true });
40144
40349
  await rename10(staged, target);
@@ -40163,7 +40368,7 @@ async function planManagedSkills(managedSkills, sharedSkills, optionalShares) {
40163
40368
  const tree = [];
40164
40369
  await walkSafeSkillTree(shared.source, shared.source, {
40165
40370
  directory: async (rel) => void tree.push(`d ${join15(shared.name, rel)}`),
40166
- file: async (rel, realPath) => void tree.push(`f ${join15(shared.name, rel)} ${sha2563(await readFile26(realPath))}`)
40371
+ file: async (rel, realPath) => void tree.push(`f ${join15(shared.name, rel)} ${sha2563(await readFile27(realPath))}`)
40167
40372
  });
40168
40373
  entries.push({ kind: "shared", name: shared.name, source: shared.source });
40169
40374
  lines.push(...tree);
@@ -40176,15 +40381,15 @@ async function planManagedSkills(managedSkills, sharedSkills, optionalShares) {
40176
40381
  return { entries, manifest: lines.sort().join("\n") };
40177
40382
  }
40178
40383
  async function materializedSkillManifest(target) {
40179
- const stats = await lstat5(target).catch(() => void 0);
40384
+ const stats = await lstat6(target).catch(() => void 0);
40180
40385
  if (!stats?.isDirectory() || stats.isSymbolicLink())
40181
40386
  return void 0;
40182
40387
  const lines = [];
40183
40388
  const visit = async (directory, prefix) => {
40184
- for (const entry of await readdir8(directory)) {
40185
- const path = resolve30(directory, entry);
40389
+ for (const entry of await readdir9(directory)) {
40390
+ const path = resolve31(directory, entry);
40186
40391
  const rel = prefix ? join15(prefix, entry) : entry;
40187
- const entryStats = await lstat5(path);
40392
+ const entryStats = await lstat6(path);
40188
40393
  if (entryStats.isSymbolicLink())
40189
40394
  return false;
40190
40395
  if (entryStats.isDirectory()) {
@@ -40195,7 +40400,7 @@ async function materializedSkillManifest(target) {
40195
40400
  }
40196
40401
  if (!entryStats.isFile() || entryStats.nlink !== 1)
40197
40402
  return false;
40198
- lines.push(`f ${rel} ${sha2563(await readFile26(path))}`);
40403
+ lines.push(`f ${rel} ${sha2563(await readFile27(path))}`);
40199
40404
  }
40200
40405
  return true;
40201
40406
  };
@@ -40217,16 +40422,16 @@ async function resolveSharedSkillSources(operatorHome, names) {
40217
40422
  const resolved = [];
40218
40423
  const skipped = [];
40219
40424
  for (const relativeRoot of OPERATOR_SKILL_SOURCE_DIRS) {
40220
- const sourceRoot = resolve30(operatorHome, relativeRoot);
40221
- const rootStats = await lstat5(sourceRoot).catch(() => void 0);
40425
+ const sourceRoot = resolve31(operatorHome, relativeRoot);
40426
+ const rootStats = await lstat6(sourceRoot).catch(() => void 0);
40222
40427
  if (!rootStats?.isDirectory() || rootStats.isSymbolicLink())
40223
40428
  continue;
40224
- for (const entry of await readdir8(sourceRoot)) {
40429
+ for (const entry of await readdir9(sourceRoot)) {
40225
40430
  if (!isSharedSkillName(entry) || seen.has(entry))
40226
40431
  continue;
40227
- const candidate = resolve30(sourceRoot, entry);
40432
+ const candidate = resolve31(sourceRoot, entry);
40228
40433
  try {
40229
- const candidateStats = await lstat5(candidate);
40434
+ const candidateStats = await lstat6(candidate);
40230
40435
  if (candidateStats.isSymbolicLink()) {
40231
40436
  const reason = await realpath2(candidate).then(() => "symlinked directory", (error) => isMissingPathError(error) ? "dangling symlink" : "symlinked directory");
40232
40437
  skipped.push({
@@ -40240,8 +40445,8 @@ async function resolveSharedSkillSources(operatorHome, names) {
40240
40445
  continue;
40241
40446
  }
40242
40447
  assertContained(sourceRoot, candidate);
40243
- const skillMd = resolve30(candidate, "SKILL.md");
40244
- const skillStats = await lstat5(skillMd).catch((error) => {
40448
+ const skillMd = resolve31(candidate, "SKILL.md");
40449
+ const skillStats = await lstat6(skillMd).catch((error) => {
40245
40450
  if (isMissingPathError(error)) {
40246
40451
  skipped.push({ path: candidate, reason: "missing SKILL.md" });
40247
40452
  return void 0;
@@ -40292,10 +40497,10 @@ async function resolveExplicitSkillSources(operatorHome, names) {
40292
40497
  for (const name of unique) {
40293
40498
  const matches = [];
40294
40499
  for (const relativeRoot of OPERATOR_SKILL_SOURCE_DIRS) {
40295
- const sourceRoot = resolve30(operatorHome, relativeRoot);
40296
- const candidate = resolve30(sourceRoot, name);
40297
- const rootStats = await lstat5(sourceRoot).catch(() => void 0);
40298
- const candidateStats = await lstat5(candidate).catch(() => void 0);
40500
+ const sourceRoot = resolve31(operatorHome, relativeRoot);
40501
+ const candidate = resolve31(sourceRoot, name);
40502
+ const rootStats = await lstat6(sourceRoot).catch(() => void 0);
40503
+ const candidateStats = await lstat6(candidate).catch(() => void 0);
40299
40504
  if (!candidateStats)
40300
40505
  continue;
40301
40506
  if (!rootStats?.isDirectory() || rootStats.isSymbolicLink()) {
@@ -40310,8 +40515,8 @@ async function resolveExplicitSkillSources(operatorHome, names) {
40310
40515
  if (matches.length !== 1) {
40311
40516
  throw new Error(matches.length === 0 ? `shared skill is unavailable: ${name}` : `shared skill source is ambiguous: ${name}`);
40312
40517
  }
40313
- const skillMd = resolve30(matches[0], "SKILL.md");
40314
- const skillStats = await lstat5(skillMd).catch(() => void 0);
40518
+ const skillMd = resolve31(matches[0], "SKILL.md");
40519
+ const skillStats = await lstat6(skillMd).catch(() => void 0);
40315
40520
  if (!skillStats?.isFile() || skillStats.isSymbolicLink() || skillStats.nlink !== 1) {
40316
40521
  throw new Error(`shared skill requires an ordinary SKILL.md: ${name}`);
40317
40522
  }
@@ -40321,13 +40526,13 @@ async function resolveExplicitSkillSources(operatorHome, names) {
40321
40526
  }
40322
40527
  function assertContained(root, candidate) {
40323
40528
  const rel = relative2(root, candidate);
40324
- if (rel === ".." || rel.startsWith(`..${sep2}`) || resolve30(root, rel) !== resolve30(candidate)) {
40529
+ if (rel === ".." || rel.startsWith(`..${sep2}`) || resolve31(root, rel) !== resolve31(candidate)) {
40325
40530
  throw new Error(`path escapes the agent skill boundary: ${candidate}`);
40326
40531
  }
40327
40532
  }
40328
40533
  async function assertRealContainedDirectory(path, root) {
40329
40534
  assertContained(root, path);
40330
- const stats = await lstat5(path);
40535
+ const stats = await lstat6(path);
40331
40536
  if (!stats.isDirectory() || stats.isSymbolicLink()) {
40332
40537
  throw new AgentHomeSecurityError(`agent skill destination is not an ordinary directory: ${path}`);
40333
40538
  }
@@ -40336,11 +40541,11 @@ var BLOCKED_SHARED_FILENAMES = /^(?:\.env(?:\..*)?|auth\.json|\.credentials\.jso
40336
40541
  async function walkSafeSkillTree(source, sourceRoot, visitor, rel = "") {
40337
40542
  assertContained(sourceRoot, source);
40338
40543
  const resolvedSource = await realpath2(source);
40339
- if (resolvedSource !== resolve30(source)) {
40544
+ if (resolvedSource !== resolve31(source)) {
40340
40545
  throw new Error(`shared skill path resolves through a link: ${source}`);
40341
40546
  }
40342
40547
  assertContained(sourceRoot, resolvedSource);
40343
- const stats = await lstat5(resolvedSource);
40548
+ const stats = await lstat6(resolvedSource);
40344
40549
  if (stats.isSymbolicLink())
40345
40550
  throw new Error(`shared skill contains a symlink: ${source}`);
40346
40551
  if (BLOCKED_SHARED_FILENAMES.test(basename8(source))) {
@@ -40348,10 +40553,10 @@ async function walkSafeSkillTree(source, sourceRoot, visitor, rel = "") {
40348
40553
  }
40349
40554
  if (stats.isDirectory()) {
40350
40555
  await visitor.directory(rel);
40351
- for (const entry of await readdir8(resolvedSource)) {
40556
+ for (const entry of await readdir9(resolvedSource)) {
40352
40557
  if (entry === "." || entry === "..")
40353
40558
  throw new Error("invalid shared skill entry");
40354
- await walkSafeSkillTree(resolve30(source, entry), sourceRoot, visitor, rel ? join15(rel, entry) : entry);
40559
+ await walkSafeSkillTree(resolve31(source, entry), sourceRoot, visitor, rel ? join15(rel, entry) : entry);
40355
40560
  }
40356
40561
  return;
40357
40562
  }
@@ -40363,10 +40568,10 @@ async function walkSafeSkillTree(source, sourceRoot, visitor, rel = "") {
40363
40568
  async function copySafeSkillTree(source, target, sourceRoot) {
40364
40569
  await walkSafeSkillTree(source, sourceRoot, {
40365
40570
  directory: async (rel) => {
40366
- await mkdir19(resolve30(target, rel), { mode: 448 });
40571
+ await mkdir19(resolve31(target, rel), { mode: 448 });
40367
40572
  },
40368
40573
  file: async (rel, realPath) => {
40369
- const destination = resolve30(target, rel);
40574
+ const destination = resolve31(target, rel);
40370
40575
  await copyFile(realPath, destination);
40371
40576
  await chmod8(destination, 384);
40372
40577
  }
@@ -40374,11 +40579,11 @@ async function copySafeSkillTree(source, target, sourceRoot) {
40374
40579
  }
40375
40580
  async function writeIsolatedHarnessFile(path, content) {
40376
40581
  const parent = dirname22(path);
40377
- const parentStats = await lstat5(parent);
40582
+ const parentStats = await lstat6(parent);
40378
40583
  if (!parentStats.isDirectory() || parentStats.isSymbolicLink()) {
40379
40584
  throw new Error(`isolated harness parent is not a real directory: ${parent}`);
40380
40585
  }
40381
- const temporary = resolve30(parent, `.${basename8(path)}.${process.pid}.${randomUUID13()}.tmp`);
40586
+ const temporary = resolve31(parent, `.${basename8(path)}.${process.pid}.${randomUUID13()}.tmp`);
40382
40587
  try {
40383
40588
  await writeFile17(temporary, content, { mode: 384, flag: "wx" });
40384
40589
  await chmod8(temporary, 384);
@@ -40388,24 +40593,24 @@ async function writeIsolatedHarnessFile(path, content) {
40388
40593
  }
40389
40594
  }
40390
40595
  function roomSessionTmpDir(root, base = "/tmp") {
40391
- const hash = createHash13("sha256").update(resolve30(root)).digest("hex").slice(0, 12);
40596
+ const hash = createHash13("sha256").update(resolve31(root)).digest("hex").slice(0, 12);
40392
40597
  return join15(base, `beeline-${hash}`);
40393
40598
  }
40394
40599
  function roomAgentHomeEnv(root) {
40395
- const resolved = resolve30(root);
40600
+ const resolved = resolve31(root);
40396
40601
  return {
40397
- HOME: resolve30(resolved, "user"),
40398
- CLAUDE_CONFIG_DIR: resolve30(resolved, "claude"),
40399
- CODEX_HOME: resolve30(resolved, "codex"),
40400
- GOOSE_PATH_ROOT: resolve30(resolved, "goose"),
40401
- GROK_HOME: resolve30(resolved, "grok"),
40402
- CURSOR_HOME: resolve30(resolved, "cursor"),
40403
- OPENCODE_CONFIG_DIR: resolve30(resolved, "opencode"),
40404
- PI_CODING_AGENT_DIR: resolve30(resolved, "pi"),
40405
- XDG_CONFIG_HOME: resolve30(resolved, "user/.config"),
40406
- XDG_DATA_HOME: resolve30(resolved, "user/.local/share"),
40407
- XDG_STATE_HOME: resolve30(resolved, "state"),
40408
- XDG_CACHE_HOME: resolve30(resolved, "cache"),
40602
+ HOME: resolve31(resolved, "user"),
40603
+ CLAUDE_CONFIG_DIR: resolve31(resolved, "claude"),
40604
+ CODEX_HOME: resolve31(resolved, "codex"),
40605
+ GOOSE_PATH_ROOT: resolve31(resolved, "goose"),
40606
+ GROK_HOME: resolve31(resolved, "grok"),
40607
+ CURSOR_HOME: resolve31(resolved, "cursor"),
40608
+ OPENCODE_CONFIG_DIR: resolve31(resolved, "opencode"),
40609
+ PI_CODING_AGENT_DIR: resolve31(resolved, "pi"),
40610
+ XDG_CONFIG_HOME: resolve31(resolved, "user/.config"),
40611
+ XDG_DATA_HOME: resolve31(resolved, "user/.local/share"),
40612
+ XDG_STATE_HOME: resolve31(resolved, "state"),
40613
+ XDG_CACHE_HOME: resolve31(resolved, "cache"),
40409
40614
  TMPDIR: roomSessionTmpDir(resolved)
40410
40615
  };
40411
40616
  }
@@ -40428,10 +40633,10 @@ function harnessStateDirsFromEnv(env) {
40428
40633
  for (const name of HARNESS_STATE_ENV_VARS) {
40429
40634
  const value = env[name];
40430
40635
  if (value)
40431
- stateDirs.push(resolve30(value));
40636
+ stateDirs.push(resolve31(value));
40432
40637
  }
40433
40638
  const tmp = env.TMPDIR;
40434
- return { stateDirs, ...tmp ? { tmpDir: resolve30(tmp) } : {} };
40639
+ return { stateDirs, ...tmp ? { tmpDir: resolve31(tmp) } : {} };
40435
40640
  }
40436
40641
 
40437
40642
  // apps/body/dist/agent-command-catalog.js
@@ -41071,12 +41276,12 @@ function mountedMcpSet(servers) {
41071
41276
  }
41072
41277
 
41073
41278
  // apps/body/dist/corner-prepare-script.js
41074
- import { readFile as readFile27 } from "node:fs/promises";
41075
- import { resolve as resolve31 } from "node:path";
41279
+ import { readFile as readFile28 } from "node:fs/promises";
41280
+ import { resolve as resolve32 } from "node:path";
41076
41281
  var CORNER_PREPARE_SCRIPT = "corner:prepare";
41077
41282
  async function hasCornerPrepareScript(worktreePath) {
41078
41283
  try {
41079
- const parsed = JSON.parse(await readFile27(resolve31(worktreePath, "package.json"), "utf8"));
41284
+ const parsed = JSON.parse(await readFile28(resolve32(worktreePath, "package.json"), "utf8"));
41080
41285
  return typeof parsed.scripts?.[CORNER_PREPARE_SCRIPT] === "string";
41081
41286
  } catch {
41082
41287
  return false;
@@ -41085,9 +41290,9 @@ async function hasCornerPrepareScript(worktreePath) {
41085
41290
 
41086
41291
  // apps/body/dist/pi-mcp-bridge.js
41087
41292
  import { execFile as execFile13 } from "node:child_process";
41088
- import { mkdtemp as mkdtemp2, mkdir as mkdir21, readFile as readFile28, rm as rm15, unlink as unlink7 } from "node:fs/promises";
41293
+ import { mkdtemp as mkdtemp2, mkdir as mkdir21, readFile as readFile29, rm as rm15, unlink as unlink7 } from "node:fs/promises";
41089
41294
  import { tmpdir as tmpdir5 } from "node:os";
41090
- import { resolve as resolve32 } from "node:path";
41295
+ import { resolve as resolve33 } from "node:path";
41091
41296
  import { promisify as promisify8 } from "node:util";
41092
41297
  var PI_MCP_BRIDGE_FILENAME = "beeline-mcp-bridge.js";
41093
41298
  var execFileAsync8 = promisify8(execFile13);
@@ -41098,7 +41303,7 @@ async function piHasNativeMcp(command, env) {
41098
41303
  let probe = nativeMcpProbes.get(cacheKey);
41099
41304
  if (!probe) {
41100
41305
  probe = (async () => {
41101
- const home = await mkdtemp2(resolve32(tmpdir5(), "beeline-pi-mcp-probe-"));
41306
+ const home = await mkdtemp2(resolve33(tmpdir5(), "beeline-pi-mcp-probe-"));
41102
41307
  try {
41103
41308
  const { stdout: stdout6 } = await execFileAsync8(command, ["mcp", "list", "--json"], {
41104
41309
  cwd: home,
@@ -41119,7 +41324,7 @@ async function piHasNativeMcp(command, env) {
41119
41324
  }
41120
41325
  async function isolatedPiConfig(piHome) {
41121
41326
  try {
41122
- const parsed = JSON.parse(await readFile28(resolve32(piHome, "mcp.json"), "utf8"));
41327
+ const parsed = JSON.parse(await readFile29(resolve33(piHome, "mcp.json"), "utf8"));
41123
41328
  return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
41124
41329
  } catch (error) {
41125
41330
  if (error.code !== "ENOENT")
@@ -41173,8 +41378,8 @@ async function installPiMcpBridge(input) {
41173
41378
  return void 0;
41174
41379
  if (!input.piHome)
41175
41380
  return void 0;
41176
- const directory = resolve32(input.piHome, "extensions");
41177
- const path = resolve32(directory, PI_MCP_BRIDGE_FILENAME);
41381
+ const directory = resolve33(input.piHome, "extensions");
41382
+ const path = resolve33(directory, PI_MCP_BRIDGE_FILENAME);
41178
41383
  try {
41179
41384
  const config = await isolatedPiConfig(input.piHome);
41180
41385
  const nativeMcp = input.nativeMcp ?? await piHasNativeMcp(input.piCommand ?? "pi", input.agentEnv);
@@ -41187,13 +41392,13 @@ async function installPiMcpBridge(input) {
41187
41392
  env: Object.fromEntries((server.env ?? []).map((entry) => [entry.name, entry.value])),
41188
41393
  exposure: "direct"
41189
41394
  };
41190
- await writeIsolatedHarnessFile(resolve32(input.piHome, "mcp.json"), `${JSON.stringify({ ...config, mcpServers: mcpServers2 }, null, 2)}
41395
+ await writeIsolatedHarnessFile(resolve33(input.piHome, "mcp.json"), `${JSON.stringify({ ...config, mcpServers: mcpServers2 }, null, 2)}
41191
41396
  `);
41192
41397
  await unlink7(path).catch((error) => {
41193
41398
  if (error.code !== "ENOENT")
41194
41399
  throw error;
41195
41400
  });
41196
- return resolve32(input.piHome, "mcp.json");
41401
+ return resolve33(input.piHome, "mcp.json");
41197
41402
  }
41198
41403
  const servers = [...input.servers, ...importedStdioServers(config, input.servers)];
41199
41404
  if (!servers.length)
@@ -41206,7 +41411,7 @@ async function installPiMcpBridge(input) {
41206
41411
  env: Object.fromEntries((server.env ?? []).map((entry) => [entry.name, entry.value])),
41207
41412
  enabled: false
41208
41413
  };
41209
- await writeIsolatedHarnessFile(resolve32(input.piHome, "mcp.json"), `${JSON.stringify({ ...config, mcpServers }, null, 2)}
41414
+ await writeIsolatedHarnessFile(resolve33(input.piHome, "mcp.json"), `${JSON.stringify({ ...config, mcpServers }, null, 2)}
41210
41415
  `);
41211
41416
  await mkdir21(directory, { recursive: true, mode: 448 });
41212
41417
  await writeIsolatedHarnessFile(path, piMcpBridgeSource(servers));
@@ -41398,8 +41603,8 @@ export default async function (pi) {
41398
41603
 
41399
41604
  // apps/body/dist/corner-branch-sync.js
41400
41605
  import { execFile as execFile14 } from "node:child_process";
41401
- import { access as access2, readFile as readFile29 } from "node:fs/promises";
41402
- import { resolve as resolve33 } from "node:path";
41606
+ import { access as access2, readFile as readFile30 } from "node:fs/promises";
41607
+ import { resolve as resolve34 } from "node:path";
41403
41608
  var CORNER_GIT_SYNC_TIMEOUT_MS = 12e4;
41404
41609
  var CORNER_GIT_SYNC_KILL_GRACE_MS = 1e3;
41405
41610
  var CornerGitSyncInterruptedError = class extends Error {
@@ -41413,7 +41618,7 @@ async function syncCornerBranch(input) {
41413
41618
  try {
41414
41619
  if (signal.aborted)
41415
41620
  throw interrupted();
41416
- return await new Promise((resolve52, reject) => {
41621
+ return await new Promise((resolve53, reject) => {
41417
41622
  let killTimer;
41418
41623
  let stdout6 = "";
41419
41624
  let failure = null;
@@ -41447,19 +41652,19 @@ async function syncCornerBranch(input) {
41447
41652
  else if (failure)
41448
41653
  reject(failure);
41449
41654
  else
41450
- resolve52(stdout6);
41655
+ resolve53(stdout6);
41451
41656
  });
41452
41657
  else
41453
- input.git(args).then(resolve52, reject).finally(cleanup2);
41658
+ input.git(args).then(resolve53, reject).finally(cleanup2);
41454
41659
  });
41455
41660
  } finally {
41456
41661
  clearTimeout(timer);
41457
41662
  }
41458
41663
  };
41459
- const marker = await readFile29(resolve33(input.worktreePath, ".git"), "utf8").catch(() => "");
41460
- const gitDir = resolve33(input.worktreePath, marker.startsWith("gitdir: ") ? marker.slice(8).trim() : ".git");
41664
+ const marker = await readFile30(resolve34(input.worktreePath, ".git"), "utf8").catch(() => "");
41665
+ const gitDir = resolve34(input.worktreePath, marker.startsWith("gitdir: ") ? marker.slice(8).trim() : ".git");
41461
41666
  for (const directory of ["rebase-merge", "rebase-apply"]) {
41462
- if (await access2(resolve33(gitDir, directory)).then(() => true, () => false))
41667
+ if (await access2(resolve34(gitDir, directory)).then(() => true, () => false))
41463
41668
  await git2(["rebase", "--abort"], true);
41464
41669
  }
41465
41670
  const remoteRef = `refs/remotes/origin/${input.featureBranch}`;
@@ -41507,7 +41712,7 @@ async function contains(git2, head, ancestor) {
41507
41712
  }
41508
41713
 
41509
41714
  // apps/body/dist/room-session.js
41510
- import { resolve as resolve34 } from "node:path";
41715
+ import { resolve as resolve35 } from "node:path";
41511
41716
  import { homedir as homedir15 } from "node:os";
41512
41717
 
41513
41718
  // apps/body/dist/read-only-policy.js
@@ -41749,22 +41954,22 @@ function readOnlyMcpServer(config, cwd, agentMemoryDir) {
41749
41954
  command: config.readonlyMcpCommand,
41750
41955
  args: [...config.readonlyMcpArgs ?? []],
41751
41956
  env: [
41752
- { name: "BEELINE_READONLY_ROOT", value: resolve34(cwd) },
41957
+ { name: "BEELINE_READONLY_ROOT", value: resolve35(cwd) },
41753
41958
  ...config.agentHomeRoot ? [
41754
41959
  {
41755
41960
  name: "BEELINE_READONLY_AGENT_SKILLS_ROOT",
41756
- value: resolve34(config.agentHomeRoot, skillDir, "skills")
41961
+ value: resolve35(config.agentHomeRoot, skillDir, "skills")
41757
41962
  }
41758
41963
  ] : [],
41759
- ...agentMemoryDir ? [{ name: "BEELINE_READONLY_AGENT_MEMORY_ROOT", value: resolve34(agentMemoryDir) }] : []
41964
+ ...agentMemoryDir ? [{ name: "BEELINE_READONLY_AGENT_MEMORY_ROOT", value: resolve35(agentMemoryDir) }] : []
41760
41965
  ]
41761
41966
  };
41762
41967
  }
41763
41968
 
41764
41969
  // apps/body/dist/scratch-lifecycle.js
41765
41970
  import { execFile as execFile15 } from "node:child_process";
41766
- import { lstat as lstat6, readdir as readdir9, rmdir as rmdir2, rm as rm16, stat as stat10, unlink as unlink8 } from "node:fs/promises";
41767
- import { join as join17, resolve as resolve35 } from "node:path";
41971
+ import { lstat as lstat7, readdir as readdir10, rmdir as rmdir2, rm as rm16, stat as stat10, unlink as unlink8 } from "node:fs/promises";
41972
+ import { join as join17, resolve as resolve36 } from "node:path";
41768
41973
  import { promisify as promisify9 } from "node:util";
41769
41974
  var execFileAsync9 = promisify9(execFile15);
41770
41975
  var CORNER_SCRATCH_BUDGET_BYTES = 5 * 1024 ** 3;
@@ -41772,7 +41977,7 @@ var CORNER_SCRATCH_TTL_MS = 14 * 24 * 60 * 6e4;
41772
41977
  var SHARED_MODEL_CACHE_BUDGET_BYTES = 32 * 1024 ** 3;
41773
41978
  var MODEL_CACHE_IDLE_MS = 24 * 60 * 6e4;
41774
41979
  async function allocatedDirectoryBytes(path) {
41775
- if (!await lstat6(path).catch(() => void 0))
41980
+ if (!await lstat7(path).catch(() => void 0))
41776
41981
  return 0;
41777
41982
  const output = await execFileAsync9("du", ["-s", "-B1", "--", path], {
41778
41983
  maxBuffer: 1024 * 1024
@@ -41794,11 +41999,11 @@ async function sweepStaleCornerScratch(root, now2 = Date.now(), ttlMs = CORNER_S
41794
41999
  let files = 0;
41795
42000
  let bytes = 0;
41796
42001
  const visit = async (dir, top) => {
41797
- for (const entry of await readdir9(dir, { withFileTypes: true }).catch(() => [])) {
42002
+ for (const entry of await readdir10(dir, { withFileTypes: true }).catch(() => [])) {
41798
42003
  if (top && (entry.name === "agent-home" || entry.name === "agent-private" || entry.name === ".git"))
41799
42004
  continue;
41800
42005
  const path = join17(dir, entry.name);
41801
- const info = await lstat6(path).catch(() => void 0);
42006
+ const info = await lstat7(path).catch(() => void 0);
41802
42007
  if (!info || info.isSymbolicLink())
41803
42008
  continue;
41804
42009
  if (info.isDirectory()) {
@@ -41812,8 +42017,8 @@ async function sweepStaleCornerScratch(root, now2 = Date.now(), ttlMs = CORNER_S
41812
42017
  }
41813
42018
  }
41814
42019
  };
41815
- if ((await lstat6(root).catch(() => void 0))?.isDirectory())
41816
- await visit(resolve35(root), true);
42020
+ if ((await lstat7(root).catch(() => void 0))?.isDirectory())
42021
+ await visit(resolve36(root), true);
41817
42022
  return { files, bytes };
41818
42023
  }
41819
42024
  async function pruneSharedModelCache(root, now2 = Date.now(), budget = SHARED_MODEL_CACHE_BUDGET_BYTES) {
@@ -41822,7 +42027,7 @@ async function pruneSharedModelCache(root, now2 = Date.now(), budget = SHARED_MO
41822
42027
  return [];
41823
42028
  const candidates = [];
41824
42029
  for (const parent of [join17(root, "hub"), root]) {
41825
- for (const entry of await readdir9(parent, { withFileTypes: true }).catch(() => [])) {
42030
+ for (const entry of await readdir10(parent, { withFileTypes: true }).catch(() => [])) {
41826
42031
  const eligible = parent === root ? entry.name === "xet" : /^(?:models|datasets|spaces)--/.test(entry.name);
41827
42032
  if (!eligible || !entry.isDirectory())
41828
42033
  continue;
@@ -41894,15 +42099,15 @@ async function awaitInstitutionalContext(fetch2, log2 = console.warn, budgetMs =
41894
42099
 
41895
42100
  // apps/body/dist/codegraph.js
41896
42101
  import { execFile as execFile16 } from "node:child_process";
41897
- import { access as access3, appendFile, mkdir as mkdir22, readFile as readFile30 } from "node:fs/promises";
41898
- import { dirname as dirname23, isAbsolute as isAbsolute4, resolve as resolve36 } from "node:path";
42102
+ import { access as access3, appendFile, mkdir as mkdir22, readFile as readFile31 } from "node:fs/promises";
42103
+ import { dirname as dirname23, isAbsolute as isAbsolute4, resolve as resolve37 } from "node:path";
41899
42104
  import { promisify as promisify10 } from "node:util";
41900
42105
  var execFileAsync10 = promisify10(execFile16);
41901
42106
  var CODEGRAPH_MCP_SERVER_NAME = "codegraph";
41902
42107
  var CODEGRAPH_INDEX_PATH = ".codegraph/codegraph.db";
41903
42108
  var CODEGRAPH_PREPARE_TIMEOUT_MS = 12e4;
41904
42109
  function codegraphIndexDirectory(cwd) {
41905
- return resolve36(cwd, dirname23(CODEGRAPH_INDEX_PATH));
42110
+ return resolve37(cwd, dirname23(CODEGRAPH_INDEX_PATH));
41906
42111
  }
41907
42112
  function codegraphMcpServer(config, cwd, options) {
41908
42113
  if (!config.codegraphCommand)
@@ -41910,7 +42115,7 @@ function codegraphMcpServer(config, cwd, options) {
41910
42115
  return {
41911
42116
  name: CODEGRAPH_MCP_SERVER_NAME,
41912
42117
  command: config.codegraphCommand,
41913
- args: ["serve", "--mcp", "--path", resolve36(cwd), ...options.readonly ? ["--no-watch"] : []],
42118
+ args: ["serve", "--mcp", "--path", resolve37(cwd), ...options.readonly ? ["--no-watch"] : []],
41914
42119
  env: [
41915
42120
  { name: "CODEGRAPH_TELEMETRY", value: "0" },
41916
42121
  // One MCP child per harness session is easier to contain than a daemon
@@ -41928,7 +42133,7 @@ async function isGitWorktree(cwd) {
41928
42133
  cwd,
41929
42134
  timeout: 1e4
41930
42135
  });
41931
- return resolve36(stdout6.trim()) === resolve36(cwd);
42136
+ return resolve37(stdout6.trim()) === resolve37(cwd);
41932
42137
  } catch {
41933
42138
  return false;
41934
42139
  }
@@ -41942,9 +42147,9 @@ async function excludeIndexFromGitStatus(cwd) {
41942
42147
  const gitPath = stdout6.trim();
41943
42148
  if (!gitPath)
41944
42149
  return;
41945
- const path = isAbsolute4(gitPath) ? gitPath : resolve36(cwd, gitPath);
42150
+ const path = isAbsolute4(gitPath) ? gitPath : resolve37(cwd, gitPath);
41946
42151
  await mkdir22(dirname23(path), { recursive: true });
41947
- const existing = await readFile30(path, "utf8").catch(() => "");
42152
+ const existing = await readFile31(path, "utf8").catch(() => "");
41948
42153
  if (existing.split("\n").includes(".codegraph/"))
41949
42154
  return;
41950
42155
  await appendFile(path, `${existing && !existing.endsWith("\n") ? "\n" : ""}.codegraph/
@@ -41957,7 +42162,7 @@ async function prepareCodegraphIndex(config, cwd) {
41957
42162
  if (!command || !await isGitWorktree(cwd))
41958
42163
  return false;
41959
42164
  await excludeIndexFromGitStatus(cwd);
41960
- const indexPath = resolve36(cwd, CODEGRAPH_INDEX_PATH);
42165
+ const indexPath = resolve37(cwd, CODEGRAPH_INDEX_PATH);
41961
42166
  const indexed = await access3(indexPath).then(() => true, () => false);
41962
42167
  const args = indexed ? ["sync", "--quiet", cwd] : ["init", "--yes", cwd];
41963
42168
  try {
@@ -42777,8 +42982,8 @@ function assembleTurnPrompt(context) {
42777
42982
  }
42778
42983
 
42779
42984
  // apps/body/dist/turn-trace.js
42780
- import { appendFile as appendFile2, mkdir as mkdir23, readdir as readdir10, rm as rm17 } from "node:fs/promises";
42781
- import { resolve as resolve37 } from "node:path";
42985
+ import { appendFile as appendFile2, mkdir as mkdir23, readdir as readdir11, rm as rm17 } from "node:fs/promises";
42986
+ import { resolve as resolve38 } from "node:path";
42782
42987
  import { performance as performance3 } from "node:perf_hooks";
42783
42988
  var TURN_PHASES = [
42784
42989
  /** Enqueued on `SessionScheduler` until this turn holds a slot. A capacity wait lives here. */
@@ -43067,7 +43272,7 @@ function formatTurnTraceLine(record5) {
43067
43272
  return [head, ...record5.attempts.map((attempt) => formatTurnAttempt(attempt))].join("\n ");
43068
43273
  }
43069
43274
  function turnTraceDirectory(runtimeDir) {
43070
- return resolve37(runtimeDir, "turn-traces");
43275
+ return resolve38(runtimeDir, "turn-traces");
43071
43276
  }
43072
43277
  var TURN_TRACE_RETENTION_DAYS = 7;
43073
43278
  function traceFileName(date) {
@@ -43084,7 +43289,7 @@ var TurnTraceFile = class {
43084
43289
  this.options = options;
43085
43290
  }
43086
43291
  path(now2 = (this.options.clock ?? (() => /* @__PURE__ */ new Date()))()) {
43087
- return resolve37(this.directory, traceFileName(now2));
43292
+ return resolve38(this.directory, traceFileName(now2));
43088
43293
  }
43089
43294
  write(record5) {
43090
43295
  this.tail = this.tail.catch(() => void 0).then(async () => {
@@ -43107,8 +43312,8 @@ var TurnTraceFile = class {
43107
43312
  return;
43108
43313
  this.prunedDay = day;
43109
43314
  const cutoff = traceFileName(new Date(now2.getTime() - TURN_TRACE_RETENTION_DAYS * 864e5));
43110
- const names = await readdir10(this.directory).catch(() => []);
43111
- await Promise.all(names.filter((name) => /^turns-\d{4}-\d{2}-\d{2}\.jsonl$/.test(name) && name < cutoff).map((name) => rm17(resolve37(this.directory, name), { force: true })));
43315
+ const names = await readdir11(this.directory).catch(() => []);
43316
+ await Promise.all(names.filter((name) => /^turns-\d{4}-\d{2}-\d{2}\.jsonl$/.test(name) && name < cutoff).map((name) => rm17(resolve38(this.directory, name), { force: true })));
43112
43317
  }
43113
43318
  };
43114
43319
 
@@ -44132,8 +44337,8 @@ var MonolithRoomTurnLoop = class {
44132
44337
  let timer;
44133
44338
  const stats = statsPromise && remaining > 0 ? await Promise.race([
44134
44339
  statsPromise,
44135
- new Promise((resolve52) => {
44136
- timer = setTimeout(() => resolve52(void 0), remaining);
44340
+ new Promise((resolve53) => {
44341
+ timer = setTimeout(() => resolve53(void 0), remaining);
44137
44342
  })
44138
44343
  ]).finally(() => {
44139
44344
  if (timer)
@@ -44550,9 +44755,9 @@ function roomMessagePrompt(author, body, attachments, delivered, harnessAcceptsI
44550
44755
 
44551
44756
  // apps/body/dist/corner-github-auth.js
44552
44757
  import { chmod as chmod9, mkdir as mkdir25, writeFile as writeFile20 } from "node:fs/promises";
44553
- import { delimiter as delimiter3, resolve as resolve38 } from "node:path";
44758
+ import { delimiter as delimiter3, resolve as resolve39 } from "node:path";
44554
44759
  async function installCornerGitHubWrappers(input) {
44555
- const bin = resolve38(input.root, "beeline-github-bin");
44760
+ const bin = resolve39(input.root, "beeline-github-bin");
44556
44761
  await mkdir25(bin, { recursive: true, mode: 448 });
44557
44762
  const common = {
44558
44763
  node: process.execPath,
@@ -44564,13 +44769,13 @@ async function installCornerGitHubWrappers(input) {
44564
44769
  gitCommand: input.gitBinary,
44565
44770
  originUrl: input.originUrl ?? ""
44566
44771
  };
44567
- await writeLauncher(resolve38(bin, "git"), {
44772
+ await writeLauncher(resolve39(bin, "git"), {
44568
44773
  ...common,
44569
44774
  command: input.gitBinary,
44570
44775
  launcher: "git",
44571
44776
  restFallback: false
44572
44777
  });
44573
- await writeLauncher(resolve38(bin, "gh"), {
44778
+ await writeLauncher(resolve39(bin, "gh"), {
44574
44779
  ...common,
44575
44780
  command: input.ghBinary ?? "",
44576
44781
  launcher: "gh",
@@ -45024,32 +45229,32 @@ function agentGitIdentityEnv(agent) {
45024
45229
  // apps/body/dist/warm-node-modules.js
45025
45230
  import { createHash as createHash15, randomUUID as randomUUID14 } from "node:crypto";
45026
45231
  import { constants as fsConstants3 } from "node:fs";
45027
- import { chmod as chmod10, copyFile as copyFile2, link, lstat as lstat7, mkdir as mkdir26, readdir as readdir11, readFile as readFile31, readlink as readlink2, rename as rename11, rm as rm18, stat as stat11, symlink as symlink3, utimes } from "node:fs/promises";
45028
- import { dirname as dirname25, join as join19, resolve as resolve39 } from "node:path";
45232
+ import { chmod as chmod10, copyFile as copyFile2, link, lstat as lstat8, mkdir as mkdir26, readdir as readdir12, readFile as readFile32, readlink as readlink2, rename as rename11, rm as rm18, stat as stat11, symlink as symlink3, utimes } from "node:fs/promises";
45233
+ import { dirname as dirname25, join as join19, resolve as resolve40 } from "node:path";
45029
45234
  var STORE_FORMAT = "v1";
45030
45235
  var STAGING_PREFIX = ".beeline-warm-";
45031
45236
  var STAGING_SWEEP_MS = 24 * 60 * 60 * 1e3;
45032
45237
  var WARM_STORE_MAX_ENTRIES = 3;
45033
45238
  function sharedNpmCacheDir(supervisorRoot2) {
45034
- return resolve39(supervisorRoot2, "beeline", "npm-cache");
45239
+ return resolve40(supervisorRoot2, "beeline", "npm-cache");
45035
45240
  }
45036
45241
  function sharedPnpmStoreDir(supervisorRoot2) {
45037
- return resolve39(supervisorRoot2, "beeline", "pnpm-store");
45242
+ return resolve40(supervisorRoot2, "beeline", "pnpm-store");
45038
45243
  }
45039
45244
  function sharedTurboCacheDir(supervisorRoot2) {
45040
- return resolve39(supervisorRoot2, "beeline", "turbo-cache");
45245
+ return resolve40(supervisorRoot2, "beeline", "turbo-cache");
45041
45246
  }
45042
45247
  function warmNodeModulesStoreDir(supervisorRoot2) {
45043
- return resolve39(supervisorRoot2, "beeline", "node-modules");
45248
+ return resolve40(supervisorRoot2, "beeline", "node-modules");
45044
45249
  }
45045
45250
  function mobileNodeModulesStoreDir(supervisorRoot2) {
45046
- return resolve39(supervisorRoot2, "beeline", "node-modules-mobile");
45251
+ return resolve40(supervisorRoot2, "beeline", "node-modules-mobile");
45047
45252
  }
45048
45253
  function isPlanRefusal(value) {
45049
45254
  return "failure" in value;
45050
45255
  }
45051
45256
  async function readWarmPlan(worktreePath) {
45052
- const lockfile = await readFile31(resolve39(worktreePath, "package-lock.json")).catch(() => void 0);
45257
+ const lockfile = await readFile32(resolve40(worktreePath, "package-lock.json")).catch(() => void 0);
45053
45258
  if (!lockfile)
45054
45259
  return { failure: "no-lockfile" };
45055
45260
  const packages = parseLockfilePackages(lockfile);
@@ -45088,11 +45293,11 @@ async function seedWarmNodeModules(input) {
45088
45293
  return { reason: plan.failure, ...plan.detail ? { detail: plan.detail } : {} };
45089
45294
  }
45090
45295
  for (const tree of plan.trees) {
45091
- if (await pathExists(resolve39(input.worktreePath, tree))) {
45296
+ if (await pathExists(resolve40(input.worktreePath, tree))) {
45092
45297
  return { reason: "present", key: plan.key };
45093
45298
  }
45094
45299
  }
45095
- const entry = resolve39(input.storeRoot, plan.key);
45300
+ const entry = resolve40(input.storeRoot, plan.key);
45096
45301
  if (!await isDirectory(entry))
45097
45302
  return { reason: "cold", key: plan.key };
45098
45303
  const [storeDevice, checkoutDevice] = await Promise.all([
@@ -45102,19 +45307,19 @@ async function seedWarmNodeModules(input) {
45102
45307
  if (storeDevice === void 0 || storeDevice !== checkoutDevice) {
45103
45308
  return { reason: "cross-device", key: plan.key };
45104
45309
  }
45105
- const staging = resolve39(input.storeRoot, `${STAGING_PREFIX}${process.pid}.${randomUUID14()}`);
45310
+ const staging = resolve40(input.storeRoot, `${STAGING_PREFIX}${process.pid}.${randomUUID14()}`);
45106
45311
  const placed = [];
45107
45312
  const now2 = (input.now ?? Date.now)();
45108
45313
  try {
45109
45314
  await sweepStaleStaging(input.storeRoot, now2);
45110
45315
  await utimes(entry, now2 / 1e3, now2 / 1e3).catch(() => void 0);
45111
45316
  for (const tree of plan.trees) {
45112
- await cloneTree(resolve39(entry, tree), resolve39(staging, tree), seedFile);
45317
+ await cloneTree(resolve40(entry, tree), resolve40(staging, tree), seedFile);
45113
45318
  }
45114
45319
  for (const tree of plan.trees) {
45115
- const target = resolve39(input.worktreePath, tree);
45320
+ const target = resolve40(input.worktreePath, tree);
45116
45321
  await mkdir26(dirname25(target), { recursive: true });
45117
- await rename11(resolve39(staging, tree), target);
45322
+ await rename11(resolve40(staging, tree), target);
45118
45323
  placed.push(target);
45119
45324
  }
45120
45325
  return { reason: "seeded", key: plan.key };
@@ -45132,11 +45337,11 @@ async function harvestWarmNodeModules(input) {
45132
45337
  if (isPlanRefusal(plan)) {
45133
45338
  return { reason: plan.failure, ...plan.detail ? { detail: plan.detail } : {} };
45134
45339
  }
45135
- const entry = resolve39(input.storeRoot, plan.key);
45340
+ const entry = resolve40(input.storeRoot, plan.key);
45136
45341
  if (await pathExists(entry))
45137
45342
  return { reason: "already-warm", key: plan.key };
45138
45343
  for (const tree of plan.trees) {
45139
- if (!await isDirectory(resolve39(input.worktreePath, tree))) {
45344
+ if (!await isDirectory(resolve40(input.worktreePath, tree))) {
45140
45345
  return { reason: "no-node-modules", key: plan.key, detail: tree };
45141
45346
  }
45142
45347
  }
@@ -45148,12 +45353,12 @@ async function harvestWarmNodeModules(input) {
45148
45353
  detail: `${missing.length} absent, e.g. ${missing.slice(0, 3).join(", ")}`
45149
45354
  };
45150
45355
  }
45151
- const staging = resolve39(input.storeRoot, `${STAGING_PREFIX}${process.pid}.${randomUUID14()}`);
45356
+ const staging = resolve40(input.storeRoot, `${STAGING_PREFIX}${process.pid}.${randomUUID14()}`);
45152
45357
  try {
45153
45358
  await mkdir26(input.storeRoot, { recursive: true, mode: 493 });
45154
45359
  await sweepStaleStaging(input.storeRoot, (input.now ?? Date.now)());
45155
45360
  for (const tree of plan.trees) {
45156
- await cloneTree(resolve39(input.worktreePath, tree), resolve39(staging, tree), harvestFile);
45361
+ await cloneTree(resolve40(input.worktreePath, tree), resolve40(staging, tree), harvestFile);
45157
45362
  }
45158
45363
  await input.onCopied?.();
45159
45364
  if (!await stagedTreeIsPublishable(input.worktreePath, staging, plan.key)) {
@@ -45176,16 +45381,16 @@ async function stagedTreeIsPublishable(worktreePath, staging, key) {
45176
45381
  return false;
45177
45382
  const hidden = join19("node_modules", ".package-lock.json");
45178
45383
  const [copied, current] = await Promise.all([
45179
- readFile31(resolve39(staging, hidden)).catch(() => void 0),
45180
- readFile31(resolve39(worktreePath, hidden)).catch(() => void 0)
45384
+ readFile32(resolve40(staging, hidden)).catch(() => void 0),
45385
+ readFile32(resolve40(worktreePath, hidden)).catch(() => void 0)
45181
45386
  ]);
45182
45387
  if (!copied || !current || !copied.equals(current))
45183
45388
  return false;
45184
45389
  return (await missingInstalledPackages(worktreePath, staging)).length === 0;
45185
45390
  }
45186
45391
  async function missingInstalledPackages(worktreePath, treeRoot = worktreePath) {
45187
- const wanted = parseLockfilePackages(await readFile31(resolve39(worktreePath, "package-lock.json")).catch(() => void 0));
45188
- const installed = parseLockfilePackages(await readFile31(resolve39(treeRoot, "node_modules", ".package-lock.json")).catch(() => void 0));
45392
+ const wanted = parseLockfilePackages(await readFile32(resolve40(worktreePath, "package-lock.json")).catch(() => void 0));
45393
+ const installed = parseLockfilePackages(await readFile32(resolve40(treeRoot, "node_modules", ".package-lock.json")).catch(() => void 0));
45189
45394
  if (!wanted)
45190
45395
  return ["package-lock.json is unreadable"];
45191
45396
  if (!installed)
@@ -45205,7 +45410,7 @@ async function missingInstalledPackages(worktreePath, treeRoot = worktreePath) {
45205
45410
  required.push(path);
45206
45411
  }
45207
45412
  await mapWithLimit(required, INTEGRITY_READ_CONCURRENCY, async (path) => {
45208
- if (!(path in installed) || !await isInstalledPackage(resolve39(treeRoot, path))) {
45413
+ if (!(path in installed) || !await isInstalledPackage(resolve40(treeRoot, path))) {
45209
45414
  missing.push(path);
45210
45415
  }
45211
45416
  });
@@ -45245,7 +45450,7 @@ function isContainedTreePath(value) {
45245
45450
  }
45246
45451
  async function cloneTree(source, target, file, topLevel = true) {
45247
45452
  await mkdir26(target, { recursive: true, mode: 493 });
45248
- for (const entry of await readdir11(source, { withFileTypes: true })) {
45453
+ for (const entry of await readdir12(source, { withFileTypes: true })) {
45249
45454
  const from = join19(source, entry.name);
45250
45455
  const to = join19(target, entry.name);
45251
45456
  if (entry.isSymbolicLink()) {
@@ -45274,10 +45479,10 @@ var seedFile = async (source, target, topLevel) => {
45274
45479
  await chmod10(target, 420);
45275
45480
  };
45276
45481
  async function pruneWarmStore(storeRoot, keep) {
45277
- const names = (await readdir11(storeRoot).catch(() => [])).filter((name) => !name.startsWith(STAGING_PREFIX));
45482
+ const names = (await readdir12(storeRoot).catch(() => [])).filter((name) => !name.startsWith(STAGING_PREFIX));
45278
45483
  const entries = [];
45279
45484
  for (const name of names) {
45280
- const info = await lstat7(join19(storeRoot, name)).catch(() => void 0);
45485
+ const info = await lstat8(join19(storeRoot, name)).catch(() => void 0);
45281
45486
  if (info?.isDirectory())
45282
45487
  entries.push({ name, usedAt: info.mtimeMs });
45283
45488
  }
@@ -45288,19 +45493,19 @@ async function pruneWarmStore(storeRoot, keep) {
45288
45493
  return dropped.map((entry) => entry.name);
45289
45494
  }
45290
45495
  async function sweepStaleStaging(storeRoot, now2) {
45291
- const entries = await readdir11(storeRoot).catch(() => []);
45496
+ const entries = await readdir12(storeRoot).catch(() => []);
45292
45497
  for (const name of entries) {
45293
45498
  if (!name.startsWith(STAGING_PREFIX))
45294
45499
  continue;
45295
45500
  const path = join19(storeRoot, name);
45296
- const info = await lstat7(path).catch(() => void 0);
45501
+ const info = await lstat8(path).catch(() => void 0);
45297
45502
  if (!info || now2 - info.mtimeMs < STAGING_SWEEP_MS)
45298
45503
  continue;
45299
45504
  await rm18(path, { recursive: true, force: true }).catch(() => void 0);
45300
45505
  }
45301
45506
  }
45302
45507
  async function pathExists(path) {
45303
- return lstat7(path).then(() => true, () => false);
45508
+ return lstat8(path).then(() => true, () => false);
45304
45509
  }
45305
45510
  async function deviceOf(path) {
45306
45511
  return stat11(path).then((info) => info.dev, () => void 0);
@@ -45863,7 +46068,7 @@ var MonolithCornerTurnLoop = class {
45863
46068
  this.options.api.execute("getCornerRestoreState", { cornerId: this.options.cornerId })
45864
46069
  ]);
45865
46070
  const { hostRoutes: grantedHostRoutes, devices: grantedDevices, isolatedCategories } = grants;
45866
- const privateAssetRoot = resolve40(runtimeDirectory(this.options.runtime.supervisorRoot, this.options.runtime.agent.publicKey), "private-assets");
46071
+ const privateAssetRoot = resolve41(runtimeDirectory(this.options.runtime.supervisorRoot, this.options.runtime.agent.publicKey), "private-assets");
45867
46072
  const self = roster.members.find((member) => member.identityId === this.agent.publicKey);
45868
46073
  const opener = this.options.openedBy ? roster.members.find((member) => member.identityId === this.options.openedBy) : void 0;
45869
46074
  const reviewer = Boolean(this.options.repository) && configuration.isReviewer === true;
@@ -45987,12 +46192,12 @@ var MonolithCornerTurnLoop = class {
45987
46192
  await prepareCodexCacheTargets(homeOverlay.CODEX_HOME);
45988
46193
  if (assets && homeOverlay.HOME)
45989
46194
  await preparePackageCacheTargets(homeOverlay.HOME);
45990
- const cargoTargetDir = resolve40(this.options.worktreePath, ".beeline-cargo-target");
46195
+ const cargoTargetDir = resolve41(this.options.worktreePath, ".beeline-cargo-target");
45991
46196
  const npmCacheDir = cacheEnv.npm_config_cache ?? sharedNpmCacheDir(this.options.runtime.supervisorRoot);
45992
46197
  const pnpmStoreDir = cacheEnv.PNPM_CONFIG_STORE_DIR ?? sharedPnpmStoreDir(this.options.runtime.supervisorRoot);
45993
46198
  const turboCacheDir = cacheEnv.TURBO_CACHE_DIR ?? sharedTurboCacheDir(this.options.runtime.supervisorRoot);
45994
- const modelCacheDir = cacheEnv.HF_HUB_CACHE ?? resolve40(this.options.runtime.supervisorRoot, "beeline", "model-cache");
45995
- const hfHomeDir = assets && this.options.config.agentHomeRoot ? resolve40(this.options.config.agentHomeRoot, "cache/huggingface-private") : modelCacheDir;
46199
+ const modelCacheDir = cacheEnv.HF_HUB_CACHE ?? resolve41(this.options.runtime.supervisorRoot, "beeline", "model-cache");
46200
+ const hfHomeDir = assets && this.options.config.agentHomeRoot ? resolve41(this.options.config.agentHomeRoot, "cache/huggingface-private") : modelCacheDir;
45996
46201
  await Promise.all([npmCacheDir, pnpmStoreDir, cargoTargetDir, turboCacheDir, modelCacheDir].map((path) => mkdir27(path, { recursive: true, mode: 448 })));
45997
46202
  const agentEnv = {
45998
46203
  ...this.options.config.agentEnv,
@@ -46004,7 +46209,7 @@ var MonolithCornerTurnLoop = class {
46004
46209
  ...cacheEnv,
46005
46210
  ...androidAssets && this.options.config.agentHomeRoot ? {
46006
46211
  ANDROID_AVD_HOME: androidAssets.avdBase,
46007
- ANDROID_EMULATOR_HOME: resolve40(this.options.config.agentHomeRoot, "android-emulator")
46212
+ ANDROID_EMULATOR_HOME: resolve41(this.options.config.agentHomeRoot, "android-emulator")
46008
46213
  } : {},
46009
46214
  npm_config_cache: npmCacheDir,
46010
46215
  // pnpm reads its settings from PNPM_CONFIG_* environment variables and
@@ -46015,14 +46220,14 @@ var MonolithCornerTurnLoop = class {
46015
46220
  HF_HOME: hfHomeDir,
46016
46221
  HUGGINGFACE_HUB_CACHE: assets || isolatedCategories.includes("package-cache") ? modelCacheDir : join20(modelCacheDir, "hub"),
46017
46222
  ...assets && androidAssets && this.options.config.agentHomeRoot ? {
46018
- BEELINE_ANDROID_LEASE_ROOT: resolve40(assets.cache, "android-leases"),
46019
- BEELINE_ANDROID_INSTANCE_ROOT: resolve40(this.options.config.agentHomeRoot, "android-instances"),
46223
+ BEELINE_ANDROID_LEASE_ROOT: resolve41(assets.cache, "android-leases"),
46224
+ BEELINE_ANDROID_INSTANCE_ROOT: resolve41(this.options.config.agentHomeRoot, "android-instances"),
46020
46225
  BEELINE_ANDROID_BASE_AVD_HOME: androidAssets.avdBase,
46021
- BEELINE_ANDROID_EMULATOR_BINARY: resolve40(homeOverlay.ANDROID_HOME, "emulator/emulator")
46226
+ BEELINE_ANDROID_EMULATOR_BINARY: resolve41(homeOverlay.ANDROID_HOME, "emulator/emulator")
46022
46227
  } : {}
46023
46228
  };
46024
46229
  if (toolchain && assets) {
46025
- agentEnv.PATH = `${resolve40(toolchain.binDir, "../../bin")}:${toolchain.binDir}:${agentEnv.PATH ?? ""}`;
46230
+ agentEnv.PATH = `${resolve41(toolchain.binDir, "../../bin")}:${toolchain.binDir}:${agentEnv.PATH ?? ""}`;
46026
46231
  if (this.options.config.agentKind === "pi")
46027
46232
  agentEnv.PI_ACP_PI_COMMAND = toolchain.cliCommand;
46028
46233
  }
@@ -46286,7 +46491,7 @@ var MonolithCornerTurnLoop = class {
46286
46491
  briefRevision: restore.brief?.revision
46287
46492
  }),
46288
46493
  ...this.options.config.agentHomeRoot && this.options.config.agentKind && !AGENT_SKILL_DIRS.includes(this.options.config.agentKind) ? [
46289
- `This harness has no verified native skill discovery. Read the release-managed review procedure at ${resolve40(this.options.config.agentHomeRoot, "codex", "skills", "beeline-review", "SKILL.md")} before the verdict.`
46494
+ `This harness has no verified native skill discovery. Read the release-managed review procedure at ${resolve41(this.options.config.agentHomeRoot, "codex", "skills", "beeline-review", "SKILL.md")} before the verdict.`
46290
46495
  ] : []
46291
46496
  ].join("\n");
46292
46497
  } catch {
@@ -46404,8 +46609,8 @@ var MonolithCornerTurnLoop = class {
46404
46609
  let timer;
46405
46610
  const stats = statsPromise && remaining > 0 ? await Promise.race([
46406
46611
  statsPromise,
46407
- new Promise((resolve52) => {
46408
- timer = setTimeout(() => resolve52(void 0), remaining);
46612
+ new Promise((resolve53) => {
46613
+ timer = setTimeout(() => resolve53(void 0), remaining);
46409
46614
  })
46410
46615
  ]).finally(() => {
46411
46616
  if (timer)
@@ -46470,7 +46675,7 @@ var MonolithCornerTurnLoop = class {
46470
46675
  const briefDelivered = this.attachmentDir && briefAttachments.length ? await deliverAttachments(briefAttachments, join20(this.attachmentDir, requestId.replace(/[^\w-]/g, "_"), "brief", String(assignedBrief.revision)), this.options.fetchImpl) : [];
46471
46676
  briefFileLines = await Promise.all((assignedBrief?.attachments ?? []).map(async (file, index) => {
46472
46677
  const entry = briefDelivered.find((item) => item.attachment === briefAttachments[index]);
46473
- const verified = entry?.path && createHash16("sha256").update(await readFile32(entry.path)).digest("hex") === file.sha256;
46678
+ const verified = entry?.path && createHash16("sha256").update(await readFile33(entry.path)).digest("hex") === file.sha256;
46474
46679
  return `- ${file.title} (${file.purpose}; ${file.required ? "required" : "optional"}; sha256 ${file.sha256}): ${verified ? entry.path : "UNAVAILABLE OR CONTENT MISMATCH"}`;
46475
46680
  }));
46476
46681
  missingRequiredBriefFile = (assignedBrief?.attachments ?? []).some((file, index) => file.required && briefFileLines[index]?.includes("UNAVAILABLE OR CONTENT MISMATCH"));
@@ -46908,13 +47113,13 @@ ${continuation}` : assembled;
46908
47113
  if (this.harvest || !this.options.repository || this.options.config.agentSharedAssetRoot)
46909
47114
  return;
46910
47115
  const { cornerId, worktreePath, runtime } = this.options;
46911
- const mobilePath = resolve40(worktreePath, "apps/mobile");
47116
+ const mobilePath = resolve41(worktreePath, "apps/mobile");
46912
47117
  const jobs = [
46913
47118
  harvestWarmNodeModules({
46914
47119
  worktreePath,
46915
47120
  storeRoot: warmNodeModulesStoreDir(runtime.supervisorRoot)
46916
47121
  }),
46917
- ...existsSync9(resolve40(mobilePath, "package-lock.json")) ? [
47122
+ ...existsSync9(resolve41(mobilePath, "package-lock.json")) ? [
46918
47123
  harvestWarmNodeModules({
46919
47124
  worktreePath: mobilePath,
46920
47125
  storeRoot: mobileNodeModulesStoreDir(runtime.supervisorRoot)
@@ -46962,7 +47167,7 @@ ${continuation}` : assembled;
46962
47167
  const delay = outage ? Math.min(2e3 * 2 ** attempt, 3e4) : 250 * (attempt + 1);
46963
47168
  if ((outage ? Date.now() + delay > outageDeadline : attempt === 2) || this.forcedStop || this.currentTurn && this.stoppedTurns.has(this.currentTurn.requestId))
46964
47169
  throw error;
46965
- await new Promise((resolve52) => setTimeout(resolve52, delay));
47170
+ await new Promise((resolve53) => setTimeout(resolve53, delay));
46966
47171
  }
46967
47172
  }
46968
47173
  if (!token)
@@ -47062,8 +47267,8 @@ ${continuation}` : assembled;
47062
47267
 
47063
47268
  // apps/body/dist/corner-disk-recovery.js
47064
47269
  import { execFile as execFile18 } from "node:child_process";
47065
- import { lstat as lstat8, readdir as readdir12, realpath as realpath3, rm as rm19 } from "node:fs/promises";
47066
- import { basename as basename10, dirname as dirname27, join as join21, relative as relative3, resolve as resolve41, sep as sep3 } from "node:path";
47270
+ import { lstat as lstat9, readdir as readdir13, realpath as realpath3, rm as rm19 } from "node:fs/promises";
47271
+ import { basename as basename10, dirname as dirname27, join as join21, relative as relative3, resolve as resolve42, sep as sep3 } from "node:path";
47067
47272
  import { promisify as promisify12 } from "node:util";
47068
47273
  var execFileAsync12 = promisify12(execFile18);
47069
47274
  var GENERATED_DIRS = /* @__PURE__ */ new Set([
@@ -47078,11 +47283,11 @@ var GENERATED_DIRS = /* @__PURE__ */ new Set([
47078
47283
  var MAX_DIRECTORY_DEPTH = 4;
47079
47284
  var MAX_VISITED_DIRECTORIES = 5e3;
47080
47285
  function cornerRecoveryPointerPath(worktree) {
47081
- const checkout = resolve41(worktree.path);
47286
+ const checkout = resolve42(worktree.path);
47082
47287
  if (basename10(checkout) !== worktree.cornerId || basename10(dirname27(checkout)) !== "corners" || basename10(dirname27(dirname27(checkout))) !== "beeline" || !/^[a-zA-Z0-9-]{1,80}$/.test(worktree.cornerId)) {
47083
47288
  throw new Error("refusing recovery pointer outside a Beeline corner checkout");
47084
47289
  }
47085
- return resolve41(dirname27(dirname27(checkout)), "recovery", "corners", `${worktree.cornerId}.json`);
47290
+ return resolve42(dirname27(dirname27(checkout)), "recovery", "corners", `${worktree.cornerId}.json`);
47086
47291
  }
47087
47292
  async function git(checkout, args) {
47088
47293
  const result = await execFileAsync12("git", ["-C", checkout, ...args], {
@@ -47100,9 +47305,9 @@ async function ignoredAndUntracked(checkout, path) {
47100
47305
  return !(await git(checkout, ["ls-files", "--", rel])).trim();
47101
47306
  }
47102
47307
  async function preserveUnpublishedCornerWorktree(worktree, reason) {
47103
- const checkout = resolve41(worktree.path);
47308
+ const checkout = resolve42(worktree.path);
47104
47309
  const pointer = cornerRecoveryPointerPath(worktree);
47105
- const info = await lstat8(checkout);
47310
+ const info = await lstat9(checkout);
47106
47311
  if (!info.isDirectory() || await realpath3(checkout) !== checkout) {
47107
47312
  throw new Error("refusing to prune a non-canonical corner checkout");
47108
47313
  }
@@ -47126,7 +47331,7 @@ async function preserveUnpublishedCornerWorktree(worktree, reason) {
47126
47331
  break;
47127
47332
  if (current.depth >= MAX_DIRECTORY_DEPTH)
47128
47333
  continue;
47129
- for (const entry of await readdir12(current.path, { withFileTypes: true })) {
47334
+ for (const entry of await readdir13(current.path, { withFileTypes: true })) {
47130
47335
  if (!entry.isDirectory() || entry.name === ".git")
47131
47336
  continue;
47132
47337
  const path = join21(current.path, entry.name);
@@ -47662,7 +47867,7 @@ function cornerStartConfigKey(repository, objective) {
47662
47867
  function cornerRepositoryCacheDir(supervisorRoot2, remote) {
47663
47868
  const normalizedRemote = roomCheckoutRemote(remote);
47664
47869
  const repositoryHash = createHash17("sha256").update(normalizedRemote).digest("hex").slice(0, 24);
47665
- return resolve42(supervisorRoot2, "beeline", "repositories", `${repositoryHash}.git`);
47870
+ return resolve43(supervisorRoot2, "beeline", "repositories", `${repositoryHash}.git`);
47666
47871
  }
47667
47872
  function isStandingCornerStartFault(error) {
47668
47873
  const text2 = error instanceof Error ? error.message : String(error);
@@ -47671,11 +47876,11 @@ function isStandingCornerStartFault(error) {
47671
47876
  async function materializeCornerWorktree(input) {
47672
47877
  const remote = roomCheckoutRemote(input.remote);
47673
47878
  const gitCommonDir = cornerRepositoryCacheDir(input.supervisorRoot, remote);
47674
- const path = resolve42(input.supervisorRoot, "beeline", "corners", input.cornerId);
47879
+ const path = resolve43(input.supervisorRoot, "beeline", "corners", input.cornerId);
47675
47880
  await mkdir28(dirname28(gitCommonDir), { recursive: true, mode: 448 });
47676
47881
  await mkdir28(dirname28(path), { recursive: true, mode: 448 });
47677
47882
  const authEnv = githubGitEnv(input.token);
47678
- if (!existsSync10(resolve42(gitCommonDir, "HEAD"))) {
47883
+ if (!existsSync10(resolve43(gitCommonDir, "HEAD"))) {
47679
47884
  await execFileAsync13("git", ["clone", "--bare", remote, gitCommonDir], {
47680
47885
  env: authEnv,
47681
47886
  maxBuffer: 4 * 1024 * 1024
@@ -47698,7 +47903,7 @@ async function materializeCornerWorktree(input) {
47698
47903
  return false;
47699
47904
  throw error;
47700
47905
  });
47701
- if (!existsSync10(resolve42(path, ".git"))) {
47906
+ if (!existsSync10(resolve43(path, ".git"))) {
47702
47907
  await rm20(path, { recursive: true, force: true });
47703
47908
  await execFileAsync13("git", [
47704
47909
  `--git-dir=${gitCommonDir}`,
@@ -47716,8 +47921,8 @@ async function materializeCornerWorktree(input) {
47716
47921
  if (seed.reason !== "no-lockfile") {
47717
47922
  console.log(`[thin-core] corner ${input.cornerId} warm node_modules: ${seed.reason}${seed.detail ? ` (${seed.detail})` : ""}`);
47718
47923
  }
47719
- const mobilePath = resolve42(path, "apps/mobile");
47720
- if (existsSync10(resolve42(mobilePath, "package-lock.json"))) {
47924
+ const mobilePath = resolve43(path, "apps/mobile");
47925
+ if (existsSync10(resolve43(mobilePath, "package-lock.json"))) {
47721
47926
  const mobileSeed = input.workspaceId ? { reason: "no-lockfile" } : await seedWarmNodeModules({
47722
47927
  worktreePath: mobilePath,
47723
47928
  storeRoot: mobileNodeModulesStoreDir(input.supervisorRoot)
@@ -47775,9 +47980,9 @@ async function mapWithConcurrency(values, limit, visit) {
47775
47980
  }));
47776
47981
  }
47777
47982
  async function discoverCornerWorktree(supervisorRoot2, cornerId) {
47778
- const cornersRoot = resolve42(supervisorRoot2, "beeline", "corners");
47779
- const path = resolve42(cornersRoot, cornerId);
47780
- if (dirname28(path) !== cornersRoot || !existsSync10(resolve42(path, ".git")))
47983
+ const cornersRoot = resolve43(supervisorRoot2, "beeline", "corners");
47984
+ const path = resolve43(cornersRoot, cornerId);
47985
+ if (dirname28(path) !== cornersRoot || !existsSync10(resolve43(path, ".git")))
47781
47986
  return void 0;
47782
47987
  const [canonicalRoot, canonicalPath] = await Promise.all([
47783
47988
  realpath4(cornersRoot),
@@ -47789,8 +47994,8 @@ async function discoverCornerWorktree(supervisorRoot2, cornerId) {
47789
47994
  const common = await execFileAsync13("git", ["-C", path, "rev-parse", "--git-common-dir"]).catch(() => void 0);
47790
47995
  if (!common)
47791
47996
  return void 0;
47792
- const gitCommonDir = resolve42(path, common.stdout.trim());
47793
- const repositoriesRoot = resolve42(supervisorRoot2, "beeline", "repositories");
47997
+ const gitCommonDir = resolve43(path, common.stdout.trim());
47998
+ const repositoriesRoot = resolve43(supervisorRoot2, "beeline", "repositories");
47794
47999
  const commonRelative = relative4(repositoriesRoot, gitCommonDir);
47795
48000
  if (!commonRelative || commonRelative === ".." || commonRelative.startsWith(`..${sep4}`) || commonRelative.startsWith(sep4)) {
47796
48001
  throw new Error(`refusing corner ${cornerId} with git directory outside repository cache`);
@@ -47798,8 +48003,8 @@ async function discoverCornerWorktree(supervisorRoot2, cornerId) {
47798
48003
  return { path, gitCommonDir };
47799
48004
  }
47800
48005
  async function localCornerWorktreeIds(supervisorRoot2) {
47801
- const root = resolve42(supervisorRoot2, "beeline", "corners");
47802
- const entries = await readdir13(root, { withFileTypes: true }).catch((error) => {
48006
+ const root = resolve43(supervisorRoot2, "beeline", "corners");
48007
+ const entries = await readdir14(root, { withFileTypes: true }).catch((error) => {
47803
48008
  if (error.code === "ENOENT")
47804
48009
  return [];
47805
48010
  throw error;
@@ -47904,14 +48109,14 @@ async function originContains(gitCommonDir, head) {
47904
48109
  }
47905
48110
  var execFileAsync13 = promisify13(execFile19);
47906
48111
  async function removeCornerScratchWorkspace(input) {
47907
- const expected = resolve42(input.roomRoot, "scratch");
47908
- if (resolve42(input.scratchPath) !== expected) {
48112
+ const expected = resolve43(input.roomRoot, "scratch");
48113
+ if (resolve43(input.scratchPath) !== expected) {
47909
48114
  throw new Error(`refusing to remove scratch outside corner ${input.cornerId}`);
47910
48115
  }
47911
- for (const entry of await readdir13(expected, { withFileTypes: true }).catch(() => [])) {
48116
+ for (const entry of await readdir14(expected, { withFileTypes: true }).catch(() => [])) {
47912
48117
  if (entry.name === "agent-home" || entry.name === "agent-private")
47913
48118
  continue;
47914
- await rm20(resolve42(expected, entry.name), { recursive: true, force: true });
48119
+ await rm20(resolve43(expected, entry.name), { recursive: true, force: true });
47915
48120
  }
47916
48121
  }
47917
48122
  var RoomRuntimeCoordinator = class {
@@ -47930,8 +48135,8 @@ var RoomRuntimeCoordinator = class {
47930
48135
  localWorktreeIds;
47931
48136
  /** Event-driven cleanup retries stay scoped to the failed local corner. */
47932
48137
  archiveCleanupFaults = /* @__PURE__ */ new Map();
47933
- /** A refused local checkout is kept until a later Room listing proves membership again. */
47934
- archiveCleanupAccessDenied = /* @__PURE__ */ new Set();
48138
+ /** A non-retryable refusal parks this local checkout for the rest of this core's lifetime. */
48139
+ archiveCleanupRefused = /* @__PURE__ */ new Set();
47935
48140
  /**
47936
48141
  * A corner whose branch cleanup found commits no origin ref contains. That
47937
48142
  * is never transient - nothing pushes them later - so retrying it every
@@ -48387,13 +48592,13 @@ var RoomRuntimeCoordinator = class {
48387
48592
  return this.runtime.rooms.find((room) => room.channelId === roomId);
48388
48593
  }
48389
48594
  roomRoot(roomId) {
48390
- return this.roomRecord(roomId)?.root ?? resolve42(dirname28(this.configPath), "rooms", roomId);
48595
+ return this.roomRecord(roomId)?.root ?? resolve43(dirname28(this.configPath), "rooms", roomId);
48391
48596
  }
48392
48597
  roomAgentHomeRoot(workspaceRoot, required = false) {
48393
48598
  const flag = process.env.BUZZY_BODY_ROOM_HOME;
48394
48599
  if (!required && flag === "0")
48395
48600
  return void 0;
48396
- const home = resolve42(workspaceRoot, "agent-home");
48601
+ const home = resolve43(workspaceRoot, "agent-home");
48397
48602
  if (!required && flag !== "1" && !existsSync10(home) && existsSync10(workspaceRoot))
48398
48603
  return void 0;
48399
48604
  try {
@@ -48410,8 +48615,8 @@ var RoomRuntimeCoordinator = class {
48410
48615
  ...this.baseConfig,
48411
48616
  workspaceRoot,
48412
48617
  ...process.env.BEELINE_SHARED_ASSETS_ENABLED === "0" ? { agentSharedAssetRoot: void 0 } : { agentSharedAssetRoot: workspaceAssetRoot(this.runtime.supervisorRoot, this.runtime.communityId) },
48413
- agentPrivateRoot: resolve42(workspaceRoot, "agent-private"),
48414
- agentMemoryRoot: resolve42(dirname28(this.configPath), "memory"),
48618
+ agentPrivateRoot: resolve43(workspaceRoot, "agent-private"),
48619
+ agentMemoryRoot: resolve43(dirname28(this.configPath), "memory"),
48415
48620
  openRouterRoutingCacheDir: openRouterRoutingCacheDir(dirname28(this.configPath)),
48416
48621
  turnTraceDir: turnTraceDirectory(dirname28(this.configPath)),
48417
48622
  ...agentHomeRoot ? { agentHomeRoot } : {}
@@ -48494,11 +48699,11 @@ var RoomRuntimeCoordinator = class {
48494
48699
  const remote = roomCheckoutRemote(repository.remote);
48495
48700
  const targetBranch = repository.targetBranch || "main";
48496
48701
  const checkoutId = createHash17("sha256").update(`${roomId}\0${remote}\0${targetBranch}`).digest("hex").slice(0, 24);
48497
- const path = resolve42(this.runtime.supervisorRoot, "beeline", "room-checkouts", checkoutId);
48702
+ const path = resolve43(this.runtime.supervisorRoot, "beeline", "room-checkouts", checkoutId);
48498
48703
  await mkdir28(dirname28(path), { recursive: true, mode: 448 });
48499
48704
  const token = remote.startsWith("https://github.com/") ? await this.parentRepositoryToken(roomId) : void 0;
48500
48705
  const env = token ? githubGitEnv(token.token) : process.env;
48501
- if (!existsSync10(resolve42(path, ".git"))) {
48706
+ if (!existsSync10(resolve43(path, ".git"))) {
48502
48707
  await execFileAsync13("git", ["clone", "--no-checkout", remote, path], {
48503
48708
  env,
48504
48709
  maxBuffer: 4 * 1024 * 1024
@@ -48585,10 +48790,10 @@ var RoomRuntimeCoordinator = class {
48585
48790
  featureBranch,
48586
48791
  token: granted.token
48587
48792
  }) : void 0;
48588
- const workspacePath = worktree?.path ?? resolve42(this.roomRoot(corner.cornerId), "scratch");
48793
+ const workspacePath = worktree?.path ?? resolve43(this.roomRoot(corner.cornerId), "scratch");
48589
48794
  if (!worktree)
48590
48795
  await mkdir28(workspacePath, { recursive: true, mode: 448 });
48591
- await writePrivateFileAtomically(resolve42(this.roomRoot(corner.cornerId), ".beeline-corner.json"), `${JSON.stringify({ cornerId: corner.cornerId, parentRoomId: corner.parentRoomId })}
48796
+ await writePrivateFileAtomically(resolve43(this.roomRoot(corner.cornerId), ".beeline-corner.json"), `${JSON.stringify({ cornerId: corner.cornerId, parentRoomId: corner.parentRoomId })}
48592
48797
  `);
48593
48798
  if (worktree && shouldPostInitialCornerWorkingState(restore)) {
48594
48799
  await this.options.daemonApi.execute("postCornerRemoteState", {
@@ -48913,7 +49118,7 @@ var RoomRuntimeCoordinator = class {
48913
49118
  this.archiveCleanupAbandoned.delete(cornerId);
48914
49119
  continue;
48915
49120
  }
48916
- if (this.archiveCleanupAbandoned.has(cornerId))
49121
+ if (this.archiveCleanupAbandoned.has(cornerId) || this.archiveCleanupRefused.has(cornerId))
48917
49122
  continue;
48918
49123
  if (!this.archiveCleanupDue(cornerId))
48919
49124
  continue;
@@ -48931,7 +49136,10 @@ var RoomRuntimeCoordinator = class {
48931
49136
  console.error(`[thin-core] corner ${cornerId} branch cleanup abandoned; unpublished work kept:`, error);
48932
49137
  continue;
48933
49138
  }
48934
- this.deferArchiveCleanup(cornerId);
49139
+ if (error instanceof DaemonApiError && error.status >= 400 && error.status < 500 && !error.retryable)
49140
+ this.archiveCleanupRefused.add(cornerId);
49141
+ else
49142
+ this.deferArchiveCleanup(cornerId);
48935
49143
  console.error(`[thin-core] corner ${cornerId} branch cleanup retry failed:`, error);
48936
49144
  }
48937
49145
  }
@@ -48950,9 +49158,8 @@ var RoomRuntimeCoordinator = class {
48950
49158
  continue;
48951
49159
  if (this.archiveCleanupAbandoned.has(cornerId))
48952
49160
  continue;
48953
- if (this.archiveCleanupAccessDenied.has(cornerId) && !corners.has(cornerId))
49161
+ if (this.archiveCleanupRefused.has(cornerId))
48954
49162
  continue;
48955
- this.archiveCleanupAccessDenied.delete(cornerId);
48956
49163
  let corner = corners.get(cornerId);
48957
49164
  let discovered;
48958
49165
  let candidate;
@@ -48981,7 +49188,7 @@ var RoomRuntimeCoordinator = class {
48981
49188
  throw new Error(`archived corner ${corner.cornerId} has no authoritative repository`);
48982
49189
  }
48983
49190
  const expectedCommonDir = cornerRepositoryCacheDir(this.runtime.supervisorRoot, repository.remote);
48984
- if (resolve42(discovered.gitCommonDir) !== expectedCommonDir) {
49191
+ if (resolve43(discovered.gitCommonDir) !== expectedCommonDir) {
48985
49192
  throw new Error(`archived corner ${corner.cornerId} repository cache does not match`);
48986
49193
  }
48987
49194
  if (!restore.featureBranch) {
@@ -49008,8 +49215,8 @@ var RoomRuntimeCoordinator = class {
49008
49215
  }
49009
49216
  continue;
49010
49217
  }
49011
- if (error instanceof DaemonApiError && error.status === 403)
49012
- this.archiveCleanupAccessDenied.add(cornerId);
49218
+ if (error instanceof DaemonApiError && error.status >= 400 && error.status < 500 && !error.retryable)
49219
+ this.archiveCleanupRefused.add(cornerId);
49013
49220
  else
49014
49221
  this.deferArchiveCleanup(cornerId);
49015
49222
  console.error(`[thin-core] archived corner ${cornerId} cleanup deferred:`, error);
@@ -49069,10 +49276,10 @@ var RoomRuntimeCoordinator = class {
49069
49276
  async cleanupArchivedCornerLocalState(cornerId, knownArchive) {
49070
49277
  if (this.running.has(cornerId) || this.startingCorners.has(cornerId))
49071
49278
  return false;
49072
- const root = resolve42(dirname28(this.configPath), "rooms", cornerId);
49279
+ const root = resolve43(dirname28(this.configPath), "rooms", cornerId);
49073
49280
  if (this.roomRoot(cornerId) !== root || !/^[a-zA-Z0-9-]{1,80}$/.test(cornerId))
49074
49281
  return false;
49075
- const info = await lstat9(root).catch(() => void 0);
49282
+ const info = await lstat10(root).catch(() => void 0);
49076
49283
  if (!info?.isDirectory() || await realpath4(root) !== root)
49077
49284
  return false;
49078
49285
  let archived = knownArchive?.has(cornerId) ?? false;
@@ -49090,9 +49297,9 @@ var RoomRuntimeCoordinator = class {
49090
49297
  await removeCornerScratchWorkspace({
49091
49298
  cornerId,
49092
49299
  roomRoot: root,
49093
- scratchPath: resolve42(root, "scratch")
49300
+ scratchPath: resolve43(root, "scratch")
49094
49301
  });
49095
- await rm20(resolve42(root, ".beeline-corner.json"), { force: true });
49302
+ await rm20(resolve43(root, ".beeline-corner.json"), { force: true });
49096
49303
  return true;
49097
49304
  }
49098
49305
  /** Recover chat-only scratch and per-member homes after missed close events
@@ -49100,18 +49307,18 @@ var RoomRuntimeCoordinator = class {
49100
49307
  * checkout has already gone; a scratch directory identifies legacy chat
49101
49308
  * corners. Active scratch gets a 14-day file TTL, never a wholesale reap. */
49102
49309
  async sweepCornerLocalState(archived, desired) {
49103
- const root = resolve42(dirname28(this.configPath), "rooms");
49310
+ const root = resolve43(dirname28(this.configPath), "rooms");
49104
49311
  const due = this.now() - this.lastCornerScratchSweepAt >= 6 * 60 * 6e4;
49105
49312
  if (due)
49106
49313
  this.lastCornerScratchSweepAt = this.now();
49107
- for (const entry of await readdir13(root, { withFileTypes: true }).catch(() => [])) {
49314
+ for (const entry of await readdir14(root, { withFileTypes: true }).catch(() => [])) {
49108
49315
  if (!entry.isDirectory() || !/^[a-zA-Z0-9-]{1,80}$/.test(entry.name))
49109
49316
  continue;
49110
- const roomRoot = resolve42(root, entry.name);
49111
- const scratch = resolve42(roomRoot, "scratch");
49112
- const marker = resolve42(roomRoot, ".beeline-corner.json");
49113
- const hasScratch = (await lstat9(scratch).catch(() => void 0))?.isDirectory() ?? false;
49114
- const hasMarker = (await lstat9(marker).catch(() => void 0))?.isFile() ?? false;
49317
+ const roomRoot = resolve43(root, entry.name);
49318
+ const scratch = resolve43(roomRoot, "scratch");
49319
+ const marker = resolve43(roomRoot, ".beeline-corner.json");
49320
+ const hasScratch = (await lstat10(scratch).catch(() => void 0))?.isDirectory() ?? false;
49321
+ const hasMarker = (await lstat10(marker).catch(() => void 0))?.isFile() ?? false;
49115
49322
  if (!hasScratch && !hasMarker)
49116
49323
  continue;
49117
49324
  if (desired.has(entry.name)) {
@@ -49282,6 +49489,7 @@ var ThinDaemonCore = class {
49282
49489
  pendingDiscovery = false;
49283
49490
  discoveryWaiter;
49284
49491
  discoveryStatus = "starting";
49492
+ progressWaiters = /* @__PURE__ */ new Set();
49285
49493
  constructor(runtime, configPath, baseConfig, options) {
49286
49494
  if (!runtime.transport)
49287
49495
  throw new Error("thin daemon requires monolith transport");
@@ -49292,7 +49500,7 @@ var ThinDaemonCore = class {
49292
49500
  });
49293
49501
  }
49294
49502
  async waitForDiscovery(signal) {
49295
- if (this.pendingDiscovery || signal?.aborted)
49503
+ if (this.pendingDiscovery || this.progressWaiters.size || signal?.aborted)
49296
49504
  return;
49297
49505
  await new Promise((resolveWait) => {
49298
49506
  const done = () => {
@@ -49302,10 +49510,17 @@ var ThinDaemonCore = class {
49302
49510
  };
49303
49511
  this.discoveryWaiter = done;
49304
49512
  signal?.addEventListener("abort", done, { once: true });
49305
- if (this.pendingDiscovery)
49513
+ if (this.pendingDiscovery || this.progressWaiters.size)
49306
49514
  done();
49307
49515
  });
49308
49516
  }
49517
+ /** The existing machine watchdog tick wakes this loop without discovering Rooms. */
49518
+ requestWorkLoopProgress() {
49519
+ return new Promise((resolveProgress) => {
49520
+ this.progressWaiters.add(resolveProgress);
49521
+ this.discoveryWaiter?.();
49522
+ });
49523
+ }
49309
49524
  activeRoomIds() {
49310
49525
  return this.roomRuntime.activeRoomIds();
49311
49526
  }
@@ -49369,19 +49584,25 @@ var ThinDaemonCore = class {
49369
49584
  await opts.onEstablished?.();
49370
49585
  const supervisor2 = this.roomRuntime.supervisor;
49371
49586
  let failures = 0;
49587
+ let discover = true;
49372
49588
  while (!opts.signal?.aborted) {
49373
- this.pendingDiscovery = false;
49589
+ const acknowledge = [...this.progressWaiters];
49590
+ const shouldDiscover = discover || this.pendingDiscovery;
49591
+ if (shouldDiscover)
49592
+ this.pendingDiscovery = false;
49374
49593
  const wakesBefore = supervisor2.wakes;
49375
49594
  try {
49376
- const membership = await this.roomRuntime.reconcile();
49377
- if (membership === "not-member")
49378
- return "agent-removed";
49379
- this.discoveryStatus = membership === "unknown" ? "monolith membership degraded" : "";
49380
- failures = 0;
49595
+ if (shouldDiscover) {
49596
+ const membership = await this.roomRuntime.reconcile();
49597
+ if (membership === "not-member")
49598
+ return "agent-removed";
49599
+ this.discoveryStatus = membership === "unknown" ? "monolith membership degraded" : "";
49600
+ failures = 0;
49601
+ }
49381
49602
  } catch (error) {
49382
49603
  if (isAgentRemovedError(error))
49383
49604
  return "agent-removed";
49384
- failures += 1;
49605
+ failures = error instanceof DaemonApiError && !error.retryable ? supervisor2.retries + 1 : failures + 1;
49385
49606
  console.error(failures > supervisor2.retries ? "[thin-core] discovery failed; waiting for the next live open or discovery wake:" : `[thin-core] discovery failed; retry ${failures} of ${supervisor2.retries}:`, error);
49386
49607
  this.discoveryStatus = `monolith discovery degraded: ${error instanceof Error ? error.message : String(error)}`;
49387
49608
  this.roomRuntime.suspectLink(error);
@@ -49389,16 +49610,24 @@ var ThinDaemonCore = class {
49389
49610
  if (opts.signal?.aborted)
49390
49611
  break;
49391
49612
  await opts.onProgress?.(this.healthStatus());
49392
- if (failures > 0) {
49613
+ for (const done of acknowledge) {
49614
+ this.progressWaiters.delete(done);
49615
+ done();
49616
+ }
49617
+ if (failures > 0 && failures <= supervisor2.retries) {
49393
49618
  await supervisor2.retryDelay(failures, opts.signal, wakesBefore);
49394
- if (failures > supervisor2.retries)
49395
- failures = 0;
49396
- } else if (!this.pendingDiscovery) {
49619
+ discover = true;
49620
+ } else {
49621
+ failures = 0;
49397
49622
  await this.waitForDiscovery(opts.signal);
49623
+ discover = this.pendingDiscovery;
49398
49624
  }
49399
49625
  }
49400
49626
  return "aborted";
49401
49627
  } finally {
49628
+ for (const done of this.progressWaiters)
49629
+ done();
49630
+ this.progressWaiters.clear();
49402
49631
  opts.signal?.removeEventListener("abort", stop);
49403
49632
  await this.roomRuntime.shutdown();
49404
49633
  }
@@ -49407,10 +49636,10 @@ var ThinDaemonCore = class {
49407
49636
 
49408
49637
  // apps/body/dist/force-update-journal.js
49409
49638
  import { mkdirSync as mkdirSync5, readFileSync as readFileSync11, renameSync as renameSync2, writeFileSync as writeFileSync5 } from "node:fs";
49410
- import { resolve as resolve43 } from "node:path";
49639
+ import { resolve as resolve44 } from "node:path";
49411
49640
  var NAME = "force-update-interruptions.json";
49412
49641
  function pathFor(runtimeDir) {
49413
- return resolve43(runtimeDir, NAME);
49642
+ return resolve44(runtimeDir, NAME);
49414
49643
  }
49415
49644
  function read(runtimeDir) {
49416
49645
  try {
@@ -49488,17 +49717,17 @@ function staleGeneration(error) {
49488
49717
  init_launchd();
49489
49718
  init_systemd();
49490
49719
  import { mkdir as mkdir29, rename as rename12 } from "node:fs/promises";
49491
- import { dirname as dirname29, resolve as resolve44 } from "node:path";
49720
+ import { dirname as dirname29, resolve as resolve45 } from "node:path";
49492
49721
  async function retireRemovedAgent(runtime, options = {}) {
49493
- const deletedRoot = resolve44(runtime.supervisorRoot, "beeline", "deleted-runtimes");
49494
- const target = resolve44(deletedRoot, `${runtime.agent.publicKey}-${Date.now()}`);
49722
+ const deletedRoot = resolve45(runtime.supervisorRoot, "beeline", "deleted-runtimes");
49723
+ const target = resolve45(deletedRoot, `${runtime.agent.publicKey}-${Date.now()}`);
49495
49724
  return relocateAgentRuntime(runtime, target, {
49496
49725
  ...options.run ? { run: options.run } : {}
49497
49726
  });
49498
49727
  }
49499
49728
  async function relocateAgentRuntime(runtime, target, options = {}) {
49500
49729
  const source = runtimeDirectory(runtime.supervisorRoot, runtime.agent.publicKey);
49501
- const destination = resolve44(target);
49730
+ const destination = resolve45(target);
49502
49731
  if (destination === source || destination.startsWith(`${source}/`)) {
49503
49732
  throw new Error("agent runtime destination must be outside the live runtime");
49504
49733
  }
@@ -49520,8 +49749,8 @@ async function relocateAgentRuntime(runtime, target, options = {}) {
49520
49749
  init_systemd();
49521
49750
 
49522
49751
  // apps/body/dist/release-status.js
49523
- import { readFile as readFile33, readdir as readdir14, rename as rename13, writeFile as writeFile22 } from "node:fs/promises";
49524
- import { resolve as resolve45 } from "node:path";
49752
+ import { readFile as readFile34, readdir as readdir15, rename as rename13, writeFile as writeFile22 } from "node:fs/promises";
49753
+ import { resolve as resolve46 } from "node:path";
49525
49754
  var DAEMON_RELEASE_STATUS_FILE = "release-status.json";
49526
49755
  var RELEASE_VERSION = /^v\d+\.\d+\.\d+$/;
49527
49756
  var SOURCE_SHA = /^[0-9a-f]{7,64}$/;
@@ -49538,7 +49767,7 @@ async function writeDaemonReleaseStatus(runtimeDir, agentPubkey, identity, optio
49538
49767
  pid: options.pid ?? process.pid,
49539
49768
  readyAt: (options.now?.() ?? /* @__PURE__ */ new Date()).toISOString()
49540
49769
  };
49541
- const target = resolve45(runtimeDir, DAEMON_RELEASE_STATUS_FILE);
49770
+ const target = resolve46(runtimeDir, DAEMON_RELEASE_STATUS_FILE);
49542
49771
  const temporary = `${target}.${status.pid}.tmp`;
49543
49772
  await writeFile22(temporary, `${JSON.stringify(status, null, 2)}
49544
49773
  `, { mode: 384 });
@@ -49547,8 +49776,8 @@ async function writeDaemonReleaseStatus(runtimeDir, agentPubkey, identity, optio
49547
49776
  }
49548
49777
 
49549
49778
  // apps/body/dist/scratch-sweep.js
49550
- import { lstat as lstat10, readdir as readdir15, rmdir as rmdir3, unlink as unlink9 } from "node:fs/promises";
49551
- import { resolve as resolve46 } from "node:path";
49779
+ import { lstat as lstat11, readdir as readdir16, rmdir as rmdir3, unlink as unlink9 } from "node:fs/promises";
49780
+ import { resolve as resolve47 } from "node:path";
49552
49781
  var DEFAULT_SCRATCH_TTL_HOURS = 72;
49553
49782
  var NEVER_SWEEP_SUBDIR_NAMES = new Set(HOME_SUBDIRS.filter((name) => name !== "tmp"));
49554
49783
  function scratchTtlMs(env = process.env) {
@@ -49557,10 +49786,10 @@ function scratchTtlMs(env = process.env) {
49557
49786
  return (Number.isFinite(hours) && hours > 0 ? hours : DEFAULT_SCRATCH_TTL_HOURS) * 60 * 60 * 1e3;
49558
49787
  }
49559
49788
  async function discoverAttachScratchRoots(runtimeDir) {
49560
- const roomsDir = resolve46(runtimeDir, "rooms");
49789
+ const roomsDir = resolve47(runtimeDir, "rooms");
49561
49790
  let entries;
49562
49791
  try {
49563
- entries = await readdir15(roomsDir, { withFileTypes: true });
49792
+ entries = await readdir16(roomsDir, { withFileTypes: true });
49564
49793
  } catch {
49565
49794
  return [];
49566
49795
  }
@@ -49568,8 +49797,8 @@ async function discoverAttachScratchRoots(runtimeDir) {
49568
49797
  for (const entry of entries) {
49569
49798
  if (!entry.isDirectory())
49570
49799
  continue;
49571
- const home = resolve46(roomsDir, entry.name, "agent-home");
49572
- const stats = await lstat10(home).catch(() => void 0);
49800
+ const home = resolve47(roomsDir, entry.name, "agent-home");
49801
+ const stats = await lstat11(home).catch(() => void 0);
49573
49802
  if (stats?.isDirectory())
49574
49803
  roots.push(home);
49575
49804
  }
@@ -49578,7 +49807,7 @@ async function discoverAttachScratchRoots(runtimeDir) {
49578
49807
  async function removeStaleFiles(dir, cutoffMs, protectNamesHere) {
49579
49808
  let entries;
49580
49809
  try {
49581
- entries = await readdir15(dir, { withFileTypes: true });
49810
+ entries = await readdir16(dir, { withFileTypes: true });
49582
49811
  } catch {
49583
49812
  return { removedFiles: 0, removedBytes: 0 };
49584
49813
  }
@@ -49587,15 +49816,15 @@ async function removeStaleFiles(dir, cutoffMs, protectNamesHere) {
49587
49816
  for (const entry of entries) {
49588
49817
  if (protectNamesHere && NEVER_SWEEP_SUBDIR_NAMES.has(entry.name))
49589
49818
  continue;
49590
- const path = resolve46(dir, entry.name);
49591
- const stats = await lstat10(path).catch(() => void 0);
49819
+ const path = resolve47(dir, entry.name);
49820
+ const stats = await lstat11(path).catch(() => void 0);
49592
49821
  if (!stats || stats.isSymbolicLink())
49593
49822
  continue;
49594
49823
  if (stats.isDirectory()) {
49595
49824
  const nested = await removeStaleFiles(path, cutoffMs, false);
49596
49825
  removedFiles += nested.removedFiles;
49597
49826
  removedBytes += nested.removedBytes;
49598
- const remaining = await readdir15(path).catch(() => void 0);
49827
+ const remaining = await readdir16(path).catch(() => void 0);
49599
49828
  if (remaining && remaining.length === 0)
49600
49829
  await rmdir3(path).catch(() => void 0);
49601
49830
  continue;
@@ -49613,7 +49842,7 @@ async function sweepAttachScratchRoots(roots, ttlMs, now2 = Date.now()) {
49613
49842
  let removedFiles = 0;
49614
49843
  let removedBytes = 0;
49615
49844
  for (const root of roots) {
49616
- const stats = await lstat10(root).catch(() => void 0);
49845
+ const stats = await lstat11(root).catch(() => void 0);
49617
49846
  if (!stats?.isDirectory())
49618
49847
  continue;
49619
49848
  const result = await removeStaleFiles(root, cutoffMs, true);
@@ -49657,7 +49886,7 @@ async function runAgentRuntime(configPath, host, signal) {
49657
49886
  BUZZ_DEV_MCP_BIN: runtime.mcpBinary
49658
49887
  };
49659
49888
  const config = loadBodyConfig({
49660
- workspaceRoot: resolve47(runtimeDir, "workspace"),
49889
+ workspaceRoot: resolve48(runtimeDir, "workspace"),
49661
49890
  llmEnvFile: runtime.llmEnvFile,
49662
49891
  env,
49663
49892
  agent
@@ -49923,26 +50152,26 @@ init_squire_host();
49923
50152
 
49924
50153
  // apps/body/dist/host-disk-retention.js
49925
50154
  import { execFile as execFile20 } from "node:child_process";
49926
- import { lstat as lstat11, readdir as readdir16, rm as rm21 } from "node:fs/promises";
49927
- import { join as join23, resolve as resolve48 } from "node:path";
50155
+ import { lstat as lstat12, readdir as readdir17, rm as rm21 } from "node:fs/promises";
50156
+ import { join as join23, resolve as resolve49 } from "node:path";
49928
50157
  import { promisify as promisify14 } from "node:util";
49929
50158
  var execFileAsync14 = promisify14(execFile20);
49930
50159
  var DELETED_RUNTIME_TTL_MS = 30 * 24 * 60 * 6e4;
49931
50160
  var REPOSITORY_CACHE_TTL_MS = 30 * 24 * 60 * 6e4;
49932
50161
  async function pruneDeletedRuntimes(supervisorRoot2, now2 = Date.now()) {
49933
- const root = resolve48(supervisorRoot2, "beeline", "deleted-runtimes");
50162
+ const root = resolve49(supervisorRoot2, "beeline", "deleted-runtimes");
49934
50163
  const removed = [];
49935
- for (const entry of await readdir16(root, { withFileTypes: true }).catch(() => [])) {
50164
+ for (const entry of await readdir17(root, { withFileTypes: true }).catch(() => [])) {
49936
50165
  const match = /^([a-f0-9]{64})-(\d{13})$/.exec(entry.name);
49937
50166
  if (!entry.isDirectory() || !match || now2 - Number(match[2]) < DELETED_RUNTIME_TTL_MS)
49938
50167
  continue;
49939
50168
  const path = join23(root, entry.name);
49940
- if (!(await lstat11(path)).isDirectory())
50169
+ if (!(await lstat12(path)).isDirectory())
49941
50170
  continue;
49942
- const rooms = resolve48(path, "rooms");
50171
+ const rooms = resolve49(path, "rooms");
49943
50172
  let retainsHome = false;
49944
- for (const room of await readdir16(rooms).catch(() => [])) {
49945
- const home = await lstat11(resolve48(rooms, room, "agent-home")).catch(() => void 0);
50173
+ for (const room of await readdir17(rooms).catch(() => [])) {
50174
+ const home = await lstat12(resolve49(rooms, room, "agent-home")).catch(() => void 0);
49946
50175
  if (home) {
49947
50176
  retainsHome = true;
49948
50177
  break;
@@ -49956,19 +50185,19 @@ async function pruneDeletedRuntimes(supervisorRoot2, now2 = Date.now()) {
49956
50185
  return removed;
49957
50186
  }
49958
50187
  async function pruneRepositoryCaches(supervisorRoot2, now2 = Date.now()) {
49959
- const root = resolve48(supervisorRoot2, "beeline", "repositories");
50188
+ const root = resolve49(supervisorRoot2, "beeline", "repositories");
49960
50189
  const removed = [];
49961
- for (const entry of await readdir16(root, { withFileTypes: true }).catch(() => [])) {
50190
+ for (const entry of await readdir17(root, { withFileTypes: true }).catch(() => [])) {
49962
50191
  if (!entry.isDirectory() || !/^[a-f0-9]{24}\.git$/.test(entry.name))
49963
50192
  continue;
49964
50193
  const path = join23(root, entry.name);
49965
- const info = await lstat11(path);
50194
+ const info = await lstat12(path);
49966
50195
  if (!info.isDirectory() || now2 - info.mtimeMs < REPOSITORY_CACHE_TTL_MS)
49967
50196
  continue;
49968
50197
  const listing = await execFileAsync14("git", [`--git-dir=${path}`, "worktree", "list", "--porcelain"]).then((result) => result.stdout, () => void 0);
49969
50198
  if (listing === void 0)
49970
50199
  continue;
49971
- const attached = listing.split("\n").some((line) => line.startsWith("worktree ") && resolve48(line.slice("worktree ".length)) !== path);
50200
+ const attached = listing.split("\n").some((line) => line.startsWith("worktree ") && resolve49(line.slice("worktree ".length)) !== path);
49972
50201
  if (attached)
49973
50202
  continue;
49974
50203
  const refs = await execFileAsync14("git", [
@@ -50034,7 +50263,7 @@ async function runMachineHelper(options = {}) {
50034
50263
  diskSweepRunning = true;
50035
50264
  try {
50036
50265
  const modelDue = now2 - lastModelSweepAt >= 60 * 6e4;
50037
- const removed = modelDue ? await pruneSharedModelCache(resolve49(supervisorRoot2, "beeline", "model-cache")) : [];
50266
+ const removed = modelDue ? await pruneSharedModelCache(resolve50(supervisorRoot2, "beeline", "model-cache")) : [];
50038
50267
  if (modelDue)
50039
50268
  lastModelSweepAt = now2;
50040
50269
  if (now2 - lastRetentionSweepAt >= 24 * 60 * 6e4) {
@@ -50360,7 +50589,12 @@ async function runMachineHelper(options = {}) {
50360
50589
  void rescan().catch((error) => console.error("[helper] rescan failed:", error));
50361
50590
  };
50362
50591
  signals.on("SIGHUP", onHangup);
50363
- const stopWatchdog = startLocalWatchdog(notifier, statusLine);
50592
+ const stopWatchdog = startLocalWatchdog(notifier, statusLine, async () => {
50593
+ if ([...slots.values()].some((slot) => slot.running && !slot.controller.signal.aborted && !hosted.has(slot.agentId)))
50594
+ return false;
50595
+ await Promise.all([...hosted.values()].map((agent) => agent.core.requestWorkLoopProgress()));
50596
+ return true;
50597
+ }, void 0, env);
50364
50598
  try {
50365
50599
  console.log(`[helper] hosting ${initial.length} agent(s) on one machine socket per server`);
50366
50600
  for (const configPath of initial)
@@ -50446,10 +50680,10 @@ function sleep3(ms, signal) {
50446
50680
  // apps/body/dist/android-emulator-lease.js
50447
50681
  import { execFileSync, spawn as spawn14 } from "node:child_process";
50448
50682
  import { randomUUID as randomUUID15 } from "node:crypto";
50449
- import { cp as cp2, mkdir as mkdir31, open as open6, readFile as readFile34, rm as rm22, stat as stat13, writeFile as writeFile24 } from "node:fs/promises";
50683
+ import { cp as cp2, mkdir as mkdir31, open as open6, readFile as readFile35, rm as rm22, stat as stat13, writeFile as writeFile24 } from "node:fs/promises";
50450
50684
  import { createServer as createServer5 } from "node:net";
50451
50685
  import { existsSync as existsSync11 } from "node:fs";
50452
- import { resolve as resolve50 } from "node:path";
50686
+ import { resolve as resolve51 } from "node:path";
50453
50687
  var FIRST_PORT = 5554;
50454
50688
  var LAST_PORT = 5584;
50455
50689
  var PORT_STEP = 4;
@@ -50462,7 +50696,7 @@ function processAlive(pid) {
50462
50696
  }
50463
50697
  }
50464
50698
  async function processStart(pid) {
50465
- const raw = await readFile34(`/proc/${pid}/stat`, "utf8").catch(() => void 0);
50699
+ const raw = await readFile35(`/proc/${pid}/stat`, "utf8").catch(() => void 0);
50466
50700
  if (raw)
50467
50701
  return raw.slice(raw.lastIndexOf(")") + 2).split(" ")[19];
50468
50702
  try {
@@ -50479,13 +50713,13 @@ async function portFree(port) {
50479
50713
  });
50480
50714
  }
50481
50715
  async function leaseEmulator(root, privateRoot) {
50482
- const absolute = resolve50(root);
50716
+ const absolute = resolve51(root);
50483
50717
  await Promise.all([
50484
50718
  mkdir31(absolute, { recursive: true, mode: 448 }),
50485
50719
  mkdir31(privateRoot, { recursive: true, mode: 448 })
50486
50720
  ]);
50487
50721
  for (let port = FIRST_PORT; port <= LAST_PORT; port += PORT_STEP) {
50488
- const marker = resolve50(absolute, `port-${port}.lease`);
50722
+ const marker = resolve51(absolute, `port-${port}.lease`);
50489
50723
  let handle2;
50490
50724
  for (let attempt = 0; attempt < 2; attempt++) {
50491
50725
  try {
@@ -50494,7 +50728,7 @@ async function leaseEmulator(root, privateRoot) {
50494
50728
  } catch (error) {
50495
50729
  if (error.code !== "EEXIST")
50496
50730
  throw error;
50497
- const old = await readFile34(marker, "utf8").catch(() => "");
50731
+ const old = await readFile35(marker, "utf8").catch(() => "");
50498
50732
  const [pidText, start] = old.split(":");
50499
50733
  const pid = Number(pidText);
50500
50734
  if (Number.isSafeInteger(pid) && pid > 0 && processAlive(pid)) {
@@ -50508,20 +50742,20 @@ async function leaseEmulator(root, privateRoot) {
50508
50742
  if (!before || !await portFree(port) || !await portFree(port + 1) || !await portFree(port + 2))
50509
50743
  break;
50510
50744
  const after = await stat13(marker).catch(() => void 0);
50511
- if (after && before.ino === after.ino && await readFile34(marker, "utf8").catch(() => "") === old)
50745
+ if (after && before.ino === after.ino && await readFile35(marker, "utf8").catch(() => "") === old)
50512
50746
  await rm22(marker, { force: true });
50513
50747
  }
50514
50748
  }
50515
50749
  if (!handle2)
50516
50750
  continue;
50517
- const instance = resolve50(privateRoot, `instance-${randomUUID15()}`);
50751
+ const instance = resolve51(privateRoot, `instance-${randomUUID15()}`);
50518
50752
  const ownership = `${process.pid}:${await processStart(process.pid)}:${randomUUID15()}:${instance}`;
50519
50753
  try {
50520
50754
  await handle2.writeFile(ownership);
50521
50755
  await handle2.sync();
50522
50756
  if (!await portFree(port) || !await portFree(port + 1) || !await portFree(port + 2)) {
50523
50757
  await handle2.close();
50524
- if (await readFile34(marker, "utf8").catch(() => "") === ownership)
50758
+ if (await readFile35(marker, "utf8").catch(() => "") === ownership)
50525
50759
  await rm22(marker, { force: true });
50526
50760
  continue;
50527
50761
  }
@@ -50532,14 +50766,14 @@ async function leaseEmulator(root, privateRoot) {
50532
50766
  serial: `emulator-${port}`,
50533
50767
  root: instance,
50534
50768
  release: async () => {
50535
- if (await readFile34(marker, "utf8").catch(() => "") === ownership)
50769
+ if (await readFile35(marker, "utf8").catch(() => "") === ownership)
50536
50770
  await rm22(marker, { force: true });
50537
50771
  await rm22(instance, { recursive: true, force: true });
50538
50772
  }
50539
50773
  };
50540
50774
  } catch (error) {
50541
50775
  await handle2.close().catch(() => void 0);
50542
- if (await readFile34(marker, "utf8").catch(() => "") === ownership)
50776
+ if (await readFile35(marker, "utf8").catch(() => "") === ownership)
50543
50777
  await rm22(marker, { force: true });
50544
50778
  throw error;
50545
50779
  }
@@ -50564,19 +50798,19 @@ async function runLeasedEmulator(args, env = process.env) {
50564
50798
  if (env.ANDROID_EMULATOR_HOME)
50565
50799
  await mkdir31(env.ANDROID_EMULATOR_HOME, { recursive: true, mode: 448 });
50566
50800
  if (env.ANDROID_HOME) {
50567
- const adb = resolve50(env.ANDROID_HOME, "platform-tools/adb");
50801
+ const adb = resolve51(env.ANDROID_HOME, "platform-tools/adb");
50568
50802
  if (existsSync11(adb))
50569
50803
  execFileSync(adb, ["start-server"], { env, timeout: 15e3 });
50570
50804
  }
50571
- const original = resolve50(baseAvdHome, `${avdName}.avd`);
50572
- const localAvdHome = resolve50(lease.root, "avd");
50573
- const local = resolve50(localAvdHome, `${avdName}.avd`);
50574
- const data = resolve50(lease.root, "data");
50805
+ const original = resolve51(baseAvdHome, `${avdName}.avd`);
50806
+ const localAvdHome = resolve51(lease.root, "avd");
50807
+ const local = resolve51(localAvdHome, `${avdName}.avd`);
50808
+ const data = resolve51(lease.root, "data");
50575
50809
  await mkdir31(local, { recursive: true, mode: 448 });
50576
50810
  await mkdir31(data, { recursive: true, mode: 448 });
50577
- await cp2(resolve50(original, "config.ini"), resolve50(local, "config.ini"));
50578
- const metadata = await readFile34(resolve50(baseAvdHome, `${avdName}.ini`), "utf8");
50579
- await writeFile24(resolve50(localAvdHome, `${avdName}.ini`), metadata.replace(/^path\s*=.*$/m, `path=${local}`).replace(/^path\.rel\s*=.*\n?/m, ""), { mode: 384 });
50811
+ await cp2(resolve51(original, "config.ini"), resolve51(local, "config.ini"));
50812
+ const metadata = await readFile35(resolve51(baseAvdHome, `${avdName}.ini`), "utf8");
50813
+ await writeFile24(resolve51(localAvdHome, `${avdName}.ini`), metadata.replace(/^path\s*=.*$/m, `path=${local}`).replace(/^path\.rel\s*=.*\n?/m, ""), { mode: 384 });
50580
50814
  const status = await new Promise((done, reject) => {
50581
50815
  const child = spawn14(emulator, [...args.filter((arg) => arg !== "-read-only"), "-port", String(lease.port), "-datadir", data], {
50582
50816
  env: { ...env, ANDROID_AVD_HOME: localAvdHome, ADB_EMU: "0" },
@@ -50693,7 +50927,7 @@ async function main() {
50693
50927
  const roomId = roomFlag >= 0 ? args[roomFlag + 1] : void 0;
50694
50928
  if (!configPath || !roomId)
50695
50929
  throw new Error("corner-read-token requires --config and --room");
50696
- const activated = await activateDaemonTransport(resolve51(configPath));
50930
+ const activated = await activateDaemonTransport(resolve52(configPath));
50697
50931
  if (!activated)
50698
50932
  throw new Error("corner-read-token requires monolith transport");
50699
50933
  const credential = await activated.client.execute("getRoomGitHubToken", { roomId });
@@ -50748,7 +50982,7 @@ async function main() {
50748
50982
  }
50749
50983
  if (!configPath && !args.includes("--machine"))
50750
50984
  throw new Error("daemon requires --machine, or --config <runtime.json> for one agent");
50751
- const { reason, lifecycle } = await runMachineHelper(configPath ? { configPaths: [resolve51(configPath)] } : {});
50985
+ const { reason, lifecycle } = await runMachineHelper(configPath ? { configPaths: [resolve52(configPath)] } : {});
50752
50986
  daemonLifecycle = lifecycle;
50753
50987
  lifecycle.exit(reason);
50754
50988
  return;