@aspectlylabs/mikka 0.0.723 → 0.0.741

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli.js CHANGED
@@ -2062,7 +2062,7 @@ function readJson(file) {
2062
2062
  }
2063
2063
 
2064
2064
  // src/lock.ts
2065
- import { mkdirSync as mkdirSync2, readFileSync as readFileSync2, rmSync } from "node:fs";
2065
+ import { existsSync, mkdirSync as mkdirSync2, readFileSync as readFileSync2, rmSync } from "node:fs";
2066
2066
  import { createConnection } from "node:net";
2067
2067
  import { join } from "node:path";
2068
2068
  import { setTimeout as sleep } from "node:timers/promises";
@@ -2133,16 +2133,18 @@ async function acquireLock(dataDir, lockfilePath, onCompromised = () => void 0,
2133
2133
  };
2134
2134
  const deadline = Date.now() + (options.takeoverMs ?? LOCK_TAKEOVER_MS);
2135
2135
  for (; ; ) {
2136
- try {
2137
- return await lock();
2138
- } catch (error) {
2139
- if (error.code !== "ELOCKED") throw error;
2140
- }
2141
2136
  if (options.socketPath && await socketAnswers(options.socketPath)) {
2142
2137
  throw new DaemonAlreadyRunningError(dataDir);
2143
2138
  }
2144
2139
  const pid = holderPid(dataDir);
2145
2140
  const crashed = pid !== null && pid !== process.pid && !processAlive(pid);
2141
+ if (pid === null || crashed || !existsSync(lockfilePath)) {
2142
+ try {
2143
+ return await lock();
2144
+ } catch (error) {
2145
+ if (error.code !== "ELOCKED") throw error;
2146
+ }
2147
+ }
2146
2148
  if (crashed || pid === null && Date.now() >= deadline) {
2147
2149
  rmSync(lockfilePath, { recursive: true, force: true });
2148
2150
  try {
@@ -2218,11 +2220,49 @@ function closeLogger(logger) {
2218
2220
  return new Promise((resolve20) => file.end(resolve20));
2219
2221
  }
2220
2222
 
2223
+ // src/lifecycle-record.ts
2224
+ import { join as join2 } from "node:path";
2225
+ var LIFECYCLE_FILE = "lifecycle.json";
2226
+ function trackDaemonLifecycle(logsDir, proc = process, now = () => /* @__PURE__ */ new Date()) {
2227
+ const file = join2(logsDir, LIFECYCLE_FILE);
2228
+ const startedAt = now().toISOString();
2229
+ let reason, error, owned = true;
2230
+ const write = (phase, code) => {
2231
+ if (!owned) return;
2232
+ const record3 = { phase, pid: proc.pid, startedAt, ...reason ? { reason } : {}, ...error ? { error } : {}, ...code === void 0 ? {} : { code }, at: now().toISOString() };
2233
+ try {
2234
+ writeJsonAtomic(file, record3);
2235
+ } catch {
2236
+ }
2237
+ };
2238
+ write("running");
2239
+ proc.on("uncaughtExceptionMonitor", (thrown, origin) => {
2240
+ reason ??= origin;
2241
+ if (error) return;
2242
+ const code = thrown?.code;
2243
+ error = { name: thrown instanceof Error ? thrown.name : typeof thrown, ...typeof code === "string" ? { code } : {} };
2244
+ });
2245
+ proc.once("exit", (code) => {
2246
+ reason ??= "exit";
2247
+ write("exited", code);
2248
+ });
2249
+ return {
2250
+ stopping(why) {
2251
+ reason ??= why;
2252
+ write("stopping");
2253
+ },
2254
+ /** Another daemon took the data dir; the record is its to write from now on. */
2255
+ disown() {
2256
+ owned = false;
2257
+ }
2258
+ };
2259
+ }
2260
+
2221
2261
  // src/auto-update.ts
2222
2262
  import { execFile } from "node:child_process";
2223
2263
  import { realpathSync } from "node:fs";
2224
2264
  import { homedir } from "node:os";
2225
- import { dirname as dirname2, join as join2, resolve } from "node:path";
2265
+ import { dirname as dirname2, join as join3, resolve } from "node:path";
2226
2266
  import { promisify } from "node:util";
2227
2267
  var exec = promisify(execFile);
2228
2268
  var PACKAGE = "@aspectlylabs/mikka";
@@ -2234,11 +2274,11 @@ function newerStableVersion(candidate, current) {
2234
2274
  return false;
2235
2275
  }
2236
2276
  function serviceNpmEnvironment(entry, home, env) {
2237
- const prefix = join2(home, ".mikka/npm");
2238
- return resolve(entry) === join2(prefix, "lib/node_modules/@aspectlylabs/mikka/mikka.js") ? { ...env, npm_config_prefix: prefix, npm_config_cache: join2(home, ".mikka/npm-cache") } : env;
2277
+ const prefix = join3(home, ".mikka/npm");
2278
+ return resolve(entry) === join3(prefix, "lib/node_modules/@aspectlylabs/mikka/mikka.js") ? { ...env, npm_config_prefix: prefix, npm_config_cache: join3(home, ".mikka/npm-cache") } : env;
2239
2279
  }
2240
2280
  async function runServiceNpm(args) {
2241
- const npm = realpathSync(join2(dirname2(process.execPath), "npm"));
2281
+ const npm = realpathSync(join3(dirname2(process.execPath), "npm"));
2242
2282
  const { stdout } = await exec(process.execPath, [npm, ...args], {
2243
2283
  cwd: homedir(),
2244
2284
  timeout: 3e5,
@@ -2253,10 +2293,10 @@ async function managedAutoUpdateRuntime(entry, flavor, enabled) {
2253
2293
  try {
2254
2294
  const file = realpathSync(resolve(entry));
2255
2295
  const root = dirname2(file);
2256
- const pkg = readJson(join2(root, "package.json"));
2296
+ const pkg = readJson(join3(root, "package.json"));
2257
2297
  if (pkg?.name !== PACKAGE || pkg.private !== false) return;
2258
2298
  const globalRoot = await runServiceNpm(["root", "--global"]);
2259
- if (realpathSync(join2(globalRoot, PACKAGE)) !== root || file !== join2(root, "mikka.js")) return;
2299
+ if (realpathSync(join3(globalRoot, PACKAGE)) !== root || file !== join3(root, "mikka.js")) return;
2260
2300
  return {
2261
2301
  install: async (version) => {
2262
2302
  await runServiceNpm(["install", "--global", "--engine-strict", `${PACKAGE}@${version}`]);
@@ -2292,7 +2332,7 @@ import { execFile as execFile2 } from "node:child_process";
2292
2332
  import { promisify as promisify2 } from "node:util";
2293
2333
  import { mkdir, readFile, writeFile, rm } from "node:fs/promises";
2294
2334
  import { homedir as homedir2 } from "node:os";
2295
- import { dirname as dirname3, join as join3, resolve as resolve2 } from "node:path";
2335
+ import { dirname as dirname3, join as join4, resolve as resolve2 } from "node:path";
2296
2336
  var exec2 = promisify2(execFile2);
2297
2337
  var label = "com.aspectlylabs.mikka.daemon";
2298
2338
  var xml = (s) => s.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;");
@@ -2320,7 +2360,7 @@ WantedBy=default.target
2320
2360
  if (input.platform !== "darwin") throw new Error("Services require Linux or macOS");
2321
2361
  return `<?xml version="1.0" encoding="UTF-8"?>
2322
2362
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
2323
- <plist version="1.0"><dict><key>Label</key><string>${label}</string><key>ProgramArguments</key><array>${args.map((arg) => `<string>${xml(arg)}</string>`).join("")}</array><key>RunAtLoad</key><true/><key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict><key>EnvironmentVariables</key><dict><key>PATH</key><string>${xml(input.path)}</string><key>MIKKA_SERVICE</key><string>launchd</string><key>MIKKA_DEVICE_TYPE</key><string>${input.deviceType === "server" ? "server" : "laptop"}</string></dict><key>StandardErrorPath</key><string>${xml(join3(input.home, "Library/Logs/mikka-daemon.log"))}</string></dict></plist>
2363
+ <plist version="1.0"><dict><key>Label</key><string>${label}</string><key>ProgramArguments</key><array>${args.map((arg) => `<string>${xml(arg)}</string>`).join("")}</array><key>RunAtLoad</key><true/><key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict><key>EnvironmentVariables</key><dict><key>PATH</key><string>${xml(input.path)}</string><key>MIKKA_SERVICE</key><string>launchd</string><key>MIKKA_DEVICE_TYPE</key><string>${input.deviceType === "server" ? "server" : "laptop"}</string></dict><key>StandardErrorPath</key><string>${xml(join4(input.home, "Library/Logs/mikka-daemon.log"))}</string></dict></plist>
2324
2364
  `;
2325
2365
  }
2326
2366
  async function installService(server, deviceType = "server", options = {}) {
@@ -2329,7 +2369,7 @@ async function installService(server, deviceType = "server", options = {}) {
2329
2369
  const home = homedir2();
2330
2370
  const content = serviceDefinition({ platform: process.platform, node: process.execPath, entry: resolve2(process.argv[1]), server, home, path: process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin", deviceType, ...options });
2331
2371
  if (process.platform === "linux") {
2332
- const file = join3(home, ".config/systemd/user/mikka-daemon.service");
2372
+ const file = join4(home, ".config/systemd/user/mikka-daemon.service");
2333
2373
  await mkdir(dirname3(file), { recursive: true, mode: 448 });
2334
2374
  await writeFile(file, content, { mode: 384 });
2335
2375
  await exec2("loginctl", ["enable-linger"], { timeout: 1e4 }).catch(() => void 0);
@@ -2337,9 +2377,9 @@ async function installService(server, deviceType = "server", options = {}) {
2337
2377
  await exec2("systemctl", ["--user", "enable", "mikka-daemon.service"]);
2338
2378
  await exec2("systemctl", ["--user", "restart", "mikka-daemon.service"]);
2339
2379
  } else {
2340
- const file = join3(home, "Library/LaunchAgents", `${label}.plist`);
2380
+ const file = join4(home, "Library/LaunchAgents", `${label}.plist`);
2341
2381
  await mkdir(dirname3(file), { recursive: true, mode: 448 });
2342
- await mkdir(join3(home, "Library/Logs"), { recursive: true });
2382
+ await mkdir(join4(home, "Library/Logs"), { recursive: true });
2343
2383
  const domain = `gui/${process.getuid()}`;
2344
2384
  await installLaunchAgent(domain, file, content);
2345
2385
  }
@@ -2402,10 +2442,10 @@ async function uninstallService(clearCredential, dependencies = {
2402
2442
  try {
2403
2443
  if (dependencies.manager === "systemd") {
2404
2444
  await dependencies.run("systemctl", ["--user", "disable", "mikka-daemon.service"]);
2405
- await rm(join3(dependencies.home, ".config/systemd/user/mikka-daemon.service"), { force: true });
2445
+ await rm(join4(dependencies.home, ".config/systemd/user/mikka-daemon.service"), { force: true });
2406
2446
  await dependencies.run("systemctl", ["--user", "daemon-reload"]);
2407
2447
  } else if (dependencies.manager === "launchd") {
2408
- await rm(join3(dependencies.home, "Library/LaunchAgents", `${label}.plist`), { force: true });
2448
+ await rm(join4(dependencies.home, "Library/LaunchAgents", `${label}.plist`), { force: true });
2409
2449
  }
2410
2450
  } finally {
2411
2451
  clearCredential();
@@ -6597,14 +6637,14 @@ function isNonRetryable(error) {
6597
6637
  }
6598
6638
 
6599
6639
  // src/paths.ts
6600
- import { existsSync } from "node:fs";
6640
+ import { existsSync as existsSync2 } from "node:fs";
6601
6641
  import { homedir as homedir3 } from "node:os";
6602
- import { join as join4 } from "node:path";
6642
+ import { join as join5 } from "node:path";
6603
6643
 
6604
6644
  // package.json
6605
6645
  var package_default = {
6606
6646
  name: "@mikka/daemon",
6607
- version: "0.0.723",
6647
+ version: "0.0.741",
6608
6648
  description: "Local Mikka daemon: runs agents through the user's own CLIs",
6609
6649
  type: "module",
6610
6650
  private: true,
@@ -6672,7 +6712,7 @@ var package_default = {
6672
6712
  engines: {
6673
6713
  node: ">=22"
6674
6714
  },
6675
- gitHead: "679022e02d24c445bcf23235e1e68ff757830d84"
6715
+ gitHead: "0b7e13795e13a5539bc161e1a78750bd47bb09b4"
6676
6716
  };
6677
6717
 
6678
6718
  // src/paths.ts
@@ -6685,10 +6725,10 @@ function defaultDataDir(flavor, env = process.env, platform4 = process.platform)
6685
6725
  return env.MIKKA_USER_DATA_DIR;
6686
6726
  }
6687
6727
  const home = env.HOME || homedir3();
6688
- const base = platform4 === "darwin" ? join4(home, "Library", "Application Support") : platform4 === "win32" ? env.APPDATA || join4(home, "AppData", "Roaming") : env.XDG_CONFIG_HOME || join4(home, ".config");
6689
- const dir = join4(base, productName(flavor));
6690
- const legacy = join4(base, legacyProductName(flavor));
6691
- return !existsSync(dir) && existsSync(legacy) ? legacy : dir;
6728
+ const base = platform4 === "darwin" ? join5(home, "Library", "Application Support") : platform4 === "win32" ? env.APPDATA || join5(home, "AppData", "Roaming") : env.XDG_CONFIG_HOME || join5(home, ".config");
6729
+ const dir = join5(base, productName(flavor));
6730
+ const legacy = join5(base, legacyProductName(flavor));
6731
+ return !existsSync2(dir) && existsSync2(legacy) ? legacy : dir;
6692
6732
  }
6693
6733
  function legacyProductName(flavor) {
6694
6734
  return flavor === "dev" ? "Orvilo Dev" : "Orvilo";
@@ -6696,19 +6736,19 @@ function legacyProductName(flavor) {
6696
6736
  function daemonPaths(dataDir) {
6697
6737
  return {
6698
6738
  dataDir,
6699
- socket: join4(dataDir, "daemon.sock"),
6700
- lock: join4(dataDir, "daemon.lock"),
6701
- secret: join4(dataDir, "daemon.secret"),
6702
- device: join4(dataDir, "device.json"),
6703
- journal: join4(dataDir, "runs.json"),
6704
- outbox: join4(dataDir, "outbox"),
6705
- worktrees: join4(dataDir, "worktrees"),
6706
- repos: join4(dataDir, "repos"),
6707
- adapterState: join4(dataDir, "adapters"),
6739
+ socket: join5(dataDir, "daemon.sock"),
6740
+ lock: join5(dataDir, "daemon.lock"),
6741
+ secret: join5(dataDir, "daemon.secret"),
6742
+ device: join5(dataDir, "device.json"),
6743
+ journal: join5(dataDir, "runs.json"),
6744
+ outbox: join5(dataDir, "outbox"),
6745
+ worktrees: join5(dataDir, "worktrees"),
6746
+ repos: join5(dataDir, "repos"),
6747
+ adapterState: join5(dataDir, "adapters"),
6708
6748
  /** Pinned Claude Code and Codex the daemon installs for its runs. */
6709
- harness: join4(dataDir, "harness"),
6710
- logs: join4(dataDir, "logs"),
6711
- devRepos: join4(dataDir, "dev-repos.json")
6749
+ harness: join5(dataDir, "harness"),
6750
+ logs: join5(dataDir, "logs"),
6751
+ devRepos: join5(dataDir, "dev-repos.json")
6712
6752
  };
6713
6753
  }
6714
6754
 
@@ -7274,7 +7314,7 @@ async function createRunMailbox(host) {
7274
7314
  // src/run-drive.ts
7275
7315
  import { createHash as createHash3 } from "node:crypto";
7276
7316
  import { lstat, mkdir as mkdir2, readFile as readFile2, readdir, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
7277
- import { dirname as dirname4, extname, join as join5, relative, resolve as resolve3, sep } from "node:path";
7317
+ import { dirname as dirname4, extname, join as join6, relative, resolve as resolve3, sep } from "node:path";
7278
7318
  import { z as z35 } from "zod";
7279
7319
  var READ_LIMIT = 1024 * 1024;
7280
7320
  var WRITE_LIMIT = 4 * 1024 * 1024;
@@ -7300,7 +7340,7 @@ async function walk(folder) {
7300
7340
  const visit = async (dir) => {
7301
7341
  for (const entry of await readdir(dir, { withFileTypes: true })) {
7302
7342
  if (found.length >= MAX_FILES) return;
7303
- const full = join5(dir, entry.name);
7343
+ const full = join6(dir, entry.name);
7304
7344
  if (entry.isSymbolicLink()) continue;
7305
7345
  if (entry.isDirectory()) await visit(full);
7306
7346
  else if (entry.isFile()) found.push(relative(folder, full).split(sep).join("/"));
@@ -7315,8 +7355,8 @@ function createDriveMirror(options) {
7315
7355
  const { root, runId, call } = options;
7316
7356
  const warn = options.warn ?? (() => {
7317
7357
  });
7318
- const folderOf = (scope) => join5(root, scope.scope, scope.scopeId);
7319
- const stateFile = (scope) => join5(root, STATE_DIR, `${scope.scope}-${scope.scopeId}.json`);
7358
+ const folderOf = (scope) => join6(root, scope.scope, scope.scopeId);
7359
+ const stateFile = (scope) => join6(root, STATE_DIR, `${scope.scope}-${scope.scopeId}.json`);
7320
7360
  const target = (scope) => ({ scope: scope.scope, scopeId: scope.scopeId });
7321
7361
  const readState2 = async (scope) => {
7322
7362
  try {
@@ -7326,7 +7366,7 @@ function createDriveMirror(options) {
7326
7366
  }
7327
7367
  };
7328
7368
  const saveState = async (scope, state2) => {
7329
- await mkdir2(join5(root, STATE_DIR), { recursive: true, mode: 448 });
7369
+ await mkdir2(join6(root, STATE_DIR), { recursive: true, mode: 448 });
7330
7370
  await writeFile2(stateFile(scope), JSON.stringify(state2), { mode: 384 });
7331
7371
  };
7332
7372
  const list = async (scope, volumeId) => {
@@ -9312,14 +9352,14 @@ async function registrationLogin(options) {
9312
9352
  import { randomBytes as randomBytes6, randomUUID as randomUUID10 } from "node:crypto";
9313
9353
  import {
9314
9354
  chmodSync as chmodSync3,
9315
- existsSync as existsSync9,
9355
+ existsSync as existsSync10,
9316
9356
  mkdirSync as mkdirSync19,
9317
9357
  readFileSync as readFileSync15,
9318
9358
  rmSync as rmSync21,
9319
9359
  realpathSync as realpathSync15
9320
9360
  } from "node:fs";
9321
9361
  import { arch as arch3, hostname as hostname2, platform as platform3 } from "node:os";
9322
- import { join as join36 } from "node:path";
9362
+ import { join as join38 } from "node:path";
9323
9363
  import { fileURLToPath as fileURLToPath2 } from "node:url";
9324
9364
 
9325
9365
  // src/runs/quota-exhausted.ts
@@ -9403,7 +9443,7 @@ function quotaStopApplies(assignment) {
9403
9443
  import { spawn as spawn2 } from "node:child_process";
9404
9444
  import { randomUUID as randomUUID2 } from "node:crypto";
9405
9445
  import { realpathSync as realpathSync10 } from "node:fs";
9406
- import { join as join15 } from "node:path";
9446
+ import { join as join16 } from "node:path";
9407
9447
 
9408
9448
  // src/adapters/generation-metrics.ts
9409
9449
  var record2 = (value) => value && typeof value === "object" ? value : {};
@@ -9777,7 +9817,7 @@ import {
9777
9817
  rmSync as rmSync2,
9778
9818
  writeFileSync
9779
9819
  } from "node:fs";
9780
- import { join as join6 } from "node:path";
9820
+ import { join as join7 } from "node:path";
9781
9821
 
9782
9822
  // src/credential-globs.ts
9783
9823
  var CLOUD_WORKER_STATE_DIR = "/home/user/.mikka/worker/adapters";
@@ -9832,25 +9872,25 @@ var CODEX_CONFIG = [
9832
9872
  ].join("\n");
9833
9873
  function prepareCodexHome(dir, log) {
9834
9874
  ownDir(dir);
9835
- writeOwnFile(join6(dir, "config.toml"), CODEX_CONFIG);
9836
- if (lstatSync(join6(dir, "auth.json"), { throwIfNoEntry: false })) {
9875
+ writeOwnFile(join7(dir, "config.toml"), CODEX_CONFIG);
9876
+ if (lstatSync(join7(dir, "auth.json"), { throwIfNoEntry: false })) {
9837
9877
  log.warn("removing a credential file left in the run's codex home");
9838
- rmSync2(join6(dir, "auth.json"), { force: true, recursive: true });
9878
+ rmSync2(join7(dir, "auth.json"), { force: true, recursive: true });
9839
9879
  }
9840
9880
  return { home: dir };
9841
9881
  }
9842
9882
  function wipeRunCredentials(runDir) {
9843
- for (const path3 of RUN_CREDENTIAL_PATHS) rmSync2(join6(runDir, path3), { force: true, recursive: true });
9883
+ for (const path3 of RUN_CREDENTIAL_PATHS) rmSync2(join7(runDir, path3), { force: true, recursive: true });
9844
9884
  }
9845
9885
  function sweepRunCredentials(stateDir) {
9846
- rmSync2(join6(stateDir, "github"), { recursive: true, force: true });
9886
+ rmSync2(join7(stateDir, "github"), { recursive: true, force: true });
9847
9887
  let runs;
9848
9888
  try {
9849
- runs = readdirSync(join6(stateDir, "runs"));
9889
+ runs = readdirSync(join7(stateDir, "runs"));
9850
9890
  } catch {
9851
9891
  return;
9852
9892
  }
9853
- for (const run3 of runs) wipeRunCredentials(join6(stateDir, "runs", run3));
9893
+ for (const run3 of runs) wipeRunCredentials(join7(stateDir, "runs", run3));
9854
9894
  }
9855
9895
  function writeOwnFile(file, content) {
9856
9896
  rmSync2(file, { force: true, recursive: true });
@@ -9865,9 +9905,9 @@ function carryHistory(from, to, entries) {
9865
9905
  if (!lstatSync(from, { throwIfNoEntry: false })?.isDirectory()) return;
9866
9906
  ownDir(to);
9867
9907
  for (const entry of entries) {
9868
- const source = join6(from, entry);
9908
+ const source = join7(from, entry);
9869
9909
  if (!lstatSync(source, { throwIfNoEntry: false })) continue;
9870
- cpSync(source, join6(to, entry), {
9910
+ cpSync(source, join7(to, entry), {
9871
9911
  recursive: true,
9872
9912
  force: true,
9873
9913
  filter: (path3) => !lstatSync(path3).isSymbolicLink()
@@ -10061,17 +10101,17 @@ function errorMessage(error) {
10061
10101
  }
10062
10102
 
10063
10103
  // src/agents/github-runtime.ts
10064
- import { existsSync as existsSync3, lstatSync as lstatSync4, mkdirSync as mkdirSync6, mkdtempSync as mkdtempSync2, realpathSync as realpathSync7, rmSync as rmSync6, writeFileSync as writeFileSync3 } from "node:fs";
10065
- import { delimiter as delimiter2, join as join10, resolve as resolve7 } from "node:path";
10104
+ import { existsSync as existsSync4, lstatSync as lstatSync4, mkdirSync as mkdirSync6, mkdtempSync as mkdtempSync2, realpathSync as realpathSync7, rmSync as rmSync6, writeFileSync as writeFileSync3 } from "node:fs";
10105
+ import { delimiter as delimiter2, join as join11, resolve as resolve7 } from "node:path";
10066
10106
  import { execa as execa4 } from "execa";
10067
10107
 
10068
10108
  // src/path-search.ts
10069
10109
  import { accessSync, constants, statSync } from "node:fs";
10070
- import { delimiter, isAbsolute, join as join7 } from "node:path";
10110
+ import { delimiter, isAbsolute, join as join8 } from "node:path";
10071
10111
  function findOnPath(command, path3 = process.env.PATH ?? "") {
10072
10112
  for (const directory of path3.split(delimiter)) {
10073
10113
  if (!directory) continue;
10074
- const candidate = join7(directory, command);
10114
+ const candidate = join8(directory, command);
10075
10115
  try {
10076
10116
  accessSync(candidate, constants.X_OK);
10077
10117
  if (statSync(candidate).isFile()) return candidate;
@@ -10090,7 +10130,7 @@ import {
10090
10130
  rmSync as rmSync5
10091
10131
  } from "node:fs";
10092
10132
  import { tmpdir } from "node:os";
10093
- import { basename, dirname as dirname7, join as join9, resolve as resolve5 } from "node:path";
10133
+ import { basename, dirname as dirname7, join as join10, resolve as resolve5 } from "node:path";
10094
10134
 
10095
10135
  // src/ids.ts
10096
10136
  var SAFE_ID = /^[A-Za-z0-9_-]{1,64}$/;
@@ -10149,7 +10189,7 @@ function withoutTaskEnv(assignment) {
10149
10189
  import {
10150
10190
  appendFileSync,
10151
10191
  copyFileSync,
10152
- existsSync as existsSync2,
10192
+ existsSync as existsSync3,
10153
10193
  lstatSync as lstatSync2,
10154
10194
  mkdirSync as mkdirSync5,
10155
10195
  readdirSync as readdirSync2,
@@ -10158,7 +10198,7 @@ import {
10158
10198
  rmSync as rmSync4
10159
10199
  } from "node:fs";
10160
10200
  import { lstat as lstat2, readdir as readdir2 } from "node:fs/promises";
10161
- import { dirname as dirname6, isAbsolute as isAbsolute2, join as join8, relative as relative2, resolve as resolve4 } from "node:path";
10201
+ import { dirname as dirname6, isAbsolute as isAbsolute2, join as join9, relative as relative2, resolve as resolve4 } from "node:path";
10162
10202
  import { execa as execa2 } from "execa";
10163
10203
  import { simpleGit } from "simple-git";
10164
10204
 
@@ -10279,7 +10319,7 @@ var WorktreeManager = class {
10279
10319
  async create(runId, repoPath, baseBranch) {
10280
10320
  await excludeVerifyArtifacts(repoPath);
10281
10321
  const path3 = this.pathFor(runId);
10282
- if (existsSync2(join8(path3, ".git"))) return path3;
10322
+ if (existsSync3(join9(path3, ".git"))) return path3;
10283
10323
  mkdirSync5(this.root, { recursive: true });
10284
10324
  await withRepoConfig(
10285
10325
  repoPath,
@@ -10346,7 +10386,7 @@ var WorktreeManager = class {
10346
10386
  const root = resolve4(this.root);
10347
10387
  const path3 = resolve4(previousWorktree);
10348
10388
  if (dirname6(path3) !== root) return null;
10349
- if (!existsSync2(join8(path3, ".git"))) return null;
10389
+ if (!existsSync3(join9(path3, ".git"))) return null;
10350
10390
  let gitDir;
10351
10391
  try {
10352
10392
  gitDir = await worktreeGitDir(repoPath, path3);
@@ -10384,7 +10424,7 @@ var WorktreeManager = class {
10384
10424
  if (rel === "" || rel.startsWith("..") || isAbsolute2(rel)) {
10385
10425
  throw new Error(`setup recipe copies a file outside the repo: ${file}`);
10386
10426
  }
10387
- const from = join8(repoPath, rel);
10427
+ const from = join9(repoPath, rel);
10388
10428
  const fromStat = lstatSync2(from, { throwIfNoEntry: false });
10389
10429
  if (!fromStat) continue;
10390
10430
  if (!fromStat.isFile() || !isInside(repoReal, realpathSync4(from))) {
@@ -10392,7 +10432,7 @@ var WorktreeManager = class {
10392
10432
  `setup recipe copies a symlink or non-file, or leaves the repo: ${file}`
10393
10433
  );
10394
10434
  }
10395
- const to = join8(worktree, rel);
10435
+ const to = join9(worktree, rel);
10396
10436
  mkdirSync5(dirname6(to), { recursive: true });
10397
10437
  const toStat = lstatSync2(to, { throwIfNoEntry: false });
10398
10438
  if (!isInside(worktreeReal, realpathSync4(dirname6(to))) || toStat && !toStat.isFile()) {
@@ -10441,7 +10481,7 @@ var WorktreeManager = class {
10441
10481
  const path3 = worktree ? resolve4(worktree) : null;
10442
10482
  if (path3 && dirname6(path3) !== root) return false;
10443
10483
  const git3 = simpleGit(repoPath);
10444
- if (path3 && existsSync2(join8(path3, ".git"))) {
10484
+ if (path3 && existsSync3(join9(path3, ".git"))) {
10445
10485
  if ((await this.changedFiles(path3)).length > 0) return false;
10446
10486
  }
10447
10487
  const branches = [];
@@ -10530,7 +10570,7 @@ var WorktreeManager = class {
10530
10570
  const removed = [];
10531
10571
  for (const run3 of finished) {
10532
10572
  if (now - Date.parse(run3.finishedAt) < retentionMs) continue;
10533
- if (!existsSync2(this.pathFor(run3.runId))) continue;
10573
+ if (!existsSync3(this.pathFor(run3.runId))) continue;
10534
10574
  await this.remove(run3.runId, run3.repoPath);
10535
10575
  removed.push(run3.runId);
10536
10576
  }
@@ -10540,11 +10580,11 @@ var WorktreeManager = class {
10540
10580
  async function excludeVerifyArtifacts(repoPath) {
10541
10581
  await withRepoConfig(repoPath, async () => {
10542
10582
  const common2 = (await simpleGit(repoPath).raw(["rev-parse", "--path-format=absolute", "--git-common-dir"])).trim();
10543
- const info = join8(common2, "info");
10583
+ const info = join9(common2, "info");
10544
10584
  mkdirSync5(info, { recursive: true });
10545
- const file = join8(info, "exclude");
10546
- if (existsSync2(file) && !lstatSync2(file).isFile()) throw new Error("Invalid repository exclude file");
10547
- const existing = existsSync2(file) ? readFileSync4(file, "utf8") : "";
10585
+ const file = join9(info, "exclude");
10586
+ if (existsSync3(file) && !lstatSync2(file).isFile()) throw new Error("Invalid repository exclude file");
10587
+ const existing = existsSync3(file) ? readFileSync4(file, "utf8") : "";
10548
10588
  if (!existing.split(/\r?\n/).includes("/.verify/")) appendFileSync(file, "\n/.verify/\n");
10549
10589
  });
10550
10590
  }
@@ -10563,7 +10603,7 @@ async function du(path3) {
10563
10603
  return 0;
10564
10604
  }
10565
10605
  let total = 0;
10566
- for (const entry of entries) total += await du(join8(path3, entry));
10606
+ for (const entry of entries) total += await du(join9(path3, entry));
10567
10607
  return total;
10568
10608
  }
10569
10609
 
@@ -10603,10 +10643,10 @@ async function worktreeGitDir(repoPath, worktree, signal) {
10603
10643
  }
10604
10644
  )).stdout.trim()
10605
10645
  );
10606
- const dotGit = join9(realpathSync5(worktree), ".git");
10607
- const root = join9(common2, "worktrees");
10646
+ const dotGit = join10(realpathSync5(worktree), ".git");
10647
+ const root = join10(common2, "worktrees");
10608
10648
  for (const name of readdirSync3(root)) {
10609
- const gitdirFile = join9(root, name, "gitdir");
10649
+ const gitdirFile = join10(root, name, "gitdir");
10610
10650
  let target;
10611
10651
  try {
10612
10652
  target = readFileSync5(gitdirFile, "utf8").trim();
@@ -10614,7 +10654,7 @@ async function worktreeGitDir(repoPath, worktree, signal) {
10614
10654
  continue;
10615
10655
  }
10616
10656
  if (target === dotGit || safeRealpath(target) === dotGit) {
10617
- return join9(root, name);
10657
+ return join10(root, name);
10618
10658
  }
10619
10659
  }
10620
10660
  throw new Error(`${worktree} is not a worktree of ${repoPath}`);
@@ -10651,8 +10691,8 @@ async function pinnedGit(repoPath, worktree, env = process.env, signal) {
10651
10691
  }
10652
10692
  async function snapshotTree(repoPath, worktree, env, signal) {
10653
10693
  const git3 = await pinnedGit(repoPath, worktree, env, signal);
10654
- const dir = mkdtempSync(join9(tmpdir(), "mikka-index-"));
10655
- const index = { GIT_INDEX_FILE: join9(dir, "index") };
10694
+ const dir = mkdtempSync(join10(tmpdir(), "mikka-index-"));
10695
+ const index = { GIT_INDEX_FILE: join10(dir, "index") };
10656
10696
  try {
10657
10697
  await git3(["read-tree", "HEAD"], index);
10658
10698
  await git3(["add", "--all"], index);
@@ -10878,19 +10918,19 @@ function githubReceiptEnvironment(host = process.env) {
10878
10918
  function prepareGitHubEnvironment(runDir, github, path3, runtime) {
10879
10919
  const endpoint = new URL(github.endpoint);
10880
10920
  if (!endpoint.pathname.endsWith("/api/runs/github-token") || !trustedServerEndpoint(endpoint)) throw new Error("Invalid run GitHub endpoint");
10881
- const gh = runtime?.ghBinary ?? path3.split(delimiter2).map((dir2) => join10(dir2, "gh")).find((file) => existsSync3(file));
10921
+ const gh = runtime?.ghBinary ?? path3.split(delimiter2).map((dir2) => join11(dir2, "gh")).find((file) => existsSync4(file));
10882
10922
  const node = runtime?.nodeBinary ?? process.execPath;
10883
10923
  if (!gh) throw new Error("Install GitHub CLI (gh) before running GitHub tasks");
10884
- const dir = join10(runDir, "github");
10924
+ const dir = join11(runDir, "github");
10885
10925
  mkdirSync6(dir, { recursive: true, mode: 448 });
10886
- if (!lstatSync4(dir).isDirectory() || realpathSync7(dir) !== join10(realpathSync7(runDir), "github")) throw new Error("Invalid run GitHub directory");
10887
- const config = join10(dir, "config.json");
10926
+ if (!lstatSync4(dir).isDirectory() || realpathSync7(dir) !== join11(realpathSync7(runDir), "github")) throw new Error("Invalid run GitHub directory");
10927
+ const config = join11(dir, "config.json");
10888
10928
  rmSync6(config, { force: true });
10889
10929
  writeFileSync3(config, JSON.stringify({ ...github, gh }), { mode: 384, flag: "wx" });
10890
- const bin = join10(dir, "bin");
10930
+ const bin = join11(dir, "bin");
10891
10931
  mkdirSync6(bin, { recursive: true, mode: 448 });
10892
- if (!lstatSync4(bin).isDirectory() || realpathSync7(bin) !== join10(realpathSync7(dir), "bin")) throw new Error("Invalid run GitHub executable directory");
10893
- const wrapper = join10(bin, "gh");
10932
+ if (!lstatSync4(bin).isDirectory() || realpathSync7(bin) !== join11(realpathSync7(dir), "bin")) throw new Error("Invalid run GitHub executable directory");
10933
+ const wrapper = join11(bin, "gh");
10894
10934
  rmSync6(wrapper, { force: true });
10895
10935
  const fixtureConfig = localGitConfig();
10896
10936
  const fixtureProxy = fixtureConfig.length ? 'case "${HTTP_PROXY:-${http_proxy:-}}" in http://*@localhost:*|http://*@127.0.0.1:*) unset NO_PROXY no_proxy ;; esac\n' : "";
@@ -10939,7 +10979,7 @@ async function withRunGitCredentials(assignment, privateDir, work, preparedEnvir
10939
10979
  } });
10940
10980
  }
10941
10981
  mkdirSync6(privateDir, { recursive: true, mode: 448 });
10942
- const dir = mkdtempSync2(join10(privateDir, "github-fetch-"));
10982
+ const dir = mkdtempSync2(join11(privateDir, "github-fetch-"));
10943
10983
  try {
10944
10984
  let env = {};
10945
10985
  try {
@@ -10963,7 +11003,7 @@ async function agentPublishedReceipt(input) {
10963
11003
  if (!input.github.branch) throw new Error("No task branch to read back");
10964
11004
  const branch = input.github.branch;
10965
11005
  mkdirSync6(input.privateDir, { recursive: true, mode: 448 });
10966
- const receiptDir = mkdtempSync2(join10(input.privateDir, "github-receipt-"));
11006
+ const receiptDir = mkdtempSync2(join11(input.privateDir, "github-receipt-"));
10967
11007
  const nativeGitHub = input.hosted || Boolean(input.githubEnvironment);
10968
11008
  try {
10969
11009
  const env = {
@@ -10993,7 +11033,7 @@ async function agentPublishedReceipt(input) {
10993
11033
  try {
10994
11034
  const gh = (args) => {
10995
11035
  input.signal?.throwIfAborted();
10996
- return execa4(nativeGitHub ? "gh" : join10(receiptDir, "github", "bin", "gh"), args, { cwd: input.worktree, env, extendEnv: false, stdin: "ignore", cancelSignal: input.signal, killDescendants: true });
11036
+ return execa4(nativeGitHub ? "gh" : join11(receiptDir, "github", "bin", "gh"), args, { cwd: input.worktree, env, extendEnv: false, stdin: "ignore", cancelSignal: input.signal, killDescendants: true });
10997
11037
  };
10998
11038
  const [owner, repository2] = input.github.repository.split("/");
10999
11039
  const query2 = "query($owner:String!,$repository:String!,$commit:GitObjectID!){repository(owner:$owner,name:$repository){object(oid:$commit){... on Commit {oid statusCheckRollup{state}}}}}";
@@ -11085,7 +11125,7 @@ import {
11085
11125
  writeFileSync as writeFileSync4
11086
11126
  } from "node:fs";
11087
11127
  import { homedir as homedir5 } from "node:os";
11088
- import { dirname as dirname11, join as join14, resolve as resolve11 } from "node:path";
11128
+ import { dirname as dirname11, join as join15, resolve as resolve11 } from "node:path";
11089
11129
 
11090
11130
  // src/agents/skill-artifact.ts
11091
11131
  import { createHash as createHash5 } from "node:crypto";
@@ -11118,7 +11158,7 @@ import {
11118
11158
  basename as basename3,
11119
11159
  dirname as dirname9,
11120
11160
  isAbsolute as isAbsolute3,
11121
- join as join11,
11161
+ join as join12,
11122
11162
  relative as relative3,
11123
11163
  resolve as resolve9
11124
11164
  } from "node:path";
@@ -11209,7 +11249,7 @@ function realTarget(path3) {
11209
11249
  let current = path3;
11210
11250
  for (let hops = 0; ; ) {
11211
11251
  try {
11212
- return join11(realpathSync8(current), ...[...missing2].reverse());
11252
+ return join12(realpathSync8(current), ...[...missing2].reverse());
11213
11253
  } catch {
11214
11254
  if (lstatSync6(current, { throwIfNoEntry: false })?.isSymbolicLink()) {
11215
11255
  if (++hops > 40) return path3;
@@ -11237,7 +11277,7 @@ function classifyWrite(worktree, target) {
11237
11277
  // src/captures.ts
11238
11278
  import { createHash as createHash7 } from "node:crypto";
11239
11279
  import { closeSync as closeSync2, constants as constants3, createReadStream, fstatSync, lstatSync as lstatSync7, mkdirSync as mkdirSync7, mkdtempSync as mkdtempSync3, openSync as openSync2, readFileSync as readFileSync7, readSync, readdirSync as readdirSync4, rmSync as rmSync7 } from "node:fs";
11240
- import { join as join13 } from "node:path";
11280
+ import { join as join14 } from "node:path";
11241
11281
  import { tmpdir as tmpdir3 } from "node:os";
11242
11282
 
11243
11283
  // src/agents/capture-video.mjs
@@ -11245,7 +11285,7 @@ import { execFile as execFile3 } from "node:child_process";
11245
11285
  import { createHash as createHash6 } from "node:crypto";
11246
11286
  import { constants as constants2, createWriteStream } from "node:fs";
11247
11287
  import { chmod, lstat as lstat3, mkdir as mkdir3, mkdtemp, open, readFile as readFile3, rename, rm as rm3, stat } from "node:fs/promises";
11248
- import { dirname as dirname10, basename as basename4, join as join12, resolve as resolve10 } from "node:path";
11288
+ import { dirname as dirname10, basename as basename4, join as join13, resolve as resolve10 } from "node:path";
11249
11289
  import { devNull } from "node:os";
11250
11290
  import { pipeline } from "node:stream/promises";
11251
11291
  import { pathToFileURL as pathToFileURL2 } from "node:url";
@@ -11313,7 +11353,7 @@ async function captureVideoBinaries({ directory = CAPTURE_TOOLS_DIRECTORY, owner
11313
11353
  if (!info) return { ffmpeg: "ffmpeg", ffprobe: "ffprobe" };
11314
11354
  try {
11315
11355
  if (!info.isDirectory() || info.uid !== ownerId || info.mode & 18) throw new Error("Private capture tools directory is unsafe");
11316
- const binaries = { ffmpeg: join12(directory, "ffmpeg"), ffprobe: join12(directory, "ffprobe") };
11356
+ const binaries = { ffmpeg: join13(directory, "ffmpeg"), ffprobe: join13(directory, "ffprobe") };
11317
11357
  for (const path3 of Object.values(binaries)) {
11318
11358
  const binary = await lstat3(path3);
11319
11359
  if (!binary.isFile() || binary.uid !== ownerId || binary.mode & 18 || !(binary.mode & 73)) throw new Error("Private capture tool is unsafe");
@@ -11404,7 +11444,7 @@ async function processCaptureVideo(input, output, options = {}) {
11404
11444
  const deadline = Date.now() + Math.min(options.timeoutMs ?? 9e4, 18e4);
11405
11445
  const binaries = await captureVideoBinaries();
11406
11446
  await mkdir3(dirname10(output), { recursive: true, mode: 448 });
11407
- const temporary = await mkdtemp(join12(dirname10(output), ".capture-process-"));
11447
+ const temporary = await mkdtemp(join13(dirname10(output), ".capture-process-"));
11408
11448
  await chmod(temporary, 448);
11409
11449
  const run3 = async (binary, args) => {
11410
11450
  options.signal?.throwIfAborted();
@@ -11444,12 +11484,12 @@ async function processCaptureVideo(input, output, options = {}) {
11444
11484
  return { durationMs: Math.round(seconds * 1e3), width: stream.width, height: stream.height };
11445
11485
  };
11446
11486
  try {
11447
- const source = join12(temporary, "source.video");
11487
+ const source = join13(temporary, "source.video");
11448
11488
  const originalFile = await snapshot2(input, source, options.signal);
11449
11489
  const original = await probe(source);
11450
11490
  const windows = recordingWindows(original.durationMs, steps);
11451
11491
  const retainedMs = windows.reduce((total, window) => total + window.endMs - window.startMs, 0);
11452
- const result = join12(temporary, "final.mp4");
11492
+ const result = join13(temporary, "final.mp4");
11453
11493
  const base = [
11454
11494
  "-y",
11455
11495
  "-nostdin",
@@ -11489,7 +11529,7 @@ async function processCaptureVideo(input, output, options = {}) {
11489
11529
  "2",
11490
11530
  "-pix_fmt",
11491
11531
  "yuv420p",
11492
- ...rate ? ["-b:v", `${rate}k`, "-pass", String(pass), "-passlogfile", join12(temporary, "pass")] : ["-crf", "28"],
11532
+ ...rate ? ["-b:v", `${rate}k`, "-pass", String(pass), "-passlogfile", join13(temporary, "pass")] : ["-crf", "28"],
11493
11533
  ...pass === 1 ? ["-f", "null", devNull] : ["-movflags", "+faststart", result]
11494
11534
  ]);
11495
11535
  };
@@ -11566,7 +11606,7 @@ function readPlain(path3, max) {
11566
11606
  }
11567
11607
  }
11568
11608
  var drop = (dir, id5) => {
11569
- for (const name of [`${id5}.json`, ...EXTENSIONS.map((ext) => `${id5}.${ext}`)]) rmSync7(join13(dir, name), { force: true });
11609
+ for (const name of [`${id5}.json`, ...EXTENSIONS.map((ext) => `${id5}.${ext}`)]) rmSync7(join14(dir, name), { force: true });
11570
11610
  };
11571
11611
  async function hashPlain(path3, signal) {
11572
11612
  signal?.throwIfAborted();
@@ -11584,9 +11624,9 @@ async function hashPlain(path3, signal) {
11584
11624
  }
11585
11625
  async function prepareVideo(file, id5, steps, pendingDir, signal) {
11586
11626
  signal?.throwIfAborted();
11587
- const directory = pendingDir ?? mkdtempSync3(join13(tmpdir3(), "mikka-capture-pending-"));
11627
+ const directory = pendingDir ?? mkdtempSync3(join14(tmpdir3(), "mikka-capture-pending-"));
11588
11628
  mkdirSync7(directory, { recursive: true, mode: 448 });
11589
- const output = join13(directory, `${id5}.processed.mp4`), receipt = join13(directory, `${id5}.video.json`);
11629
+ const output = join14(directory, `${id5}.processed.mp4`), receipt = join14(directory, `${id5}.video.json`);
11590
11630
  try {
11591
11631
  const originalHash = await hashPlain(file, signal);
11592
11632
  const stepHash = createHash7("sha256").update(JSON.stringify(steps)).digest("hex");
@@ -11617,7 +11657,7 @@ async function prepareVideo(file, id5, steps, pendingDir, signal) {
11617
11657
  }
11618
11658
  function dropPrepared(pendingDir, id5) {
11619
11659
  if (!pendingDir) return;
11620
- for (const name of [`${id5}.json`, `${id5}.processed.mp4`, `${id5}.video.json`]) rmSync7(join13(pendingDir, name), { force: true });
11660
+ for (const name of [`${id5}.json`, `${id5}.processed.mp4`, `${id5}.video.json`]) rmSync7(join14(pendingDir, name), { force: true });
11621
11661
  }
11622
11662
  function fileType(path3) {
11623
11663
  let fd;
@@ -11644,7 +11684,7 @@ async function uploadCaptures(dir, runId, link, log, pendingDir, existingOnly =
11644
11684
  signal?.throwIfAborted();
11645
11685
  const id5 = name.endsWith(".json") ? name.slice(0, -5) : "";
11646
11686
  if (!ID.test(id5)) continue;
11647
- const meta = readPlain(join13(dir, name), 128e3);
11687
+ const meta = readPlain(join14(dir, name), 128e3);
11648
11688
  let title2 = "";
11649
11689
  let steps = [];
11650
11690
  try {
@@ -11654,7 +11694,7 @@ async function uploadCaptures(dir, runId, link, log, pendingDir, existingOnly =
11654
11694
  } catch {
11655
11695
  title2 = "";
11656
11696
  }
11657
- const file = EXTENSIONS.map((ext) => join13(dir, `${id5}.${ext}`)).find((path3) => lstatSync7(path3, { throwIfNoEntry: false }));
11697
+ const file = EXTENSIONS.map((ext) => join14(dir, `${id5}.${ext}`)).find((path3) => lstatSync7(path3, { throwIfNoEntry: false }));
11658
11698
  const originalType = file ? fileType(file) : null;
11659
11699
  let video;
11660
11700
  if (file && title2 && originalType?.startsWith("video/")) {
@@ -11677,7 +11717,7 @@ async function uploadCaptures(dir, runId, link, log, pendingDir, existingOnly =
11677
11717
  }
11678
11718
  try {
11679
11719
  const sha2562 = createHash7("sha256").update(bytes).digest("hex");
11680
- const pendingPath = pendingDir ? join13(pendingDir, `${id5}.json`) : null;
11720
+ const pendingPath = pendingDir ? join14(pendingDir, `${id5}.json`) : null;
11681
11721
  let pending;
11682
11722
  if (pendingPath) {
11683
11723
  try {
@@ -11735,7 +11775,7 @@ async function uploadCaptures(dir, runId, link, log, pendingDir, existingOnly =
11735
11775
  log.warn({ run_id: runId, capture: id5, status: error.code }, "capture reservation unavailable; retry stopped");
11736
11776
  if (pendingDir) {
11737
11777
  mkdirSync7(pendingDir, { recursive: true, mode: 448 });
11738
- writeJsonAtomic(join13(pendingDir, "blocked.json"), { status: error.code });
11778
+ writeJsonAtomic(join14(pendingDir, "blocked.json"), { status: error.code });
11739
11779
  }
11740
11780
  return sent;
11741
11781
  }
@@ -11761,8 +11801,8 @@ var CaptureUploader = class {
11761
11801
  /** A final signal bounds both this pass and any earlier pass still in flight. */
11762
11802
  flush(runId, existingOnly = false, signal) {
11763
11803
  if (!/^[A-Za-z0-9_-]{1,64}$/.test(runId)) return Promise.resolve();
11764
- const pendingDir = this.pendingRoot ? join13(this.pendingRoot, runId) : void 0;
11765
- if (pendingDir && lstatSync7(join13(pendingDir, "blocked.json"), { throwIfNoEntry: false }))
11804
+ const pendingDir = this.pendingRoot ? join14(this.pendingRoot, runId) : void 0;
11805
+ if (pendingDir && lstatSync7(join14(pendingDir, "blocked.json"), { throwIfNoEntry: false }))
11766
11806
  return signal ? Promise.reject(new Error("Capture upload incomplete")) : Promise.resolve();
11767
11807
  const pass = this.passes.get(runId) ?? { tail: Promise.resolve(), abort: new AbortController() };
11768
11808
  const abort = () => pass.abort.abort(signal?.reason);
@@ -11838,7 +11878,7 @@ function credentialDenyRead(harness, home = homedir5()) {
11838
11878
  // Other harnesses' logins; each harness still reads its own.
11839
11879
  ...harness === "codex" ? [] : [".codex/auth.json"],
11840
11880
  ...harness === "claude_code" ? [] : [".claude/.credentials.json"]
11841
- ].map((path3) => join14(home, path3));
11881
+ ].map((path3) => join15(home, path3));
11842
11882
  }
11843
11883
  function daemonSecrets(dataDir) {
11844
11884
  const paths = daemonPaths(realpathSync9(dataDir));
@@ -11849,7 +11889,7 @@ function daemonSecrets(dataDir) {
11849
11889
  paths.outbox,
11850
11890
  paths.logs,
11851
11891
  paths.devRepos,
11852
- join14(paths.adapterState, "pids")
11892
+ join15(paths.adapterState, "pids")
11853
11893
  ];
11854
11894
  }
11855
11895
  function runPaths(stateDir, runId) {
@@ -11858,9 +11898,9 @@ function runPaths(stateDir, runId) {
11858
11898
  /** The daemon's data dir (`stateDir` is `<dataDir>/adapters`). */
11859
11899
  privateDir: resolve11(stateDir, ".."),
11860
11900
  /** Writable from the sandbox. */
11861
- runDir: join14(stateDir, "runs", id5),
11901
+ runDir: join15(stateDir, "runs", id5),
11862
11902
  /** Daemon only. */
11863
- pidFile: join14(stateDir, "pids", `${id5}.pgid`)
11903
+ pidFile: join15(stateDir, "pids", `${id5}.pgid`)
11864
11904
  };
11865
11905
  }
11866
11906
  function repositorySkill(worktree, slug) {
@@ -11868,7 +11908,7 @@ function repositorySkill(worktree, slug) {
11868
11908
  const missing2 = (reason) => ({ id: id5, name: slug, description: "", source: "repository", digest: null, instructions: null, available: false, reason });
11869
11909
  if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(slug)) return missing2("invalid");
11870
11910
  for (const root of [".claude/skills", ".agents/skills"]) {
11871
- const file = join14(worktree, root, slug, SKILL_BODY_FILE);
11911
+ const file = join15(worktree, root, slug, SKILL_BODY_FILE);
11872
11912
  const meta = lstatSync8(file, { throwIfNoEntry: false });
11873
11913
  if (!meta) continue;
11874
11914
  if (!meta.isFile() || meta.isSymbolicLink() || meta.nlink !== 1 || meta.size < 1 || meta.size > MAX_PROFILE_SKILL_INSTRUCTIONS_LENGTH) return missing2("invalid");
@@ -11910,10 +11950,10 @@ function writeProfileSkillManifest(options, runDir, worktree, includeRepository)
11910
11950
  }
11911
11951
  for (const slug of declared) entries.push(includeRepository ? repositorySkill(worktree, slug) : { id: `repository:${slug}`, name: slug, description: "", source: "repository", digest: null, instructions: null, available: false, reason: "pending" });
11912
11952
  const unique = [...new Map(entries.map((entry) => [entry.id, entry])).values()];
11913
- const dir = join14(runDir, PROFILE_SKILLS_DIR);
11953
+ const dir = join15(runDir, PROFILE_SKILLS_DIR);
11914
11954
  ownDir(dir);
11915
11955
  const manifest = { version: 1, skills: unique };
11916
- const file = join14(dir, PROFILE_SKILL_MANIFEST_FILE);
11956
+ const file = join15(dir, PROFILE_SKILL_MANIFEST_FILE);
11917
11957
  const tmp = `${file}.${process.pid}.tmp`;
11918
11958
  writeFileSync4(tmp, `${JSON.stringify(manifest)}
11919
11959
  `, { encoding: "utf8", mode: 384 });
@@ -11926,9 +11966,9 @@ function prepareRunContextFiles(options) {
11926
11966
  const files2 = {
11927
11967
  worktree: resolve11(options.worktree),
11928
11968
  runDir,
11929
- handoffFile: join14(runDir, "handoff.json"),
11930
- tmpDir: join14(runDir, "tmp"),
11931
- capturesDir: join14(runDir, CAPTURES_DIR)
11969
+ handoffFile: join15(runDir, "handoff.json"),
11970
+ tmpDir: join15(runDir, "tmp"),
11971
+ capturesDir: join15(runDir, CAPTURES_DIR)
11932
11972
  };
11933
11973
  ownDir(files2.tmpDir);
11934
11974
  ownDir(files2.capturesDir);
@@ -11962,7 +12002,7 @@ function runMcpServer(options, files2) {
11962
12002
  files2.worktree,
11963
12003
  "--capture-root",
11964
12004
  files2.tmpDir,
11965
- ...options.profileSkills?.length || options.repositorySkills?.length ? ["--profile-skills", join14(files2.runDir, PROFILE_SKILLS_DIR)] : [],
12005
+ ...options.profileSkills?.length || options.repositorySkills?.length ? ["--profile-skills", join15(files2.runDir, PROFILE_SKILLS_DIR)] : [],
11966
12006
  ...options.factoryCheck && (!options.factoryCheck.reportOnly || options.factoryCheck.inferCommand) ? ["--factory-verify", JSON.stringify({ cwd: files2.worktree, command: options.verifyCommand ?? null, infer: options.factoryCheck.inferCommand })] : [],
11967
12007
  ...options.factoryCheck?.reportOnly || readOnlyInspection ? ["--factory-artifacts", files2.worktree] : [],
11968
12008
  ...repositoryExecution ? ["--repository-selection", files2.worktree] : []
@@ -12010,13 +12050,13 @@ var RunContext = class {
12010
12050
  );
12011
12051
  ownDir(options.runDir);
12012
12052
  this.runDir = realpathSync9(options.runDir);
12013
- this.handoffFile = join14(this.runDir, "handoff.json");
12014
- this.skillsDir = join14(this.runDir, SKILLS_DIR);
12015
- this.tmpDir = join14(this.runDir, "tmp");
12053
+ this.handoffFile = join15(this.runDir, "handoff.json");
12054
+ this.skillsDir = join15(this.runDir, SKILLS_DIR);
12055
+ this.tmpDir = join15(this.runDir, "tmp");
12016
12056
  ownDir(this.tmpDir);
12017
- this.capturesDir = join14(this.runDir, CAPTURES_DIR);
12057
+ this.capturesDir = join15(this.runDir, CAPTURES_DIR);
12018
12058
  ownDir(this.capturesDir);
12019
- this.profileSkillsDir = join14(this.runDir, PROFILE_SKILLS_DIR);
12059
+ this.profileSkillsDir = join15(this.runDir, PROFILE_SKILLS_DIR);
12020
12060
  this.writeSkills();
12021
12061
  this.writeProfileSkills();
12022
12062
  if (options.github && !options.machineEnvironment) {
@@ -12059,19 +12099,19 @@ var RunContext = class {
12059
12099
  let slug = base;
12060
12100
  for (let n = 2; taken.has(slug); n += 1) slug = `${base}-${n}`;
12061
12101
  taken.add(slug);
12062
- const dir = join14(this.skillsDir, slug);
12102
+ const dir = join15(this.skillsDir, slug);
12063
12103
  if (this.options.skillReceipt) {
12064
12104
  const existing = lstatSync8(dir, { throwIfNoEntry: false });
12065
12105
  if (existing && (!existing.isDirectory() || existing.isSymbolicLink())) throw new Error("Unsafe Skill artifact directory");
12066
- const file = lstatSync8(join14(dir, SKILL_BODY_FILE), { throwIfNoEntry: false });
12106
+ const file = lstatSync8(join15(dir, SKILL_BODY_FILE), { throwIfNoEntry: false });
12067
12107
  if (file && (!file.isFile() || file.isSymbolicLink() || file.nlink !== 1)) throw new Error("Unsafe Skill artifact file");
12068
12108
  }
12069
12109
  mkdirSync8(dir, { recursive: true });
12070
- const bodyFile = join14(dir, SKILL_BODY_FILE);
12110
+ const bodyFile = join15(dir, SKILL_BODY_FILE);
12071
12111
  if (this.options.skillReceipt) {
12072
12112
  if (!lstatSync8(bodyFile, { throwIfNoEntry: false })) writeFileSync4(bodyFile, skillMarkdown(skill), { encoding: "utf8", flag: "wx", mode: 384 });
12073
12113
  } else writeFileSync4(bodyFile, skillMarkdown(skill), "utf8");
12074
- if (this.options.skillReceipt) verifyMountedSkill(join14(dir, SKILL_BODY_FILE), this.options.skillReceipt);
12114
+ if (this.options.skillReceipt) verifyMountedSkill(join15(dir, SKILL_BODY_FILE), this.options.skillReceipt);
12075
12115
  for (const file of skill.files) {
12076
12116
  const target = resolve11(dir, file.path);
12077
12117
  if (!target.startsWith(`${dir}/`)) continue;
@@ -12109,14 +12149,14 @@ var RunContext = class {
12109
12149
  denyWrite: [
12110
12150
  // The fixture's refs/objects are writable for push; its configuration
12111
12151
  // and hooks must remain host-owned because fixture verification runs Git.
12112
- ...fixtureOrigin ? [join14(fixtureOrigin, "config"), join14(fixtureOrigin, "hooks")] : [],
12113
- join14(this.worktree, ".git"),
12114
- join14(this.gitDir, "commondir"),
12115
- join14(this.gitDir, "gitdir"),
12116
- join14(this.gitDir, "config.worktree"),
12152
+ ...fixtureOrigin ? [join15(fixtureOrigin, "config"), join15(fixtureOrigin, "hooks")] : [],
12153
+ join15(this.worktree, ".git"),
12154
+ join15(this.gitDir, "commondir"),
12155
+ join15(this.gitDir, "gitdir"),
12156
+ join15(this.gitDir, "config.worktree"),
12117
12157
  // A repository's config and hooks in the shared clone, outside the
12118
12158
  // working directory, are declared read-only here too.
12119
- ...this.options.gitWritePaths?.length ? [join14(this.gitDir, "..", "..", "config"), join14(this.gitDir, "..", "..", "hooks")] : [],
12159
+ ...this.options.gitWritePaths?.length ? [join15(this.gitDir, "..", "..", "config"), join15(this.gitDir, "..", "..", "hooks")] : [],
12120
12160
  ...readOnly ? [this.worktree, ...this.options.gitWritePaths ?? []] : []
12121
12161
  ],
12122
12162
  denyRead: [
@@ -12170,7 +12210,7 @@ var RunContext = class {
12170
12210
  */
12171
12211
  tempEnv() {
12172
12212
  if (this.options.machineEnvironment) return this.options.policyHash ? { MIKKA_POLICY_HASH: this.options.policyHash } : {};
12173
- return { TMPDIR: this.tmpDir, TMPPREFIX: join14(this.tmpDir, "zsh"), ...withGitConfig(this.githubEnv, RUN_GIT_CONFIG), ...this.options.policyHash ? { MIKKA_POLICY_HASH: this.options.policyHash } : {} };
12213
+ return { TMPDIR: this.tmpDir, TMPPREFIX: join15(this.tmpDir, "zsh"), ...withGitConfig(this.githubEnv, RUN_GIT_CONFIG), ...this.options.policyHash ? { MIKKA_POLICY_HASH: this.options.policyHash } : {} };
12174
12214
  }
12175
12215
  /**
12176
12216
  * The agent delivers this run itself: it commits, pushes to the task
@@ -12463,7 +12503,7 @@ function claudeSettings(workspace) {
12463
12503
  attribution: { pr: "" }
12464
12504
  };
12465
12505
  }
12466
- function claudeChunks(message) {
12506
+ function claudeChunks(message, turnModel) {
12467
12507
  const chunks = [];
12468
12508
  if (message.type === "assistant") {
12469
12509
  message.message.content.forEach((block, index) => {
@@ -12508,11 +12548,15 @@ function claudeChunks(message) {
12508
12548
  );
12509
12549
  }
12510
12550
  } else if (message.type === "result") {
12551
+ const usedModels = Object.keys(message.modelUsage ?? {});
12511
12552
  chunks.push({
12512
12553
  type: "data-usage",
12513
12554
  data: {
12514
12555
  inputTokens: message.usage.input_tokens ?? 0,
12515
12556
  outputTokens: message.usage.output_tokens ?? 0,
12557
+ model: turnModel ?? (usedModels.length === 1 ? usedModels[0] : void 0),
12558
+ cacheReadTokens: message.usage.cache_read_input_tokens ?? null,
12559
+ cacheWriteTokens: message.usage.cache_creation_input_tokens ?? null,
12516
12560
  costUsd: message.total_cost_usd ?? null,
12517
12561
  source: "claude agent sdk result"
12518
12562
  }
@@ -12810,15 +12854,15 @@ var ClaudeAdapter = class {
12810
12854
  throw new Error(SUBSCRIPTION_ERROR, { cause: error });
12811
12855
  }
12812
12856
  }
12813
- const nativeHome = options.machineEnvironment ? options.env.HOME : join15(runDir, "native-home");
12857
+ const nativeHome = options.machineEnvironment ? options.env.HOME : join16(runDir, "native-home");
12814
12858
  if (!nativeHome) throw new Error("Cloud machine HOME unavailable");
12815
- const configDir = options.machineEnvironment ? options.env.CLAUDE_CONFIG_DIR ?? join15(nativeHome, ".claude") : join15(nativeHome, ".claude");
12859
+ const configDir = options.machineEnvironment ? options.env.CLAUDE_CONFIG_DIR ?? join16(nativeHome, ".claude") : join16(nativeHome, ".claude");
12816
12860
  if (!options.machineEnvironment) {
12817
12861
  ownDir(nativeHome);
12818
12862
  ownDir(configDir);
12819
12863
  }
12820
12864
  if (!options.machineEnvironment && mode === "continue" && options.continueSession) {
12821
- carryHistory(join15(runPaths(this.options.stateDir, options.continueSession.runId).runDir, "native-home", ".claude"), configDir, ["projects"]);
12865
+ carryHistory(join16(runPaths(this.options.stateDir, options.continueSession.runId).runDir, "native-home", ".claude"), configDir, ["projects"]);
12822
12866
  }
12823
12867
  if (externalAuth && options.credential) throw new Error(SUBSCRIPTION_ERROR);
12824
12868
  const credentialEnv = claudeCredentialEnv(options.credential);
@@ -12853,8 +12897,8 @@ var ClaudeAdapter = class {
12853
12897
  privateDir: paths.privateDir,
12854
12898
  // Its session store, so `resume` works; keyed by the cwd it sees.
12855
12899
  extraWrite: preparing ? [] : [
12856
- join15(configDir, "projects", claudeProjectDirName(options.cwd)),
12857
- join15(
12900
+ join16(configDir, "projects", claudeProjectDirName(options.cwd)),
12901
+ join16(
12858
12902
  configDir,
12859
12903
  "projects",
12860
12904
  claudeProjectDirName(realpathSync10(options.cwd))
@@ -12878,6 +12922,7 @@ var ClaudeAdapter = class {
12878
12922
  let written = 0;
12879
12923
  let results = 0;
12880
12924
  let runtimeModel = null;
12925
+ let turnModel;
12881
12926
  let ending = false;
12882
12927
  let failureDetails;
12883
12928
  let lastError;
@@ -12997,7 +13042,7 @@ var ClaudeAdapter = class {
12997
13042
  if (preparation) {
12998
13043
  const { binding, control } = preparation;
12999
13044
  const fixed = claudePrewarmOptionsKey(options);
13000
- const parking = join15(runDir, "claude-parking");
13045
+ const parking = join16(runDir, "claude-parking");
13001
13046
  ownDir(parking);
13002
13047
  let anonymousAdopted = false;
13003
13048
  const prepared = prepareClaudeSession({
@@ -13141,8 +13186,10 @@ var ClaudeAdapter = class {
13141
13186
  runRuntimeTimings.agentAccepted(options.runId, "claude_user_ack");
13142
13187
  if (message.type === "system" && message.subtype === "init" && typeof message.model === "string")
13143
13188
  runtimeModel = message.model || null;
13144
- if (message.type === "assistant" && message.parent_tool_use_id == null && typeof message.message.model === "string")
13189
+ if (message.type === "assistant" && message.parent_tool_use_id == null && typeof message.message.model === "string") {
13145
13190
  runtimeModel = message.message.model || null;
13191
+ if (!message.error && runtimeModel) turnModel = runtimeModel;
13192
+ }
13146
13193
  if (runtimeModel && (message.type === "system" && message.subtype === "init" || message.type === "assistant" && message.parent_tool_use_id == null))
13147
13194
  options.onRuntimeModel?.(sessionId, runtimeModel);
13148
13195
  if (provesSession(message)) {
@@ -13156,8 +13203,9 @@ var ClaudeAdapter = class {
13156
13203
  quota = mergeQuota(quota, claudeQuotaSignal(message));
13157
13204
  if (message.type === "tool_progress" && message.session_id === sessionId) queue.progress();
13158
13205
  if (!(message.type === "assistant" && message.error))
13159
- for (const chunk of claudeChunks(message)) queue.chunk(chunk);
13206
+ for (const chunk of claudeChunks(message, turnModel)) queue.chunk(chunk);
13160
13207
  if (message.type !== "result") continue;
13208
+ turnModel = void 0;
13161
13209
  results++;
13162
13210
  failureDetails = message.is_error ? capture(message) : void 0;
13163
13211
  providerFailure = claudeProviderFailure(message, assistantError);
@@ -13353,7 +13401,7 @@ function codexFailureMessage(phase, info) {
13353
13401
  }
13354
13402
 
13355
13403
  // src/adapters/codex.ts
13356
- import { delimiter as delimiter3, dirname as dirname12, isAbsolute as isAbsolute5, join as join17, relative as relative5 } from "node:path";
13404
+ import { delimiter as delimiter3, dirname as dirname12, isAbsolute as isAbsolute5, join as join18, relative as relative5 } from "node:path";
13357
13405
  import { mkdirSync as mkdirSync10 } from "node:fs";
13358
13406
 
13359
13407
  // src/codex-generation-telemetry.ts
@@ -13869,9 +13917,14 @@ function jsonlConnection(input, output) {
13869
13917
 
13870
13918
  // src/adapters/codex-mailbox.ts
13871
13919
  import { closeSync as closeSync3, constants as constants4, fstatSync as fstatSync2, lstatSync as lstatSync9, mkdirSync as mkdirSync9, openSync as openSync3, readSync as readSync2 } from "node:fs";
13872
- import { isAbsolute as isAbsolute4, join as join16, relative as relative4, sep as sep3 } from "node:path";
13920
+ import { isAbsolute as isAbsolute4, join as join17, relative as relative4, sep as sep3 } from "node:path";
13873
13921
  import { isDeepStrictEqual } from "node:util";
13874
- var unavailable2 = () => new Error("Run mailbox requires a verified original Codex thread");
13922
+ var UNAVAILABLE = "Run mailbox requires a verified original Codex thread";
13923
+ var unavailable2 = (reason, cause) => Object.assign(
13924
+ new Error(`${UNAVAILABLE} (${reason})`, { cause }),
13925
+ { name: "codex_mailbox_unavailable", detail: reason }
13926
+ );
13927
+ var isUnavailable = (error) => error instanceof Error && error.name === "codex_mailbox_unavailable";
13875
13928
  function codexMailboxResumeVersion(userAgent) {
13876
13929
  const version = typeof userAgent === "string" ? /^[A-Za-z0-9._-]+\/(0\.163\.0|0\.166\.0|0\.167\.0)(?:\s|$)/.exec(userAgent)?.[1] : void 0;
13877
13930
  return version === "0.163.0" || version === "0.166.0" || version === "0.167.0" ? version : null;
@@ -13880,24 +13933,33 @@ function codexMailboxCatalogue(mailbox) {
13880
13933
  return JSON.parse(JSON.stringify(mailbox.tools.map((tool) => ({ type: "function", ...tool }))));
13881
13934
  }
13882
13935
  function historyParts(value) {
13883
- if (typeof value !== "string" || value.length > 1024 || /[\\\0]/.test(value)) throw unavailable2();
13936
+ if (typeof value !== "string" || value.length > 1024 || /[\\\0]/.test(value)) throw unavailable2("history_path");
13884
13937
  const parts = value.split("/");
13885
- if (!["sessions", "archived_sessions"].includes(parts[0]) || parts.length < 2 || parts.some((part) => !part || part === "." || part === "..") || !value.endsWith(".jsonl")) throw unavailable2();
13938
+ if (!["sessions", "archived_sessions"].includes(parts[0]) || parts.length < 2 || parts.some((part) => !part || part === "." || part === "..") || !value.endsWith(".jsonl")) throw unavailable2("history_path");
13886
13939
  return parts;
13887
13940
  }
13888
13941
  function receiptFile(stateDir, runId) {
13889
- return join16(stateDir, "codex-mailbox", assertSafeId("run id", runId) + ".json");
13942
+ return join17(stateDir, "codex-mailbox", assertSafeId("run id", runId) + ".json");
13890
13943
  }
13891
- function readJson2(file, limit, firstLine = false) {
13892
- const fd = openSync3(file, constants4.O_RDONLY | constants4.O_NOFOLLOW | constants4.O_NONBLOCK);
13944
+ function readJson2(file, limit, firstLine = false, reason = "history_file") {
13945
+ let fd;
13946
+ try {
13947
+ fd = openSync3(file, constants4.O_RDONLY | constants4.O_NOFOLLOW | constants4.O_NONBLOCK);
13948
+ } catch {
13949
+ throw unavailable2(reason);
13950
+ }
13893
13951
  try {
13894
13952
  const stat3 = fstatSync2(fd);
13895
- if (!stat3.isFile() || stat3.nlink !== 1 || !firstLine && stat3.size > limit) throw unavailable2();
13953
+ if (!stat3.isFile() || stat3.nlink !== 1 || !firstLine && stat3.size > limit) throw unavailable2(reason);
13896
13954
  const buffer = Buffer.alloc(Math.min(stat3.size, limit + 1));
13897
13955
  const length = readSync2(fd, buffer, 0, buffer.length, 0);
13898
13956
  const end = firstLine ? buffer.subarray(0, length).indexOf(10) : length;
13899
- if (end < 0 || end > limit) throw unavailable2();
13900
- return JSON.parse(buffer.subarray(0, end).toString("utf8"));
13957
+ if (end < 0 || end > limit) throw unavailable2(reason);
13958
+ try {
13959
+ return JSON.parse(buffer.subarray(0, end).toString("utf8"));
13960
+ } catch {
13961
+ throw unavailable2(reason);
13962
+ }
13901
13963
  } finally {
13902
13964
  closeSync3(fd);
13903
13965
  }
@@ -13906,38 +13968,38 @@ function verifyHistory(home, path3, threadId, catalogue) {
13906
13968
  const parts = historyParts(path3);
13907
13969
  let parent = home;
13908
13970
  for (const part of ["", ...parts.slice(0, -1)]) {
13909
- if (part) parent = join16(parent, part);
13971
+ if (part) parent = join17(parent, part);
13910
13972
  const stat3 = lstatSync9(parent);
13911
- if (!stat3.isDirectory() || stat3.isSymbolicLink()) throw unavailable2();
13973
+ if (!stat3.isDirectory() || stat3.isSymbolicLink()) throw unavailable2("history_dir");
13912
13974
  }
13913
- const header = readJson2(join16(home, ...parts), 1024 * 1024, true);
13914
- if (header?.type !== "session_meta" || header.payload?.id !== threadId || !isDeepStrictEqual(header.payload.dynamic_tools, catalogue)) throw unavailable2();
13975
+ const header = readJson2(join17(home, ...parts), 1024 * 1024, true, "history_meta");
13976
+ if (header?.type !== "session_meta" || header.payload?.id !== threadId || !isDeepStrictEqual(header.payload.dynamic_tools, catalogue)) throw unavailable2("history_meta");
13915
13977
  }
13916
13978
  function verifyCodexMailboxResume(stateDir, sourceRunId, home, threadId, catalogue) {
13917
13979
  try {
13918
- const dir = lstatSync9(join16(stateDir, "codex-mailbox"));
13919
- if (!dir.isDirectory() || dir.isSymbolicLink()) throw unavailable2();
13920
- const receipt = readJson2(receiptFile(stateDir, sourceRunId), 256 * 1024);
13921
- if (receipt?.version !== 1 || receipt.nativeVersion !== "0.163.0" && receipt.nativeVersion !== "0.166.0" && receipt.nativeVersion !== "0.167.0" || receipt.runId !== sourceRunId || receipt.threadId !== threadId || !isDeepStrictEqual(receipt.catalogue, catalogue) || typeof receipt.historyPath !== "string") throw unavailable2();
13980
+ const dir = lstatSync9(join17(stateDir, "codex-mailbox"));
13981
+ if (!dir.isDirectory() || dir.isSymbolicLink()) throw unavailable2("mailbox_dir");
13982
+ const receipt = readJson2(receiptFile(stateDir, sourceRunId), 256 * 1024, false, "receipt");
13983
+ if (receipt?.version !== 1 || receipt.nativeVersion !== "0.163.0" && receipt.nativeVersion !== "0.166.0" && receipt.nativeVersion !== "0.167.0" || receipt.runId !== sourceRunId || receipt.threadId !== threadId || !isDeepStrictEqual(receipt.catalogue, catalogue) || typeof receipt.historyPath !== "string") throw unavailable2("receipt_mismatch");
13922
13984
  verifyHistory(home, receipt.historyPath, threadId, catalogue);
13923
13985
  return receipt.nativeVersion;
13924
- } catch {
13925
- throw unavailable2();
13986
+ } catch (error) {
13987
+ throw isUnavailable(error) ? error : unavailable2("verify", error);
13926
13988
  }
13927
13989
  }
13928
13990
  function recordCodexMailboxSession(stateDir, runId, home, thread, catalogue, resumed, nativeVersion) {
13929
13991
  try {
13930
- if (!thread.id || typeof thread.path !== "string" || !isAbsolute4(thread.path)) throw unavailable2();
13992
+ if (!thread.id || typeof thread.path !== "string" || !isAbsolute4(thread.path)) throw unavailable2("thread_path");
13931
13993
  const historyPath = relative4(home, thread.path).split(sep3).join("/");
13932
13994
  historyParts(historyPath);
13933
13995
  if (resumed) verifyHistory(home, historyPath, thread.id, catalogue);
13934
- const dir = join16(stateDir, "codex-mailbox");
13996
+ const dir = join17(stateDir, "codex-mailbox");
13935
13997
  mkdirSync9(dir, { recursive: true, mode: 448 });
13936
13998
  const stat3 = lstatSync9(dir);
13937
- if (!stat3.isDirectory() || stat3.isSymbolicLink()) throw unavailable2();
13999
+ if (!stat3.isDirectory() || stat3.isSymbolicLink()) throw unavailable2("mailbox_dir");
13938
14000
  writeJsonAtomic(receiptFile(stateDir, runId), { version: 1, nativeVersion, runId, threadId: thread.id, historyPath, catalogue });
13939
- } catch {
13940
- if (resumed) throw unavailable2();
14001
+ } catch (error) {
14002
+ if (resumed) throw isUnavailable(error) ? error : unavailable2("record", error);
13941
14003
  }
13942
14004
  }
13943
14005
 
@@ -14195,8 +14257,8 @@ var CodexAdapter = class {
14195
14257
  options.continueSession.runId
14196
14258
  ).runDir;
14197
14259
  carryHistory(
14198
- join17(earlier2, "codex-home"),
14199
- join17(runDir, "codex-home"),
14260
+ join18(earlier2, "codex-home"),
14261
+ join18(runDir, "codex-home"),
14200
14262
  CODEX_HISTORY
14201
14263
  );
14202
14264
  } catch (error) {
@@ -14207,7 +14269,7 @@ var CodexAdapter = class {
14207
14269
  log.info({ err: error }, "could not copy the earlier codex threads");
14208
14270
  }
14209
14271
  }
14210
- const codexHome = options.machineEnvironment ? { home: options.env.CODEX_HOME ?? join17(options.env.HOME, ".codex") } : prepareCodexHome(join17(runDir, "codex-home"), log);
14272
+ const codexHome = options.machineEnvironment ? { home: options.env.CODEX_HOME ?? join18(options.env.HOME, ".codex") } : prepareCodexHome(join18(runDir, "codex-home"), log);
14211
14273
  if (options.machineEnvironment) mkdirSync10(codexHome.home, { recursive: true, mode: 448 });
14212
14274
  const mailboxResumeVersion = mailboxCatalogue && threadId ? verifyCodexMailboxResume(
14213
14275
  this.options.stateDir,
@@ -14415,7 +14477,15 @@ var CodexAdapter = class {
14415
14477
  let quota;
14416
14478
  let rateLimits;
14417
14479
  let usage = { inputTokens: 0, outputTokens: 0 };
14418
- const generations = new CodexGenerationMetrics((metrics) => nativeGenerations ? nativeGenerations.collector.observeFallback(metrics, sessionId) : daemonTracer.generation({ ...metrics, nativeUnavailableReason }, traceContext));
14480
+ let turnUsage;
14481
+ const generations = new CodexGenerationMetrics((metrics) => {
14482
+ turnUsage = {
14483
+ inputTokens: (turnUsage?.inputTokens ?? 0) + (metrics.inputTokens ?? 0),
14484
+ outputTokens: (turnUsage?.outputTokens ?? 0) + (metrics.outputTokens ?? 0)
14485
+ };
14486
+ if (nativeGenerations) nativeGenerations.collector.observeFallback(metrics, sessionId);
14487
+ else daemonTracer.generation({ ...metrics, nativeUnavailableReason }, traceContext);
14488
+ });
14419
14489
  const pendingMcp = /* @__PURE__ */ new Map();
14420
14490
  const handInTools = /* @__PURE__ */ new Set([
14421
14491
  "submit",
@@ -14598,11 +14668,14 @@ var CodexAdapter = class {
14598
14668
  type: "data-usage",
14599
14669
  data: {
14600
14670
  ...usage,
14671
+ turnUsage,
14672
+ model: runtimeModel ?? void 0,
14601
14673
  // Priced later with the LiteLLM table (ADR 0003).
14602
14674
  costUsd: null,
14603
14675
  source: "codex app-server thread/tokenUsage"
14604
14676
  }
14605
14677
  });
14678
+ turnUsage = void 0;
14606
14679
  if (ending) return;
14607
14680
  if (cancelling) return finish({ outcome: "cancelled" });
14608
14681
  const handoff = ctx.readHandoff(log);
@@ -14650,6 +14723,7 @@ var CodexAdapter = class {
14650
14723
  throw new Error(SUBSCRIPTION_AUTH_ERROR, { cause: error });
14651
14724
  }
14652
14725
  }
14726
+ turnUsage = void 0;
14653
14727
  generations.startTurn();
14654
14728
  const result = rpc.sendRequest("turn/start", {
14655
14729
  threadId: sessionId,
@@ -14851,7 +14925,7 @@ var CodexAdapter = class {
14851
14925
  // src/adapters/cursor.ts
14852
14926
  import { Readable, Writable } from "node:stream";
14853
14927
  import * as acp from "@agentclientprotocol/sdk";
14854
- import { join as join18 } from "node:path";
14928
+ import { join as join19 } from "node:path";
14855
14929
  function cursorAppServers(apps) {
14856
14930
  return [
14857
14931
  ...(apps?.apps ?? []).map((app) => ({ type: "http", name: app.name, url: app.url, headers: [{ name: "Authorization", value: `Bearer ${apps.token}` }] })),
@@ -14983,15 +15057,15 @@ var CursorAdapter = class {
14983
15057
  options.continueSession.runId
14984
15058
  ).runDir;
14985
15059
  carryHistory(
14986
- join18(earlier2, "cursor-home"),
14987
- join18(paths.runDir, "cursor-home"),
15060
+ join19(earlier2, "cursor-home"),
15061
+ join19(paths.runDir, "cursor-home"),
14988
15062
  CURSOR_HISTORY
14989
15063
  );
14990
15064
  } catch (error) {
14991
15065
  log.info({ err: error }, "could not copy the earlier cursor chats");
14992
15066
  }
14993
15067
  }
14994
- const configDir = prepareCursorHome(join18(paths.runDir, "cursor-home"));
15068
+ const configDir = prepareCursorHome(join19(paths.runDir, "cursor-home"));
14995
15069
  const ctx = new RunContext({
14996
15070
  github: options.github,
14997
15071
  githubEnvironment: options.githubEnvironment,
@@ -15226,7 +15300,7 @@ ${firstMessage}` : firstMessage
15226
15300
  // src/adapters/mock.ts
15227
15301
  import { randomUUID as randomUUID3 } from "node:crypto";
15228
15302
  import { mkdirSync as mkdirSync11, readFileSync as readFileSync9, writeFileSync as writeFileSync5 } from "node:fs";
15229
- import { dirname as dirname13, join as join19, resolve as resolve12 } from "node:path";
15303
+ import { dirname as dirname13, join as join20, resolve as resolve12 } from "node:path";
15230
15304
  import { setTimeout as sleep2 } from "node:timers/promises";
15231
15305
  import { execa as execa5 } from "execa";
15232
15306
 
@@ -15292,7 +15366,7 @@ var MockAdapter = class {
15292
15366
  fixturesDir;
15293
15367
  speed;
15294
15368
  stateFile(sessionId) {
15295
- return join19(
15369
+ return join20(
15296
15370
  this.options.stateDir,
15297
15371
  `mock-${assertSafeId("session id", sessionId)}.json`
15298
15372
  );
@@ -15336,7 +15410,7 @@ var MockAdapter = class {
15336
15410
  open(sessionId, state2, options) {
15337
15411
  const name = assertSafeId("fixture", state2.fixture.replace(/\.jsonl$/, ""));
15338
15412
  const lines = parseFixture(
15339
- readFileSync9(join19(this.fixturesDir, `${name}.jsonl`), "utf8"),
15413
+ readFileSync9(join20(this.fixturesDir, `${name}.jsonl`), "utf8"),
15340
15414
  name
15341
15415
  );
15342
15416
  const abort = new AbortController();
@@ -15451,12 +15525,12 @@ var MockAdapter = class {
15451
15525
  // src/agents/local-github.ts
15452
15526
  import { mkdirSync as mkdirSync13, mkdtempSync as mkdtempSync4, rmSync as rmSync10, writeFileSync as writeFileSync7 } from "node:fs";
15453
15527
  import { homedir as homedir6 } from "node:os";
15454
- import { delimiter as delimiter4, join as join21 } from "node:path";
15528
+ import { delimiter as delimiter4, join as join22 } from "node:path";
15455
15529
 
15456
15530
  // src/agents/machine-github.ts
15457
- import { existsSync as existsSync4, mkdirSync as mkdirSync12, readFileSync as readFileSync10, renameSync as renameSync3, rmSync as rmSync9, writeFileSync as writeFileSync6 } from "node:fs";
15531
+ import { existsSync as existsSync5, mkdirSync as mkdirSync12, readFileSync as readFileSync10, renameSync as renameSync3, rmSync as rmSync9, writeFileSync as writeFileSync6 } from "node:fs";
15458
15532
  import { randomUUID as randomUUID4 } from "node:crypto";
15459
- import { dirname as dirname14, join as join20 } from "node:path";
15533
+ import { dirname as dirname14, join as join21 } from "node:path";
15460
15534
  function githubHosts(contents, token) {
15461
15535
  if (!token || /[\r\n\0]/.test(token) || token.length > 32768) throw Error("github_credential_invalid");
15462
15536
  const lines = contents.split(/\r?\n/);
@@ -15481,9 +15555,9 @@ function prepareMachineGitHub(github, host) {
15481
15555
  if (!github.token) throw Error("github_credential_missing");
15482
15556
  const home = host.env.HOME;
15483
15557
  if (!home) throw Error("github_home_missing");
15484
- const directory = host.env.GH_CONFIG_DIR ?? join20(host.env.XDG_CONFIG_HOME ?? join20(home, ".config"), "gh");
15485
- const file = join20(directory, "hosts.yml");
15486
- const original = existsSync4(file) ? readFileSync10(file, "utf8") : void 0;
15558
+ const directory = host.env.GH_CONFIG_DIR ?? join21(host.env.XDG_CONFIG_HOME ?? join21(home, ".config"), "gh");
15559
+ const file = join21(directory, "hosts.yml");
15560
+ const original = existsSync5(file) ? readFileSync10(file, "utf8") : void 0;
15487
15561
  let written;
15488
15562
  let closed = false;
15489
15563
  let timer;
@@ -15494,7 +15568,7 @@ function prepareMachineGitHub(github, host) {
15494
15568
  if (credential.expiresAt !== null && (!Number.isFinite(Date.parse(credential.expiresAt)) || Date.parse(credential.expiresAt) <= Date.now()))
15495
15569
  throw Error("github_credential_expired");
15496
15570
  host.onCredential?.("GITHUB_TOKEN", credential.token);
15497
- const latest = existsSync4(file) ? readFileSync10(file, "utf8") : "";
15571
+ const latest = existsSync5(file) ? readFileSync10(file, "utf8") : "";
15498
15572
  const next = githubHosts(latest, credential.token);
15499
15573
  mkdirSync12(dirname14(file), { recursive: true, mode: 448 });
15500
15574
  const temporary = `${file}.${randomUUID4()}`;
@@ -15536,7 +15610,7 @@ function prepareMachineGitHub(github, host) {
15536
15610
  closed = true;
15537
15611
  clearTimeout(timer);
15538
15612
  host.signal.removeEventListener("abort", stopRefresh);
15539
- if (!options?.retainCredential && written !== void 0 && existsSync4(file) && readFileSync10(file, "utf8") === written) {
15613
+ if (!options?.retainCredential && written !== void 0 && existsSync5(file) && readFileSync10(file, "utf8") === written) {
15540
15614
  if (original === void 0) rmSync9(file, { force: true });
15541
15615
  else writeFileSync6(file, original, { mode: 384 });
15542
15616
  }
@@ -15582,14 +15656,14 @@ async function prepareLocalGitHub(assignment, host) {
15582
15656
  const credential = assignment.github.token ? { token: assignment.github.token, expiresAt: assignment.github.expiresAt ?? null } : await lease();
15583
15657
  if (host.signal.aborted) throw Error("github_run_closed");
15584
15658
  mkdirSync13(host.stateDir, { recursive: true, mode: 448 });
15585
- const directory = mkdtempSync4(join21(host.stateDir, "github-"));
15659
+ const directory = mkdtempSync4(join22(host.stateDir, "github-"));
15586
15660
  try {
15587
- const bin = join21(directory, "bin");
15661
+ const bin = join22(directory, "bin");
15588
15662
  const quote2 = (value) => `'${value.replaceAll("'", "'\\''")}'`;
15589
15663
  const helper2 = `${process.versions.electron ? "env ELECTRON_RUN_AS_NODE=1 " : ""}${quote2(process.execPath)} ${quote2(GITHUB_CREDENTIAL_SCRIPT)}`;
15590
15664
  if (binary) {
15591
15665
  mkdirSync13(bin, { mode: 448 });
15592
- writeFileSync7(join21(bin, "gh"), `#!/bin/sh
15666
+ writeFileSync7(join22(bin, "gh"), `#!/bin/sh
15593
15667
  exec ${helper2} native-gh ${quote2(binary)} ${quote2(directory)} "$@"
15594
15668
  `, { mode: 448, flag: "wx" });
15595
15669
  }
@@ -15629,20 +15703,20 @@ exec ${helper2} native-gh ${quote2(binary)} ${quote2(directory)} "$@"
15629
15703
  }
15630
15704
 
15631
15705
  // src/agents/verify.ts
15632
- import { existsSync as existsSync5, mkdirSync as mkdirSync14, mkdtempSync as mkdtempSync5, realpathSync as realpathSync11, rmSync as rmSync11 } from "node:fs";
15633
- import { join as join22 } from "node:path";
15706
+ import { existsSync as existsSync6, mkdirSync as mkdirSync14, mkdtempSync as mkdtempSync5, realpathSync as realpathSync11, rmSync as rmSync11 } from "node:fs";
15707
+ import { join as join23 } from "node:path";
15634
15708
  var OUTPUT_TAIL = 4e3;
15635
15709
  var SETUP_ATTEMPTS = 3;
15636
15710
  async function runVerify(sandbox, options) {
15637
15711
  options.signal?.throwIfAborted();
15638
15712
  mkdirSync14(options.tmpRoot, { recursive: true, mode: 448 });
15639
- const tmpDir = mkdtempSync5(join22(realpathSync11(options.tmpRoot), "verify-"));
15713
+ const tmpDir = mkdtempSync5(join23(realpathSync11(options.tmpRoot), "verify-"));
15640
15714
  const deadline = Date.now() + options.timeoutMs;
15641
15715
  try {
15642
15716
  for (let attempt = 1; ; attempt++) {
15643
- const started = join22(tmpDir, `.started-${attempt}`);
15717
+ const started = join23(tmpDir, `.started-${attempt}`);
15644
15718
  const result = await attemptVerify(sandbox, options, tmpDir, started, deadline - Date.now());
15645
- if (result.exitCode === 0 || result.timedOut || options.signal?.aborted || existsSync5(started) || attempt >= SETUP_ATTEMPTS)
15719
+ if (result.exitCode === 0 || result.timedOut || options.signal?.aborted || existsSync6(started) || attempt >= SETUP_ATTEMPTS)
15646
15720
  return result;
15647
15721
  }
15648
15722
  } finally {
@@ -15659,7 +15733,7 @@ async function attemptVerify(sandbox, options, tmpDir, started, timeoutMs) {
15659
15733
  policy: {
15660
15734
  allowWrite: options.readOnly ? [tmpDir] : [options.worktree, tmpDir],
15661
15735
  denyWrite: [
15662
- join22(options.worktree, ".git"),
15736
+ join23(options.worktree, ".git"),
15663
15737
  ...options.readOnly ? [options.worktree] : []
15664
15738
  ],
15665
15739
  denyRead: [
@@ -15793,8 +15867,8 @@ import { execa as execa7 } from "execa";
15793
15867
  // harness/install.mjs
15794
15868
  import { createHash as createHash9, randomBytes as randomBytes2 } from "node:crypto";
15795
15869
  import { execFile as execFile5 } from "node:child_process";
15796
- import { createWriteStream as createWriteStream2, existsSync as existsSync6, mkdirSync as mkdirSync15, readdirSync as readdirSync5, readFileSync as readFileSync11, renameSync as renameSync4, rmSync as rmSync12, statSync as statSync2, symlinkSync, writeFileSync as writeFileSync8 } from "node:fs";
15797
- import { dirname as dirname15, join as join23, relative as relative6 } from "node:path";
15870
+ import { createWriteStream as createWriteStream2, existsSync as existsSync7, mkdirSync as mkdirSync15, readdirSync as readdirSync5, readFileSync as readFileSync11, renameSync as renameSync4, rmSync as rmSync12, statSync as statSync2, symlinkSync, writeFileSync as writeFileSync8 } from "node:fs";
15871
+ import { dirname as dirname15, join as join24, relative as relative6 } from "node:path";
15798
15872
  import { Readable as Readable2, Transform } from "node:stream";
15799
15873
  import { pipeline as pipeline2 } from "node:stream/promises";
15800
15874
  import { promisify as promisify5 } from "node:util";
@@ -15843,17 +15917,17 @@ function resolvePin(store, harness) {
15843
15917
  return { pin, artifact: pin.platforms[store.platform ?? platformKey()] };
15844
15918
  }
15845
15919
  function versionDir(store, harness) {
15846
- return join23(store.root, harness, resolvePin(store, harness).pin.version);
15920
+ return join24(store.root, harness, resolvePin(store, harness).pin.version);
15847
15921
  }
15848
15922
  function harnessBinaryPath(store, harness) {
15849
- return join23(versionDir(store, harness), "bin", resolvePin(store, harness).pin.command);
15923
+ return join24(versionDir(store, harness), "bin", resolvePin(store, harness).pin.command);
15850
15924
  }
15851
15925
  function harnessInstallState(store, harness) {
15852
15926
  const { pin, artifact } = resolvePin(store, harness);
15853
15927
  if (!artifact) return { state: "unsupported", version: pin.version };
15854
15928
  let installed = false;
15855
15929
  try {
15856
- installed = readFileSync11(join23(versionDir(store, harness), MARKER), "utf8") === installMarker(pin, artifact) && runtimeFiles(store, harness).every((path3) => {
15930
+ installed = readFileSync11(join24(versionDir(store, harness), MARKER), "utf8") === installMarker(pin, artifact) && runtimeFiles(store, harness).every((path3) => {
15857
15931
  const stat3 = statSync2(path3);
15858
15932
  return stat3.isFile() && (stat3.mode & 73) !== 0;
15859
15933
  });
@@ -15863,7 +15937,7 @@ function harnessInstallState(store, harness) {
15863
15937
  }
15864
15938
  function runtimeFiles(store, harness) {
15865
15939
  const binary = harnessBinaryPath(store, harness);
15866
- return harness === "codex" ? [binary, join23(dirname15(binary), "codex-code-mode-host")] : [binary];
15940
+ return harness === "codex" ? [binary, join24(dirname15(binary), "codex-code-mode-host")] : [binary];
15867
15941
  }
15868
15942
  function ensureHarness(store, harness) {
15869
15943
  const key2 = `${store.root}\0${harness}`;
@@ -15880,29 +15954,29 @@ async function install(store, harness) {
15880
15954
  if (state2 === "unsupported") throw new Error(`${harness} has no build for ${store.platform ?? platformKey()}`);
15881
15955
  if (state2 === "installed") return binary;
15882
15956
  const { pin, artifact } = resolvePin(store, harness);
15883
- const parent = join23(store.root, harness);
15957
+ const parent = join24(store.root, harness);
15884
15958
  mkdirSync15(parent, { recursive: true, mode: 448 });
15885
- const staging = join23(parent, `.staging-${randomBytes2(6).toString("hex")}`);
15959
+ const staging = join24(parent, `.staging-${randomBytes2(6).toString("hex")}`);
15886
15960
  mkdirSync15(staging, { recursive: true, mode: 448 });
15887
15961
  try {
15888
- const tarball = join23(staging, "package.tgz");
15962
+ const tarball = join24(staging, "package.tgz");
15889
15963
  await download(`${(store.pins ?? HARNESS_PINS).registry.replace(/\/$/, "")}/${artifact.tarball}`, tarball, artifact.integrity);
15890
15964
  await run2("tar", ["-xzf", tarball, "-C", staging]);
15891
15965
  if (harness === "codex") {
15892
15966
  if (!artifact.entry.endsWith("/bin/codex")) throw new Error("Invalid Codex bundle entry");
15893
15967
  const bundle = dirname15(dirname15(artifact.entry));
15894
- for (const name of readdirSync5(join23(staging, bundle))) symlinkSync(relative6(staging, join23(staging, bundle, name)), join23(staging, name));
15968
+ for (const name of readdirSync5(join24(staging, bundle))) symlinkSync(relative6(staging, join24(staging, bundle, name)), join24(staging, name));
15895
15969
  for (const name of ["codex", "codex-code-mode-host"]) {
15896
- const stat3 = statSync2(join23(staging, "bin", name));
15970
+ const stat3 = statSync2(join24(staging, "bin", name));
15897
15971
  if (!stat3.isFile() || (stat3.mode & 73) === 0) throw new Error("Incomplete Codex runtime bundle");
15898
15972
  }
15899
15973
  } else {
15900
- mkdirSync15(join23(staging, "bin"), { mode: 448 });
15901
- symlinkSync(relative6(join23(staging, "bin"), join23(staging, artifact.entry)), join23(staging, "bin", pin.command));
15974
+ mkdirSync15(join24(staging, "bin"), { mode: 448 });
15975
+ symlinkSync(relative6(join24(staging, "bin"), join24(staging, artifact.entry)), join24(staging, "bin", pin.command));
15902
15976
  }
15903
- writeFileSync8(join23(staging, MARKER), installMarker(pin, artifact), { mode: 384 });
15977
+ writeFileSync8(join24(staging, MARKER), installMarker(pin, artifact), { mode: 384 });
15904
15978
  const target = versionDir(store, harness);
15905
- const retained = existsSync6(target) ? `${target}.retained-${randomBytes2(6).toString("hex")}` : null;
15979
+ const retained = existsSync7(target) ? `${target}.retained-${randomBytes2(6).toString("hex")}` : null;
15906
15980
  if (retained) renameSync4(target, retained);
15907
15981
  try {
15908
15982
  renameSync4(staging, target);
@@ -15982,7 +16056,7 @@ function harnessFingerprint(store) {
15982
16056
  // src/model-probe.ts
15983
16057
  import { spawn as spawn3 } from "node:child_process";
15984
16058
  import { mkdtempSync as mkdtempSync6, readdirSync as readdirSync6, rmSync as rmSync13 } from "node:fs";
15985
- import { join as join24 } from "node:path";
16059
+ import { join as join25 } from "node:path";
15986
16060
 
15987
16061
  // src/process-group.ts
15988
16062
  async function stopGroup(child, graceMs = 3e3) {
@@ -16062,10 +16136,10 @@ function sweepModelProbeHomes(scratchDir) {
16062
16136
  } catch {
16063
16137
  return;
16064
16138
  }
16065
- for (const name of names) if (name.startsWith(HOME_PREFIX)) rmSync13(join24(scratchDir, name), { recursive: true, force: true });
16139
+ for (const name of names) if (name.startsWith(HOME_PREFIX)) rmSync13(join25(scratchDir, name), { recursive: true, force: true });
16066
16140
  }
16067
16141
  async function probeHarnessModels(harness, binary, options) {
16068
- const home = mkdtempSync6(join24(options.scratchDir, HOME_PREFIX));
16142
+ const home = mkdtempSync6(join25(options.scratchDir, HOME_PREFIX));
16069
16143
  try {
16070
16144
  return await exchange(harness, binary, home, options);
16071
16145
  } finally {
@@ -16074,7 +16148,7 @@ async function probeHarnessModels(harness, binary, options) {
16074
16148
  }
16075
16149
  function exchange(harness, binary, home, options) {
16076
16150
  const args = harness === "codex" ? ["app-server"] : ["-p", "--input-format", "stream-json", "--output-format", "stream-json", "--verbose"];
16077
- const env = { PATH: process.env.PATH ?? "", HOME: home, CODEX_HOME: home, CLAUDE_CONFIG_DIR: join24(home, ".claude"), LANG: process.env.LANG ?? "C.UTF-8" };
16151
+ const env = { PATH: process.env.PATH ?? "", HOME: home, CODEX_HOME: home, CLAUDE_CONFIG_DIR: join25(home, ".claude"), LANG: process.env.LANG ?? "C.UTF-8" };
16078
16152
  return new Promise((resolve20) => {
16079
16153
  const child = (options.spawnImpl ?? spawn3)(binary, args, { env, cwd: home, detached: process.platform !== "win32", stdio: ["pipe", "pipe", "ignore"] });
16080
16154
  let result;
@@ -16145,9 +16219,9 @@ function exchange(harness, binary, home, options) {
16145
16219
 
16146
16220
  // src/cloud-registration.ts
16147
16221
  import { createHash as createHash10 } from "node:crypto";
16148
- import { join as join25 } from "node:path";
16222
+ import { join as join26 } from "node:path";
16149
16223
  function writeCloudRegistration(dataDir, deviceId, workspaceId, credential) {
16150
- writeJsonAtomic(join25(dataDir, "registration.json"), {
16224
+ writeJsonAtomic(join26(dataDir, "registration.json"), {
16151
16225
  version: 1,
16152
16226
  deviceId,
16153
16227
  workspaceId,
@@ -16354,16 +16428,16 @@ async function prepareSubscriptionCredentials(assignment, host) {
16354
16428
 
16355
16429
  // src/run-scratch.ts
16356
16430
  import { rmSync as rmSync15 } from "node:fs";
16357
- import { join as join26 } from "node:path";
16431
+ import { join as join27 } from "node:path";
16358
16432
  function removeRunCredentials(stateDir, runId) {
16359
16433
  const { runDir } = runPaths(stateDir, runId);
16360
- for (const path3 of RUN_CREDENTIAL_PATHS) rmSync15(join26(runDir, path3), { recursive: true, force: true });
16434
+ for (const path3 of RUN_CREDENTIAL_PATHS) rmSync15(join27(runDir, path3), { recursive: true, force: true });
16361
16435
  }
16362
16436
 
16363
16437
  // src/subscription-local-runner.ts
16364
16438
  var unavailable3 = (detail, cause) => new CodedError("subscription_local_runtime_unavailable", { detail, cause });
16365
- var isUnavailable = (error) => error instanceof CodedError && error.code === "subscription_local_runtime_unavailable";
16366
- var startFailed = (error) => isUnavailable(error) ? error : error instanceof SubscriptionCredentialError ? unavailable3(error.detail, error.cause ?? error) : unavailable3(findCodedError(error, "subscription_local_runtime_unavailable")?.detail ?? "adapter_start_failed", error);
16439
+ var isUnavailable2 = (error) => error instanceof CodedError && error.code === "subscription_local_runtime_unavailable";
16440
+ var startFailed = (error) => isUnavailable2(error) ? error : error instanceof SubscriptionCredentialError ? unavailable3(error.detail, error.cause ?? error) : unavailable3(findCodedError(error, "subscription_local_runtime_unavailable")?.detail ?? "adapter_start_failed", error);
16367
16441
  function createLocalSubscriptionRunner(host) {
16368
16442
  return {
16369
16443
  async start(assignment, options) {
@@ -16456,7 +16530,7 @@ function createLocalSubscriptionRunner(host) {
16456
16530
 
16457
16531
  // src/subscription-preflight.ts
16458
16532
  import { mkdtempSync as mkdtempSync8, rmSync as rmSync16 } from "node:fs";
16459
- import { join as join27 } from "node:path";
16533
+ import { join as join28 } from "node:path";
16460
16534
  import { execa as execa8 } from "execa";
16461
16535
  var refused = (detail, cause) => ({
16462
16536
  ready: false,
@@ -16475,7 +16549,7 @@ async function preflightLocalSubscription(harness, options) {
16475
16549
  const expected2 = (options.store.pins ?? HARNESS_PINS).harnesses[harness].version;
16476
16550
  let home;
16477
16551
  try {
16478
- home = mkdtempSync8(join27(options.scratchDir, "subscription-preflight-"));
16552
+ home = mkdtempSync8(join28(options.scratchDir, "subscription-preflight-"));
16479
16553
  const result = await execa8(binary, ["--version"], {
16480
16554
  env: { ...env, HOME: home },
16481
16555
  extendEnv: false,
@@ -16608,7 +16682,7 @@ import {
16608
16682
  rmSync as rmSync17,
16609
16683
  truncateSync
16610
16684
  } from "node:fs";
16611
- import { join as join28 } from "node:path";
16685
+ import { join as join29 } from "node:path";
16612
16686
  var RETRY_MAX_MS = 3e4;
16613
16687
  var Outbox = class {
16614
16688
  constructor(dir, link, log, retryMs = 1e3, onUndeliverable = () => void 0, retainResources = false, traceContext = () => void 0) {
@@ -16636,10 +16710,10 @@ var Outbox = class {
16636
16710
  /** Runs whose file was checked for a torn tail since this process started. */
16637
16711
  repaired = /* @__PURE__ */ new Set();
16638
16712
  file(runId) {
16639
- return join28(this.dir, `${assertSafeId("run id", runId)}.jsonl`);
16713
+ return join29(this.dir, `${assertSafeId("run id", runId)}.jsonl`);
16640
16714
  }
16641
16715
  ackFile(runId) {
16642
- return join28(this.dir, `${assertSafeId("run id", runId)}.ack.json`);
16716
+ return join29(this.dir, `${assertSafeId("run id", runId)}.ack.json`);
16643
16717
  }
16644
16718
  parse(runId) {
16645
16719
  let data;
@@ -17117,6 +17191,405 @@ var RunJournal = class {
17117
17191
  }
17118
17192
  };
17119
17193
 
17194
+ // src/runs/publication.ts
17195
+ import { createHash as createHash11 } from "node:crypto";
17196
+ import { lstatSync as lstatSync11, readFileSync as readFileSync14, readdirSync as readdirSync8 } from "node:fs";
17197
+ import { join as join30 } from "node:path";
17198
+ import { execa as execa10 } from "execa";
17199
+
17200
+ // src/runs/check.ts
17201
+ import { execa as execa9 } from "execa";
17202
+ async function fixedCheckSnapshot(repoPath, worktree, sha6, signal) {
17203
+ signal?.throwIfAborted();
17204
+ if (!/^[a-f0-9]{40}$/.test(sha6))
17205
+ throw new Error("Check requires an exact candidate SHA");
17206
+ const gitDir = await worktreeGitDir(repoPath, worktree, signal);
17207
+ const git3 = async (...args) => (await execa9(
17208
+ "git",
17209
+ [
17210
+ "-c",
17211
+ "core.hooksPath=/dev/null",
17212
+ "-c",
17213
+ "core.fsmonitor=false",
17214
+ ...args
17215
+ ],
17216
+ {
17217
+ cwd: worktree,
17218
+ env: { GIT_DIR: gitDir, GIT_WORK_TREE: worktree },
17219
+ stdin: "ignore",
17220
+ cancelSignal: signal,
17221
+ killDescendants: true
17222
+ }
17223
+ )).stdout.trim();
17224
+ if (await git3("rev-parse", "HEAD") !== sha6)
17225
+ throw new Error("Check worktree HEAD differs from the fixed candidate");
17226
+ if (await git3("status", "--porcelain"))
17227
+ throw new Error(
17228
+ "Check worktree contains changes outside the fixed candidate"
17229
+ );
17230
+ return { sha: sha6, tree: await git3("rev-parse", `${sha6}^{tree}`) };
17231
+ }
17232
+
17233
+ // src/runs/publication.ts
17234
+ var VERIFY_TIMEOUT_MS = 30 * 6e4;
17235
+ var MAX_REPORTED_FILES = 5e3;
17236
+ var MAX_REPORTED_CRITERIA = 200;
17237
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
17238
+ async function verifyAndPublish(context, event) {
17239
+ const { assignment, repo, worktree, signal } = context;
17240
+ const initialStopReason = context.getStopReason();
17241
+ const error = event.error ?? (initialStopReason === "turn_ended" ? "Session ended without a submission" : initialStopReason === "timeout" ? "No progress before the watchdog limit" : initialStopReason === "device_lost" ? "Run lease expired; the server could not be reached" : void 0);
17242
+ let outcome;
17243
+ try {
17244
+ if (assignment.benchmark && !context.cancelRequested) {
17245
+ const fixed = await fixedCheckSnapshot(repo.path, worktree, assignment.benchmark.sourceCommit, signal);
17246
+ if (createHash11("sha256").update(fixed.sha).digest("hex") !== assignment.benchmark.fixtureDigest)
17247
+ throw new Error("Benchmark fixture changed during model execution");
17248
+ }
17249
+ outcome = await collectReport(context, initialStopReason, error, event.report);
17250
+ } catch (error2) {
17251
+ if (!signal.aborted) throw error2;
17252
+ outcome = { report: { ...baseReport(), ...pickAgentReport(event.report) } };
17253
+ }
17254
+ if (context.isStopping()) return;
17255
+ const stopReason = context.getStopReason();
17256
+ const { verifyError, tree } = outcome;
17257
+ let report2 = stopReason === "quota_exhausted" ? { ...outcome.report, resetsAt: event.quota?.resetsAt ?? null } : outcome.report;
17258
+ if (stopReason === "provider_failure") {
17259
+ report2 = {
17260
+ ...report2,
17261
+ providerFailure: providerFailureSchema.parse(event.providerFailure),
17262
+ ...event.quota ? { resetsAt: event.quota.resetsAt } : {}
17263
+ };
17264
+ }
17265
+ const policy = runPolicy(assignment.policy);
17266
+ const { publisher } = context.deps;
17267
+ if (stopReason === "submitted" && report2.verify.status !== "failed" && tree && publisher && // The draft-PR exception requires an explicit repository push
17268
+ // approval. It must not even create a local commit without it.
17269
+ (report2.verify.status === "passed" || pushDecision(policy).push) && // A read-only check (ADR 0046) never commits or pushes: it reports
17270
+ // on the commit the implementation run already pushed.
17271
+ policy.readOnly !== true) {
17272
+ const publish = await publishRun2(context, publisher, report2, tree);
17273
+ report2 = { ...report2, publish };
17274
+ }
17275
+ return { report: report2, error: error ?? verifyError };
17276
+ }
17277
+ function finishRun(context, stopReason, error, report2 = baseReport(error), failureDetails) {
17278
+ const { runId, journal, active } = context;
17279
+ if (active?.cancelRequested || active?.forcedStop) {
17280
+ stopReason = active.forcedStop ?? "cancelled";
17281
+ error = void 0;
17282
+ }
17283
+ active?.span?.set("mikka.outcome", stopReason);
17284
+ if (stopReason !== "provider_failure" && report2.providerFailure) {
17285
+ const { providerFailure: _failure, ...rest } = report2;
17286
+ report2 = rest;
17287
+ }
17288
+ if (stopReason !== "provider_failure" && stopReason !== "quota_exhausted" && report2.providerCheckpoint) {
17289
+ const { providerCheckpoint: _checkpoint, ...rest } = report2;
17290
+ report2 = rest;
17291
+ }
17292
+ const entry = journal.get(runId);
17293
+ const planning = entry?.assignment.kind === "plan";
17294
+ if (entry && stopReason === "blocked" && report2.repositorySelection)
17295
+ entry.assignment.preserveQuestionWorktree = true;
17296
+ const readOnlyTask = entry && (isReadOnlyTask(entry.assignment) || entry.assignment.factoryCheck?.reportOnly === true || entry.assignment.factoryExecuteKind === "deliverable");
17297
+ const { sourceCommit: _source, deliverableCommit: _delivery, skillMount: _mount, skillPrompt: _prompt, execution: _execution, runtime: _runtime, safePoint: _safePoint, ...content } = report2;
17298
+ report2 = {
17299
+ ...content,
17300
+ ...active?.safePoint ? { safePoint: active.safePoint } : {},
17301
+ ...entry?.baseCommit && /^[a-f0-9]{40}$/.test(entry.baseCommit) ? { sourceCommit: entry.baseCommit } : {},
17302
+ ...entry?.assignment.factoryExecuteKind === "deliverable" && entry.deliverableCommit ? { deliverableCommit: entry.deliverableCommit } : {},
17303
+ // What the prompt actually carried of the run's skills; a deferred body
17304
+ // is a fact the person needs to see, not something to leave unsaid.
17305
+ ...entry && skillPromptOf(entry.assignment) ? { skillPrompt: skillPromptOf(entry.assignment) } : {},
17306
+ ...entry?.skillMount && entry.skillMount.sessionId === entry.sessionId && entry.skillMount.receiptId === entry.assignment.skillReceipt?.id && entry.skillMount.versionId === entry.assignment.skillReceipt?.artifact.versionId && entry.skillMount.sha256 === entry.assignment.skillReceipt?.artifact.sha256 ? {
17307
+ skillMount: entry.skillMount,
17308
+ ...entry.runtime ? { runtime: {
17309
+ ...entry.runtime,
17310
+ observedModel: active?.session?.runtimeModel ?? entry.runtime.observedModel
17311
+ } } : {},
17312
+ ...entry.execution && entry.assignment.benchmark ? { execution: {
17313
+ ...entry.execution,
17314
+ observedModel: active?.session?.runtimeModel ?? entry.execution.observedModel
17315
+ } } : {}
17316
+ } : {}
17317
+ };
17318
+ context.closeOutput(report2, planning);
17319
+ if (stopReason === "submitted") context.setState("finishing");
17320
+ let state2 = runStateForStop(stopReason);
17321
+ if (stopReason === "submitted" && report2.verify.status !== "passed") {
17322
+ const failed = report2.verify.status === "failed";
17323
+ if (!planning && !readOnlyTask) state2 = failed ? "failed" : report2.publish?.pushed === true ? "succeeded" : "stopped";
17324
+ if (!failed && !planning && !readOnlyTask)
17325
+ error ??= "Submitted, but no verify command ran; the work is unverified";
17326
+ }
17327
+ if ((stopReason === "asked_human" || stopReason === "blocked") && report2.question) {
17328
+ journal.update(runId, {
17329
+ waitingQuestionId: report2.question.questionId
17330
+ });
17331
+ }
17332
+ if (state2 === "failed") active?.span?.fail({ name: "RunFailure" }, stopReason);
17333
+ else active?.span?.set("mikka.outcome", stopReason);
17334
+ context.setState(state2, {
17335
+ stopReason,
17336
+ ...error ? { error } : {}
17337
+ });
17338
+ const terminalFailure = state2 === "failed" && !active?.cancelRequested && !active?.forcedStop ? captureRunFailure(failureDetails ?? new Error(error ?? report2.summary), {
17339
+ runId,
17340
+ appVersion: DAEMON_VERSION,
17341
+ sensitiveText: [entry?.assignment.prompt ?? ""]
17342
+ }) : void 0;
17343
+ context.complete({ stopReason, report: report2, ...terminalFailure ? { failureDetails: terminalFailure } : {} });
17344
+ }
17345
+ async function collectReport(context, stopReason, error, agent) {
17346
+ const { deps, runId, worktree, repo, assignment, signal } = context;
17347
+ const profileSkills = profileSkillReport(runId, assignment, deps.adapterStateDir);
17348
+ let report2 = {
17349
+ ...baseReport(error),
17350
+ ...pickAgentReport(agent),
17351
+ ...profileSkills ? { profileSkills } : {}
17352
+ };
17353
+ const filesChanged = (await deps.worktrees.changedFiles(worktree, deps.journal.get(runId)?.baseCommit).catch(() => [])).slice(0, MAX_REPORTED_FILES);
17354
+ const inferred = assignment.factoryCheck?.stage === "verify" && assignment.factoryCheck.inferCommand && !assignment.factoryCheck.reportOnly ? report2.verificationCommand : void 0;
17355
+ const command = assignment.verifyCommand ?? inferred?.command;
17356
+ if (stopReason === "submitted") context.assertLive();
17357
+ if (stopReason === "submitted" && assignment.factoryExecuteKind === "deliverable") {
17358
+ const deliverableCommit = await retainDeliverable(repo.path, worktree, runId, signal);
17359
+ context.assertLive();
17360
+ deps.journal.update(runId, { deliverableCommit });
17361
+ }
17362
+ if (stopReason !== "submitted" && fixedCandidateCheck(assignment)) {
17363
+ const fixed = await fixedCheckSnapshot(repo.path, worktree, assignment.baseBranch, signal).catch(() => null);
17364
+ if (fixed) report2 = { ...report2, check: { sha: fixed.sha, readOnly: true } };
17365
+ }
17366
+ if (stopReason !== "submitted" || assignment.kind === "plan" || isReadOnlyTask(assignment) || assignment.factoryExecuteKind === "deliverable")
17367
+ return {
17368
+ report: { ...report2, filesChanged, verify: { status: "not_run" } }
17369
+ };
17370
+ if (!command) {
17371
+ if (fixedCandidateCheck(assignment)) {
17372
+ const fixed = await fixedCheckSnapshot(repo.path, worktree, assignment.baseBranch, signal);
17373
+ report2 = { ...report2, check: { sha: fixed.sha, readOnly: true } };
17374
+ }
17375
+ context.assertLive();
17376
+ const tree = await deps.publisher?.snapshot({ worktree, repo, signal });
17377
+ context.assertLive();
17378
+ return { report: { ...report2, filesChanged, verify: { status: "not_run" } }, tree };
17379
+ }
17380
+ let execution = {};
17381
+ const failed = (output2, verifyError) => ({
17382
+ report: {
17383
+ ...report2,
17384
+ filesChanged,
17385
+ verify: { status: "failed", command, output: output2, ...execution }
17386
+ },
17387
+ verifyError
17388
+ });
17389
+ const publisher = deps.publisher;
17390
+ let before;
17391
+ try {
17392
+ if (fixedCandidateCheck(assignment)) {
17393
+ if (runPolicy(assignment.policy).readOnly !== true)
17394
+ throw new Error("Check assignment is missing its read-only policy");
17395
+ const fixed = await fixedCheckSnapshot(
17396
+ repo.path,
17397
+ worktree,
17398
+ assignment.baseBranch,
17399
+ signal
17400
+ );
17401
+ report2 = { ...report2, check: { sha: fixed.sha, readOnly: true } };
17402
+ before = fixed.tree;
17403
+ } else {
17404
+ before = await publisher?.snapshot({ worktree, repo, signal });
17405
+ }
17406
+ } catch (snapshotError) {
17407
+ signal.throwIfAborted();
17408
+ return failed("", `Could not read the worktree: ${String(snapshotError)}`);
17409
+ }
17410
+ context.assertLive();
17411
+ const result = await (deps.verify ?? unsandboxedVerify)({
17412
+ runId,
17413
+ worktree,
17414
+ repo,
17415
+ command,
17416
+ timeoutMs: VERIFY_TIMEOUT_MS,
17417
+ signal,
17418
+ readOnly: runPolicy(assignment.policy).readOnly === true,
17419
+ githubEnvironment: context.githubEnvironment()
17420
+ });
17421
+ context.assertLive();
17422
+ execution = {
17423
+ exitCode: result.exitCode,
17424
+ signal: result.signal,
17425
+ timedOut: result.timedOut
17426
+ };
17427
+ const output = result.output.slice(-4e3);
17428
+ if (result.exitCode !== 0 || result.timedOut)
17429
+ return failed(output, verifyFailure(command, result));
17430
+ const after = fixedCandidateCheck(assignment) ? await fixedCheckSnapshot(repo.path, worktree, assignment.baseBranch, signal).then((fixed) => fixed.tree).catch(() => null) : publisher ? await publisher.snapshot({ worktree, repo, signal }).catch(() => null) : void 0;
17431
+ context.assertLive();
17432
+ if (after !== before)
17433
+ return failed(
17434
+ output,
17435
+ `Submitted, but the verify command changed the worktree (\`${command}\`); the work is unverified`
17436
+ );
17437
+ return {
17438
+ report: {
17439
+ ...report2,
17440
+ filesChanged,
17441
+ verify: { status: "passed", command, output, ...inferred ? { inferredFrom: inferred.basis } : {}, ...execution }
17442
+ },
17443
+ tree: before
17444
+ };
17445
+ }
17446
+ async function publishRun2(context, publisher, report2, tree) {
17447
+ const { runId, worktree, repo, assignment, signal } = context;
17448
+ let data;
17449
+ try {
17450
+ context.assertLive();
17451
+ data = await publisher.publish({
17452
+ runId,
17453
+ worktree,
17454
+ repo,
17455
+ assignment,
17456
+ report: report2,
17457
+ tree,
17458
+ githubEnvironment: context.githubEnvironment(),
17459
+ signal
17460
+ });
17461
+ } catch (error) {
17462
+ const message = error instanceof Error ? error.message : String(error);
17463
+ if (!signal.aborted) context.logPublishError(error);
17464
+ data = {
17465
+ branch: "",
17466
+ commit: null,
17467
+ pushed: false,
17468
+ remote: null,
17469
+ note: signal.aborted ? "Run stopped before publication completed" : `Commit failed: ${message}`.slice(0, 2e3)
17470
+ };
17471
+ }
17472
+ context.emitPublish(data);
17473
+ return data;
17474
+ }
17475
+ function profileSkillReport(runId, assignment, adapterStateDir) {
17476
+ const configured = (assignment.profileSkills ?? []).map((skill) => ({ id: skill.id, name: skill.name, source: skill.source, digest: skill.digest }));
17477
+ for (const slug of assignment.repositorySkills ?? []) {
17478
+ if (!configured.some((ref) => ref.id === `repository:${slug}`)) configured.push({ id: `repository:${slug}`, name: slug, source: "repository", digest: null });
17479
+ }
17480
+ if (configured.length === 0) return void 0;
17481
+ const loaded = [];
17482
+ if (adapterStateDir) {
17483
+ const dir = join30(runPaths(adapterStateDir, runId).runDir, PROFILE_SKILLS_DIR, PROFILE_SKILL_LOADS_DIR);
17484
+ try {
17485
+ for (const name of readdirSync8(dir).sort()) {
17486
+ if (!name.endsWith(".json") || loaded.length >= configured.length) continue;
17487
+ const file = join30(dir, name), meta = lstatSync11(file, { throwIfNoEntry: false });
17488
+ if (!meta?.isFile() || meta.isSymbolicLink() || meta.nlink !== 1 || meta.size < 2 || meta.size > 4096) continue;
17489
+ const receipt = profileSkillLoadReceiptSchema.safeParse(JSON.parse(readFileSync14(file, "utf8")));
17490
+ if (!receipt.success || loaded.some((item) => item.id === receipt.data.id)) continue;
17491
+ if (!configured.some((ref) => ref.id === receipt.data.id && (ref.digest === null || ref.digest === receipt.data.digest))) continue;
17492
+ loaded.push(receipt.data);
17493
+ }
17494
+ } catch {
17495
+ }
17496
+ }
17497
+ return { configured, loaded };
17498
+ }
17499
+ function pickAgentReport(agent) {
17500
+ if (!agent) return {};
17501
+ const picked = {};
17502
+ if (agent.repositorySelection) picked.repositorySelection = agent.repositorySelection;
17503
+ if (agent.verificationCommand && typeof agent.verificationCommand.command === "string" && agent.verificationCommand.command.trim() && typeof agent.verificationCommand.basis === "string" && agent.verificationCommand.basis.trim())
17504
+ picked.verificationCommand = { command: agent.verificationCommand.command.trim().slice(0, 2e3), basis: agent.verificationCommand.basis.trim().slice(0, 2e3) };
17505
+ const visualEvidence = runVisualEvidence.safeParse(agent.visualEvidence);
17506
+ if (visualEvidence.success) picked.visualEvidence = visualEvidence.data;
17507
+ const verdict = reviewVerdict.safeParse(agent.reviewVerdict);
17508
+ if (verdict.success) picked.reviewVerdict = verdict.data;
17509
+ if (typeof agent.summary === "string")
17510
+ picked.summary = agent.summary.slice(0, 1e4);
17511
+ if (Array.isArray(agent.openQuestions) && agent.openQuestions.every((q) => typeof q === "string"))
17512
+ picked.openQuestions = agent.openQuestions.slice(0, 50).map((q) => q.slice(0, 2e3));
17513
+ if (typeof agent.nextStep === "string")
17514
+ picked.nextStep = agent.nextStep.slice(0, 2e3);
17515
+ else if (agent.nextStep === null) picked.nextStep = null;
17516
+ if (typeof agent.blockedOn === "string")
17517
+ picked.blockedOn = agent.blockedOn.slice(0, 500);
17518
+ const question = runQuestion.safeParse(agent.question);
17519
+ if (question.success) picked.question = question.data;
17520
+ if (agent.plan) picked.plan = agent.plan;
17521
+ if (typeof agent.previewDatabaseBranch === "string" && agent.previewDatabaseBranch.trim())
17522
+ picked.previewDatabaseBranch = agent.previewDatabaseBranch.trim().slice(0, 500);
17523
+ if (Array.isArray(agent.criteria)) {
17524
+ const criteria = [];
17525
+ for (const entry of agent.criteria) {
17526
+ if (criteria.length >= MAX_REPORTED_CRITERIA) break;
17527
+ if (!entry || typeof entry !== "object") continue;
17528
+ const { criterionId, text: text4, passed, status: status3, reason, resolution, evidence, command, exitCode } = entry;
17529
+ if (!(typeof criterionId === "string" && UUID_RE.test(criterionId)) && !(typeof text4 === "string" && text4.trim()))
17530
+ continue;
17531
+ if (typeof passed !== "boolean") continue;
17532
+ const criterion = runCriterion.safeParse({
17533
+ ...typeof criterionId === "string" && UUID_RE.test(criterionId) ? { criterionId } : {},
17534
+ ...typeof text4 === "string" && text4.trim() ? { text: text4.trim().slice(0, 2e3) } : {},
17535
+ passed,
17536
+ ...status3 !== void 0 ? { status: status3 } : {},
17537
+ ...typeof reason === "string" && reason.trim() ? { reason: reason.trim().slice(0, 2e3) } : {},
17538
+ ...typeof resolution === "string" && resolution.trim() ? { resolution: resolution.trim().slice(0, 2e3) } : {},
17539
+ ...typeof command === "string" && command.trim() ? { command: command.trim().slice(0, 2e3), ...exitCode === null || typeof exitCode === "number" && Number.isSafeInteger(exitCode) ? { exitCode } : {} } : {},
17540
+ ...typeof evidence === "string" ? { evidence: evidence.slice(0, 1e4) } : {}
17541
+ });
17542
+ if (criterion.success) criteria.push(criterion.data);
17543
+ }
17544
+ picked.criteria = criteria;
17545
+ }
17546
+ return picked;
17547
+ }
17548
+ async function unsandboxedVerify(run3) {
17549
+ const result = await execa10(run3.command, {
17550
+ shell: true,
17551
+ cwd: run3.worktree,
17552
+ env: buildChildEnv(),
17553
+ extendEnv: false,
17554
+ reject: false,
17555
+ all: true,
17556
+ stdin: "ignore",
17557
+ timeout: run3.timeoutMs,
17558
+ cancelSignal: run3.signal,
17559
+ killDescendants: true
17560
+ });
17561
+ return {
17562
+ exitCode: result.exitCode ?? null,
17563
+ signal: result.signal ?? null,
17564
+ timedOut: result.timedOut,
17565
+ output: String(result.all ?? "")
17566
+ };
17567
+ }
17568
+ function verifyFailure(command, result) {
17569
+ const how = result.timedOut ? "timed out" : result.exitCode !== null ? `exited with code ${result.exitCode}` : result.signal ? `was killed by ${result.signal}` : "did not finish";
17570
+ return `Submitted, but the verify command failed: \`${command}\` ${how}`;
17571
+ }
17572
+ function baseReport(summary = "") {
17573
+ return emptyRunReport(summary.slice(0, 1e4));
17574
+ }
17575
+ function isReadOnlyTask(assignment) {
17576
+ return runPolicy(assignment.policy).readOnly === true && assignment.kind !== "acceptance" && !assignment.benchmark;
17577
+ }
17578
+ function skillPromptOf(assignment) {
17579
+ const skills = assignment.skills;
17580
+ if (!skills?.length) return void 0;
17581
+ const plan = skillPromptPlan(skills);
17582
+ return {
17583
+ budgetChars: plan.budgetChars,
17584
+ usedChars: plan.usedChars,
17585
+ inlined: plan.inlined.map((entry) => entry.name),
17586
+ deferred: plan.degraded.map((entry) => entry.name)
17587
+ };
17588
+ }
17589
+ function fixedCandidateCheck(assignment) {
17590
+ return assignment.kind === "acceptance" && runPolicy(assignment.policy).readOnly === true && typeof assignment.baseBranch === "string" && /^[a-f0-9]{40}$/.test(assignment.baseBranch);
17591
+ }
17592
+
17120
17593
  // src/tool-duration.ts
17121
17594
  function toolDuration(clock = () => performance.now()) {
17122
17595
  const starts = /* @__PURE__ */ new Map();
@@ -17340,9 +17813,9 @@ async function startTaskSecretBridge(options) {
17340
17813
  }
17341
17814
 
17342
17815
  // src/agents/chat-files.ts
17343
- import { createHash as createHash11 } from "node:crypto";
17816
+ import { createHash as createHash12 } from "node:crypto";
17344
17817
  import { lstat as lstat4, mkdir as mkdir4, readFile as readFile5, writeFile as writeFile3 } from "node:fs/promises";
17345
- import { join as join29 } from "node:path";
17818
+ import { join as join31 } from "node:path";
17346
17819
  async function materializeChatFiles(text4, directory, download2) {
17347
17820
  const parsed = splitChatFiles(text4);
17348
17821
  if (!parsed.files.length) return text4;
@@ -17354,19 +17827,19 @@ async function materializeChatFiles(text4, directory, download2) {
17354
17827
  const file = chatFileDownloadSchema.parse(await download2(ref.id));
17355
17828
  if (file.id !== ref.id) throw Error("Attachment identity mismatch");
17356
17829
  const bytes = Buffer.from(file.data, "base64");
17357
- if (bytes.length !== file.size || bytes.toString("base64") !== file.data || createHash11("sha256").update(bytes).digest("hex") !== file.sha256)
17830
+ if (bytes.length !== file.size || bytes.toString("base64") !== file.data || createHash12("sha256").update(bytes).digest("hex") !== file.sha256)
17358
17831
  throw Error("Attachment content mismatch");
17359
17832
  const ext = /\.([a-z0-9]{1,12})$/i.exec(file.name)?.[1]?.toLowerCase() ?? "bin";
17360
- const path3 = join29(directory, `${file.id}.${ext}`);
17833
+ const path3 = join31(directory, `${file.id}.${ext}`);
17361
17834
  try {
17362
17835
  await writeFile3(path3, bytes, { flag: "wx", mode: 256 });
17363
17836
  } catch (error) {
17364
- if (error.code !== "EEXIST" || (await lstat4(path3)).isSymbolicLink() || createHash11("sha256").update(await readFile5(path3)).digest("hex") !== file.sha256)
17837
+ if (error.code !== "EEXIST" || (await lstat4(path3)).isSymbolicLink() || createHash12("sha256").update(await readFile5(path3)).digest("hex") !== file.sha256)
17365
17838
  throw Error("Attachment file unavailable");
17366
17839
  }
17367
17840
  let textPath;
17368
17841
  if (file.text !== null) {
17369
- textPath = join29(directory, `${file.id}.extracted.txt`);
17842
+ textPath = join31(directory, `${file.id}.extracted.txt`);
17370
17843
  try {
17371
17844
  await writeFile3(textPath, file.text, { flag: "wx", mode: 256 });
17372
17845
  } catch (error) {
@@ -17382,42 +17855,6 @@ Attached files (read the original files; extracted document text is provided whe
17382
17855
  ${JSON.stringify(entries)}`;
17383
17856
  }
17384
17857
 
17385
- // src/runs/check.ts
17386
- import { execa as execa9 } from "execa";
17387
- async function fixedCheckSnapshot(repoPath, worktree, sha6, signal) {
17388
- signal?.throwIfAborted();
17389
- if (!/^[a-f0-9]{40}$/.test(sha6))
17390
- throw new Error("Check requires an exact candidate SHA");
17391
- const gitDir = await worktreeGitDir(repoPath, worktree, signal);
17392
- const git3 = async (...args) => (await execa9(
17393
- "git",
17394
- [
17395
- "-c",
17396
- "core.hooksPath=/dev/null",
17397
- "-c",
17398
- "core.fsmonitor=false",
17399
- ...args
17400
- ],
17401
- {
17402
- cwd: worktree,
17403
- env: { GIT_DIR: gitDir, GIT_WORK_TREE: worktree },
17404
- stdin: "ignore",
17405
- cancelSignal: signal,
17406
- killDescendants: true
17407
- }
17408
- )).stdout.trim();
17409
- if (await git3("rev-parse", "HEAD") !== sha6)
17410
- throw new Error("Check worktree HEAD differs from the fixed candidate");
17411
- if (await git3("status", "--porcelain"))
17412
- throw new Error(
17413
- "Check worktree contains changes outside the fixed candidate"
17414
- );
17415
- return { sha: sha6, tree: await git3("rev-parse", `${sha6}^{tree}`) };
17416
- }
17417
-
17418
- // src/runs/supervisor.ts
17419
- import { lstatSync as lstatSync11, readFileSync as readFileSync14, readdirSync as readdirSync8 } from "node:fs";
17420
-
17421
17858
  // src/secret-mask.ts
17422
17859
  import { gunzipSync, gzipSync } from "node:zlib";
17423
17860
  var MASK_MIN_LENGTH = 8;
@@ -17560,23 +17997,22 @@ function createRunMasker(secrets) {
17560
17997
 
17561
17998
  // src/runs/supervisor.ts
17562
17999
  import { stdSerializers } from "pino";
17563
- import { createHash as createHash13, randomUUID as randomUUID6 } from "node:crypto";
17564
- import { join as join31, resolve as resolve14 } from "node:path";
18000
+ import { createHash as createHash14, randomUUID as randomUUID6 } from "node:crypto";
18001
+ import { join as join33, resolve as resolve14 } from "node:path";
17565
18002
  import { tmpdir as tmpdir5 } from "node:os";
17566
- import { execa as execa12 } from "execa";
17567
18003
 
17568
18004
  // src/agents/checkpoint.ts
17569
18005
  import { mkdtempSync as mkdtempSync9, rmSync as rmSync19, writeFileSync as writeFileSync9 } from "node:fs";
17570
18006
  import { tmpdir as tmpdir4 } from "node:os";
17571
- import { join as join30 } from "node:path";
18007
+ import { join as join32 } from "node:path";
17572
18008
  import { gunzipSync as gunzipSync2, gzipSync as gzipSync2 } from "node:zlib";
17573
- import { execa as execa11 } from "execa";
18009
+ import { execa as execa12 } from "execa";
17574
18010
 
17575
18011
  // src/coding-workspace/checkpoint.ts
17576
- import { createHash as createHash12 } from "node:crypto";
18012
+ import { createHash as createHash13 } from "node:crypto";
17577
18013
  import { resolve as resolve13 } from "node:path";
17578
- import { execa as execa10 } from "execa";
17579
- var digest6 = (value) => createHash12("sha256").update(value).digest("hex");
18014
+ import { execa as execa11 } from "execa";
18015
+ var digest6 = (value) => createHash13("sha256").update(value).digest("hex");
17580
18016
  var oid = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/;
17581
18017
  var MANIFEST_BYTES = 1536 * 1024;
17582
18018
  var regular = (mode) => mode === null || mode === "100644" || mode === "100755";
@@ -17617,7 +18053,7 @@ async function captureCheckpointReview(input) {
17617
18053
  };
17618
18054
  const git3 = async (args, text4, maximum = MANIFEST_BYTES) => {
17619
18055
  signal.throwIfAborted();
17620
- const child = await execa10("git", [
18056
+ const child = await execa11("git", [
17621
18057
  "--no-optional-locks",
17622
18058
  "-c",
17623
18059
  "core.hooksPath=/dev/null",
@@ -17795,8 +18231,8 @@ async function takeCheckpoint(options) {
17795
18231
  }
17796
18232
  async function applyCheckpoint(options) {
17797
18233
  const git3 = await pinnedGit(options.repoPath, options.worktree);
17798
- const dir = mkdtempSync9(join30(tmpdir4(), "mikka-checkpoint-"));
17799
- const file = join30(dir, "checkpoint.patch");
18234
+ const dir = mkdtempSync9(join32(tmpdir4(), "mikka-checkpoint-"));
18235
+ const file = join32(dir, "checkpoint.patch");
17800
18236
  try {
17801
18237
  const patch = gunzipSync2(Buffer.from(options.checkpoint.patch, "base64"));
17802
18238
  if (!patch.length && options.checkpoint.files === 0) return true;
@@ -17817,7 +18253,7 @@ async function applyCheckpoint(options) {
17817
18253
  }
17818
18254
  }
17819
18255
  async function hasCommit(repoPath, commit) {
17820
- return execa11(
18256
+ return execa12(
17821
18257
  "git",
17822
18258
  ["-c", "core.hooksPath=/dev/null", "cat-file", "-e", `${commit}^{commit}`],
17823
18259
  { cwd: repoPath, stdin: "ignore" }
@@ -18140,10 +18576,6 @@ var MemoryServer = class {
18140
18576
  var DEFAULT_STALL_MS = 10 * 6e4;
18141
18577
  var DEFAULT_STOP_GRACE_MS = 3e3;
18142
18578
  var DEFAULT_CANCEL_GRACE_MS = 1e4;
18143
- var VERIFY_TIMEOUT_MS = 30 * 6e4;
18144
- var MAX_REPORTED_FILES = 5e3;
18145
- var MAX_REPORTED_CRITERIA = 200;
18146
- var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
18147
18579
  var CHECKPOINT_EVERY_MS = 2 * 6e4;
18148
18580
  var RunSupervisor = class {
18149
18581
  constructor(deps) {
@@ -18590,7 +19022,7 @@ var RunSupervisor = class {
18590
19022
  const entry = this.deps.journal.get(runId);
18591
19023
  if (splitChatFiles(text4).files.length) {
18592
19024
  if (!entry || !this.deps.downloadChatFile || !this.deps.adapterStateDir) throw Error("Run attachments unavailable");
18593
- text4 = await materializeChatFiles(text4, join31(this.deps.adapterStateDir, "inputs", runId), (id5) => this.deps.downloadChatFile(entry.assignment, id5, run3.abort.signal));
19025
+ text4 = await materializeChatFiles(text4, join33(this.deps.adapterStateDir, "inputs", runId), (id5) => this.deps.downloadChatFile(entry.assignment, id5, run3.abort.signal));
18594
19026
  }
18595
19027
  await run3.session.send(text4, mode);
18596
19028
  }
@@ -18761,80 +19193,25 @@ var RunSupervisor = class {
18761
19193
  * The only way into a terminal state: the terminal patch, then exactly one
18762
19194
  * completion for the server, then the outbox is compacted.
18763
19195
  */
18764
- finish(runId, stopReason, error, report2 = baseReport(error), failureDetails) {
19196
+ finish(runId, stopReason, error, report2, failureDetails) {
18765
19197
  this.active.get(runId)?.toolApproval?.revoke();
18766
19198
  const active = this.active.get(runId);
18767
- if (active?.cancelRequested || active?.forcedStop) {
18768
- stopReason = active.forcedStop ?? "cancelled";
18769
- error = void 0;
18770
- }
18771
- active?.span?.set("mikka.outcome", stopReason);
18772
- if (stopReason !== "provider_failure" && report2.providerFailure) {
18773
- const { providerFailure: _failure, ...rest } = report2;
18774
- report2 = rest;
18775
- }
18776
- if (stopReason !== "provider_failure" && stopReason !== "quota_exhausted" && report2.providerCheckpoint) {
18777
- const { providerCheckpoint: _checkpoint, ...rest } = report2;
18778
- report2 = rest;
18779
- }
18780
- const entry = this.deps.journal.get(runId);
18781
- const planning = entry?.assignment.kind === "plan";
18782
- if (entry && stopReason === "blocked" && report2.repositorySelection)
18783
- entry.assignment.preserveQuestionWorktree = true;
18784
- const readOnlyTask = entry && (isReadOnlyTask(entry.assignment) || entry.assignment.factoryCheck?.reportOnly === true || entry.assignment.factoryExecuteKind === "deliverable");
18785
- const { sourceCommit: _source, deliverableCommit: _delivery, skillMount: _mount, skillPrompt: _prompt, execution: _execution, runtime: _runtime, safePoint: _safePoint, ...content } = report2;
18786
- report2 = {
18787
- ...content,
18788
- ...active?.safePoint ? { safePoint: active.safePoint } : {},
18789
- ...entry?.baseCommit && /^[a-f0-9]{40}$/.test(entry.baseCommit) ? { sourceCommit: entry.baseCommit } : {},
18790
- ...entry?.assignment.factoryExecuteKind === "deliverable" && entry.deliverableCommit ? { deliverableCommit: entry.deliverableCommit } : {},
18791
- // What the prompt actually carried of the run's skills; a deferred body
18792
- // is a fact the person needs to see, not something to leave unsaid.
18793
- ...entry && skillPromptOf(entry.assignment) ? { skillPrompt: skillPromptOf(entry.assignment) } : {},
18794
- ...entry?.skillMount && entry.skillMount.sessionId === entry.sessionId && entry.skillMount.receiptId === entry.assignment.skillReceipt?.id && entry.skillMount.versionId === entry.assignment.skillReceipt?.artifact.versionId && entry.skillMount.sha256 === entry.assignment.skillReceipt?.artifact.sha256 ? {
18795
- skillMount: entry.skillMount,
18796
- ...entry.runtime ? { runtime: {
18797
- ...entry.runtime,
18798
- observedModel: this.active.get(runId)?.session?.runtimeModel ?? entry.runtime.observedModel
18799
- } } : {},
18800
- ...entry.execution && entry.assignment.benchmark ? { execution: {
18801
- ...entry.execution,
18802
- observedModel: this.active.get(runId)?.session?.runtimeModel ?? entry.execution.observedModel
18803
- } } : {}
18804
- } : {}
18805
- };
18806
- this.emitPlanCards(runId, report2, planning);
18807
- this.endMessage(runId, this.active.get(runId)?.runtimeTiming?.finish());
18808
- this.flushMasker(runId);
18809
- this.openParts.delete(runId);
18810
- if (stopReason === "submitted") this.setState(runId, "finishing");
18811
- let state2 = runStateForStop(stopReason);
18812
- if (stopReason === "submitted" && report2.verify.status !== "passed") {
18813
- const failed = report2.verify.status === "failed";
18814
- if (!planning && !readOnlyTask) state2 = failed ? "failed" : report2.publish?.pushed === true ? "succeeded" : "stopped";
18815
- if (!failed && !planning && !readOnlyTask)
18816
- error ??= "Submitted, but no verify command ran; the work is unverified";
18817
- }
18818
- if ((stopReason === "asked_human" || stopReason === "blocked") && report2.question) {
18819
- this.deps.journal.update(runId, {
18820
- waitingQuestionId: report2.question.questionId
18821
- });
18822
- }
18823
- if (state2 === "failed") active?.span?.fail({ name: "RunFailure" }, stopReason);
18824
- else active?.span?.set("mikka.outcome", stopReason);
18825
- this.setState(runId, state2, {
18826
- stopReason,
18827
- ...error ? { error } : {}
18828
- });
18829
- const terminalFailure = state2 === "failed" && !active?.cancelRequested && !active?.forcedStop ? captureRunFailure(failureDetails ?? new Error(error ?? report2.summary), {
19199
+ finishRun({
18830
19200
  runId,
18831
- appVersion: DAEMON_VERSION,
18832
- sensitiveText: [entry?.assignment.prompt ?? ""]
18833
- }) : void 0;
18834
- this.push(runId, {
18835
- kind: "complete",
18836
- completion: { stopReason, report: report2, ...terminalFailure ? { failureDetails: terminalFailure } : {} }
18837
- });
19201
+ journal: this.deps.journal,
19202
+ active,
19203
+ closeOutput: (report3, planning) => {
19204
+ this.emitPlanCards(runId, report3, planning);
19205
+ this.endMessage(runId, this.active.get(runId)?.runtimeTiming?.finish());
19206
+ this.flushMasker(runId);
19207
+ this.openParts.delete(runId);
19208
+ },
19209
+ setState: (state2, extra) => this.setState(runId, state2, extra),
19210
+ complete: (completion) => this.push(runId, { kind: "complete", completion })
19211
+ }, stopReason, error, report2, failureDetails);
19212
+ this.cleanupFinishedRun(runId);
19213
+ }
19214
+ cleanupFinishedRun(runId) {
18838
19215
  this.disposeMasker(runId);
18839
19216
  const run3 = this.active.get(runId);
18840
19217
  if (run3) void this.closeMailbox(run3).catch(() => this.deps.log.warn("Run mailbox shutdown failed"));
@@ -18935,143 +19312,6 @@ var RunSupervisor = class {
18935
19312
  this.forceStop(runId, run3, "device_lost");
18936
19313
  signal.throwIfAborted();
18937
19314
  }
18938
- /**
18939
- * What the frozen Profile selected and what its agent actually loaded. The
18940
- * load receipts are written by the `load_skill` tool itself; a configured
18941
- * Skill without a receipt is not reported as used. Digests must match the
18942
- * configured pinned body, so a tampered manifest cannot mint a receipt.
18943
- */
18944
- profileSkillReport(runId, assignment) {
18945
- const configured = (assignment.profileSkills ?? []).map((skill) => ({ id: skill.id, name: skill.name, source: skill.source, digest: skill.digest }));
18946
- for (const slug of assignment.repositorySkills ?? []) {
18947
- if (!configured.some((ref) => ref.id === `repository:${slug}`)) configured.push({ id: `repository:${slug}`, name: slug, source: "repository", digest: null });
18948
- }
18949
- if (configured.length === 0) return void 0;
18950
- const loaded = [];
18951
- if (this.deps.adapterStateDir) {
18952
- const dir = join31(runPaths(this.deps.adapterStateDir, runId).runDir, PROFILE_SKILLS_DIR, PROFILE_SKILL_LOADS_DIR);
18953
- try {
18954
- for (const name of readdirSync8(dir).sort()) {
18955
- if (!name.endsWith(".json") || loaded.length >= configured.length) continue;
18956
- const file = join31(dir, name), meta = lstatSync11(file, { throwIfNoEntry: false });
18957
- if (!meta?.isFile() || meta.isSymbolicLink() || meta.nlink !== 1 || meta.size < 2 || meta.size > 4096) continue;
18958
- const receipt = profileSkillLoadReceiptSchema.safeParse(JSON.parse(readFileSync14(file, "utf8")));
18959
- if (!receipt.success || loaded.some((item) => item.id === receipt.data.id)) continue;
18960
- if (!configured.some((ref) => ref.id === receipt.data.id && (ref.digest === null || ref.digest === receipt.data.digest))) continue;
18961
- loaded.push(receipt.data);
18962
- }
18963
- } catch {
18964
- }
18965
- }
18966
- return { configured, loaded };
18967
- }
18968
- /**
18969
- * The handoff report: the agent's own words (summary, questions, next
18970
- * step, blocker) plus what only the daemon may state: changed files and,
18971
- * after a submit, the verify result. Anything else the agent sent
18972
- * (a self-reported verify, say) is dropped. `verifyError` describes a
18973
- * failed verify (command and exit code) for the run's error text.
18974
- */
18975
- async report(runId, worktree, repo, assignment, stopReason, error, agent, signal) {
18976
- const profileSkills = this.profileSkillReport(runId, assignment);
18977
- let report2 = {
18978
- ...baseReport(error),
18979
- ...pickAgentReport(agent),
18980
- ...profileSkills ? { profileSkills } : {}
18981
- };
18982
- const filesChanged = (await this.deps.worktrees.changedFiles(worktree, this.deps.journal.get(runId)?.baseCommit).catch(() => [])).slice(0, MAX_REPORTED_FILES);
18983
- const inferred = assignment.factoryCheck?.stage === "verify" && assignment.factoryCheck.inferCommand && !assignment.factoryCheck.reportOnly ? report2.verificationCommand : void 0;
18984
- const command = assignment.verifyCommand ?? inferred?.command;
18985
- if (stopReason === "submitted") this.assertFinishingRunLive(runId, signal);
18986
- if (stopReason === "submitted" && assignment.factoryExecuteKind === "deliverable") {
18987
- const deliverableCommit = await retainDeliverable(repo.path, worktree, runId, signal);
18988
- this.assertFinishingRunLive(runId, signal);
18989
- this.deps.journal.update(runId, { deliverableCommit });
18990
- }
18991
- if (stopReason !== "submitted" && fixedCandidateCheck(assignment)) {
18992
- const fixed = await fixedCheckSnapshot(repo.path, worktree, assignment.baseBranch, signal).catch(() => null);
18993
- if (fixed) report2 = { ...report2, check: { sha: fixed.sha, readOnly: true } };
18994
- }
18995
- if (stopReason !== "submitted" || assignment.kind === "plan" || isReadOnlyTask(assignment) || assignment.factoryExecuteKind === "deliverable")
18996
- return {
18997
- report: { ...report2, filesChanged, verify: { status: "not_run" } }
18998
- };
18999
- if (!command) {
19000
- if (fixedCandidateCheck(assignment)) {
19001
- const fixed = await fixedCheckSnapshot(repo.path, worktree, assignment.baseBranch, signal);
19002
- report2 = { ...report2, check: { sha: fixed.sha, readOnly: true } };
19003
- }
19004
- this.assertFinishingRunLive(runId, signal);
19005
- const tree = await this.deps.publisher?.snapshot({ worktree, repo, signal });
19006
- this.assertFinishingRunLive(runId, signal);
19007
- return { report: { ...report2, filesChanged, verify: { status: "not_run" } }, tree };
19008
- }
19009
- let execution = {};
19010
- const failed = (output2, verifyError) => ({
19011
- report: {
19012
- ...report2,
19013
- filesChanged,
19014
- verify: { status: "failed", command, output: output2, ...execution }
19015
- },
19016
- verifyError
19017
- });
19018
- const publisher = this.deps.publisher;
19019
- let before;
19020
- try {
19021
- if (fixedCandidateCheck(assignment)) {
19022
- if (runPolicy(assignment.policy).readOnly !== true)
19023
- throw new Error("Check assignment is missing its read-only policy");
19024
- const fixed = await fixedCheckSnapshot(
19025
- repo.path,
19026
- worktree,
19027
- assignment.baseBranch,
19028
- signal
19029
- );
19030
- report2 = { ...report2, check: { sha: fixed.sha, readOnly: true } };
19031
- before = fixed.tree;
19032
- } else {
19033
- before = await publisher?.snapshot({ worktree, repo, signal });
19034
- }
19035
- } catch (snapshotError) {
19036
- signal.throwIfAborted();
19037
- return failed("", `Could not read the worktree: ${String(snapshotError)}`);
19038
- }
19039
- this.assertFinishingRunLive(runId, signal);
19040
- const result = await (this.deps.verify ?? unsandboxedVerify)({
19041
- runId,
19042
- worktree,
19043
- repo,
19044
- command,
19045
- timeoutMs: VERIFY_TIMEOUT_MS,
19046
- signal,
19047
- readOnly: runPolicy(assignment.policy).readOnly === true,
19048
- githubEnvironment: this.active.get(runId)?.github?.env
19049
- });
19050
- this.assertFinishingRunLive(runId, signal);
19051
- execution = {
19052
- exitCode: result.exitCode,
19053
- signal: result.signal,
19054
- timedOut: result.timedOut
19055
- };
19056
- const output = result.output.slice(-4e3);
19057
- if (result.exitCode !== 0 || result.timedOut)
19058
- return failed(output, verifyFailure(command, result));
19059
- const after = fixedCandidateCheck(assignment) ? await fixedCheckSnapshot(repo.path, worktree, assignment.baseBranch, signal).then((fixed) => fixed.tree).catch(() => null) : publisher ? await publisher.snapshot({ worktree, repo, signal }).catch(() => null) : void 0;
19060
- this.assertFinishingRunLive(runId, signal);
19061
- if (after !== before)
19062
- return failed(
19063
- output,
19064
- `Submitted, but the verify command changed the worktree (\`${command}\`); the work is unverified`
19065
- );
19066
- return {
19067
- report: {
19068
- ...report2,
19069
- filesChanged,
19070
- verify: { status: "passed", command, output, ...inferred ? { inferredFrom: inferred.basis } : {}, ...execution }
19071
- },
19072
- tree: before
19073
- };
19074
- }
19075
19315
  /**
19076
19316
  * Where a fresh worktree starts: the issue's branch on the remote when
19077
19317
  * the run pushes there (ADR 0024), so it builds on what earlier runs and
@@ -19097,7 +19337,7 @@ var RunSupervisor = class {
19097
19337
  try {
19098
19338
  return await withRunGitCredentials(
19099
19339
  assignment,
19100
- runPaths(this.deps.adapterStateDir ?? join31(tmpdir5(), "mikka-run-state"), runId).privateDir,
19340
+ runPaths(this.deps.adapterStateDir ?? join33(tmpdir5(), "mikka-run-state"), runId).privateDir,
19101
19341
  (env) => this.deps.worktrees.fetchBranch(
19102
19342
  repo.path,
19103
19343
  repo.push?.remote ?? "origin",
@@ -19115,39 +19355,6 @@ var RunSupervisor = class {
19115
19355
  return base;
19116
19356
  }
19117
19357
  }
19118
- /**
19119
- * A failed commit or push is reported (in a `data-publish` chunk and in
19120
- * the completion's report), never fails the verified run.
19121
- */
19122
- async publish(runId, worktree, repo, assignment, report2, tree, signal) {
19123
- const publisher = this.deps.publisher;
19124
- let data;
19125
- try {
19126
- this.assertFinishingRunLive(runId, signal);
19127
- data = await publisher.publish({
19128
- runId,
19129
- worktree,
19130
- repo,
19131
- assignment,
19132
- report: report2,
19133
- tree,
19134
- githubEnvironment: this.active.get(runId)?.github?.env,
19135
- signal
19136
- });
19137
- } catch (error) {
19138
- const message = error instanceof Error ? error.message : String(error);
19139
- if (!signal.aborted) this.deps.log.error({ run_id: runId, err: this.logError(runId, error) }, "publish failed");
19140
- data = {
19141
- branch: "",
19142
- commit: null,
19143
- pushed: false,
19144
- remote: null,
19145
- note: signal.aborted ? "Run stopped before publication completed" : `Commit failed: ${message}`.slice(0, 2e3)
19146
- };
19147
- }
19148
- this.emit(runId, { type: "data-publish", data });
19149
- return data;
19150
- }
19151
19358
  launch(runId, repo, initialClaim = false) {
19152
19359
  const run3 = {
19153
19360
  repoPath: repo.path,
@@ -19496,7 +19703,7 @@ ${run3.drive.folders.map((folder) => `- ${folder.scope}: ${folder.path}${folder.
19496
19703
  let followUp = assignment.followUp;
19497
19704
  if (splitChatFiles(prompt).files.length || followUp && splitChatFiles(followUp).files.length) {
19498
19705
  if (!this.deps.downloadChatFile || !this.deps.adapterStateDir) throw Error("Run attachments unavailable");
19499
- const directory = join31(this.deps.adapterStateDir, "inputs", runId);
19706
+ const directory = join33(this.deps.adapterStateDir, "inputs", runId);
19500
19707
  const download2 = (id5) => this.deps.downloadChatFile(assignment, id5, run3.abort.signal);
19501
19708
  prompt = await materializeChatFiles(prompt, directory, download2);
19502
19709
  if (followUp) followUp = await materializeChatFiles(followUp, directory, download2);
@@ -19518,13 +19725,13 @@ ${run3.drive.folders.map((folder) => `- ${folder.scope}: ${folder.path}${folder.
19518
19725
  if (assignment.requireSessionResume && (!assignment.resumeSessionId || !assignment.continuesRunId || !adapter.capabilities.supportsResume || !resuming && !continueSession || resuming && entry.sessionId !== assignment.resumeSessionId))
19519
19726
  throw new Error("factory_question_session_resume_required");
19520
19727
  const benchmark = assignment.benchmark;
19521
- const policyDigest = assignment.skillReceipt ? createHash13("sha256").update(runPolicyDigestInput(assignment.policy)).digest("hex") : void 0;
19728
+ const policyDigest = assignment.skillReceipt ? createHash14("sha256").update(runPolicyDigestInput(assignment.policy)).digest("hex") : void 0;
19522
19729
  if (benchmark && (!assignment.skillReceipt || assignment.harness === "mock" || !assignment.verifyCommand || benchmark.sourceCommit !== this.deps.journal.get(runId)?.baseCommit || policyDigest !== benchmark.policyDigest)) throw new Error("Frozen benchmark execution configuration mismatch");
19523
19730
  let fixtureDigest;
19524
19731
  if (benchmark) {
19525
19732
  if (runPolicy(assignment.policy).readOnly !== true) throw new Error("Benchmark fixture must be read-only");
19526
19733
  const fixed = await fixedCheckSnapshot(repo.path, worktree, benchmark.sourceCommit);
19527
- fixtureDigest = createHash13("sha256").update(fixed.sha).digest("hex");
19734
+ fixtureDigest = createHash14("sha256").update(fixed.sha).digest("hex");
19528
19735
  if (fixtureDigest !== benchmark.fixtureDigest) throw new Error("Frozen benchmark fixture digest mismatch");
19529
19736
  }
19530
19737
  const previousMount = entry.skillMount;
@@ -19565,7 +19772,7 @@ ${run3.drive.folders.map((folder) => `- ${folder.scope}: ${folder.path}${folder.
19565
19772
  if (!this.deps.adapterStateDir || assignment.harness === "mock" || !session.sessionId || resuming && session.sessionId !== entry.sessionId || assignment.requireSessionResume && session.sessionId !== assignment.resumeSessionId)
19566
19773
  throw new Error("Skill mount requires the actual original harness session");
19567
19774
  verifySkillAssignment(assignment);
19568
- const file = join31(
19775
+ const file = join33(
19569
19776
  runPaths(this.deps.adapterStateDir, runId).runDir,
19570
19777
  SKILLS_DIR,
19571
19778
  skillSlug(assignment.skills[0].name),
@@ -19677,55 +19884,29 @@ ${run3.drive.folders.map((folder) => `- ${folder.scope}: ${folder.path}${folder.
19677
19884
  const finishingSignal = AbortSignal.any([this.stopController.signal, run3.abort.signal]);
19678
19885
  run3.runtimeTiming?.finishing();
19679
19886
  await this.closeMailbox(run3);
19680
- let stopReason = stopReasonOf(event, run3, assignment);
19681
- const error = event.error ?? (stopReason === "turn_ended" ? "Session ended without a submission" : stopReason === "timeout" ? "No progress before the watchdog limit" : stopReason === "device_lost" ? "Run lease expired; the server could not be reached" : void 0);
19682
- let outcome;
19683
- try {
19684
- if (assignment.benchmark && !run3.cancelRequested) {
19685
- const fixed = await fixedCheckSnapshot(repo.path, worktree, assignment.benchmark.sourceCommit, finishingSignal);
19686
- if (createHash13("sha256").update(fixed.sha).digest("hex") !== assignment.benchmark.fixtureDigest)
19687
- throw new Error("Benchmark fixture changed during model execution");
19688
- }
19689
- outcome = await this.report(runId, worktree, repo, assignment, stopReason, error, event.report, finishingSignal);
19690
- } catch (error2) {
19691
- if (!finishingSignal.aborted) throw error2;
19692
- outcome = { report: { ...baseReport(), ...pickAgentReport(event.report) } };
19693
- }
19694
- if (this.stopping) return;
19695
- stopReason = stopReasonOf(event, run3, assignment);
19696
- const { verifyError, tree } = outcome;
19697
- let report2 = stopReason === "quota_exhausted" ? { ...outcome.report, resetsAt: event.quota?.resetsAt ?? null } : outcome.report;
19698
- if (stopReason === "provider_failure") {
19699
- report2 = {
19700
- ...report2,
19701
- providerFailure: providerFailureSchema.parse(event.providerFailure),
19702
- ...event.quota ? { resetsAt: event.quota.resetsAt } : {}
19703
- };
19704
- }
19705
- const policy = runPolicy(assignment.policy);
19706
- if (stopReason === "submitted" && report2.verify.status !== "failed" && tree && // The draft-PR exception requires an explicit repository push
19707
- // approval. It must not even create a local commit without it.
19708
- (report2.verify.status === "passed" || pushDecision(policy).push) && // A read-only check (ADR 0046) never commits or pushes: it reports
19709
- // on the commit the implementation run already pushed.
19710
- policy.readOnly !== true) {
19711
- const publish = await this.publish(
19712
- runId,
19713
- worktree,
19714
- repo,
19715
- assignment,
19716
- report2,
19717
- tree,
19718
- finishingSignal
19719
- );
19720
- report2 = { ...report2, publish };
19721
- stopReason = stopReasonOf(event, run3, assignment);
19722
- }
19887
+ const publication = await verifyAndPublish({
19888
+ deps: this.deps,
19889
+ runId,
19890
+ worktree,
19891
+ repo,
19892
+ assignment,
19893
+ signal: finishingSignal,
19894
+ assertLive: () => this.assertFinishingRunLive(runId, finishingSignal),
19895
+ githubEnvironment: () => this.active.get(runId)?.github?.env,
19896
+ getStopReason: () => stopReasonOf(event, run3, assignment),
19897
+ isStopping: () => this.stopping,
19898
+ cancelRequested: run3.cancelRequested,
19899
+ logPublishError: (error) => this.deps.log.error({ run_id: runId, err: this.logError(runId, error) }, "publish failed"),
19900
+ emitPublish: (data) => this.emit(runId, { type: "data-publish", data })
19901
+ }, event);
19902
+ if (!publication) return;
19903
+ let { report: report2 } = publication;
19723
19904
  const capturesSaved = !this.stopping && await this.flushCaptures(runId, finishingSignal);
19724
- stopReason = stopReasonOf(event, run3, assignment);
19905
+ const stopReason = stopReasonOf(event, run3, assignment);
19725
19906
  const checkpoint = await this.saveTerminalCheckpoint(runId, run3, capturesSaved);
19726
19907
  if (stopReason === "provider_failure" || stopReason === "quota_exhausted") report2 = { ...report2, providerCheckpoint: checkpoint.checkpoint };
19727
19908
  if (this.stopping) return;
19728
- this.finish(runId, stopReason, error ?? verifyError, report2, event.failureDetails);
19909
+ this.finish(runId, stopReason, publication.error, report2, event.failureDetails);
19729
19910
  log.info(
19730
19911
  { outcome: event.outcome, stop_reason: stopReason },
19731
19912
  "run ended"
@@ -19773,55 +19954,6 @@ function abortPromise(signal) {
19773
19954
  signal.addEventListener("abort", () => resolve20(ABORTED), { once: true });
19774
19955
  });
19775
19956
  }
19776
- function pickAgentReport(agent) {
19777
- if (!agent) return {};
19778
- const picked = {};
19779
- if (agent.repositorySelection) picked.repositorySelection = agent.repositorySelection;
19780
- if (agent.verificationCommand && typeof agent.verificationCommand.command === "string" && agent.verificationCommand.command.trim() && typeof agent.verificationCommand.basis === "string" && agent.verificationCommand.basis.trim())
19781
- picked.verificationCommand = { command: agent.verificationCommand.command.trim().slice(0, 2e3), basis: agent.verificationCommand.basis.trim().slice(0, 2e3) };
19782
- const visualEvidence = runVisualEvidence.safeParse(agent.visualEvidence);
19783
- if (visualEvidence.success) picked.visualEvidence = visualEvidence.data;
19784
- const verdict = reviewVerdict.safeParse(agent.reviewVerdict);
19785
- if (verdict.success) picked.reviewVerdict = verdict.data;
19786
- if (typeof agent.summary === "string")
19787
- picked.summary = agent.summary.slice(0, 1e4);
19788
- if (Array.isArray(agent.openQuestions) && agent.openQuestions.every((q) => typeof q === "string"))
19789
- picked.openQuestions = agent.openQuestions.slice(0, 50).map((q) => q.slice(0, 2e3));
19790
- if (typeof agent.nextStep === "string")
19791
- picked.nextStep = agent.nextStep.slice(0, 2e3);
19792
- else if (agent.nextStep === null) picked.nextStep = null;
19793
- if (typeof agent.blockedOn === "string")
19794
- picked.blockedOn = agent.blockedOn.slice(0, 500);
19795
- const question = runQuestion.safeParse(agent.question);
19796
- if (question.success) picked.question = question.data;
19797
- if (agent.plan) picked.plan = agent.plan;
19798
- if (typeof agent.previewDatabaseBranch === "string" && agent.previewDatabaseBranch.trim())
19799
- picked.previewDatabaseBranch = agent.previewDatabaseBranch.trim().slice(0, 500);
19800
- if (Array.isArray(agent.criteria)) {
19801
- const criteria = [];
19802
- for (const entry of agent.criteria) {
19803
- if (criteria.length >= MAX_REPORTED_CRITERIA) break;
19804
- if (!entry || typeof entry !== "object") continue;
19805
- const { criterionId, text: text4, passed, status: status3, reason, resolution, evidence, command, exitCode } = entry;
19806
- if (!(typeof criterionId === "string" && UUID_RE.test(criterionId)) && !(typeof text4 === "string" && text4.trim()))
19807
- continue;
19808
- if (typeof passed !== "boolean") continue;
19809
- const criterion = runCriterion.safeParse({
19810
- ...typeof criterionId === "string" && UUID_RE.test(criterionId) ? { criterionId } : {},
19811
- ...typeof text4 === "string" && text4.trim() ? { text: text4.trim().slice(0, 2e3) } : {},
19812
- passed,
19813
- ...status3 !== void 0 ? { status: status3 } : {},
19814
- ...typeof reason === "string" && reason.trim() ? { reason: reason.trim().slice(0, 2e3) } : {},
19815
- ...typeof resolution === "string" && resolution.trim() ? { resolution: resolution.trim().slice(0, 2e3) } : {},
19816
- ...typeof command === "string" && command.trim() ? { command: command.trim().slice(0, 2e3), ...exitCode === null || typeof exitCode === "number" && Number.isSafeInteger(exitCode) ? { exitCode } : {} } : {},
19817
- ...typeof evidence === "string" ? { evidence: evidence.slice(0, 1e4) } : {}
19818
- });
19819
- if (criterion.success) criteria.push(criterion.data);
19820
- }
19821
- picked.criteria = criteria;
19822
- }
19823
- return picked;
19824
- }
19825
19957
  var KEEP_WORKTREE = ["turn_ended", "asked_human", "quota_exhausted", "provider_failure"];
19826
19958
  function startupProviderFailure(error) {
19827
19959
  for (let depth = 0; depth < 5 && error instanceof Error; depth++, error = error.cause) {
@@ -19837,50 +19969,6 @@ function stopReasonOf(event, run3, assignment) {
19837
19969
  if (event.outcome === "failed" && event.quota && quotaStopApplies(assignment)) return "quota_exhausted";
19838
19970
  return event.outcome === "failed" ? "error" : "turn_ended";
19839
19971
  }
19840
- async function unsandboxedVerify(run3) {
19841
- const result = await execa12(run3.command, {
19842
- shell: true,
19843
- cwd: run3.worktree,
19844
- env: buildChildEnv(),
19845
- extendEnv: false,
19846
- reject: false,
19847
- all: true,
19848
- stdin: "ignore",
19849
- timeout: run3.timeoutMs,
19850
- cancelSignal: run3.signal,
19851
- killDescendants: true
19852
- });
19853
- return {
19854
- exitCode: result.exitCode ?? null,
19855
- signal: result.signal ?? null,
19856
- timedOut: result.timedOut,
19857
- output: String(result.all ?? "")
19858
- };
19859
- }
19860
- function verifyFailure(command, result) {
19861
- const how = result.timedOut ? "timed out" : result.exitCode !== null ? `exited with code ${result.exitCode}` : result.signal ? `was killed by ${result.signal}` : "did not finish";
19862
- return `Submitted, but the verify command failed: \`${command}\` ${how}`;
19863
- }
19864
- function baseReport(summary = "") {
19865
- return emptyRunReport(summary.slice(0, 1e4));
19866
- }
19867
- function isReadOnlyTask(assignment) {
19868
- return runPolicy(assignment.policy).readOnly === true && assignment.kind !== "acceptance" && !assignment.benchmark;
19869
- }
19870
- function skillPromptOf(assignment) {
19871
- const skills = assignment.skills;
19872
- if (!skills?.length) return void 0;
19873
- const plan = skillPromptPlan(skills);
19874
- return {
19875
- budgetChars: plan.budgetChars,
19876
- usedChars: plan.usedChars,
19877
- inlined: plan.inlined.map((entry) => entry.name),
19878
- deferred: plan.degraded.map((entry) => entry.name)
19879
- };
19880
- }
19881
- function fixedCandidateCheck(assignment) {
19882
- return assignment.kind === "acceptance" && runPolicy(assignment.policy).readOnly === true && typeof assignment.baseBranch === "string" && /^[a-f0-9]{40}$/.test(assignment.baseBranch);
19883
- }
19884
19972
 
19885
19973
  // src/device-gateway.ts
19886
19974
  var DEVICE_GATEWAY_PING = "ping";
@@ -20086,10 +20174,10 @@ import { constants as constants7 } from "node:fs";
20086
20174
  import { open as open2, readFile as readFile6, realpath as realpath2 } from "node:fs/promises";
20087
20175
  import { execFile as execFile7 } from "node:child_process";
20088
20176
  import { promisify as promisify7 } from "node:util";
20089
- import { createHash as createHash14 } from "node:crypto";
20177
+ import { createHash as createHash15 } from "node:crypto";
20090
20178
  import { extname as extname2, resolve as resolve15 } from "node:path";
20091
20179
  var execute2 = promisify7(execFile7);
20092
- var hash = (value) => createHash14("sha256").update(value).digest("hex");
20180
+ var hash = (value) => createHash15("sha256").update(value).digest("hex");
20093
20181
  var denied = () => new CodingWorkspaceError("workspace_path_unavailable");
20094
20182
  function isFileReadRequest(request2) {
20095
20183
  return request2.kind === "file" || request2.kind === "tree" || request2.kind === "search" || request2.kind === "context";
@@ -20338,8 +20426,8 @@ async function readWorkspaceReceipt(command, entry) {
20338
20426
  // src/coding-workspace/diff.ts
20339
20427
  import { constants as constants8 } from "node:fs";
20340
20428
  import { open as open3, realpath as realpath3, mkdtemp as mkdtemp2, mkdir as mkdir5, writeFile as writeFile4, rm as rm4, lstat as lstat5 } from "node:fs/promises";
20341
- import { createHash as createHash15 } from "node:crypto";
20342
- import { resolve as resolve16, dirname as dirname16, join as join32, posix } from "node:path";
20429
+ import { createHash as createHash16 } from "node:crypto";
20430
+ import { resolve as resolve16, dirname as dirname16, join as join34, posix } from "node:path";
20343
20431
  import { tmpdir as tmpdir6 } from "node:os";
20344
20432
  import { execa as execa13 } from "execa";
20345
20433
 
@@ -20408,7 +20496,7 @@ var CRLFCleaner = class {
20408
20496
  };
20409
20497
 
20410
20498
  // src/coding-workspace/diff.ts
20411
- var digest7 = (value) => createHash15("sha256").update(value).digest("hex");
20499
+ var digest7 = (value) => createHash16("sha256").update(value).digest("hex");
20412
20500
  var fenceMode = (mode) => mode === "100644" || mode === "100755" || mode === "120000" || mode === "160000" ? mode : null;
20413
20501
  var oid2 = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/;
20414
20502
  var MAX_SCAN_BYTES = 64 * 1024 * 1024;
@@ -20517,12 +20605,12 @@ async function conversionSettings(git3) {
20517
20605
  const host = buildChildEnv({});
20518
20606
  const defaults = ["/etc/gitattributes", "/usr/etc/gitattributes", "/usr/local/etc/gitattributes"];
20519
20607
  if (!external) {
20520
- const configHome = host.XDG_CONFIG_HOME || (host.HOME ? join32(host.HOME, ".config") : void 0);
20521
- if (configHome) defaults.push(join32(configHome, "git", "attributes"));
20608
+ const configHome = host.XDG_CONFIG_HOME || (host.HOME ? join34(host.HOME, ".config") : void 0);
20609
+ if (configHome) defaults.push(join34(configHome, "git", "attributes"));
20522
20610
  }
20523
- const info = join32(git3.commonDir, "info");
20611
+ const info = join34(git3.commonDir, "info");
20524
20612
  if (await existsWithoutReading(info)) {
20525
- if (!(await lstat5(info)).isDirectory() || await existsWithoutReading(join32(info, "attributes")))
20613
+ if (!(await lstat5(info)).isDirectory() || await existsWithoutReading(join34(info, "attributes")))
20526
20614
  throw new CodingWorkspaceError("workspace_unsupported");
20527
20615
  }
20528
20616
  for (const path3 of defaults) if (await existsWithoutReading(path3)) throw new CodingWorkspaceError("workspace_unsupported");
@@ -20568,10 +20656,10 @@ async function workingConversion(git3, root, paths, head, signal, budget) {
20568
20656
  throw new CodingWorkspaceError("workspace_unsupported");
20569
20657
  attributeBytes.set(path3, bytes);
20570
20658
  }
20571
- const directory = await mkdtemp2(join32(tmpdir6(), "mikka-diff-attributes-"));
20659
+ const directory = await mkdtemp2(join34(tmpdir6(), "mikka-diff-attributes-"));
20572
20660
  const actions = /* @__PURE__ */ new Map();
20573
20661
  try {
20574
- const gitDir = join32(directory, "git"), worktree = join32(directory, "worktree");
20662
+ const gitDir = join34(directory, "git"), worktree = join34(directory, "worktree");
20575
20663
  await mkdir5(worktree, { mode: 448 });
20576
20664
  const env = {
20577
20665
  ...buildChildEnv({}),
@@ -20591,7 +20679,7 @@ async function workingConversion(git3, root, paths, head, signal, budget) {
20591
20679
  killDescendants: true
20592
20680
  });
20593
20681
  for (const [path3, bytes] of attributeBytes) {
20594
- const target = join32(worktree, path3);
20682
+ const target = join34(worktree, path3);
20595
20683
  await mkdir5(dirname16(target), { recursive: true, mode: 448 });
20596
20684
  await writeFile4(target, bytes, { mode: 384, flag: "wx" });
20597
20685
  }
@@ -20674,7 +20762,7 @@ async function currentFile(root, path3, head, budget, signal, conversion, git3)
20674
20762
  budget.bytes += size;
20675
20763
  if (budget.bytes > MAX_SCAN_BYTES) throw new CodingWorkspaceError("workspace_limit_exceeded");
20676
20764
  const algorithm = head.length === 64 ? "sha256" : "sha1";
20677
- const hasher = createHash15(algorithm).update(`blob ${size}\0`), stats = new GitTextStats();
20765
+ const hasher = createHash16(algorithm).update(`blob ${size}\0`), stats = new GitTextStats();
20678
20766
  const bytes = size <= WORKSPACE_DIFF_MAX_BLOB_BYTES ? Buffer.alloc(size) : null;
20679
20767
  const chunk = Buffer.alloc(64 * 1024);
20680
20768
  let offset = 0;
@@ -20714,7 +20802,7 @@ async function currentFile(root, path3, head, budget, signal, conversion, git3)
20714
20802
  let blob = rawBlob, cleanSize = size;
20715
20803
  if (normalize) {
20716
20804
  cleanSize -= stats.crlf;
20717
- const cleaned = createHash15(algorithm).update(`blob ${cleanSize}\0`), cleaner = new CRLFCleaner();
20805
+ const cleaned = createHash16(algorithm).update(`blob ${cleanSize}\0`), cleaner = new CRLFCleaner();
20718
20806
  if (bytes) cleaned.update(cleaner.push(bytes));
20719
20807
  else {
20720
20808
  budget.bytes += size;
@@ -20998,8 +21086,8 @@ async function readWorkspaceRevertPreview(command, entry, repoPath) {
20998
21086
  // src/coding-workspace/git.ts
20999
21087
  import { constants as constants9 } from "node:fs";
21000
21088
  import { lstat as lstat6, mkdtemp as mkdtemp3, open as open4, readFile as readFile7, realpath as realpath4, rm as rm5, unlink, writeFile as writeFile5 } from "node:fs/promises";
21001
- import { createHash as createHash16 } from "node:crypto";
21002
- import { join as join33, resolve as resolve17 } from "node:path";
21089
+ import { createHash as createHash17 } from "node:crypto";
21090
+ import { join as join35, resolve as resolve17 } from "node:path";
21003
21091
  import { tmpdir as tmpdir7 } from "node:os";
21004
21092
  import { execa as execa14 } from "execa";
21005
21093
 
@@ -21133,7 +21221,7 @@ function parseHistoryCursor(cursor, headSha2) {
21133
21221
  var historyCursor = (headSha2, offset) => `${headSha2}:${offset}`;
21134
21222
 
21135
21223
  // src/coding-workspace/git.ts
21136
- var digest8 = (value) => createHash16("sha256").update(value).digest("hex");
21224
+ var digest8 = (value) => createHash17("sha256").update(value).digest("hex");
21137
21225
  var oid4 = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/;
21138
21226
  var STATUS_BYTES = 8 * 1024 * 1024;
21139
21227
  var STATUS_SCAN_BYTES = 16 * 1024 * 1024;
@@ -21595,7 +21683,7 @@ function runGit(cwd, args, env, signal, maximum = 8 * 1024 * 1024) {
21595
21683
  }
21596
21684
  async function readTempFile(worktree, path3) {
21597
21685
  if (!visibleWorkspacePath(path3)) throw new CodingWorkspaceError("workspace_path_unavailable");
21598
- const full = join33(worktree, ...path3.split("/"));
21686
+ const full = join35(worktree, ...path3.split("/"));
21599
21687
  if (!full.startsWith(`${worktree}/`)) throw new CodingWorkspaceError("workspace_path_unavailable");
21600
21688
  try {
21601
21689
  const stat3 = await lstat6(full);
@@ -21616,8 +21704,8 @@ async function dryRunCheckpoint(git3, root, identity, statusBase, patchBase, pat
21616
21704
  } catch (error) {
21617
21705
  throw new CodingWorkspaceError("workspace_unsupported", { cause: error });
21618
21706
  }
21619
- const parent = await mkdtemp3(join33(tmpdir7(), "mikka-git-restore-"));
21620
- const worktree = join33(parent, "wt"), patchFile = join33(parent, "checkpoint.patch");
21707
+ const parent = await mkdtemp3(join35(tmpdir7(), "mikka-git-restore-"));
21708
+ const worktree = join35(parent, "wt"), patchFile = join35(parent, "checkpoint.patch");
21621
21709
  try {
21622
21710
  await writeFile5(patchFile, patch, { mode: 384 });
21623
21711
  await runGit(git3.commonDir, ["worktree", "add", "--detach", "--quiet", worktree, head], commonEnv(git3), signal);
@@ -21897,9 +21985,9 @@ async function handleWorkspaceGitRequest(command, entry, repoPath) {
21897
21985
  }
21898
21986
 
21899
21987
  // src/repositories.ts
21900
- import { createHash as createHash17, randomUUID as randomUUID7 } from "node:crypto";
21901
- import { existsSync as existsSync7, lstatSync as lstatSync12, mkdirSync as mkdirSync17, readdirSync as readdirSync9, realpathSync as realpathSync13, renameSync as renameSync5, rmSync as rmSync20 } from "node:fs";
21902
- import { dirname as dirname17, join as join34, resolve as resolve18 } from "node:path";
21988
+ import { createHash as createHash18, randomUUID as randomUUID7 } from "node:crypto";
21989
+ import { existsSync as existsSync8, lstatSync as lstatSync12, mkdirSync as mkdirSync17, readdirSync as readdirSync9, realpathSync as realpathSync13, renameSync as renameSync5, rmSync as rmSync20 } from "node:fs";
21990
+ import { dirname as dirname17, join as join36, resolve as resolve18 } from "node:path";
21903
21991
  import { setTimeout as delay } from "node:timers/promises";
21904
21992
  import { execa as execa15 } from "execa";
21905
21993
  import lockfile2 from "proper-lockfile";
@@ -21923,7 +22011,7 @@ var RepositoryCache = class {
21923
22011
  retainResources;
21924
22012
  pathFor(remoteUrl) {
21925
22013
  const { key: key2 } = normalizeRepository(remoteUrl, { allowFile: this.allowFile });
21926
- const path3 = resolve18(this.root, "v2", createHash17("sha256").update(key2).digest("hex"));
22014
+ const path3 = resolve18(this.root, "v2", createHash18("sha256").update(key2).digest("hex"));
21927
22015
  if (!isInside(resolve18(this.root), path3) || path3 === resolve18(this.root)) throw new Error("Invalid repository cache path");
21928
22016
  return path3;
21929
22017
  }
@@ -21959,7 +22047,7 @@ var RepositoryCache = class {
21959
22047
  return diagnostics.timer ? diagnostics.timer.measure(phase, traced) : traced();
21960
22048
  };
21961
22049
  let cloned = false;
21962
- if (!existsSync7(path3)) {
22050
+ if (!existsSync8(path3)) {
21963
22051
  const temporary = `${path3}.clone-${randomUUID7()}`;
21964
22052
  try {
21965
22053
  await git3(["clone", "--depth=50", "--no-single-branch", "--no-checkout", "--no-hardlinks", "--no-recurse-submodules", "--", remote, temporary]);
@@ -21971,7 +22059,7 @@ var RepositoryCache = class {
21971
22059
  } else {
21972
22060
  this.assertClone(path3);
21973
22061
  await git3(["remote", "set-url", "origin", remote], path3);
21974
- const depth = existsSync7(join34(path3, ".git", "shallow")) ? ["--depth=50"] : [];
22062
+ const depth = existsSync8(join36(path3, ".git", "shallow")) ? ["--depth=50"] : [];
21975
22063
  await git3(["fetch", ...depth, ...this.retainResources ? [] : ["--prune"], "--no-tags", "--no-recurse-submodules", "--no-write-fetch-head", "origin"], path3);
21976
22064
  }
21977
22065
  this.assertClone(path3);
@@ -22062,12 +22150,12 @@ var RepositoryCache = class {
22062
22150
  /** Cache paths for retention/orphan cleanup; never consult user checkouts. */
22063
22151
  paths() {
22064
22152
  const visit = (path3) => {
22065
- if (!existsSync7(path3) || lstatSync12(path3).isSymbolicLink()) return [];
22066
- if (existsSync7(join34(path3, ".git"))) {
22153
+ if (!existsSync8(path3) || lstatSync12(path3).isSymbolicLink()) return [];
22154
+ if (existsSync8(join36(path3, ".git"))) {
22067
22155
  this.assertClone(path3);
22068
22156
  return [path3];
22069
22157
  }
22070
- return readdirSync9(path3, { withFileTypes: true }).flatMap((entry) => entry.isDirectory() && !entry.name.endsWith(".lock") && !entry.name.includes(".clone-") ? visit(join34(path3, entry.name)) : []);
22158
+ return readdirSync9(path3, { withFileTypes: true }).flatMap((entry) => entry.isDirectory() && !entry.name.endsWith(".lock") && !entry.name.includes(".clone-") ? visit(join36(path3, entry.name)) : []);
22071
22159
  };
22072
22160
  return visit(resolve18(this.root));
22073
22161
  }
@@ -22077,14 +22165,14 @@ var RepositoryCache = class {
22077
22165
  const root = realpathSync13(this.root);
22078
22166
  let current = resolve18(this.root);
22079
22167
  for (const part of path3.slice(current.length + 1).split("/").filter(Boolean)) {
22080
- current = join34(current, part);
22081
- if (existsSync7(current) && lstatSync12(current).isSymbolicLink()) throw new Error("Repository cache contains a symlink");
22168
+ current = join36(current, part);
22169
+ if (existsSync8(current) && lstatSync12(current).isSymbolicLink()) throw new Error("Repository cache contains a symlink");
22082
22170
  mkdirSync17(current, { recursive: true, mode: 448 });
22083
22171
  if (!isInside(root, realpathSync13(current))) throw new Error("Repository cache escapes its directory");
22084
22172
  }
22085
22173
  }
22086
22174
  assertClone(path3) {
22087
- if (lstatSync12(path3).isSymbolicLink() || !lstatSync12(join34(path3, ".git")).isDirectory() || lstatSync12(join34(path3, ".git")).isSymbolicLink()) throw new Error("Repository cache is not a standard clone");
22175
+ if (lstatSync12(path3).isSymbolicLink() || !lstatSync12(join36(path3, ".git")).isDirectory() || lstatSync12(join36(path3, ".git")).isSymbolicLink()) throw new Error("Repository cache is not a standard clone");
22088
22176
  if (!isInside(realpathSync13(this.root), realpathSync13(path3))) throw new Error("Repository cache escapes its directory");
22089
22177
  }
22090
22178
  async lock(path3, signal) {
@@ -22189,12 +22277,12 @@ async function prepareRunRepository(repositories, privateDir, assignment, signal
22189
22277
  // src/subscription-hosted-runner.ts
22190
22278
  import { randomUUID as randomUUID8 } from "node:crypto";
22191
22279
  import { spawn as spawn5 } from "node:child_process";
22192
- import { existsSync as existsSync8, mkdirSync as mkdirSync18, realpathSync as realpathSync14 } from "node:fs";
22193
- import { dirname as dirname18, join as join35, resolve as resolve19 } from "node:path";
22280
+ import { existsSync as existsSync9, mkdirSync as mkdirSync18, realpathSync as realpathSync14 } from "node:fs";
22281
+ import { dirname as dirname18, join as join37, resolve as resolve19 } from "node:path";
22194
22282
  import { fileURLToPath } from "node:url";
22195
22283
 
22196
22284
  // src/official-cli-timing.ts
22197
- import { createHash as createHash18, randomBytes as randomBytes4 } from "node:crypto";
22285
+ import { createHash as createHash19, randomBytes as randomBytes4 } from "node:crypto";
22198
22286
  import { createServer as createServer4 } from "node:http";
22199
22287
 
22200
22288
  // src/mcp-http-timing.ts
@@ -22518,7 +22606,7 @@ var OfficialCliTimingCollector = class {
22518
22606
  };
22519
22607
  async function startCliTimingCollector({ runId, harness, remoteMcpServerCount, decisionCatalogue }) {
22520
22608
  const collector = new OfficialCliTimingCollector(runId, harness);
22521
- const expectedCatalogueSha256 = decisionCatalogue ? createHash18("sha256").update(JSON.stringify(decisionCatalogue)).digest("hex") : null;
22609
+ const expectedCatalogueSha256 = decisionCatalogue ? createHash19("sha256").update(JSON.stringify(decisionCatalogue)).digest("hex") : null;
22522
22610
  const mcpCollector = new McpHttpTimingCollector(runId, harness, remoteMcpServerCount, Date.now, expectedCatalogueSha256);
22523
22611
  const path3 = `/v1/logs/${randomBytes4(16).toString("hex")}`;
22524
22612
  const mcpPath = `/v1/mcp-http/${randomBytes4(16).toString("hex")}`;
@@ -22825,7 +22913,7 @@ async function createHostedBotRunner(host) {
22825
22913
  });
22826
22914
  Object.assign(env, github.env);
22827
22915
  }
22828
- const ledger = join35(host.stateDir, "native-ledgers", assignment.runId + ".json");
22916
+ const ledger = join37(host.stateDir, "native-ledgers", assignment.runId + ".json");
22829
22917
  const scope = selected && subscription ? {
22830
22918
  runId: assignment.runId,
22831
22919
  bindingId: selected.bindingId,
@@ -22837,12 +22925,12 @@ async function createHostedBotRunner(host) {
22837
22925
  accountId: subscription.first.accountId,
22838
22926
  modelId: subscription.first.modelId
22839
22927
  } : void 0;
22840
- if (continuation && existsSync8(ledger)) throw unavailable5("ledger_mismatch");
22841
- const previousLedger = continuation ? join35(host.stateDir, "native-ledgers", continuation.runId + ".json") : ledger;
22928
+ if (continuation && existsSync9(ledger)) throw unavailable5("ledger_mismatch");
22929
+ const previousLedger = continuation ? join37(host.stateDir, "native-ledgers", continuation.runId + ".json") : ledger;
22842
22930
  const previous = scope ? readJson(previousLedger) : void 0;
22843
22931
  if (preparation && previous) throw unavailable5("ledger_mismatch");
22844
22932
  const expectedScope = scope && continuation ? { ...scope, runId: continuation.runId } : scope;
22845
- if (scope && (existsSync8(previousLedger) && (!previous || JSON.stringify(previous.scope) !== JSON.stringify(expectedScope) || typeof previous.sessionId !== "string") || assignment.requireSessionResume && (!previous || previous.sessionId !== assignment.resumeSessionId))) throw unavailable5("ledger_mismatch");
22933
+ if (scope && (existsSync9(previousLedger) && (!previous || JSON.stringify(previous.scope) !== JSON.stringify(expectedScope) || typeof previous.sessionId !== "string") || assignment.requireSessionResume && (!previous || previous.sessionId !== assignment.resumeSessionId))) throw unavailable5("ledger_mismatch");
22846
22934
  if (scope) mkdirSync18(dirname18(ledger), { recursive: true, mode: 448 });
22847
22935
  const record3 = async (sessionId) => {
22848
22936
  assertOpen();
@@ -23104,7 +23192,7 @@ async function createHostedBotRunner(host) {
23104
23192
  import {
23105
23193
  randomBytes as randomBytes5,
23106
23194
  randomUUID as randomUUID9,
23107
- createHash as createHash20,
23195
+ createHash as createHash21,
23108
23196
  timingSafeEqual as timingSafeEqual2
23109
23197
  } from "node:crypto";
23110
23198
  import { chmodSync as chmodSync2 } from "node:fs";
@@ -23114,7 +23202,7 @@ import { createServer as createServer5 } from "node:net";
23114
23202
  import { spawn as spawn6 } from "node:child_process";
23115
23203
  import { execFile as execFile8 } from "node:child_process";
23116
23204
  import { promisify as promisify8 } from "node:util";
23117
- import { createHash as createHash19 } from "node:crypto";
23205
+ import { createHash as createHash20 } from "node:crypto";
23118
23206
  import { readFile as readFile8, realpath as realpath5 } from "node:fs/promises";
23119
23207
  import { createInterface } from "node:readline";
23120
23208
  var exec3 = promisify8(execFile8);
@@ -23131,7 +23219,7 @@ async function detectComputerDriver(binary = "cua-driver") {
23131
23219
  installed: true,
23132
23220
  version,
23133
23221
  path: path3,
23134
- fingerprint: createHash19("sha256").update(await readFile8(path3)).digest("hex")
23222
+ fingerprint: createHash20("sha256").update(await readFile8(path3)).digest("hex")
23135
23223
  };
23136
23224
  } catch {
23137
23225
  return null;
@@ -23198,7 +23286,7 @@ async function executeDriver(driver, input, display, leaseGuard, assertLive = ()
23198
23286
  if (display !== void 0 && !/^:[1-9][0-9]{0,3}$/.test(display))
23199
23287
  throw new Error("Invalid desktop display");
23200
23288
  const call = normalizeCall(input);
23201
- const fingerprint2 = createHash19("sha256").update(await readFile8(driver.path)).digest("hex");
23289
+ const fingerprint2 = createHash20("sha256").update(await readFile8(driver.path)).digest("hex");
23202
23290
  if (fingerprint2 !== driver.fingerprint)
23203
23291
  throw new Error("Driver changed; restart and approve a new request");
23204
23292
  const args = driverArguments(call);
@@ -23493,7 +23581,7 @@ var ComputerBroker = class {
23493
23581
  call,
23494
23582
  expiresAt: this.now() + this.ttl
23495
23583
  };
23496
- const digest9 = createHash20("sha256").update(JSON.stringify(request2)).digest("hex");
23584
+ const digest9 = createHash21("sha256").update(JSON.stringify(request2)).digest("hex");
23497
23585
  return new Promise((resolve20, reject) => {
23498
23586
  const timer = setTimeout(() => {
23499
23587
  this.pending.delete(request2.id);
@@ -23610,10 +23698,10 @@ var ComputerBroker = class {
23610
23698
  };
23611
23699
 
23612
23700
  // src/computer/credential-executor.ts
23613
- import { createHash as createHash21 } from "node:crypto";
23701
+ import { createHash as createHash22 } from "node:crypto";
23614
23702
  function credentialAwareExecutor(deps) {
23615
23703
  return async (driver, call, display, runId, context) => {
23616
- const digest9 = createHash21("sha256").update(JSON.stringify(call)).digest("hex");
23704
+ const digest9 = createHash22("sha256").update(JSON.stringify(call)).digest("hex");
23617
23705
  const resolved = await deps.consumeMatchingIntent(runId, context.actionId, digest9);
23618
23706
  context.assertLive();
23619
23707
  if (resolved.kind === "ordinary") return deps.executeOrdinary(driver, call, display, runId, context.assertLive);
@@ -23895,7 +23983,7 @@ var Daemon = class {
23895
23983
  if (this.options.credential)
23896
23984
  this.saveDevice({ credential: this.options.credential });
23897
23985
  this.journal = new RunJournal(paths.journal);
23898
- this.captureUploader = new CaptureUploader((runId) => join36(runPaths(paths.adapterState, runId).runDir, CAPTURES_DIR), this.options.link, this.log, join36(paths.dataDir, "capture-pending"));
23986
+ this.captureUploader = new CaptureUploader((runId) => join38(runPaths(paths.adapterState, runId).runDir, CAPTURES_DIR), this.options.link, this.log, join38(paths.dataDir, "capture-pending"));
23899
23987
  this.outbox = new Outbox(
23900
23988
  paths.outbox,
23901
23989
  this.options.link,
@@ -23914,7 +24002,7 @@ var Daemon = class {
23914
24002
  if (this.localComputerDriver && this.options.link.syncComputerReviews) {
23915
24003
  this.localComputerBroker = new ComputerBroker({
23916
24004
  driver: this.localComputerDriver,
23917
- socketPath: join36(paths.dataDir, "local-computer.sock"),
24005
+ socketPath: join38(paths.dataDir, "local-computer.sock"),
23918
24006
  transport: "tcp",
23919
24007
  needsPerson: this.computerNeedsPerson(),
23920
24008
  permitted: (runId) => {
@@ -23957,7 +24045,7 @@ var Daemon = class {
23957
24045
  };
23958
24046
  this.cloudComputerBroker = new ComputerBroker({
23959
24047
  driver,
23960
- socketPath: join36(paths.dataDir, "computer.sock"),
24048
+ socketPath: join38(paths.dataDir, "computer.sock"),
23961
24049
  needsPerson: this.computerNeedsPerson(),
23962
24050
  permitted: (runId) => {
23963
24051
  const entry = this.journal.get(runId);
@@ -24052,7 +24140,7 @@ var Daemon = class {
24052
24140
  prepareRunDrive: this.options.link.prepareRunDrive?.bind(this.options.link),
24053
24141
  prepareRunToolApproval: this.options.link.prepareRunToolApproval?.bind(this.options.link),
24054
24142
  prepareRunGitHub: hosted ? void 0 : (assignment, signal, onCredential) => prepareLocalGitHub(assignment, {
24055
- stateDir: join36(this.paths.adapterState, "github"),
24143
+ stateDir: join38(this.paths.adapterState, "github"),
24056
24144
  link: this.options.link,
24057
24145
  signal,
24058
24146
  onCredential,
@@ -24122,7 +24210,7 @@ var Daemon = class {
24122
24210
  worktree,
24123
24211
  tree,
24124
24212
  github: { ...assignment.github, runToken: assignment.mcp?.token, issueId: assignment.issueId },
24125
- privateDir: join36(paths.adapterState, "pids"),
24213
+ privateDir: join38(paths.adapterState, "pids"),
24126
24214
  ...hosted ? { hosted: true } : {},
24127
24215
  env: hosted ? process.env : githubReceiptEnvironment(),
24128
24216
  githubEnvironment,
@@ -24837,11 +24925,11 @@ var Daemon = class {
24837
24925
  return runVerify(sandbox, {
24838
24926
  command,
24839
24927
  worktree: realpathSync15(worktree),
24840
- tmpRoot: join36(this.paths.adapterState, "verify", runId),
24928
+ tmpRoot: join38(this.paths.adapterState, "verify", runId),
24841
24929
  privateDir: paths.privateDir,
24842
24930
  pidFile: paths.pidFile.replace(/\.pgid$/, ".verify.pgid"),
24843
24931
  networkAllow: repo.networkAllow,
24844
- env: { ...buildChildEnv(), ...githubEnvironment, MIKKA_HANDOFF_FILE: join36(paths.runDir, "handoff.json") },
24932
+ env: { ...buildChildEnv(), ...githubEnvironment, MIKKA_HANDOFF_FILE: join38(paths.runDir, "handoff.json") },
24845
24933
  timeoutMs,
24846
24934
  signal,
24847
24935
  readOnly
@@ -24916,7 +25004,7 @@ var Daemon = class {
24916
25004
  void this.stop().finally(() => this.options.onLockLost?.(error));
24917
25005
  }
24918
25006
  ensureSecret() {
24919
- if (existsSync9(this.paths.secret)) {
25007
+ if (existsSync10(this.paths.secret)) {
24920
25008
  return readFileSync15(this.paths.secret, "utf8").trim();
24921
25009
  }
24922
25010
  const secret = randomBytes6(32).toString("hex");
@@ -25396,7 +25484,7 @@ var Daemon = class {
25396
25484
  });
25397
25485
  }
25398
25486
  get updateStateFile() {
25399
- return join36(this.paths.dataDir, "auto-update.json");
25487
+ return join38(this.paths.dataDir, "auto-update.json");
25400
25488
  }
25401
25489
  /** A server named this release (a report answer, a commands read, a 426), or npm did for a refused daemon. */
25402
25490
  learnRelease(latest) {
@@ -25758,6 +25846,7 @@ async function runCli(argv, io = defaultIO, privateConfig) {
25758
25846
  dir: daemonPaths(dataDir).logs,
25759
25847
  stdout: flavor === "dev"
25760
25848
  });
25849
+ let lifecycle;
25761
25850
  const speed = values["mock-speed"] ? Number(values["mock-speed"]) : void 0;
25762
25851
  try {
25763
25852
  const daemon = await startDaemon({
@@ -25781,17 +25870,23 @@ async function runCli(argv, io = defaultIO, privateConfig) {
25781
25870
  e2bContainerRuntime: values["e2b-container-runtime"],
25782
25871
  cloudComputer: values["e2b-computer"],
25783
25872
  stallMs: values["stall-minutes"] ? Number(values["stall-minutes"]) * 6e4 : void 0,
25784
- onDrained: () => process.exit(0),
25785
- onLockLost: () => process.exit(1)
25873
+ onDrained: () => {
25874
+ lifecycle?.stopping("drained");
25875
+ process.exit(0);
25876
+ },
25877
+ onLockLost: () => {
25878
+ lifecycle?.disown();
25879
+ process.exit(1);
25880
+ }
25786
25881
  });
25787
- const shutdown = () => {
25788
- void daemon.stop().then(() => process.exit(0));
25882
+ lifecycle = trackDaemonLifecycle(daemonPaths(dataDir).logs);
25883
+ const shutdown = (signal, code) => {
25884
+ lifecycle?.stopping(`signal:${signal}`);
25885
+ void daemon.stop().then(() => process.exit(code));
25789
25886
  };
25790
- process.once("SIGUSR2", () => {
25791
- void daemon.stop().then(() => process.exit(1));
25792
- });
25793
- process.once("SIGINT", shutdown);
25794
- process.once("SIGTERM", shutdown);
25887
+ process.once("SIGUSR2", () => shutdown("SIGUSR2", 1));
25888
+ process.once("SIGINT", () => shutdown("SIGINT", 0));
25889
+ process.once("SIGTERM", () => shutdown("SIGTERM", 0));
25795
25890
  return null;
25796
25891
  } catch (error) {
25797
25892
  if (error instanceof DaemonAlreadyRunningError) {