@evident-ai/cli 3.5.2-dev.dc42196 → 3.5.2-dev.e19e5d4

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/dist/index.js CHANGED
@@ -315,14 +315,14 @@ function blank() {
315
315
  console.log();
316
316
  }
317
317
  function waitForEnter(prompt = "Press Enter to continue...") {
318
- return new Promise((resolve4) => {
318
+ return new Promise((resolve5) => {
319
319
  process.stdout.write(chalk.dim(prompt));
320
320
  const handler = () => {
321
321
  process.stdin.removeListener("data", handler);
322
322
  process.stdin.setRawMode?.(false);
323
323
  process.stdin.pause();
324
324
  console.log();
325
- resolve4();
325
+ resolve5();
326
326
  };
327
327
  if (process.stdin.isTTY) {
328
328
  process.stdin.setRawMode?.(true);
@@ -332,7 +332,7 @@ function waitForEnter(prompt = "Press Enter to continue...") {
332
332
  });
333
333
  }
334
334
  function sleep(ms) {
335
- return new Promise((resolve4) => setTimeout(resolve4, ms));
335
+ return new Promise((resolve5) => setTimeout(resolve5, ms));
336
336
  }
337
337
 
338
338
  // src/commands/login.ts
@@ -410,19 +410,19 @@ async function tokenLogin() {
410
410
  );
411
411
  blank();
412
412
  process.stdout.write("Paste token: ");
413
- const token = await new Promise((resolve4) => {
413
+ const token = await new Promise((resolve5) => {
414
414
  let data = "";
415
415
  process.stdin.setEncoding("utf8");
416
416
  process.stdin.on("data", (chunk) => {
417
417
  data += chunk;
418
418
  });
419
419
  process.stdin.on("end", () => {
420
- resolve4(data.trim());
420
+ resolve5(data.trim());
421
421
  });
422
422
  if (process.stdin.isTTY) {
423
423
  process.stdin.once("data", (chunk) => {
424
424
  process.stdin.pause();
425
- resolve4(chunk.toString().trim());
425
+ resolve5(chunk.toString().trim());
426
426
  });
427
427
  process.stdin.resume();
428
428
  }
@@ -1158,7 +1158,7 @@ async function claudeUsage() {
1158
1158
  // src/commands/run.ts
1159
1159
  import { chmodSync as chmodSync3, existsSync as existsSync3, readFileSync as readFileSync7, writeFileSync as writeFileSync6 } from "node:fs";
1160
1160
  import { homedir as homedir7 } from "node:os";
1161
- import { isAbsolute as isAbsolute3, join as join11, parse, resolve as resolvePath2 } from "node:path";
1161
+ import { isAbsolute as isAbsolute4, join as join12, parse, resolve as resolvePath2 } from "node:path";
1162
1162
  import chalk7 from "chalk";
1163
1163
 
1164
1164
  // ../../packages/types/src/agents/index.ts
@@ -1293,7 +1293,11 @@ var FORWARD_FAILURE_REASON_HEADER = "X-Evident-Failure-Reason";
1293
1293
  function log(level, event, fields) {
1294
1294
  const method = level === "debug" ? "log" : level;
1295
1295
  try {
1296
- console[method]("[evident]", JSON.stringify({ level, event, ...fields }));
1296
+ const payload = Object.fromEntries(
1297
+ Object.entries({ level, event, ...fields }).filter(([, value]) => value !== void 0)
1298
+ );
1299
+ const secondArgument = globalThis.navigator?.userAgent === "Cloudflare-Workers" ? payload : JSON.stringify(payload);
1300
+ console[method]("[evident]", secondArgument);
1297
1301
  } catch (err) {
1298
1302
  console.error(
1299
1303
  "[evident] log_serialize_failed",
@@ -1322,7 +1326,7 @@ import ora4 from "ora";
1322
1326
  import { select as select4 } from "@inquirer/prompts";
1323
1327
 
1324
1328
  // src/lib/telemetry.ts
1325
- var CLI_VERSION = (true ? "3.5.2-dev.dc42196" : void 0) ?? process.env.npm_package_version ?? "unknown";
1329
+ var CLI_VERSION = (true ? "3.5.2-dev.e19e5d4" : void 0) ?? process.env.npm_package_version ?? "unknown";
1326
1330
  function getCliVersion() {
1327
1331
  return CLI_VERSION;
1328
1332
  }
@@ -1515,9 +1519,10 @@ function redactDiagnosticText(message) {
1515
1519
  }
1516
1520
 
1517
1521
  // src/lib/opencode/session-db-reclaim.ts
1518
- var SESSION_DB_RECLAIM_CHUNK_PAGES = 2e3;
1522
+ var SESSION_DB_RECLAIM_CHUNK_PAGES = 100;
1519
1523
  var SESSION_DB_RECLAIM_TIME_BUDGET_MS = 500;
1520
1524
  var SESSION_DB_RECLAIM_PAGE_CEILING = 4e4;
1525
+ var SESSION_DB_RECLAIM_BUSY_TIMEOUT_MS = 5e3;
1521
1526
  function errorMessage(error2) {
1522
1527
  if (!(error2 instanceof Error)) return String(error2);
1523
1528
  return error2.cause instanceof Error ? error2.cause.message : error2.message;
@@ -1642,6 +1647,7 @@ function readFreelistCount(db) {
1642
1647
  return db.prepare("PRAGMA freelist_count").get().freelist_count;
1643
1648
  }
1644
1649
  function readCheckpointResult(db) {
1650
+ db.exec("PRAGMA busy_timeout=0");
1645
1651
  const row = db.prepare("PRAGMA wal_checkpoint(TRUNCATE)").get();
1646
1652
  return { busy: row.busy !== 0, log: row.log, checkpointed: row.checkpointed };
1647
1653
  }
@@ -1659,7 +1665,7 @@ async function probeReclaimAvailability(input) {
1659
1665
  try {
1660
1666
  const db = new sqlite.DatabaseSync(dbPath, { readOnly: true });
1661
1667
  try {
1662
- db.exec("PRAGMA busy_timeout=5000");
1668
+ db.exec(`PRAGMA busy_timeout=${SESSION_DB_RECLAIM_BUSY_TIMEOUT_MS}`);
1663
1669
  autoVacuum = db.prepare("PRAGMA auto_vacuum").get().auto_vacuum;
1664
1670
  } finally {
1665
1671
  db.close();
@@ -1679,7 +1685,8 @@ async function reclaimSessionDbSpace(input) {
1679
1685
  timeBudgetMs = SESSION_DB_RECLAIM_TIME_BUDGET_MS,
1680
1686
  chunkPages = SESSION_DB_RECLAIM_CHUNK_PAGES,
1681
1687
  now = () => performance.now(),
1682
- allowFullVacuum = true
1688
+ hasLiveTurn = false,
1689
+ hasProvenanceAnomaly = false
1683
1690
  } = input;
1684
1691
  let sqlite;
1685
1692
  try {
@@ -1695,17 +1702,19 @@ async function reclaimSessionDbSpace(input) {
1695
1702
  let db;
1696
1703
  try {
1697
1704
  db = new DatabaseSync(dbPath);
1698
- db.exec("PRAGMA busy_timeout=5000");
1705
+ db.exec(`PRAGMA busy_timeout=${SESSION_DB_RECLAIM_BUSY_TIMEOUT_MS}`);
1699
1706
  const autoVacuum = db.prepare("PRAGMA auto_vacuum").get().auto_vacuum;
1700
1707
  if (autoVacuum === 0) {
1701
- if (!allowFullVacuum) {
1702
- console.warn(
1703
- `[reclaimSessionDbSpace] skipping VACUUM conversion of ${dbPath}: a session turn is live`
1704
- );
1708
+ if (hasLiveTurn || hasProvenanceAnomaly) {
1709
+ const detail = [
1710
+ ...hasLiveTurn ? ["a session turn is live"] : [],
1711
+ ...hasProvenanceAnomaly ? ["session-DB provenance is anomalous"] : []
1712
+ ].join(" and ");
1713
+ console.warn(`[reclaimSessionDbSpace] skipping VACUUM conversion of ${dbPath}: ${detail}`);
1705
1714
  return {
1706
1715
  ok: false,
1707
1716
  skipped: "full-vacuum-blocked",
1708
- detail: "a session turn is live"
1717
+ detail
1709
1718
  };
1710
1719
  }
1711
1720
  const fileBytesForGuard = statSync2(dbPath).size;
@@ -1723,7 +1732,9 @@ async function reclaimSessionDbSpace(input) {
1723
1732
  db.exec("VACUUM");
1724
1733
  const afterBytes = readLogicalBytes(db);
1725
1734
  const freelistAfter = readFreelistCount(db);
1735
+ const checkpointStartedAt = now();
1726
1736
  const checkpoint = readCheckpointResult(db);
1737
+ const checkpointElapsedMs = Math.max(0, now() - checkpointStartedAt);
1727
1738
  return {
1728
1739
  ok: true,
1729
1740
  mode: "convert",
@@ -1734,10 +1745,18 @@ async function reclaimSessionDbSpace(input) {
1734
1745
  pagesReclaimed: Math.max(0, freelistBefore - freelistAfter),
1735
1746
  stoppedBy: "freelist-drained",
1736
1747
  elapsedMs: Math.max(0, now() - startedAt),
1748
+ checkpointElapsedMs,
1737
1749
  checkpoint
1738
1750
  };
1739
1751
  }
1740
1752
  if (autoVacuum === 2) {
1753
+ if (hasLiveTurn) {
1754
+ const detail = "a session turn is live";
1755
+ console.warn(
1756
+ `[reclaimSessionDbSpace] skipping incremental reclaim of ${dbPath}: ${detail}`
1757
+ );
1758
+ return { ok: false, skipped: "live-turn", detail };
1759
+ }
1741
1760
  const beforeBytes = readLogicalBytes(db);
1742
1761
  const freelistBefore = readFreelistCount(db);
1743
1762
  const startedAt = now();
@@ -1762,7 +1781,9 @@ async function reclaimSessionDbSpace(input) {
1762
1781
  freelistAfter = readFreelistCount(db);
1763
1782
  }
1764
1783
  const afterBytes = readLogicalBytes(db);
1784
+ const checkpointStartedAt = now();
1765
1785
  const checkpoint = readCheckpointResult(db);
1786
+ const checkpointElapsedMs = Math.max(0, now() - checkpointStartedAt);
1766
1787
  return {
1767
1788
  ok: true,
1768
1789
  mode: "incremental",
@@ -1773,6 +1794,7 @@ async function reclaimSessionDbSpace(input) {
1773
1794
  pagesReclaimed: Math.max(0, freelistBefore - freelistAfter),
1774
1795
  stoppedBy,
1775
1796
  elapsedMs: Math.max(0, now() - startedAt),
1797
+ checkpointElapsedMs,
1776
1798
  checkpoint
1777
1799
  };
1778
1800
  }
@@ -1792,6 +1814,263 @@ async function reclaimSessionDbSpace(input) {
1792
1814
  }
1793
1815
  }
1794
1816
 
1817
+ // src/lib/opencode/dependency-install-diagnostic.ts
1818
+ import { lstatSync, realpathSync } from "node:fs";
1819
+ import { basename, dirname as dirname3, isAbsolute, join as join2, relative, resolve, sep } from "node:path";
1820
+ var DEPENDENCY_INSTALL_FAILURE_MESSAGE = "background dependency install failed";
1821
+ var MAX_DISTINCT_DIAGNOSTICS = 32;
1822
+ var EFFECT = "OpenCode could not install background dependencies for this scope; its plugins and tools may be unavailable";
1823
+ function readOpenCodeLogField(line, key) {
1824
+ const match = line.match(new RegExp(`(?:^|\\s)${key}=(?:"((?:\\\\.|[^"])*)"|(\\S+))`));
1825
+ if (!match) return void 0;
1826
+ if (match[1] === void 0) return match[2];
1827
+ return match[1].replace(/\\(["\\n])/g, (_match, escaped) => {
1828
+ return escaped === "n" ? "\n" : escaped;
1829
+ });
1830
+ }
1831
+ function parseTrigger(line) {
1832
+ if (readOpenCodeLogField(line, "message") !== DEPENDENCY_INSTALL_FAILURE_MESSAGE) {
1833
+ return null;
1834
+ }
1835
+ const error2 = readOpenCodeLogField(line, "error");
1836
+ if (!error2 || !/\bEACCES\b/.test(error2)) return null;
1837
+ const errnoMatch = error2.match(/\bEACCES:\s*permission denied,\s*([a-z_]+)\s+'([^']*)'/);
1838
+ const capturedPath = errnoMatch?.[2];
1839
+ return {
1840
+ dir: readOpenCodeLogField(line, "dir"),
1841
+ op: errnoMatch?.[1],
1842
+ path: capturedPath && isAbsolute(capturedPath) ? capturedPath : void 0
1843
+ };
1844
+ }
1845
+ function getErrorCode(error2) {
1846
+ if (typeof error2 === "object" && error2 !== null && "code" in error2) {
1847
+ const code = error2.code;
1848
+ if (typeof code === "string") return code;
1849
+ }
1850
+ return "UNKNOWN";
1851
+ }
1852
+ function isWithin(path, root) {
1853
+ const candidate = resolve(path);
1854
+ const resolvedRoot = resolve(root);
1855
+ return candidate === resolvedRoot || candidate.startsWith(`${resolvedRoot}${sep}`);
1856
+ }
1857
+ function rootSpecs(context) {
1858
+ return [
1859
+ { token: "~", configured: resolve(context.homeDir) },
1860
+ { token: "$WORKSPACE", configured: resolve(context.cwd) }
1861
+ ];
1862
+ }
1863
+ function resolveRoots(context) {
1864
+ const resolved = [];
1865
+ const unresolved = [];
1866
+ for (const spec of rootSpecs(context)) {
1867
+ try {
1868
+ resolved.push({ ...spec, real: realpathSync(spec.configured) });
1869
+ } catch (_error) {
1870
+ unresolved.push(spec);
1871
+ }
1872
+ }
1873
+ return { resolved, unresolved };
1874
+ }
1875
+ function resolveNearestAncestor(failingPath, remaining, error2) {
1876
+ let ancestor = dirname3(failingPath);
1877
+ const suffix = [basename(failingPath), ...remaining];
1878
+ while (ancestor) {
1879
+ try {
1880
+ return {
1881
+ path: resolve(realpathSync(ancestor), ...suffix),
1882
+ failure: { path: resolve(failingPath), error: error2 }
1883
+ };
1884
+ } catch (ancestorError) {
1885
+ if (ancestor === dirname3(ancestor) || !getErrorCode(ancestorError).startsWith("E")) {
1886
+ return null;
1887
+ }
1888
+ suffix.unshift(basename(ancestor));
1889
+ ancestor = dirname3(ancestor);
1890
+ }
1891
+ }
1892
+ return null;
1893
+ }
1894
+ function resolveExistingPath(absolutePath) {
1895
+ if (!isAbsolute(absolutePath)) return null;
1896
+ const candidate = resolve(absolutePath);
1897
+ const remaining = [];
1898
+ let current = candidate;
1899
+ while (current) {
1900
+ try {
1901
+ const stat2 = lstatSync(current);
1902
+ if (stat2.isSymbolicLink()) {
1903
+ if (remaining.length === 0) {
1904
+ return { path: join2(realpathSync(dirname3(current)), basename(current)) };
1905
+ }
1906
+ return { path: resolve(realpathSync(current), ...remaining) };
1907
+ }
1908
+ return { path: resolve(realpathSync(current), ...remaining) };
1909
+ } catch (error2) {
1910
+ const code = getErrorCode(error2);
1911
+ if (code !== "ENOENT" && code !== "ENOTDIR") {
1912
+ return resolveNearestAncestor(current, remaining, error2);
1913
+ }
1914
+ }
1915
+ if (current === dirname3(current)) return null;
1916
+ remaining.unshift(basename(current));
1917
+ current = dirname3(current);
1918
+ }
1919
+ return null;
1920
+ }
1921
+ function tokenise(absolutePath, roots) {
1922
+ const pathResolution = resolveExistingPath(absolutePath);
1923
+ if (!pathResolution) return null;
1924
+ const root = roots.reduce((selected, candidate) => {
1925
+ if (!isWithin(pathResolution.path, candidate.real)) return selected;
1926
+ if (!selected || candidate.real.length > selected.real.length || candidate.real.length === selected.real.length && candidate.token === "$WORKSPACE") {
1927
+ return candidate;
1928
+ }
1929
+ return selected;
1930
+ }, null);
1931
+ if (!root) return null;
1932
+ const suffix = relative(root.real, pathResolution.path);
1933
+ return {
1934
+ value: suffix ? `${root.token}/${suffix.split(sep).join("/")}` : root.token,
1935
+ root,
1936
+ resolutionFailure: pathResolution.failure
1937
+ };
1938
+ }
1939
+ function classifyScope(dir, roots) {
1940
+ if (!dir) return "other";
1941
+ const tokenisedDir = tokenise(dir, roots.resolved);
1942
+ if (tokenisedDir) return tokenisedDir.root.token === "$WORKSPACE" ? "workspace" : "global";
1943
+ for (const spec of roots.unresolved) {
1944
+ if (isWithin(dir, spec.configured)) {
1945
+ return spec.token === "$WORKSPACE" ? "workspace" : "global";
1946
+ }
1947
+ }
1948
+ return "other";
1949
+ }
1950
+ function unresolvedRootForPath(path, unresolved) {
1951
+ return unresolved.find((spec) => isWithin(path, spec.configured));
1952
+ }
1953
+ function statType(stat2) {
1954
+ if (stat2.isDirectory()) return "d";
1955
+ if (stat2.isFile()) return "f";
1956
+ if (stat2.isSymbolicLink()) return "l";
1957
+ return "o";
1958
+ }
1959
+ function renderStat(name, stat2) {
1960
+ const mode = (stat2.mode & 4095).toString(8).padStart(4, "0");
1961
+ return `${name}:${statType(stat2)}:${stat2.uid}:${stat2.gid}:${mode}`;
1962
+ }
1963
+ function renderStatError(name, error2) {
1964
+ const code = getErrorCode(error2);
1965
+ return `${name}:${renderErrorCode(code)}`;
1966
+ }
1967
+ function renderErrorCode(code) {
1968
+ if (code === "ENOENT") return "missing";
1969
+ return code.startsWith("E") ? code : `E${code}`;
1970
+ }
1971
+ function inspectChain(rootReal, rootToken, absolutePath, resolutionFailure) {
1972
+ const target = resolve(absolutePath);
1973
+ const relativePath = relative(rootReal, target);
1974
+ const components = relativePath ? relativePath.split(sep) : [];
1975
+ const entries = [];
1976
+ let current = rootReal;
1977
+ let status2 = "complete";
1978
+ let finalStat;
1979
+ for (const name of [rootToken, ...components]) {
1980
+ if (name !== rootToken) current = join2(current, name);
1981
+ if (resolutionFailure && resolve(current) === resolve(resolutionFailure.path)) {
1982
+ entries.push(renderStatError(name, resolutionFailure.error));
1983
+ status2 = "stat_failed";
1984
+ break;
1985
+ }
1986
+ try {
1987
+ const stat2 = lstatSync(current);
1988
+ entries.push(renderStat(name, stat2));
1989
+ finalStat = stat2;
1990
+ } catch (error2) {
1991
+ entries.push(renderStatError(name, error2));
1992
+ if (getErrorCode(error2) !== "ENOENT") status2 = "stat_failed";
1993
+ break;
1994
+ }
1995
+ }
1996
+ let symlinkTarget;
1997
+ let symlinkMeta;
1998
+ if (finalStat?.isSymbolicLink() && entries.length === components.length + 1) {
1999
+ try {
2000
+ symlinkTarget = realpathSync(current);
2001
+ try {
2002
+ symlinkMeta = renderStat("", lstatSync(symlinkTarget)).slice(1);
2003
+ } catch (error2) {
2004
+ symlinkMeta = renderErrorCode(getErrorCode(error2));
2005
+ status2 = "stat_failed";
2006
+ }
2007
+ } catch (error2) {
2008
+ symlinkTarget = "<unresolved>";
2009
+ symlinkMeta = renderErrorCode(getErrorCode(error2));
2010
+ status2 = "stat_failed";
2011
+ }
2012
+ }
2013
+ return { status: status2, chain: entries.join(","), symlinkTarget, symlinkMeta };
2014
+ }
2015
+ function buildDiagnostic(line, context) {
2016
+ const trigger = parseTrigger(line);
2017
+ if (!trigger) return null;
2018
+ const roots = resolveRoots(context);
2019
+ const scope = classifyScope(trigger.dir, roots);
2020
+ const pathSource = trigger.path ? "error" : trigger.dir ? "dir" : "none";
2021
+ const inspectedPath = trigger.path ?? trigger.dir;
2022
+ const microvmId = context.microvmId?.trim() || "unknown";
2023
+ const euid = context.euid === void 0 ? "unavailable" : String(context.euid);
2024
+ const egid = context.egid === void 0 ? "unavailable" : String(context.egid);
2025
+ const op = trigger.op ?? "unknown";
2026
+ if (!inspectedPath) {
2027
+ return {
2028
+ event: `OPENCODE-DEPENDENCY-INSTALL-EACCES: status=no_path path_source=${pathSource} scope=${scope} microvm_id=${microvmId} op=${op} path=unknown cli_euid=${euid} cli_egid=${egid} effect="${EFFECT}" chain=unavailable`,
2029
+ localDetail: null
2030
+ };
2031
+ }
2032
+ const tokenisedPath = tokenise(inspectedPath, roots.resolved);
2033
+ if (!tokenisedPath) {
2034
+ const unresolvedRoot = unresolvedRootForPath(inspectedPath, roots.unresolved);
2035
+ if (unresolvedRoot) {
2036
+ return {
2037
+ event: `OPENCODE-DEPENDENCY-INSTALL-EACCES: status=root_unresolved path_source=${pathSource} scope=${scope} microvm_id=${microvmId} op=${op} path=unknown cli_euid=${euid} cli_egid=${egid} effect="${EFFECT}" chain=unavailable`,
2038
+ localDetail: null
2039
+ };
2040
+ }
2041
+ return {
2042
+ event: `OPENCODE-DEPENDENCY-INSTALL-EACCES: status=outside_roots path_source=${pathSource} scope=${scope} microvm_id=${microvmId} op=${op} path=<outside-approved-roots> cli_euid=${euid} cli_egid=${egid} effect="${EFFECT}" chain=unavailable`,
2043
+ localDetail: `OPENCODE-DEPENDENCY-INSTALL-EACCES (local only): outside approved roots: ${inspectedPath}`
2044
+ };
2045
+ }
2046
+ const inspection = inspectChain(
2047
+ tokenisedPath.root.real,
2048
+ tokenisedPath.root.token,
2049
+ inspectedPath,
2050
+ tokenisedPath.resolutionFailure
2051
+ );
2052
+ const optionalSymlinkFields = inspection.symlinkTarget ? ` symlink_target=${tokenise(inspection.symlinkTarget, roots.resolved)?.value ?? "<outside-approved-roots>"}` + (inspection.symlinkMeta ? ` symlink_meta=${inspection.symlinkMeta}` : "") : "";
2053
+ return {
2054
+ event: `OPENCODE-DEPENDENCY-INSTALL-EACCES: status=${inspection.status} path_source=${pathSource} scope=${scope} microvm_id=${microvmId} op=${op} path=${tokenisedPath.value} cli_euid=${euid} cli_egid=${egid} effect="${EFFECT}" chain=${inspection.chain}${optionalSymlinkFields}`,
2055
+ localDetail: null
2056
+ };
2057
+ }
2058
+ function createDependencyInstallDiagnosticReporter({
2059
+ context,
2060
+ emitEvent: emitEvent2,
2061
+ emitLocal
2062
+ }) {
2063
+ const emittedEvents = /* @__PURE__ */ new Set();
2064
+ return (line) => {
2065
+ const diagnostic = buildDiagnostic(line, context);
2066
+ if (!diagnostic || emittedEvents.has(diagnostic.event)) return;
2067
+ if (emittedEvents.size >= MAX_DISTINCT_DIAGNOSTICS) return;
2068
+ emittedEvents.add(diagnostic.event);
2069
+ emitEvent2(diagnostic.event);
2070
+ if (diagnostic.localDetail) emitLocal(diagnostic.localDetail);
2071
+ };
2072
+ }
2073
+
1795
2074
  // src/lib/runner-activity-telemetry.ts
1796
2075
  var FORWARDED_LEVELS_BY_SOURCE = {
1797
2076
  "cli.run": /* @__PURE__ */ new Set(["warn", "error"]),
@@ -1823,7 +2102,17 @@ function parseOpenCodeLogLine(line) {
1823
2102
  }
1824
2103
  var MAX_LINE_BUFFER_BYTES = 16 * 1024;
1825
2104
  var REPEAT_SUPPRESSION_WINDOW_MS = 6e4;
1826
- function createOpenCodeActivityForwarder(getContext, onSessionStoreWriteFailure) {
2105
+ function sanitiseDependencyInstallWarning(line) {
2106
+ const withoutDirectory = line.replace(
2107
+ /((?:^|\s)dir=)(?:"(?:\\.|[^"])*"|\/[^\s)"']+|\S+)/g,
2108
+ "$1<path>"
2109
+ );
2110
+ return withoutDirectory.replace(
2111
+ /((?:^|\s)error=)"((?:\\.|[^"])*)"/,
2112
+ (_match, prefix, error2) => `${prefix}"${error2.replace(/'\/[^']*'/g, "'<path>'")}"`
2113
+ );
2114
+ }
2115
+ function createOpenCodeActivityForwarder(getContext, onSessionStoreWriteFailure, onDependencyInstallFailure) {
1827
2116
  let buffer = Buffer.alloc(0);
1828
2117
  const repeatStates = /* @__PURE__ */ new Map();
1829
2118
  const forwardLine = (line, parsed, repeatsSuppressed = 0) => {
@@ -1835,7 +2124,7 @@ function createOpenCodeActivityForwarder(getContext, onSessionStoreWriteFailure)
1835
2124
  forwardRunnerActivity(
1836
2125
  {
1837
2126
  level: parsed.level,
1838
- error: line,
2127
+ error: parsed.message === DEPENDENCY_INSTALL_FAILURE_MESSAGE ? sanitiseDependencyInstallWarning(line) : line,
1839
2128
  metadata: Object.keys(metadata).length > 0 ? metadata : void 0,
1840
2129
  source: "opencode"
1841
2130
  },
@@ -1853,24 +2142,7 @@ function createOpenCodeActivityForwarder(getContext, onSessionStoreWriteFailure)
1853
2142
  repeatStates.delete(key);
1854
2143
  }
1855
2144
  };
1856
- const flushLine = (line) => {
1857
- const parsed = parseOpenCodeLogLine(line);
1858
- const isDiskFailure = isSessionStoreWriteFailure(line);
1859
- const cause = sessionStoreCauseToken(line);
1860
- if (onSessionStoreWriteFailure && (isDiskFailure || cause !== null)) {
1861
- try {
1862
- onSessionStoreWriteFailure({
1863
- isDiskFailure,
1864
- sessionId: parsed?.sessionID ?? null,
1865
- cause
1866
- });
1867
- } catch (err) {
1868
- reportTelemetryDiagnostic(
1869
- `Runner activity telemetry could not record session-store write failure: ${err instanceof Error ? err.message : String(err)}`
1870
- );
1871
- }
1872
- }
1873
- if (!parsed) return;
2145
+ const forwardWithRepeatSuppression = (line, parsed) => {
1874
2146
  const now = Date.now();
1875
2147
  const key = parsed.message === void 0 ? void 0 : `${parsed.level}\0${parsed.message}\0${parsed.sessionID ?? ""}\0${parsed.messageID ?? ""}`;
1876
2148
  expireRepeatStates(now, key);
@@ -1893,6 +2165,35 @@ function createOpenCodeActivityForwarder(getContext, onSessionStoreWriteFailure)
1893
2165
  previous.parsed = parsed;
1894
2166
  previous.repeatsSuppressed++;
1895
2167
  };
2168
+ const flushLine = (line) => {
2169
+ const parsed = parseOpenCodeLogLine(line);
2170
+ const isDiskFailure = isSessionStoreWriteFailure(line);
2171
+ const cause = sessionStoreCauseToken(line);
2172
+ if (onSessionStoreWriteFailure && (isDiskFailure || cause !== null)) {
2173
+ try {
2174
+ onSessionStoreWriteFailure({
2175
+ isDiskFailure,
2176
+ sessionId: parsed?.sessionID ?? null,
2177
+ cause
2178
+ });
2179
+ } catch (err) {
2180
+ reportTelemetryDiagnostic(
2181
+ `Runner activity telemetry could not record session-store write failure: ${err instanceof Error ? err.message : String(err)}`
2182
+ );
2183
+ }
2184
+ }
2185
+ if (!parsed) return;
2186
+ forwardWithRepeatSuppression(line, parsed);
2187
+ if (onDependencyInstallFailure && parsed.message === DEPENDENCY_INSTALL_FAILURE_MESSAGE) {
2188
+ try {
2189
+ onDependencyInstallFailure(line);
2190
+ } catch (err) {
2191
+ reportTelemetryDiagnostic(
2192
+ `Runner activity telemetry could not record dependency-install failure diagnostic: ${err instanceof Error ? err.message : String(err)}`
2193
+ );
2194
+ }
2195
+ }
2196
+ };
1896
2197
  const forward = ((chunk) => {
1897
2198
  buffer = Buffer.concat([buffer, Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, "utf-8")]);
1898
2199
  let newlineIndex;
@@ -1932,6 +2233,23 @@ function truncate(message) {
1932
2233
  const remaining = MAX_MESSAGE_LENGTH - marker.length;
1933
2234
  const headLength = Math.ceil(remaining * 0.6);
1934
2235
  const tailLength = remaining - headLength;
2236
+ const effectMatch = message.startsWith("OPENCODE-DEPENDENCY-INSTALL-EACCES:") ? message.match(/ effect="[^"]*"/) : null;
2237
+ if (effectMatch?.index !== void 0) {
2238
+ const effectEnd = effectMatch.index + effectMatch[0].length;
2239
+ if (effectEnd > headLength && effectEnd < message.length) {
2240
+ const effectLength = effectMatch[0].length;
2241
+ const nonEffectLength = remaining - effectLength;
2242
+ const preservedTailLength = Math.min(
2243
+ message.length - effectEnd,
2244
+ nonEffectLength - Math.min(effectMatch.index, Math.ceil(nonEffectLength * 0.6))
2245
+ );
2246
+ const preservedHeadLength = Math.min(
2247
+ effectMatch.index,
2248
+ nonEffectLength - preservedTailLength
2249
+ );
2250
+ return message.slice(0, preservedHeadLength) + marker + message.slice(effectMatch.index, effectEnd) + message.slice(message.length - preservedTailLength);
2251
+ }
2252
+ }
1935
2253
  return message.slice(0, headLength) + marker + message.slice(message.length - tailLength);
1936
2254
  }
1937
2255
  function sanitiseMetadata(metadata) {
@@ -2009,10 +2327,10 @@ function forwardRunnerActivity(entry, context) {
2009
2327
 
2010
2328
  // src/lib/opencode/session-db-recovery-report.ts
2011
2329
  import { readFileSync as readFileSync2, unlinkSync } from "node:fs";
2012
- import { join as join2 } from "node:path";
2330
+ import { join as join3 } from "node:path";
2013
2331
  function sessionDbRecoveryReportPath(homeDir, env) {
2014
2332
  const override = env.EVIDENT_SESSION_DB_RECOVERY_REPORT?.trim();
2015
- return override || join2(homeDir, ".local", "state", "evident", "session-db-recovery.jsonl");
2333
+ return override || join3(homeDir, ".local", "state", "evident", "session-db-recovery.jsonl");
2016
2334
  }
2017
2335
  function drainSessionDbRecoveryReport({
2018
2336
  homeDir,
@@ -2285,7 +2603,7 @@ async function waitForOpenCodeHealth(port, timeoutMs = 3e4) {
2285
2603
  if (health.healthy || health.authFailed) {
2286
2604
  return health;
2287
2605
  }
2288
- await new Promise((resolve4) => setTimeout(resolve4, 1e3));
2606
+ await new Promise((resolve5) => setTimeout(resolve5, 1e3));
2289
2607
  }
2290
2608
  return { healthy: false, error: "Timeout waiting for OpenCode to be healthy" };
2291
2609
  }
@@ -2296,7 +2614,7 @@ async function waitForOpenCode2Health(port, password, timeoutMs = 3e4) {
2296
2614
  if (health.healthy || health.authFailed) {
2297
2615
  return health;
2298
2616
  }
2299
- await new Promise((resolve4) => setTimeout(resolve4, 1e3));
2617
+ await new Promise((resolve5) => setTimeout(resolve5, 1e3));
2300
2618
  }
2301
2619
  return { healthy: false, error: "Timeout waiting for OpenCode to be healthy" };
2302
2620
  }
@@ -2563,7 +2881,18 @@ async function deleteSession(port, id, client) {
2563
2881
  { method: "DELETE" },
2564
2882
  { allowStatuses: ALL_HTTP_STATUSES }
2565
2883
  );
2566
- return { ok: res.status >= 200 && res.status < 300, status: res.status };
2884
+ if (res.status >= 200 && res.status < 300) {
2885
+ return { ok: true, status: res.status };
2886
+ }
2887
+ try {
2888
+ const body = await res.text();
2889
+ return body ? { ok: false, status: res.status, body } : { ok: false, status: res.status };
2890
+ } catch (error2) {
2891
+ console.error(
2892
+ `[deleteSession] DELETE /session/${id} response body read failed for HTTP ${res.status}: ${error2 instanceof Error ? error2.message : String(error2)}`
2893
+ );
2894
+ return { ok: false, status: res.status };
2895
+ }
2567
2896
  } catch (error2) {
2568
2897
  console.error(
2569
2898
  `[deleteSession] DELETE /session/${id} failed: ${error2 instanceof Error ? error2.message : String(error2)}`
@@ -2875,7 +3204,7 @@ async function sendPromptAsync(port, sessionId, content, options, attachments, c
2875
3204
  return dispatchedUserMessageId;
2876
3205
  }
2877
3206
  if (attempt < READ_BACK_ATTEMPTS - 1) {
2878
- await new Promise((resolve4) => setTimeout(resolve4, READ_BACK_DELAY_MS));
3207
+ await new Promise((resolve5) => setTimeout(resolve5, READ_BACK_DELAY_MS));
2879
3208
  }
2880
3209
  }
2881
3210
  return null;
@@ -3047,9 +3376,11 @@ function sumAssistantUsage(messages) {
3047
3376
  let cacheWriteSum = 0;
3048
3377
  let costSum = 0;
3049
3378
  let sawCost = false;
3379
+ let toolCallCount = 0;
3050
3380
  let modelId = null;
3051
3381
  let providerId = null;
3052
3382
  for (const m of selected) {
3383
+ toolCallCount += m.parts?.filter((part) => part.type === "tool").length ?? 0;
3053
3384
  const info = m.info;
3054
3385
  if (!info) continue;
3055
3386
  const tokens = info.tokens;
@@ -3086,7 +3417,8 @@ function sumAssistantUsage(messages) {
3086
3417
  usage_tokens_cache_write: cacheWriteSum,
3087
3418
  // NULL means OpenCode never reported a cost; it is distinct from a genuine
3088
3419
  // zero-cost message, which sets `sawCost` with `costSum === 0`.
3089
- usage_cost_usd: sawCost ? costSum : null
3420
+ usage_cost_usd: sawCost ? costSum : null,
3421
+ turn_tool_calls: toolCallCount
3090
3422
  };
3091
3423
  }
3092
3424
  function messageUsage(messages, userMessageId) {
@@ -3190,19 +3522,32 @@ function isAbortedTerminalReply(messages, userMessageId) {
3190
3522
  }
3191
3523
  return false;
3192
3524
  }
3525
+ var CLAUDE_AUTH_EXPIRY_MESSAGES = Object.freeze([
3526
+ "Claude Code credentials are unavailable or expired. Run `claude` to refresh them."
3527
+ ]);
3528
+ function extractReplyErrorShape(reply) {
3529
+ const error2 = errorOf(reply);
3530
+ if (error2 == null || typeof error2 !== "object") {
3531
+ return { name: null, statusCode: null };
3532
+ }
3533
+ const e = error2;
3534
+ const name = typeof e.name === "string" ? e.name.slice(0, 100) : null;
3535
+ const data = e.data;
3536
+ const statusCode = typeof data?.statusCode === "number" && Number.isFinite(data.statusCode) ? data.statusCode : null;
3537
+ return { name, statusCode };
3538
+ }
3193
3539
  function classifyReplyAuthError(reply) {
3194
3540
  const error2 = errorOf(reply);
3195
3541
  if (error2 == null || typeof error2 !== "object") return null;
3196
3542
  const e = error2;
3197
3543
  const replyProviderId = reply?.info?.providerID ?? null;
3198
3544
  const replyModelId = reply?.info?.modelID ?? null;
3545
+ const data = e.data;
3199
3546
  if (e.name === "ProviderAuthError") {
3200
- const data = e.data;
3201
3547
  const providerId = typeof data?.providerID === "string" && data.providerID || replyProviderId;
3202
3548
  return { kind: "model_auth", providerId, modelId: replyModelId, reason: "missing" };
3203
3549
  }
3204
3550
  if (e.name === "APIError") {
3205
- const data = e.data;
3206
3551
  const statusCode = data?.statusCode;
3207
3552
  if (statusCode === 401 || statusCode === 403) {
3208
3553
  return {
@@ -3213,11 +3558,23 @@ function classifyReplyAuthError(reply) {
3213
3558
  };
3214
3559
  }
3215
3560
  }
3561
+ const errorMessage3 = typeof data?.message === "string" ? data.message : typeof e.message === "string" ? e.message : null;
3562
+ if (errorMessage3 !== null && CLAUDE_AUTH_EXPIRY_MESSAGES.some((knownMessage) => errorMessage3.includes(knownMessage))) {
3563
+ return {
3564
+ kind: "model_auth",
3565
+ providerId: typeof data?.providerID === "string" && data.providerID || replyProviderId,
3566
+ modelId: replyModelId,
3567
+ reason: "rejected"
3568
+ };
3569
+ }
3216
3570
  return null;
3217
3571
  }
3218
3572
  function messageFailure(messages, userMessageId) {
3219
3573
  return classifyReplyAuthError(findLastAssistantReplyFor(messages, userMessageId));
3220
3574
  }
3575
+ function isProviderModelNotFoundError(reason) {
3576
+ return reason.includes("Model not found:");
3577
+ }
3221
3578
  function findLatestSubagentAuthOutcome(messages, sinceMs) {
3222
3579
  if (!messages || messages.length === 0) return null;
3223
3580
  for (let i = messages.length - 1; i >= 0; i--) {
@@ -3748,7 +4105,18 @@ async function deleteV2Session(client, sessionId) {
3748
4105
  { method: "DELETE" },
3749
4106
  { allowStatuses: Array.from({ length: 500 }, (_, index) => index + 100) }
3750
4107
  );
3751
- return { ok: response.status >= 200 && response.status < 300, status: response.status };
4108
+ if (response.status >= 200 && response.status < 300) {
4109
+ return { ok: true, status: response.status };
4110
+ }
4111
+ try {
4112
+ const body = await response.text();
4113
+ return body ? { ok: false, status: response.status, body } : { ok: false, status: response.status };
4114
+ } catch (error2) {
4115
+ console.error(
4116
+ `[deleteV2Session] DELETE /api/session/${sessionId} response body read failed for HTTP ${response.status}: ${error2 instanceof Error ? error2.message : String(error2)}`
4117
+ );
4118
+ return { ok: false, status: response.status };
4119
+ }
3752
4120
  } catch (error2) {
3753
4121
  console.error(
3754
4122
  `[deleteV2Session] DELETE /api/session/${sessionId} failed: ${error2 instanceof Error ? error2.message : String(error2)}`
@@ -3924,12 +4292,12 @@ async function readV2SessionErrorStream(client, options) {
3924
4292
 
3925
4293
  // src/lib/opencode/credential-import-v2.ts
3926
4294
  import { readFileSync as readFileSync4 } from "node:fs";
3927
- import { join as join4 } from "node:path";
4295
+ import { join as join5 } from "node:path";
3928
4296
 
3929
4297
  // src/lib/openai-usage.ts
3930
4298
  import { readFileSync as readFileSync3 } from "node:fs";
3931
4299
  import { homedir as homedir3 } from "node:os";
3932
- import { join as join3 } from "node:path";
4300
+ import { join as join4 } from "node:path";
3933
4301
  var CODEX_RESPONSES_URL = "https://chatgpt.com/backend-api/codex/responses";
3934
4302
  var OPENCODE_AUTH_SEGMENTS = [".local", "share", "opencode", "auth.json"];
3935
4303
  var OpenAiUsageError = class extends Error {
@@ -3943,7 +4311,7 @@ function isLocalCredentialProblem2(err) {
3943
4311
  }
3944
4312
  function readOpenCodeChatGptCredentials() {
3945
4313
  try {
3946
- const raw = readFileSync3(join3(homedir3(), ...OPENCODE_AUTH_SEGMENTS), "utf-8");
4314
+ const raw = readFileSync3(join4(homedir3(), ...OPENCODE_AUTH_SEGMENTS), "utf-8");
3947
4315
  let parsed;
3948
4316
  try {
3949
4317
  parsed = JSON.parse(raw);
@@ -4169,13 +4537,13 @@ var INTEGRATION_LIST_RETRY_DELAY_MS = 1e3;
4169
4537
  function isRecord3(value) {
4170
4538
  return typeof value === "object" && value !== null && !Array.isArray(value);
4171
4539
  }
4172
- var sleep2 = (milliseconds) => new Promise((resolve4) => setTimeout(resolve4, milliseconds));
4540
+ var sleep2 = (milliseconds) => new Promise((resolve5) => setTimeout(resolve5, milliseconds));
4173
4541
  function emptyResult(unsupported = [], outcome = "completed") {
4174
4542
  return { outcome, imported: [], alreadyConnected: [], unsupported, failed: [] };
4175
4543
  }
4176
4544
  function readOpenCodeCredentials(homeDir, log3) {
4177
4545
  try {
4178
- const raw = readFileSync4(join4(homeDir, ...OPENCODE_AUTH_SEGMENTS), "utf8");
4546
+ const raw = readFileSync4(join5(homeDir, ...OPENCODE_AUTH_SEGMENTS), "utf8");
4179
4547
  let parsed;
4180
4548
  try {
4181
4549
  parsed = JSON.parse(raw);
@@ -4377,7 +4745,7 @@ async function importOpenCodeV2Credentials({
4377
4745
  import { spawn as spawn2 } from "node:child_process";
4378
4746
  import { mkdirSync, statSync as statSync3, unlinkSync as unlinkSync2, writeFileSync } from "node:fs";
4379
4747
  import { homedir as homedir4 } from "node:os";
4380
- import { dirname as dirname3, resolve as resolvePath } from "node:path";
4748
+ import { dirname as dirname4, resolve as resolvePath } from "node:path";
4381
4749
 
4382
4750
  // src/lib/runner-synchroniser.ts
4383
4751
  import { spawn } from "node:child_process";
@@ -4387,7 +4755,7 @@ function appendError(stderr, error2) {
4387
4755
  ${message}`;
4388
4756
  }
4389
4757
  function runSynchroniser(args, opts) {
4390
- return new Promise((resolve4) => {
4758
+ return new Promise((resolve5) => {
4391
4759
  let child;
4392
4760
  let stdout = "";
4393
4761
  let stderr = "";
@@ -4401,7 +4769,7 @@ function runSynchroniser(args, opts) {
4401
4769
  if (timer.handle) clearTimeout(timer.handle);
4402
4770
  if (abortListener) opts.signal?.removeEventListener("abort", abortListener);
4403
4771
  if (spawnListener) child.removeListener("spawn", spawnListener);
4404
- resolve4(result);
4772
+ resolve5(result);
4405
4773
  };
4406
4774
  try {
4407
4775
  child = spawn("runner-synchroniser", args, {
@@ -4505,7 +4873,7 @@ function clearMarker(options) {
4505
4873
  function markNoReplicate(options, message) {
4506
4874
  if (options.noReplicateMarker) {
4507
4875
  try {
4508
- mkdirSync(dirname3(options.noReplicateMarker), { recursive: true });
4876
+ mkdirSync(dirname4(options.noReplicateMarker), { recursive: true });
4509
4877
  writeFileSync(options.noReplicateMarker, "");
4510
4878
  } catch (error2) {
4511
4879
  options.log(
@@ -4564,7 +4932,7 @@ function parseSynchroniserEnv(stdout) {
4564
4932
  return values;
4565
4933
  }
4566
4934
  function runCommand(command, args, options) {
4567
- return new Promise((resolve4) => {
4935
+ return new Promise((resolve5) => {
4568
4936
  let child;
4569
4937
  let stdout = "";
4570
4938
  let stderr = "";
@@ -4573,7 +4941,7 @@ function runCommand(command, args, options) {
4573
4941
  if (settled) return;
4574
4942
  settled = true;
4575
4943
  if (timer) clearTimeout(timer);
4576
- resolve4(result);
4944
+ resolve5(result);
4577
4945
  };
4578
4946
  try {
4579
4947
  child = spawn2(command, args, {
@@ -4581,7 +4949,7 @@ function runCommand(command, args, options) {
4581
4949
  stdio: ["ignore", "pipe", "pipe"]
4582
4950
  });
4583
4951
  } catch (error2) {
4584
- resolve4({
4952
+ resolve5({
4585
4953
  code: null,
4586
4954
  stdout,
4587
4955
  stderr: error2 instanceof Error ? error2.message : String(error2),
@@ -4660,7 +5028,7 @@ async function ensureLitestreamConfig(options, env) {
4660
5028
  return null;
4661
5029
  }
4662
5030
  try {
4663
- mkdirSync(dirname3(configPath), { recursive: true });
5031
+ mkdirSync(dirname4(configPath), { recursive: true });
4664
5032
  writeFileSync(configPath, rendered.stdout);
4665
5033
  } catch (error2) {
4666
5034
  options.log(
@@ -4927,7 +5295,7 @@ async function restoreAndVerifySessionDb(options) {
4927
5295
  // src/lib/opencode/session-db-provenance.ts
4928
5296
  import { createRequire } from "node:module";
4929
5297
  import { mkdirSync as mkdirSync2, readFileSync as readFileSync5, writeFileSync as writeFileSync2 } from "node:fs";
4930
- import { dirname as dirname4, join as join5 } from "node:path";
5298
+ import { dirname as dirname5, join as join6 } from "node:path";
4931
5299
  var require2 = createRequire(import.meta.url);
4932
5300
  function readSessionDbMigrationIds(dbPath) {
4933
5301
  let db;
@@ -4964,7 +5332,7 @@ function readSessionDbMigrationIds(dbPath) {
4964
5332
  }
4965
5333
  function sessionDbProvenanceStatePath(homeDir, env) {
4966
5334
  const override = env.EVIDENT_SESSION_DB_PROVENANCE_STATE?.trim();
4967
- return override || join5(homeDir, ".local", "state", "evident", "session-db-provenance.json");
5335
+ return override || join6(homeDir, ".local", "state", "evident", "session-db-provenance.json");
4968
5336
  }
4969
5337
  function loadSessionDbProvenanceState(path) {
4970
5338
  let value;
@@ -4993,7 +5361,7 @@ function loadSessionDbProvenanceState(path) {
4993
5361
  }
4994
5362
  function saveSessionDbProvenanceState(path, state) {
4995
5363
  try {
4996
- mkdirSync2(dirname4(path), { recursive: true });
5364
+ mkdirSync2(dirname5(path), { recursive: true });
4997
5365
  writeFileSync2(path, `${JSON.stringify(state, null, 2)}
4998
5366
  `, "utf8");
4999
5367
  } catch (error2) {
@@ -5084,7 +5452,7 @@ async function stopProcessAndWait(child, timeoutMs, sendTerm, sendKill) {
5084
5452
  if (child.exitCode !== null || child.signalCode !== null) {
5085
5453
  return { outcome: "exited", code: child.exitCode, signal: child.signalCode };
5086
5454
  }
5087
- return new Promise((resolve4, reject) => {
5455
+ return new Promise((resolve5, reject) => {
5088
5456
  let forced = false;
5089
5457
  let settled = false;
5090
5458
  const timer = setTimeout(() => {
@@ -5104,7 +5472,7 @@ async function stopProcessAndWait(child, timeoutMs, sendTerm, sendKill) {
5104
5472
  settled = true;
5105
5473
  clearTimeout(timer);
5106
5474
  child.removeListener("exit", onExit);
5107
- resolve4(result);
5475
+ resolve5(result);
5108
5476
  };
5109
5477
  const fail = (error2) => {
5110
5478
  if (settled) return;
@@ -5580,7 +5948,7 @@ function selectSessionsToDelete(sessions, opts) {
5580
5948
  );
5581
5949
  }
5582
5950
  var DEFAULT_INTERVAL = "1h";
5583
- function resolve(flag, envValue, fallback) {
5951
+ function resolve2(flag, envValue, fallback) {
5584
5952
  return flag ?? envValue ?? fallback;
5585
5953
  }
5586
5954
  function parseMaxCount(input) {
@@ -5596,9 +5964,9 @@ function parseMaxCount(input) {
5596
5964
  }
5597
5965
  function resolveSessionCleanupConfig(flags, env = process.env) {
5598
5966
  const warnings = [];
5599
- const maxAgeRaw = resolve(flags.maxAge, env.EVIDENT_SESSION_CLEANUP_MAX_AGE);
5600
- const maxCountRaw = resolve(flags.maxCount, env.EVIDENT_SESSION_CLEANUP_MAX_COUNT);
5601
- const intervalRaw = resolve(
5967
+ const maxAgeRaw = resolve2(flags.maxAge, env.EVIDENT_SESSION_CLEANUP_MAX_AGE);
5968
+ const maxCountRaw = resolve2(flags.maxCount, env.EVIDENT_SESSION_CLEANUP_MAX_COUNT);
5969
+ const intervalRaw = resolve2(
5602
5970
  flags.interval,
5603
5971
  env.EVIDENT_SESSION_CLEANUP_INTERVAL,
5604
5972
  DEFAULT_INTERVAL
@@ -5638,10 +6006,10 @@ function resolveSessionCleanupConfig(flags, env = process.env) {
5638
6006
 
5639
6007
  // src/lib/opencode/session-db-size.ts
5640
6008
  import { statSync as statSync4 } from "node:fs";
5641
- import { join as join6 } from "node:path";
6009
+ import { join as join7 } from "node:path";
5642
6010
  var LARGE_DB_THRESHOLD_BYTES = 268435456;
5643
6011
  function statSessionDbBytes(homeDir) {
5644
- const dbPath = join6(homeDir, ".local", "share", "opencode", "opencode.db");
6012
+ const dbPath = join7(homeDir, ".local", "share", "opencode", "opencode.db");
5645
6013
  try {
5646
6014
  return statSync4(dbPath).size;
5647
6015
  } catch (err) {
@@ -5671,12 +6039,12 @@ function buildSessionStoreSizeWarning(input) {
5671
6039
  // src/lib/opencode/log-tail.ts
5672
6040
  import { statSync as statSync5 } from "node:fs";
5673
6041
  import { homedir as homedir5 } from "node:os";
5674
- import { join as join7 } from "node:path";
6042
+ import { join as join8 } from "node:path";
5675
6043
  import { open as open2, stat } from "node:fs/promises";
5676
6044
  var DEFAULT_POLL_INTERVAL_MS = 1e3;
5677
6045
  function resolveOpenCodeLogPath(homeDir = homedir5(), env = process.env) {
5678
- const dataDir = env.XDG_DATA_HOME || join7(homeDir, ".local", "share");
5679
- return join7(dataDir, "opencode", "log", "opencode.log");
6046
+ const dataDir = env.XDG_DATA_HOME || join8(homeDir, ".local", "share");
6047
+ return join8(dataDir, "opencode", "log", "opencode.log");
5680
6048
  }
5681
6049
  function isEnoent(error2) {
5682
6050
  return error2?.code === "ENOENT";
@@ -5831,8 +6199,8 @@ var StreamForwarder = class {
5831
6199
  pauseStream(sid, stream) {
5832
6200
  if (!stream.paused) {
5833
6201
  stream.paused = true;
5834
- stream.pausePromise = new Promise((resolve4) => {
5835
- stream.resume = resolve4;
6202
+ stream.pausePromise = new Promise((resolve5) => {
6203
+ stream.resume = resolve5;
5836
6204
  });
5837
6205
  }
5838
6206
  if (stream.pauseTimer !== null) clearTimeout(stream.pauseTimer);
@@ -5899,12 +6267,12 @@ var StreamForwarder = class {
5899
6267
  let endBody;
5900
6268
  if (has_body) {
5901
6269
  const chunks = [];
5902
- bodyPromise = new Promise((resolve4) => {
6270
+ bodyPromise = new Promise((resolve5) => {
5903
6271
  pushBody = (buf) => {
5904
6272
  chunks.push(buf);
5905
6273
  };
5906
6274
  endBody = () => {
5907
- resolve4(Buffer.concat(chunks));
6275
+ resolve5(Buffer.concat(chunks));
5908
6276
  };
5909
6277
  });
5910
6278
  }
@@ -6075,7 +6443,7 @@ function connectTunnel(options) {
6075
6443
  } = options;
6076
6444
  const tunnelUrl = getTunnelUrlConfig();
6077
6445
  const url = `${tunnelUrl}/tunnel/${agentId}/connect`;
6078
- return new Promise((resolve4, reject) => {
6446
+ return new Promise((resolve5, reject) => {
6079
6447
  const ws = new WebSocket2(url, {
6080
6448
  headers: {
6081
6449
  Authorization: authHeader,
@@ -6184,7 +6552,7 @@ function connectTunnel(options) {
6184
6552
  forwarder.setBinaryFramesSupported(message.binary_frames === true);
6185
6553
  const connectedAgentId = message.agent_id ?? agentId;
6186
6554
  onConnected?.(connectedAgentId);
6187
- resolve4({
6555
+ resolve5({
6188
6556
  ws,
6189
6557
  close: () => ws.close(1e3, "CLI shutdown")
6190
6558
  });
@@ -6739,12 +7107,12 @@ function createSessionStoreHealth(options = {}) {
6739
7107
  import { homedir as homedir6 } from "node:os";
6740
7108
 
6741
7109
  // src/lib/runner-file-sync.ts
6742
- import { join as join9 } from "node:path";
7110
+ import { join as join10 } from "node:path";
6743
7111
 
6744
7112
  // src/lib/file-push.ts
6745
7113
  import { randomUUID } from "node:crypto";
6746
7114
  import { chmod, mkdir, open as open3, realpath, rename, unlink } from "node:fs/promises";
6747
- import { basename, dirname as dirname5, isAbsolute, join as join8, relative, resolve as resolve2, sep } from "node:path";
7115
+ import { basename as basename2, dirname as dirname6, isAbsolute as isAbsolute2, join as join9, relative as relative2, resolve as resolve3, sep as sep2 } from "node:path";
6748
7116
  var FILE_MODE = 384;
6749
7117
  var DIRECTORY_MODE = 448;
6750
7118
  async function writePushedFile(request2) {
@@ -6775,9 +7143,9 @@ async function writePushedFile(request2) {
6775
7143
  }
6776
7144
  try {
6777
7145
  const { existingAncestor, missingSegments } = await resolveNearestExistingAncestor(
6778
- dirname5(candidate)
7146
+ dirname6(candidate)
6779
7147
  );
6780
- const realTarget = join8(existingAncestor, ...missingSegments, basename(candidate));
7148
+ const realTarget = join9(existingAncestor, ...missingSegments, basename2(candidate));
6781
7149
  const allowedDirectory = await findContainingAllowedDirectory(allowedDirectories, realTarget);
6782
7150
  if (allowedDirectory === null) {
6783
7151
  return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
@@ -6787,8 +7155,8 @@ async function writePushedFile(request2) {
6787
7155
  }
6788
7156
  if (missingSegments.length > 0) {
6789
7157
  await createMissingDirectories(existingAncestor, missingSegments);
6790
- const realParent = await realpath(dirname5(realTarget));
6791
- if (realParent !== dirname5(realTarget) || !contains(allowedDirectory, realTarget)) {
7158
+ const realParent = await realpath(dirname6(realTarget));
7159
+ if (realParent !== dirname6(realTarget) || !contains(allowedDirectory, realTarget)) {
6792
7160
  return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
6793
7161
  path: realTarget,
6794
7162
  bytes,
@@ -6813,15 +7181,15 @@ function expandAndValidate(requestedPath, homeDir) {
6813
7181
  if (requestedPath.trim() === "" || requestedPath.includes("\0")) {
6814
7182
  return null;
6815
7183
  }
6816
- const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join8(homeDir, requestedPath.slice(2)) : requestedPath;
7184
+ const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join9(homeDir, requestedPath.slice(2)) : requestedPath;
6817
7185
  if (expanded.split(/[/\\]/).includes("..")) {
6818
7186
  return null;
6819
7187
  }
6820
- if (!isAbsolute(expanded)) {
7188
+ if (!isAbsolute2(expanded)) {
6821
7189
  return null;
6822
7190
  }
6823
- const candidate = resolve2(expanded);
6824
- const name = basename(candidate);
7191
+ const candidate = resolve3(expanded);
7192
+ const name = basename2(candidate);
6825
7193
  return name === "" || name === "." || name === ".." ? null : candidate;
6826
7194
  }
6827
7195
  async function resolveNearestExistingAncestor(directory) {
@@ -6831,18 +7199,18 @@ async function resolveNearestExistingAncestor(directory) {
6831
7199
  try {
6832
7200
  return { existingAncestor: await realpath(current), missingSegments };
6833
7201
  } catch (err) {
6834
- const parent = dirname5(current);
7202
+ const parent = dirname6(current);
6835
7203
  if (err.code !== "ENOENT" || parent === current) {
6836
7204
  throw err;
6837
7205
  }
6838
- missingSegments.unshift(basename(current));
7206
+ missingSegments.unshift(basename2(current));
6839
7207
  current = parent;
6840
7208
  }
6841
7209
  }
6842
7210
  }
6843
7211
  async function findContainingAllowedDirectory(allowedDirectories, realTarget) {
6844
7212
  for (const directory of allowedDirectories) {
6845
- if (!isAbsolute(directory)) {
7213
+ if (!isAbsolute2(directory)) {
6846
7214
  log("warn", "file_push_allowed_directory_skipped", { directory, reason: "not_absolute" });
6847
7215
  continue;
6848
7216
  }
@@ -6880,19 +7248,19 @@ async function realpathCreatingIfMissing(directory) {
6880
7248
  }
6881
7249
  }
6882
7250
  function contains(realDirectory, realTarget) {
6883
- const rel = relative(realDirectory, realTarget);
6884
- return rel !== "" && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
7251
+ const rel = relative2(realDirectory, realTarget);
7252
+ return rel !== "" && rel !== ".." && !rel.startsWith(`..${sep2}`) && !isAbsolute2(rel);
6885
7253
  }
6886
7254
  async function createMissingDirectories(existingAncestor, missingSegments) {
6887
7255
  let current = existingAncestor;
6888
7256
  for (const segment of missingSegments) {
6889
- current = join8(current, segment);
7257
+ current = join9(current, segment);
6890
7258
  await mkdir(current, { recursive: true, mode: DIRECTORY_MODE });
6891
7259
  await chmod(current, DIRECTORY_MODE);
6892
7260
  }
6893
7261
  }
6894
7262
  async function writeAtomically(realTarget, content) {
6895
- const temporaryPath = join8(dirname5(realTarget), `.evident-push-${randomUUID()}.tmp`);
7263
+ const temporaryPath = join9(dirname6(realTarget), `.evident-push-${randomUUID()}.tmp`);
6896
7264
  let handle;
6897
7265
  try {
6898
7266
  handle = await open3(temporaryPath, "wx", FILE_MODE);
@@ -7022,12 +7390,12 @@ var NOT_APPLIED = {
7022
7390
  opencodeAuthApplied: false
7023
7391
  };
7024
7392
  function isClaudeCredentialPath(requestedPath, homeDir) {
7025
- const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join9(homeDir, requestedPath.slice(2)) : requestedPath;
7026
- return expanded === join9(homeDir, ...CLAUDE_CREDENTIALS_SEGMENTS);
7393
+ const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join10(homeDir, requestedPath.slice(2)) : requestedPath;
7394
+ return expanded === join10(homeDir, ...CLAUDE_CREDENTIALS_SEGMENTS);
7027
7395
  }
7028
7396
  function isOpenCodeAuthPath(requestedPath, homeDir) {
7029
- const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join9(homeDir, requestedPath.slice(2)) : requestedPath;
7030
- return expanded === join9(homeDir, ...OPENCODE_AUTH_SEGMENTS);
7397
+ const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join10(homeDir, requestedPath.slice(2)) : requestedPath;
7398
+ return expanded === join10(homeDir, ...OPENCODE_AUTH_SEGMENTS);
7031
7399
  }
7032
7400
  async function applyOne(options, file) {
7033
7401
  const label = `${file.id.slice(0, 8)} (${file.path})`;
@@ -7198,7 +7566,7 @@ var SESSION_ERROR_BUFFER_TTL_MS = SESSION_ERROR_STREAM_HEALTHY_MS;
7198
7566
  var MAX_BUFFERED_SESSION_ERRORS = 256;
7199
7567
  var SESSION_ERROR_RETENTION_TTL_MS = 6e4;
7200
7568
  var SESSION_STORE_UNWRITABLE_ERROR = "The runner session database could not be written, so this turn did not finish. Nothing was lost from the queue. Clear disk space and retry.";
7201
- var SESSION_ERROR_RETAINED_DETAIL = "The runner's session database could not be written, so this turn stopped part-way. Runner-observed session error: ";
7569
+ var SESSION_ERROR_RETAINED_DETAIL = "Runner-observed OpenCode session error: ";
7202
7570
  var SESSION_ERROR_OBSERVED_CAUSE = "Runner-observed OpenCode session-store cause: ";
7203
7571
  var DEFAULT_PAUSED_POLL_INTERVAL_MS = 2e3;
7204
7572
  var DEFAULT_PAUSED_MAX_WAIT_MS = 10 * 60 * 1e3;
@@ -9594,14 +9962,53 @@ var ChannelDriver = class _ChannelDriver {
9594
9962
  conversation_id: watcher.conv.id,
9595
9963
  message_id: inFlight.evidentMessageId
9596
9964
  });
9597
- await this.markFailed(
9598
- watcher.conv.id,
9599
- inFlight.evidentMessageId,
9600
- event.sessionId,
9601
- `OpenCode could not run this turn: ${event.reason}`
9602
- );
9965
+ const isMissingProvider = isProviderModelNotFoundError(event.reason);
9966
+ if (isMissingProvider) {
9967
+ const dispatchedModel = inFlight.message.opencode_model;
9968
+ const separator = dispatchedModel?.indexOf("/") ?? -1;
9969
+ const hasProviderAndModel = dispatchedModel !== null && separator > 0 && separator < dispatchedModel.length - 1;
9970
+ await this.markFailed(
9971
+ watcher.conv.id,
9972
+ inFlight.evidentMessageId,
9973
+ event.sessionId,
9974
+ `OpenCode could not run this turn: ${event.reason}`,
9975
+ void 0,
9976
+ {
9977
+ classification: {
9978
+ kind: "model_auth",
9979
+ providerId: hasProviderAndModel ? dispatchedModel.slice(0, separator) : null,
9980
+ modelId: hasProviderAndModel ? dispatchedModel.slice(separator + 1) : null,
9981
+ reason: "missing"
9982
+ },
9983
+ errorShape: { name: null, statusCode: null }
9984
+ }
9985
+ );
9986
+ } else {
9987
+ await this.markFailed(
9988
+ watcher.conv.id,
9989
+ inFlight.evidentMessageId,
9990
+ event.sessionId,
9991
+ `OpenCode could not run this turn: ${event.reason}`
9992
+ );
9993
+ }
9603
9994
  inFlight.done = true;
9604
9995
  this.removeInFlight(watcher, inFlight.evidentMessageId);
9996
+ if (isMissingProvider) {
9997
+ if (this.isV2) {
9998
+ void this.postSignal(
9999
+ watcher.conv.id,
10000
+ inFlight.evidentMessageId,
10001
+ "provider_registry_reload_unsupported"
10002
+ );
10003
+ } else {
10004
+ await reloadProviderCache(this.port, this.openCodeClient);
10005
+ void this.postSignal(
10006
+ watcher.conv.id,
10007
+ inFlight.evidentMessageId,
10008
+ "provider_registry_reload_issued"
10009
+ );
10010
+ }
10011
+ }
9605
10012
  } catch (err) {
9606
10013
  if (err instanceof ChannelAuthError) {
9607
10014
  this.log({
@@ -9813,7 +10220,7 @@ var ChannelDriver = class _ChannelDriver {
9813
10220
  if (!inFlight.done) {
9814
10221
  const messageErrorText = messageError(messages, inFlight.opencodeMessageId);
9815
10222
  const retainedReason = this.readRetainedSessionError(sessionId);
9816
- const retainedError = retainedReason === null ? null : `${SESSION_ERROR_RETAINED_DETAIL}${retainedReason}`;
10223
+ const retainedError = retainedReason === null || messageErrorText !== null && messageErrorText.includes(retainedReason) ? null : `${SESSION_ERROR_RETAINED_DETAIL}${retainedReason}`;
9817
10224
  const observedCause = this.sessionStoreHealth?.readCause(sessionId);
9818
10225
  const causeError = observedCause === null || observedCause === void 0 ? null : `${SESSION_ERROR_OBSERVED_CAUSE}${observedCause}`;
9819
10226
  const storeError = this.sessionStoreHealth?.isUnwritable() ? SESSION_STORE_UNWRITABLE_ERROR : null;
@@ -11522,14 +11929,14 @@ var ChannelDriver = class _ChannelDriver {
11522
11929
  const fetchChildWithoutBlocking = async (sessionId) => {
11523
11930
  const pending = fetchChildMessages(sessionId);
11524
11931
  let timer;
11525
- const timeout = new Promise((resolve4) => {
11932
+ const timeout = new Promise((resolve5) => {
11526
11933
  timer = setTimeout(() => {
11527
11934
  this.log({
11528
11935
  level: "warn",
11529
11936
  message: `Best-effort subagent session fetch for message ${messageId.slice(0, 8)} and child session ${sessionId.slice(0, 8)} was slow \u2014 omitting invocation telemetry without delaying completion`,
11530
11937
  message_id: messageId
11531
11938
  });
11532
- resolve4(null);
11939
+ resolve5(null);
11533
11940
  }, SUBAGENT_TELEMETRY_FETCH_TIMEOUT_MS);
11534
11941
  });
11535
11942
  try {
@@ -12168,11 +12575,17 @@ var ChannelDriver = class _ChannelDriver {
12168
12575
  if (subagentInvocations && subagentInvocations.length > 0) {
12169
12576
  body.subagent_invocations = subagentInvocations;
12170
12577
  }
12171
- if (failure) {
12172
- body.failure_kind = failure.kind;
12173
- body.failure_provider_id = failure.providerId;
12174
- body.failure_model_id = failure.modelId;
12175
- body.failure_reason = failure.reason;
12578
+ if (failure && failure.errorShape.name !== null) {
12579
+ body.failure_error_name = failure.errorShape.name;
12580
+ }
12581
+ if (failure && failure.errorShape.statusCode !== null) {
12582
+ body.failure_status_code = failure.errorShape.statusCode;
12583
+ }
12584
+ if (failure?.classification) {
12585
+ body.failure_kind = failure.classification.kind;
12586
+ body.failure_provider_id = failure.classification.providerId;
12587
+ body.failure_model_id = failure.classification.modelId;
12588
+ body.failure_reason = failure.classification.reason;
12176
12589
  }
12177
12590
  try {
12178
12591
  await this.callWithRetry(
@@ -12193,27 +12606,28 @@ var ChannelDriver = class _ChannelDriver {
12193
12606
  this.clearSubagentInvocationCaches(messageId);
12194
12607
  }
12195
12608
  /**
12196
- * Classify an errored turn as a model-auth failure (#736 P1-4), for `markFailed`.
12609
+ * Classify an errored turn and extract its bounded error shape for `markFailed`.
12197
12610
  *
12198
12611
  * `messageFailure` alone (structured OpenCode error → `model_auth`) covers
12199
12612
  * most cases; when it returns `null` on this ALREADY-FAILED turn, fall back
12200
12613
  * to the P1-2b zero-provider check — one extra loopback call to
12201
12614
  * `hasAnyConfiguredProvider`, only reached when the structured classifier
12202
12615
  * couldn't place it. Fails open (never throws): a fallback probe failure
12203
- * (`null`/indeterminate) leaves the classification `null`, which produces
12204
- * today's byte-identical PATCH body via `markFailed`'s `if (failure)` guard.
12616
+ * (`null`/indeterminate) leaves the classification `null`; the raw error shape
12617
+ * is still retained for diagnostics.
12205
12618
  */
12206
12619
  async classifyModelAuthFailure(messages, userMessageId) {
12207
- const classified = messageFailure(messages, userMessageId);
12208
- if (classified != null) return classified;
12209
12620
  const reply = findLastAssistantReplyFor(messages, userMessageId);
12210
- const hasProvider = await this.hasAnyConfiguredProvider();
12211
- return applyZeroProviderFallback(
12621
+ const errorShape = extractReplyErrorShape(reply);
12622
+ const classified = messageFailure(messages, userMessageId);
12623
+ if (classified != null) return { classification: classified, errorShape };
12624
+ const classification = applyZeroProviderFallback(
12212
12625
  classified,
12213
- hasProvider,
12626
+ await this.hasAnyConfiguredProvider(),
12214
12627
  reply?.info?.providerID ?? null,
12215
12628
  reply?.info?.modelID ?? null
12216
12629
  );
12630
+ return { classification, errorShape };
12217
12631
  }
12218
12632
  async recordSubagentModelAuthFailure(failure, conversationId, messageId) {
12219
12633
  const providerId = failure.providerId ?? "(unknown)";
@@ -12771,7 +13185,7 @@ function commandError2(result) {
12771
13185
  return result.stderr.trim() || `process exited with code ${result.code ?? "null"}`;
12772
13186
  }
12773
13187
  var runCommand2 = (command, args, opts) => {
12774
- return new Promise((resolve4) => {
13188
+ return new Promise((resolve5) => {
12775
13189
  let child;
12776
13190
  let stdout = "";
12777
13191
  let stderr = "";
@@ -12781,7 +13195,7 @@ var runCommand2 = (command, args, opts) => {
12781
13195
  if (settled) return;
12782
13196
  settled = true;
12783
13197
  if (timer.handle) clearTimeout(timer.handle);
12784
- resolve4(result);
13198
+ resolve5(result);
12785
13199
  };
12786
13200
  try {
12787
13201
  child = spawn5(command, args, { env: opts.env, stdio: ["ignore", "pipe", "pipe"] });
@@ -12836,7 +13250,9 @@ async function installRunnerSecret({
12836
13250
  }) {
12837
13251
  const arn = env.RUNNER_SECRET_ARN?.trim();
12838
13252
  if (!arn) {
12839
- log3("runner secret is not configured; continuing without GitHub and MCP credentials");
13253
+ if (!env.GH_TOKEN) {
13254
+ log3("runner secret is not configured; continuing without GitHub and MCP credentials");
13255
+ }
12840
13256
  return false;
12841
13257
  }
12842
13258
  const result = await (commandRunner ?? runCommand2)(
@@ -13035,7 +13451,7 @@ async function configureGitHubAccess({ env, log: log3 }) {
13035
13451
  // src/lib/opencode/config-overlay.ts
13036
13452
  import { execFileSync as execFileSync2 } from "node:child_process";
13037
13453
  import { copyFileSync, existsSync as existsSync2, statSync as statSync6 } from "node:fs";
13038
- import { isAbsolute as isAbsolute2, join as join10, resolve as resolve3 } from "node:path";
13454
+ import { isAbsolute as isAbsolute3, join as join11, resolve as resolve4 } from "node:path";
13039
13455
  function isFile(filePath) {
13040
13456
  return existsSync2(filePath) && statSync6(filePath).isFile();
13041
13457
  }
@@ -13048,8 +13464,8 @@ function applyRunnerOpenCodeConfig({
13048
13464
  log3("runner OpenCode config is not configured; using the baked project config", "debug");
13049
13465
  return;
13050
13466
  }
13051
- const source = isAbsolute2(overlayPath) ? overlayPath : resolve3(cwd, overlayPath);
13052
- const target = isFile(join10(cwd, "opencode.jsonc")) ? "opencode.jsonc" : "opencode.json";
13467
+ const source = isAbsolute3(overlayPath) ? overlayPath : resolve4(cwd, overlayPath);
13468
+ const target = isFile(join11(cwd, "opencode.jsonc")) ? "opencode.jsonc" : "opencode.json";
13053
13469
  if (!isFile(source)) {
13054
13470
  log3(
13055
13471
  `RUNNER-OPENCODE-CONFIG-MISSING: ${source} is not a file; headless turns will wedge on the first external-directory permission prompt (#563)`,
@@ -13057,7 +13473,7 @@ function applyRunnerOpenCodeConfig({
13057
13473
  );
13058
13474
  return;
13059
13475
  }
13060
- copyFileSync(source, join10(cwd, target));
13476
+ copyFileSync(source, join11(cwd, target));
13061
13477
  try {
13062
13478
  execFileSync2("git", ["-C", cwd, "update-index", "--skip-worktree", target], {
13063
13479
  stdio: "ignore"
@@ -13066,7 +13482,7 @@ function applyRunnerOpenCodeConfig({
13066
13482
  const detail = error2 instanceof Error ? error2.message : String(error2);
13067
13483
  log3(`could not mark ${target} skip-worktree: ${detail}; it may show as a local change`, "warn");
13068
13484
  }
13069
- log3(`Applied runner OpenCode config ${source} to ${join10(cwd, target)}`);
13485
+ log3(`Applied runner OpenCode config ${source} to ${join11(cwd, target)}`);
13070
13486
  }
13071
13487
 
13072
13488
  // src/lib/credential-sync.ts
@@ -13084,14 +13500,14 @@ function errorMessage2(error2) {
13084
13500
  return error2 instanceof Error ? error2.message : String(error2);
13085
13501
  }
13086
13502
  function waitForSettlement(promise, timeoutMs) {
13087
- return new Promise((resolve4) => {
13503
+ return new Promise((resolve5) => {
13088
13504
  let settled = false;
13089
13505
  const timer = setTimeout(() => finish(false), Math.max(0, timeoutMs));
13090
13506
  const finish = (value) => {
13091
13507
  if (settled) return;
13092
13508
  settled = true;
13093
13509
  clearTimeout(timer);
13094
- resolve4(value);
13510
+ resolve5(value);
13095
13511
  };
13096
13512
  promise.then(
13097
13513
  () => finish(true),
@@ -13342,8 +13758,8 @@ function resolveFileSyncDirectories(raw, homeDir) {
13342
13758
  if (trimmed === "") {
13343
13759
  throw new Error("--enable-file-sync-to requires a directory path (got an empty value)");
13344
13760
  }
13345
- const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join11(homeDir, trimmed.slice(2)) : trimmed;
13346
- if (!isAbsolute3(expanded)) {
13761
+ const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join12(homeDir, trimmed.slice(2)) : trimmed;
13762
+ if (!isAbsolute4(expanded)) {
13347
13763
  throw new Error(`--enable-file-sync-to requires an absolute directory path; got "${entry}"`);
13348
13764
  }
13349
13765
  const normalized = resolvePath2(expanded);
@@ -13443,8 +13859,7 @@ function resolveMaxActiveSessions(options, env = process.env) {
13443
13859
  function meetsThreshold(state, level) {
13444
13860
  return LOG_LEVELS[level] >= LOG_LEVELS[state.logLevel];
13445
13861
  }
13446
- function log2(state, message, level = "info") {
13447
- if (!meetsThreshold(state, level)) return;
13862
+ function writeConsoleLog(state, message, level) {
13448
13863
  if (state.json) {
13449
13864
  console.log(
13450
13865
  JSON.stringify({
@@ -13453,10 +13868,18 @@ function log2(state, message, level = "info") {
13453
13868
  message
13454
13869
  })
13455
13870
  );
13456
- } else if (!state.interactive) {
13457
- const prefix = level === "error" ? chalk7.red("\u2717") : level === "warn" ? chalk7.yellow("!") : level === "debug" ? chalk7.dim("\xB7") : chalk7.green("\u2022");
13458
- console.log(`${prefix} ${message}`);
13871
+ return;
13459
13872
  }
13873
+ const prefix = level === "error" ? chalk7.red("\u2717") : level === "warn" ? chalk7.yellow("!") : level === "debug" ? chalk7.dim("\xB7") : chalk7.green("\u2022");
13874
+ console.log(`${prefix} ${message}`);
13875
+ }
13876
+ function log2(state, message, level = "info") {
13877
+ if (!meetsThreshold(state, level)) return;
13878
+ if (state.json || !state.interactive) writeConsoleLog(state, message, level);
13879
+ }
13880
+ function logLocalOnly(state, message, level = "info") {
13881
+ if (!meetsThreshold(state, level)) return;
13882
+ writeConsoleLog(state, message, level);
13460
13883
  }
13461
13884
  function logActivity(state, entry) {
13462
13885
  const level = entry.level ?? (entry.type === "error" ? "error" : "info");
@@ -13657,6 +14080,8 @@ async function driveChannels(state, driver) {
13657
14080
  let lastSeenAppliedFiles = driver.fileSyncActivity().appliedFiles;
13658
14081
  let lastSeenClaudeApplies = driver.fileSyncActivity().claudeCredentialApplies;
13659
14082
  let lastSeenOpencodeAuthApplies = driver.fileSyncActivity().opencodeAuthApplyCount;
14083
+ const stayAwakeHolds = () => state.stayAwakeUntilMs !== null && Date.now() < state.stayAwakeUntilMs;
14084
+ let stayAwakeSuppressionLogged = false;
13660
14085
  while (state.running) {
13661
14086
  const cycleStartedAtMs = performance.now();
13662
14087
  let idleThisCycle = false;
@@ -13758,7 +14183,7 @@ async function driveChannels(state, driver) {
13758
14183
  }
13759
14184
  }
13760
14185
  }
13761
- await new Promise((resolve4) => setTimeout(resolve4, CHANNEL_POLL_INTERVAL_MS));
14186
+ await new Promise((resolve5) => setTimeout(resolve5, CHANNEL_POLL_INTERVAL_MS));
13762
14187
  const cycleMs = performance.now() - cycleStartedAtMs;
13763
14188
  if (idleThisCycle) idleMs += cycleMs;
13764
14189
  if (unreachableThisCycle) unreachableMs += cycleMs;
@@ -13771,15 +14196,27 @@ async function driveChannels(state, driver) {
13771
14196
  if (state.interactive) displayStatus(state);
13772
14197
  break;
13773
14198
  }
13774
- if (state.idleTimeout !== null && idlePolls >= 2 && idleMs > state.idleTimeout * 1e3) {
14199
+ if (state.idleTimeout !== null && idlePolls >= 2 && idleMs > state.idleTimeout * 1e3 && !stayAwakeHolds()) {
13775
14200
  logActivity(state, { type: "info", message: "Idle timeout reached" });
13776
14201
  if (state.interactive) displayStatus(state);
13777
14202
  break;
13778
14203
  }
14204
+ if (state.idleTimeout !== null && idlePolls >= 2 && idleMs > state.idleTimeout * 1e3 && stayAwakeHolds()) {
14205
+ if (!stayAwakeSuppressionLogged) {
14206
+ stayAwakeSuppressionLogged = true;
14207
+ logActivity(state, {
14208
+ type: "info",
14209
+ message: "Idle, but staying awake until the requested minimum passes"
14210
+ });
14211
+ }
14212
+ }
13779
14213
  }
13780
14214
  }
13781
14215
  var SESSION_CLEANUP_FIRST_SWEEP_MS = 1e4;
13782
14216
  var SESSION_CLEANUP_MAX_DELETES_PER_SWEEP = 100;
14217
+ var SESSION_CLEANUP_MAX_ISOLATED_DELETE_FAILURES = 2;
14218
+ var SESSION_CLEANUP_GIVE_UP_AFTER_FAILURES = 2;
14219
+ var MAX_SESSION_DELETE_BODY_LENGTH = 200;
13783
14220
  function shouldWarnForReclaimSkip(reason) {
13784
14221
  if (reason !== "sqlite-unavailable" && reason !== "disk-exhaustion") return false;
13785
14222
  const version2 = /^v(\d+)\.(\d+)\.(\d+)$/.exec(process.version);
@@ -13790,7 +14227,7 @@ function shouldWarnForReclaimSkip(reason) {
13790
14227
  return major > 22 || major === 22 && (minor > 13 || minor === 13 && patch >= 0);
13791
14228
  }
13792
14229
  function sessionDbPath() {
13793
- return join11(homedir7(), ".local", "share", "opencode", "opencode.db");
14230
+ return join12(homedir7(), ".local", "share", "opencode", "opencode.db");
13794
14231
  }
13795
14232
  function logSessionCleanupActivity(state, phase, entry) {
13796
14233
  logActivity(state, {
@@ -13867,8 +14304,12 @@ async function runSweep(state, driver, config) {
13867
14304
  protectedIds: protectedNow
13868
14305
  }
13869
14306
  );
13870
- const deleteCandidates = toDelete.slice(0, SESSION_CLEANUP_MAX_DELETES_PER_SWEEP);
13871
- remaining = toDelete.length - deleteCandidates.length;
14307
+ const eligibleToDelete = toDelete.filter(
14308
+ (id) => (state.sessionDeleteFailures.get(id)?.isolatedFailures ?? 0) < SESSION_CLEANUP_GIVE_UP_AFTER_FAILURES
14309
+ );
14310
+ const deleteCandidates = eligibleToDelete.slice(0, SESSION_CLEANUP_MAX_DELETES_PER_SWEEP);
14311
+ remaining = eligibleToDelete.length - deleteCandidates.length;
14312
+ const answeredFailures = [];
13872
14313
  protectedNow = driver.protectedSessionIds();
13873
14314
  for (const id of deleteCandidates) {
13874
14315
  if (protectedNow.has(id)) {
@@ -13891,8 +14332,44 @@ async function runSweep(state, driver, config) {
13891
14332
  if (statusClass === 4) failed4xx++;
13892
14333
  else if (statusClass === 5) failed5xx++;
13893
14334
  else failedOtherStatus++;
14335
+ answeredFailures.push({
14336
+ id,
14337
+ status: outcome.status,
14338
+ ...outcome.body !== void 0 ? { body: outcome.body } : {}
14339
+ });
13894
14340
  }
13895
14341
  }
14342
+ const givenUpFailures = [];
14343
+ if (failed > SESSION_CLEANUP_MAX_ISOLATED_DELETE_FAILURES) {
14344
+ for (const { id } of answeredFailures) state.sessionDeleteFailures.delete(id);
14345
+ } else {
14346
+ for (const failure of answeredFailures) {
14347
+ const previous = state.sessionDeleteFailures.get(failure.id);
14348
+ const record = previous?.status === failure.status ? { status: failure.status, isolatedFailures: previous.isolatedFailures + 1 } : { status: failure.status, isolatedFailures: 1 };
14349
+ state.sessionDeleteFailures.set(failure.id, record);
14350
+ if (record.isolatedFailures >= SESSION_CLEANUP_GIVE_UP_AFTER_FAILURES) {
14351
+ givenUpFailures.push(failure);
14352
+ }
14353
+ }
14354
+ }
14355
+ for (const failure of givenUpFailures) {
14356
+ const excerpt = redactDiagnosticText(failure.body ?? "(no response body)").slice(
14357
+ 0,
14358
+ MAX_SESSION_DELETE_BODY_LENGTH
14359
+ );
14360
+ logSessionCleanupActivity(state, "sweep", {
14361
+ type: "info",
14362
+ level: "warn",
14363
+ message: `Session cleanup: gave up on session ${failure.id} after ${SESSION_CLEANUP_GIVE_UP_AFTER_FAILURES} isolated delete failures (status ${failure.status}): ${excerpt}`,
14364
+ metadata: {
14365
+ outcome: "session-delete-given-up",
14366
+ session_id: failure.id,
14367
+ status: failure.status,
14368
+ body_excerpt: excerpt,
14369
+ given_up_count: givenUpFailures.length
14370
+ }
14371
+ });
14372
+ }
13896
14373
  const failedNote = failed > 0 ? `, failed ${failed}` : "";
13897
14374
  const skippedNote = skippedNewlyActive > 0 ? `, skipped ${skippedNewlyActive} newly-active` : "";
13898
14375
  const remainingNote = remaining > 0 ? `, remaining ${remaining}` : "";
@@ -13913,21 +14390,31 @@ async function runSweep(state, driver, config) {
13913
14390
  sessions_remaining: remaining,
13914
14391
  ...enumerationReason !== null ? { session_enumeration_reason: enumerationReason } : {}
13915
14392
  };
14393
+ const protectedForReclaim = driver.protectedSessionIds();
13916
14394
  const reclaimResult = await reclaimSessionDbSpace({
13917
14395
  dbPath: sessionDbPath(),
13918
14396
  chunkPages: SESSION_DB_RECLAIM_CHUNK_PAGES,
13919
14397
  pageCeiling: SESSION_DB_RECLAIM_PAGE_CEILING,
13920
14398
  timeBudgetMs: SESSION_DB_RECLAIM_TIME_BUDGET_MS,
13921
- allowFullVacuum: protectedNow.size === 0 && !state.sessionDbProvenanceAnomaly
14399
+ hasLiveTurn: protectedForReclaim.size > 0,
14400
+ hasProvenanceAnomaly: state.sessionDbProvenanceAnomaly
13922
14401
  });
13923
14402
  if (reclaimResult.ok) {
13924
14403
  state.sessionStoreHealth.observeWritable();
13925
14404
  const beforeMib = (reclaimResult.beforeBytes / 1024 / 1024).toFixed(1);
13926
14405
  const afterMib = (reclaimResult.afterBytes / 1024 / 1024).toFixed(1);
13927
14406
  const checkpointNote = reclaimResult.checkpoint.busy ? ` (on-disk file truncation deferred: checkpoint busy, ${reclaimResult.checkpoint.log} WAL frames pending)` : "";
14407
+ const loopElapsedMs = Math.max(
14408
+ 0,
14409
+ reclaimResult.elapsedMs - reclaimResult.checkpointElapsedMs
14410
+ );
14411
+ const reclaimIsSlow = reclaimResult.elapsedMs >= 4 * SESSION_DB_RECLAIM_TIME_BUDGET_MS;
14412
+ const perPageNote = reclaimResult.pagesReclaimed > 0 ? `, per-page ${(loopElapsedMs / reclaimResult.pagesReclaimed).toFixed(2)} ms/page` : "";
14413
+ const slowReclaimNote = reclaimIsSlow ? ` (slow reclaim: total elapsed ${reclaimResult.elapsedMs} ms, checkpoint ${reclaimResult.checkpointElapsedMs} ms, loop ${loopElapsedMs} ms, budget ${SESSION_DB_RECLAIM_TIME_BUDGET_MS} ms${perPageNote})` : "";
13928
14414
  logSessionCleanupActivity(state, "sweep", {
13929
14415
  type: "info",
13930
- message: `Session cleanup: reclaimed session-db space (${reclaimResult.mode}): ${beforeMib} MiB -> ${afterMib} MiB (stopped by ${reclaimResult.stoppedBy}; freelist ${reclaimResult.freelistBefore} -> ${reclaimResult.freelistAfter} pages)` + checkpointNote,
14416
+ level: reclaimIsSlow ? "warn" : "info",
14417
+ message: `Session cleanup: reclaimed session-db space (${reclaimResult.mode}): ${beforeMib} MiB -> ${afterMib} MiB (stopped by ${reclaimResult.stoppedBy}; freelist ${reclaimResult.freelistBefore} -> ${reclaimResult.freelistAfter} pages)` + checkpointNote + slowReclaimNote,
13931
14418
  metadata: {
13932
14419
  outcome: "reclaimed",
13933
14420
  mode: reclaimResult.mode,
@@ -13940,6 +14427,7 @@ async function runSweep(state, driver, config) {
13940
14427
  freelist_after: reclaimResult.freelistAfter,
13941
14428
  pages_reclaimed: reclaimResult.pagesReclaimed,
13942
14429
  reclaim_elapsed_ms: reclaimResult.elapsedMs,
14430
+ checkpoint_elapsed_ms: reclaimResult.checkpointElapsedMs,
13943
14431
  ...sessionMetadata
13944
14432
  }
13945
14433
  });
@@ -14050,10 +14538,12 @@ function scheduleUsageReporting(state, params) {
14050
14538
  let phase = "dormant";
14051
14539
  let rearmRequested = false;
14052
14540
  const armProbe = () => {
14541
+ if (!state.running) return;
14053
14542
  phase = "probe-pending";
14054
14543
  params.setTimer(setTimeout(() => void tick(true), params.firstDelayMs()));
14055
14544
  };
14056
14545
  const scheduleNextTick = () => {
14546
+ if (!state.running) return;
14057
14547
  if (rearmRequested) {
14058
14548
  rearmRequested = false;
14059
14549
  armProbe();
@@ -14087,6 +14577,7 @@ function scheduleUsageReporting(state, params) {
14087
14577
  phase = "tick-in-flight";
14088
14578
  try {
14089
14579
  const usage = await params.fetchUsage();
14580
+ if (!state.running) return;
14090
14581
  const result = await params.report(usage);
14091
14582
  if (result.ok) {
14092
14583
  if (consecutiveFailures > 0) {
@@ -14225,6 +14716,7 @@ function scheduleResourceUsageReporting(state, options) {
14225
14716
  message: lowDiskDecision.warning
14226
14717
  });
14227
14718
  }
14719
+ if (!state.running) return;
14228
14720
  const result = await reportResourceUsage(state.agentId, state.authHeader, usage);
14229
14721
  if (result.ok) {
14230
14722
  if (consecutiveFailures > 0) {
@@ -14257,7 +14749,9 @@ function scheduleResourceUsageReporting(state, options) {
14257
14749
  message: `Resource usage reporting failed: ${message}${failureStreakSuffix(consecutiveFailures)}`
14258
14750
  });
14259
14751
  } finally {
14260
- state.resourceUsageTimer = setTimeout(() => void tick(), usageReportDelayMs());
14752
+ if (state.running) {
14753
+ state.resourceUsageTimer = setTimeout(() => void tick(), usageReportDelayMs());
14754
+ }
14261
14755
  }
14262
14756
  };
14263
14757
  state.resourceUsageTimer = setTimeout(() => void tick(), firstReportDelayMs());
@@ -14419,8 +14913,8 @@ async function beginGracefulShutdown(state, trigger) {
14419
14913
  return true;
14420
14914
  }
14421
14915
  );
14422
- const timedOut = new Promise((resolve4) => {
14423
- timer = setTimeout(() => resolve4(false), telemetryBudgetMs);
14916
+ const timedOut = new Promise((resolve5) => {
14917
+ timer = setTimeout(() => resolve5(false), telemetryBudgetMs);
14424
14918
  });
14425
14919
  if (!await Promise.race([flushed, timedOut])) {
14426
14920
  log2(state, `Telemetry flush exceeded ${telemetryBudgetMs}ms \u2014 exiting anyway`, "warn");
@@ -14460,6 +14954,8 @@ async function run(options) {
14460
14954
  port: options.port ?? 4096,
14461
14955
  conversationFilter: options.conversation ?? null,
14462
14956
  idleTimeout: options.idleTimeout ?? null,
14957
+ stayAwakeSeconds: null,
14958
+ stayAwakeUntilMs: null,
14463
14959
  json: options.json ?? false,
14464
14960
  interactive,
14465
14961
  logLevel,
@@ -14483,6 +14979,7 @@ async function run(options) {
14483
14979
  messageCount: 0,
14484
14980
  lastProxiedActivityAt: null,
14485
14981
  sessionCleanupTimers: [],
14982
+ sessionDeleteFailures: /* @__PURE__ */ new Map(),
14486
14983
  claudeUsageTimer: null,
14487
14984
  claudeUsageRearm: null,
14488
14985
  openaiUsageTimer: null,
@@ -14648,6 +15145,17 @@ async function run(options) {
14648
15145
  }
14649
15146
  spinner?.succeed(`Runner: ${validation.agent.name || state.agentId}`);
14650
15147
  state.agentName = validation.agent.name;
15148
+ const requestedStayAwakeSeconds = validation.agent?.wake_stay_awake_seconds;
15149
+ if (typeof requestedStayAwakeSeconds === "number" && Number.isFinite(requestedStayAwakeSeconds) && requestedStayAwakeSeconds > 0) {
15150
+ state.stayAwakeSeconds = requestedStayAwakeSeconds;
15151
+ } else if (requestedStayAwakeSeconds !== void 0 && requestedStayAwakeSeconds !== null) {
15152
+ state.stayAwakeSeconds = null;
15153
+ log2(
15154
+ state,
15155
+ `Ignoring invalid wake_stay_awake_seconds (type: ${typeof requestedStayAwakeSeconds})`,
15156
+ "warn"
15157
+ );
15158
+ }
14651
15159
  const microvmId = process.env.MICROVM_ID?.trim();
14652
15160
  if (microvmId) {
14653
15161
  const reported = await reportMicrovmId(state.agentId, state.authHeader, microvmId);
@@ -14691,23 +15199,33 @@ async function run(options) {
14691
15199
  );
14692
15200
  }
14693
15201
  }
14694
- if (options.restoreRunnerCredentials) {
14695
- log2(state, "Restoring runner credentials before starting OpenCode");
14696
- const credentialContext = {
14697
- env: process.env,
14698
- log: (message, level = "info") => {
14699
- if (level === "error") {
14700
- logActivity(state, { type: "error", error: message });
14701
- } else {
14702
- logActivity(state, { type: "info", level, message });
14703
- }
15202
+ const credentialContext = {
15203
+ env: process.env,
15204
+ log: (message, level = "info") => {
15205
+ if (level === "error") {
15206
+ logActivity(state, { type: "error", error: message });
15207
+ } else {
15208
+ logActivity(state, { type: "info", level, message });
14704
15209
  }
14705
- };
14706
- const githubTokenPopulated = await installRunnerSecret(credentialContext);
15210
+ }
15211
+ };
15212
+ const githubTokenPopulated = await installRunnerSecret(credentialContext);
15213
+ if (options.restoreRunnerCredentials) {
14707
15214
  await restoreCredentialStores(credentialContext);
14708
- if (githubTokenPopulated) await configureGitHubAccess(credentialContext);
14709
15215
  }
15216
+ if (githubTokenPopulated) await configureGitHubAccess(credentialContext);
14710
15217
  state.credentialSync?.arm();
15218
+ const dependencyInstallDiagnosticReporter = createDependencyInstallDiagnosticReporter({
15219
+ context: {
15220
+ homeDir: homedir7(),
15221
+ cwd: process.cwd(),
15222
+ microvmId: process.env.MICROVM_ID?.trim(),
15223
+ euid: process.getuid?.(),
15224
+ egid: process.getgid?.()
15225
+ },
15226
+ emitEvent: (message) => logActivity(state, { type: "info", level: "warn", message }),
15227
+ emitLocal: (message) => logLocalOnly(state, message, "warn")
15228
+ });
14711
15229
  const openCodeActivityForwarder = createOpenCodeActivityForwarder(
14712
15230
  () => ({
14713
15231
  agentId: state.agentId,
@@ -14718,7 +15236,8 @@ async function run(options) {
14718
15236
  if (cause !== null && sessionId !== null) {
14719
15237
  state.sessionStoreHealth.observeCause(sessionId, cause);
14720
15238
  }
14721
- }
15239
+ },
15240
+ dependencyInstallDiagnosticReporter
14722
15241
  );
14723
15242
  const openCodeLogTail = tailOpenCodeLogFile(
14724
15243
  resolveOpenCodeLogPath(homedir7(), process.env),
@@ -15051,6 +15570,13 @@ async function run(options) {
15051
15570
  type: "info",
15052
15571
  message: connectionMessage
15053
15572
  });
15573
+ if (!isReconnect && state.stayAwakeSeconds !== null && state.stayAwakeUntilMs === null) {
15574
+ state.stayAwakeUntilMs = Date.now() + state.stayAwakeSeconds * 1e3;
15575
+ logActivity(state, {
15576
+ type: "info",
15577
+ message: `Staying awake for at least ${state.stayAwakeSeconds}s as requested by the wake`
15578
+ });
15579
+ }
15054
15580
  if (options.tunnelReadyFile) {
15055
15581
  const marker = writeTunnelReadyMarker(options.tunnelReadyFile, agentId);
15056
15582
  if (marker.ok) {
@@ -15185,6 +15711,7 @@ async function run(options) {
15185
15711
  if (error2.message === "Unauthorized") tunnelSpinner?.fail("Unauthorized");
15186
15712
  throw error2;
15187
15713
  }
15714
+ if (!state.running) return;
15188
15715
  scheduleSessionCleanup(state, channelDriver, options);
15189
15716
  state.claudeUsageRearm = scheduleClaudeUsageReporting(state, options);
15190
15717
  state.openaiUsageRearm = scheduleUsageReporting(state, {