@evident-ai/cli 3.5.2-dev.fbf25b4 → 3.5.2-dev.fdeb718

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.fbf25b4" : void 0) ?? process.env.npm_package_version ?? "unknown";
1329
+ var CLI_VERSION = (true ? "3.5.2-dev.fdeb718" : 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--) {
@@ -3426,23 +3783,49 @@ async function readSessionErrorStream(port, options, client) {
3426
3783
  if (reader) void reader.cancel().catch(() => void 0);
3427
3784
  }
3428
3785
  }
3429
- async function reloadProviderCache(port, client) {
3430
- if (client?.version === "v2") return;
3786
+ async function disposeAndReloadProviderConfig(port, client) {
3787
+ if (client?.version === "v2") return { outcome: "skipped_v2" };
3431
3788
  try {
3432
- const res = await requestWithClient(port, client, "/config", {
3433
- method: "PATCH",
3434
- headers: { "Content-Type": "application/json" },
3435
- body: JSON.stringify({})
3436
- });
3789
+ const res = await requestWithClient(
3790
+ port,
3791
+ client,
3792
+ "/config",
3793
+ {
3794
+ method: "PATCH",
3795
+ headers: { "Content-Type": "application/json" },
3796
+ body: JSON.stringify({})
3797
+ },
3798
+ { allowStatuses: ALL_HTTP_STATUSES }
3799
+ );
3437
3800
  if (!res.ok) {
3438
3801
  console.error(
3439
- `[reloadProviderCache] PATCH /config returned HTTP ${res.status} (port ${port})`
3802
+ `[disposeAndReloadProviderConfig] PATCH /config returned HTTP ${res.status} (port ${port})`
3440
3803
  );
3804
+ return { outcome: "failed", status: res.status, detail: null };
3441
3805
  }
3806
+ return { outcome: "reloaded" };
3442
3807
  } catch (err) {
3443
3808
  console.error(
3444
- `[reloadProviderCache] PATCH /config failed (port ${port}): ${err instanceof Error ? err.message : String(err)}`
3809
+ `[disposeAndReloadProviderConfig] PATCH /config failed (port ${port}): ${err instanceof Error ? err.message : String(err)}`
3445
3810
  );
3811
+ return {
3812
+ outcome: "failed",
3813
+ status: null,
3814
+ detail: err instanceof Error ? err.message : String(err)
3815
+ };
3816
+ }
3817
+ }
3818
+ async function probeOpenCodeRequestReadiness(port, client) {
3819
+ try {
3820
+ const res = await requestWithClient(port, client, "/config", void 0, {
3821
+ allowStatuses: ALL_HTTP_STATUSES
3822
+ });
3823
+ const body = await res.text();
3824
+ return { ok: res.ok, status: res.status, bodyEmpty: body.trim().length === 0, detail: null };
3825
+ } catch (err) {
3826
+ const detail = err instanceof Error ? err.message : String(err);
3827
+ console.error(`[probeOpenCodeRequestReadiness] GET /config failed (port ${port}): ${detail}`);
3828
+ return { ok: false, status: null, bodyEmpty: null, detail };
3446
3829
  }
3447
3830
  }
3448
3831
 
@@ -3748,7 +4131,18 @@ async function deleteV2Session(client, sessionId) {
3748
4131
  { method: "DELETE" },
3749
4132
  { allowStatuses: Array.from({ length: 500 }, (_, index) => index + 100) }
3750
4133
  );
3751
- return { ok: response.status >= 200 && response.status < 300, status: response.status };
4134
+ if (response.status >= 200 && response.status < 300) {
4135
+ return { ok: true, status: response.status };
4136
+ }
4137
+ try {
4138
+ const body = await response.text();
4139
+ return body ? { ok: false, status: response.status, body } : { ok: false, status: response.status };
4140
+ } catch (error2) {
4141
+ console.error(
4142
+ `[deleteV2Session] DELETE /api/session/${sessionId} response body read failed for HTTP ${response.status}: ${error2 instanceof Error ? error2.message : String(error2)}`
4143
+ );
4144
+ return { ok: false, status: response.status };
4145
+ }
3752
4146
  } catch (error2) {
3753
4147
  console.error(
3754
4148
  `[deleteV2Session] DELETE /api/session/${sessionId} failed: ${error2 instanceof Error ? error2.message : String(error2)}`
@@ -3924,12 +4318,12 @@ async function readV2SessionErrorStream(client, options) {
3924
4318
 
3925
4319
  // src/lib/opencode/credential-import-v2.ts
3926
4320
  import { readFileSync as readFileSync4 } from "node:fs";
3927
- import { join as join4 } from "node:path";
4321
+ import { join as join5 } from "node:path";
3928
4322
 
3929
4323
  // src/lib/openai-usage.ts
3930
4324
  import { readFileSync as readFileSync3 } from "node:fs";
3931
4325
  import { homedir as homedir3 } from "node:os";
3932
- import { join as join3 } from "node:path";
4326
+ import { join as join4 } from "node:path";
3933
4327
  var CODEX_RESPONSES_URL = "https://chatgpt.com/backend-api/codex/responses";
3934
4328
  var OPENCODE_AUTH_SEGMENTS = [".local", "share", "opencode", "auth.json"];
3935
4329
  var OpenAiUsageError = class extends Error {
@@ -3943,7 +4337,7 @@ function isLocalCredentialProblem2(err) {
3943
4337
  }
3944
4338
  function readOpenCodeChatGptCredentials() {
3945
4339
  try {
3946
- const raw = readFileSync3(join3(homedir3(), ...OPENCODE_AUTH_SEGMENTS), "utf-8");
4340
+ const raw = readFileSync3(join4(homedir3(), ...OPENCODE_AUTH_SEGMENTS), "utf-8");
3947
4341
  let parsed;
3948
4342
  try {
3949
4343
  parsed = JSON.parse(raw);
@@ -4169,13 +4563,13 @@ var INTEGRATION_LIST_RETRY_DELAY_MS = 1e3;
4169
4563
  function isRecord3(value) {
4170
4564
  return typeof value === "object" && value !== null && !Array.isArray(value);
4171
4565
  }
4172
- var sleep2 = (milliseconds) => new Promise((resolve4) => setTimeout(resolve4, milliseconds));
4566
+ var sleep2 = (milliseconds) => new Promise((resolve5) => setTimeout(resolve5, milliseconds));
4173
4567
  function emptyResult(unsupported = [], outcome = "completed") {
4174
4568
  return { outcome, imported: [], alreadyConnected: [], unsupported, failed: [] };
4175
4569
  }
4176
4570
  function readOpenCodeCredentials(homeDir, log3) {
4177
4571
  try {
4178
- const raw = readFileSync4(join4(homeDir, ...OPENCODE_AUTH_SEGMENTS), "utf8");
4572
+ const raw = readFileSync4(join5(homeDir, ...OPENCODE_AUTH_SEGMENTS), "utf8");
4179
4573
  let parsed;
4180
4574
  try {
4181
4575
  parsed = JSON.parse(raw);
@@ -4377,7 +4771,7 @@ async function importOpenCodeV2Credentials({
4377
4771
  import { spawn as spawn2 } from "node:child_process";
4378
4772
  import { mkdirSync, statSync as statSync3, unlinkSync as unlinkSync2, writeFileSync } from "node:fs";
4379
4773
  import { homedir as homedir4 } from "node:os";
4380
- import { dirname as dirname3, resolve as resolvePath } from "node:path";
4774
+ import { dirname as dirname4, resolve as resolvePath } from "node:path";
4381
4775
 
4382
4776
  // src/lib/runner-synchroniser.ts
4383
4777
  import { spawn } from "node:child_process";
@@ -4387,7 +4781,7 @@ function appendError(stderr, error2) {
4387
4781
  ${message}`;
4388
4782
  }
4389
4783
  function runSynchroniser(args, opts) {
4390
- return new Promise((resolve4) => {
4784
+ return new Promise((resolve5) => {
4391
4785
  let child;
4392
4786
  let stdout = "";
4393
4787
  let stderr = "";
@@ -4401,7 +4795,7 @@ function runSynchroniser(args, opts) {
4401
4795
  if (timer.handle) clearTimeout(timer.handle);
4402
4796
  if (abortListener) opts.signal?.removeEventListener("abort", abortListener);
4403
4797
  if (spawnListener) child.removeListener("spawn", spawnListener);
4404
- resolve4(result);
4798
+ resolve5(result);
4405
4799
  };
4406
4800
  try {
4407
4801
  child = spawn("runner-synchroniser", args, {
@@ -4505,7 +4899,7 @@ function clearMarker(options) {
4505
4899
  function markNoReplicate(options, message) {
4506
4900
  if (options.noReplicateMarker) {
4507
4901
  try {
4508
- mkdirSync(dirname3(options.noReplicateMarker), { recursive: true });
4902
+ mkdirSync(dirname4(options.noReplicateMarker), { recursive: true });
4509
4903
  writeFileSync(options.noReplicateMarker, "");
4510
4904
  } catch (error2) {
4511
4905
  options.log(
@@ -4564,7 +4958,7 @@ function parseSynchroniserEnv(stdout) {
4564
4958
  return values;
4565
4959
  }
4566
4960
  function runCommand(command, args, options) {
4567
- return new Promise((resolve4) => {
4961
+ return new Promise((resolve5) => {
4568
4962
  let child;
4569
4963
  let stdout = "";
4570
4964
  let stderr = "";
@@ -4573,7 +4967,7 @@ function runCommand(command, args, options) {
4573
4967
  if (settled) return;
4574
4968
  settled = true;
4575
4969
  if (timer) clearTimeout(timer);
4576
- resolve4(result);
4970
+ resolve5(result);
4577
4971
  };
4578
4972
  try {
4579
4973
  child = spawn2(command, args, {
@@ -4581,7 +4975,7 @@ function runCommand(command, args, options) {
4581
4975
  stdio: ["ignore", "pipe", "pipe"]
4582
4976
  });
4583
4977
  } catch (error2) {
4584
- resolve4({
4978
+ resolve5({
4585
4979
  code: null,
4586
4980
  stdout,
4587
4981
  stderr: error2 instanceof Error ? error2.message : String(error2),
@@ -4660,7 +5054,7 @@ async function ensureLitestreamConfig(options, env) {
4660
5054
  return null;
4661
5055
  }
4662
5056
  try {
4663
- mkdirSync(dirname3(configPath), { recursive: true });
5057
+ mkdirSync(dirname4(configPath), { recursive: true });
4664
5058
  writeFileSync(configPath, rendered.stdout);
4665
5059
  } catch (error2) {
4666
5060
  options.log(
@@ -4927,7 +5321,7 @@ async function restoreAndVerifySessionDb(options) {
4927
5321
  // src/lib/opencode/session-db-provenance.ts
4928
5322
  import { createRequire } from "node:module";
4929
5323
  import { mkdirSync as mkdirSync2, readFileSync as readFileSync5, writeFileSync as writeFileSync2 } from "node:fs";
4930
- import { dirname as dirname4, join as join5 } from "node:path";
5324
+ import { dirname as dirname5, join as join6 } from "node:path";
4931
5325
  var require2 = createRequire(import.meta.url);
4932
5326
  function readSessionDbMigrationIds(dbPath) {
4933
5327
  let db;
@@ -4964,7 +5358,7 @@ function readSessionDbMigrationIds(dbPath) {
4964
5358
  }
4965
5359
  function sessionDbProvenanceStatePath(homeDir, env) {
4966
5360
  const override = env.EVIDENT_SESSION_DB_PROVENANCE_STATE?.trim();
4967
- return override || join5(homeDir, ".local", "state", "evident", "session-db-provenance.json");
5361
+ return override || join6(homeDir, ".local", "state", "evident", "session-db-provenance.json");
4968
5362
  }
4969
5363
  function loadSessionDbProvenanceState(path) {
4970
5364
  let value;
@@ -4993,7 +5387,7 @@ function loadSessionDbProvenanceState(path) {
4993
5387
  }
4994
5388
  function saveSessionDbProvenanceState(path, state) {
4995
5389
  try {
4996
- mkdirSync2(dirname4(path), { recursive: true });
5390
+ mkdirSync2(dirname5(path), { recursive: true });
4997
5391
  writeFileSync2(path, `${JSON.stringify(state, null, 2)}
4998
5392
  `, "utf8");
4999
5393
  } catch (error2) {
@@ -5084,7 +5478,7 @@ async function stopProcessAndWait(child, timeoutMs, sendTerm, sendKill) {
5084
5478
  if (child.exitCode !== null || child.signalCode !== null) {
5085
5479
  return { outcome: "exited", code: child.exitCode, signal: child.signalCode };
5086
5480
  }
5087
- return new Promise((resolve4, reject) => {
5481
+ return new Promise((resolve5, reject) => {
5088
5482
  let forced = false;
5089
5483
  let settled = false;
5090
5484
  const timer = setTimeout(() => {
@@ -5104,7 +5498,7 @@ async function stopProcessAndWait(child, timeoutMs, sendTerm, sendKill) {
5104
5498
  settled = true;
5105
5499
  clearTimeout(timer);
5106
5500
  child.removeListener("exit", onExit);
5107
- resolve4(result);
5501
+ resolve5(result);
5108
5502
  };
5109
5503
  const fail = (error2) => {
5110
5504
  if (settled) return;
@@ -5580,7 +5974,7 @@ function selectSessionsToDelete(sessions, opts) {
5580
5974
  );
5581
5975
  }
5582
5976
  var DEFAULT_INTERVAL = "1h";
5583
- function resolve(flag, envValue, fallback) {
5977
+ function resolve2(flag, envValue, fallback) {
5584
5978
  return flag ?? envValue ?? fallback;
5585
5979
  }
5586
5980
  function parseMaxCount(input) {
@@ -5596,9 +5990,9 @@ function parseMaxCount(input) {
5596
5990
  }
5597
5991
  function resolveSessionCleanupConfig(flags, env = process.env) {
5598
5992
  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(
5993
+ const maxAgeRaw = resolve2(flags.maxAge, env.EVIDENT_SESSION_CLEANUP_MAX_AGE);
5994
+ const maxCountRaw = resolve2(flags.maxCount, env.EVIDENT_SESSION_CLEANUP_MAX_COUNT);
5995
+ const intervalRaw = resolve2(
5602
5996
  flags.interval,
5603
5997
  env.EVIDENT_SESSION_CLEANUP_INTERVAL,
5604
5998
  DEFAULT_INTERVAL
@@ -5638,10 +6032,10 @@ function resolveSessionCleanupConfig(flags, env = process.env) {
5638
6032
 
5639
6033
  // src/lib/opencode/session-db-size.ts
5640
6034
  import { statSync as statSync4 } from "node:fs";
5641
- import { join as join6 } from "node:path";
6035
+ import { join as join7 } from "node:path";
5642
6036
  var LARGE_DB_THRESHOLD_BYTES = 268435456;
5643
6037
  function statSessionDbBytes(homeDir) {
5644
- const dbPath = join6(homeDir, ".local", "share", "opencode", "opencode.db");
6038
+ const dbPath = join7(homeDir, ".local", "share", "opencode", "opencode.db");
5645
6039
  try {
5646
6040
  return statSync4(dbPath).size;
5647
6041
  } catch (err) {
@@ -5671,12 +6065,12 @@ function buildSessionStoreSizeWarning(input) {
5671
6065
  // src/lib/opencode/log-tail.ts
5672
6066
  import { statSync as statSync5 } from "node:fs";
5673
6067
  import { homedir as homedir5 } from "node:os";
5674
- import { join as join7 } from "node:path";
6068
+ import { join as join8 } from "node:path";
5675
6069
  import { open as open2, stat } from "node:fs/promises";
5676
6070
  var DEFAULT_POLL_INTERVAL_MS = 1e3;
5677
6071
  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");
6072
+ const dataDir = env.XDG_DATA_HOME || join8(homeDir, ".local", "share");
6073
+ return join8(dataDir, "opencode", "log", "opencode.log");
5680
6074
  }
5681
6075
  function isEnoent(error2) {
5682
6076
  return error2?.code === "ENOENT";
@@ -5831,8 +6225,8 @@ var StreamForwarder = class {
5831
6225
  pauseStream(sid, stream) {
5832
6226
  if (!stream.paused) {
5833
6227
  stream.paused = true;
5834
- stream.pausePromise = new Promise((resolve4) => {
5835
- stream.resume = resolve4;
6228
+ stream.pausePromise = new Promise((resolve5) => {
6229
+ stream.resume = resolve5;
5836
6230
  });
5837
6231
  }
5838
6232
  if (stream.pauseTimer !== null) clearTimeout(stream.pauseTimer);
@@ -5899,12 +6293,12 @@ var StreamForwarder = class {
5899
6293
  let endBody;
5900
6294
  if (has_body) {
5901
6295
  const chunks = [];
5902
- bodyPromise = new Promise((resolve4) => {
6296
+ bodyPromise = new Promise((resolve5) => {
5903
6297
  pushBody = (buf) => {
5904
6298
  chunks.push(buf);
5905
6299
  };
5906
6300
  endBody = () => {
5907
- resolve4(Buffer.concat(chunks));
6301
+ resolve5(Buffer.concat(chunks));
5908
6302
  };
5909
6303
  });
5910
6304
  }
@@ -6075,7 +6469,7 @@ function connectTunnel(options) {
6075
6469
  } = options;
6076
6470
  const tunnelUrl = getTunnelUrlConfig();
6077
6471
  const url = `${tunnelUrl}/tunnel/${agentId}/connect`;
6078
- return new Promise((resolve4, reject) => {
6472
+ return new Promise((resolve5, reject) => {
6079
6473
  const ws = new WebSocket2(url, {
6080
6474
  headers: {
6081
6475
  Authorization: authHeader,
@@ -6184,7 +6578,7 @@ function connectTunnel(options) {
6184
6578
  forwarder.setBinaryFramesSupported(message.binary_frames === true);
6185
6579
  const connectedAgentId = message.agent_id ?? agentId;
6186
6580
  onConnected?.(connectedAgentId);
6187
- resolve4({
6581
+ resolve5({
6188
6582
  ws,
6189
6583
  close: () => ws.close(1e3, "CLI shutdown")
6190
6584
  });
@@ -6739,12 +7133,12 @@ function createSessionStoreHealth(options = {}) {
6739
7133
  import { homedir as homedir6 } from "node:os";
6740
7134
 
6741
7135
  // src/lib/runner-file-sync.ts
6742
- import { join as join9 } from "node:path";
7136
+ import { join as join10 } from "node:path";
6743
7137
 
6744
7138
  // src/lib/file-push.ts
6745
7139
  import { randomUUID } from "node:crypto";
6746
7140
  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";
7141
+ 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
7142
  var FILE_MODE = 384;
6749
7143
  var DIRECTORY_MODE = 448;
6750
7144
  async function writePushedFile(request2) {
@@ -6775,9 +7169,9 @@ async function writePushedFile(request2) {
6775
7169
  }
6776
7170
  try {
6777
7171
  const { existingAncestor, missingSegments } = await resolveNearestExistingAncestor(
6778
- dirname5(candidate)
7172
+ dirname6(candidate)
6779
7173
  );
6780
- const realTarget = join8(existingAncestor, ...missingSegments, basename(candidate));
7174
+ const realTarget = join9(existingAncestor, ...missingSegments, basename2(candidate));
6781
7175
  const allowedDirectory = await findContainingAllowedDirectory(allowedDirectories, realTarget);
6782
7176
  if (allowedDirectory === null) {
6783
7177
  return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
@@ -6787,8 +7181,8 @@ async function writePushedFile(request2) {
6787
7181
  }
6788
7182
  if (missingSegments.length > 0) {
6789
7183
  await createMissingDirectories(existingAncestor, missingSegments);
6790
- const realParent = await realpath(dirname5(realTarget));
6791
- if (realParent !== dirname5(realTarget) || !contains(allowedDirectory, realTarget)) {
7184
+ const realParent = await realpath(dirname6(realTarget));
7185
+ if (realParent !== dirname6(realTarget) || !contains(allowedDirectory, realTarget)) {
6792
7186
  return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
6793
7187
  path: realTarget,
6794
7188
  bytes,
@@ -6813,15 +7207,15 @@ function expandAndValidate(requestedPath, homeDir) {
6813
7207
  if (requestedPath.trim() === "" || requestedPath.includes("\0")) {
6814
7208
  return null;
6815
7209
  }
6816
- const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join8(homeDir, requestedPath.slice(2)) : requestedPath;
7210
+ const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join9(homeDir, requestedPath.slice(2)) : requestedPath;
6817
7211
  if (expanded.split(/[/\\]/).includes("..")) {
6818
7212
  return null;
6819
7213
  }
6820
- if (!isAbsolute(expanded)) {
7214
+ if (!isAbsolute2(expanded)) {
6821
7215
  return null;
6822
7216
  }
6823
- const candidate = resolve2(expanded);
6824
- const name = basename(candidate);
7217
+ const candidate = resolve3(expanded);
7218
+ const name = basename2(candidate);
6825
7219
  return name === "" || name === "." || name === ".." ? null : candidate;
6826
7220
  }
6827
7221
  async function resolveNearestExistingAncestor(directory) {
@@ -6831,18 +7225,18 @@ async function resolveNearestExistingAncestor(directory) {
6831
7225
  try {
6832
7226
  return { existingAncestor: await realpath(current), missingSegments };
6833
7227
  } catch (err) {
6834
- const parent = dirname5(current);
7228
+ const parent = dirname6(current);
6835
7229
  if (err.code !== "ENOENT" || parent === current) {
6836
7230
  throw err;
6837
7231
  }
6838
- missingSegments.unshift(basename(current));
7232
+ missingSegments.unshift(basename2(current));
6839
7233
  current = parent;
6840
7234
  }
6841
7235
  }
6842
7236
  }
6843
7237
  async function findContainingAllowedDirectory(allowedDirectories, realTarget) {
6844
7238
  for (const directory of allowedDirectories) {
6845
- if (!isAbsolute(directory)) {
7239
+ if (!isAbsolute2(directory)) {
6846
7240
  log("warn", "file_push_allowed_directory_skipped", { directory, reason: "not_absolute" });
6847
7241
  continue;
6848
7242
  }
@@ -6880,19 +7274,19 @@ async function realpathCreatingIfMissing(directory) {
6880
7274
  }
6881
7275
  }
6882
7276
  function contains(realDirectory, realTarget) {
6883
- const rel = relative(realDirectory, realTarget);
6884
- return rel !== "" && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
7277
+ const rel = relative2(realDirectory, realTarget);
7278
+ return rel !== "" && rel !== ".." && !rel.startsWith(`..${sep2}`) && !isAbsolute2(rel);
6885
7279
  }
6886
7280
  async function createMissingDirectories(existingAncestor, missingSegments) {
6887
7281
  let current = existingAncestor;
6888
7282
  for (const segment of missingSegments) {
6889
- current = join8(current, segment);
7283
+ current = join9(current, segment);
6890
7284
  await mkdir(current, { recursive: true, mode: DIRECTORY_MODE });
6891
7285
  await chmod(current, DIRECTORY_MODE);
6892
7286
  }
6893
7287
  }
6894
7288
  async function writeAtomically(realTarget, content) {
6895
- const temporaryPath = join8(dirname5(realTarget), `.evident-push-${randomUUID()}.tmp`);
7289
+ const temporaryPath = join9(dirname6(realTarget), `.evident-push-${randomUUID()}.tmp`);
6896
7290
  let handle;
6897
7291
  try {
6898
7292
  handle = await open3(temporaryPath, "wx", FILE_MODE);
@@ -7022,12 +7416,12 @@ var NOT_APPLIED = {
7022
7416
  opencodeAuthApplied: false
7023
7417
  };
7024
7418
  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);
7419
+ const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join10(homeDir, requestedPath.slice(2)) : requestedPath;
7420
+ return expanded === join10(homeDir, ...CLAUDE_CREDENTIALS_SEGMENTS);
7027
7421
  }
7028
7422
  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);
7423
+ const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join10(homeDir, requestedPath.slice(2)) : requestedPath;
7424
+ return expanded === join10(homeDir, ...OPENCODE_AUTH_SEGMENTS);
7031
7425
  }
7032
7426
  async function applyOne(options, file) {
7033
7427
  const label = `${file.id.slice(0, 8)} (${file.path})`;
@@ -7171,6 +7565,11 @@ function messageIdOf(m) {
7171
7565
  const infoId = m.info?.id;
7172
7566
  return typeof infoId === "string" ? infoId : void 0;
7173
7567
  }
7568
+ function composeAbandonmentNote(finish, replyShape, outcome) {
7569
+ const base = `OpenCode ended this turn after a tool call (finish="${finish ?? "(unknown)"}") ` + (outcome === "without-answer" ? "without writing an answer, and confirmed it is no longer working on this conversation. Evident is reporting the run as failed so the failure and its reason are visible in failed runs." : "after writing only part of an answer, and confirmed it is no longer working on this conversation. Evident delivered what was written and is reporting the run as finished.");
7570
+ if (replyShape === null) return base;
7571
+ return `${base} ${replyShape.lastToolName === null ? "No tool call was recorded" : `The last tool call was "${replyShape.lastToolName}" with status "${replyShape.lastToolStatus ?? "(unknown)"}"`}; the reply's final part types were [${replyShape.partTypes.join(", ")}]${replyShape.droppedPartCount > 0 ? ` (${replyShape.droppedPartCount} earlier part types omitted)` : ""}.`;
7572
+ }
7174
7573
  function cleanImageMime(contentType) {
7175
7574
  if (!contentType) return null;
7176
7575
  const media = contentType.split(";")[0].trim().toLowerCase();
@@ -7193,7 +7592,7 @@ var SESSION_ERROR_BUFFER_TTL_MS = SESSION_ERROR_STREAM_HEALTHY_MS;
7193
7592
  var MAX_BUFFERED_SESSION_ERRORS = 256;
7194
7593
  var SESSION_ERROR_RETENTION_TTL_MS = 6e4;
7195
7594
  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.";
7196
- var SESSION_ERROR_RETAINED_DETAIL = "The runner's session database could not be written, so this turn stopped part-way. Runner-observed session error: ";
7595
+ var SESSION_ERROR_RETAINED_DETAIL = "Runner-observed OpenCode session error: ";
7197
7596
  var SESSION_ERROR_OBSERVED_CAUSE = "Runner-observed OpenCode session-store cause: ";
7198
7597
  var DEFAULT_PAUSED_POLL_INTERVAL_MS = 2e3;
7199
7598
  var DEFAULT_PAUSED_MAX_WAIT_MS = 10 * 60 * 1e3;
@@ -7317,12 +7716,15 @@ var ChannelDriver = class _ChannelDriver {
7317
7716
  /**
7318
7717
  * Per-conversation throttle state for the #183 recurrence warning (#1618
7319
7718
  * WI-4) — see `reportWedgedConversation`'s doc comment for why this exists.
7320
- * `firstWedgedAt` anchors `stuck_for_ms`; `lastWarnedAt` throttles both the
7321
- * log line and the `dispatch_wedged` signal to at most once per
7322
- * `wedgeWarningIntervalMs`; `consecutiveTicks` is reported in the log text
7323
- * so the operator sees magnitude, not repetition. Cleared the moment the
7324
- * conversation dispatches anything (a fresh wedge, if it recurs, is a new
7325
- * incident). Bounded FIFO, mirroring `supersededSessions`
7719
+ * `firstWedgedAt` anchors `stuck_for_ms`; `warnAnchorAt` is the throttle
7720
+ * anchor from first detection through the first warning, then from each
7721
+ * warning onward; `consecutiveTicks` is reported in the log text so the
7722
+ * operator sees magnitude, not repetition. Cleared the moment the
7723
+ * conversation dispatches anything, or when it drops off the pending list
7724
+ * (`runDrain`'s prune, the dominant real-world path — a wedge normally ends
7725
+ * with its message completing, not a fresh dispatch on the same
7726
+ * conversation) — either way a fresh wedge, if it recurs, is a new
7727
+ * incident. Bounded FIFO, mirroring `supersededSessions`
7326
7728
  * (`MAX_WEDGED_CONVERSATIONS`).
7327
7729
  */
7328
7730
  wedgeWarnings = /* @__PURE__ */ new Map();
@@ -7552,6 +7954,7 @@ var ChannelDriver = class _ChannelDriver {
7552
7954
  subagentInvocationPrefetches = /* @__PURE__ */ new Map();
7553
7955
  /** Serialises drains so a reconnect during a drain doesn't double-process. */
7554
7956
  draining = false;
7957
+ pendingProviderRegistryRepair = null;
7555
7958
  /**
7556
7959
  * Serialises runner-file syncs (#559) so the ~2s poll tick and a concurrent
7557
7960
  * drain ping don't download, write and ack the same file twice.
@@ -7737,8 +8140,33 @@ var ChannelDriver = class _ChannelDriver {
7737
8140
  async runDrain() {
7738
8141
  let dispatched = 0;
7739
8142
  try {
8143
+ const pendingRepair = this.pendingProviderRegistryRepair;
8144
+ if (pendingRepair && this.protectedSessionIds().size === 0) {
8145
+ try {
8146
+ await this.issueProviderRegistryReload(
8147
+ pendingRepair.conversationId,
8148
+ pendingRepair.messageId
8149
+ );
8150
+ } catch (err) {
8151
+ this.log({
8152
+ level: "error",
8153
+ message: `Provider registry repair adoption failed for message ${pendingRepair.messageId.slice(0, 8)}: ${err instanceof Error ? err.message : String(err)}`,
8154
+ conversation_id: pendingRepair.conversationId,
8155
+ message_id: pendingRepair.messageId
8156
+ });
8157
+ }
8158
+ return 0;
8159
+ }
7740
8160
  this.pendingMessageIds.clear();
7741
8161
  const conversations = await this.getPendingConversations();
8162
+ if (this.wedgeWarnings.size > 0) {
8163
+ const pendingConversationIds = new Set(conversations.map(({ id }) => id));
8164
+ for (const conversationId of this.wedgeWarnings.keys()) {
8165
+ if (!pendingConversationIds.has(conversationId)) {
8166
+ this.wedgeWarnings.delete(conversationId);
8167
+ }
8168
+ }
8169
+ }
7742
8170
  if (this.recycleRequestedFlag) {
7743
8171
  this.stop();
7744
8172
  }
@@ -8275,14 +8703,13 @@ var ChannelDriver = class _ChannelDriver {
8275
8703
  * skip-because-already-`dispatched`, the exact signature of a message stuck
8276
8704
  * acknowledged-but-never-worked.
8277
8705
  *
8278
- * Unthrottled, this fired every ~6s drain tick for as long as a wedge lasted
8279
- * (52,843 occurrences observed in one incident) — burning the GLOBAL
8280
- * 30-events/60s `runner-activity-telemetry.ts` budget that was itself
8281
- * suppressing the diagnostics needed to debug the wedge. The `warn` log (and
8282
- * the `dispatch_wedged` signal once the wedge has persisted past the same
8283
- * interval) fire at most once per `wedgeWarningIntervalMs` per conversation,
8284
- * naming the consecutive-tick count so the operator sees magnitude rather
8285
- * than repetition.
8706
+ * The first detection starts the clock and emits a local `debug` entry. The
8707
+ * `warn` log and paired `dispatch_wedged` signal fire once the wedge has
8708
+ * lasted `wedgeWarningIntervalMs`, then at most once per interval, naming the
8709
+ * consecutive-tick count so the operator sees magnitude rather than repetition.
8710
+ * A watcher stall that the loop-liveness watchdog recovers is expected and is
8711
+ * already reported by its `watcher_recovered` signal, so it does not reach an
8712
+ * operator through this warning.
8286
8713
  *
8287
8714
  * Deliberately does NOT trigger a release: WI-1's `reconcileWatchers` runs
8288
8715
  * unconditionally on this same tick and is already recovering anything it
@@ -8294,36 +8721,41 @@ var ChannelDriver = class _ChannelDriver {
8294
8721
  const existing = this.wedgeWarnings.get(conv.id);
8295
8722
  const firstWedgedAt = existing?.firstWedgedAt ?? now;
8296
8723
  const consecutiveTicks = (existing?.consecutiveTicks ?? 0) + 1;
8297
- const dueForWarn = !existing || now - existing.lastWarnedAt >= this.wedgeWarningIntervalMs;
8298
- if (!dueForWarn) {
8299
- this.wedgeWarnings.delete(conv.id);
8300
- this.wedgeWarnings.set(conv.id, {
8301
- firstWedgedAt,
8302
- lastWarnedAt: existing.lastWarnedAt,
8303
- consecutiveTicks
8724
+ const warnAnchorAt = existing?.warnAnchorAt ?? now;
8725
+ const dueForWarn = now - warnAnchorAt >= this.wedgeWarningIntervalMs;
8726
+ if (!existing) {
8727
+ this.log({
8728
+ level: "debug",
8729
+ message: `Detected a possible wedge for conversation ${conv.id.slice(0, 8)} with ${messages.length} pending message(s); it will be reported only if it outlasts the watchdog's recovery.`,
8730
+ conversation_id: conv.id
8731
+ });
8732
+ }
8733
+ let untracked = 0;
8734
+ if (dueForWarn) {
8735
+ const stuckForMs = now - firstWedgedAt;
8736
+ untracked = this.countUntrackedIds(messages);
8737
+ this.log({
8738
+ level: "warn",
8739
+ message: `Conversation ${conv.id.slice(0, 8)} has ${messages.length} pending message(s) but ALL are already marked dispatched locally (in-flight set: ${this.dispatched.size}) \u2014 none sent to OpenCode for ${consecutiveTicks} consecutive tick(s) now (${Math.round(stuckForMs / 1e3)}s stuck). ` + (untracked > 0 ? `${untracked} of these id(s) are tracked by NO watcher \u2014 the dispatched/in-flight pairing invariant is violated for this conversation, which will NOT self-heal and needs a runner restart.` : `A watcher is tracking this work; the loop-liveness watchdog is already recovering it.`),
8740
+ conversation_id: conv.id
8304
8741
  });
8305
- return;
8306
8742
  }
8307
- const stuckForMs = now - firstWedgedAt;
8308
- const untracked = this.countUntrackedIds(messages);
8309
- this.log({
8310
- level: "warn",
8311
- message: `Conversation ${conv.id.slice(0, 8)} has ${messages.length} pending message(s) but ALL are already marked dispatched locally (in-flight set: ${this.dispatched.size}) \u2014 none sent to OpenCode for ${consecutiveTicks} consecutive tick(s) now (${stuckForMs}ms stuck). ` + (untracked > 0 ? `${untracked} of these id(s) are tracked by NO watcher \u2014 the dispatched/in-flight pairing invariant is violated for this conversation, which will NOT self-heal and needs a runner restart.` : `A watcher is tracking this work; the loop-liveness watchdog is already recovering it.`),
8312
- conversation_id: conv.id
8313
- });
8314
8743
  this.wedgeWarnings.delete(conv.id);
8315
- this.wedgeWarnings.set(conv.id, { firstWedgedAt, lastWarnedAt: now, consecutiveTicks });
8744
+ this.wedgeWarnings.set(conv.id, {
8745
+ firstWedgedAt,
8746
+ warnAnchorAt: dueForWarn ? now : warnAnchorAt,
8747
+ consecutiveTicks
8748
+ });
8316
8749
  while (this.wedgeWarnings.size > MAX_WEDGED_CONVERSATIONS) {
8317
8750
  const oldest = this.wedgeWarnings.keys().next().value;
8318
8751
  if (oldest === void 0) break;
8319
8752
  this.wedgeWarnings.delete(oldest);
8320
8753
  }
8321
- if (stuckForMs >= this.wedgeWarningIntervalMs) {
8322
- void this.postSignal(conv.id, messages[0].id, "dispatch_wedged", {
8323
- stuck_for_ms: stuckForMs,
8324
- untracked
8325
- });
8326
- }
8754
+ if (!dueForWarn) return;
8755
+ void this.postSignal(conv.id, messages[0].id, "dispatch_wedged", {
8756
+ stuck_for_ms: now - firstWedgedAt,
8757
+ untracked
8758
+ });
8327
8759
  }
8328
8760
  /**
8329
8761
  * How many of `messages`' ids are tracked by NO watcher's `inFlight` (#1618
@@ -9589,14 +10021,40 @@ var ChannelDriver = class _ChannelDriver {
9589
10021
  conversation_id: watcher.conv.id,
9590
10022
  message_id: inFlight.evidentMessageId
9591
10023
  });
9592
- await this.markFailed(
9593
- watcher.conv.id,
9594
- inFlight.evidentMessageId,
9595
- event.sessionId,
9596
- `OpenCode could not run this turn: ${event.reason}`
9597
- );
10024
+ const isMissingProvider = isProviderModelNotFoundError(event.reason);
10025
+ if (isMissingProvider) {
10026
+ const dispatchedModel = inFlight.message.opencode_model;
10027
+ const separator = dispatchedModel?.indexOf("/") ?? -1;
10028
+ const hasProviderAndModel = dispatchedModel !== null && separator > 0 && separator < dispatchedModel.length - 1;
10029
+ await this.markFailed(
10030
+ watcher.conv.id,
10031
+ inFlight.evidentMessageId,
10032
+ event.sessionId,
10033
+ `OpenCode could not run this turn: ${event.reason}`,
10034
+ void 0,
10035
+ {
10036
+ classification: {
10037
+ kind: "model_auth",
10038
+ providerId: hasProviderAndModel ? dispatchedModel.slice(0, separator) : null,
10039
+ modelId: hasProviderAndModel ? dispatchedModel.slice(separator + 1) : null,
10040
+ reason: "missing"
10041
+ },
10042
+ errorShape: { name: null, statusCode: null }
10043
+ }
10044
+ );
10045
+ } else {
10046
+ await this.markFailed(
10047
+ watcher.conv.id,
10048
+ inFlight.evidentMessageId,
10049
+ event.sessionId,
10050
+ `OpenCode could not run this turn: ${event.reason}`
10051
+ );
10052
+ }
9598
10053
  inFlight.done = true;
9599
10054
  this.removeInFlight(watcher, inFlight.evidentMessageId);
10055
+ if (isMissingProvider) {
10056
+ await this.repairProviderRegistry(watcher.conv.id, inFlight.evidentMessageId);
10057
+ }
9600
10058
  } catch (err) {
9601
10059
  if (err instanceof ChannelAuthError) {
9602
10060
  this.log({
@@ -9617,6 +10075,44 @@ var ChannelDriver = class _ChannelDriver {
9617
10075
  this.sessionErrorHandled.delete(inFlight.evidentMessageId);
9618
10076
  }
9619
10077
  }
10078
+ async repairProviderRegistry(conversationId, messageId) {
10079
+ if (this.isV2) {
10080
+ void this.postSignal(conversationId, messageId, "provider_registry_reload_unsupported");
10081
+ return;
10082
+ }
10083
+ const activeSessions = this.protectedSessionIds().size;
10084
+ if (activeSessions > 0 || this.draining) {
10085
+ this.pendingProviderRegistryRepair = { conversationId, messageId };
10086
+ void this.postSignal(conversationId, messageId, "provider_registry_repair_deferred", {
10087
+ active_sessions: activeSessions
10088
+ });
10089
+ this.log({
10090
+ level: "warn",
10091
+ message: `Provider registry repair deferred until a lifecycle-safe point; ${activeSessions} active session(s) protected`,
10092
+ conversation_id: conversationId,
10093
+ message_id: messageId
10094
+ });
10095
+ return;
10096
+ }
10097
+ await this.issueProviderRegistryReload(conversationId, messageId);
10098
+ }
10099
+ async issueProviderRegistryReload(conversationId, messageId) {
10100
+ this.pendingProviderRegistryRepair = null;
10101
+ const result = await disposeAndReloadProviderConfig(this.port, this.openCodeClient);
10102
+ if (result.outcome === "failed") {
10103
+ const failure = result.status === null ? `transport failure${result.detail ? `: ${result.detail}` : ""}` : `HTTP ${result.status}`;
10104
+ this.log({
10105
+ level: "warn",
10106
+ message: `Provider registry reload failed (${failure})`,
10107
+ conversation_id: conversationId,
10108
+ message_id: messageId
10109
+ });
10110
+ }
10111
+ const repairOutcome = result.outcome === "reloaded" ? "reloaded" : "reload_failed";
10112
+ void this.postSignal(conversationId, messageId, "provider_registry_reload_issued", {
10113
+ repair_outcome: repairOutcome
10114
+ });
10115
+ }
9620
10116
  /**
9621
10117
  * The per-session polling loop (WI-3). Once per tick it:
9622
10118
  * 1. polls `GET /session/:id/message` once and, per in-flight message,
@@ -9808,7 +10304,7 @@ var ChannelDriver = class _ChannelDriver {
9808
10304
  if (!inFlight.done) {
9809
10305
  const messageErrorText = messageError(messages, inFlight.opencodeMessageId);
9810
10306
  const retainedReason = this.readRetainedSessionError(sessionId);
9811
- const retainedError = retainedReason === null ? null : `${SESSION_ERROR_RETAINED_DETAIL}${retainedReason}`;
10307
+ const retainedError = retainedReason === null || messageErrorText !== null && messageErrorText.includes(retainedReason) ? null : `${SESSION_ERROR_RETAINED_DETAIL}${retainedReason}`;
9812
10308
  const observedCause = this.sessionStoreHealth?.readCause(sessionId);
9813
10309
  const causeError = observedCause === null || observedCause === void 0 ? null : `${SESSION_ERROR_OBSERVED_CAUSE}${observedCause}`;
9814
10310
  const storeError = this.sessionStoreHealth?.isUnwritable() ? SESSION_STORE_UNWRITABLE_ERROR : null;
@@ -9905,17 +10401,28 @@ var ChannelDriver = class _ChannelDriver {
9905
10401
  }
9906
10402
  } else {
9907
10403
  if (inFlight.b2AbandonedSignalled) {
10404
+ const reply = findLastAssistantReplyFor(messages, inFlight.opencodeMessageId);
10405
+ const finish = reply?.info?.finish ?? reply?.finish;
9908
10406
  if (inFlight.b2AbandonedWithoutAnswer) {
9909
- const reply = findLastAssistantReplyFor(messages, inFlight.opencodeMessageId);
9910
10407
  await this.settleMessageAbandonedWithoutAnswer(
9911
10408
  sessionId,
9912
10409
  watcher,
9913
10410
  inFlight,
9914
10411
  messages,
9915
- reply?.info?.finish ?? reply?.finish
10412
+ finish
9916
10413
  );
9917
10414
  } else {
9918
- await this.settleMessageDone(sessionId, watcher, inFlight, messages);
10415
+ await this.settleMessageDone(
10416
+ sessionId,
10417
+ watcher,
10418
+ inFlight,
10419
+ messages,
10420
+ composeAbandonmentNote(
10421
+ finish,
10422
+ describeAbandonedReplyShape(messages, inFlight.opencodeMessageId),
10423
+ "with-answer"
10424
+ )
10425
+ );
9919
10426
  }
9920
10427
  return;
9921
10428
  }
@@ -9978,7 +10485,17 @@ var ChannelDriver = class _ChannelDriver {
9978
10485
  ...descendantOngoing != null ? { descendant_ongoing: descendantOngoing } : {},
9979
10486
  opencode_message_id: inFlight.opencodeMessageId
9980
10487
  });
9981
- await this.settleMessageDone(sessionId, watcher, inFlight, messages);
10488
+ await this.settleMessageDone(
10489
+ sessionId,
10490
+ watcher,
10491
+ inFlight,
10492
+ messages,
10493
+ composeAbandonmentNote(
10494
+ finish,
10495
+ describeAbandonedReplyShape(messages, inFlight.opencodeMessageId),
10496
+ "with-answer"
10497
+ )
10498
+ );
9982
10499
  return;
9983
10500
  }
9984
10501
  if (rootOngoing === true && !inFlight.b2RootOngoingHeldLogged) {
@@ -10178,15 +10695,11 @@ var ChannelDriver = class _ChannelDriver {
10178
10695
  }
10179
10696
  }
10180
10697
  /**
10181
- * Settle a message whose run-state has resolved `'done'` — extracted verbatim
10182
- * (pure refactor, no behavior change) from `serviceInFlightMessage`'s former
10183
- * inline `state === 'done'` branch body, so a SECOND caller (the #721
10184
- * b2-abandonment resolution) can reach the exact same completion behavior
10185
- * (delivery-deadline anchoring, title resolution, usage extraction, and
10186
- * `markDone`'s auth/terminal/transient-retry discipline) without duplicating it
10187
- * and risking the two copies silently drifting apart.
10698
+ * Settle a message whose run-state has resolved `'done'`. Normal completion and
10699
+ * confirmed b2 abandonment share the same delivery, usage, and terminal handling.
10700
+ * Normal completions omit the optional terminal diagnostic.
10188
10701
  */
10189
- async settleMessageDone(sessionId, watcher, inFlight, messages) {
10702
+ async settleMessageDone(sessionId, watcher, inFlight, messages, note) {
10190
10703
  const conv = watcher.conv;
10191
10704
  this.anchorDeliveryDeadline(inFlight);
10192
10705
  if (!inFlight.done) {
@@ -10213,7 +10726,8 @@ var ChannelDriver = class _ChannelDriver {
10213
10726
  title,
10214
10727
  usage,
10215
10728
  usageAgentName,
10216
- subagentInvocations
10729
+ subagentInvocations,
10730
+ note
10217
10731
  );
10218
10732
  } catch (err) {
10219
10733
  if (err instanceof ChannelAuthError) throw err;
@@ -10258,9 +10772,11 @@ var ChannelDriver = class _ChannelDriver {
10258
10772
  /** Report a confirmed b2 abandonment that produced no answer text. */
10259
10773
  async settleMessageAbandonedWithoutAnswer(sessionId, watcher, inFlight, messages, finish) {
10260
10774
  const conv = watcher.conv;
10261
- const legacyError = `OpenCode ended this turn after a tool call (finish="${finish ?? "(unknown)"}") without writing an answer, and confirmed it is no longer working on this conversation. Evident is reporting the run as failed so the failure and its reason are visible in failed runs.`;
10262
- const replyShape = describeAbandonedReplyShape(messages, inFlight.opencodeMessageId);
10263
- const error2 = replyShape === null ? legacyError : `${legacyError} ${replyShape.lastToolName === null ? "No tool call was recorded" : `The last tool call was "${replyShape.lastToolName}" with status "${replyShape.lastToolStatus ?? "(unknown)"}"`}; the reply's final part types were [${replyShape.partTypes.join(", ")}]${replyShape.droppedPartCount > 0 ? ` (${replyShape.droppedPartCount} earlier part types omitted)` : ""}.`;
10775
+ const error2 = composeAbandonmentNote(
10776
+ finish,
10777
+ describeAbandonedReplyShape(messages, inFlight.opencodeMessageId),
10778
+ "without-answer"
10779
+ );
10264
10780
  this.anchorDeliveryDeadline(inFlight);
10265
10781
  this.log({
10266
10782
  level: "warn",
@@ -11497,14 +12013,14 @@ var ChannelDriver = class _ChannelDriver {
11497
12013
  const fetchChildWithoutBlocking = async (sessionId) => {
11498
12014
  const pending = fetchChildMessages(sessionId);
11499
12015
  let timer;
11500
- const timeout = new Promise((resolve4) => {
12016
+ const timeout = new Promise((resolve5) => {
11501
12017
  timer = setTimeout(() => {
11502
12018
  this.log({
11503
12019
  level: "warn",
11504
12020
  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`,
11505
12021
  message_id: messageId
11506
12022
  });
11507
- resolve4(null);
12023
+ resolve5(null);
11508
12024
  }, SUBAGENT_TELEMETRY_FETCH_TIMEOUT_MS);
11509
12025
  });
11510
12026
  try {
@@ -12064,7 +12580,7 @@ var ChannelDriver = class _ChannelDriver {
12064
12580
  * watcher retries next tick within the
12065
12581
  * deadline, Finding 4).
12066
12582
  */
12067
- async markDone(conversationId, messageId, sessionId, opencodeMessageId, title, usage, usageAgentName, subagentInvocations) {
12583
+ async markDone(conversationId, messageId, sessionId, opencodeMessageId, title, usage, usageAgentName, subagentInvocations, error2) {
12068
12584
  const res = await this.fetchImpl(
12069
12585
  `${this.apiUrl}/runners/${this.agentId}/threads/${conversationId}/messages/${messageId}`,
12070
12586
  {
@@ -12082,7 +12598,8 @@ var ChannelDriver = class _ChannelDriver {
12082
12598
  ...title ? { title } : {},
12083
12599
  ...usage ? usage : {},
12084
12600
  ...usageAgentName ? { usage_agent_name: usageAgentName } : {},
12085
- ...subagentInvocations && subagentInvocations.length > 0 ? { subagent_invocations: subagentInvocations } : {}
12601
+ ...subagentInvocations && subagentInvocations.length > 0 ? { subagent_invocations: subagentInvocations } : {},
12602
+ ...error2 ? { error: error2 } : {}
12086
12603
  })
12087
12604
  }
12088
12605
  );
@@ -12142,11 +12659,17 @@ var ChannelDriver = class _ChannelDriver {
12142
12659
  if (subagentInvocations && subagentInvocations.length > 0) {
12143
12660
  body.subagent_invocations = subagentInvocations;
12144
12661
  }
12145
- if (failure) {
12146
- body.failure_kind = failure.kind;
12147
- body.failure_provider_id = failure.providerId;
12148
- body.failure_model_id = failure.modelId;
12149
- body.failure_reason = failure.reason;
12662
+ if (failure && failure.errorShape.name !== null) {
12663
+ body.failure_error_name = failure.errorShape.name;
12664
+ }
12665
+ if (failure && failure.errorShape.statusCode !== null) {
12666
+ body.failure_status_code = failure.errorShape.statusCode;
12667
+ }
12668
+ if (failure?.classification) {
12669
+ body.failure_kind = failure.classification.kind;
12670
+ body.failure_provider_id = failure.classification.providerId;
12671
+ body.failure_model_id = failure.classification.modelId;
12672
+ body.failure_reason = failure.classification.reason;
12150
12673
  }
12151
12674
  try {
12152
12675
  await this.callWithRetry(
@@ -12167,27 +12690,28 @@ var ChannelDriver = class _ChannelDriver {
12167
12690
  this.clearSubagentInvocationCaches(messageId);
12168
12691
  }
12169
12692
  /**
12170
- * Classify an errored turn as a model-auth failure (#736 P1-4), for `markFailed`.
12693
+ * Classify an errored turn and extract its bounded error shape for `markFailed`.
12171
12694
  *
12172
12695
  * `messageFailure` alone (structured OpenCode error → `model_auth`) covers
12173
12696
  * most cases; when it returns `null` on this ALREADY-FAILED turn, fall back
12174
12697
  * to the P1-2b zero-provider check — one extra loopback call to
12175
12698
  * `hasAnyConfiguredProvider`, only reached when the structured classifier
12176
12699
  * couldn't place it. Fails open (never throws): a fallback probe failure
12177
- * (`null`/indeterminate) leaves the classification `null`, which produces
12178
- * today's byte-identical PATCH body via `markFailed`'s `if (failure)` guard.
12700
+ * (`null`/indeterminate) leaves the classification `null`; the raw error shape
12701
+ * is still retained for diagnostics.
12179
12702
  */
12180
12703
  async classifyModelAuthFailure(messages, userMessageId) {
12181
- const classified = messageFailure(messages, userMessageId);
12182
- if (classified != null) return classified;
12183
12704
  const reply = findLastAssistantReplyFor(messages, userMessageId);
12184
- const hasProvider = await this.hasAnyConfiguredProvider();
12185
- return applyZeroProviderFallback(
12705
+ const errorShape = extractReplyErrorShape(reply);
12706
+ const classified = messageFailure(messages, userMessageId);
12707
+ if (classified != null) return { classification: classified, errorShape };
12708
+ const classification = applyZeroProviderFallback(
12186
12709
  classified,
12187
- hasProvider,
12710
+ await this.hasAnyConfiguredProvider(),
12188
12711
  reply?.info?.providerID ?? null,
12189
12712
  reply?.info?.modelID ?? null
12190
12713
  );
12714
+ return { classification, errorShape };
12191
12715
  }
12192
12716
  async recordSubagentModelAuthFailure(failure, conversationId, messageId) {
12193
12717
  const providerId = failure.providerId ?? "(unknown)";
@@ -12745,7 +13269,7 @@ function commandError2(result) {
12745
13269
  return result.stderr.trim() || `process exited with code ${result.code ?? "null"}`;
12746
13270
  }
12747
13271
  var runCommand2 = (command, args, opts) => {
12748
- return new Promise((resolve4) => {
13272
+ return new Promise((resolve5) => {
12749
13273
  let child;
12750
13274
  let stdout = "";
12751
13275
  let stderr = "";
@@ -12755,7 +13279,7 @@ var runCommand2 = (command, args, opts) => {
12755
13279
  if (settled) return;
12756
13280
  settled = true;
12757
13281
  if (timer.handle) clearTimeout(timer.handle);
12758
- resolve4(result);
13282
+ resolve5(result);
12759
13283
  };
12760
13284
  try {
12761
13285
  child = spawn5(command, args, { env: opts.env, stdio: ["ignore", "pipe", "pipe"] });
@@ -12810,7 +13334,9 @@ async function installRunnerSecret({
12810
13334
  }) {
12811
13335
  const arn = env.RUNNER_SECRET_ARN?.trim();
12812
13336
  if (!arn) {
12813
- log3("runner secret is not configured; continuing without GitHub and MCP credentials");
13337
+ if (!env.GH_TOKEN) {
13338
+ log3("runner secret is not configured; continuing without GitHub and MCP credentials");
13339
+ }
12814
13340
  return false;
12815
13341
  }
12816
13342
  const result = await (commandRunner ?? runCommand2)(
@@ -13009,7 +13535,7 @@ async function configureGitHubAccess({ env, log: log3 }) {
13009
13535
  // src/lib/opencode/config-overlay.ts
13010
13536
  import { execFileSync as execFileSync2 } from "node:child_process";
13011
13537
  import { copyFileSync, existsSync as existsSync2, statSync as statSync6 } from "node:fs";
13012
- import { isAbsolute as isAbsolute2, join as join10, resolve as resolve3 } from "node:path";
13538
+ import { isAbsolute as isAbsolute3, join as join11, resolve as resolve4 } from "node:path";
13013
13539
  function isFile(filePath) {
13014
13540
  return existsSync2(filePath) && statSync6(filePath).isFile();
13015
13541
  }
@@ -13022,8 +13548,8 @@ function applyRunnerOpenCodeConfig({
13022
13548
  log3("runner OpenCode config is not configured; using the baked project config", "debug");
13023
13549
  return;
13024
13550
  }
13025
- const source = isAbsolute2(overlayPath) ? overlayPath : resolve3(cwd, overlayPath);
13026
- const target = isFile(join10(cwd, "opencode.jsonc")) ? "opencode.jsonc" : "opencode.json";
13551
+ const source = isAbsolute3(overlayPath) ? overlayPath : resolve4(cwd, overlayPath);
13552
+ const target = isFile(join11(cwd, "opencode.jsonc")) ? "opencode.jsonc" : "opencode.json";
13027
13553
  if (!isFile(source)) {
13028
13554
  log3(
13029
13555
  `RUNNER-OPENCODE-CONFIG-MISSING: ${source} is not a file; headless turns will wedge on the first external-directory permission prompt (#563)`,
@@ -13031,7 +13557,7 @@ function applyRunnerOpenCodeConfig({
13031
13557
  );
13032
13558
  return;
13033
13559
  }
13034
- copyFileSync(source, join10(cwd, target));
13560
+ copyFileSync(source, join11(cwd, target));
13035
13561
  try {
13036
13562
  execFileSync2("git", ["-C", cwd, "update-index", "--skip-worktree", target], {
13037
13563
  stdio: "ignore"
@@ -13040,7 +13566,7 @@ function applyRunnerOpenCodeConfig({
13040
13566
  const detail = error2 instanceof Error ? error2.message : String(error2);
13041
13567
  log3(`could not mark ${target} skip-worktree: ${detail}; it may show as a local change`, "warn");
13042
13568
  }
13043
- log3(`Applied runner OpenCode config ${source} to ${join10(cwd, target)}`);
13569
+ log3(`Applied runner OpenCode config ${source} to ${join11(cwd, target)}`);
13044
13570
  }
13045
13571
 
13046
13572
  // src/lib/credential-sync.ts
@@ -13058,14 +13584,14 @@ function errorMessage2(error2) {
13058
13584
  return error2 instanceof Error ? error2.message : String(error2);
13059
13585
  }
13060
13586
  function waitForSettlement(promise, timeoutMs) {
13061
- return new Promise((resolve4) => {
13587
+ return new Promise((resolve5) => {
13062
13588
  let settled = false;
13063
13589
  const timer = setTimeout(() => finish(false), Math.max(0, timeoutMs));
13064
13590
  const finish = (value) => {
13065
13591
  if (settled) return;
13066
13592
  settled = true;
13067
13593
  clearTimeout(timer);
13068
- resolve4(value);
13594
+ resolve5(value);
13069
13595
  };
13070
13596
  promise.then(
13071
13597
  () => finish(true),
@@ -13282,6 +13808,8 @@ function createCredentialSync({
13282
13808
  var MAX_ACTIVITY_LOG_ENTRIES = 10;
13283
13809
  var MAX_DISCONNECT_REASON_LENGTH = 200;
13284
13810
  var CHANNEL_POLL_INTERVAL_MS = Number(process.env.EVIDENT_CHANNEL_POLL_INTERVAL_MS) || 2e3;
13811
+ var CREDENTIAL_ADOPTION_PROBE_ATTEMPTS = 3;
13812
+ var CREDENTIAL_ADOPTION_PROBE_INTERVAL_MS = 1e3;
13285
13813
  var CHANNEL_STUCK_QUEUED_MS = Number(process.env.EVIDENT_STUCK_QUEUED_MS) || void 0;
13286
13814
  var SHUTDOWN_DRAIN_TIMEOUT_MS = Number(process.env.EVIDENT_SHUTDOWN_DRAIN_MS) || 25e3;
13287
13815
  var TELEMETRY_SHUTDOWN_TIMEOUT_MS = 5e3;
@@ -13316,8 +13844,8 @@ function resolveFileSyncDirectories(raw, homeDir) {
13316
13844
  if (trimmed === "") {
13317
13845
  throw new Error("--enable-file-sync-to requires a directory path (got an empty value)");
13318
13846
  }
13319
- const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join11(homeDir, trimmed.slice(2)) : trimmed;
13320
- if (!isAbsolute3(expanded)) {
13847
+ const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join12(homeDir, trimmed.slice(2)) : trimmed;
13848
+ if (!isAbsolute4(expanded)) {
13321
13849
  throw new Error(`--enable-file-sync-to requires an absolute directory path; got "${entry}"`);
13322
13850
  }
13323
13851
  const normalized = resolvePath2(expanded);
@@ -13417,8 +13945,7 @@ function resolveMaxActiveSessions(options, env = process.env) {
13417
13945
  function meetsThreshold(state, level) {
13418
13946
  return LOG_LEVELS[level] >= LOG_LEVELS[state.logLevel];
13419
13947
  }
13420
- function log2(state, message, level = "info") {
13421
- if (!meetsThreshold(state, level)) return;
13948
+ function writeConsoleLog(state, message, level) {
13422
13949
  if (state.json) {
13423
13950
  console.log(
13424
13951
  JSON.stringify({
@@ -13427,10 +13954,18 @@ function log2(state, message, level = "info") {
13427
13954
  message
13428
13955
  })
13429
13956
  );
13430
- } else if (!state.interactive) {
13431
- const prefix = level === "error" ? chalk7.red("\u2717") : level === "warn" ? chalk7.yellow("!") : level === "debug" ? chalk7.dim("\xB7") : chalk7.green("\u2022");
13432
- console.log(`${prefix} ${message}`);
13957
+ return;
13433
13958
  }
13959
+ const prefix = level === "error" ? chalk7.red("\u2717") : level === "warn" ? chalk7.yellow("!") : level === "debug" ? chalk7.dim("\xB7") : chalk7.green("\u2022");
13960
+ console.log(`${prefix} ${message}`);
13961
+ }
13962
+ function log2(state, message, level = "info") {
13963
+ if (!meetsThreshold(state, level)) return;
13964
+ if (state.json || !state.interactive) writeConsoleLog(state, message, level);
13965
+ }
13966
+ function logLocalOnly(state, message, level = "info") {
13967
+ if (!meetsThreshold(state, level)) return;
13968
+ writeConsoleLog(state, message, level);
13434
13969
  }
13435
13970
  function logActivity(state, entry) {
13436
13971
  const level = entry.level ?? (entry.type === "error" ? "error" : "info");
@@ -13622,6 +14157,125 @@ async function handleAuthError(state, error2) {
13622
14157
  return { success: false };
13623
14158
  }
13624
14159
  }
14160
+ function logCredentialAdoptionActivity(state, activity, level) {
14161
+ const message = (() => {
14162
+ switch (activity.outcome) {
14163
+ case "deferred":
14164
+ return `CREDENTIAL-ADOPTION: deferred generation ${activity.generation} with ${activity.active_sessions} active session(s)`;
14165
+ case "reloaded_ready":
14166
+ return `CREDENTIAL-ADOPTION: adopted generation ${activity.generation} with ${activity.active_sessions} active session(s); readiness probe succeeded after ${activity.probe_attempts} attempt(s)`;
14167
+ case "reloaded_interrupted": {
14168
+ const response = activity.probe_status === null ? "without an HTTP response" : `with HTTP ${activity.probe_status} and ${activity.probe_body_empty ? "an empty" : "a non-empty"} body`;
14169
+ return `CREDENTIAL-ADOPTION: generation ${activity.generation} with ${activity.active_sessions} active session(s); replacement instance answered ${response} after ${activity.probe_attempts} probe attempt(s)`;
14170
+ }
14171
+ case "reload_failed":
14172
+ return `CREDENTIAL-ADOPTION: failed to adopt generation ${activity.generation} with ${activity.active_sessions} active session(s)`;
14173
+ case "skipped_v2":
14174
+ return `CREDENTIAL-ADOPTION: skipped generation ${activity.generation} with ${activity.active_sessions} active session(s) on OpenCode V2`;
14175
+ }
14176
+ })();
14177
+ logActivity(state, {
14178
+ type: level === "error" ? "error" : "info",
14179
+ level,
14180
+ ...level === "error" ? { error: message } : { message },
14181
+ metadata: {
14182
+ ...activity,
14183
+ opencode_version: state.opencodeVersion,
14184
+ port: state.port
14185
+ }
14186
+ });
14187
+ }
14188
+ async function adoptCredentialGeneration(state, generation, adoption, activeSessions, deferredForMs) {
14189
+ const reload = await disposeAndReloadProviderConfig(
14190
+ state.port,
14191
+ state.opencodeClient ?? void 0
14192
+ );
14193
+ if (reload.outcome === "failed") {
14194
+ logCredentialAdoptionActivity(
14195
+ state,
14196
+ {
14197
+ outcome: "reload_failed",
14198
+ generation,
14199
+ active_sessions: activeSessions,
14200
+ adoption,
14201
+ deferred_for_ms: deferredForMs,
14202
+ reload_status: reload.status,
14203
+ reload_detail: reload.detail,
14204
+ probe_attempts: null,
14205
+ probe_status: null,
14206
+ probe_body_empty: null,
14207
+ probe_detail: null
14208
+ },
14209
+ "error"
14210
+ );
14211
+ return;
14212
+ }
14213
+ if (reload.outcome === "skipped_v2") {
14214
+ logCredentialAdoptionActivity(
14215
+ state,
14216
+ {
14217
+ outcome: "skipped_v2",
14218
+ generation,
14219
+ active_sessions: activeSessions,
14220
+ adoption,
14221
+ deferred_for_ms: deferredForMs,
14222
+ reload_status: null,
14223
+ reload_detail: null,
14224
+ probe_attempts: null,
14225
+ probe_status: null,
14226
+ probe_body_empty: null,
14227
+ probe_detail: null
14228
+ },
14229
+ "debug"
14230
+ );
14231
+ return;
14232
+ }
14233
+ let lastProbe = null;
14234
+ let attempts = 0;
14235
+ for (attempts = 1; attempts <= CREDENTIAL_ADOPTION_PROBE_ATTEMPTS; attempts++) {
14236
+ lastProbe = await probeOpenCodeRequestReadiness(state.port, state.opencodeClient ?? void 0);
14237
+ if (lastProbe.ok) {
14238
+ logCredentialAdoptionActivity(
14239
+ state,
14240
+ {
14241
+ outcome: "reloaded_ready",
14242
+ generation,
14243
+ active_sessions: activeSessions,
14244
+ adoption,
14245
+ deferred_for_ms: deferredForMs,
14246
+ reload_status: null,
14247
+ reload_detail: null,
14248
+ probe_attempts: attempts,
14249
+ probe_status: lastProbe.status,
14250
+ probe_body_empty: lastProbe.bodyEmpty,
14251
+ probe_detail: lastProbe.detail
14252
+ },
14253
+ "warn"
14254
+ );
14255
+ return;
14256
+ }
14257
+ if (attempts < CREDENTIAL_ADOPTION_PROBE_ATTEMPTS) {
14258
+ await new Promise((resolve5) => setTimeout(resolve5, CREDENTIAL_ADOPTION_PROBE_INTERVAL_MS));
14259
+ }
14260
+ }
14261
+ logCredentialAdoptionActivity(
14262
+ state,
14263
+ {
14264
+ outcome: "reloaded_interrupted",
14265
+ generation,
14266
+ active_sessions: activeSessions,
14267
+ adoption,
14268
+ deferred_for_ms: deferredForMs,
14269
+ reload_status: null,
14270
+ reload_detail: null,
14271
+ probe_attempts: CREDENTIAL_ADOPTION_PROBE_ATTEMPTS,
14272
+ probe_status: lastProbe?.status ?? null,
14273
+ probe_body_empty: lastProbe?.bodyEmpty ?? null,
14274
+ probe_detail: lastProbe?.detail ?? null
14275
+ },
14276
+ "error"
14277
+ );
14278
+ }
13625
14279
  async function driveChannels(state, driver) {
13626
14280
  let idlePolls = 0;
13627
14281
  let idleMs = 0;
@@ -13631,6 +14285,15 @@ async function driveChannels(state, driver) {
13631
14285
  let lastSeenAppliedFiles = driver.fileSyncActivity().appliedFiles;
13632
14286
  let lastSeenClaudeApplies = driver.fileSyncActivity().claudeCredentialApplies;
13633
14287
  let lastSeenOpencodeAuthApplies = driver.fileSyncActivity().opencodeAuthApplyCount;
14288
+ const credentialAdoption = {
14289
+ generation: 0,
14290
+ pendingGeneration: null,
14291
+ pendingSinceMs: null,
14292
+ deferredGeneration: null,
14293
+ adoption: 0
14294
+ };
14295
+ const stayAwakeHolds = () => state.stayAwakeUntilMs !== null && Date.now() < state.stayAwakeUntilMs;
14296
+ let stayAwakeSuppressionLogged = false;
13634
14297
  while (state.running) {
13635
14298
  const cycleStartedAtMs = performance.now();
13636
14299
  let idleThisCycle = false;
@@ -13672,12 +14335,30 @@ async function driveChannels(state, driver) {
13672
14335
  lastSeenOpencodeAuthApplies = opencodeAuthApplies;
13673
14336
  if (opencodeAuthApplied) state.openaiUsageRearm?.();
13674
14337
  if (claudeCredentialApplied || opencodeAuthApplied) {
13675
- void reloadProviderCache(state.port, state.opencodeClient ?? void 0).catch(
13676
- (error2) => logActivity(state, {
13677
- type: "error",
13678
- error: `OpenCode provider cache reload failed on port ${state.port}: ${error2 instanceof Error ? error2.message : String(error2)}`
13679
- })
13680
- );
14338
+ credentialAdoption.generation++;
14339
+ if (state.opencodeApiVersion === "v2") {
14340
+ logCredentialAdoptionActivity(
14341
+ state,
14342
+ {
14343
+ outcome: "skipped_v2",
14344
+ generation: credentialAdoption.generation,
14345
+ active_sessions: driver.protectedSessionIds().size,
14346
+ adoption: null,
14347
+ deferred_for_ms: null,
14348
+ reload_status: null,
14349
+ reload_detail: null,
14350
+ probe_attempts: null,
14351
+ probe_status: null,
14352
+ probe_body_empty: null,
14353
+ probe_detail: null
14354
+ },
14355
+ "debug"
14356
+ );
14357
+ } else {
14358
+ credentialAdoption.pendingGeneration = credentialAdoption.generation;
14359
+ credentialAdoption.pendingSinceMs = Date.now();
14360
+ credentialAdoption.deferredGeneration = null;
14361
+ }
13681
14362
  }
13682
14363
  if (opencodeAuthApplied && state.opencodeApiVersion === "v2") {
13683
14364
  void importOpenCodeV2CredentialsForState(state).catch(
@@ -13732,7 +14413,50 @@ async function driveChannels(state, driver) {
13732
14413
  }
13733
14414
  }
13734
14415
  }
13735
- await new Promise((resolve4) => setTimeout(resolve4, CHANNEL_POLL_INTERVAL_MS));
14416
+ if (credentialAdoption.pendingGeneration !== null) {
14417
+ const activeSessions = driver.protectedSessionIds();
14418
+ const generation = credentialAdoption.pendingGeneration;
14419
+ if (activeSessions.size > 0) {
14420
+ if (credentialAdoption.deferredGeneration !== generation) {
14421
+ credentialAdoption.deferredGeneration = generation;
14422
+ logCredentialAdoptionActivity(
14423
+ state,
14424
+ {
14425
+ outcome: "deferred",
14426
+ generation,
14427
+ active_sessions: activeSessions.size,
14428
+ adoption: null,
14429
+ deferred_for_ms: null,
14430
+ reload_status: null,
14431
+ reload_detail: null,
14432
+ probe_attempts: null,
14433
+ probe_status: null,
14434
+ probe_body_empty: null,
14435
+ probe_detail: null
14436
+ },
14437
+ "warn"
14438
+ );
14439
+ }
14440
+ } else {
14441
+ const deferredForMs = credentialAdoption.deferredGeneration === generation && credentialAdoption.pendingSinceMs !== null ? Math.max(0, Date.now() - credentialAdoption.pendingSinceMs) : null;
14442
+ credentialAdoption.pendingGeneration = null;
14443
+ credentialAdoption.pendingSinceMs = null;
14444
+ credentialAdoption.adoption++;
14445
+ void adoptCredentialGeneration(
14446
+ state,
14447
+ generation,
14448
+ credentialAdoption.adoption,
14449
+ activeSessions.size,
14450
+ deferredForMs
14451
+ ).catch(
14452
+ (error2) => logActivity(state, {
14453
+ type: "error",
14454
+ error: `CREDENTIAL-ADOPTION: adoption failed for generation ${generation} with ${activeSessions.size} active session(s) on port ${state.port}: ${error2 instanceof Error ? error2.message : String(error2)}`
14455
+ })
14456
+ );
14457
+ }
14458
+ }
14459
+ await new Promise((resolve5) => setTimeout(resolve5, CHANNEL_POLL_INTERVAL_MS));
13736
14460
  const cycleMs = performance.now() - cycleStartedAtMs;
13737
14461
  if (idleThisCycle) idleMs += cycleMs;
13738
14462
  if (unreachableThisCycle) unreachableMs += cycleMs;
@@ -13745,15 +14469,27 @@ async function driveChannels(state, driver) {
13745
14469
  if (state.interactive) displayStatus(state);
13746
14470
  break;
13747
14471
  }
13748
- if (state.idleTimeout !== null && idlePolls >= 2 && idleMs > state.idleTimeout * 1e3) {
14472
+ if (state.idleTimeout !== null && idlePolls >= 2 && idleMs > state.idleTimeout * 1e3 && !stayAwakeHolds()) {
13749
14473
  logActivity(state, { type: "info", message: "Idle timeout reached" });
13750
14474
  if (state.interactive) displayStatus(state);
13751
14475
  break;
13752
14476
  }
14477
+ if (state.idleTimeout !== null && idlePolls >= 2 && idleMs > state.idleTimeout * 1e3 && stayAwakeHolds()) {
14478
+ if (!stayAwakeSuppressionLogged) {
14479
+ stayAwakeSuppressionLogged = true;
14480
+ logActivity(state, {
14481
+ type: "info",
14482
+ message: "Idle, but staying awake until the requested minimum passes"
14483
+ });
14484
+ }
14485
+ }
13753
14486
  }
13754
14487
  }
13755
14488
  var SESSION_CLEANUP_FIRST_SWEEP_MS = 1e4;
13756
14489
  var SESSION_CLEANUP_MAX_DELETES_PER_SWEEP = 100;
14490
+ var SESSION_CLEANUP_MAX_ISOLATED_DELETE_FAILURES = 2;
14491
+ var SESSION_CLEANUP_GIVE_UP_AFTER_FAILURES = 2;
14492
+ var MAX_SESSION_DELETE_BODY_LENGTH = 200;
13757
14493
  function shouldWarnForReclaimSkip(reason) {
13758
14494
  if (reason !== "sqlite-unavailable" && reason !== "disk-exhaustion") return false;
13759
14495
  const version2 = /^v(\d+)\.(\d+)\.(\d+)$/.exec(process.version);
@@ -13764,7 +14500,7 @@ function shouldWarnForReclaimSkip(reason) {
13764
14500
  return major > 22 || major === 22 && (minor > 13 || minor === 13 && patch >= 0);
13765
14501
  }
13766
14502
  function sessionDbPath() {
13767
- return join11(homedir7(), ".local", "share", "opencode", "opencode.db");
14503
+ return join12(homedir7(), ".local", "share", "opencode", "opencode.db");
13768
14504
  }
13769
14505
  function logSessionCleanupActivity(state, phase, entry) {
13770
14506
  logActivity(state, {
@@ -13841,8 +14577,12 @@ async function runSweep(state, driver, config) {
13841
14577
  protectedIds: protectedNow
13842
14578
  }
13843
14579
  );
13844
- const deleteCandidates = toDelete.slice(0, SESSION_CLEANUP_MAX_DELETES_PER_SWEEP);
13845
- remaining = toDelete.length - deleteCandidates.length;
14580
+ const eligibleToDelete = toDelete.filter(
14581
+ (id) => (state.sessionDeleteFailures.get(id)?.isolatedFailures ?? 0) < SESSION_CLEANUP_GIVE_UP_AFTER_FAILURES
14582
+ );
14583
+ const deleteCandidates = eligibleToDelete.slice(0, SESSION_CLEANUP_MAX_DELETES_PER_SWEEP);
14584
+ remaining = eligibleToDelete.length - deleteCandidates.length;
14585
+ const answeredFailures = [];
13846
14586
  protectedNow = driver.protectedSessionIds();
13847
14587
  for (const id of deleteCandidates) {
13848
14588
  if (protectedNow.has(id)) {
@@ -13865,8 +14605,44 @@ async function runSweep(state, driver, config) {
13865
14605
  if (statusClass === 4) failed4xx++;
13866
14606
  else if (statusClass === 5) failed5xx++;
13867
14607
  else failedOtherStatus++;
14608
+ answeredFailures.push({
14609
+ id,
14610
+ status: outcome.status,
14611
+ ...outcome.body !== void 0 ? { body: outcome.body } : {}
14612
+ });
14613
+ }
14614
+ }
14615
+ const givenUpFailures = [];
14616
+ if (failed > SESSION_CLEANUP_MAX_ISOLATED_DELETE_FAILURES) {
14617
+ for (const { id } of answeredFailures) state.sessionDeleteFailures.delete(id);
14618
+ } else {
14619
+ for (const failure of answeredFailures) {
14620
+ const previous = state.sessionDeleteFailures.get(failure.id);
14621
+ const record = previous?.status === failure.status ? { status: failure.status, isolatedFailures: previous.isolatedFailures + 1 } : { status: failure.status, isolatedFailures: 1 };
14622
+ state.sessionDeleteFailures.set(failure.id, record);
14623
+ if (record.isolatedFailures >= SESSION_CLEANUP_GIVE_UP_AFTER_FAILURES) {
14624
+ givenUpFailures.push(failure);
14625
+ }
13868
14626
  }
13869
14627
  }
14628
+ for (const failure of givenUpFailures) {
14629
+ const excerpt = redactDiagnosticText(failure.body ?? "(no response body)").slice(
14630
+ 0,
14631
+ MAX_SESSION_DELETE_BODY_LENGTH
14632
+ );
14633
+ logSessionCleanupActivity(state, "sweep", {
14634
+ type: "info",
14635
+ level: "warn",
14636
+ message: `Session cleanup: gave up on session ${failure.id} after ${SESSION_CLEANUP_GIVE_UP_AFTER_FAILURES} isolated delete failures (status ${failure.status}): ${excerpt}`,
14637
+ metadata: {
14638
+ outcome: "session-delete-given-up",
14639
+ session_id: failure.id,
14640
+ status: failure.status,
14641
+ body_excerpt: excerpt,
14642
+ given_up_count: givenUpFailures.length
14643
+ }
14644
+ });
14645
+ }
13870
14646
  const failedNote = failed > 0 ? `, failed ${failed}` : "";
13871
14647
  const skippedNote = skippedNewlyActive > 0 ? `, skipped ${skippedNewlyActive} newly-active` : "";
13872
14648
  const remainingNote = remaining > 0 ? `, remaining ${remaining}` : "";
@@ -13887,21 +14663,31 @@ async function runSweep(state, driver, config) {
13887
14663
  sessions_remaining: remaining,
13888
14664
  ...enumerationReason !== null ? { session_enumeration_reason: enumerationReason } : {}
13889
14665
  };
14666
+ const protectedForReclaim = driver.protectedSessionIds();
13890
14667
  const reclaimResult = await reclaimSessionDbSpace({
13891
14668
  dbPath: sessionDbPath(),
13892
14669
  chunkPages: SESSION_DB_RECLAIM_CHUNK_PAGES,
13893
14670
  pageCeiling: SESSION_DB_RECLAIM_PAGE_CEILING,
13894
14671
  timeBudgetMs: SESSION_DB_RECLAIM_TIME_BUDGET_MS,
13895
- allowFullVacuum: protectedNow.size === 0 && !state.sessionDbProvenanceAnomaly
14672
+ hasLiveTurn: protectedForReclaim.size > 0,
14673
+ hasProvenanceAnomaly: state.sessionDbProvenanceAnomaly
13896
14674
  });
13897
14675
  if (reclaimResult.ok) {
13898
14676
  state.sessionStoreHealth.observeWritable();
13899
14677
  const beforeMib = (reclaimResult.beforeBytes / 1024 / 1024).toFixed(1);
13900
14678
  const afterMib = (reclaimResult.afterBytes / 1024 / 1024).toFixed(1);
13901
14679
  const checkpointNote = reclaimResult.checkpoint.busy ? ` (on-disk file truncation deferred: checkpoint busy, ${reclaimResult.checkpoint.log} WAL frames pending)` : "";
14680
+ const loopElapsedMs = Math.max(
14681
+ 0,
14682
+ reclaimResult.elapsedMs - reclaimResult.checkpointElapsedMs
14683
+ );
14684
+ const reclaimIsSlow = reclaimResult.elapsedMs >= 4 * SESSION_DB_RECLAIM_TIME_BUDGET_MS;
14685
+ const perPageNote = reclaimResult.pagesReclaimed > 0 ? `, per-page ${(loopElapsedMs / reclaimResult.pagesReclaimed).toFixed(2)} ms/page` : "";
14686
+ 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})` : "";
13902
14687
  logSessionCleanupActivity(state, "sweep", {
13903
14688
  type: "info",
13904
- message: `Session cleanup: reclaimed session-db space (${reclaimResult.mode}): ${beforeMib} MiB -> ${afterMib} MiB (stopped by ${reclaimResult.stoppedBy}; freelist ${reclaimResult.freelistBefore} -> ${reclaimResult.freelistAfter} pages)` + checkpointNote,
14689
+ level: reclaimIsSlow ? "warn" : "info",
14690
+ 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,
13905
14691
  metadata: {
13906
14692
  outcome: "reclaimed",
13907
14693
  mode: reclaimResult.mode,
@@ -13914,6 +14700,7 @@ async function runSweep(state, driver, config) {
13914
14700
  freelist_after: reclaimResult.freelistAfter,
13915
14701
  pages_reclaimed: reclaimResult.pagesReclaimed,
13916
14702
  reclaim_elapsed_ms: reclaimResult.elapsedMs,
14703
+ checkpoint_elapsed_ms: reclaimResult.checkpointElapsedMs,
13917
14704
  ...sessionMetadata
13918
14705
  }
13919
14706
  });
@@ -14024,10 +14811,12 @@ function scheduleUsageReporting(state, params) {
14024
14811
  let phase = "dormant";
14025
14812
  let rearmRequested = false;
14026
14813
  const armProbe = () => {
14814
+ if (!state.running) return;
14027
14815
  phase = "probe-pending";
14028
14816
  params.setTimer(setTimeout(() => void tick(true), params.firstDelayMs()));
14029
14817
  };
14030
14818
  const scheduleNextTick = () => {
14819
+ if (!state.running) return;
14031
14820
  if (rearmRequested) {
14032
14821
  rearmRequested = false;
14033
14822
  armProbe();
@@ -14061,6 +14850,7 @@ function scheduleUsageReporting(state, params) {
14061
14850
  phase = "tick-in-flight";
14062
14851
  try {
14063
14852
  const usage = await params.fetchUsage();
14853
+ if (!state.running) return;
14064
14854
  const result = await params.report(usage);
14065
14855
  if (result.ok) {
14066
14856
  if (consecutiveFailures > 0) {
@@ -14199,6 +14989,7 @@ function scheduleResourceUsageReporting(state, options) {
14199
14989
  message: lowDiskDecision.warning
14200
14990
  });
14201
14991
  }
14992
+ if (!state.running) return;
14202
14993
  const result = await reportResourceUsage(state.agentId, state.authHeader, usage);
14203
14994
  if (result.ok) {
14204
14995
  if (consecutiveFailures > 0) {
@@ -14231,7 +15022,9 @@ function scheduleResourceUsageReporting(state, options) {
14231
15022
  message: `Resource usage reporting failed: ${message}${failureStreakSuffix(consecutiveFailures)}`
14232
15023
  });
14233
15024
  } finally {
14234
- state.resourceUsageTimer = setTimeout(() => void tick(), usageReportDelayMs());
15025
+ if (state.running) {
15026
+ state.resourceUsageTimer = setTimeout(() => void tick(), usageReportDelayMs());
15027
+ }
14235
15028
  }
14236
15029
  };
14237
15030
  state.resourceUsageTimer = setTimeout(() => void tick(), firstReportDelayMs());
@@ -14393,8 +15186,8 @@ async function beginGracefulShutdown(state, trigger) {
14393
15186
  return true;
14394
15187
  }
14395
15188
  );
14396
- const timedOut = new Promise((resolve4) => {
14397
- timer = setTimeout(() => resolve4(false), telemetryBudgetMs);
15189
+ const timedOut = new Promise((resolve5) => {
15190
+ timer = setTimeout(() => resolve5(false), telemetryBudgetMs);
14398
15191
  });
14399
15192
  if (!await Promise.race([flushed, timedOut])) {
14400
15193
  log2(state, `Telemetry flush exceeded ${telemetryBudgetMs}ms \u2014 exiting anyway`, "warn");
@@ -14434,6 +15227,8 @@ async function run(options) {
14434
15227
  port: options.port ?? 4096,
14435
15228
  conversationFilter: options.conversation ?? null,
14436
15229
  idleTimeout: options.idleTimeout ?? null,
15230
+ stayAwakeSeconds: null,
15231
+ stayAwakeUntilMs: null,
14437
15232
  json: options.json ?? false,
14438
15233
  interactive,
14439
15234
  logLevel,
@@ -14457,6 +15252,7 @@ async function run(options) {
14457
15252
  messageCount: 0,
14458
15253
  lastProxiedActivityAt: null,
14459
15254
  sessionCleanupTimers: [],
15255
+ sessionDeleteFailures: /* @__PURE__ */ new Map(),
14460
15256
  claudeUsageTimer: null,
14461
15257
  claudeUsageRearm: null,
14462
15258
  openaiUsageTimer: null,
@@ -14622,6 +15418,17 @@ async function run(options) {
14622
15418
  }
14623
15419
  spinner?.succeed(`Runner: ${validation.agent.name || state.agentId}`);
14624
15420
  state.agentName = validation.agent.name;
15421
+ const requestedStayAwakeSeconds = validation.agent?.wake_stay_awake_seconds;
15422
+ if (typeof requestedStayAwakeSeconds === "number" && Number.isFinite(requestedStayAwakeSeconds) && requestedStayAwakeSeconds > 0) {
15423
+ state.stayAwakeSeconds = requestedStayAwakeSeconds;
15424
+ } else if (requestedStayAwakeSeconds !== void 0 && requestedStayAwakeSeconds !== null) {
15425
+ state.stayAwakeSeconds = null;
15426
+ log2(
15427
+ state,
15428
+ `Ignoring invalid wake_stay_awake_seconds (type: ${typeof requestedStayAwakeSeconds})`,
15429
+ "warn"
15430
+ );
15431
+ }
14625
15432
  const microvmId = process.env.MICROVM_ID?.trim();
14626
15433
  if (microvmId) {
14627
15434
  const reported = await reportMicrovmId(state.agentId, state.authHeader, microvmId);
@@ -14665,23 +15472,33 @@ async function run(options) {
14665
15472
  );
14666
15473
  }
14667
15474
  }
14668
- if (options.restoreRunnerCredentials) {
14669
- log2(state, "Restoring runner credentials before starting OpenCode");
14670
- const credentialContext = {
14671
- env: process.env,
14672
- log: (message, level = "info") => {
14673
- if (level === "error") {
14674
- logActivity(state, { type: "error", error: message });
14675
- } else {
14676
- logActivity(state, { type: "info", level, message });
14677
- }
15475
+ const credentialContext = {
15476
+ env: process.env,
15477
+ log: (message, level = "info") => {
15478
+ if (level === "error") {
15479
+ logActivity(state, { type: "error", error: message });
15480
+ } else {
15481
+ logActivity(state, { type: "info", level, message });
14678
15482
  }
14679
- };
14680
- const githubTokenPopulated = await installRunnerSecret(credentialContext);
15483
+ }
15484
+ };
15485
+ const githubTokenPopulated = await installRunnerSecret(credentialContext);
15486
+ if (options.restoreRunnerCredentials) {
14681
15487
  await restoreCredentialStores(credentialContext);
14682
- if (githubTokenPopulated) await configureGitHubAccess(credentialContext);
14683
15488
  }
15489
+ if (githubTokenPopulated) await configureGitHubAccess(credentialContext);
14684
15490
  state.credentialSync?.arm();
15491
+ const dependencyInstallDiagnosticReporter = createDependencyInstallDiagnosticReporter({
15492
+ context: {
15493
+ homeDir: homedir7(),
15494
+ cwd: process.cwd(),
15495
+ microvmId: process.env.MICROVM_ID?.trim(),
15496
+ euid: process.getuid?.(),
15497
+ egid: process.getgid?.()
15498
+ },
15499
+ emitEvent: (message) => logActivity(state, { type: "info", level: "warn", message }),
15500
+ emitLocal: (message) => logLocalOnly(state, message, "warn")
15501
+ });
14685
15502
  const openCodeActivityForwarder = createOpenCodeActivityForwarder(
14686
15503
  () => ({
14687
15504
  agentId: state.agentId,
@@ -14692,7 +15509,8 @@ async function run(options) {
14692
15509
  if (cause !== null && sessionId !== null) {
14693
15510
  state.sessionStoreHealth.observeCause(sessionId, cause);
14694
15511
  }
14695
- }
15512
+ },
15513
+ dependencyInstallDiagnosticReporter
14696
15514
  );
14697
15515
  const openCodeLogTail = tailOpenCodeLogFile(
14698
15516
  resolveOpenCodeLogPath(homedir7(), process.env),
@@ -14854,7 +15672,7 @@ async function run(options) {
14854
15672
  logActivity(state, { type: "info", level: "warn", message: versionWarning });
14855
15673
  }
14856
15674
  }
14857
- await reloadProviderCache(state.port, state.opencodeClient ?? void 0);
15675
+ await disposeAndReloadProviderConfig(state.port, state.opencodeClient ?? void 0);
14858
15676
  if (state.opencodeApiVersion === "v2" && state.opencodeClient !== null) {
14859
15677
  await importOpenCodeV2CredentialsForState(state);
14860
15678
  }
@@ -15025,6 +15843,13 @@ async function run(options) {
15025
15843
  type: "info",
15026
15844
  message: connectionMessage
15027
15845
  });
15846
+ if (!isReconnect && state.stayAwakeSeconds !== null && state.stayAwakeUntilMs === null) {
15847
+ state.stayAwakeUntilMs = Date.now() + state.stayAwakeSeconds * 1e3;
15848
+ logActivity(state, {
15849
+ type: "info",
15850
+ message: `Staying awake for at least ${state.stayAwakeSeconds}s as requested by the wake`
15851
+ });
15852
+ }
15028
15853
  if (options.tunnelReadyFile) {
15029
15854
  const marker = writeTunnelReadyMarker(options.tunnelReadyFile, agentId);
15030
15855
  if (marker.ok) {
@@ -15159,6 +15984,7 @@ async function run(options) {
15159
15984
  if (error2.message === "Unauthorized") tunnelSpinner?.fail("Unauthorized");
15160
15985
  throw error2;
15161
15986
  }
15987
+ if (!state.running) return;
15162
15988
  scheduleSessionCleanup(state, channelDriver, options);
15163
15989
  state.claudeUsageRearm = scheduleClaudeUsageReporting(state, options);
15164
15990
  state.openaiUsageRearm = scheduleUsageReporting(state, {