@evident-ai/cli 3.4.1-dev.77d5cb6 → 3.4.1-dev.86701df

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
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/index.ts
4
- import { createRequire } from "module";
4
+ import { createRequire as createRequire2 } from "module";
5
5
  import { Command } from "commander";
6
6
 
7
7
  // src/commands/login.ts
@@ -371,14 +371,14 @@ function blank() {
371
371
  console.log();
372
372
  }
373
373
  function waitForEnter(prompt = "Press Enter to continue...") {
374
- return new Promise((resolve3) => {
374
+ return new Promise((resolve4) => {
375
375
  process.stdout.write(chalk.dim(prompt));
376
376
  const handler = () => {
377
377
  process.stdin.removeListener("data", handler);
378
378
  process.stdin.setRawMode?.(false);
379
379
  process.stdin.pause();
380
380
  console.log();
381
- resolve3();
381
+ resolve4();
382
382
  };
383
383
  if (process.stdin.isTTY) {
384
384
  process.stdin.setRawMode?.(true);
@@ -388,7 +388,7 @@ function waitForEnter(prompt = "Press Enter to continue...") {
388
388
  });
389
389
  }
390
390
  function sleep(ms) {
391
- return new Promise((resolve3) => setTimeout(resolve3, ms));
391
+ return new Promise((resolve4) => setTimeout(resolve4, ms));
392
392
  }
393
393
 
394
394
  // src/commands/login.ts
@@ -466,19 +466,19 @@ async function tokenLogin() {
466
466
  );
467
467
  blank();
468
468
  process.stdout.write("Paste token: ");
469
- const token = await new Promise((resolve3) => {
469
+ const token = await new Promise((resolve4) => {
470
470
  let data = "";
471
471
  process.stdin.setEncoding("utf8");
472
472
  process.stdin.on("data", (chunk) => {
473
473
  data += chunk;
474
474
  });
475
475
  process.stdin.on("end", () => {
476
- resolve3(data.trim());
476
+ resolve4(data.trim());
477
477
  });
478
478
  if (process.stdin.isTTY) {
479
479
  process.stdin.once("data", (chunk) => {
480
480
  process.stdin.pause();
481
- resolve3(chunk.toString().trim());
481
+ resolve4(chunk.toString().trim());
482
482
  });
483
483
  process.stdin.resume();
484
484
  }
@@ -763,6 +763,13 @@ function toReportedOpenAiWindow(window) {
763
763
  resets_at: window.resetsAt
764
764
  };
765
765
  }
766
+ function toReportedOpenAiSubscription(snapshot) {
767
+ if (!snapshot.subscription) return null;
768
+ return {
769
+ owner_email: snapshot.subscription.ownerEmail,
770
+ plan_type: snapshot.subscription.planType
771
+ };
772
+ }
766
773
  async function reportOpenAiUsage(agentId, authHeader, snapshot) {
767
774
  try {
768
775
  const apiUrl = getApiUrlConfig();
@@ -773,7 +780,8 @@ async function reportOpenAiUsage(agentId, authHeader, snapshot) {
773
780
  primary: toReportedOpenAiWindow(snapshot.primary),
774
781
  secondary: toReportedOpenAiWindow(snapshot.secondary),
775
782
  has_credits: snapshot.hasCredits,
776
- credits_unlimited: snapshot.creditsUnlimited
783
+ credits_unlimited: snapshot.creditsUnlimited,
784
+ subscription: toReportedOpenAiSubscription(snapshot)
777
785
  }),
778
786
  signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
779
787
  });
@@ -797,6 +805,7 @@ async function reportResourceUsage(agentId, authHeader, usage) {
797
805
  headers: { Authorization: authHeader, "Content-Type": "application/json" },
798
806
  body: JSON.stringify({
799
807
  cpu_percent: usage.cpuPercent,
808
+ cpu_peak_percent: usage.cpuPeakPercent,
800
809
  cpu_count: usage.cpuCount,
801
810
  memory_total_bytes: usage.memoryTotalBytes,
802
811
  memory_available_bytes: usage.memoryAvailableBytes,
@@ -1183,8 +1192,9 @@ async function claudeUsage() {
1183
1192
  }
1184
1193
 
1185
1194
  // src/commands/run.ts
1186
- import { homedir as homedir4 } from "os";
1187
- import { isAbsolute as isAbsolute2, join as join7, parse, resolve as resolvePath } from "path";
1195
+ import { chmodSync as chmodSync3, existsSync as existsSync3, readFileSync as readFileSync6, writeFileSync as writeFileSync6 } from "fs";
1196
+ import { homedir as homedir5 } from "os";
1197
+ import { isAbsolute as isAbsolute3, join as join9, parse, resolve as resolvePath2 } from "path";
1188
1198
  import chalk6 from "chalk";
1189
1199
 
1190
1200
  // ../../packages/types/src/agents/index.ts
@@ -1524,7 +1534,14 @@ function drainSessionDbRecoveryReport({
1524
1534
  skippedLines++;
1525
1535
  return [];
1526
1536
  }
1527
- return [value];
1537
+ return [
1538
+ {
1539
+ ...value,
1540
+ provenance_reason: value.provenance_reason ?? null,
1541
+ provenance_migration_delta: value.provenance_migration_delta ?? null,
1542
+ replication_suspended: value.replication_suspended ?? false
1543
+ }
1544
+ ];
1528
1545
  } catch (error2) {
1529
1546
  skippedLines++;
1530
1547
  console.error(
@@ -1549,12 +1566,39 @@ function buildSessionDbRecoveryActivity(record) {
1549
1566
  const level = record.severity === "warning" ? "warn" : record.severity === "error" ? "error" : null;
1550
1567
  if (!level) return null;
1551
1568
  const noVerifiedPoint = record.verified_restore_point ? ` The verified restore point is ${record.verified_restore_point}.` : " No verified restore point is known.";
1569
+ const replication = record.replication_suspended ? " This start is not backing up its new session history; restart after fixing the cause." : "";
1570
+ const giveupMessage = (() => {
1571
+ switch (record.reason) {
1572
+ case "restore_deadline_exceeded":
1573
+ return "The restore did not finish before this startup deadline. Earlier sessions are unavailable for this start; collect the SESSION-DB-RESTORE-TRUNCATED boot log before retrying.";
1574
+ case "restore_tool_unusable":
1575
+ case "classification_unrecognised":
1576
+ return "The restore or classification tool produced an unsupported result. Inspect the named boot marker or log and repair the runner image or bundle before restarting.";
1577
+ case "synchroniser_config_unevaluable":
1578
+ case "synchroniser_config_incomplete":
1579
+ return "The installed hook and synchroniser bundle could not agree on configuration. Inspect the named boot marker or log and repair the runner image or bundle before restarting.";
1580
+ case "synchroniser_config_unresolved":
1581
+ return "The synchroniser configuration could not be resolved. Inspect the preceding boot error and repair the identified runner image, bundle, or local environment before restarting.";
1582
+ case "litestream_config_unavailable":
1583
+ return "The local Litestream configuration could not be generated or written. Inspect the preceding boot error and repair the runner image, bundle, local environment, or write permissions before restarting.";
1584
+ case "classification_fatal":
1585
+ return "Session history could not be restored because backup setup could not be established. Inspect the named boot marker or log and repair the identified backup configuration or permissions.";
1586
+ default:
1587
+ return null;
1588
+ }
1589
+ })();
1590
+ if (giveupMessage)
1591
+ return {
1592
+ level,
1593
+ metadata: withoutContractFields(record),
1594
+ message: `${giveupMessage}${replication}`
1595
+ };
1552
1596
  switch (record.outcome) {
1553
1597
  case "fresh_session_db":
1554
1598
  return {
1555
1599
  level,
1556
1600
  metadata: withoutContractFields(record),
1557
- message: `This runner started with a fresh session database. Earlier sessions are unavailable, and queued conversation or session references from before this start may no longer resolve.${noVerifiedPoint} Review the runner's backup configuration before relying on restored session history.`
1601
+ message: `This runner started with a fresh session database. Earlier sessions are unavailable, and queued conversation or session references from before this start may no longer resolve.${noVerifiedPoint} Review the runner's backup configuration before relying on restored session history.${replication}`
1558
1602
  };
1559
1603
  case "restore_retried":
1560
1604
  return {
@@ -1592,7 +1636,7 @@ function buildSessionDbRecoveryActivity(record) {
1592
1636
  return {
1593
1637
  level,
1594
1638
  metadata: withoutContractFields(record),
1595
- message: "This runner started with a fresh session database because it could not verify where its session history is backed up. Nothing in the backup was changed; check the runner backup configuration and permissions."
1639
+ message: `This runner started without restoring session history because it could not verify where its session history is backed up. Nothing in the backup was changed; check the runner backup configuration and permissions.${replication}`
1596
1640
  };
1597
1641
  case "session_db_boot_refused":
1598
1642
  return {
@@ -1600,6 +1644,12 @@ function buildSessionDbRecoveryActivity(record) {
1600
1644
  metadata: withoutContractFields(record),
1601
1645
  message: `This runner did not come online because its damaged session database could not be safely separated from its active backup or proven removed. Backed-up session history remains readable at ${record.quarantine_destination ?? "its original location or the quarantine destination named in the boot logs"}; any local session-database files that remain were left in place and nothing opened or wrote them. See the runner boot logs for SESSION-DB-LOCAL-DISCARD-FAILED details.`
1602
1646
  };
1647
+ case "schema_provenance_mismatch":
1648
+ return {
1649
+ level,
1650
+ metadata: withoutContractFields(record),
1651
+ message: `Session database schema provenance mismatch for ${record.dbPath ?? record.db_path ?? "unknown"}: recorded version=${record.recorded_version ?? "unknown"}, current version=${record.current_version ?? "unknown"}, reason=${record.provenance_reason ?? "unknown"}, migration delta=${record.provenance_migration_delta ?? "unknown"}. Inspect the session database and runner backup before continuing.`
1652
+ };
1603
1653
  default:
1604
1654
  return null;
1605
1655
  }
@@ -1614,7 +1664,8 @@ var OUTCOMES = /* @__PURE__ */ new Set([
1614
1664
  "fresh_session_db",
1615
1665
  "history_rolled_back",
1616
1666
  "restore_misconfigured",
1617
- "session_db_boot_refused"
1667
+ "session_db_boot_refused",
1668
+ "schema_provenance_mismatch"
1618
1669
  ]);
1619
1670
  var STAGES = /* @__PURE__ */ new Set(["restore", "verify"]);
1620
1671
  var SEVERITIES = /* @__PURE__ */ new Set(["warning", "error"]);
@@ -1632,7 +1683,7 @@ var STRING_OR_NULL_FIELDS = ["quarantine_destination", "verified_restore_point"]
1632
1683
  function isSessionDbRecoveryRecord(value) {
1633
1684
  if (!value || typeof value !== "object" || Array.isArray(value)) return false;
1634
1685
  const record = value;
1635
- return record.v === 1 && record.event === "session_db_recovery" && typeof record.at === "string" && STAGES.has(record.stage) && OUTCOMES.has(record.outcome) && SEVERITIES.has(record.severity) && typeof record.reason === "string" && NUMBER_FIELDS.every((field) => record[field] === null || Number.isInteger(record[field])) && STRING_OR_NULL_FIELDS.every(
1686
+ return record.v === 1 && record.event === "session_db_recovery" && typeof record.at === "string" && STAGES.has(record.stage) && OUTCOMES.has(record.outcome) && SEVERITIES.has(record.severity) && typeof record.reason === "string" && (record.replication_suspended === void 0 || typeof record.replication_suspended === "boolean") && (record.provenance_reason === void 0 || record.provenance_reason === null || typeof record.provenance_reason === "string") && (record.provenance_migration_delta === void 0 || record.provenance_migration_delta === null || Number.isInteger(record.provenance_migration_delta)) && NUMBER_FIELDS.every((field) => record[field] === null || Number.isInteger(record[field])) && STRING_OR_NULL_FIELDS.every(
1636
1687
  (field) => record[field] === null || typeof record[field] === "string"
1637
1688
  );
1638
1689
  }
@@ -1661,11 +1712,667 @@ async function waitForOpenCodeHealth(port, timeoutMs = 3e4) {
1661
1712
  if (health.healthy) {
1662
1713
  return health;
1663
1714
  }
1664
- await new Promise((resolve3) => setTimeout(resolve3, 1e3));
1715
+ await new Promise((resolve4) => setTimeout(resolve4, 1e3));
1665
1716
  }
1666
1717
  return { healthy: false, error: "Timeout waiting for OpenCode to be healthy" };
1667
1718
  }
1668
1719
 
1720
+ // src/lib/opencode/session-db-boot.ts
1721
+ import { spawn as spawn2 } from "child_process";
1722
+ import { mkdirSync, statSync as statSync2, unlinkSync as unlinkSync2, writeFileSync } from "fs";
1723
+ import { homedir as homedir2 } from "os";
1724
+ import { dirname as dirname2, resolve as resolvePath } from "path";
1725
+
1726
+ // src/lib/runner-synchroniser.ts
1727
+ import { spawn } from "child_process";
1728
+ function appendError(stderr, error2) {
1729
+ const message = error2 instanceof Error ? error2.message : String(error2);
1730
+ return stderr === "" ? message : `${stderr}
1731
+ ${message}`;
1732
+ }
1733
+ function runSynchroniser(args, opts) {
1734
+ return new Promise((resolve4) => {
1735
+ let child;
1736
+ let stdout = "";
1737
+ let stderr = "";
1738
+ let settled = false;
1739
+ const timer = {};
1740
+ let abortListener;
1741
+ let spawnListener;
1742
+ const finish = (result) => {
1743
+ if (settled) return;
1744
+ settled = true;
1745
+ if (timer.handle) clearTimeout(timer.handle);
1746
+ if (abortListener) opts.signal?.removeEventListener("abort", abortListener);
1747
+ if (spawnListener) child.removeListener("spawn", spawnListener);
1748
+ resolve4(result);
1749
+ };
1750
+ try {
1751
+ child = spawn("runner-synchroniser", args, {
1752
+ env: opts.env ?? process.env,
1753
+ stdio: ["ignore", "pipe", "pipe"]
1754
+ });
1755
+ } catch (error2) {
1756
+ finish({ code: null, stdout, stderr: appendError(stderr, error2), timedOut: false });
1757
+ return;
1758
+ }
1759
+ child.stdout?.setEncoding("utf8");
1760
+ child.stdout?.on("data", (chunk) => {
1761
+ stdout += chunk;
1762
+ });
1763
+ child.stderr?.setEncoding("utf8");
1764
+ child.stderr?.on("data", (chunk) => {
1765
+ stderr += chunk;
1766
+ });
1767
+ child.once("error", (error2) => {
1768
+ finish({ code: null, stdout, stderr: appendError(stderr, error2), timedOut: false });
1769
+ });
1770
+ child.once("close", (code) => {
1771
+ finish({ code, stdout, stderr, timedOut: false });
1772
+ });
1773
+ if (opts.signal) {
1774
+ const killChild = () => {
1775
+ if (child.pid === void 0) {
1776
+ if (!spawnListener) {
1777
+ spawnListener = killChild;
1778
+ child.once("spawn", spawnListener);
1779
+ }
1780
+ return;
1781
+ }
1782
+ child.kill("SIGKILL");
1783
+ };
1784
+ abortListener = killChild;
1785
+ if (opts.signal.aborted) {
1786
+ abortListener();
1787
+ } else {
1788
+ opts.signal.addEventListener("abort", abortListener, { once: true });
1789
+ if (opts.signal.aborted) abortListener();
1790
+ }
1791
+ }
1792
+ timer.handle = setTimeout(
1793
+ () => {
1794
+ child.kill("SIGKILL");
1795
+ finish({ code: null, stdout, stderr, timedOut: true });
1796
+ },
1797
+ Math.max(0, opts.timeoutMs)
1798
+ );
1799
+ });
1800
+ }
1801
+
1802
+ // src/lib/opencode/session-db-boot.ts
1803
+ var SESSION_DB_RESTORE_TIMEOUT_MS = 3e5;
1804
+ var SESSION_DB_VERIFY_TIMEOUT_MS = 12e4;
1805
+ var SESSION_DB_SYNCHRONISER_TIMEOUT_MS = 12e4;
1806
+ var SESSION_DB_VERIFY_WALKBACK_BUDGET_SECONDS = 120;
1807
+ function commandError(result) {
1808
+ return result.stderr.trim() || `process exited with code ${result.code ?? "null"}`;
1809
+ }
1810
+ function reportRecord(stage, outcome, reason, litestreamExitCode, options) {
1811
+ options.reportRecovery({
1812
+ v: 1,
1813
+ event: "session_db_recovery",
1814
+ at: (/* @__PURE__ */ new Date()).toISOString(),
1815
+ stage,
1816
+ outcome,
1817
+ severity: "error",
1818
+ reason,
1819
+ litestream_exit_code: litestreamExitCode,
1820
+ attempt: null,
1821
+ replica_objects: null,
1822
+ replica_bytes: null,
1823
+ quarantine_destination: null,
1824
+ quarantined_objects: null,
1825
+ quarantine_failed_objects: null,
1826
+ quarantined_bytes: null,
1827
+ verified_restore_point: null,
1828
+ restore_points_tried: null,
1829
+ provenance_reason: null,
1830
+ provenance_migration_delta: null,
1831
+ replication_suspended: stage === "restore"
1832
+ });
1833
+ }
1834
+ function clearMarker(options) {
1835
+ if (!options.noReplicateMarker) return;
1836
+ try {
1837
+ unlinkSync2(options.noReplicateMarker);
1838
+ } catch (error2) {
1839
+ if (error2 instanceof Error && "code" in error2 && error2.code === "ENOENT") return;
1840
+ options.log(
1841
+ `Could not clear the previous session-DB no-replicate marker ${options.noReplicateMarker}: ${error2 instanceof Error ? error2.message : String(error2)}`,
1842
+ "warn"
1843
+ );
1844
+ }
1845
+ }
1846
+ function markNoReplicate(options, message) {
1847
+ if (options.noReplicateMarker) {
1848
+ try {
1849
+ mkdirSync(dirname2(options.noReplicateMarker), { recursive: true });
1850
+ writeFileSync(options.noReplicateMarker, "");
1851
+ } catch (error2) {
1852
+ options.log(
1853
+ `Could not write session-DB no-replicate marker ${options.noReplicateMarker}: ${error2 instanceof Error ? error2.message : String(error2)}`,
1854
+ "error"
1855
+ );
1856
+ }
1857
+ }
1858
+ options.log(`SESSION-DB-NO-REPLICATE: ${message}`, "warn");
1859
+ }
1860
+ function discardSessionDbDebris(options) {
1861
+ for (const path of [options.dbPath, `${options.dbPath}-wal`, `${options.dbPath}-shm`]) {
1862
+ try {
1863
+ unlinkSync2(path);
1864
+ } catch (error2) {
1865
+ if (error2 instanceof Error && "code" in error2 && error2.code === "ENOENT") continue;
1866
+ options.log(
1867
+ `Could not remove session-DB debris ${path}: ${error2 instanceof Error ? error2.message : String(error2)}`,
1868
+ "warn"
1869
+ );
1870
+ }
1871
+ }
1872
+ }
1873
+ function splitDiagnostics(text) {
1874
+ return text.split("\n").map((line) => line.trim()).filter((line) => line.length > 0);
1875
+ }
1876
+ function logSynchroniserDiagnostics(result, options) {
1877
+ for (const line of splitDiagnostics(result.stderr)) options.log(line, "warn");
1878
+ }
1879
+ function parseSingleQuotedAssignment(line) {
1880
+ const match = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(line);
1881
+ if (!match || !match[2].startsWith("'")) return null;
1882
+ const valueSource = match[2];
1883
+ let value = "";
1884
+ for (let index = 1; index < valueSource.length; index++) {
1885
+ const character = valueSource[index];
1886
+ if (character !== "'") {
1887
+ value += character;
1888
+ continue;
1889
+ }
1890
+ if (index === valueSource.length - 1) return [match[1], value];
1891
+ if (valueSource.slice(index + 1, index + 4) !== "\\''") return null;
1892
+ value += "'";
1893
+ index += 3;
1894
+ }
1895
+ return null;
1896
+ }
1897
+ function parseSynchroniserEnv(stdout) {
1898
+ const values = {};
1899
+ for (const line of stdout.split("\n")) {
1900
+ if (line.trim() === "") continue;
1901
+ const assignment = parseSingleQuotedAssignment(line);
1902
+ if (!assignment) return null;
1903
+ values[assignment[0]] = assignment[1];
1904
+ }
1905
+ return values;
1906
+ }
1907
+ function runCommand(command, args, options) {
1908
+ return new Promise((resolve4) => {
1909
+ let child;
1910
+ let stdout = "";
1911
+ let stderr = "";
1912
+ let settled = false;
1913
+ const finish = (result) => {
1914
+ if (settled) return;
1915
+ settled = true;
1916
+ if (timer) clearTimeout(timer);
1917
+ resolve4(result);
1918
+ };
1919
+ try {
1920
+ child = spawn2(command, args, {
1921
+ env: options.env,
1922
+ stdio: ["ignore", "pipe", "pipe"]
1923
+ });
1924
+ } catch (error2) {
1925
+ resolve4({
1926
+ code: null,
1927
+ stdout,
1928
+ stderr: error2 instanceof Error ? error2.message : String(error2),
1929
+ timedOut: false
1930
+ });
1931
+ return;
1932
+ }
1933
+ child.stdout?.setEncoding("utf8");
1934
+ child.stdout?.on("data", (chunk) => {
1935
+ stdout += chunk;
1936
+ });
1937
+ child.stderr?.setEncoding("utf8");
1938
+ child.stderr?.on("data", (chunk) => {
1939
+ stderr += chunk;
1940
+ });
1941
+ child.once("error", (error2) => {
1942
+ finish({
1943
+ code: null,
1944
+ stdout,
1945
+ stderr: stderr === "" ? error2.message : `${stderr}
1946
+ ${error2.message}`,
1947
+ timedOut: false
1948
+ });
1949
+ });
1950
+ child.once("close", (code) => finish({ code, stdout, stderr, timedOut: false }));
1951
+ const timer = setTimeout(
1952
+ () => {
1953
+ child.kill("SIGKILL");
1954
+ finish({ code: null, stdout, stderr, timedOut: true });
1955
+ },
1956
+ Math.max(0, options.timeoutMs)
1957
+ );
1958
+ });
1959
+ }
1960
+ async function ensureLitestreamConfig(options, env) {
1961
+ const configPath = options.litestreamConfig;
1962
+ if (!configPath) {
1963
+ markNoReplicate(options, "no Litestream configuration path was provided");
1964
+ reportRecord(
1965
+ "restore",
1966
+ "restore_misconfigured",
1967
+ "litestream_config_unavailable",
1968
+ null,
1969
+ options
1970
+ );
1971
+ return null;
1972
+ }
1973
+ try {
1974
+ if (statSync2(configPath).size > 0) return configPath;
1975
+ } catch (error2) {
1976
+ if (!(error2 instanceof Error && "code" in error2 && error2.code === "ENOENT")) {
1977
+ options.log(
1978
+ `Could not inspect ${configPath}: ${error2 instanceof Error ? error2.message : String(error2)}`,
1979
+ "warn"
1980
+ );
1981
+ }
1982
+ }
1983
+ const rendered = await runSynchroniser(["litestream-config"], {
1984
+ timeoutMs: SESSION_DB_SYNCHRONISER_TIMEOUT_MS,
1985
+ env
1986
+ });
1987
+ logSynchroniserDiagnostics(rendered, options);
1988
+ if (rendered.timedOut || rendered.code !== 0) {
1989
+ options.log(
1990
+ `Could not generate ${configPath}: runner-synchroniser litestream-config failed (${commandError(rendered)})`,
1991
+ "error"
1992
+ );
1993
+ markNoReplicate(options, `could not generate ${configPath}`);
1994
+ reportRecord(
1995
+ "restore",
1996
+ "restore_misconfigured",
1997
+ "litestream_config_unavailable",
1998
+ null,
1999
+ options
2000
+ );
2001
+ return null;
2002
+ }
2003
+ try {
2004
+ mkdirSync(dirname2(configPath), { recursive: true });
2005
+ writeFileSync(configPath, rendered.stdout);
2006
+ } catch (error2) {
2007
+ options.log(
2008
+ `Could not write ${configPath}: ${error2 instanceof Error ? error2.message : String(error2)}`,
2009
+ "error"
2010
+ );
2011
+ markNoReplicate(options, `could not generate ${configPath}`);
2012
+ reportRecord(
2013
+ "restore",
2014
+ "restore_misconfigured",
2015
+ "litestream_config_unavailable",
2016
+ null,
2017
+ options
2018
+ );
2019
+ return null;
2020
+ }
2021
+ const version2 = await runCommand("litestream", ["version"], {
2022
+ env,
2023
+ timeoutMs: 1e4
2024
+ });
2025
+ const litestreamVersion = version2.code === 0 ? version2.stdout.trim() || "unknown" : "unknown";
2026
+ const regionEmpty = !/^\s*region:\s*\S+/m.test(rendered.stdout);
2027
+ options.log(
2028
+ `litestream ${litestreamVersion}; AWS_REGION=${env.AWS_REGION ?? "<unset>"} AWS_DEFAULT_REGION=${env.AWS_DEFAULT_REGION ?? "<unset>"}; rendered litestream.yml region empty: ${regionEmpty ? "yes" : "no"}`
2029
+ );
2030
+ return configPath;
2031
+ }
2032
+ function restoreGiveUp(options, reason, message, litestreamExitCode, outcome = "fresh_session_db") {
2033
+ discardSessionDbDebris(options);
2034
+ markNoReplicate(options, message);
2035
+ reportRecord("restore", outcome, reason, litestreamExitCode, options);
2036
+ }
2037
+ async function restoreSessionDb(options, configPath, env) {
2038
+ const restored = await runCommand(
2039
+ "litestream",
2040
+ ["restore", "-config", configPath, "-if-db-not-exists", "-if-replica-exists", options.dbPath],
2041
+ { env, timeoutMs: SESSION_DB_RESTORE_TIMEOUT_MS }
2042
+ );
2043
+ for (const line of splitDiagnostics(restored.stderr)) options.log(line, "warn");
2044
+ if (restored.timedOut || restored.code === 124 || restored.code === 137) {
2045
+ restoreGiveUp(
2046
+ options,
2047
+ "restore_deadline_exceeded",
2048
+ `SESSION-DB-RESTORE-TRUNCATED: litestream restore did not finish within ${SESSION_DB_RESTORE_TIMEOUT_MS}ms; opencode starts with a fresh session DB and nothing is replicated this boot`,
2049
+ restored.code ?? 124
2050
+ );
2051
+ return;
2052
+ }
2053
+ if (restored.code === null || restored.code === 125 || restored.code === 126 || restored.code === 127) {
2054
+ options.log(`litestream restore could not run (${commandError(restored)})`, "error");
2055
+ restoreGiveUp(
2056
+ options,
2057
+ "restore_tool_unusable",
2058
+ `restore tool is broken (${commandError(restored)}); opencode starts with a fresh session DB and nothing is replicated this boot`,
2059
+ restored.code
2060
+ );
2061
+ return;
2062
+ }
2063
+ const classified = await runSynchroniser(
2064
+ [
2065
+ "session-db-classify",
2066
+ String(restored.code ?? 1),
2067
+ "1",
2068
+ "--on-unusable-replica=leave",
2069
+ "--fresh-db-fallback"
2070
+ ],
2071
+ { timeoutMs: SESSION_DB_SYNCHRONISER_TIMEOUT_MS, env }
2072
+ );
2073
+ logSynchroniserDiagnostics(classified, options);
2074
+ const classifyCode = classified.code;
2075
+ switch (classifyCode) {
2076
+ case 0:
2077
+ return;
2078
+ case 31:
2079
+ acknowledgeSessionDbRecoveryReport(sessionDbRecoveryReportPath(homedir2(), env));
2080
+ options.log(
2081
+ "SESSION-DB-REPLICA-UNUSABLE: booting with a fresh opencode.db and replicating into the existing prefix this boot",
2082
+ "warn"
2083
+ );
2084
+ return;
2085
+ case 32:
2086
+ acknowledgeSessionDbRecoveryReport(sessionDbRecoveryReportPath(homedir2(), env));
2087
+ discardSessionDbDebris(options);
2088
+ markNoReplicate(
2089
+ options,
2090
+ "session-db-classify asked for another restore attempt (32), but this boot has budget for only one; treating it as a give-up rather than retrying"
2091
+ );
2092
+ return;
2093
+ case 30:
2094
+ restoreGiveUp(
2095
+ options,
2096
+ "classification_fatal",
2097
+ "session-db-classify returned fatal (30); see the FATAL message above",
2098
+ restored.code,
2099
+ "restore_misconfigured"
2100
+ );
2101
+ return;
2102
+ default:
2103
+ restoreGiveUp(
2104
+ options,
2105
+ "classification_unrecognised",
2106
+ `session-db-classify exited ${classifyCode ?? "null"}, which is none of its documented answers`,
2107
+ restored.code
2108
+ );
2109
+ }
2110
+ }
2111
+ async function verifySessionDb(options, configPath, env) {
2112
+ if (!options.noReplicateMarker || !fileExists(options.noReplicateMarker)) {
2113
+ const result = await runSynchroniser(["session-db-verify", configPath], {
2114
+ timeoutMs: SESSION_DB_VERIFY_TIMEOUT_MS,
2115
+ env: {
2116
+ ...env,
2117
+ // The synchroniser reads this value in SECONDS. Keep this at 120, not
2118
+ // 120_000, so the walkback gives up before the outer process bound.
2119
+ EVIDENT_SESSION_DB_WALKBACK_BUDGET_SECONDS: String(
2120
+ SESSION_DB_VERIFY_WALKBACK_BUDGET_SECONDS
2121
+ )
2122
+ }
2123
+ });
2124
+ logSynchroniserDiagnostics(result, options);
2125
+ if (result.timedOut || result.code === 124 || result.code === 137) {
2126
+ options.log(
2127
+ `SESSION-DB-VERIFY-TIMEOUT: verification did not finish within its ${SESSION_DB_VERIFY_TIMEOUT_MS}ms deadline; continuing with the restored opencode.db as-is, unverified`,
2128
+ "warn"
2129
+ );
2130
+ return false;
2131
+ }
2132
+ if (result.code === 34) {
2133
+ reportRecord(
2134
+ "verify",
2135
+ "session_db_boot_refused",
2136
+ result.stderr.includes("SESSION-DB-LOCAL-DISCARD-FAILED") ? "local_discard_failed" : "replica_separation_unproven",
2137
+ null,
2138
+ options
2139
+ );
2140
+ return true;
2141
+ }
2142
+ if (result.code === 33) {
2143
+ options.log(
2144
+ "SESSION-DB-INTEGRITY-EXHAUSTED: booting continues and litestream still replicates, starting an empty backup chain after the corrupt replica was separated.",
2145
+ "warn"
2146
+ );
2147
+ return false;
2148
+ }
2149
+ if (result.code !== 0) {
2150
+ options.log(
2151
+ `SESSION-DB-VERIFY-UNKNOWN: session-db-verify exited ${result.code ?? "null"}, which is none of its documented answers; continuing with the restored opencode.db as-is`,
2152
+ "warn"
2153
+ );
2154
+ }
2155
+ return false;
2156
+ }
2157
+ options.log(
2158
+ "skipping session-DB verification: this boot's session DB was not proven safe to replicate",
2159
+ "debug"
2160
+ );
2161
+ return false;
2162
+ }
2163
+ function fileExists(path) {
2164
+ try {
2165
+ statSync2(path);
2166
+ return true;
2167
+ } catch (error2) {
2168
+ if (error2 instanceof Error && "code" in error2 && error2.code === "ENOENT") return false;
2169
+ return true;
2170
+ }
2171
+ }
2172
+ async function restoreAndVerifySessionDb(options) {
2173
+ const env = options.env ?? process.env;
2174
+ clearMarker(options);
2175
+ acknowledgeSessionDbRecoveryReport(sessionDbRecoveryReportPath(homedir2(), env));
2176
+ const synchroniserEnv = await runSynchroniser(["env"], {
2177
+ timeoutMs: SESSION_DB_SYNCHRONISER_TIMEOUT_MS,
2178
+ env
2179
+ });
2180
+ logSynchroniserDiagnostics(synchroniserEnv, options);
2181
+ if (synchroniserEnv.timedOut || synchroniserEnv.code !== 0) {
2182
+ options.log(
2183
+ `runner-synchroniser env could not resolve the session-DB configuration (${commandError(synchroniserEnv)})`,
2184
+ "error"
2185
+ );
2186
+ markNoReplicate(
2187
+ options,
2188
+ "could not resolve the runner-synchroniser configuration (see the ERROR above)"
2189
+ );
2190
+ reportRecord(
2191
+ "restore",
2192
+ "restore_misconfigured",
2193
+ "synchroniser_config_unresolved",
2194
+ null,
2195
+ options
2196
+ );
2197
+ return { verifyFatal: false };
2198
+ }
2199
+ const values = parseSynchroniserEnv(synchroniserEnv.stdout);
2200
+ if (!values) {
2201
+ markNoReplicate(
2202
+ options,
2203
+ "the runner-synchroniser configuration could not be evaluated; the installed bundle likely does not match this hook"
2204
+ );
2205
+ reportRecord(
2206
+ "restore",
2207
+ "restore_misconfigured",
2208
+ "synchroniser_config_unevaluable",
2209
+ null,
2210
+ options
2211
+ );
2212
+ return { verifyFatal: false };
2213
+ }
2214
+ const synchroniserDbPath = values.OPENCODE_DB_PATH;
2215
+ if (!synchroniserDbPath) {
2216
+ markNoReplicate(
2217
+ options,
2218
+ "run_synchroniser env did not define OPENCODE_DB_PATH; the installed runner-synchroniser build likely does not match this hook"
2219
+ );
2220
+ reportRecord(
2221
+ "restore",
2222
+ "restore_misconfigured",
2223
+ "synchroniser_config_incomplete",
2224
+ null,
2225
+ options
2226
+ );
2227
+ return { verifyFatal: false };
2228
+ }
2229
+ if (resolvePath(synchroniserDbPath) !== resolvePath(options.dbPath)) {
2230
+ options.log(
2231
+ `runner-synchroniser reported OPENCODE_DB_PATH=${synchroniserDbPath}, but OpenCode uses ${options.dbPath}; continuing with OpenCode's session-DB path`,
2232
+ "warn"
2233
+ );
2234
+ }
2235
+ if (!values.PERSISTENCE_BUCKET) {
2236
+ options.log(
2237
+ "SESSION-DB-PERSISTENCE-DISABLED: LITESTREAM_BUCKET/LITESTREAM_PREFIX are not both set; opencode starts with a fresh session DB and nothing is replicated.",
2238
+ "warn"
2239
+ );
2240
+ return { verifyFatal: false };
2241
+ }
2242
+ const configPath = await ensureLitestreamConfig(options, env);
2243
+ if (!configPath) return { verifyFatal: false };
2244
+ await restoreSessionDb(options, configPath, env);
2245
+ if (options.noReplicateMarker && fileExists(options.noReplicateMarker)) {
2246
+ return { verifyFatal: false };
2247
+ }
2248
+ return { verifyFatal: await verifySessionDb(options, configPath, env) };
2249
+ }
2250
+
2251
+ // src/lib/opencode/session-db-provenance.ts
2252
+ import { createRequire } from "module";
2253
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
2254
+ import { dirname as dirname3, join as join3 } from "path";
2255
+ var require2 = createRequire(import.meta.url);
2256
+ function readSessionDbMigrationIds(dbPath) {
2257
+ let db;
2258
+ try {
2259
+ const { DatabaseSync } = require2("node:sqlite");
2260
+ db = new DatabaseSync(dbPath, { readOnly: true });
2261
+ const columns = db.prepare("PRAGMA table_info(migration)").all();
2262
+ const hasExpectedShape = columns.length === 2 && columns.some(
2263
+ (column) => column.name === "id" && typeof column.type === "string" && column.type.toUpperCase() === "TEXT" && column.pk === 1
2264
+ ) && columns.some(
2265
+ (column) => column.name === "time_completed" && typeof column.type === "string" && column.type.toUpperCase() === "INTEGER" && column.notnull === 1 && column.pk === 0
2266
+ );
2267
+ if (!hasExpectedShape) {
2268
+ console.warn(`[readSessionDbMigrationIds] unsupported migration table shape in ${dbPath}`);
2269
+ return null;
2270
+ }
2271
+ const rows = db.prepare("SELECT id FROM migration ORDER BY id").all();
2272
+ if (rows.some((row) => typeof row.id !== "string")) return null;
2273
+ return rows.map((row) => row.id);
2274
+ } catch (error2) {
2275
+ console.warn(
2276
+ `[readSessionDbMigrationIds] could not read migration history from ${dbPath}: ${error2 instanceof Error ? error2.message : String(error2)}`
2277
+ );
2278
+ return null;
2279
+ } finally {
2280
+ try {
2281
+ db?.close();
2282
+ } catch (error2) {
2283
+ console.warn(
2284
+ `[readSessionDbMigrationIds] could not close ${dbPath}: ${error2 instanceof Error ? error2.message : String(error2)}`
2285
+ );
2286
+ }
2287
+ }
2288
+ }
2289
+ function sessionDbProvenanceStatePath(homeDir, env) {
2290
+ const override = env.EVIDENT_SESSION_DB_PROVENANCE_STATE?.trim();
2291
+ return override || join3(homeDir, ".local", "state", "evident", "session-db-provenance.json");
2292
+ }
2293
+ function loadSessionDbProvenanceState(path) {
2294
+ let value;
2295
+ try {
2296
+ value = JSON.parse(readFileSync3(path, "utf8"));
2297
+ } catch (error2) {
2298
+ if (error2 instanceof Error && "code" in error2 && error2.code === "ENOENT") return {};
2299
+ console.error(
2300
+ `[session-db-provenance] could not read ${path}: ${error2 instanceof Error ? error2.message : String(error2)}`
2301
+ );
2302
+ return {};
2303
+ }
2304
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
2305
+ console.error(`[session-db-provenance] ignored malformed state in ${path}`);
2306
+ return {};
2307
+ }
2308
+ const state = {};
2309
+ for (const [dbPath, record] of Object.entries(value)) {
2310
+ if (!isSessionDbProvenanceRecord(record)) {
2311
+ console.error(`[session-db-provenance] ignored malformed state in ${path}`);
2312
+ return {};
2313
+ }
2314
+ state[dbPath] = record;
2315
+ }
2316
+ return state;
2317
+ }
2318
+ function saveSessionDbProvenanceState(path, state) {
2319
+ try {
2320
+ mkdirSync2(dirname3(path), { recursive: true });
2321
+ writeFileSync2(path, `${JSON.stringify(state, null, 2)}
2322
+ `, "utf8");
2323
+ } catch (error2) {
2324
+ console.error(
2325
+ `[session-db-provenance] could not write ${path}: ${error2 instanceof Error ? error2.message : String(error2)}`
2326
+ );
2327
+ }
2328
+ }
2329
+ function evaluateSessionDbProvenance(input) {
2330
+ const { currentVersion, currentIds, previous } = input;
2331
+ if (!previous) return { anomaly: false, reason: null };
2332
+ const current = new Set(currentIds);
2333
+ const prior = new Set(previous.migrationIds);
2334
+ for (const id of prior) {
2335
+ if (!current.has(id)) return { anomaly: true, reason: "migration-history-regressed" };
2336
+ }
2337
+ if (current.size > prior.size && previous.opencodeVersion === currentVersion) {
2338
+ return { anomaly: true, reason: "foreign-version-migrations" };
2339
+ }
2340
+ return { anomaly: false, reason: null };
2341
+ }
2342
+ function checkSessionDbProvenance(input) {
2343
+ const { dbPath, currentVersion, homeDir, env } = input;
2344
+ const path = sessionDbProvenanceStatePath(homeDir, env);
2345
+ const state = loadSessionDbProvenanceState(path);
2346
+ const previous = state[dbPath];
2347
+ const currentIds = readSessionDbMigrationIds(dbPath);
2348
+ if (currentIds === null) {
2349
+ return {
2350
+ anomaly: false,
2351
+ reason: null,
2352
+ recordedVersion: previous?.opencodeVersion ?? null,
2353
+ migrationDelta: null
2354
+ };
2355
+ }
2356
+ const decision = evaluateSessionDbProvenance({ currentVersion, currentIds, previous });
2357
+ const migrationDelta = previous ? new Set(currentIds).size - new Set(previous.migrationIds).size : null;
2358
+ state[dbPath] = {
2359
+ opencodeVersion: currentVersion,
2360
+ migrationIds: currentIds,
2361
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
2362
+ };
2363
+ saveSessionDbProvenanceState(path, state);
2364
+ return {
2365
+ ...decision,
2366
+ recordedVersion: previous?.opencodeVersion ?? null,
2367
+ migrationDelta
2368
+ };
2369
+ }
2370
+ function isSessionDbProvenanceRecord(value) {
2371
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
2372
+ const record = value;
2373
+ return typeof record.opencodeVersion === "string" && Array.isArray(record.migrationIds) && record.migrationIds.every((id) => typeof id === "string") && typeof record.updatedAt === "string";
2374
+ }
2375
+
1669
2376
  // src/lib/opencode/opencode-version-gate.ts
1670
2377
  var QUEUE_VALIDATED_OPENCODE_VERSIONS = ["1.17.11", "1.18.3"];
1671
2378
  function isQueueValidatedVersion(version2) {
@@ -1680,7 +2387,63 @@ function buildOpenCodeVersionWarning(version2) {
1680
2387
  }
1681
2388
 
1682
2389
  // src/lib/opencode/process.ts
1683
- import { execSync, spawn } from "child_process";
2390
+ import { execSync, spawn as spawn3 } from "child_process";
2391
+
2392
+ // src/lib/process-stop.ts
2393
+ async function stopProcessAndWait(child, timeoutMs, sendTerm, sendKill) {
2394
+ if (!child.pid) {
2395
+ return { outcome: "not-running", code: child.exitCode, signal: child.signalCode };
2396
+ }
2397
+ if (child.exitCode !== null || child.signalCode !== null) {
2398
+ return { outcome: "exited", code: child.exitCode, signal: child.signalCode };
2399
+ }
2400
+ return new Promise((resolve4, reject) => {
2401
+ let forced = false;
2402
+ let settled = false;
2403
+ const timer = setTimeout(() => {
2404
+ forced = true;
2405
+ try {
2406
+ sendKill();
2407
+ } catch (error2) {
2408
+ if (error2.code === "ESRCH") {
2409
+ finish({ outcome: "exited", code: child.exitCode, signal: child.signalCode });
2410
+ } else {
2411
+ fail(error2);
2412
+ }
2413
+ }
2414
+ }, timeoutMs);
2415
+ const finish = (result) => {
2416
+ if (settled) return;
2417
+ settled = true;
2418
+ clearTimeout(timer);
2419
+ child.removeListener("exit", onExit);
2420
+ resolve4(result);
2421
+ };
2422
+ const fail = (error2) => {
2423
+ if (settled) return;
2424
+ settled = true;
2425
+ clearTimeout(timer);
2426
+ child.removeListener("exit", onExit);
2427
+ reject(error2);
2428
+ };
2429
+ const onExit = (code, signal) => {
2430
+ finish({ outcome: forced ? "killed" : "exited", code, signal });
2431
+ };
2432
+ child.once("exit", onExit);
2433
+ try {
2434
+ sendTerm();
2435
+ } catch (error2) {
2436
+ if (error2.code === "ESRCH") {
2437
+ finish({ outcome: "exited", code: child.exitCode, signal: child.signalCode });
2438
+ } else {
2439
+ fail(error2);
2440
+ }
2441
+ return;
2442
+ }
2443
+ });
2444
+ }
2445
+
2446
+ // src/lib/opencode/process.ts
1684
2447
  var OPENCODE_PORT_RANGE = [4096, 4097, 4098, 4099, 4100];
1685
2448
  function getProcessCwd(pid) {
1686
2449
  const platform = process.platform;
@@ -1836,39 +2599,45 @@ async function findHealthyOpenCodeInstances() {
1836
2599
  }
1837
2600
  return healthy;
1838
2601
  }
1839
- async function startOpenCode(port) {
2602
+ async function startOpenCode(port, options = {}) {
1840
2603
  let command = "opencode";
1841
- let args = ["serve", "--port", port.toString(), "--hostname", "127.0.0.1"];
2604
+ const printLogs = options.inheritStdio ? ["--print-logs"] : [];
2605
+ let args = ["serve", "--port", port.toString(), "--hostname", "127.0.0.1", ...printLogs];
1842
2606
  try {
1843
2607
  execSync("which opencode", { stdio: "ignore" });
1844
2608
  } catch {
1845
2609
  command = "npx";
1846
- args = ["opencode", "serve", "--port", port.toString(), "--hostname", "127.0.0.1"];
1847
- }
1848
- const child = spawn(command, args, {
2610
+ args = [
2611
+ "opencode",
2612
+ "serve",
2613
+ "--port",
2614
+ port.toString(),
2615
+ "--hostname",
2616
+ "127.0.0.1",
2617
+ ...printLogs
2618
+ ];
2619
+ }
2620
+ const child = spawn3(command, args, {
1849
2621
  detached: true,
1850
- stdio: "ignore",
2622
+ stdio: options.inheritStdio ? "inherit" : "ignore",
1851
2623
  cwd: process.cwd()
1852
2624
  });
1853
2625
  return child;
1854
2626
  }
1855
- function stopOpenCode(opencodeProcess) {
1856
- if (!opencodeProcess || !opencodeProcess.pid) {
1857
- return;
1858
- }
1859
- try {
2627
+ function stopOpenCodeAndWait(opencodeProcess, timeoutMs) {
2628
+ const sendSignal = (signal) => {
1860
2629
  if (process.platform === "win32") {
1861
- opencodeProcess.kill("SIGTERM");
2630
+ opencodeProcess.kill(signal);
1862
2631
  } else {
1863
- process.kill(-opencodeProcess.pid, "SIGTERM");
2632
+ process.kill(-opencodeProcess.pid, signal);
1864
2633
  }
1865
- } catch (err) {
1866
- if (err.code !== "ESRCH") {
1867
- console.warn(
1868
- `stopOpenCode: kill failed: ${err instanceof Error ? err.message : String(err)}`
1869
- );
1870
- }
1871
- }
2634
+ };
2635
+ return stopProcessAndWait(
2636
+ opencodeProcess,
2637
+ timeoutMs,
2638
+ () => sendSignal("SIGTERM"),
2639
+ () => sendSignal("SIGKILL")
2640
+ );
1872
2641
  }
1873
2642
 
1874
2643
  // src/lib/opencode/install.ts
@@ -2155,6 +2924,7 @@ async function createOpenCodeSession(port, directory) {
2155
2924
  return data.id;
2156
2925
  }
2157
2926
  async function getModelAttachmentCapability(port, model) {
2927
+ const { model: baseModel } = splitModelVariant(model);
2158
2928
  try {
2159
2929
  const res = await timedFetch(`${opencodeBase(port)}/config/providers`);
2160
2930
  if (!res.ok) {
@@ -2171,9 +2941,9 @@ async function getModelAttachmentCapability(port, model) {
2171
2941
  );
2172
2942
  return null;
2173
2943
  }
2174
- const slash = model ? model.indexOf("/") : -1;
2175
- const providerId = slash > 0 ? model.slice(0, slash) : void 0;
2176
- let modelId = slash > 0 ? model.slice(slash + 1) : void 0;
2944
+ const slash = baseModel ? baseModel.indexOf("/") : -1;
2945
+ const providerId = slash > 0 ? baseModel.slice(0, slash) : void 0;
2946
+ let modelId = slash > 0 ? baseModel.slice(slash + 1) : void 0;
2177
2947
  const defaults2 = body?.default && typeof body.default === "object" ? body.default : void 0;
2178
2948
  let provider = providerId ? providers.find((p) => p?.id === providerId) : void 0;
2179
2949
  if (!provider && !providerId) {
@@ -2253,6 +3023,29 @@ async function buildFileParts(attachments, capable) {
2253
3023
  }
2254
3024
  return { parts, outcomes, capabilityUnknown };
2255
3025
  }
3026
+ function splitModelVariant(raw) {
3027
+ const value = raw?.trim();
3028
+ if (!value) return {};
3029
+ const hashIndex = value.indexOf("#");
3030
+ if (hashIndex === -1) return { model: value };
3031
+ const model = value.slice(0, hashIndex).trim() || void 0;
3032
+ const variant = value.slice(hashIndex + 1).trim() || void 0;
3033
+ return { model, variant };
3034
+ }
3035
+ function applyModelOptions(body, options) {
3036
+ if (options?.agent) body.agent = options.agent;
3037
+ const { model, variant } = splitModelVariant(options?.model);
3038
+ if (model) {
3039
+ const slashIndex = model.indexOf("/");
3040
+ if (slashIndex !== -1) {
3041
+ body.model = {
3042
+ providerID: model.substring(0, slashIndex),
3043
+ modelID: model.substring(slashIndex + 1)
3044
+ };
3045
+ }
3046
+ }
3047
+ if (variant) body.variant = variant;
3048
+ }
2256
3049
  function messageText(m) {
2257
3050
  if (!m || !Array.isArray(m.parts)) return "";
2258
3051
  return m.parts.filter((p) => p.type === "text" && typeof p.text === "string").map((p) => p.text).join("");
@@ -2277,18 +3070,7 @@ async function sendPromptAsync(port, sessionId, content, options, attachments) {
2277
3070
  const body = {
2278
3071
  parts
2279
3072
  };
2280
- if (options?.agent) {
2281
- body.agent = options.agent;
2282
- }
2283
- if (options?.model) {
2284
- const slashIndex = options.model.indexOf("/");
2285
- if (slashIndex !== -1) {
2286
- body.model = {
2287
- providerID: options.model.substring(0, slashIndex),
2288
- modelID: options.model.substring(slashIndex + 1)
2289
- };
2290
- }
2291
- }
3073
+ applyModelOptions(body, options);
2292
3074
  const res = await timedFetch(`${opencodeBase(port)}/session/${sessionId}/prompt_async`, {
2293
3075
  method: "POST",
2294
3076
  headers: { "Content-Type": "application/json" },
@@ -2296,7 +3078,10 @@ async function sendPromptAsync(port, sessionId, content, options, attachments) {
2296
3078
  });
2297
3079
  if (res.status < 200 || res.status >= 300) {
2298
3080
  const text = await res.text().catch(() => "");
2299
- throw new Error(`OpenCode prompt_async failed: HTTP ${res.status}${text ? `: ${text}` : ""}`);
3081
+ const { variant } = splitModelVariant(options?.model);
3082
+ throw new Error(
3083
+ `OpenCode prompt_async failed: HTTP ${res.status}${text ? `: ${text}` : ""}${variant ? ` (variant: ${variant})` : ""}`
3084
+ );
2300
3085
  }
2301
3086
  const READ_BACK_ATTEMPTS = 5;
2302
3087
  const READ_BACK_DELAY_MS = 150;
@@ -2320,7 +3105,7 @@ async function sendPromptAsync(port, sessionId, content, options, attachments) {
2320
3105
  }
2321
3106
  }
2322
3107
  if (attempt < READ_BACK_ATTEMPTS - 1) {
2323
- await new Promise((resolve3) => setTimeout(resolve3, READ_BACK_DELAY_MS));
3108
+ await new Promise((resolve4) => setTimeout(resolve4, READ_BACK_DELAY_MS));
2324
3109
  }
2325
3110
  }
2326
3111
  return null;
@@ -2451,7 +3236,7 @@ function isPreamblePinnedRunning(messages, userMessageId) {
2451
3236
  return completedOf(reply) != null && finishOf(reply) === "tool-calls";
2452
3237
  }
2453
3238
  function isB2AbandonmentConfirmed(params) {
2454
- return params.pinnedForMs >= params.minPinnedMs && params.descendantOngoing === false;
3239
+ return params.pinnedForMs >= params.minPinnedMs && params.descendantOngoing === false && params.rootOngoing === false;
2455
3240
  }
2456
3241
  function isAmbiguousTerminalFinish(m) {
2457
3242
  if (completedOf(m) == null) return false;
@@ -2464,7 +3249,7 @@ function isAmbiguousFinishPinnedRunning(messages, userMessageId) {
2464
3249
  return isAmbiguousTerminalFinish(reply);
2465
3250
  }
2466
3251
  function isAmbiguousFinishResolved(params) {
2467
- return params.sessionOngoing === false || params.pinnedForMs >= params.maxPinnedMs;
3252
+ return params.sessionOngoing === false || params.sessionOngoing !== true && params.pinnedForMs >= params.maxPinnedMs;
2468
3253
  }
2469
3254
  function messageError(messages, userMessageId) {
2470
3255
  const reply = findLastAssistantReplyFor(messages, userMessageId);
@@ -2673,13 +3458,13 @@ function resolveSessionCleanupConfig(flags, env = process.env) {
2673
3458
  }
2674
3459
 
2675
3460
  // src/lib/opencode/session-db-size.ts
2676
- import { statSync as statSync2 } from "fs";
2677
- import { join as join3 } from "path";
3461
+ import { statSync as statSync3 } from "fs";
3462
+ import { join as join4 } from "path";
2678
3463
  var LARGE_DB_THRESHOLD_BYTES = 268435456;
2679
3464
  function statSessionDbBytes(homeDir) {
2680
- const dbPath = join3(homeDir, ".local", "share", "opencode", "opencode.db");
3465
+ const dbPath = join4(homeDir, ".local", "share", "opencode", "opencode.db");
2681
3466
  try {
2682
- return statSync2(dbPath).size;
3467
+ return statSync3(dbPath).size;
2683
3468
  } catch (err) {
2684
3469
  const isMissingFile = err instanceof Error && "code" in err && err.code === "ENOENT";
2685
3470
  if (!isMissingFile) {
@@ -2705,11 +3490,11 @@ function buildSessionStoreSizeWarning(input) {
2705
3490
  }
2706
3491
 
2707
3492
  // src/lib/opencode/session-db-reclaim.ts
2708
- import { statSync as statSync3, statfsSync } from "fs";
2709
- import { dirname as dirname2 } from "path";
3493
+ import { statSync as statSync4, statfsSync } from "fs";
3494
+ import { dirname as dirname4 } from "path";
2710
3495
  function insufficientSpaceReason(dbPath, requiredBytes) {
2711
3496
  try {
2712
- const fsStats = statfsSync(dirname2(dbPath));
3497
+ const fsStats = statfsSync(dirname4(dbPath));
2713
3498
  const availableBytes = fsStats.bavail * fsStats.bsize;
2714
3499
  if (availableBytes < requiredBytes) {
2715
3500
  return `only ${availableBytes} bytes free, need ${requiredBytes} for a second copy`;
@@ -2778,7 +3563,7 @@ async function reclaimSessionDbSpace(input) {
2778
3563
  );
2779
3564
  return { ok: false, skipped: "full-vacuum-blocked" };
2780
3565
  }
2781
- const fileBytesForGuard = statSync3(dbPath).size;
3566
+ const fileBytesForGuard = statSync4(dbPath).size;
2782
3567
  const skipReason = insufficientSpaceReason(dbPath, fileBytesForGuard);
2783
3568
  if (skipReason !== null) {
2784
3569
  console.warn(
@@ -2906,12 +3691,12 @@ var StreamForwarder = class {
2906
3691
  let endBody;
2907
3692
  if (has_body) {
2908
3693
  const chunks = [];
2909
- bodyPromise = new Promise((resolve3) => {
3694
+ bodyPromise = new Promise((resolve4) => {
2910
3695
  pushBody = (buf) => {
2911
3696
  chunks.push(buf);
2912
3697
  };
2913
3698
  endBody = () => {
2914
- resolve3(Buffer.concat(chunks));
3699
+ resolve4(Buffer.concat(chunks));
2915
3700
  };
2916
3701
  });
2917
3702
  }
@@ -3040,7 +3825,7 @@ function connectTunnel(options) {
3040
3825
  } = options;
3041
3826
  const tunnelUrl = getTunnelUrlConfig();
3042
3827
  const url = `${tunnelUrl}/tunnel/${agentId}/connect`;
3043
- return new Promise((resolve3, reject) => {
3828
+ return new Promise((resolve4, reject) => {
3044
3829
  const ws = new WebSocket2(url, {
3045
3830
  headers: {
3046
3831
  Authorization: authHeader
@@ -3091,8 +3876,8 @@ function connectTunnel(options) {
3091
3876
  try {
3092
3877
  message = JSON.parse(data.toString());
3093
3878
  } catch (error2) {
3094
- const errorMessage = error2 instanceof Error ? error2.message : "Unknown error";
3095
- onError?.(`Failed to handle message: ${errorMessage}`);
3879
+ const errorMessage2 = error2 instanceof Error ? error2.message : "Unknown error";
3880
+ onError?.(`Failed to handle message: ${errorMessage2}`);
3096
3881
  return;
3097
3882
  }
3098
3883
  if (isStreamFrame(message)) {
@@ -3104,7 +3889,7 @@ function connectTunnel(options) {
3104
3889
  clearTimeout(connectionTimeout);
3105
3890
  const connectedAgentId = message.agent_id ?? agentId;
3106
3891
  onConnected?.(connectedAgentId);
3107
- resolve3({
3892
+ resolve4({
3108
3893
  ws,
3109
3894
  close: () => ws.close(1e3, "CLI shutdown")
3110
3895
  });
@@ -3235,10 +4020,10 @@ var RunnerConnection = class {
3235
4020
  };
3236
4021
 
3237
4022
  // src/lib/tunnel/ready-marker.ts
3238
- import { writeFileSync } from "fs";
4023
+ import { writeFileSync as writeFileSync3 } from "fs";
3239
4024
  function writeTunnelReadyMarker(path, agentId) {
3240
4025
  try {
3241
- writeFileSync(path, `${agentId}
4026
+ writeFileSync3(path, `${agentId}
3242
4027
  `);
3243
4028
  return { ok: true };
3244
4029
  } catch (error2) {
@@ -3246,10 +4031,52 @@ function writeTunnelReadyMarker(path, agentId) {
3246
4031
  }
3247
4032
  }
3248
4033
 
4034
+ // src/lib/replication.ts
4035
+ import { spawn as spawn4 } from "child_process";
4036
+ function startSessionDbReplication(configPath) {
4037
+ return spawn4("litestream", ["replicate", "-config", configPath], {
4038
+ stdio: "inherit"
4039
+ });
4040
+ }
4041
+ async function stopSessionDbReplication(child, timeoutMs) {
4042
+ return stopProcessAndWait(
4043
+ child,
4044
+ timeoutMs,
4045
+ () => child.kill("SIGTERM"),
4046
+ () => child.kill("SIGKILL")
4047
+ );
4048
+ }
4049
+
4050
+ // src/lib/process-liveness.ts
4051
+ import { readFileSync as readFileSync4 } from "fs";
4052
+ function isProcessAlive(pid) {
4053
+ try {
4054
+ process.kill(pid, 0);
4055
+ } catch (error2) {
4056
+ const code = error2.code;
4057
+ if (code === "ESRCH") return false;
4058
+ if (code === "EPERM") return true;
4059
+ console.error(
4060
+ `[process-liveness] could not probe process ${pid}: ${error2 instanceof Error ? error2.message : String(error2)}`
4061
+ );
4062
+ return false;
4063
+ }
4064
+ if (process.platform !== "linux") return true;
4065
+ try {
4066
+ const status2 = readFileSync4(`/proc/${pid}/status`, "utf8");
4067
+ return !/^State:\s+Z(?:\s|$)/m.test(status2);
4068
+ } catch (error2) {
4069
+ console.error(
4070
+ `[process-liveness] could not inspect /proc/${pid}/status: ${error2 instanceof Error ? error2.message : String(error2)}`
4071
+ );
4072
+ return true;
4073
+ }
4074
+ }
4075
+
3249
4076
  // src/lib/openai-usage.ts
3250
- import { readFileSync as readFileSync3 } from "fs";
3251
- import { homedir as homedir2 } from "os";
3252
- import { join as join4 } from "path";
4077
+ import { readFileSync as readFileSync5 } from "fs";
4078
+ import { homedir as homedir3 } from "os";
4079
+ import { join as join5 } from "path";
3253
4080
  var CODEX_RESPONSES_URL = "https://chatgpt.com/backend-api/codex/responses";
3254
4081
  var OPENCODE_AUTH_SEGMENTS = [".local", "share", "opencode", "auth.json"];
3255
4082
  var OpenAiUsageError = class extends Error {
@@ -3263,7 +4090,7 @@ function isLocalCredentialProblem2(err) {
3263
4090
  }
3264
4091
  function readOpenCodeChatGptCredentials() {
3265
4092
  try {
3266
- const raw = readFileSync3(join4(homedir2(), ...OPENCODE_AUTH_SEGMENTS), "utf-8");
4093
+ const raw = readFileSync5(join5(homedir3(), ...OPENCODE_AUTH_SEGMENTS), "utf-8");
3267
4094
  let parsed;
3268
4095
  try {
3269
4096
  parsed = JSON.parse(raw);
@@ -3285,6 +4112,23 @@ function readOpenCodeChatGptCredentials() {
3285
4112
  return null;
3286
4113
  }
3287
4114
  }
4115
+ function parseChatGptIdentity(accessToken) {
4116
+ const segments = accessToken.split(".");
4117
+ if (segments.length !== 3) return null;
4118
+ let payload;
4119
+ try {
4120
+ const parsed = JSON.parse(Buffer.from(segments[1], "base64url").toString("utf8"));
4121
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return null;
4122
+ payload = parsed;
4123
+ } catch {
4124
+ return null;
4125
+ }
4126
+ const profile = payload["https://api.openai.com/profile"];
4127
+ const auth = payload["https://api.openai.com/auth"];
4128
+ const ownerEmail = typeof profile?.email === "string" ? profile.email.trim() || null : null;
4129
+ const planType = typeof auth?.chatgpt_plan_type === "string" ? auth.chatgpt_plan_type.trim() || null : null;
4130
+ return ownerEmail === null && planType === null ? null : { ownerEmail, planType };
4131
+ }
3288
4132
  function toWindow2(headers, name) {
3289
4133
  const utilizationHeader = headers.get(`x-codex-${name}-used-percent`);
3290
4134
  const windowMinutesHeader = headers.get(`x-codex-${name}-window-minutes`);
@@ -3360,6 +4204,7 @@ async function getOpenAiUsage(port) {
3360
4204
  "credentials_expired"
3361
4205
  );
3362
4206
  }
4207
+ const subscription = parseChatGptIdentity(credentials2.accessToken);
3363
4208
  const models = await resolveProbeModels(port);
3364
4209
  if (models.length === 0) {
3365
4210
  throw new OpenAiUsageError("No supported OpenAI probe model is available.", "no_probe_model");
@@ -3392,7 +4237,7 @@ async function getOpenAiUsage(port) {
3392
4237
  "no_usable_window"
3393
4238
  );
3394
4239
  }
3395
- return usage;
4240
+ return { ...usage, subscription };
3396
4241
  }
3397
4242
  if (res.status === 401) {
3398
4243
  throw new OpenAiUsageError(
@@ -3593,58 +4438,97 @@ function readDisk(homeDir) {
3593
4438
  };
3594
4439
  }
3595
4440
  }
3596
- function createResourceUsageCollector(homeDir) {
3597
- let previous = readCpuSample();
3598
- return async () => {
4441
+ var CPU_PEAK_WINDOW_MS = 6e4;
4442
+ var CPU_PEAK_WINDOW_SAMPLE_COUNT = 4;
4443
+ var CPU_PEAK_SAMPLE_INTERVAL_MS = CPU_PEAK_WINDOW_MS / CPU_PEAK_WINDOW_SAMPLE_COUNT;
4444
+ function createCpuPeakSampler() {
4445
+ const sampleHistory = new Array(CPU_PEAK_WINDOW_SAMPLE_COUNT);
4446
+ sampleHistory[0] = readCpuSample();
4447
+ let nextSampleIndex = 1;
4448
+ let sampleCount = 1;
4449
+ let peak = null;
4450
+ const timer = setInterval(() => {
3599
4451
  const current = readCpuSample();
3600
- const hostCpuPercent = cpuPercentBetween(previous, current);
3601
- const hostCpuCount = cpus().length;
3602
- previous = current;
3603
- const disk = readDisk(homeDir);
3604
- const opencodeDbBytes = statSessionDbBytes(homeDir);
3605
- const { limits, warning: ecsWarning } = await readEcsTaskLimits(process.env);
3606
- const warnings = [];
3607
- if (disk.warning) warnings.push(disk.warning);
3608
- if (ecsWarning) warnings.push(ecsWarning);
3609
- let cpuPercent = hostCpuPercent;
3610
- let cpuCount = hostCpuCount;
3611
- let memoryTotalBytes = totalmem();
3612
- let memoryAvailableBytes = freemem();
3613
- if (limits !== null) {
3614
- cpuCount = limits.cpuCount;
3615
- memoryTotalBytes = limits.memoryTotalBytes;
3616
- memoryAvailableBytes = clamp(
3617
- limits.memoryTotalBytes - (totalmem() - freemem()),
3618
- 0,
3619
- limits.memoryTotalBytes
3620
- );
3621
- cpuPercent = hostCpuPercent === null ? null : clamp(round2(hostCpuPercent * hostCpuCount / limits.cpuCount), 0, 100);
4452
+ const sampleFromWindowAgo = sampleCount === CPU_PEAK_WINDOW_SAMPLE_COUNT ? sampleHistory[nextSampleIndex] : void 0;
4453
+ if (sampleFromWindowAgo !== void 0) {
4454
+ const percentage = cpuPercentBetween(sampleFromWindowAgo, current);
4455
+ if (percentage !== null) {
4456
+ peak = peak === null ? percentage : Math.max(peak, percentage);
4457
+ }
3622
4458
  }
3623
- return {
3624
- usage: {
3625
- cpuPercent,
3626
- cpuCount,
3627
- memoryTotalBytes,
3628
- memoryAvailableBytes,
3629
- diskTotalBytes: disk.totalBytes,
3630
- diskFreeBytes: disk.freeBytes,
3631
- opencodeDbBytes
3632
- },
3633
- warnings
3634
- };
4459
+ sampleHistory[nextSampleIndex] = current;
4460
+ nextSampleIndex = (nextSampleIndex + 1) % CPU_PEAK_WINDOW_SAMPLE_COUNT;
4461
+ sampleCount = Math.min(sampleCount + 1, CPU_PEAK_WINDOW_SAMPLE_COUNT);
4462
+ }, CPU_PEAK_SAMPLE_INTERVAL_MS);
4463
+ return {
4464
+ takeAndReset: () => {
4465
+ const currentPeak = peak;
4466
+ peak = null;
4467
+ return currentPeak;
4468
+ },
4469
+ stop: () => clearInterval(timer)
4470
+ };
4471
+ }
4472
+ function createResourceUsageCollector(homeDir) {
4473
+ let previous = readCpuSample();
4474
+ const cpuPeakSampler = createCpuPeakSampler();
4475
+ return {
4476
+ collect: async () => {
4477
+ const current = readCpuSample();
4478
+ const hostCpuPercent = cpuPercentBetween(previous, current);
4479
+ const hostCpuPeakPercent = cpuPeakSampler.takeAndReset();
4480
+ const hostCpuCount = cpus().length;
4481
+ previous = current;
4482
+ const disk = readDisk(homeDir);
4483
+ const opencodeDbBytes = statSessionDbBytes(homeDir);
4484
+ const { limits, warning: ecsWarning } = await readEcsTaskLimits(process.env);
4485
+ const warnings = [];
4486
+ if (disk.warning) warnings.push(disk.warning);
4487
+ if (ecsWarning) warnings.push(ecsWarning);
4488
+ let cpuPercent = hostCpuPercent;
4489
+ let cpuPeakPercent = hostCpuPeakPercent;
4490
+ let cpuCount = hostCpuCount;
4491
+ let memoryTotalBytes = totalmem();
4492
+ let memoryAvailableBytes = freemem();
4493
+ if (limits !== null) {
4494
+ cpuCount = limits.cpuCount;
4495
+ memoryTotalBytes = limits.memoryTotalBytes;
4496
+ memoryAvailableBytes = clamp(
4497
+ limits.memoryTotalBytes - (totalmem() - freemem()),
4498
+ 0,
4499
+ limits.memoryTotalBytes
4500
+ );
4501
+ cpuPercent = hostCpuPercent === null ? null : clamp(round2(hostCpuPercent * hostCpuCount / limits.cpuCount), 0, 100);
4502
+ cpuPeakPercent = hostCpuPeakPercent === null ? null : clamp(round2(hostCpuPeakPercent * hostCpuCount / limits.cpuCount), 0, 100);
4503
+ }
4504
+ return {
4505
+ usage: {
4506
+ cpuPercent,
4507
+ cpuPeakPercent,
4508
+ cpuCount,
4509
+ memoryTotalBytes,
4510
+ memoryAvailableBytes,
4511
+ diskTotalBytes: disk.totalBytes,
4512
+ diskFreeBytes: disk.freeBytes,
4513
+ opencodeDbBytes
4514
+ },
4515
+ warnings
4516
+ };
4517
+ },
4518
+ stop: cpuPeakSampler.stop
3635
4519
  };
3636
4520
  }
3637
4521
 
3638
4522
  // src/lib/channels/driver.ts
3639
- import { homedir as homedir3 } from "os";
4523
+ import { homedir as homedir4 } from "os";
3640
4524
 
3641
4525
  // src/lib/runner-file-sync.ts
3642
- import { join as join6 } from "path";
4526
+ import { join as join7 } from "path";
3643
4527
 
3644
4528
  // src/lib/file-push.ts
3645
4529
  import { randomUUID } from "crypto";
3646
4530
  import { chmod, mkdir, open as open2, realpath, rename, unlink } from "fs/promises";
3647
- import { basename, dirname as dirname3, isAbsolute, join as join5, relative, resolve as resolve2, sep } from "path";
4531
+ import { basename, dirname as dirname5, isAbsolute, join as join6, relative, resolve as resolve2, sep } from "path";
3648
4532
  var FILE_MODE = 384;
3649
4533
  var DIRECTORY_MODE = 448;
3650
4534
  async function writePushedFile(request) {
@@ -3675,9 +4559,9 @@ async function writePushedFile(request) {
3675
4559
  }
3676
4560
  try {
3677
4561
  const { existingAncestor, missingSegments } = await resolveNearestExistingAncestor(
3678
- dirname3(candidate)
4562
+ dirname5(candidate)
3679
4563
  );
3680
- const realTarget = join5(existingAncestor, ...missingSegments, basename(candidate));
4564
+ const realTarget = join6(existingAncestor, ...missingSegments, basename(candidate));
3681
4565
  const allowedDirectory = await findContainingAllowedDirectory(allowedDirectories, realTarget);
3682
4566
  if (allowedDirectory === null) {
3683
4567
  return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
@@ -3687,8 +4571,8 @@ async function writePushedFile(request) {
3687
4571
  }
3688
4572
  if (missingSegments.length > 0) {
3689
4573
  await createMissingDirectories(existingAncestor, missingSegments);
3690
- const realParent = await realpath(dirname3(realTarget));
3691
- if (realParent !== dirname3(realTarget) || !contains(allowedDirectory, realTarget)) {
4574
+ const realParent = await realpath(dirname5(realTarget));
4575
+ if (realParent !== dirname5(realTarget) || !contains(allowedDirectory, realTarget)) {
3692
4576
  return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
3693
4577
  path: realTarget,
3694
4578
  bytes,
@@ -3713,7 +4597,7 @@ function expandAndValidate(requestedPath, homeDir) {
3713
4597
  if (requestedPath.trim() === "" || requestedPath.includes("\0")) {
3714
4598
  return null;
3715
4599
  }
3716
- const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join5(homeDir, requestedPath.slice(2)) : requestedPath;
4600
+ const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join6(homeDir, requestedPath.slice(2)) : requestedPath;
3717
4601
  if (expanded.split(/[/\\]/).includes("..")) {
3718
4602
  return null;
3719
4603
  }
@@ -3731,7 +4615,7 @@ async function resolveNearestExistingAncestor(directory) {
3731
4615
  try {
3732
4616
  return { existingAncestor: await realpath(current), missingSegments };
3733
4617
  } catch (err) {
3734
- const parent = dirname3(current);
4618
+ const parent = dirname5(current);
3735
4619
  if (err.code !== "ENOENT" || parent === current) {
3736
4620
  throw err;
3737
4621
  }
@@ -3786,13 +4670,13 @@ function contains(realDirectory, realTarget) {
3786
4670
  async function createMissingDirectories(existingAncestor, missingSegments) {
3787
4671
  let current = existingAncestor;
3788
4672
  for (const segment of missingSegments) {
3789
- current = join5(current, segment);
4673
+ current = join6(current, segment);
3790
4674
  await mkdir(current, { recursive: true, mode: DIRECTORY_MODE });
3791
4675
  await chmod(current, DIRECTORY_MODE);
3792
4676
  }
3793
4677
  }
3794
4678
  async function writeAtomically(realTarget, content) {
3795
- const temporaryPath = join5(dirname3(realTarget), `.evident-push-${randomUUID()}.tmp`);
4679
+ const temporaryPath = join6(dirname5(realTarget), `.evident-push-${randomUUID()}.tmp`);
3796
4680
  let handle;
3797
4681
  try {
3798
4682
  handle = await open2(temporaryPath, "wx", FILE_MODE);
@@ -3922,12 +4806,12 @@ var NOT_APPLIED = {
3922
4806
  opencodeAuthApplied: false
3923
4807
  };
3924
4808
  function isClaudeCredentialPath(requestedPath, homeDir) {
3925
- const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join6(homeDir, requestedPath.slice(2)) : requestedPath;
3926
- return expanded === join6(homeDir, ...CLAUDE_CREDENTIALS_SEGMENTS);
4809
+ const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join7(homeDir, requestedPath.slice(2)) : requestedPath;
4810
+ return expanded === join7(homeDir, ...CLAUDE_CREDENTIALS_SEGMENTS);
3927
4811
  }
3928
4812
  function isOpenCodeAuthPath(requestedPath, homeDir) {
3929
- const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join6(homeDir, requestedPath.slice(2)) : requestedPath;
3930
- return expanded === join6(homeDir, ...OPENCODE_AUTH_SEGMENTS);
4813
+ const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join7(homeDir, requestedPath.slice(2)) : requestedPath;
4814
+ return expanded === join7(homeDir, ...OPENCODE_AUTH_SEGMENTS);
3931
4815
  }
3932
4816
  async function applyOne(options, file) {
3933
4817
  const label = `${file.id.slice(0, 8)} (${file.path})`;
@@ -4454,6 +5338,7 @@ var ChannelDriver = class _ChannelDriver {
4454
5338
  * and stops opencode.
4455
5339
  */
4456
5340
  stopped = false;
5341
+ recycleRequestedFlag = false;
4457
5342
  constructor(config) {
4458
5343
  this.agentId = config.agentId;
4459
5344
  this.port = config.port;
@@ -4473,7 +5358,7 @@ var ChannelDriver = class _ChannelDriver {
4473
5358
  this.stuckQueuedMs = config.stuckQueuedMs ?? DEFAULT_STUCK_QUEUED_MS;
4474
5359
  this.now = config.now ?? (() => Date.now());
4475
5360
  this.fileSyncDirectories = config.fileSyncDirectories ?? [];
4476
- this.homeDir = config.homeDir ?? homedir3();
5361
+ this.homeDir = config.homeDir ?? homedir4();
4477
5362
  this.maxActiveSessions = config.maxActiveSessions;
4478
5363
  this.watcherStallMs = config.watcherStallMs ?? WATCHER_STALL_MS;
4479
5364
  this.wedgeWarningIntervalMs = config.wedgeWarningIntervalMs ?? WEDGE_WARNING_INTERVAL_MS;
@@ -4559,6 +5444,9 @@ var ChannelDriver = class _ChannelDriver {
4559
5444
  let dispatched = 0;
4560
5445
  try {
4561
5446
  const conversations = await this.getPendingConversations();
5447
+ if (this.recycleRequestedFlag) {
5448
+ this.stop();
5449
+ }
4562
5450
  if (conversations.length > 0) {
4563
5451
  const total = conversations.reduce((sum, c) => sum + (c.pending_message_count ?? 0), 0);
4564
5452
  this.log({
@@ -4687,6 +5575,14 @@ var ChannelDriver = class _ChannelDriver {
4687
5575
  stop() {
4688
5576
  this.stopped = true;
4689
5577
  }
5578
+ /**
5579
+ * The server clears this request when a new MicroVM identity is recorded, so a
5580
+ * same-VM tunnel reconnect does not consume it. This is a plain read rather
5581
+ * than a consume; `run.ts` guards the action once-only.
5582
+ */
5583
+ get recycleRequested() {
5584
+ return this.recycleRequestedFlag;
5585
+ }
4690
5586
  /**
4691
5587
  * Wait (up to `timeoutMs`) for in-flight watcher work to settle during a
4692
5588
  * graceful shutdown, so a turn whose reply is ready — or completes within the
@@ -4824,7 +5720,7 @@ var ChannelDriver = class _ChannelDriver {
4824
5720
  this.signalDispatchNotStarted(conv, message, "session_existence_unknown");
4825
5721
  break;
4826
5722
  }
4827
- const errorMessage = err instanceof Error ? err.message : String(err);
5723
+ const errorMessage2 = err instanceof Error ? err.message : String(err);
4828
5724
  this.sessions.delete(conv.id);
4829
5725
  this.supersede(conv.id, sessionId);
4830
5726
  this.log({
@@ -4833,7 +5729,7 @@ var ChannelDriver = class _ChannelDriver {
4833
5729
  conversation_id: conv.id,
4834
5730
  message_id: message.id
4835
5731
  });
4836
- await this.markFailed(conv.id, message.id, null, errorMessage).catch((markErr) => {
5732
+ await this.markFailed(conv.id, message.id, null, errorMessage2).catch((markErr) => {
4837
5733
  this.log({
4838
5734
  level: "warn",
4839
5735
  message: `markFailed PATCH for message ${message.id.slice(0, 8)} (conversation ${conv.id.slice(0, 8)}) failed (best-effort, not retried): ${markErr instanceof Error ? markErr.message : String(markErr)}`,
@@ -4844,7 +5740,7 @@ var ChannelDriver = class _ChannelDriver {
4844
5740
  });
4845
5741
  this.log({
4846
5742
  level: "error",
4847
- message: `Message ${message.id.slice(0, 8)} dispatch failed: ${errorMessage}`,
5743
+ message: `Message ${message.id.slice(0, 8)} dispatch failed: ${errorMessage2}`,
4848
5744
  conversation_id: conv.id,
4849
5745
  message_id: message.id
4850
5746
  });
@@ -4865,14 +5761,14 @@ var ChannelDriver = class _ChannelDriver {
4865
5761
  this.unconfirmedDispatchFailures.delete(message.id);
4866
5762
  this.sessions.delete(conv.id);
4867
5763
  this.supersede(conv.id, sessionId);
4868
- const errorMessage = `OpenCode accepted this message ${streak} times in a row but never confirmed its assigned id (session ${sessionId.slice(0, 8)}'s message list could not be read back) \u2014 the session was abandoned; a fresh one is used for further messages.`;
5764
+ const errorMessage2 = `OpenCode accepted this message ${streak} times in a row but never confirmed its assigned id (session ${sessionId.slice(0, 8)}'s message list could not be read back) \u2014 the session was abandoned; a fresh one is used for further messages.`;
4869
5765
  this.log({
4870
5766
  level: "error",
4871
- message: errorMessage,
5767
+ message: errorMessage2,
4872
5768
  conversation_id: conv.id,
4873
5769
  message_id: message.id
4874
5770
  });
4875
- await this.markFailed(conv.id, message.id, null, errorMessage).catch((markErr) => {
5771
+ await this.markFailed(conv.id, message.id, null, errorMessage2).catch((markErr) => {
4876
5772
  this.log({
4877
5773
  level: "warn",
4878
5774
  message: `markFailed PATCH for message ${message.id.slice(0, 8)} (conversation ${conv.id.slice(0, 8)}) failed (best-effort, not retried): ${markErr instanceof Error ? markErr.message : String(markErr)}`,
@@ -5740,6 +6636,7 @@ var ChannelDriver = class _ChannelDriver {
5740
6636
  deliveryDeadlineAnchored: false,
5741
6637
  b2PinnedSinceMs: 0,
5742
6638
  b2LastDescendantCheckMs: 0,
6639
+ b2RootOngoingHeldLogged: false,
5743
6640
  b2AbandonedSignalled: false,
5744
6641
  ambiguousPinnedSinceMs: 0,
5745
6642
  ambiguousResolved: false
@@ -5834,6 +6731,7 @@ var ChannelDriver = class _ChannelDriver {
5834
6731
  deliveryDeadlineAnchored: false,
5835
6732
  b2PinnedSinceMs: 0,
5836
6733
  b2LastDescendantCheckMs: 0,
6734
+ b2RootOngoingHeldLogged: false,
5837
6735
  b2AbandonedSignalled: false,
5838
6736
  ambiguousPinnedSinceMs: 0,
5839
6737
  ambiguousResolved: false
@@ -6187,6 +7085,7 @@ var ChannelDriver = class _ChannelDriver {
6187
7085
  if (snapshotReadable) {
6188
7086
  inFlight.b2PinnedSinceMs = 0;
6189
7087
  inFlight.b2LastDescendantCheckMs = 0;
7088
+ inFlight.b2RootOngoingHeldLogged = false;
6190
7089
  inFlight.b2AbandonedSignalled = false;
6191
7090
  }
6192
7091
  } else {
@@ -6198,11 +7097,15 @@ var ChannelDriver = class _ChannelDriver {
6198
7097
  const pinnedForMs = this.now() - inFlight.b2PinnedSinceMs;
6199
7098
  if (pinnedForMs >= B2_ABANDONMENT_MIN_PINNED_MS && this.now() - inFlight.b2LastDescendantCheckMs >= B2_ABANDONMENT_RECHECK_MS) {
6200
7099
  inFlight.b2LastDescendantCheckMs = this.now();
6201
- const descendantOngoing = await this.isAnyDescendantSessionOngoing(sessionId);
7100
+ const [descendantOngoing, rootOngoing] = await Promise.all([
7101
+ this.isAnyDescendantSessionOngoing(sessionId),
7102
+ isSessionOngoing(this.port, sessionId)
7103
+ ]);
6202
7104
  if (isB2AbandonmentConfirmed({
6203
7105
  pinnedForMs,
6204
7106
  minPinnedMs: B2_ABANDONMENT_MIN_PINNED_MS,
6205
- descendantOngoing
7107
+ descendantOngoing,
7108
+ rootOngoing
6206
7109
  })) {
6207
7110
  inFlight.b2AbandonedSignalled = true;
6208
7111
  this.log({
@@ -6211,12 +7114,26 @@ var ChannelDriver = class _ChannelDriver {
6211
7114
  conversation_id: conv.id,
6212
7115
  message_id: id
6213
7116
  });
7117
+ const reply = findLastAssistantReplyFor(messages, inFlight.opencodeMessageId);
6214
7118
  void this.postSignal(conv.id, id, "b2_abandoned_resolved", {
6215
- watched_for_ms: pinnedForMs
7119
+ watched_for_ms: pinnedForMs,
7120
+ finish: reply?.info?.finish ?? reply?.finish,
7121
+ ...rootOngoing != null ? { root_ongoing: rootOngoing } : {},
7122
+ ...descendantOngoing != null ? { descendant_ongoing: descendantOngoing } : {},
7123
+ opencode_message_id: inFlight.opencodeMessageId
6216
7124
  });
6217
7125
  await this.settleMessageDone(sessionId, watcher, inFlight, messages);
6218
7126
  return;
6219
7127
  }
7128
+ if (rootOngoing === true && !inFlight.b2RootOngoingHeldLogged) {
7129
+ inFlight.b2RootOngoingHeldLogged = true;
7130
+ this.log({
7131
+ level: "warn",
7132
+ message: `Message ${id.slice(0, 8)} b2-pinned for ${Math.round(pinnedForMs / 1e3)}s with root_ongoing=${rootOngoing} and descendant_ongoing=${descendantOngoing} \u2014 holding until OpenCode confirms the root is idle`,
7133
+ conversation_id: conv.id,
7134
+ message_id: id
7135
+ });
7136
+ }
6220
7137
  }
6221
7138
  }
6222
7139
  const ambiguousPinnedNow = activelyRunning && isAmbiguousFinishPinnedRunning(messages, inFlight.opencodeMessageId);
@@ -6815,14 +7732,14 @@ var ChannelDriver = class _ChannelDriver {
6815
7732
  this.unconfirmedDispatchFailures.delete(row.id);
6816
7733
  this.sessions.delete(readoptConv.id);
6817
7734
  this.supersede(readoptConv.id, sessionId);
6818
- const errorMessage = `OpenCode accepted this re-dispatched message ${streak} times in a row but never confirmed its assigned id (session ${sessionId.slice(0, 8)}'s message list could not be read back) \u2014 the session was abandoned; a fresh one is used for further messages.`;
7735
+ const errorMessage2 = `OpenCode accepted this re-dispatched message ${streak} times in a row but never confirmed its assigned id (session ${sessionId.slice(0, 8)}'s message list could not be read back) \u2014 the session was abandoned; a fresh one is used for further messages.`;
6819
7736
  this.log({
6820
7737
  level: "error",
6821
- message: errorMessage,
7738
+ message: errorMessage2,
6822
7739
  conversation_id: row.conversation_id,
6823
7740
  message_id: row.id
6824
7741
  });
6825
- await this.markFailed(row.conversation_id, row.id, null, errorMessage).catch((markErr) => {
7742
+ await this.markFailed(row.conversation_id, row.id, null, errorMessage2).catch((markErr) => {
6826
7743
  this.log({
6827
7744
  level: "warn",
6828
7745
  message: `markFailed PATCH for message ${row.id.slice(0, 8)} (conversation ${row.conversation_id.slice(0, 8)}) failed (best-effort, not retried): ${markErr instanceof Error ? markErr.message : String(markErr)}`,
@@ -7437,6 +8354,7 @@ var ChannelDriver = class _ChannelDriver {
7437
8354
  throw new Error(`Failed to get pending conversations: HTTP ${res.status}`);
7438
8355
  }
7439
8356
  const data = await res.json();
8357
+ this.recycleRequestedFlag = data.recycle_requested === true;
7440
8358
  let conversations = data.conversations;
7441
8359
  if (this.conversationFilter) {
7442
8360
  conversations = conversations.filter((c) => c.id === this.conversationFilter);
@@ -7873,7 +8791,7 @@ async function ensureOpenCodeRunning(ctx) {
7873
8791
  }
7874
8792
  if (!ctx.interactive) {
7875
8793
  ctx.log(`OpenCode is not running on port ${ctx.port}. Starting it automatically...`);
7876
- const proc = await startOpenCode(ctx.port);
8794
+ const proc = await startOpenCode(ctx.port, { inheritStdio: ctx.inheritStdio });
7877
8795
  const health = await waitForOpenCodeHealth(ctx.port, ctx.startTimeoutMs);
7878
8796
  if (!health.healthy) {
7879
8797
  return {
@@ -7941,7 +8859,7 @@ Port ${port} is already in use.`));
7941
8859
  }
7942
8860
  if (action === "start") {
7943
8861
  const spinner = ora2("Starting OpenCode...").start();
7944
- const proc = await startOpenCode(port);
8862
+ const proc = await startOpenCode(port, { inheritStdio: ctx.inheritStdio });
7945
8863
  const health = await waitForOpenCodeHealth(port, INTERACTIVE_START_TIMEOUT_MS);
7946
8864
  if (!health.healthy) {
7947
8865
  spinner.fail("Failed to start OpenCode");
@@ -7953,12 +8871,558 @@ Port ${port} is already in use.`));
7953
8871
  return { port, process: null, version: null, notReadyReason: "you chose to continue without it" };
7954
8872
  }
7955
8873
 
8874
+ // src/lib/runner-credentials.ts
8875
+ import { chmodSync as chmodSync2, writeFileSync as writeFileSync4 } from "fs";
8876
+ import { spawn as spawn5 } from "child_process";
8877
+ var RUNNER_SECRET_FETCH_TIMEOUT_MS = 6e4;
8878
+ var CREDENTIAL_RESTORE_TIMEOUT_MS = 6e4;
8879
+ var GITHUB_PROBE_TIMEOUT_MS = 1e4;
8880
+ var GIT_CONFIG_GLOBAL = "/tmp/gitconfig";
8881
+ var GIT_CREDENTIAL_HELPER = "/tmp/git-credential-helper.sh";
8882
+ function commandError2(result) {
8883
+ return result.stderr.trim() || `process exited with code ${result.code ?? "null"}`;
8884
+ }
8885
+ var runCommand2 = (command, args, opts) => {
8886
+ return new Promise((resolve4) => {
8887
+ let child;
8888
+ let stdout = "";
8889
+ let stderr = "";
8890
+ let settled = false;
8891
+ const timer = {};
8892
+ const finish = (result) => {
8893
+ if (settled) return;
8894
+ settled = true;
8895
+ if (timer.handle) clearTimeout(timer.handle);
8896
+ resolve4(result);
8897
+ };
8898
+ try {
8899
+ child = spawn5(command, args, { env: opts.env, stdio: ["ignore", "pipe", "pipe"] });
8900
+ } catch (error2) {
8901
+ finish({
8902
+ code: null,
8903
+ stdout,
8904
+ stderr: error2 instanceof Error ? error2.message : String(error2),
8905
+ timedOut: false
8906
+ });
8907
+ return;
8908
+ }
8909
+ child.stdout?.setEncoding("utf8");
8910
+ child.stdout?.on("data", (chunk) => {
8911
+ stdout += chunk;
8912
+ });
8913
+ child.stderr?.setEncoding("utf8");
8914
+ child.stderr?.on("data", (chunk) => {
8915
+ stderr += chunk;
8916
+ });
8917
+ child.once("error", (error2) => {
8918
+ finish({
8919
+ code: null,
8920
+ stdout,
8921
+ stderr: stderr === "" ? error2.message : `${stderr}
8922
+ ${error2.message}`,
8923
+ timedOut: false
8924
+ });
8925
+ });
8926
+ child.once("close", (code) => finish({ code, stdout, stderr, timedOut: false }));
8927
+ timer.handle = setTimeout(
8928
+ () => {
8929
+ child.kill("SIGKILL");
8930
+ finish({ code: null, stdout, stderr, timedOut: true });
8931
+ },
8932
+ Math.max(0, opts.timeoutMs)
8933
+ );
8934
+ });
8935
+ };
8936
+ function isEnvironmentObject(value) {
8937
+ return typeof value === "object" && value !== null && !Array.isArray(value);
8938
+ }
8939
+ function secretFailure(marker, detail, log3) {
8940
+ const message = `${marker}: ${detail}`;
8941
+ log3(message, "error");
8942
+ return new Error(message);
8943
+ }
8944
+ async function installRunnerSecret({
8945
+ env,
8946
+ log: log3,
8947
+ commandRunner
8948
+ }) {
8949
+ const arn = env.RUNNER_SECRET_ARN?.trim();
8950
+ if (!arn) {
8951
+ log3("runner secret is not configured; continuing without GitHub and MCP credentials");
8952
+ return false;
8953
+ }
8954
+ const result = await (commandRunner ?? runCommand2)(
8955
+ "aws",
8956
+ [
8957
+ "secretsmanager",
8958
+ "get-secret-value",
8959
+ "--secret-id",
8960
+ arn,
8961
+ "--query",
8962
+ "SecretString",
8963
+ "--output",
8964
+ "text"
8965
+ ],
8966
+ { env, timeoutMs: RUNNER_SECRET_FETCH_TIMEOUT_MS }
8967
+ );
8968
+ if (result.timedOut) {
8969
+ throw secretFailure(
8970
+ "CREDENTIAL-RESTORE-TIMEOUT",
8971
+ `runner-secret did not finish within ${RUNNER_SECRET_FETCH_TIMEOUT_MS}ms`,
8972
+ log3
8973
+ );
8974
+ }
8975
+ if (result.code !== 0) {
8976
+ throw secretFailure("RUNNER-SECRET-UNREADABLE", commandError2(result), log3);
8977
+ }
8978
+ let payload;
8979
+ try {
8980
+ payload = JSON.parse(result.stdout);
8981
+ } catch (error2) {
8982
+ log3(
8983
+ `RUNNER-SECRET-UNPARSEABLE: secret value is not a JSON object (${error2 instanceof Error ? error2.message : String(error2)})`,
8984
+ "warn"
8985
+ );
8986
+ return false;
8987
+ }
8988
+ if (!isEnvironmentObject(payload)) {
8989
+ log3("RUNNER-SECRET-UNPARSEABLE: secret value is not a JSON object", "warn");
8990
+ return false;
8991
+ }
8992
+ let populated = 0;
8993
+ let skipped = 0;
8994
+ let githubTokenPopulated = false;
8995
+ for (const [key, value] of Object.entries(payload)) {
8996
+ if (typeof value !== "string" || value.length === 0) continue;
8997
+ if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key)) {
8998
+ log3(
8999
+ `RUNNER-SECRET-KEY-SKIPPED: ${JSON.stringify(key)} is not a valid environment variable name`,
9000
+ "warn"
9001
+ );
9002
+ skipped += 1;
9003
+ continue;
9004
+ }
9005
+ env[key] = value;
9006
+ populated += 1;
9007
+ if (key === "GH_TOKEN") githubTokenPopulated = true;
9008
+ }
9009
+ if (populated === 0) {
9010
+ log3(
9011
+ "RUNNER-SECRET-UNPOPULATED: populate the runner secret as documented in infrastructure/evident-runner/MICROVM.md",
9012
+ "warn"
9013
+ );
9014
+ } else {
9015
+ log3(
9016
+ `RUNNER-SECRET-OK: exported ${populated} secret values; skipped ${skipped} invalid environment variable names`
9017
+ );
9018
+ }
9019
+ return githubTokenPopulated;
9020
+ }
9021
+ function restoreFailure(operation, result, log3) {
9022
+ const message = `CREDENTIAL-RESTORE-FAILED: ${operation} failed: ${commandError2(result)}`;
9023
+ log3(message, "error");
9024
+ return new Error(message);
9025
+ }
9026
+ async function runCredentialRestore(args, operation, log3, synchroniserRunner) {
9027
+ const result = await synchroniserRunner(args, { timeoutMs: CREDENTIAL_RESTORE_TIMEOUT_MS });
9028
+ if (result.timedOut) {
9029
+ log3(
9030
+ `CREDENTIAL-RESTORE-TIMEOUT: ${operation} did not finish within ${CREDENTIAL_RESTORE_TIMEOUT_MS}ms; continuing without it`,
9031
+ "warn"
9032
+ );
9033
+ return result;
9034
+ }
9035
+ if (result.code !== 0) throw restoreFailure(operation, result, log3);
9036
+ return result;
9037
+ }
9038
+ async function restoreCredentialStores({
9039
+ env,
9040
+ log: log3,
9041
+ synchroniserRunner = runSynchroniser
9042
+ }) {
9043
+ await runCredentialRestore(["restore", "claude"], "restore-claude", log3, synchroniserRunner);
9044
+ await runCredentialRestore(["restore", "opencode"], "restore-opencode", log3, synchroniserRunner);
9045
+ const result = await synchroniserRunner(["model-auth-ready"], {
9046
+ timeoutMs: CREDENTIAL_RESTORE_TIMEOUT_MS
9047
+ });
9048
+ if (result.timedOut) {
9049
+ log3(
9050
+ `CREDENTIAL-RESTORE-TIMEOUT: model-auth-ready did not finish within ${CREDENTIAL_RESTORE_TIMEOUT_MS}ms; continuing without it`,
9051
+ "warn"
9052
+ );
9053
+ return;
9054
+ }
9055
+ switch (result.code) {
9056
+ case 0:
9057
+ return;
9058
+ case 10:
9059
+ log3(
9060
+ `no model credentials under s3://${env.LITESTREAM_BUCKET ?? ""}/${env.LITESTREAM_PREFIX ?? ""}/ (neither claude/credentials.json nor opencode/auth.json yielded valid JSON) and neither ANTHROPIC_API_KEY nor OPENAI_API_KEY is set. This VM boots and connects; a turn that needs a model provider fails until one is connected. See 'Seeding a credential store' in infrastructure/evident-runner/MICROVM.md.`,
9061
+ "warn"
9062
+ );
9063
+ return;
9064
+ default:
9065
+ log3("could not determine whether this VM has model credentials", "warn");
9066
+ }
9067
+ }
9068
+ var GIT_CREDENTIAL_HELPER_CONTENT = [
9069
+ "#!/usr/bin/env bash",
9070
+ '[ "$1" = get ] || exit 0',
9071
+ "echo username=x-access-token",
9072
+ 'echo "password=${GH_TOKEN}"',
9073
+ ""
9074
+ ].join("\n");
9075
+ async function probeGitHubAccess({ env, log: log3 }) {
9076
+ const auth = await runCommand2("gh", ["api", "user", "--jq", ".login"], {
9077
+ env,
9078
+ timeoutMs: GITHUB_PROBE_TIMEOUT_MS
9079
+ });
9080
+ if (auth.timedOut) {
9081
+ log3(`GITHUB-PROBE-TIMEOUT: auth probe exceeded ${GITHUB_PROBE_TIMEOUT_MS}ms`, "warn");
9082
+ return;
9083
+ }
9084
+ if (auth.code !== 0) {
9085
+ log3(`GITHUB-AUTH-REJECTED: ${commandError2(auth)}`, "warn");
9086
+ return;
9087
+ }
9088
+ log3(`GITHUB-AUTH-OK: ${auth.stdout.trim()}`, "debug");
9089
+ const remote = await runCommand2("git", ["-C", process.cwd(), "remote", "get-url", "origin"], {
9090
+ env,
9091
+ timeoutMs: GITHUB_PROBE_TIMEOUT_MS
9092
+ });
9093
+ if (remote.code !== 0 || remote.timedOut) return;
9094
+ const repo = remote.stdout.trim().replace(/^(?:https:\/\/github\.com\/|git@github\.com:)/, "").replace(/\.git$/, "");
9095
+ if (!repo) return;
9096
+ const repository = await runCommand2("gh", ["api", `repos/${repo}`, "--jq", ".full_name"], {
9097
+ env,
9098
+ timeoutMs: GITHUB_PROBE_TIMEOUT_MS
9099
+ });
9100
+ if (repository.timedOut) {
9101
+ log3(
9102
+ `GITHUB-PROBE-TIMEOUT: repository probe for ${repo} exceeded ${GITHUB_PROBE_TIMEOUT_MS}ms`,
9103
+ "warn"
9104
+ );
9105
+ } else if (repository.code !== 0) {
9106
+ log3(`GITHUB-REPO-INACCESSIBLE: ${repo}: ${commandError2(repository)}`, "warn");
9107
+ }
9108
+ }
9109
+ async function configureGitHubAccess({ env, log: log3 }) {
9110
+ if (!env.GH_TOKEN) {
9111
+ log3("GITHUB-CREDENTIALS-MISSING: GH_TOKEN is unavailable; see RUNNER-SECRET-* above", "warn");
9112
+ return;
9113
+ }
9114
+ try {
9115
+ env.GIT_CONFIG_GLOBAL = GIT_CONFIG_GLOBAL;
9116
+ writeFileSync4(GIT_CONFIG_GLOBAL, "");
9117
+ writeFileSync4(GIT_CREDENTIAL_HELPER, GIT_CREDENTIAL_HELPER_CONTENT, { mode: 448 });
9118
+ chmodSync2(GIT_CREDENTIAL_HELPER, 448);
9119
+ const config = [
9120
+ ["user.name", env.GIT_USER_NAME ?? "evident-bot"],
9121
+ ["user.email", env.GIT_USER_EMAIL ?? "evident-bot@users.noreply.github.com"],
9122
+ ["init.defaultBranch", "main"],
9123
+ ["credential.https://github.com.helper", GIT_CREDENTIAL_HELPER]
9124
+ ];
9125
+ for (const [key, value] of config) {
9126
+ const result = await runCommand2("git", ["config", "--global", key, value], {
9127
+ env,
9128
+ timeoutMs: GITHUB_PROBE_TIMEOUT_MS
9129
+ });
9130
+ if (result.timedOut || result.code !== 0) throw new Error(commandError2(result));
9131
+ }
9132
+ } catch (error2) {
9133
+ log3(
9134
+ `GITHUB-SETUP-FAILED: could not configure local git credentials; continuing without GitHub access (${error2 instanceof Error ? error2.message : String(error2)})`,
9135
+ "warn"
9136
+ );
9137
+ return;
9138
+ }
9139
+ void probeGitHubAccess({ env, log: log3 }).catch((error2) => {
9140
+ log3(
9141
+ `GITHUB-SETUP-FAILED: GitHub access probe failed: ${error2 instanceof Error ? error2.message : String(error2)}`,
9142
+ "warn"
9143
+ );
9144
+ });
9145
+ }
9146
+
9147
+ // src/lib/opencode/config-overlay.ts
9148
+ import { execFileSync as execFileSync2 } from "child_process";
9149
+ import { copyFileSync, existsSync as existsSync2, statSync as statSync5 } from "fs";
9150
+ import { isAbsolute as isAbsolute2, join as join8, resolve as resolve3 } from "path";
9151
+ function isFile(filePath) {
9152
+ return existsSync2(filePath) && statSync5(filePath).isFile();
9153
+ }
9154
+ function applyRunnerOpenCodeConfig({
9155
+ overlayPath,
9156
+ cwd = process.cwd(),
9157
+ log: log3
9158
+ }) {
9159
+ if (!overlayPath) {
9160
+ log3("runner OpenCode config is not configured; using the baked project config", "debug");
9161
+ return;
9162
+ }
9163
+ const source = isAbsolute2(overlayPath) ? overlayPath : resolve3(cwd, overlayPath);
9164
+ const target = isFile(join8(cwd, "opencode.jsonc")) ? "opencode.jsonc" : "opencode.json";
9165
+ if (!isFile(source)) {
9166
+ log3(
9167
+ `RUNNER-OPENCODE-CONFIG-MISSING: ${source} is not a file; headless turns will wedge on the first external-directory permission prompt (#563)`,
9168
+ "error"
9169
+ );
9170
+ return;
9171
+ }
9172
+ copyFileSync(source, join8(cwd, target));
9173
+ try {
9174
+ execFileSync2("git", ["-C", cwd, "update-index", "--skip-worktree", target], {
9175
+ stdio: "ignore"
9176
+ });
9177
+ } catch (error2) {
9178
+ const detail = error2 instanceof Error ? error2.message : String(error2);
9179
+ log3(`could not mark ${target} skip-worktree: ${detail}; it may show as a local change`, "warn");
9180
+ }
9181
+ log3(`Applied runner OpenCode config ${source} to ${join8(cwd, target)}`);
9182
+ }
9183
+
9184
+ // src/lib/credential-sync.ts
9185
+ import { renameSync, writeFileSync as writeFileSync5 } from "fs";
9186
+ var CREDENTIAL_SYNC_TICK_TIMEOUT_MS = 3e4;
9187
+ var CREDENTIAL_FLUSH_DEADLINE_MS = 8e3;
9188
+ var CREDENTIAL_FLUSH_ABORT_GRACE_MS = 500;
9189
+ var DEFAULT_CREDENTIAL_SYNC_INTERVAL_SECONDS = 60;
9190
+ var STORES = ["claude", "opencode"];
9191
+ var MAX_FLUSH_PASSES = 2;
9192
+ function outcomesWith(outcome) {
9193
+ return { claude: outcome, opencode: outcome };
9194
+ }
9195
+ function errorMessage(error2) {
9196
+ return error2 instanceof Error ? error2.message : String(error2);
9197
+ }
9198
+ function waitForSettlement(promise, timeoutMs) {
9199
+ return new Promise((resolve4) => {
9200
+ let settled = false;
9201
+ const timer = setTimeout(() => finish(false), Math.max(0, timeoutMs));
9202
+ const finish = (value) => {
9203
+ if (settled) return;
9204
+ settled = true;
9205
+ clearTimeout(timer);
9206
+ resolve4(value);
9207
+ };
9208
+ promise.then(
9209
+ () => finish(true),
9210
+ () => finish(true)
9211
+ );
9212
+ });
9213
+ }
9214
+ function writeMarker(markerPath, outcomes, log3) {
9215
+ const body = `${STORES.map((store) => `${store}=${outcomes[store]}`).join("\n")}
9216
+ `;
9217
+ const temporaryPath = `${markerPath}.tmp`;
9218
+ try {
9219
+ writeFileSync5(temporaryPath, body, { mode: 384 });
9220
+ renameSync(temporaryPath, markerPath);
9221
+ } catch (error2) {
9222
+ log3(`CREDENTIAL-FLUSH-MARKER-UNWRITABLE: ${markerPath}: ${errorMessage(error2)}`, "warn");
9223
+ }
9224
+ }
9225
+ function intervalSeconds(env, log3) {
9226
+ const raw = env.CREDS_SYNC_INTERVAL;
9227
+ if (raw === void 0 || /^[1-9][0-9]*$/.test(raw) && Number.isSafeInteger(Number(raw))) {
9228
+ return raw === void 0 ? DEFAULT_CREDENTIAL_SYNC_INTERVAL_SECONDS : Number(raw);
9229
+ }
9230
+ log3(
9231
+ `CREDENTIAL-SYNC-INTERVAL-INVALID: CREDS_SYNC_INTERVAL='${raw}' is not a positive integer; using ${DEFAULT_CREDENTIAL_SYNC_INTERVAL_SECONDS}s`,
9232
+ "warn"
9233
+ );
9234
+ return DEFAULT_CREDENTIAL_SYNC_INTERVAL_SECONDS;
9235
+ }
9236
+ async function runFlushStore(store, env, synchroniserRunner, log3, deadlineAt) {
9237
+ const remainingMs = deadlineAt - Date.now();
9238
+ if (remainingMs <= 0) return { outcome: "timeout", orphaned: false };
9239
+ const controller = new AbortController();
9240
+ let result;
9241
+ let failed = false;
9242
+ const completion = Promise.resolve().then(
9243
+ () => synchroniserRunner(["sync-once", store], {
9244
+ timeoutMs: remainingMs,
9245
+ env,
9246
+ signal: controller.signal
9247
+ })
9248
+ ).then(
9249
+ (value) => {
9250
+ result = value;
9251
+ },
9252
+ (error2) => {
9253
+ failed = true;
9254
+ log3(`CREDENTIAL-FLUSH-ERROR: ${store}: ${errorMessage(error2)}`, "warn");
9255
+ }
9256
+ );
9257
+ const abortTimer = setTimeout(() => controller.abort(), remainingMs);
9258
+ const settledBeforeDeadline = await waitForSettlement(completion, remainingMs);
9259
+ clearTimeout(abortTimer);
9260
+ if (!settledBeforeDeadline) {
9261
+ controller.abort();
9262
+ const settledAfterAbort = await waitForSettlement(completion, CREDENTIAL_FLUSH_ABORT_GRACE_MS);
9263
+ if (!settledAfterAbort) return { outcome: "timeout", orphaned: true };
9264
+ return { outcome: "timeout", orphaned: false };
9265
+ }
9266
+ if (failed || !result) return { outcome: "failed", orphaned: false };
9267
+ if (result.timedOut || Date.now() >= deadlineAt) {
9268
+ return { outcome: "timeout", orphaned: false };
9269
+ }
9270
+ return { outcome: result.code === 0 ? "ok" : "failed", orphaned: false };
9271
+ }
9272
+ function createCredentialSync({
9273
+ markerPath,
9274
+ env,
9275
+ log: log3,
9276
+ synchroniserRunner = runSynchroniser
9277
+ }) {
9278
+ const persistenceDisabled = !env.PERSISTENCE_BUCKET;
9279
+ let disabled = persistenceDisabled;
9280
+ let armed = false;
9281
+ let stopped = false;
9282
+ let timer;
9283
+ let inFlight;
9284
+ let activeTickAbort;
9285
+ let lastTickFailed;
9286
+ let flushPromise;
9287
+ const scheduleTick = (intervalMs, startTick2) => {
9288
+ if (stopped) return;
9289
+ timer = setTimeout(() => {
9290
+ timer = void 0;
9291
+ startTick2();
9292
+ }, intervalMs);
9293
+ };
9294
+ const startTick = (intervalMs) => {
9295
+ if (stopped) return;
9296
+ const controller = new AbortController();
9297
+ activeTickAbort = controller;
9298
+ const tick = (async () => {
9299
+ const outcomes = {
9300
+ claude: "failed",
9301
+ opencode: "failed"
9302
+ };
9303
+ for (const store of STORES) {
9304
+ if (controller.signal.aborted) break;
9305
+ try {
9306
+ const result = await synchroniserRunner(["sync-once", store], {
9307
+ timeoutMs: CREDENTIAL_SYNC_TICK_TIMEOUT_MS,
9308
+ env,
9309
+ signal: controller.signal
9310
+ });
9311
+ outcomes[store] = !result.timedOut && result.code === 0 ? "ok" : "failed";
9312
+ } catch (error2) {
9313
+ outcomes[store] = "failed";
9314
+ log3(`CREDENTIAL-SYNC-TICK-ERROR: ${store}: ${errorMessage(error2)}`, "debug");
9315
+ }
9316
+ }
9317
+ const failed = STORES.some((store) => outcomes[store] === "failed");
9318
+ log3(
9319
+ `CREDENTIAL-SYNC-TICK: claude=${outcomes.claude}, opencode=${outcomes.opencode}`,
9320
+ "debug"
9321
+ );
9322
+ if (failed && lastTickFailed !== true) {
9323
+ log3(
9324
+ "CREDENTIAL-SYNC-FAILED: an interval credential sync failed; retrying on the next tick",
9325
+ "warn"
9326
+ );
9327
+ } else if (!failed && lastTickFailed === true) {
9328
+ log3("CREDENTIAL-SYNC-RECOVERED: interval credential sync succeeded again", "warn");
9329
+ }
9330
+ lastTickFailed = failed;
9331
+ })().finally(() => {
9332
+ if (activeTickAbort === controller) activeTickAbort = void 0;
9333
+ if (inFlight === tick) inFlight = void 0;
9334
+ scheduleTick(intervalMs, () => startTick(intervalMs));
9335
+ });
9336
+ inFlight = tick;
9337
+ };
9338
+ const performFlush = async () => {
9339
+ stopped = true;
9340
+ if (timer) {
9341
+ clearTimeout(timer);
9342
+ timer = void 0;
9343
+ }
9344
+ const deadlineAt = Date.now() + CREDENTIAL_FLUSH_DEADLINE_MS;
9345
+ if (inFlight) {
9346
+ const settled = await waitForSettlement(inFlight, CREDENTIAL_FLUSH_DEADLINE_MS);
9347
+ if (!settled) {
9348
+ activeTickAbort?.abort();
9349
+ const settledAfterAbort = await waitForSettlement(
9350
+ inFlight,
9351
+ CREDENTIAL_FLUSH_ABORT_GRACE_MS
9352
+ );
9353
+ if (!settledAfterAbort) {
9354
+ log3(
9355
+ "CREDENTIAL-FLUSH-ORPHANED-TICK: a sync-once child could not be proven settled; skipping the boundary flush rather than becoming a second writer",
9356
+ "warn"
9357
+ );
9358
+ return { outcomes: outcomesWith("timeout"), orphaned: true };
9359
+ }
9360
+ }
9361
+ }
9362
+ if (disabled) return { outcomes: outcomesWith("skipped"), orphaned: false };
9363
+ const outcomes = outcomesWith("timeout");
9364
+ for (const store of STORES) {
9365
+ const result = await runFlushStore(store, env, synchroniserRunner, log3, deadlineAt);
9366
+ if (result.orphaned) {
9367
+ log3(
9368
+ "CREDENTIAL-FLUSH-ORPHANED-CHILD: a flush sync-once child could not be proven settled; refusing another flush pass rather than becoming a second writer",
9369
+ "warn"
9370
+ );
9371
+ return { outcomes: outcomesWith("timeout"), orphaned: true };
9372
+ }
9373
+ outcomes[store] = result.outcome;
9374
+ }
9375
+ return { outcomes, orphaned: false };
9376
+ };
9377
+ let flushPasses = 0;
9378
+ let lastFlush;
9379
+ return {
9380
+ arm() {
9381
+ if (stopped || armed) return;
9382
+ armed = true;
9383
+ if (persistenceDisabled) {
9384
+ disabled = true;
9385
+ log3(
9386
+ "CREDENTIAL-SYNC-DISABLED: LITESTREAM_BUCKET/LITESTREAM_PREFIX are not both set; no interval credential sync this boot",
9387
+ "warn"
9388
+ );
9389
+ return;
9390
+ }
9391
+ disabled = false;
9392
+ const intervalMs = intervalSeconds(env, log3) * 1e3;
9393
+ scheduleTick(intervalMs, () => startTick(intervalMs));
9394
+ },
9395
+ async stopAndFlush(publish) {
9396
+ let result;
9397
+ const runningFlush = flushPromise;
9398
+ if (runningFlush) {
9399
+ result = await runningFlush;
9400
+ } else if (flushPasses >= MAX_FLUSH_PASSES || lastFlush?.orphaned) {
9401
+ result = lastFlush ?? { outcomes: outcomesWith("timeout"), orphaned: true };
9402
+ } else {
9403
+ flushPasses++;
9404
+ const currentFlush = performFlush();
9405
+ flushPromise = currentFlush;
9406
+ try {
9407
+ result = await currentFlush;
9408
+ lastFlush = result;
9409
+ } finally {
9410
+ if (flushPromise === currentFlush) flushPromise = void 0;
9411
+ }
9412
+ }
9413
+ if (publish) writeMarker(markerPath, result.outcomes, log3);
9414
+ return result.outcomes;
9415
+ }
9416
+ };
9417
+ }
9418
+
7956
9419
  // src/commands/run.ts
7957
9420
  var MAX_ACTIVITY_LOG_ENTRIES = 10;
7958
9421
  var CHANNEL_POLL_INTERVAL_MS = Number(process.env.EVIDENT_CHANNEL_POLL_INTERVAL_MS) || 2e3;
7959
9422
  var CHANNEL_STUCK_QUEUED_MS = Number(process.env.EVIDENT_STUCK_QUEUED_MS) || void 0;
7960
9423
  var SHUTDOWN_DRAIN_TIMEOUT_MS = Number(process.env.EVIDENT_SHUTDOWN_DRAIN_MS) || 25e3;
7961
9424
  var TELEMETRY_SHUTDOWN_TIMEOUT_MS = 5e3;
9425
+ var CHILD_STOP_TIMEOUT_MS = 1e4;
7962
9426
  function resolveLogLevel(options) {
7963
9427
  const accepted = Object.keys(LOG_LEVELS);
7964
9428
  const validate = (value, source) => {
@@ -7989,11 +9453,11 @@ function resolveFileSyncDirectories(raw, homeDir) {
7989
9453
  if (trimmed === "") {
7990
9454
  throw new Error("--enable-file-sync-to requires a directory path (got an empty value)");
7991
9455
  }
7992
- const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join7(homeDir, trimmed.slice(2)) : trimmed;
7993
- if (!isAbsolute2(expanded)) {
9456
+ const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join9(homeDir, trimmed.slice(2)) : trimmed;
9457
+ if (!isAbsolute3(expanded)) {
7994
9458
  throw new Error(`--enable-file-sync-to requires an absolute directory path; got "${entry}"`);
7995
9459
  }
7996
- const normalized = resolvePath(expanded);
9460
+ const normalized = resolvePath2(expanded);
7997
9461
  if (parse(normalized).root === normalized) {
7998
9462
  throw new Error(
7999
9463
  `--enable-file-sync-to will not allow-list the filesystem root ("${entry}"); name the specific directory the credentials belong in (for example ~/.claude)`
@@ -8109,7 +9573,7 @@ function logActivity(state, entry) {
8109
9573
  }
8110
9574
  function reportSessionDbRecovery(state) {
8111
9575
  try {
8112
- const report = drainSessionDbRecoveryReport({ homeDir: homedir4(), env: process.env });
9576
+ const report = drainSessionDbRecoveryReport({ homeDir: homedir5(), env: process.env });
8113
9577
  for (const record of report.records) {
8114
9578
  const activity = buildSessionDbRecoveryActivity(record);
8115
9579
  if (!activity) throw new Error("could not map session-DB recovery record");
@@ -8127,6 +9591,16 @@ function reportSessionDbRecovery(state) {
8127
9591
  );
8128
9592
  }
8129
9593
  }
9594
+ function reportSessionDbRecoveryRecord(state, record) {
9595
+ const activity = buildSessionDbRecoveryActivity(record);
9596
+ if (!activity) throw new Error("could not map session-DB recovery record");
9597
+ logActivity(state, {
9598
+ type: activity.level === "error" ? "error" : "info",
9599
+ level: activity.level,
9600
+ ...activity.level === "error" ? { error: activity.message } : { message: activity.message },
9601
+ metadata: activity.metadata
9602
+ });
9603
+ }
8130
9604
  function displayStatus(state) {
8131
9605
  if (!state.interactive) return;
8132
9606
  const attempt = state.connection?.reconnectAttempt ?? 0;
@@ -8239,6 +9713,10 @@ async function driveChannels(state, driver) {
8239
9713
  consecutiveDrainFailures = 0;
8240
9714
  unreachableMs = 0;
8241
9715
  state.messageCount += processed;
9716
+ if (driver.recycleRequested) {
9717
+ await beginGracefulShutdown(state, "recycle");
9718
+ return;
9719
+ }
8242
9720
  const proxiedActivity = state.lastProxiedActivityAt !== lastSeenProxiedActivityAt;
8243
9721
  lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
8244
9722
  const fileActivitySnapshot = driver.fileSyncActivity();
@@ -8281,8 +9759,8 @@ async function driveChannels(state, driver) {
8281
9759
  state.running = false;
8282
9760
  break;
8283
9761
  }
8284
- const errorMessage = error2 instanceof Error ? error2.message : String(error2);
8285
- logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage}` });
9762
+ const errorMessage2 = error2 instanceof Error ? error2.message : String(error2);
9763
+ logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage2}` });
8286
9764
  if (state.interactive) displayStatus(state);
8287
9765
  if (driver.hasInFlightWatchers()) {
8288
9766
  consecutiveDrainFailures = 0;
@@ -8299,7 +9777,7 @@ async function driveChannels(state, driver) {
8299
9777
  }
8300
9778
  }
8301
9779
  }
8302
- await new Promise((resolve3) => setTimeout(resolve3, CHANNEL_POLL_INTERVAL_MS));
9780
+ await new Promise((resolve4) => setTimeout(resolve4, CHANNEL_POLL_INTERVAL_MS));
8303
9781
  const cycleMs = performance.now() - cycleStartedAtMs;
8304
9782
  if (idleThisCycle) idleMs += cycleMs;
8305
9783
  if (unreachableThisCycle) unreachableMs += cycleMs;
@@ -8322,7 +9800,43 @@ async function driveChannels(state, driver) {
8322
9800
  var SESSION_CLEANUP_FIRST_SWEEP_MS = 1e4;
8323
9801
  var SESSION_DB_RECLAIM_MAX_PAGES = 2e3;
8324
9802
  function sessionDbPath() {
8325
- return join7(homedir4(), ".local", "share", "opencode", "opencode.db");
9803
+ return join9(homedir5(), ".local", "share", "opencode", "opencode.db");
9804
+ }
9805
+ function logSessionDbProvenanceMismatch(state, provenance, currentVersion, preBootMigrationCount) {
9806
+ const record = {
9807
+ v: 1,
9808
+ event: "session_db_recovery",
9809
+ at: (/* @__PURE__ */ new Date()).toISOString(),
9810
+ stage: "verify",
9811
+ outcome: "schema_provenance_mismatch",
9812
+ severity: "error",
9813
+ reason: provenance.reason ?? "schema-provenance-mismatch",
9814
+ litestream_exit_code: null,
9815
+ attempt: null,
9816
+ replica_objects: null,
9817
+ replica_bytes: null,
9818
+ quarantine_destination: null,
9819
+ quarantined_objects: null,
9820
+ quarantine_failed_objects: null,
9821
+ quarantined_bytes: null,
9822
+ verified_restore_point: null,
9823
+ restore_points_tried: null,
9824
+ provenance_reason: provenance.reason,
9825
+ provenance_migration_delta: provenance.migrationDelta,
9826
+ replication_suspended: false,
9827
+ dbPath: sessionDbPath(),
9828
+ recorded_version: provenance.recordedVersion,
9829
+ current_version: currentVersion,
9830
+ provenance_pre_boot_migration_count: preBootMigrationCount
9831
+ };
9832
+ const activity = buildSessionDbRecoveryActivity(record);
9833
+ if (!activity) throw new Error("could not map session-DB provenance activity");
9834
+ logActivity(state, {
9835
+ type: activity.level === "error" ? "error" : "info",
9836
+ level: activity.level,
9837
+ ...activity.level === "error" ? { error: activity.message } : { message: activity.message },
9838
+ metadata: activity.metadata
9839
+ });
8326
9840
  }
8327
9841
  async function runSweep(state, driver, config) {
8328
9842
  const mode = `age=${config.maxAgeMs ?? "\u2014"} count=${config.maxCount ?? "\u2014"}`;
@@ -8369,7 +9883,7 @@ async function runSweep(state, driver, config) {
8369
9883
  const reclaimResult = await reclaimSessionDbSpace({
8370
9884
  dbPath: sessionDbPath(),
8371
9885
  maxPages: SESSION_DB_RECLAIM_MAX_PAGES,
8372
- allowFullVacuum: protectedNow.size === 0
9886
+ allowFullVacuum: protectedNow.size === 0 && !state.sessionDbProvenanceAnomaly
8373
9887
  });
8374
9888
  if (reclaimResult.ok) {
8375
9889
  const beforeMib = (reclaimResult.beforeBytes / 1024 / 1024).toFixed(1);
@@ -8405,7 +9919,7 @@ function scheduleSessionCleanup(state, driver, options) {
8405
9919
  for (const warning2 of config.warnings) {
8406
9920
  logActivity(state, { type: "info", level: "warn", message: `Session cleanup: ${warning2}` });
8407
9921
  }
8408
- const dbBytes = statSessionDbBytes(homedir4());
9922
+ const dbBytes = statSessionDbBytes(homedir5());
8409
9923
  void (async () => {
8410
9924
  const reclaimSkipReason = dbBytes !== null && config.enabled ? await probeReclaimAvailability({ dbPath: sessionDbPath(), requiredBytes: dbBytes }) : null;
8411
9925
  const sizeWarning = buildSessionStoreSizeWarning({
@@ -8606,7 +10120,8 @@ function scheduleResourceUsageReporting(state, options) {
8606
10120
  });
8607
10121
  return;
8608
10122
  }
8609
- const collect = createResourceUsageCollector(homedir4());
10123
+ const { collect, stop } = createResourceUsageCollector(homedir5());
10124
+ state.stopResourceUsageSampling = stop;
8610
10125
  let consecutiveFailures = 0;
8611
10126
  const tick = async () => {
8612
10127
  try {
@@ -8716,21 +10231,41 @@ async function cleanup(state, opts = {}) {
8716
10231
  clearTimeout(state.resourceUsageTimer);
8717
10232
  state.resourceUsageTimer = null;
8718
10233
  }
10234
+ state.stopResourceUsageSampling?.();
10235
+ state.stopResourceUsageSampling = null;
10236
+ const credentialSync = state.credentialSync;
10237
+ const flushCredentials = credentialSync ? async (phase, publish) => {
10238
+ await timeShutdownPhase(state, durations, phase, async () => {
10239
+ const outcomes = await credentialSync.stopAndFlush(publish);
10240
+ const level = Object.values(outcomes).every((outcome) => outcome === "ok") ? "info" : "warn";
10241
+ log2(
10242
+ state,
10243
+ `Credential flush: claude=${outcomes.claude}, opencode=${outcomes.opencode}`,
10244
+ level
10245
+ );
10246
+ });
10247
+ } : void 0;
10248
+ let drainSettled = true;
8719
10249
  if (opts.graceful && state.channelDriver) {
8720
10250
  state.channelDriver.stop();
10251
+ }
10252
+ if (flushCredentials) {
10253
+ await flushCredentials("credential_flush", !(opts.graceful && state.channelDriver));
10254
+ }
10255
+ if (opts.graceful && state.channelDriver) {
8721
10256
  log2(state, "Draining in-flight channel work before shutdown...");
8722
10257
  if (state.interactive) {
8723
10258
  logActivity(state, { type: "info", message: "Draining in-flight work before shutdown..." });
8724
10259
  displayStatus(state);
8725
10260
  }
8726
10261
  const driver = state.channelDriver;
8727
- const settled = await timeShutdownPhase(
10262
+ drainSettled = await timeShutdownPhase(
8728
10263
  state,
8729
10264
  durations,
8730
10265
  "drain",
8731
10266
  () => driver.waitForInFlight(SHUTDOWN_DRAIN_TIMEOUT_MS)
8732
10267
  );
8733
- if (!settled) {
10268
+ if (!drainSettled) {
8734
10269
  logActivity(state, {
8735
10270
  type: "info",
8736
10271
  message: "Shutdown drain timed out with work still in flight \u2014 leaving it for restart recovery"
@@ -8738,6 +10273,9 @@ async function cleanup(state, opts = {}) {
8738
10273
  if (state.interactive) displayStatus(state);
8739
10274
  }
8740
10275
  }
10276
+ if (opts.graceful && state.channelDriver && flushCredentials && drainSettled) {
10277
+ await flushCredentials("credential_flush_final", true);
10278
+ }
8741
10279
  await timeShutdownPhase(state, durations, "offline_notify", () => notifyOffline(state));
8742
10280
  if (state.connection) {
8743
10281
  const connection = state.connection;
@@ -8746,24 +10284,83 @@ async function cleanup(state, opts = {}) {
8746
10284
  }
8747
10285
  if (state.opencodeProcess) {
8748
10286
  const opencodeProcess = state.opencodeProcess;
8749
- await timeShutdownPhase(state, durations, "opencode_stop", () => stopOpenCode(opencodeProcess));
10287
+ const result = await timeShutdownPhase(
10288
+ state,
10289
+ durations,
10290
+ "opencode_stop",
10291
+ () => stopOpenCodeAndWait(opencodeProcess, CHILD_STOP_TIMEOUT_MS)
10292
+ );
8750
10293
  if (state.interactive) {
8751
- logActivity(state, { type: "info", message: "Stopped OpenCode process" });
10294
+ logActivity(state, { type: "info", message: `Stopped OpenCode process (${result.outcome})` });
8752
10295
  displayStatus(state);
8753
10296
  } else {
8754
- log2(state, "Stopped OpenCode process");
10297
+ log2(state, `Stopped OpenCode process (${result.outcome})`);
8755
10298
  }
8756
10299
  state.opencodeProcess = null;
8757
10300
  }
10301
+ if (state.litestreamProcess) {
10302
+ const litestreamProcess = state.litestreamProcess;
10303
+ const result = await timeShutdownPhase(
10304
+ state,
10305
+ durations,
10306
+ "litestream_stop",
10307
+ () => stopSessionDbReplication(litestreamProcess, CHILD_STOP_TIMEOUT_MS)
10308
+ );
10309
+ log2(state, `Stopped litestream replication (${result.outcome})`);
10310
+ state.litestreamProcess = null;
10311
+ }
8758
10312
  return durations;
8759
10313
  }
10314
+ async function beginGracefulShutdown(state, trigger) {
10315
+ if (state.shuttingDown) return;
10316
+ state.shuttingDown = true;
10317
+ const shutdownStartedAt = Date.now();
10318
+ const shutdownMessage = trigger === "recycle" ? "Recycle requested \u2014 finishing in-flight work, then exiting" : "Shutting down...";
10319
+ if (state.interactive) {
10320
+ logActivity(state, { type: "info", message: shutdownMessage });
10321
+ displayStatus(state);
10322
+ } else {
10323
+ log2(state, shutdownMessage);
10324
+ }
10325
+ const durations = await cleanup(state, { graceful: true });
10326
+ const telemetryBudgetMs = Number(process.env.EVIDENT_TELEMETRY_SHUTDOWN_MS) || TELEMETRY_SHUTDOWN_TIMEOUT_MS;
10327
+ await timeShutdownPhase(state, durations, "telemetry_flush", async () => {
10328
+ let timer;
10329
+ const flushed = shutdownTelemetry().then(
10330
+ () => true,
10331
+ (error2) => {
10332
+ log2(
10333
+ state,
10334
+ `Telemetry flush failed during shutdown: ${error2 instanceof Error ? error2.message : String(error2)}`,
10335
+ "warn"
10336
+ );
10337
+ return true;
10338
+ }
10339
+ );
10340
+ const timedOut = new Promise((resolve4) => {
10341
+ timer = setTimeout(() => resolve4(false), telemetryBudgetMs);
10342
+ });
10343
+ if (!await Promise.race([flushed, timedOut])) {
10344
+ log2(state, `Telemetry flush exceeded ${telemetryBudgetMs}ms \u2014 exiting anyway`, "warn");
10345
+ }
10346
+ clearTimeout(timer);
10347
+ });
10348
+ const breakdown = Object.entries(durations).map(([phase, ms]) => `${phase}=${ms}ms`).join(" ");
10349
+ log2(state, `Shutdown complete in ${Date.now() - shutdownStartedAt}ms (${breakdown})`);
10350
+ process.exit(0);
10351
+ }
8760
10352
  async function run(options) {
8761
10353
  const interactive = isInteractive(options.json);
8762
10354
  let logLevel;
8763
10355
  let fileSyncDirectories;
8764
10356
  try {
8765
10357
  logLevel = resolveLogLevel(options);
8766
- fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir4());
10358
+ fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir5());
10359
+ if (options.restoreSessionDb && !options.sessionDbNoReplicateMarker) {
10360
+ throw new Error(
10361
+ "--restore-session-db requires --session-db-no-replicate-marker <path>; restore failures must block Litestream replication"
10362
+ );
10363
+ }
8767
10364
  } catch (error2) {
8768
10365
  const message = error2 instanceof Error ? error2.message : String(error2);
8769
10366
  if (options.json) {
@@ -8787,7 +10384,9 @@ async function run(options) {
8787
10384
  connected: false,
8788
10385
  opencodeConnected: false,
8789
10386
  opencodeVersion: null,
10387
+ sessionDbProvenanceAnomaly: false,
8790
10388
  opencodeProcess: null,
10389
+ litestreamProcess: null,
8791
10390
  connection: null,
8792
10391
  channelDriver: null,
8793
10392
  running: true,
@@ -8801,9 +10400,24 @@ async function run(options) {
8801
10400
  openaiUsageTimer: null,
8802
10401
  openaiUsageRearm: null,
8803
10402
  resourceUsageTimer: null,
10403
+ stopResourceUsageSampling: null,
10404
+ credentialSync: null,
8804
10405
  authHeader: ""
8805
10406
  };
8806
10407
  setTelemetryAuthProvider(() => ({ authHeader: state.authHeader, agentId: state.agentId }));
10408
+ if (options.credentialSyncMarker) {
10409
+ state.credentialSync = createCredentialSync({
10410
+ markerPath: options.credentialSyncMarker,
10411
+ env: process.env,
10412
+ log: (message, level = "info") => {
10413
+ if (level === "error") {
10414
+ logActivity(state, { type: "error", error: message });
10415
+ } else {
10416
+ logActivity(state, { type: "info", level, message });
10417
+ }
10418
+ }
10419
+ });
10420
+ }
8807
10421
  if (fileSyncDirectories.length > 0) {
8808
10422
  log2(state, `File sync enabled for: ${fileSyncDirectories.join(", ")}`);
8809
10423
  } else {
@@ -8829,43 +10443,7 @@ async function run(options) {
8829
10443
  "warn"
8830
10444
  );
8831
10445
  }
8832
- const handleSignal = async () => {
8833
- if (state.shuttingDown) return;
8834
- state.shuttingDown = true;
8835
- const shutdownStartedAt = Date.now();
8836
- if (state.interactive) {
8837
- logActivity(state, { type: "info", message: "Shutting down..." });
8838
- displayStatus(state);
8839
- } else {
8840
- log2(state, "Shutting down...");
8841
- }
8842
- const durations = await cleanup(state, { graceful: true });
8843
- const telemetryBudgetMs = Number(process.env.EVIDENT_TELEMETRY_SHUTDOWN_MS) || TELEMETRY_SHUTDOWN_TIMEOUT_MS;
8844
- await timeShutdownPhase(state, durations, "telemetry_flush", async () => {
8845
- let timer;
8846
- const flushed = shutdownTelemetry().then(
8847
- () => true,
8848
- (error2) => {
8849
- log2(
8850
- state,
8851
- `Telemetry flush failed during shutdown: ${error2 instanceof Error ? error2.message : String(error2)}`,
8852
- "warn"
8853
- );
8854
- return true;
8855
- }
8856
- );
8857
- const timedOut = new Promise((resolve3) => {
8858
- timer = setTimeout(() => resolve3(false), telemetryBudgetMs);
8859
- });
8860
- if (!await Promise.race([flushed, timedOut])) {
8861
- log2(state, `Telemetry flush exceeded ${telemetryBudgetMs}ms \u2014 exiting anyway`, "warn");
8862
- }
8863
- clearTimeout(timer);
8864
- });
8865
- const breakdown = Object.entries(durations).map(([phase, ms]) => `${phase}=${ms}ms`).join(" ");
8866
- log2(state, `Shutdown complete in ${Date.now() - shutdownStartedAt}ms (${breakdown})`);
8867
- process.exit(0);
8868
- };
10446
+ const handleSignal = () => beginGracefulShutdown(state, "signal");
8869
10447
  process.on("SIGINT", handleSignal);
8870
10448
  process.on("SIGTERM", handleSignal);
8871
10449
  try {
@@ -8995,7 +10573,68 @@ async function run(options) {
8995
10573
  } else {
8996
10574
  log2(state, "Not running in a MicroVM (MICROVM_ID unset) \u2014 nothing to report", "debug");
8997
10575
  }
10576
+ if (options.restoreRunnerCredentials) {
10577
+ log2(state, "Restoring runner credentials before starting OpenCode");
10578
+ const credentialContext = {
10579
+ env: process.env,
10580
+ log: (message, level = "info") => {
10581
+ if (level === "error") {
10582
+ logActivity(state, { type: "error", error: message });
10583
+ } else {
10584
+ logActivity(state, { type: "info", level, message });
10585
+ }
10586
+ }
10587
+ };
10588
+ const githubTokenPopulated = await installRunnerSecret(credentialContext);
10589
+ await restoreCredentialStores(credentialContext);
10590
+ if (githubTokenPopulated) await configureGitHubAccess(credentialContext);
10591
+ }
10592
+ state.credentialSync?.arm();
10593
+ let sessionDbVerifyFatal = false;
10594
+ if (!options.restoreSessionDb) {
10595
+ log2(state, "Skipping session-DB restore: --restore-session-db was not passed", "debug");
10596
+ } else {
10597
+ const health = await checkOpenCodeHealth(state.port);
10598
+ if (health.healthy) {
10599
+ log2(
10600
+ state,
10601
+ "Skipping session-DB restore: OpenCode is already serving this database",
10602
+ "debug"
10603
+ );
10604
+ } else {
10605
+ const result = await restoreAndVerifySessionDb({
10606
+ dbPath: sessionDbPath(),
10607
+ litestreamConfig: options.litestreamConfig,
10608
+ noReplicateMarker: options.sessionDbNoReplicateMarker,
10609
+ env: process.env,
10610
+ log: (message, level = "info") => {
10611
+ if (level === "error") {
10612
+ logActivity(state, { type: "error", error: message });
10613
+ } else {
10614
+ logActivity(state, { type: "info", level, message });
10615
+ }
10616
+ },
10617
+ reportRecovery: (record) => reportSessionDbRecoveryRecord(state, record)
10618
+ });
10619
+ sessionDbVerifyFatal = result.verifyFatal;
10620
+ }
10621
+ }
8998
10622
  reportSessionDbRecovery(state);
10623
+ if (sessionDbVerifyFatal) {
10624
+ throw new Error(
10625
+ "SESSION-DB-INTEGRITY-EXHAUSTED: the corrupt session DB could not be proven separated from the active backup prefix or removed from disk"
10626
+ );
10627
+ }
10628
+ applyRunnerOpenCodeConfig({
10629
+ overlayPath: options.opencodeConfigOverlay,
10630
+ log: (message, level = "info") => {
10631
+ if (level === "error") {
10632
+ logActivity(state, { type: "error", error: message });
10633
+ } else {
10634
+ logActivity(state, { type: "info", level, message });
10635
+ }
10636
+ }
10637
+ });
8999
10638
  const { timeoutMs: opencodeStartTimeoutMs, warnings: opencodeStartTimeoutWarnings } = resolveOpenCodeStartTimeoutMs(options, process.env);
9000
10639
  for (const warning2 of opencodeStartTimeoutWarnings) {
9001
10640
  logActivity(state, { type: "info", level: "warn", message: warning2 });
@@ -9004,6 +10643,7 @@ async function run(options) {
9004
10643
  for (const warning2 of maxActiveSessionsWarnings) {
9005
10644
  logActivity(state, { type: "info", level: "warn", message: warning2 });
9006
10645
  }
10646
+ const preBootMigrationIds = readSessionDbMigrationIds(sessionDbPath());
9007
10647
  const ocSpinner = interactive && !state.json ? ora3("Checking OpenCode...").start() : null;
9008
10648
  try {
9009
10649
  const oc = await ensureOpenCodeRunning({
@@ -9011,11 +10651,41 @@ async function run(options) {
9011
10651
  interactive: state.interactive,
9012
10652
  agentId: state.agentId,
9013
10653
  log: (message) => log2(state, message),
9014
- startTimeoutMs: opencodeStartTimeoutMs
10654
+ startTimeoutMs: opencodeStartTimeoutMs,
10655
+ inheritStdio: Boolean(options.opencodePidFile)
9015
10656
  });
9016
10657
  state.port = oc.port;
9017
- state.opencodeProcess = oc.process;
10658
+ state.opencodeProcess = options.opencodePidFile ? null : oc.process;
9018
10659
  state.opencodeVersion = oc.version;
10660
+ if (options.opencodePidFile && oc.process?.pid !== void 0) {
10661
+ try {
10662
+ writeFileSync6(options.opencodePidFile, `${oc.process.pid}
10663
+ `, { mode: 384 });
10664
+ chmodSync3(options.opencodePidFile, 384);
10665
+ } catch (error2) {
10666
+ logActivity(state, {
10667
+ type: "error",
10668
+ error: `Failed to write OpenCode pid file ${options.opencodePidFile}: ${error2 instanceof Error ? error2.message : String(error2)}`
10669
+ });
10670
+ }
10671
+ }
10672
+ if (state.opencodeVersion !== null) {
10673
+ const provenance = checkSessionDbProvenance({
10674
+ dbPath: sessionDbPath(),
10675
+ currentVersion: state.opencodeVersion,
10676
+ homeDir: homedir5(),
10677
+ env: process.env
10678
+ });
10679
+ if (provenance.anomaly) {
10680
+ state.sessionDbProvenanceAnomaly = true;
10681
+ logSessionDbProvenanceMismatch(
10682
+ state,
10683
+ provenance,
10684
+ state.opencodeVersion,
10685
+ preBootMigrationIds?.length ?? null
10686
+ );
10687
+ }
10688
+ }
9019
10689
  state.opencodeConnected = oc.notReadyReason === null;
9020
10690
  const version2 = state.opencodeVersion ? ` (v${state.opencodeVersion})` : "";
9021
10691
  ocSpinner?.succeed(`OpenCode running on port ${state.port}${version2}`);
@@ -9052,6 +10722,108 @@ async function run(options) {
9052
10722
  ocSpinner?.fail(error2.message);
9053
10723
  throw error2;
9054
10724
  }
10725
+ if (options.litestreamPidFile) {
10726
+ if (options.sessionDbNoReplicateMarker && existsSync3(options.sessionDbNoReplicateMarker)) {
10727
+ log2(
10728
+ state,
10729
+ `Skipping Litestream replication because ${options.sessionDbNoReplicateMarker} marks this session database unsafe to replicate`
10730
+ );
10731
+ } else if (!options.litestreamConfig) {
10732
+ logActivity(state, {
10733
+ type: "info",
10734
+ level: "warn",
10735
+ message: "Skipping Litestream replication because no configuration file was provided"
10736
+ });
10737
+ } else {
10738
+ let existingPid;
10739
+ if (existsSync3(options.litestreamPidFile)) {
10740
+ try {
10741
+ const rawPid = readFileSync6(options.litestreamPidFile, "utf8").trim();
10742
+ const parsedPid = Number(rawPid);
10743
+ if (/^\d+$/.test(rawPid) && Number.isSafeInteger(parsedPid) && parsedPid > 0) {
10744
+ existingPid = parsedPid;
10745
+ }
10746
+ } catch (error2) {
10747
+ logActivity(state, {
10748
+ type: "info",
10749
+ level: "warn",
10750
+ message: `Could not read Litestream pid file ${options.litestreamPidFile}; checking for a new process: ${error2 instanceof Error ? error2.message : String(error2)}`
10751
+ });
10752
+ }
10753
+ }
10754
+ if (existingPid !== void 0 && isProcessAlive(existingPid)) {
10755
+ log2(state, `Litestream replication is already running with pid ${existingPid}`);
10756
+ } else {
10757
+ const litestreamProcess = startSessionDbReplication(options.litestreamConfig);
10758
+ state.litestreamProcess = null;
10759
+ let failureHandled = false;
10760
+ const reportImageOwnedReplicationFailure = (message) => {
10761
+ if (failureHandled || state.shuttingDown || !state.running) return;
10762
+ failureHandled = true;
10763
+ logActivity(state, { type: "error", error: message });
10764
+ if (state.interactive) displayStatus(state);
10765
+ };
10766
+ litestreamProcess.on("exit", (code, signal) => {
10767
+ reportImageOwnedReplicationFailure(
10768
+ `Litestream replication stopped unexpectedly (code: ${code ?? "null"}, signal: ${signal ?? "none"})`
10769
+ );
10770
+ });
10771
+ litestreamProcess.on("error", (error2) => {
10772
+ reportImageOwnedReplicationFailure(
10773
+ `Litestream replication failed: ${error2 instanceof Error ? error2.message : String(error2)}`
10774
+ );
10775
+ });
10776
+ try {
10777
+ if (litestreamProcess.pid !== void 0) {
10778
+ writeFileSync6(options.litestreamPidFile, `${litestreamProcess.pid}
10779
+ `, {
10780
+ mode: 384
10781
+ });
10782
+ chmodSync3(options.litestreamPidFile, 384);
10783
+ }
10784
+ } catch (error2) {
10785
+ logActivity(state, {
10786
+ type: "error",
10787
+ error: `Failed to write Litestream pid file ${options.litestreamPidFile}: ${error2 instanceof Error ? error2.message : String(error2)}`
10788
+ });
10789
+ }
10790
+ log2(state, `Started litestream replication with config ${options.litestreamConfig}`);
10791
+ }
10792
+ }
10793
+ } else if (options.litestreamConfig) {
10794
+ const litestreamProcess = startSessionDbReplication(options.litestreamConfig);
10795
+ state.litestreamProcess = litestreamProcess;
10796
+ let failureHandled = false;
10797
+ const failRunForReplication = (message) => {
10798
+ if (failureHandled || state.shuttingDown || !state.running) return;
10799
+ failureHandled = true;
10800
+ state.shuttingDown = true;
10801
+ logActivity(state, { type: "error", error: message });
10802
+ if (state.interactive) displayStatus(state);
10803
+ void (async () => {
10804
+ try {
10805
+ await cleanup(state);
10806
+ await shutdownTelemetry();
10807
+ } catch (error2) {
10808
+ console.error(
10809
+ `[run] replication failure cleanup failed: ${error2 instanceof Error ? error2.message : String(error2)}`
10810
+ );
10811
+ }
10812
+ process.exit(1);
10813
+ })();
10814
+ };
10815
+ litestreamProcess.on("exit", (code, signal) => {
10816
+ failRunForReplication(
10817
+ `Litestream replication stopped unexpectedly (code: ${code ?? "null"}, signal: ${signal ?? "none"})`
10818
+ );
10819
+ });
10820
+ litestreamProcess.on("error", (error2) => {
10821
+ failRunForReplication(
10822
+ `Litestream replication failed: ${error2 instanceof Error ? error2.message : String(error2)}`
10823
+ );
10824
+ });
10825
+ log2(state, `Started litestream replication with config ${options.litestreamConfig}`);
10826
+ }
9055
10827
  const tunnelSpinner = interactive && !state.json ? ora3("Connecting tunnel...").start() : null;
9056
10828
  const channelDriver = new ChannelDriver({
9057
10829
  agentId: state.agentId,
@@ -9063,7 +10835,7 @@ async function run(options) {
9063
10835
  // #559: the `--enable-file-sync-to` allow-list. Empty ⇒ pending files are
9064
10836
  // REJECTED with `file_sync_disabled` on the ack, not silently ignored.
9065
10837
  fileSyncDirectories,
9066
- homeDir: homedir4(),
10838
+ homeDir: homedir5(),
9067
10839
  maxActiveSessions,
9068
10840
  log: (entry) => (
9069
10841
  // Thread the driver's real level straight through so `debug`/`warn`
@@ -9209,7 +10981,17 @@ async function run(options) {
9209
10981
  setTimer: (timer) => {
9210
10982
  state.openaiUsageTimer = timer;
9211
10983
  },
9212
- fetchUsage: () => getOpenAiUsage(state.port),
10984
+ fetchUsage: async () => {
10985
+ const usage = await getOpenAiUsage(state.port);
10986
+ if (usage.subscription === null) {
10987
+ logActivity(state, {
10988
+ type: "info",
10989
+ level: "debug",
10990
+ message: "OpenAI usage subscription could not be identified from the local credential"
10991
+ });
10992
+ }
10993
+ return usage;
10994
+ },
9213
10995
  report: (usage) => reportOpenAiUsage(state.agentId, state.authHeader, usage),
9214
10996
  isLocalCredentialProblem: isLocalCredentialProblem2,
9215
10997
  forcedOnHint: "connect a ChatGPT account to this runner, or run `opencode auth login`",
@@ -9255,7 +11037,7 @@ async function run(options) {
9255
11037
  }
9256
11038
 
9257
11039
  // src/index.ts
9258
- var { version } = createRequire(import.meta.url)("../package.json");
11040
+ var { version } = createRequire2(import.meta.url)("../package.json");
9259
11041
  var program = new Command();
9260
11042
  program.name("evident").description("Run OpenCode locally and connect it to Evident").version(version).option(
9261
11043
  "--endpoint <url>",
@@ -9312,6 +11094,30 @@ program.command("run").description("Connect to Evident and process messages").op
9312
11094
  ).option(
9313
11095
  "--tunnel-ready-file <path>",
9314
11096
  "Path to write once the tunnel is connected (opt-in; unused unless an operator/image sets it)"
11097
+ ).option(
11098
+ "--litestream-config <path>",
11099
+ "Replicate the OpenCode session database with `litestream replicate` using this config file (written by the runner image). Omit to disable replication."
11100
+ ).option(
11101
+ "--opencode-pid-file <path>",
11102
+ "Record the OpenCode pid here and leave the process running at shutdown for the runner image's lifecycle hooks to stop."
11103
+ ).option(
11104
+ "--litestream-pid-file <path>",
11105
+ "Record the Litestream pid here and leave the process running at shutdown for the runner image's lifecycle hooks to stop."
11106
+ ).option(
11107
+ "--session-db-no-replicate-marker <path>",
11108
+ "Read this marker as a gate before starting Litestream; the session-DB restore writes it when this boot's database is not safe to replicate."
11109
+ ).option(
11110
+ "--restore-session-db",
11111
+ "Restore and verify the OpenCode session database before starting OpenCode; requires --litestream-config for the replica and --session-db-no-replicate-marker for give-up records."
11112
+ ).option(
11113
+ "--restore-runner-credentials",
11114
+ "Restore the hosted runner secret and persisted credential stores before starting OpenCode."
11115
+ ).option(
11116
+ "--opencode-config-overlay <path>",
11117
+ "Apply this runner-provided OpenCode config before starting OpenCode."
11118
+ ).option(
11119
+ "--credential-sync-marker <path>",
11120
+ "Own the interval credential sync and write this marker once the shutdown flush has finished, so the runner image's lifecycle hooks can wait on it."
9315
11121
  ).action(
9316
11122
  (options) => {
9317
11123
  run({
@@ -9343,7 +11149,15 @@ program.command("run").description("Connect to Evident and process messages").op
9343
11149
  // Raw values — expansion/validation is single-sourced in run.ts's
9344
11150
  // resolveFileSyncDirectories.
9345
11151
  enableFileSyncTo: options.enableFileSyncTo,
9346
- tunnelReadyFile: options.tunnelReadyFile
11152
+ tunnelReadyFile: options.tunnelReadyFile,
11153
+ litestreamConfig: options.litestreamConfig,
11154
+ opencodePidFile: options.opencodePidFile,
11155
+ litestreamPidFile: options.litestreamPidFile,
11156
+ sessionDbNoReplicateMarker: options.sessionDbNoReplicateMarker,
11157
+ restoreSessionDb: options.restoreSessionDb,
11158
+ restoreRunnerCredentials: options.restoreRunnerCredentials,
11159
+ opencodeConfigOverlay: options.opencodeConfigOverlay,
11160
+ credentialSyncMarker: options.credentialSyncMarker
9347
11161
  });
9348
11162
  }
9349
11163
  );