@evident-ai/cli 3.4.1-dev.49da2cf → 3.4.1-dev.4a15fbd

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
  });
@@ -1183,8 +1191,9 @@ async function claudeUsage() {
1183
1191
  }
1184
1192
 
1185
1193
  // 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";
1194
+ import { chmodSync as chmodSync3, existsSync as existsSync3, readFileSync as readFileSync6, writeFileSync as writeFileSync6 } from "fs";
1195
+ import { homedir as homedir5 } from "os";
1196
+ import { isAbsolute as isAbsolute3, join as join9, parse, resolve as resolvePath2 } from "path";
1188
1197
  import chalk6 from "chalk";
1189
1198
 
1190
1199
  // ../../packages/types/src/agents/index.ts
@@ -1524,7 +1533,14 @@ function drainSessionDbRecoveryReport({
1524
1533
  skippedLines++;
1525
1534
  return [];
1526
1535
  }
1527
- return [value];
1536
+ return [
1537
+ {
1538
+ ...value,
1539
+ provenance_reason: value.provenance_reason ?? null,
1540
+ provenance_migration_delta: value.provenance_migration_delta ?? null,
1541
+ replication_suspended: value.replication_suspended ?? false
1542
+ }
1543
+ ];
1528
1544
  } catch (error2) {
1529
1545
  skippedLines++;
1530
1546
  console.error(
@@ -1549,12 +1565,39 @@ function buildSessionDbRecoveryActivity(record) {
1549
1565
  const level = record.severity === "warning" ? "warn" : record.severity === "error" ? "error" : null;
1550
1566
  if (!level) return null;
1551
1567
  const noVerifiedPoint = record.verified_restore_point ? ` The verified restore point is ${record.verified_restore_point}.` : " No verified restore point is known.";
1568
+ const replication = record.replication_suspended ? " This start is not backing up its new session history; restart after fixing the cause." : "";
1569
+ const giveupMessage = (() => {
1570
+ switch (record.reason) {
1571
+ case "restore_deadline_exceeded":
1572
+ 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.";
1573
+ case "restore_tool_unusable":
1574
+ case "classification_unrecognised":
1575
+ 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.";
1576
+ case "synchroniser_config_unevaluable":
1577
+ case "synchroniser_config_incomplete":
1578
+ 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.";
1579
+ case "synchroniser_config_unresolved":
1580
+ 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.";
1581
+ case "litestream_config_unavailable":
1582
+ 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.";
1583
+ case "classification_fatal":
1584
+ 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.";
1585
+ default:
1586
+ return null;
1587
+ }
1588
+ })();
1589
+ if (giveupMessage)
1590
+ return {
1591
+ level,
1592
+ metadata: withoutContractFields(record),
1593
+ message: `${giveupMessage}${replication}`
1594
+ };
1552
1595
  switch (record.outcome) {
1553
1596
  case "fresh_session_db":
1554
1597
  return {
1555
1598
  level,
1556
1599
  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.`
1600
+ 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
1601
  };
1559
1602
  case "restore_retried":
1560
1603
  return {
@@ -1592,7 +1635,7 @@ function buildSessionDbRecoveryActivity(record) {
1592
1635
  return {
1593
1636
  level,
1594
1637
  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."
1638
+ 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
1639
  };
1597
1640
  case "session_db_boot_refused":
1598
1641
  return {
@@ -1600,6 +1643,12 @@ function buildSessionDbRecoveryActivity(record) {
1600
1643
  metadata: withoutContractFields(record),
1601
1644
  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
1645
  };
1646
+ case "schema_provenance_mismatch":
1647
+ return {
1648
+ level,
1649
+ metadata: withoutContractFields(record),
1650
+ 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.`
1651
+ };
1603
1652
  default:
1604
1653
  return null;
1605
1654
  }
@@ -1614,7 +1663,8 @@ var OUTCOMES = /* @__PURE__ */ new Set([
1614
1663
  "fresh_session_db",
1615
1664
  "history_rolled_back",
1616
1665
  "restore_misconfigured",
1617
- "session_db_boot_refused"
1666
+ "session_db_boot_refused",
1667
+ "schema_provenance_mismatch"
1618
1668
  ]);
1619
1669
  var STAGES = /* @__PURE__ */ new Set(["restore", "verify"]);
1620
1670
  var SEVERITIES = /* @__PURE__ */ new Set(["warning", "error"]);
@@ -1632,7 +1682,7 @@ var STRING_OR_NULL_FIELDS = ["quarantine_destination", "verified_restore_point"]
1632
1682
  function isSessionDbRecoveryRecord(value) {
1633
1683
  if (!value || typeof value !== "object" || Array.isArray(value)) return false;
1634
1684
  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(
1685
+ 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
1686
  (field) => record[field] === null || typeof record[field] === "string"
1637
1687
  );
1638
1688
  }
@@ -1661,11 +1711,667 @@ async function waitForOpenCodeHealth(port, timeoutMs = 3e4) {
1661
1711
  if (health.healthy) {
1662
1712
  return health;
1663
1713
  }
1664
- await new Promise((resolve3) => setTimeout(resolve3, 1e3));
1714
+ await new Promise((resolve4) => setTimeout(resolve4, 1e3));
1665
1715
  }
1666
1716
  return { healthy: false, error: "Timeout waiting for OpenCode to be healthy" };
1667
1717
  }
1668
1718
 
1719
+ // src/lib/opencode/session-db-boot.ts
1720
+ import { spawn as spawn2 } from "child_process";
1721
+ import { mkdirSync, statSync as statSync2, unlinkSync as unlinkSync2, writeFileSync } from "fs";
1722
+ import { homedir as homedir2 } from "os";
1723
+ import { dirname as dirname2, resolve as resolvePath } from "path";
1724
+
1725
+ // src/lib/runner-synchroniser.ts
1726
+ import { spawn } from "child_process";
1727
+ function appendError(stderr, error2) {
1728
+ const message = error2 instanceof Error ? error2.message : String(error2);
1729
+ return stderr === "" ? message : `${stderr}
1730
+ ${message}`;
1731
+ }
1732
+ function runSynchroniser(args, opts) {
1733
+ return new Promise((resolve4) => {
1734
+ let child;
1735
+ let stdout = "";
1736
+ let stderr = "";
1737
+ let settled = false;
1738
+ const timer = {};
1739
+ let abortListener;
1740
+ let spawnListener;
1741
+ const finish = (result) => {
1742
+ if (settled) return;
1743
+ settled = true;
1744
+ if (timer.handle) clearTimeout(timer.handle);
1745
+ if (abortListener) opts.signal?.removeEventListener("abort", abortListener);
1746
+ if (spawnListener) child.removeListener("spawn", spawnListener);
1747
+ resolve4(result);
1748
+ };
1749
+ try {
1750
+ child = spawn("runner-synchroniser", args, {
1751
+ env: opts.env ?? process.env,
1752
+ stdio: ["ignore", "pipe", "pipe"]
1753
+ });
1754
+ } catch (error2) {
1755
+ finish({ code: null, stdout, stderr: appendError(stderr, error2), timedOut: false });
1756
+ return;
1757
+ }
1758
+ child.stdout?.setEncoding("utf8");
1759
+ child.stdout?.on("data", (chunk) => {
1760
+ stdout += chunk;
1761
+ });
1762
+ child.stderr?.setEncoding("utf8");
1763
+ child.stderr?.on("data", (chunk) => {
1764
+ stderr += chunk;
1765
+ });
1766
+ child.once("error", (error2) => {
1767
+ finish({ code: null, stdout, stderr: appendError(stderr, error2), timedOut: false });
1768
+ });
1769
+ child.once("close", (code) => {
1770
+ finish({ code, stdout, stderr, timedOut: false });
1771
+ });
1772
+ if (opts.signal) {
1773
+ const killChild = () => {
1774
+ if (child.pid === void 0) {
1775
+ if (!spawnListener) {
1776
+ spawnListener = killChild;
1777
+ child.once("spawn", spawnListener);
1778
+ }
1779
+ return;
1780
+ }
1781
+ child.kill("SIGKILL");
1782
+ };
1783
+ abortListener = killChild;
1784
+ if (opts.signal.aborted) {
1785
+ abortListener();
1786
+ } else {
1787
+ opts.signal.addEventListener("abort", abortListener, { once: true });
1788
+ if (opts.signal.aborted) abortListener();
1789
+ }
1790
+ }
1791
+ timer.handle = setTimeout(
1792
+ () => {
1793
+ child.kill("SIGKILL");
1794
+ finish({ code: null, stdout, stderr, timedOut: true });
1795
+ },
1796
+ Math.max(0, opts.timeoutMs)
1797
+ );
1798
+ });
1799
+ }
1800
+
1801
+ // src/lib/opencode/session-db-boot.ts
1802
+ var SESSION_DB_RESTORE_TIMEOUT_MS = 3e5;
1803
+ var SESSION_DB_VERIFY_TIMEOUT_MS = 12e4;
1804
+ var SESSION_DB_SYNCHRONISER_TIMEOUT_MS = 12e4;
1805
+ var SESSION_DB_VERIFY_WALKBACK_BUDGET_SECONDS = 120;
1806
+ function commandError(result) {
1807
+ return result.stderr.trim() || `process exited with code ${result.code ?? "null"}`;
1808
+ }
1809
+ function reportRecord(stage, outcome, reason, litestreamExitCode, options) {
1810
+ options.reportRecovery({
1811
+ v: 1,
1812
+ event: "session_db_recovery",
1813
+ at: (/* @__PURE__ */ new Date()).toISOString(),
1814
+ stage,
1815
+ outcome,
1816
+ severity: "error",
1817
+ reason,
1818
+ litestream_exit_code: litestreamExitCode,
1819
+ attempt: null,
1820
+ replica_objects: null,
1821
+ replica_bytes: null,
1822
+ quarantine_destination: null,
1823
+ quarantined_objects: null,
1824
+ quarantine_failed_objects: null,
1825
+ quarantined_bytes: null,
1826
+ verified_restore_point: null,
1827
+ restore_points_tried: null,
1828
+ provenance_reason: null,
1829
+ provenance_migration_delta: null,
1830
+ replication_suspended: stage === "restore"
1831
+ });
1832
+ }
1833
+ function clearMarker(options) {
1834
+ if (!options.noReplicateMarker) return;
1835
+ try {
1836
+ unlinkSync2(options.noReplicateMarker);
1837
+ } catch (error2) {
1838
+ if (error2 instanceof Error && "code" in error2 && error2.code === "ENOENT") return;
1839
+ options.log(
1840
+ `Could not clear the previous session-DB no-replicate marker ${options.noReplicateMarker}: ${error2 instanceof Error ? error2.message : String(error2)}`,
1841
+ "warn"
1842
+ );
1843
+ }
1844
+ }
1845
+ function markNoReplicate(options, message) {
1846
+ if (options.noReplicateMarker) {
1847
+ try {
1848
+ mkdirSync(dirname2(options.noReplicateMarker), { recursive: true });
1849
+ writeFileSync(options.noReplicateMarker, "");
1850
+ } catch (error2) {
1851
+ options.log(
1852
+ `Could not write session-DB no-replicate marker ${options.noReplicateMarker}: ${error2 instanceof Error ? error2.message : String(error2)}`,
1853
+ "error"
1854
+ );
1855
+ }
1856
+ }
1857
+ options.log(`SESSION-DB-NO-REPLICATE: ${message}`, "warn");
1858
+ }
1859
+ function discardSessionDbDebris(options) {
1860
+ for (const path of [options.dbPath, `${options.dbPath}-wal`, `${options.dbPath}-shm`]) {
1861
+ try {
1862
+ unlinkSync2(path);
1863
+ } catch (error2) {
1864
+ if (error2 instanceof Error && "code" in error2 && error2.code === "ENOENT") continue;
1865
+ options.log(
1866
+ `Could not remove session-DB debris ${path}: ${error2 instanceof Error ? error2.message : String(error2)}`,
1867
+ "warn"
1868
+ );
1869
+ }
1870
+ }
1871
+ }
1872
+ function splitDiagnostics(text) {
1873
+ return text.split("\n").map((line) => line.trim()).filter((line) => line.length > 0);
1874
+ }
1875
+ function logSynchroniserDiagnostics(result, options) {
1876
+ for (const line of splitDiagnostics(result.stderr)) options.log(line, "warn");
1877
+ }
1878
+ function parseSingleQuotedAssignment(line) {
1879
+ const match = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(line);
1880
+ if (!match || !match[2].startsWith("'")) return null;
1881
+ const valueSource = match[2];
1882
+ let value = "";
1883
+ for (let index = 1; index < valueSource.length; index++) {
1884
+ const character = valueSource[index];
1885
+ if (character !== "'") {
1886
+ value += character;
1887
+ continue;
1888
+ }
1889
+ if (index === valueSource.length - 1) return [match[1], value];
1890
+ if (valueSource.slice(index + 1, index + 4) !== "\\''") return null;
1891
+ value += "'";
1892
+ index += 3;
1893
+ }
1894
+ return null;
1895
+ }
1896
+ function parseSynchroniserEnv(stdout) {
1897
+ const values = {};
1898
+ for (const line of stdout.split("\n")) {
1899
+ if (line.trim() === "") continue;
1900
+ const assignment = parseSingleQuotedAssignment(line);
1901
+ if (!assignment) return null;
1902
+ values[assignment[0]] = assignment[1];
1903
+ }
1904
+ return values;
1905
+ }
1906
+ function runCommand(command, args, options) {
1907
+ return new Promise((resolve4) => {
1908
+ let child;
1909
+ let stdout = "";
1910
+ let stderr = "";
1911
+ let settled = false;
1912
+ const finish = (result) => {
1913
+ if (settled) return;
1914
+ settled = true;
1915
+ if (timer) clearTimeout(timer);
1916
+ resolve4(result);
1917
+ };
1918
+ try {
1919
+ child = spawn2(command, args, {
1920
+ env: options.env,
1921
+ stdio: ["ignore", "pipe", "pipe"]
1922
+ });
1923
+ } catch (error2) {
1924
+ resolve4({
1925
+ code: null,
1926
+ stdout,
1927
+ stderr: error2 instanceof Error ? error2.message : String(error2),
1928
+ timedOut: false
1929
+ });
1930
+ return;
1931
+ }
1932
+ child.stdout?.setEncoding("utf8");
1933
+ child.stdout?.on("data", (chunk) => {
1934
+ stdout += chunk;
1935
+ });
1936
+ child.stderr?.setEncoding("utf8");
1937
+ child.stderr?.on("data", (chunk) => {
1938
+ stderr += chunk;
1939
+ });
1940
+ child.once("error", (error2) => {
1941
+ finish({
1942
+ code: null,
1943
+ stdout,
1944
+ stderr: stderr === "" ? error2.message : `${stderr}
1945
+ ${error2.message}`,
1946
+ timedOut: false
1947
+ });
1948
+ });
1949
+ child.once("close", (code) => finish({ code, stdout, stderr, timedOut: false }));
1950
+ const timer = setTimeout(
1951
+ () => {
1952
+ child.kill("SIGKILL");
1953
+ finish({ code: null, stdout, stderr, timedOut: true });
1954
+ },
1955
+ Math.max(0, options.timeoutMs)
1956
+ );
1957
+ });
1958
+ }
1959
+ async function ensureLitestreamConfig(options, env) {
1960
+ const configPath = options.litestreamConfig;
1961
+ if (!configPath) {
1962
+ markNoReplicate(options, "no Litestream configuration path was provided");
1963
+ reportRecord(
1964
+ "restore",
1965
+ "restore_misconfigured",
1966
+ "litestream_config_unavailable",
1967
+ null,
1968
+ options
1969
+ );
1970
+ return null;
1971
+ }
1972
+ try {
1973
+ if (statSync2(configPath).size > 0) return configPath;
1974
+ } catch (error2) {
1975
+ if (!(error2 instanceof Error && "code" in error2 && error2.code === "ENOENT")) {
1976
+ options.log(
1977
+ `Could not inspect ${configPath}: ${error2 instanceof Error ? error2.message : String(error2)}`,
1978
+ "warn"
1979
+ );
1980
+ }
1981
+ }
1982
+ const rendered = await runSynchroniser(["litestream-config"], {
1983
+ timeoutMs: SESSION_DB_SYNCHRONISER_TIMEOUT_MS,
1984
+ env
1985
+ });
1986
+ logSynchroniserDiagnostics(rendered, options);
1987
+ if (rendered.timedOut || rendered.code !== 0) {
1988
+ options.log(
1989
+ `Could not generate ${configPath}: runner-synchroniser litestream-config failed (${commandError(rendered)})`,
1990
+ "error"
1991
+ );
1992
+ markNoReplicate(options, `could not generate ${configPath}`);
1993
+ reportRecord(
1994
+ "restore",
1995
+ "restore_misconfigured",
1996
+ "litestream_config_unavailable",
1997
+ null,
1998
+ options
1999
+ );
2000
+ return null;
2001
+ }
2002
+ try {
2003
+ mkdirSync(dirname2(configPath), { recursive: true });
2004
+ writeFileSync(configPath, rendered.stdout);
2005
+ } catch (error2) {
2006
+ options.log(
2007
+ `Could not write ${configPath}: ${error2 instanceof Error ? error2.message : String(error2)}`,
2008
+ "error"
2009
+ );
2010
+ markNoReplicate(options, `could not generate ${configPath}`);
2011
+ reportRecord(
2012
+ "restore",
2013
+ "restore_misconfigured",
2014
+ "litestream_config_unavailable",
2015
+ null,
2016
+ options
2017
+ );
2018
+ return null;
2019
+ }
2020
+ const version2 = await runCommand("litestream", ["version"], {
2021
+ env,
2022
+ timeoutMs: 1e4
2023
+ });
2024
+ const litestreamVersion = version2.code === 0 ? version2.stdout.trim() || "unknown" : "unknown";
2025
+ const regionEmpty = !/^\s*region:\s*\S+/m.test(rendered.stdout);
2026
+ options.log(
2027
+ `litestream ${litestreamVersion}; AWS_REGION=${env.AWS_REGION ?? "<unset>"} AWS_DEFAULT_REGION=${env.AWS_DEFAULT_REGION ?? "<unset>"}; rendered litestream.yml region empty: ${regionEmpty ? "yes" : "no"}`
2028
+ );
2029
+ return configPath;
2030
+ }
2031
+ function restoreGiveUp(options, reason, message, litestreamExitCode, outcome = "fresh_session_db") {
2032
+ discardSessionDbDebris(options);
2033
+ markNoReplicate(options, message);
2034
+ reportRecord("restore", outcome, reason, litestreamExitCode, options);
2035
+ }
2036
+ async function restoreSessionDb(options, configPath, env) {
2037
+ const restored = await runCommand(
2038
+ "litestream",
2039
+ ["restore", "-config", configPath, "-if-db-not-exists", "-if-replica-exists", options.dbPath],
2040
+ { env, timeoutMs: SESSION_DB_RESTORE_TIMEOUT_MS }
2041
+ );
2042
+ for (const line of splitDiagnostics(restored.stderr)) options.log(line, "warn");
2043
+ if (restored.timedOut || restored.code === 124 || restored.code === 137) {
2044
+ restoreGiveUp(
2045
+ options,
2046
+ "restore_deadline_exceeded",
2047
+ `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`,
2048
+ restored.code ?? 124
2049
+ );
2050
+ return;
2051
+ }
2052
+ if (restored.code === null || restored.code === 125 || restored.code === 126 || restored.code === 127) {
2053
+ options.log(`litestream restore could not run (${commandError(restored)})`, "error");
2054
+ restoreGiveUp(
2055
+ options,
2056
+ "restore_tool_unusable",
2057
+ `restore tool is broken (${commandError(restored)}); opencode starts with a fresh session DB and nothing is replicated this boot`,
2058
+ restored.code
2059
+ );
2060
+ return;
2061
+ }
2062
+ const classified = await runSynchroniser(
2063
+ [
2064
+ "session-db-classify",
2065
+ String(restored.code ?? 1),
2066
+ "1",
2067
+ "--on-unusable-replica=leave",
2068
+ "--fresh-db-fallback"
2069
+ ],
2070
+ { timeoutMs: SESSION_DB_SYNCHRONISER_TIMEOUT_MS, env }
2071
+ );
2072
+ logSynchroniserDiagnostics(classified, options);
2073
+ const classifyCode = classified.code;
2074
+ switch (classifyCode) {
2075
+ case 0:
2076
+ return;
2077
+ case 31:
2078
+ acknowledgeSessionDbRecoveryReport(sessionDbRecoveryReportPath(homedir2(), env));
2079
+ options.log(
2080
+ "SESSION-DB-REPLICA-UNUSABLE: booting with a fresh opencode.db and replicating into the existing prefix this boot",
2081
+ "warn"
2082
+ );
2083
+ return;
2084
+ case 32:
2085
+ acknowledgeSessionDbRecoveryReport(sessionDbRecoveryReportPath(homedir2(), env));
2086
+ discardSessionDbDebris(options);
2087
+ markNoReplicate(
2088
+ options,
2089
+ "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"
2090
+ );
2091
+ return;
2092
+ case 30:
2093
+ restoreGiveUp(
2094
+ options,
2095
+ "classification_fatal",
2096
+ "session-db-classify returned fatal (30); see the FATAL message above",
2097
+ restored.code,
2098
+ "restore_misconfigured"
2099
+ );
2100
+ return;
2101
+ default:
2102
+ restoreGiveUp(
2103
+ options,
2104
+ "classification_unrecognised",
2105
+ `session-db-classify exited ${classifyCode ?? "null"}, which is none of its documented answers`,
2106
+ restored.code
2107
+ );
2108
+ }
2109
+ }
2110
+ async function verifySessionDb(options, configPath, env) {
2111
+ if (!options.noReplicateMarker || !fileExists(options.noReplicateMarker)) {
2112
+ const result = await runSynchroniser(["session-db-verify", configPath], {
2113
+ timeoutMs: SESSION_DB_VERIFY_TIMEOUT_MS,
2114
+ env: {
2115
+ ...env,
2116
+ // The synchroniser reads this value in SECONDS. Keep this at 120, not
2117
+ // 120_000, so the walkback gives up before the outer process bound.
2118
+ EVIDENT_SESSION_DB_WALKBACK_BUDGET_SECONDS: String(
2119
+ SESSION_DB_VERIFY_WALKBACK_BUDGET_SECONDS
2120
+ )
2121
+ }
2122
+ });
2123
+ logSynchroniserDiagnostics(result, options);
2124
+ if (result.timedOut || result.code === 124 || result.code === 137) {
2125
+ options.log(
2126
+ `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`,
2127
+ "warn"
2128
+ );
2129
+ return false;
2130
+ }
2131
+ if (result.code === 34) {
2132
+ reportRecord(
2133
+ "verify",
2134
+ "session_db_boot_refused",
2135
+ result.stderr.includes("SESSION-DB-LOCAL-DISCARD-FAILED") ? "local_discard_failed" : "replica_separation_unproven",
2136
+ null,
2137
+ options
2138
+ );
2139
+ return true;
2140
+ }
2141
+ if (result.code === 33) {
2142
+ options.log(
2143
+ "SESSION-DB-INTEGRITY-EXHAUSTED: booting continues and litestream still replicates, starting an empty backup chain after the corrupt replica was separated.",
2144
+ "warn"
2145
+ );
2146
+ return false;
2147
+ }
2148
+ if (result.code !== 0) {
2149
+ options.log(
2150
+ `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`,
2151
+ "warn"
2152
+ );
2153
+ }
2154
+ return false;
2155
+ }
2156
+ options.log(
2157
+ "skipping session-DB verification: this boot's session DB was not proven safe to replicate",
2158
+ "debug"
2159
+ );
2160
+ return false;
2161
+ }
2162
+ function fileExists(path) {
2163
+ try {
2164
+ statSync2(path);
2165
+ return true;
2166
+ } catch (error2) {
2167
+ if (error2 instanceof Error && "code" in error2 && error2.code === "ENOENT") return false;
2168
+ return true;
2169
+ }
2170
+ }
2171
+ async function restoreAndVerifySessionDb(options) {
2172
+ const env = options.env ?? process.env;
2173
+ clearMarker(options);
2174
+ acknowledgeSessionDbRecoveryReport(sessionDbRecoveryReportPath(homedir2(), env));
2175
+ const synchroniserEnv = await runSynchroniser(["env"], {
2176
+ timeoutMs: SESSION_DB_SYNCHRONISER_TIMEOUT_MS,
2177
+ env
2178
+ });
2179
+ logSynchroniserDiagnostics(synchroniserEnv, options);
2180
+ if (synchroniserEnv.timedOut || synchroniserEnv.code !== 0) {
2181
+ options.log(
2182
+ `runner-synchroniser env could not resolve the session-DB configuration (${commandError(synchroniserEnv)})`,
2183
+ "error"
2184
+ );
2185
+ markNoReplicate(
2186
+ options,
2187
+ "could not resolve the runner-synchroniser configuration (see the ERROR above)"
2188
+ );
2189
+ reportRecord(
2190
+ "restore",
2191
+ "restore_misconfigured",
2192
+ "synchroniser_config_unresolved",
2193
+ null,
2194
+ options
2195
+ );
2196
+ return { verifyFatal: false };
2197
+ }
2198
+ const values = parseSynchroniserEnv(synchroniserEnv.stdout);
2199
+ if (!values) {
2200
+ markNoReplicate(
2201
+ options,
2202
+ "the runner-synchroniser configuration could not be evaluated; the installed bundle likely does not match this hook"
2203
+ );
2204
+ reportRecord(
2205
+ "restore",
2206
+ "restore_misconfigured",
2207
+ "synchroniser_config_unevaluable",
2208
+ null,
2209
+ options
2210
+ );
2211
+ return { verifyFatal: false };
2212
+ }
2213
+ const synchroniserDbPath = values.OPENCODE_DB_PATH;
2214
+ if (!synchroniserDbPath) {
2215
+ markNoReplicate(
2216
+ options,
2217
+ "run_synchroniser env did not define OPENCODE_DB_PATH; the installed runner-synchroniser build likely does not match this hook"
2218
+ );
2219
+ reportRecord(
2220
+ "restore",
2221
+ "restore_misconfigured",
2222
+ "synchroniser_config_incomplete",
2223
+ null,
2224
+ options
2225
+ );
2226
+ return { verifyFatal: false };
2227
+ }
2228
+ if (resolvePath(synchroniserDbPath) !== resolvePath(options.dbPath)) {
2229
+ options.log(
2230
+ `runner-synchroniser reported OPENCODE_DB_PATH=${synchroniserDbPath}, but OpenCode uses ${options.dbPath}; continuing with OpenCode's session-DB path`,
2231
+ "warn"
2232
+ );
2233
+ }
2234
+ if (!values.PERSISTENCE_BUCKET) {
2235
+ options.log(
2236
+ "SESSION-DB-PERSISTENCE-DISABLED: LITESTREAM_BUCKET/LITESTREAM_PREFIX are not both set; opencode starts with a fresh session DB and nothing is replicated.",
2237
+ "warn"
2238
+ );
2239
+ return { verifyFatal: false };
2240
+ }
2241
+ const configPath = await ensureLitestreamConfig(options, env);
2242
+ if (!configPath) return { verifyFatal: false };
2243
+ await restoreSessionDb(options, configPath, env);
2244
+ if (options.noReplicateMarker && fileExists(options.noReplicateMarker)) {
2245
+ return { verifyFatal: false };
2246
+ }
2247
+ return { verifyFatal: await verifySessionDb(options, configPath, env) };
2248
+ }
2249
+
2250
+ // src/lib/opencode/session-db-provenance.ts
2251
+ import { createRequire } from "module";
2252
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
2253
+ import { dirname as dirname3, join as join3 } from "path";
2254
+ var require2 = createRequire(import.meta.url);
2255
+ function readSessionDbMigrationIds(dbPath) {
2256
+ let db;
2257
+ try {
2258
+ const { DatabaseSync } = require2("node:sqlite");
2259
+ db = new DatabaseSync(dbPath, { readOnly: true });
2260
+ const columns = db.prepare("PRAGMA table_info(migration)").all();
2261
+ const hasExpectedShape = columns.length === 2 && columns.some(
2262
+ (column) => column.name === "id" && typeof column.type === "string" && column.type.toUpperCase() === "TEXT" && column.pk === 1
2263
+ ) && columns.some(
2264
+ (column) => column.name === "time_completed" && typeof column.type === "string" && column.type.toUpperCase() === "INTEGER" && column.notnull === 1 && column.pk === 0
2265
+ );
2266
+ if (!hasExpectedShape) {
2267
+ console.warn(`[readSessionDbMigrationIds] unsupported migration table shape in ${dbPath}`);
2268
+ return null;
2269
+ }
2270
+ const rows = db.prepare("SELECT id FROM migration ORDER BY id").all();
2271
+ if (rows.some((row) => typeof row.id !== "string")) return null;
2272
+ return rows.map((row) => row.id);
2273
+ } catch (error2) {
2274
+ console.warn(
2275
+ `[readSessionDbMigrationIds] could not read migration history from ${dbPath}: ${error2 instanceof Error ? error2.message : String(error2)}`
2276
+ );
2277
+ return null;
2278
+ } finally {
2279
+ try {
2280
+ db?.close();
2281
+ } catch (error2) {
2282
+ console.warn(
2283
+ `[readSessionDbMigrationIds] could not close ${dbPath}: ${error2 instanceof Error ? error2.message : String(error2)}`
2284
+ );
2285
+ }
2286
+ }
2287
+ }
2288
+ function sessionDbProvenanceStatePath(homeDir, env) {
2289
+ const override = env.EVIDENT_SESSION_DB_PROVENANCE_STATE?.trim();
2290
+ return override || join3(homeDir, ".local", "state", "evident", "session-db-provenance.json");
2291
+ }
2292
+ function loadSessionDbProvenanceState(path) {
2293
+ let value;
2294
+ try {
2295
+ value = JSON.parse(readFileSync3(path, "utf8"));
2296
+ } catch (error2) {
2297
+ if (error2 instanceof Error && "code" in error2 && error2.code === "ENOENT") return {};
2298
+ console.error(
2299
+ `[session-db-provenance] could not read ${path}: ${error2 instanceof Error ? error2.message : String(error2)}`
2300
+ );
2301
+ return {};
2302
+ }
2303
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
2304
+ console.error(`[session-db-provenance] ignored malformed state in ${path}`);
2305
+ return {};
2306
+ }
2307
+ const state = {};
2308
+ for (const [dbPath, record] of Object.entries(value)) {
2309
+ if (!isSessionDbProvenanceRecord(record)) {
2310
+ console.error(`[session-db-provenance] ignored malformed state in ${path}`);
2311
+ return {};
2312
+ }
2313
+ state[dbPath] = record;
2314
+ }
2315
+ return state;
2316
+ }
2317
+ function saveSessionDbProvenanceState(path, state) {
2318
+ try {
2319
+ mkdirSync2(dirname3(path), { recursive: true });
2320
+ writeFileSync2(path, `${JSON.stringify(state, null, 2)}
2321
+ `, "utf8");
2322
+ } catch (error2) {
2323
+ console.error(
2324
+ `[session-db-provenance] could not write ${path}: ${error2 instanceof Error ? error2.message : String(error2)}`
2325
+ );
2326
+ }
2327
+ }
2328
+ function evaluateSessionDbProvenance(input) {
2329
+ const { currentVersion, currentIds, previous } = input;
2330
+ if (!previous) return { anomaly: false, reason: null };
2331
+ const current = new Set(currentIds);
2332
+ const prior = new Set(previous.migrationIds);
2333
+ for (const id of prior) {
2334
+ if (!current.has(id)) return { anomaly: true, reason: "migration-history-regressed" };
2335
+ }
2336
+ if (current.size > prior.size && previous.opencodeVersion === currentVersion) {
2337
+ return { anomaly: true, reason: "foreign-version-migrations" };
2338
+ }
2339
+ return { anomaly: false, reason: null };
2340
+ }
2341
+ function checkSessionDbProvenance(input) {
2342
+ const { dbPath, currentVersion, homeDir, env } = input;
2343
+ const path = sessionDbProvenanceStatePath(homeDir, env);
2344
+ const state = loadSessionDbProvenanceState(path);
2345
+ const previous = state[dbPath];
2346
+ const currentIds = readSessionDbMigrationIds(dbPath);
2347
+ if (currentIds === null) {
2348
+ return {
2349
+ anomaly: false,
2350
+ reason: null,
2351
+ recordedVersion: previous?.opencodeVersion ?? null,
2352
+ migrationDelta: null
2353
+ };
2354
+ }
2355
+ const decision = evaluateSessionDbProvenance({ currentVersion, currentIds, previous });
2356
+ const migrationDelta = previous ? new Set(currentIds).size - new Set(previous.migrationIds).size : null;
2357
+ state[dbPath] = {
2358
+ opencodeVersion: currentVersion,
2359
+ migrationIds: currentIds,
2360
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
2361
+ };
2362
+ saveSessionDbProvenanceState(path, state);
2363
+ return {
2364
+ ...decision,
2365
+ recordedVersion: previous?.opencodeVersion ?? null,
2366
+ migrationDelta
2367
+ };
2368
+ }
2369
+ function isSessionDbProvenanceRecord(value) {
2370
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
2371
+ const record = value;
2372
+ return typeof record.opencodeVersion === "string" && Array.isArray(record.migrationIds) && record.migrationIds.every((id) => typeof id === "string") && typeof record.updatedAt === "string";
2373
+ }
2374
+
1669
2375
  // src/lib/opencode/opencode-version-gate.ts
1670
2376
  var QUEUE_VALIDATED_OPENCODE_VERSIONS = ["1.17.11", "1.18.3"];
1671
2377
  function isQueueValidatedVersion(version2) {
@@ -1680,7 +2386,63 @@ function buildOpenCodeVersionWarning(version2) {
1680
2386
  }
1681
2387
 
1682
2388
  // src/lib/opencode/process.ts
1683
- import { execSync, spawn } from "child_process";
2389
+ import { execSync, spawn as spawn3 } from "child_process";
2390
+
2391
+ // src/lib/process-stop.ts
2392
+ async function stopProcessAndWait(child, timeoutMs, sendTerm, sendKill) {
2393
+ if (!child.pid) {
2394
+ return { outcome: "not-running", code: child.exitCode, signal: child.signalCode };
2395
+ }
2396
+ if (child.exitCode !== null || child.signalCode !== null) {
2397
+ return { outcome: "exited", code: child.exitCode, signal: child.signalCode };
2398
+ }
2399
+ return new Promise((resolve4, reject) => {
2400
+ let forced = false;
2401
+ let settled = false;
2402
+ const timer = setTimeout(() => {
2403
+ forced = true;
2404
+ try {
2405
+ sendKill();
2406
+ } catch (error2) {
2407
+ if (error2.code === "ESRCH") {
2408
+ finish({ outcome: "exited", code: child.exitCode, signal: child.signalCode });
2409
+ } else {
2410
+ fail(error2);
2411
+ }
2412
+ }
2413
+ }, timeoutMs);
2414
+ const finish = (result) => {
2415
+ if (settled) return;
2416
+ settled = true;
2417
+ clearTimeout(timer);
2418
+ child.removeListener("exit", onExit);
2419
+ resolve4(result);
2420
+ };
2421
+ const fail = (error2) => {
2422
+ if (settled) return;
2423
+ settled = true;
2424
+ clearTimeout(timer);
2425
+ child.removeListener("exit", onExit);
2426
+ reject(error2);
2427
+ };
2428
+ const onExit = (code, signal) => {
2429
+ finish({ outcome: forced ? "killed" : "exited", code, signal });
2430
+ };
2431
+ child.once("exit", onExit);
2432
+ try {
2433
+ sendTerm();
2434
+ } catch (error2) {
2435
+ if (error2.code === "ESRCH") {
2436
+ finish({ outcome: "exited", code: child.exitCode, signal: child.signalCode });
2437
+ } else {
2438
+ fail(error2);
2439
+ }
2440
+ return;
2441
+ }
2442
+ });
2443
+ }
2444
+
2445
+ // src/lib/opencode/process.ts
1684
2446
  var OPENCODE_PORT_RANGE = [4096, 4097, 4098, 4099, 4100];
1685
2447
  function getProcessCwd(pid) {
1686
2448
  const platform = process.platform;
@@ -1836,39 +2598,45 @@ async function findHealthyOpenCodeInstances() {
1836
2598
  }
1837
2599
  return healthy;
1838
2600
  }
1839
- async function startOpenCode(port) {
2601
+ async function startOpenCode(port, options = {}) {
1840
2602
  let command = "opencode";
1841
- let args = ["serve", "--port", port.toString(), "--hostname", "127.0.0.1"];
2603
+ const printLogs = options.inheritStdio ? ["--print-logs"] : [];
2604
+ let args = ["serve", "--port", port.toString(), "--hostname", "127.0.0.1", ...printLogs];
1842
2605
  try {
1843
2606
  execSync("which opencode", { stdio: "ignore" });
1844
2607
  } catch {
1845
2608
  command = "npx";
1846
- args = ["opencode", "serve", "--port", port.toString(), "--hostname", "127.0.0.1"];
1847
- }
1848
- const child = spawn(command, args, {
2609
+ args = [
2610
+ "opencode",
2611
+ "serve",
2612
+ "--port",
2613
+ port.toString(),
2614
+ "--hostname",
2615
+ "127.0.0.1",
2616
+ ...printLogs
2617
+ ];
2618
+ }
2619
+ const child = spawn3(command, args, {
1849
2620
  detached: true,
1850
- stdio: "ignore",
2621
+ stdio: options.inheritStdio ? "inherit" : "ignore",
1851
2622
  cwd: process.cwd()
1852
2623
  });
1853
2624
  return child;
1854
2625
  }
1855
- function stopOpenCode(opencodeProcess) {
1856
- if (!opencodeProcess || !opencodeProcess.pid) {
1857
- return;
1858
- }
1859
- try {
2626
+ function stopOpenCodeAndWait(opencodeProcess, timeoutMs) {
2627
+ const sendSignal = (signal) => {
1860
2628
  if (process.platform === "win32") {
1861
- opencodeProcess.kill("SIGTERM");
2629
+ opencodeProcess.kill(signal);
1862
2630
  } else {
1863
- process.kill(-opencodeProcess.pid, "SIGTERM");
2631
+ process.kill(-opencodeProcess.pid, signal);
1864
2632
  }
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
- }
2633
+ };
2634
+ return stopProcessAndWait(
2635
+ opencodeProcess,
2636
+ timeoutMs,
2637
+ () => sendSignal("SIGTERM"),
2638
+ () => sendSignal("SIGKILL")
2639
+ );
1872
2640
  }
1873
2641
 
1874
2642
  // src/lib/opencode/install.ts
@@ -2155,6 +2923,7 @@ async function createOpenCodeSession(port, directory) {
2155
2923
  return data.id;
2156
2924
  }
2157
2925
  async function getModelAttachmentCapability(port, model) {
2926
+ const { model: baseModel } = splitModelVariant(model);
2158
2927
  try {
2159
2928
  const res = await timedFetch(`${opencodeBase(port)}/config/providers`);
2160
2929
  if (!res.ok) {
@@ -2171,9 +2940,9 @@ async function getModelAttachmentCapability(port, model) {
2171
2940
  );
2172
2941
  return null;
2173
2942
  }
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;
2943
+ const slash = baseModel ? baseModel.indexOf("/") : -1;
2944
+ const providerId = slash > 0 ? baseModel.slice(0, slash) : void 0;
2945
+ let modelId = slash > 0 ? baseModel.slice(slash + 1) : void 0;
2177
2946
  const defaults2 = body?.default && typeof body.default === "object" ? body.default : void 0;
2178
2947
  let provider = providerId ? providers.find((p) => p?.id === providerId) : void 0;
2179
2948
  if (!provider && !providerId) {
@@ -2253,6 +3022,29 @@ async function buildFileParts(attachments, capable) {
2253
3022
  }
2254
3023
  return { parts, outcomes, capabilityUnknown };
2255
3024
  }
3025
+ function splitModelVariant(raw) {
3026
+ const value = raw?.trim();
3027
+ if (!value) return {};
3028
+ const hashIndex = value.indexOf("#");
3029
+ if (hashIndex === -1) return { model: value };
3030
+ const model = value.slice(0, hashIndex).trim() || void 0;
3031
+ const variant = value.slice(hashIndex + 1).trim() || void 0;
3032
+ return { model, variant };
3033
+ }
3034
+ function applyModelOptions(body, options) {
3035
+ if (options?.agent) body.agent = options.agent;
3036
+ const { model, variant } = splitModelVariant(options?.model);
3037
+ if (model) {
3038
+ const slashIndex = model.indexOf("/");
3039
+ if (slashIndex !== -1) {
3040
+ body.model = {
3041
+ providerID: model.substring(0, slashIndex),
3042
+ modelID: model.substring(slashIndex + 1)
3043
+ };
3044
+ }
3045
+ }
3046
+ if (variant) body.variant = variant;
3047
+ }
2256
3048
  function messageText(m) {
2257
3049
  if (!m || !Array.isArray(m.parts)) return "";
2258
3050
  return m.parts.filter((p) => p.type === "text" && typeof p.text === "string").map((p) => p.text).join("");
@@ -2277,18 +3069,7 @@ async function sendPromptAsync(port, sessionId, content, options, attachments) {
2277
3069
  const body = {
2278
3070
  parts
2279
3071
  };
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
- }
3072
+ applyModelOptions(body, options);
2292
3073
  const res = await timedFetch(`${opencodeBase(port)}/session/${sessionId}/prompt_async`, {
2293
3074
  method: "POST",
2294
3075
  headers: { "Content-Type": "application/json" },
@@ -2296,7 +3077,10 @@ async function sendPromptAsync(port, sessionId, content, options, attachments) {
2296
3077
  });
2297
3078
  if (res.status < 200 || res.status >= 300) {
2298
3079
  const text = await res.text().catch(() => "");
2299
- throw new Error(`OpenCode prompt_async failed: HTTP ${res.status}${text ? `: ${text}` : ""}`);
3080
+ const { variant } = splitModelVariant(options?.model);
3081
+ throw new Error(
3082
+ `OpenCode prompt_async failed: HTTP ${res.status}${text ? `: ${text}` : ""}${variant ? ` (variant: ${variant})` : ""}`
3083
+ );
2300
3084
  }
2301
3085
  const READ_BACK_ATTEMPTS = 5;
2302
3086
  const READ_BACK_DELAY_MS = 150;
@@ -2320,7 +3104,7 @@ async function sendPromptAsync(port, sessionId, content, options, attachments) {
2320
3104
  }
2321
3105
  }
2322
3106
  if (attempt < READ_BACK_ATTEMPTS - 1) {
2323
- await new Promise((resolve3) => setTimeout(resolve3, READ_BACK_DELAY_MS));
3107
+ await new Promise((resolve4) => setTimeout(resolve4, READ_BACK_DELAY_MS));
2324
3108
  }
2325
3109
  }
2326
3110
  return null;
@@ -2673,13 +3457,13 @@ function resolveSessionCleanupConfig(flags, env = process.env) {
2673
3457
  }
2674
3458
 
2675
3459
  // src/lib/opencode/session-db-size.ts
2676
- import { statSync as statSync2 } from "fs";
2677
- import { join as join3 } from "path";
3460
+ import { statSync as statSync3 } from "fs";
3461
+ import { join as join4 } from "path";
2678
3462
  var LARGE_DB_THRESHOLD_BYTES = 268435456;
2679
3463
  function statSessionDbBytes(homeDir) {
2680
- const dbPath = join3(homeDir, ".local", "share", "opencode", "opencode.db");
3464
+ const dbPath = join4(homeDir, ".local", "share", "opencode", "opencode.db");
2681
3465
  try {
2682
- return statSync2(dbPath).size;
3466
+ return statSync3(dbPath).size;
2683
3467
  } catch (err) {
2684
3468
  const isMissingFile = err instanceof Error && "code" in err && err.code === "ENOENT";
2685
3469
  if (!isMissingFile) {
@@ -2705,11 +3489,11 @@ function buildSessionStoreSizeWarning(input) {
2705
3489
  }
2706
3490
 
2707
3491
  // src/lib/opencode/session-db-reclaim.ts
2708
- import { statSync as statSync3, statfsSync } from "fs";
2709
- import { dirname as dirname2 } from "path";
3492
+ import { statSync as statSync4, statfsSync } from "fs";
3493
+ import { dirname as dirname4 } from "path";
2710
3494
  function insufficientSpaceReason(dbPath, requiredBytes) {
2711
3495
  try {
2712
- const fsStats = statfsSync(dirname2(dbPath));
3496
+ const fsStats = statfsSync(dirname4(dbPath));
2713
3497
  const availableBytes = fsStats.bavail * fsStats.bsize;
2714
3498
  if (availableBytes < requiredBytes) {
2715
3499
  return `only ${availableBytes} bytes free, need ${requiredBytes} for a second copy`;
@@ -2778,7 +3562,7 @@ async function reclaimSessionDbSpace(input) {
2778
3562
  );
2779
3563
  return { ok: false, skipped: "full-vacuum-blocked" };
2780
3564
  }
2781
- const fileBytesForGuard = statSync3(dbPath).size;
3565
+ const fileBytesForGuard = statSync4(dbPath).size;
2782
3566
  const skipReason = insufficientSpaceReason(dbPath, fileBytesForGuard);
2783
3567
  if (skipReason !== null) {
2784
3568
  console.warn(
@@ -2906,12 +3690,12 @@ var StreamForwarder = class {
2906
3690
  let endBody;
2907
3691
  if (has_body) {
2908
3692
  const chunks = [];
2909
- bodyPromise = new Promise((resolve3) => {
3693
+ bodyPromise = new Promise((resolve4) => {
2910
3694
  pushBody = (buf) => {
2911
3695
  chunks.push(buf);
2912
3696
  };
2913
3697
  endBody = () => {
2914
- resolve3(Buffer.concat(chunks));
3698
+ resolve4(Buffer.concat(chunks));
2915
3699
  };
2916
3700
  });
2917
3701
  }
@@ -3040,7 +3824,7 @@ function connectTunnel(options) {
3040
3824
  } = options;
3041
3825
  const tunnelUrl = getTunnelUrlConfig();
3042
3826
  const url = `${tunnelUrl}/tunnel/${agentId}/connect`;
3043
- return new Promise((resolve3, reject) => {
3827
+ return new Promise((resolve4, reject) => {
3044
3828
  const ws = new WebSocket2(url, {
3045
3829
  headers: {
3046
3830
  Authorization: authHeader
@@ -3091,8 +3875,8 @@ function connectTunnel(options) {
3091
3875
  try {
3092
3876
  message = JSON.parse(data.toString());
3093
3877
  } catch (error2) {
3094
- const errorMessage = error2 instanceof Error ? error2.message : "Unknown error";
3095
- onError?.(`Failed to handle message: ${errorMessage}`);
3878
+ const errorMessage2 = error2 instanceof Error ? error2.message : "Unknown error";
3879
+ onError?.(`Failed to handle message: ${errorMessage2}`);
3096
3880
  return;
3097
3881
  }
3098
3882
  if (isStreamFrame(message)) {
@@ -3104,7 +3888,7 @@ function connectTunnel(options) {
3104
3888
  clearTimeout(connectionTimeout);
3105
3889
  const connectedAgentId = message.agent_id ?? agentId;
3106
3890
  onConnected?.(connectedAgentId);
3107
- resolve3({
3891
+ resolve4({
3108
3892
  ws,
3109
3893
  close: () => ws.close(1e3, "CLI shutdown")
3110
3894
  });
@@ -3235,10 +4019,10 @@ var RunnerConnection = class {
3235
4019
  };
3236
4020
 
3237
4021
  // src/lib/tunnel/ready-marker.ts
3238
- import { writeFileSync } from "fs";
4022
+ import { writeFileSync as writeFileSync3 } from "fs";
3239
4023
  function writeTunnelReadyMarker(path, agentId) {
3240
4024
  try {
3241
- writeFileSync(path, `${agentId}
4025
+ writeFileSync3(path, `${agentId}
3242
4026
  `);
3243
4027
  return { ok: true };
3244
4028
  } catch (error2) {
@@ -3246,10 +4030,52 @@ function writeTunnelReadyMarker(path, agentId) {
3246
4030
  }
3247
4031
  }
3248
4032
 
4033
+ // src/lib/replication.ts
4034
+ import { spawn as spawn4 } from "child_process";
4035
+ function startSessionDbReplication(configPath) {
4036
+ return spawn4("litestream", ["replicate", "-config", configPath], {
4037
+ stdio: "inherit"
4038
+ });
4039
+ }
4040
+ async function stopSessionDbReplication(child, timeoutMs) {
4041
+ return stopProcessAndWait(
4042
+ child,
4043
+ timeoutMs,
4044
+ () => child.kill("SIGTERM"),
4045
+ () => child.kill("SIGKILL")
4046
+ );
4047
+ }
4048
+
4049
+ // src/lib/process-liveness.ts
4050
+ import { readFileSync as readFileSync4 } from "fs";
4051
+ function isProcessAlive(pid) {
4052
+ try {
4053
+ process.kill(pid, 0);
4054
+ } catch (error2) {
4055
+ const code = error2.code;
4056
+ if (code === "ESRCH") return false;
4057
+ if (code === "EPERM") return true;
4058
+ console.error(
4059
+ `[process-liveness] could not probe process ${pid}: ${error2 instanceof Error ? error2.message : String(error2)}`
4060
+ );
4061
+ return false;
4062
+ }
4063
+ if (process.platform !== "linux") return true;
4064
+ try {
4065
+ const status2 = readFileSync4(`/proc/${pid}/status`, "utf8");
4066
+ return !/^State:\s+Z(?:\s|$)/m.test(status2);
4067
+ } catch (error2) {
4068
+ console.error(
4069
+ `[process-liveness] could not inspect /proc/${pid}/status: ${error2 instanceof Error ? error2.message : String(error2)}`
4070
+ );
4071
+ return true;
4072
+ }
4073
+ }
4074
+
3249
4075
  // 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";
4076
+ import { readFileSync as readFileSync5 } from "fs";
4077
+ import { homedir as homedir3 } from "os";
4078
+ import { join as join5 } from "path";
3253
4079
  var CODEX_RESPONSES_URL = "https://chatgpt.com/backend-api/codex/responses";
3254
4080
  var OPENCODE_AUTH_SEGMENTS = [".local", "share", "opencode", "auth.json"];
3255
4081
  var OpenAiUsageError = class extends Error {
@@ -3263,7 +4089,7 @@ function isLocalCredentialProblem2(err) {
3263
4089
  }
3264
4090
  function readOpenCodeChatGptCredentials() {
3265
4091
  try {
3266
- const raw = readFileSync3(join4(homedir2(), ...OPENCODE_AUTH_SEGMENTS), "utf-8");
4092
+ const raw = readFileSync5(join5(homedir3(), ...OPENCODE_AUTH_SEGMENTS), "utf-8");
3267
4093
  let parsed;
3268
4094
  try {
3269
4095
  parsed = JSON.parse(raw);
@@ -3285,6 +4111,23 @@ function readOpenCodeChatGptCredentials() {
3285
4111
  return null;
3286
4112
  }
3287
4113
  }
4114
+ function parseChatGptIdentity(accessToken) {
4115
+ const segments = accessToken.split(".");
4116
+ if (segments.length !== 3) return null;
4117
+ let payload;
4118
+ try {
4119
+ const parsed = JSON.parse(Buffer.from(segments[1], "base64url").toString("utf8"));
4120
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return null;
4121
+ payload = parsed;
4122
+ } catch {
4123
+ return null;
4124
+ }
4125
+ const profile = payload["https://api.openai.com/profile"];
4126
+ const auth = payload["https://api.openai.com/auth"];
4127
+ const ownerEmail = typeof profile?.email === "string" ? profile.email.trim() || null : null;
4128
+ const planType = typeof auth?.chatgpt_plan_type === "string" ? auth.chatgpt_plan_type.trim() || null : null;
4129
+ return ownerEmail === null && planType === null ? null : { ownerEmail, planType };
4130
+ }
3288
4131
  function toWindow2(headers, name) {
3289
4132
  const utilizationHeader = headers.get(`x-codex-${name}-used-percent`);
3290
4133
  const windowMinutesHeader = headers.get(`x-codex-${name}-window-minutes`);
@@ -3360,6 +4203,7 @@ async function getOpenAiUsage(port) {
3360
4203
  "credentials_expired"
3361
4204
  );
3362
4205
  }
4206
+ const subscription = parseChatGptIdentity(credentials2.accessToken);
3363
4207
  const models = await resolveProbeModels(port);
3364
4208
  if (models.length === 0) {
3365
4209
  throw new OpenAiUsageError("No supported OpenAI probe model is available.", "no_probe_model");
@@ -3392,7 +4236,7 @@ async function getOpenAiUsage(port) {
3392
4236
  "no_usable_window"
3393
4237
  );
3394
4238
  }
3395
- return usage;
4239
+ return { ...usage, subscription };
3396
4240
  }
3397
4241
  if (res.status === 401) {
3398
4242
  throw new OpenAiUsageError(
@@ -3636,15 +4480,15 @@ function createResourceUsageCollector(homeDir) {
3636
4480
  }
3637
4481
 
3638
4482
  // src/lib/channels/driver.ts
3639
- import { homedir as homedir3 } from "os";
4483
+ import { homedir as homedir4 } from "os";
3640
4484
 
3641
4485
  // src/lib/runner-file-sync.ts
3642
- import { join as join6 } from "path";
4486
+ import { join as join7 } from "path";
3643
4487
 
3644
4488
  // src/lib/file-push.ts
3645
4489
  import { randomUUID } from "crypto";
3646
4490
  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";
4491
+ import { basename, dirname as dirname5, isAbsolute, join as join6, relative, resolve as resolve2, sep } from "path";
3648
4492
  var FILE_MODE = 384;
3649
4493
  var DIRECTORY_MODE = 448;
3650
4494
  async function writePushedFile(request) {
@@ -3675,9 +4519,9 @@ async function writePushedFile(request) {
3675
4519
  }
3676
4520
  try {
3677
4521
  const { existingAncestor, missingSegments } = await resolveNearestExistingAncestor(
3678
- dirname3(candidate)
4522
+ dirname5(candidate)
3679
4523
  );
3680
- const realTarget = join5(existingAncestor, ...missingSegments, basename(candidate));
4524
+ const realTarget = join6(existingAncestor, ...missingSegments, basename(candidate));
3681
4525
  const allowedDirectory = await findContainingAllowedDirectory(allowedDirectories, realTarget);
3682
4526
  if (allowedDirectory === null) {
3683
4527
  return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
@@ -3687,8 +4531,8 @@ async function writePushedFile(request) {
3687
4531
  }
3688
4532
  if (missingSegments.length > 0) {
3689
4533
  await createMissingDirectories(existingAncestor, missingSegments);
3690
- const realParent = await realpath(dirname3(realTarget));
3691
- if (realParent !== dirname3(realTarget) || !contains(allowedDirectory, realTarget)) {
4534
+ const realParent = await realpath(dirname5(realTarget));
4535
+ if (realParent !== dirname5(realTarget) || !contains(allowedDirectory, realTarget)) {
3692
4536
  return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
3693
4537
  path: realTarget,
3694
4538
  bytes,
@@ -3713,7 +4557,7 @@ function expandAndValidate(requestedPath, homeDir) {
3713
4557
  if (requestedPath.trim() === "" || requestedPath.includes("\0")) {
3714
4558
  return null;
3715
4559
  }
3716
- const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join5(homeDir, requestedPath.slice(2)) : requestedPath;
4560
+ const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join6(homeDir, requestedPath.slice(2)) : requestedPath;
3717
4561
  if (expanded.split(/[/\\]/).includes("..")) {
3718
4562
  return null;
3719
4563
  }
@@ -3731,7 +4575,7 @@ async function resolveNearestExistingAncestor(directory) {
3731
4575
  try {
3732
4576
  return { existingAncestor: await realpath(current), missingSegments };
3733
4577
  } catch (err) {
3734
- const parent = dirname3(current);
4578
+ const parent = dirname5(current);
3735
4579
  if (err.code !== "ENOENT" || parent === current) {
3736
4580
  throw err;
3737
4581
  }
@@ -3786,13 +4630,13 @@ function contains(realDirectory, realTarget) {
3786
4630
  async function createMissingDirectories(existingAncestor, missingSegments) {
3787
4631
  let current = existingAncestor;
3788
4632
  for (const segment of missingSegments) {
3789
- current = join5(current, segment);
4633
+ current = join6(current, segment);
3790
4634
  await mkdir(current, { recursive: true, mode: DIRECTORY_MODE });
3791
4635
  await chmod(current, DIRECTORY_MODE);
3792
4636
  }
3793
4637
  }
3794
4638
  async function writeAtomically(realTarget, content) {
3795
- const temporaryPath = join5(dirname3(realTarget), `.evident-push-${randomUUID()}.tmp`);
4639
+ const temporaryPath = join6(dirname5(realTarget), `.evident-push-${randomUUID()}.tmp`);
3796
4640
  let handle;
3797
4641
  try {
3798
4642
  handle = await open2(temporaryPath, "wx", FILE_MODE);
@@ -3922,12 +4766,12 @@ var NOT_APPLIED = {
3922
4766
  opencodeAuthApplied: false
3923
4767
  };
3924
4768
  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);
4769
+ const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join7(homeDir, requestedPath.slice(2)) : requestedPath;
4770
+ return expanded === join7(homeDir, ...CLAUDE_CREDENTIALS_SEGMENTS);
3927
4771
  }
3928
4772
  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);
4773
+ const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join7(homeDir, requestedPath.slice(2)) : requestedPath;
4774
+ return expanded === join7(homeDir, ...OPENCODE_AUTH_SEGMENTS);
3931
4775
  }
3932
4776
  async function applyOne(options, file) {
3933
4777
  const label = `${file.id.slice(0, 8)} (${file.path})`;
@@ -4454,6 +5298,7 @@ var ChannelDriver = class _ChannelDriver {
4454
5298
  * and stops opencode.
4455
5299
  */
4456
5300
  stopped = false;
5301
+ recycleRequestedFlag = false;
4457
5302
  constructor(config) {
4458
5303
  this.agentId = config.agentId;
4459
5304
  this.port = config.port;
@@ -4473,7 +5318,7 @@ var ChannelDriver = class _ChannelDriver {
4473
5318
  this.stuckQueuedMs = config.stuckQueuedMs ?? DEFAULT_STUCK_QUEUED_MS;
4474
5319
  this.now = config.now ?? (() => Date.now());
4475
5320
  this.fileSyncDirectories = config.fileSyncDirectories ?? [];
4476
- this.homeDir = config.homeDir ?? homedir3();
5321
+ this.homeDir = config.homeDir ?? homedir4();
4477
5322
  this.maxActiveSessions = config.maxActiveSessions;
4478
5323
  this.watcherStallMs = config.watcherStallMs ?? WATCHER_STALL_MS;
4479
5324
  this.wedgeWarningIntervalMs = config.wedgeWarningIntervalMs ?? WEDGE_WARNING_INTERVAL_MS;
@@ -4559,6 +5404,9 @@ var ChannelDriver = class _ChannelDriver {
4559
5404
  let dispatched = 0;
4560
5405
  try {
4561
5406
  const conversations = await this.getPendingConversations();
5407
+ if (this.recycleRequestedFlag) {
5408
+ this.stop();
5409
+ }
4562
5410
  if (conversations.length > 0) {
4563
5411
  const total = conversations.reduce((sum, c) => sum + (c.pending_message_count ?? 0), 0);
4564
5412
  this.log({
@@ -4687,6 +5535,14 @@ var ChannelDriver = class _ChannelDriver {
4687
5535
  stop() {
4688
5536
  this.stopped = true;
4689
5537
  }
5538
+ /**
5539
+ * The server clears this request when a new MicroVM identity is recorded, so a
5540
+ * same-VM tunnel reconnect does not consume it. This is a plain read rather
5541
+ * than a consume; `run.ts` guards the action once-only.
5542
+ */
5543
+ get recycleRequested() {
5544
+ return this.recycleRequestedFlag;
5545
+ }
4690
5546
  /**
4691
5547
  * Wait (up to `timeoutMs`) for in-flight watcher work to settle during a
4692
5548
  * graceful shutdown, so a turn whose reply is ready — or completes within the
@@ -4824,7 +5680,7 @@ var ChannelDriver = class _ChannelDriver {
4824
5680
  this.signalDispatchNotStarted(conv, message, "session_existence_unknown");
4825
5681
  break;
4826
5682
  }
4827
- const errorMessage = err instanceof Error ? err.message : String(err);
5683
+ const errorMessage2 = err instanceof Error ? err.message : String(err);
4828
5684
  this.sessions.delete(conv.id);
4829
5685
  this.supersede(conv.id, sessionId);
4830
5686
  this.log({
@@ -4833,7 +5689,7 @@ var ChannelDriver = class _ChannelDriver {
4833
5689
  conversation_id: conv.id,
4834
5690
  message_id: message.id
4835
5691
  });
4836
- await this.markFailed(conv.id, message.id, null, errorMessage).catch((markErr) => {
5692
+ await this.markFailed(conv.id, message.id, null, errorMessage2).catch((markErr) => {
4837
5693
  this.log({
4838
5694
  level: "warn",
4839
5695
  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 +5700,7 @@ var ChannelDriver = class _ChannelDriver {
4844
5700
  });
4845
5701
  this.log({
4846
5702
  level: "error",
4847
- message: `Message ${message.id.slice(0, 8)} dispatch failed: ${errorMessage}`,
5703
+ message: `Message ${message.id.slice(0, 8)} dispatch failed: ${errorMessage2}`,
4848
5704
  conversation_id: conv.id,
4849
5705
  message_id: message.id
4850
5706
  });
@@ -4865,14 +5721,14 @@ var ChannelDriver = class _ChannelDriver {
4865
5721
  this.unconfirmedDispatchFailures.delete(message.id);
4866
5722
  this.sessions.delete(conv.id);
4867
5723
  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.`;
5724
+ 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
5725
  this.log({
4870
5726
  level: "error",
4871
- message: errorMessage,
5727
+ message: errorMessage2,
4872
5728
  conversation_id: conv.id,
4873
5729
  message_id: message.id
4874
5730
  });
4875
- await this.markFailed(conv.id, message.id, null, errorMessage).catch((markErr) => {
5731
+ await this.markFailed(conv.id, message.id, null, errorMessage2).catch((markErr) => {
4876
5732
  this.log({
4877
5733
  level: "warn",
4878
5734
  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)}`,
@@ -6836,14 +7692,14 @@ var ChannelDriver = class _ChannelDriver {
6836
7692
  this.unconfirmedDispatchFailures.delete(row.id);
6837
7693
  this.sessions.delete(readoptConv.id);
6838
7694
  this.supersede(readoptConv.id, sessionId);
6839
- 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.`;
7695
+ 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.`;
6840
7696
  this.log({
6841
7697
  level: "error",
6842
- message: errorMessage,
7698
+ message: errorMessage2,
6843
7699
  conversation_id: row.conversation_id,
6844
7700
  message_id: row.id
6845
7701
  });
6846
- await this.markFailed(row.conversation_id, row.id, null, errorMessage).catch((markErr) => {
7702
+ await this.markFailed(row.conversation_id, row.id, null, errorMessage2).catch((markErr) => {
6847
7703
  this.log({
6848
7704
  level: "warn",
6849
7705
  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)}`,
@@ -7458,6 +8314,7 @@ var ChannelDriver = class _ChannelDriver {
7458
8314
  throw new Error(`Failed to get pending conversations: HTTP ${res.status}`);
7459
8315
  }
7460
8316
  const data = await res.json();
8317
+ this.recycleRequestedFlag = data.recycle_requested === true;
7461
8318
  let conversations = data.conversations;
7462
8319
  if (this.conversationFilter) {
7463
8320
  conversations = conversations.filter((c) => c.id === this.conversationFilter);
@@ -7894,7 +8751,7 @@ async function ensureOpenCodeRunning(ctx) {
7894
8751
  }
7895
8752
  if (!ctx.interactive) {
7896
8753
  ctx.log(`OpenCode is not running on port ${ctx.port}. Starting it automatically...`);
7897
- const proc = await startOpenCode(ctx.port);
8754
+ const proc = await startOpenCode(ctx.port, { inheritStdio: ctx.inheritStdio });
7898
8755
  const health = await waitForOpenCodeHealth(ctx.port, ctx.startTimeoutMs);
7899
8756
  if (!health.healthy) {
7900
8757
  return {
@@ -7962,7 +8819,7 @@ Port ${port} is already in use.`));
7962
8819
  }
7963
8820
  if (action === "start") {
7964
8821
  const spinner = ora2("Starting OpenCode...").start();
7965
- const proc = await startOpenCode(port);
8822
+ const proc = await startOpenCode(port, { inheritStdio: ctx.inheritStdio });
7966
8823
  const health = await waitForOpenCodeHealth(port, INTERACTIVE_START_TIMEOUT_MS);
7967
8824
  if (!health.healthy) {
7968
8825
  spinner.fail("Failed to start OpenCode");
@@ -7974,12 +8831,558 @@ Port ${port} is already in use.`));
7974
8831
  return { port, process: null, version: null, notReadyReason: "you chose to continue without it" };
7975
8832
  }
7976
8833
 
8834
+ // src/lib/runner-credentials.ts
8835
+ import { chmodSync as chmodSync2, writeFileSync as writeFileSync4 } from "fs";
8836
+ import { spawn as spawn5 } from "child_process";
8837
+ var RUNNER_SECRET_FETCH_TIMEOUT_MS = 6e4;
8838
+ var CREDENTIAL_RESTORE_TIMEOUT_MS = 6e4;
8839
+ var GITHUB_PROBE_TIMEOUT_MS = 1e4;
8840
+ var GIT_CONFIG_GLOBAL = "/tmp/gitconfig";
8841
+ var GIT_CREDENTIAL_HELPER = "/tmp/git-credential-helper.sh";
8842
+ function commandError2(result) {
8843
+ return result.stderr.trim() || `process exited with code ${result.code ?? "null"}`;
8844
+ }
8845
+ var runCommand2 = (command, args, opts) => {
8846
+ return new Promise((resolve4) => {
8847
+ let child;
8848
+ let stdout = "";
8849
+ let stderr = "";
8850
+ let settled = false;
8851
+ const timer = {};
8852
+ const finish = (result) => {
8853
+ if (settled) return;
8854
+ settled = true;
8855
+ if (timer.handle) clearTimeout(timer.handle);
8856
+ resolve4(result);
8857
+ };
8858
+ try {
8859
+ child = spawn5(command, args, { env: opts.env, stdio: ["ignore", "pipe", "pipe"] });
8860
+ } catch (error2) {
8861
+ finish({
8862
+ code: null,
8863
+ stdout,
8864
+ stderr: error2 instanceof Error ? error2.message : String(error2),
8865
+ timedOut: false
8866
+ });
8867
+ return;
8868
+ }
8869
+ child.stdout?.setEncoding("utf8");
8870
+ child.stdout?.on("data", (chunk) => {
8871
+ stdout += chunk;
8872
+ });
8873
+ child.stderr?.setEncoding("utf8");
8874
+ child.stderr?.on("data", (chunk) => {
8875
+ stderr += chunk;
8876
+ });
8877
+ child.once("error", (error2) => {
8878
+ finish({
8879
+ code: null,
8880
+ stdout,
8881
+ stderr: stderr === "" ? error2.message : `${stderr}
8882
+ ${error2.message}`,
8883
+ timedOut: false
8884
+ });
8885
+ });
8886
+ child.once("close", (code) => finish({ code, stdout, stderr, timedOut: false }));
8887
+ timer.handle = setTimeout(
8888
+ () => {
8889
+ child.kill("SIGKILL");
8890
+ finish({ code: null, stdout, stderr, timedOut: true });
8891
+ },
8892
+ Math.max(0, opts.timeoutMs)
8893
+ );
8894
+ });
8895
+ };
8896
+ function isEnvironmentObject(value) {
8897
+ return typeof value === "object" && value !== null && !Array.isArray(value);
8898
+ }
8899
+ function secretFailure(marker, detail, log3) {
8900
+ const message = `${marker}: ${detail}`;
8901
+ log3(message, "error");
8902
+ return new Error(message);
8903
+ }
8904
+ async function installRunnerSecret({
8905
+ env,
8906
+ log: log3,
8907
+ commandRunner
8908
+ }) {
8909
+ const arn = env.RUNNER_SECRET_ARN?.trim();
8910
+ if (!arn) {
8911
+ log3("runner secret is not configured; continuing without GitHub and MCP credentials");
8912
+ return false;
8913
+ }
8914
+ const result = await (commandRunner ?? runCommand2)(
8915
+ "aws",
8916
+ [
8917
+ "secretsmanager",
8918
+ "get-secret-value",
8919
+ "--secret-id",
8920
+ arn,
8921
+ "--query",
8922
+ "SecretString",
8923
+ "--output",
8924
+ "text"
8925
+ ],
8926
+ { env, timeoutMs: RUNNER_SECRET_FETCH_TIMEOUT_MS }
8927
+ );
8928
+ if (result.timedOut) {
8929
+ throw secretFailure(
8930
+ "CREDENTIAL-RESTORE-TIMEOUT",
8931
+ `runner-secret did not finish within ${RUNNER_SECRET_FETCH_TIMEOUT_MS}ms`,
8932
+ log3
8933
+ );
8934
+ }
8935
+ if (result.code !== 0) {
8936
+ throw secretFailure("RUNNER-SECRET-UNREADABLE", commandError2(result), log3);
8937
+ }
8938
+ let payload;
8939
+ try {
8940
+ payload = JSON.parse(result.stdout);
8941
+ } catch (error2) {
8942
+ log3(
8943
+ `RUNNER-SECRET-UNPARSEABLE: secret value is not a JSON object (${error2 instanceof Error ? error2.message : String(error2)})`,
8944
+ "warn"
8945
+ );
8946
+ return false;
8947
+ }
8948
+ if (!isEnvironmentObject(payload)) {
8949
+ log3("RUNNER-SECRET-UNPARSEABLE: secret value is not a JSON object", "warn");
8950
+ return false;
8951
+ }
8952
+ let populated = 0;
8953
+ let skipped = 0;
8954
+ let githubTokenPopulated = false;
8955
+ for (const [key, value] of Object.entries(payload)) {
8956
+ if (typeof value !== "string" || value.length === 0) continue;
8957
+ if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key)) {
8958
+ log3(
8959
+ `RUNNER-SECRET-KEY-SKIPPED: ${JSON.stringify(key)} is not a valid environment variable name`,
8960
+ "warn"
8961
+ );
8962
+ skipped += 1;
8963
+ continue;
8964
+ }
8965
+ env[key] = value;
8966
+ populated += 1;
8967
+ if (key === "GH_TOKEN") githubTokenPopulated = true;
8968
+ }
8969
+ if (populated === 0) {
8970
+ log3(
8971
+ "RUNNER-SECRET-UNPOPULATED: populate the runner secret as documented in infrastructure/evident-runner/MICROVM.md",
8972
+ "warn"
8973
+ );
8974
+ } else {
8975
+ log3(
8976
+ `RUNNER-SECRET-OK: exported ${populated} secret values; skipped ${skipped} invalid environment variable names`
8977
+ );
8978
+ }
8979
+ return githubTokenPopulated;
8980
+ }
8981
+ function restoreFailure(operation, result, log3) {
8982
+ const message = `CREDENTIAL-RESTORE-FAILED: ${operation} failed: ${commandError2(result)}`;
8983
+ log3(message, "error");
8984
+ return new Error(message);
8985
+ }
8986
+ async function runCredentialRestore(args, operation, log3, synchroniserRunner) {
8987
+ const result = await synchroniserRunner(args, { timeoutMs: CREDENTIAL_RESTORE_TIMEOUT_MS });
8988
+ if (result.timedOut) {
8989
+ log3(
8990
+ `CREDENTIAL-RESTORE-TIMEOUT: ${operation} did not finish within ${CREDENTIAL_RESTORE_TIMEOUT_MS}ms; continuing without it`,
8991
+ "warn"
8992
+ );
8993
+ return result;
8994
+ }
8995
+ if (result.code !== 0) throw restoreFailure(operation, result, log3);
8996
+ return result;
8997
+ }
8998
+ async function restoreCredentialStores({
8999
+ env,
9000
+ log: log3,
9001
+ synchroniserRunner = runSynchroniser
9002
+ }) {
9003
+ await runCredentialRestore(["restore", "claude"], "restore-claude", log3, synchroniserRunner);
9004
+ await runCredentialRestore(["restore", "opencode"], "restore-opencode", log3, synchroniserRunner);
9005
+ const result = await synchroniserRunner(["model-auth-ready"], {
9006
+ timeoutMs: CREDENTIAL_RESTORE_TIMEOUT_MS
9007
+ });
9008
+ if (result.timedOut) {
9009
+ log3(
9010
+ `CREDENTIAL-RESTORE-TIMEOUT: model-auth-ready did not finish within ${CREDENTIAL_RESTORE_TIMEOUT_MS}ms; continuing without it`,
9011
+ "warn"
9012
+ );
9013
+ return;
9014
+ }
9015
+ switch (result.code) {
9016
+ case 0:
9017
+ return;
9018
+ case 10:
9019
+ log3(
9020
+ `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.`,
9021
+ "warn"
9022
+ );
9023
+ return;
9024
+ default:
9025
+ log3("could not determine whether this VM has model credentials", "warn");
9026
+ }
9027
+ }
9028
+ var GIT_CREDENTIAL_HELPER_CONTENT = [
9029
+ "#!/usr/bin/env bash",
9030
+ '[ "$1" = get ] || exit 0',
9031
+ "echo username=x-access-token",
9032
+ 'echo "password=${GH_TOKEN}"',
9033
+ ""
9034
+ ].join("\n");
9035
+ async function probeGitHubAccess({ env, log: log3 }) {
9036
+ const auth = await runCommand2("gh", ["api", "user", "--jq", ".login"], {
9037
+ env,
9038
+ timeoutMs: GITHUB_PROBE_TIMEOUT_MS
9039
+ });
9040
+ if (auth.timedOut) {
9041
+ log3(`GITHUB-PROBE-TIMEOUT: auth probe exceeded ${GITHUB_PROBE_TIMEOUT_MS}ms`, "warn");
9042
+ return;
9043
+ }
9044
+ if (auth.code !== 0) {
9045
+ log3(`GITHUB-AUTH-REJECTED: ${commandError2(auth)}`, "warn");
9046
+ return;
9047
+ }
9048
+ log3(`GITHUB-AUTH-OK: ${auth.stdout.trim()}`, "debug");
9049
+ const remote = await runCommand2("git", ["-C", process.cwd(), "remote", "get-url", "origin"], {
9050
+ env,
9051
+ timeoutMs: GITHUB_PROBE_TIMEOUT_MS
9052
+ });
9053
+ if (remote.code !== 0 || remote.timedOut) return;
9054
+ const repo = remote.stdout.trim().replace(/^(?:https:\/\/github\.com\/|git@github\.com:)/, "").replace(/\.git$/, "");
9055
+ if (!repo) return;
9056
+ const repository = await runCommand2("gh", ["api", `repos/${repo}`, "--jq", ".full_name"], {
9057
+ env,
9058
+ timeoutMs: GITHUB_PROBE_TIMEOUT_MS
9059
+ });
9060
+ if (repository.timedOut) {
9061
+ log3(
9062
+ `GITHUB-PROBE-TIMEOUT: repository probe for ${repo} exceeded ${GITHUB_PROBE_TIMEOUT_MS}ms`,
9063
+ "warn"
9064
+ );
9065
+ } else if (repository.code !== 0) {
9066
+ log3(`GITHUB-REPO-INACCESSIBLE: ${repo}: ${commandError2(repository)}`, "warn");
9067
+ }
9068
+ }
9069
+ async function configureGitHubAccess({ env, log: log3 }) {
9070
+ if (!env.GH_TOKEN) {
9071
+ log3("GITHUB-CREDENTIALS-MISSING: GH_TOKEN is unavailable; see RUNNER-SECRET-* above", "warn");
9072
+ return;
9073
+ }
9074
+ try {
9075
+ env.GIT_CONFIG_GLOBAL = GIT_CONFIG_GLOBAL;
9076
+ writeFileSync4(GIT_CONFIG_GLOBAL, "");
9077
+ writeFileSync4(GIT_CREDENTIAL_HELPER, GIT_CREDENTIAL_HELPER_CONTENT, { mode: 448 });
9078
+ chmodSync2(GIT_CREDENTIAL_HELPER, 448);
9079
+ const config = [
9080
+ ["user.name", env.GIT_USER_NAME ?? "evident-bot"],
9081
+ ["user.email", env.GIT_USER_EMAIL ?? "evident-bot@users.noreply.github.com"],
9082
+ ["init.defaultBranch", "main"],
9083
+ ["credential.https://github.com.helper", GIT_CREDENTIAL_HELPER]
9084
+ ];
9085
+ for (const [key, value] of config) {
9086
+ const result = await runCommand2("git", ["config", "--global", key, value], {
9087
+ env,
9088
+ timeoutMs: GITHUB_PROBE_TIMEOUT_MS
9089
+ });
9090
+ if (result.timedOut || result.code !== 0) throw new Error(commandError2(result));
9091
+ }
9092
+ } catch (error2) {
9093
+ log3(
9094
+ `GITHUB-SETUP-FAILED: could not configure local git credentials; continuing without GitHub access (${error2 instanceof Error ? error2.message : String(error2)})`,
9095
+ "warn"
9096
+ );
9097
+ return;
9098
+ }
9099
+ void probeGitHubAccess({ env, log: log3 }).catch((error2) => {
9100
+ log3(
9101
+ `GITHUB-SETUP-FAILED: GitHub access probe failed: ${error2 instanceof Error ? error2.message : String(error2)}`,
9102
+ "warn"
9103
+ );
9104
+ });
9105
+ }
9106
+
9107
+ // src/lib/opencode/config-overlay.ts
9108
+ import { execFileSync as execFileSync2 } from "child_process";
9109
+ import { copyFileSync, existsSync as existsSync2, statSync as statSync5 } from "fs";
9110
+ import { isAbsolute as isAbsolute2, join as join8, resolve as resolve3 } from "path";
9111
+ function isFile(filePath) {
9112
+ return existsSync2(filePath) && statSync5(filePath).isFile();
9113
+ }
9114
+ function applyRunnerOpenCodeConfig({
9115
+ overlayPath,
9116
+ cwd = process.cwd(),
9117
+ log: log3
9118
+ }) {
9119
+ if (!overlayPath) {
9120
+ log3("runner OpenCode config is not configured; using the baked project config", "debug");
9121
+ return;
9122
+ }
9123
+ const source = isAbsolute2(overlayPath) ? overlayPath : resolve3(cwd, overlayPath);
9124
+ const target = isFile(join8(cwd, "opencode.jsonc")) ? "opencode.jsonc" : "opencode.json";
9125
+ if (!isFile(source)) {
9126
+ log3(
9127
+ `RUNNER-OPENCODE-CONFIG-MISSING: ${source} is not a file; headless turns will wedge on the first external-directory permission prompt (#563)`,
9128
+ "error"
9129
+ );
9130
+ return;
9131
+ }
9132
+ copyFileSync(source, join8(cwd, target));
9133
+ try {
9134
+ execFileSync2("git", ["-C", cwd, "update-index", "--skip-worktree", target], {
9135
+ stdio: "ignore"
9136
+ });
9137
+ } catch (error2) {
9138
+ const detail = error2 instanceof Error ? error2.message : String(error2);
9139
+ log3(`could not mark ${target} skip-worktree: ${detail}; it may show as a local change`, "warn");
9140
+ }
9141
+ log3(`Applied runner OpenCode config ${source} to ${join8(cwd, target)}`);
9142
+ }
9143
+
9144
+ // src/lib/credential-sync.ts
9145
+ import { renameSync, writeFileSync as writeFileSync5 } from "fs";
9146
+ var CREDENTIAL_SYNC_TICK_TIMEOUT_MS = 3e4;
9147
+ var CREDENTIAL_FLUSH_DEADLINE_MS = 8e3;
9148
+ var CREDENTIAL_FLUSH_ABORT_GRACE_MS = 500;
9149
+ var DEFAULT_CREDENTIAL_SYNC_INTERVAL_SECONDS = 60;
9150
+ var STORES = ["claude", "opencode"];
9151
+ var MAX_FLUSH_PASSES = 2;
9152
+ function outcomesWith(outcome) {
9153
+ return { claude: outcome, opencode: outcome };
9154
+ }
9155
+ function errorMessage(error2) {
9156
+ return error2 instanceof Error ? error2.message : String(error2);
9157
+ }
9158
+ function waitForSettlement(promise, timeoutMs) {
9159
+ return new Promise((resolve4) => {
9160
+ let settled = false;
9161
+ const timer = setTimeout(() => finish(false), Math.max(0, timeoutMs));
9162
+ const finish = (value) => {
9163
+ if (settled) return;
9164
+ settled = true;
9165
+ clearTimeout(timer);
9166
+ resolve4(value);
9167
+ };
9168
+ promise.then(
9169
+ () => finish(true),
9170
+ () => finish(true)
9171
+ );
9172
+ });
9173
+ }
9174
+ function writeMarker(markerPath, outcomes, log3) {
9175
+ const body = `${STORES.map((store) => `${store}=${outcomes[store]}`).join("\n")}
9176
+ `;
9177
+ const temporaryPath = `${markerPath}.tmp`;
9178
+ try {
9179
+ writeFileSync5(temporaryPath, body, { mode: 384 });
9180
+ renameSync(temporaryPath, markerPath);
9181
+ } catch (error2) {
9182
+ log3(`CREDENTIAL-FLUSH-MARKER-UNWRITABLE: ${markerPath}: ${errorMessage(error2)}`, "warn");
9183
+ }
9184
+ }
9185
+ function intervalSeconds(env, log3) {
9186
+ const raw = env.CREDS_SYNC_INTERVAL;
9187
+ if (raw === void 0 || /^[1-9][0-9]*$/.test(raw) && Number.isSafeInteger(Number(raw))) {
9188
+ return raw === void 0 ? DEFAULT_CREDENTIAL_SYNC_INTERVAL_SECONDS : Number(raw);
9189
+ }
9190
+ log3(
9191
+ `CREDENTIAL-SYNC-INTERVAL-INVALID: CREDS_SYNC_INTERVAL='${raw}' is not a positive integer; using ${DEFAULT_CREDENTIAL_SYNC_INTERVAL_SECONDS}s`,
9192
+ "warn"
9193
+ );
9194
+ return DEFAULT_CREDENTIAL_SYNC_INTERVAL_SECONDS;
9195
+ }
9196
+ async function runFlushStore(store, env, synchroniserRunner, log3, deadlineAt) {
9197
+ const remainingMs = deadlineAt - Date.now();
9198
+ if (remainingMs <= 0) return { outcome: "timeout", orphaned: false };
9199
+ const controller = new AbortController();
9200
+ let result;
9201
+ let failed = false;
9202
+ const completion = Promise.resolve().then(
9203
+ () => synchroniserRunner(["sync-once", store], {
9204
+ timeoutMs: remainingMs,
9205
+ env,
9206
+ signal: controller.signal
9207
+ })
9208
+ ).then(
9209
+ (value) => {
9210
+ result = value;
9211
+ },
9212
+ (error2) => {
9213
+ failed = true;
9214
+ log3(`CREDENTIAL-FLUSH-ERROR: ${store}: ${errorMessage(error2)}`, "warn");
9215
+ }
9216
+ );
9217
+ const abortTimer = setTimeout(() => controller.abort(), remainingMs);
9218
+ const settledBeforeDeadline = await waitForSettlement(completion, remainingMs);
9219
+ clearTimeout(abortTimer);
9220
+ if (!settledBeforeDeadline) {
9221
+ controller.abort();
9222
+ const settledAfterAbort = await waitForSettlement(completion, CREDENTIAL_FLUSH_ABORT_GRACE_MS);
9223
+ if (!settledAfterAbort) return { outcome: "timeout", orphaned: true };
9224
+ return { outcome: "timeout", orphaned: false };
9225
+ }
9226
+ if (failed || !result) return { outcome: "failed", orphaned: false };
9227
+ if (result.timedOut || Date.now() >= deadlineAt) {
9228
+ return { outcome: "timeout", orphaned: false };
9229
+ }
9230
+ return { outcome: result.code === 0 ? "ok" : "failed", orphaned: false };
9231
+ }
9232
+ function createCredentialSync({
9233
+ markerPath,
9234
+ env,
9235
+ log: log3,
9236
+ synchroniserRunner = runSynchroniser
9237
+ }) {
9238
+ const persistenceDisabled = !env.PERSISTENCE_BUCKET;
9239
+ let disabled = persistenceDisabled;
9240
+ let armed = false;
9241
+ let stopped = false;
9242
+ let timer;
9243
+ let inFlight;
9244
+ let activeTickAbort;
9245
+ let lastTickFailed;
9246
+ let flushPromise;
9247
+ const scheduleTick = (intervalMs, startTick2) => {
9248
+ if (stopped) return;
9249
+ timer = setTimeout(() => {
9250
+ timer = void 0;
9251
+ startTick2();
9252
+ }, intervalMs);
9253
+ };
9254
+ const startTick = (intervalMs) => {
9255
+ if (stopped) return;
9256
+ const controller = new AbortController();
9257
+ activeTickAbort = controller;
9258
+ const tick = (async () => {
9259
+ const outcomes = {
9260
+ claude: "failed",
9261
+ opencode: "failed"
9262
+ };
9263
+ for (const store of STORES) {
9264
+ if (controller.signal.aborted) break;
9265
+ try {
9266
+ const result = await synchroniserRunner(["sync-once", store], {
9267
+ timeoutMs: CREDENTIAL_SYNC_TICK_TIMEOUT_MS,
9268
+ env,
9269
+ signal: controller.signal
9270
+ });
9271
+ outcomes[store] = !result.timedOut && result.code === 0 ? "ok" : "failed";
9272
+ } catch (error2) {
9273
+ outcomes[store] = "failed";
9274
+ log3(`CREDENTIAL-SYNC-TICK-ERROR: ${store}: ${errorMessage(error2)}`, "debug");
9275
+ }
9276
+ }
9277
+ const failed = STORES.some((store) => outcomes[store] === "failed");
9278
+ log3(
9279
+ `CREDENTIAL-SYNC-TICK: claude=${outcomes.claude}, opencode=${outcomes.opencode}`,
9280
+ "debug"
9281
+ );
9282
+ if (failed && lastTickFailed !== true) {
9283
+ log3(
9284
+ "CREDENTIAL-SYNC-FAILED: an interval credential sync failed; retrying on the next tick",
9285
+ "warn"
9286
+ );
9287
+ } else if (!failed && lastTickFailed === true) {
9288
+ log3("CREDENTIAL-SYNC-RECOVERED: interval credential sync succeeded again", "warn");
9289
+ }
9290
+ lastTickFailed = failed;
9291
+ })().finally(() => {
9292
+ if (activeTickAbort === controller) activeTickAbort = void 0;
9293
+ if (inFlight === tick) inFlight = void 0;
9294
+ scheduleTick(intervalMs, () => startTick(intervalMs));
9295
+ });
9296
+ inFlight = tick;
9297
+ };
9298
+ const performFlush = async () => {
9299
+ stopped = true;
9300
+ if (timer) {
9301
+ clearTimeout(timer);
9302
+ timer = void 0;
9303
+ }
9304
+ const deadlineAt = Date.now() + CREDENTIAL_FLUSH_DEADLINE_MS;
9305
+ if (inFlight) {
9306
+ const settled = await waitForSettlement(inFlight, CREDENTIAL_FLUSH_DEADLINE_MS);
9307
+ if (!settled) {
9308
+ activeTickAbort?.abort();
9309
+ const settledAfterAbort = await waitForSettlement(
9310
+ inFlight,
9311
+ CREDENTIAL_FLUSH_ABORT_GRACE_MS
9312
+ );
9313
+ if (!settledAfterAbort) {
9314
+ log3(
9315
+ "CREDENTIAL-FLUSH-ORPHANED-TICK: a sync-once child could not be proven settled; skipping the boundary flush rather than becoming a second writer",
9316
+ "warn"
9317
+ );
9318
+ return { outcomes: outcomesWith("timeout"), orphaned: true };
9319
+ }
9320
+ }
9321
+ }
9322
+ if (disabled) return { outcomes: outcomesWith("skipped"), orphaned: false };
9323
+ const outcomes = outcomesWith("timeout");
9324
+ for (const store of STORES) {
9325
+ const result = await runFlushStore(store, env, synchroniserRunner, log3, deadlineAt);
9326
+ if (result.orphaned) {
9327
+ log3(
9328
+ "CREDENTIAL-FLUSH-ORPHANED-CHILD: a flush sync-once child could not be proven settled; refusing another flush pass rather than becoming a second writer",
9329
+ "warn"
9330
+ );
9331
+ return { outcomes: outcomesWith("timeout"), orphaned: true };
9332
+ }
9333
+ outcomes[store] = result.outcome;
9334
+ }
9335
+ return { outcomes, orphaned: false };
9336
+ };
9337
+ let flushPasses = 0;
9338
+ let lastFlush;
9339
+ return {
9340
+ arm() {
9341
+ if (stopped || armed) return;
9342
+ armed = true;
9343
+ if (persistenceDisabled) {
9344
+ disabled = true;
9345
+ log3(
9346
+ "CREDENTIAL-SYNC-DISABLED: LITESTREAM_BUCKET/LITESTREAM_PREFIX are not both set; no interval credential sync this boot",
9347
+ "warn"
9348
+ );
9349
+ return;
9350
+ }
9351
+ disabled = false;
9352
+ const intervalMs = intervalSeconds(env, log3) * 1e3;
9353
+ scheduleTick(intervalMs, () => startTick(intervalMs));
9354
+ },
9355
+ async stopAndFlush(publish) {
9356
+ let result;
9357
+ const runningFlush = flushPromise;
9358
+ if (runningFlush) {
9359
+ result = await runningFlush;
9360
+ } else if (flushPasses >= MAX_FLUSH_PASSES || lastFlush?.orphaned) {
9361
+ result = lastFlush ?? { outcomes: outcomesWith("timeout"), orphaned: true };
9362
+ } else {
9363
+ flushPasses++;
9364
+ const currentFlush = performFlush();
9365
+ flushPromise = currentFlush;
9366
+ try {
9367
+ result = await currentFlush;
9368
+ lastFlush = result;
9369
+ } finally {
9370
+ if (flushPromise === currentFlush) flushPromise = void 0;
9371
+ }
9372
+ }
9373
+ if (publish) writeMarker(markerPath, result.outcomes, log3);
9374
+ return result.outcomes;
9375
+ }
9376
+ };
9377
+ }
9378
+
7977
9379
  // src/commands/run.ts
7978
9380
  var MAX_ACTIVITY_LOG_ENTRIES = 10;
7979
9381
  var CHANNEL_POLL_INTERVAL_MS = Number(process.env.EVIDENT_CHANNEL_POLL_INTERVAL_MS) || 2e3;
7980
9382
  var CHANNEL_STUCK_QUEUED_MS = Number(process.env.EVIDENT_STUCK_QUEUED_MS) || void 0;
7981
9383
  var SHUTDOWN_DRAIN_TIMEOUT_MS = Number(process.env.EVIDENT_SHUTDOWN_DRAIN_MS) || 25e3;
7982
9384
  var TELEMETRY_SHUTDOWN_TIMEOUT_MS = 5e3;
9385
+ var CHILD_STOP_TIMEOUT_MS = 1e4;
7983
9386
  function resolveLogLevel(options) {
7984
9387
  const accepted = Object.keys(LOG_LEVELS);
7985
9388
  const validate = (value, source) => {
@@ -8010,11 +9413,11 @@ function resolveFileSyncDirectories(raw, homeDir) {
8010
9413
  if (trimmed === "") {
8011
9414
  throw new Error("--enable-file-sync-to requires a directory path (got an empty value)");
8012
9415
  }
8013
- const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join7(homeDir, trimmed.slice(2)) : trimmed;
8014
- if (!isAbsolute2(expanded)) {
9416
+ const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join9(homeDir, trimmed.slice(2)) : trimmed;
9417
+ if (!isAbsolute3(expanded)) {
8015
9418
  throw new Error(`--enable-file-sync-to requires an absolute directory path; got "${entry}"`);
8016
9419
  }
8017
- const normalized = resolvePath(expanded);
9420
+ const normalized = resolvePath2(expanded);
8018
9421
  if (parse(normalized).root === normalized) {
8019
9422
  throw new Error(
8020
9423
  `--enable-file-sync-to will not allow-list the filesystem root ("${entry}"); name the specific directory the credentials belong in (for example ~/.claude)`
@@ -8130,7 +9533,7 @@ function logActivity(state, entry) {
8130
9533
  }
8131
9534
  function reportSessionDbRecovery(state) {
8132
9535
  try {
8133
- const report = drainSessionDbRecoveryReport({ homeDir: homedir4(), env: process.env });
9536
+ const report = drainSessionDbRecoveryReport({ homeDir: homedir5(), env: process.env });
8134
9537
  for (const record of report.records) {
8135
9538
  const activity = buildSessionDbRecoveryActivity(record);
8136
9539
  if (!activity) throw new Error("could not map session-DB recovery record");
@@ -8148,6 +9551,16 @@ function reportSessionDbRecovery(state) {
8148
9551
  );
8149
9552
  }
8150
9553
  }
9554
+ function reportSessionDbRecoveryRecord(state, record) {
9555
+ const activity = buildSessionDbRecoveryActivity(record);
9556
+ if (!activity) throw new Error("could not map session-DB recovery record");
9557
+ logActivity(state, {
9558
+ type: activity.level === "error" ? "error" : "info",
9559
+ level: activity.level,
9560
+ ...activity.level === "error" ? { error: activity.message } : { message: activity.message },
9561
+ metadata: activity.metadata
9562
+ });
9563
+ }
8151
9564
  function displayStatus(state) {
8152
9565
  if (!state.interactive) return;
8153
9566
  const attempt = state.connection?.reconnectAttempt ?? 0;
@@ -8260,6 +9673,10 @@ async function driveChannels(state, driver) {
8260
9673
  consecutiveDrainFailures = 0;
8261
9674
  unreachableMs = 0;
8262
9675
  state.messageCount += processed;
9676
+ if (driver.recycleRequested) {
9677
+ await beginGracefulShutdown(state, "recycle");
9678
+ return;
9679
+ }
8263
9680
  const proxiedActivity = state.lastProxiedActivityAt !== lastSeenProxiedActivityAt;
8264
9681
  lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
8265
9682
  const fileActivitySnapshot = driver.fileSyncActivity();
@@ -8302,8 +9719,8 @@ async function driveChannels(state, driver) {
8302
9719
  state.running = false;
8303
9720
  break;
8304
9721
  }
8305
- const errorMessage = error2 instanceof Error ? error2.message : String(error2);
8306
- logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage}` });
9722
+ const errorMessage2 = error2 instanceof Error ? error2.message : String(error2);
9723
+ logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage2}` });
8307
9724
  if (state.interactive) displayStatus(state);
8308
9725
  if (driver.hasInFlightWatchers()) {
8309
9726
  consecutiveDrainFailures = 0;
@@ -8320,7 +9737,7 @@ async function driveChannels(state, driver) {
8320
9737
  }
8321
9738
  }
8322
9739
  }
8323
- await new Promise((resolve3) => setTimeout(resolve3, CHANNEL_POLL_INTERVAL_MS));
9740
+ await new Promise((resolve4) => setTimeout(resolve4, CHANNEL_POLL_INTERVAL_MS));
8324
9741
  const cycleMs = performance.now() - cycleStartedAtMs;
8325
9742
  if (idleThisCycle) idleMs += cycleMs;
8326
9743
  if (unreachableThisCycle) unreachableMs += cycleMs;
@@ -8343,7 +9760,43 @@ async function driveChannels(state, driver) {
8343
9760
  var SESSION_CLEANUP_FIRST_SWEEP_MS = 1e4;
8344
9761
  var SESSION_DB_RECLAIM_MAX_PAGES = 2e3;
8345
9762
  function sessionDbPath() {
8346
- return join7(homedir4(), ".local", "share", "opencode", "opencode.db");
9763
+ return join9(homedir5(), ".local", "share", "opencode", "opencode.db");
9764
+ }
9765
+ function logSessionDbProvenanceMismatch(state, provenance, currentVersion, preBootMigrationCount) {
9766
+ const record = {
9767
+ v: 1,
9768
+ event: "session_db_recovery",
9769
+ at: (/* @__PURE__ */ new Date()).toISOString(),
9770
+ stage: "verify",
9771
+ outcome: "schema_provenance_mismatch",
9772
+ severity: "error",
9773
+ reason: provenance.reason ?? "schema-provenance-mismatch",
9774
+ litestream_exit_code: null,
9775
+ attempt: null,
9776
+ replica_objects: null,
9777
+ replica_bytes: null,
9778
+ quarantine_destination: null,
9779
+ quarantined_objects: null,
9780
+ quarantine_failed_objects: null,
9781
+ quarantined_bytes: null,
9782
+ verified_restore_point: null,
9783
+ restore_points_tried: null,
9784
+ provenance_reason: provenance.reason,
9785
+ provenance_migration_delta: provenance.migrationDelta,
9786
+ replication_suspended: false,
9787
+ dbPath: sessionDbPath(),
9788
+ recorded_version: provenance.recordedVersion,
9789
+ current_version: currentVersion,
9790
+ provenance_pre_boot_migration_count: preBootMigrationCount
9791
+ };
9792
+ const activity = buildSessionDbRecoveryActivity(record);
9793
+ if (!activity) throw new Error("could not map session-DB provenance activity");
9794
+ logActivity(state, {
9795
+ type: activity.level === "error" ? "error" : "info",
9796
+ level: activity.level,
9797
+ ...activity.level === "error" ? { error: activity.message } : { message: activity.message },
9798
+ metadata: activity.metadata
9799
+ });
8347
9800
  }
8348
9801
  async function runSweep(state, driver, config) {
8349
9802
  const mode = `age=${config.maxAgeMs ?? "\u2014"} count=${config.maxCount ?? "\u2014"}`;
@@ -8390,7 +9843,7 @@ async function runSweep(state, driver, config) {
8390
9843
  const reclaimResult = await reclaimSessionDbSpace({
8391
9844
  dbPath: sessionDbPath(),
8392
9845
  maxPages: SESSION_DB_RECLAIM_MAX_PAGES,
8393
- allowFullVacuum: protectedNow.size === 0
9846
+ allowFullVacuum: protectedNow.size === 0 && !state.sessionDbProvenanceAnomaly
8394
9847
  });
8395
9848
  if (reclaimResult.ok) {
8396
9849
  const beforeMib = (reclaimResult.beforeBytes / 1024 / 1024).toFixed(1);
@@ -8426,7 +9879,7 @@ function scheduleSessionCleanup(state, driver, options) {
8426
9879
  for (const warning2 of config.warnings) {
8427
9880
  logActivity(state, { type: "info", level: "warn", message: `Session cleanup: ${warning2}` });
8428
9881
  }
8429
- const dbBytes = statSessionDbBytes(homedir4());
9882
+ const dbBytes = statSessionDbBytes(homedir5());
8430
9883
  void (async () => {
8431
9884
  const reclaimSkipReason = dbBytes !== null && config.enabled ? await probeReclaimAvailability({ dbPath: sessionDbPath(), requiredBytes: dbBytes }) : null;
8432
9885
  const sizeWarning = buildSessionStoreSizeWarning({
@@ -8627,7 +10080,7 @@ function scheduleResourceUsageReporting(state, options) {
8627
10080
  });
8628
10081
  return;
8629
10082
  }
8630
- const collect = createResourceUsageCollector(homedir4());
10083
+ const collect = createResourceUsageCollector(homedir5());
8631
10084
  let consecutiveFailures = 0;
8632
10085
  const tick = async () => {
8633
10086
  try {
@@ -8737,21 +10190,39 @@ async function cleanup(state, opts = {}) {
8737
10190
  clearTimeout(state.resourceUsageTimer);
8738
10191
  state.resourceUsageTimer = null;
8739
10192
  }
10193
+ const credentialSync = state.credentialSync;
10194
+ const flushCredentials = credentialSync ? async (phase, publish) => {
10195
+ await timeShutdownPhase(state, durations, phase, async () => {
10196
+ const outcomes = await credentialSync.stopAndFlush(publish);
10197
+ const level = Object.values(outcomes).every((outcome) => outcome === "ok") ? "info" : "warn";
10198
+ log2(
10199
+ state,
10200
+ `Credential flush: claude=${outcomes.claude}, opencode=${outcomes.opencode}`,
10201
+ level
10202
+ );
10203
+ });
10204
+ } : void 0;
10205
+ let drainSettled = true;
8740
10206
  if (opts.graceful && state.channelDriver) {
8741
10207
  state.channelDriver.stop();
10208
+ }
10209
+ if (flushCredentials) {
10210
+ await flushCredentials("credential_flush", !(opts.graceful && state.channelDriver));
10211
+ }
10212
+ if (opts.graceful && state.channelDriver) {
8742
10213
  log2(state, "Draining in-flight channel work before shutdown...");
8743
10214
  if (state.interactive) {
8744
10215
  logActivity(state, { type: "info", message: "Draining in-flight work before shutdown..." });
8745
10216
  displayStatus(state);
8746
10217
  }
8747
10218
  const driver = state.channelDriver;
8748
- const settled = await timeShutdownPhase(
10219
+ drainSettled = await timeShutdownPhase(
8749
10220
  state,
8750
10221
  durations,
8751
10222
  "drain",
8752
10223
  () => driver.waitForInFlight(SHUTDOWN_DRAIN_TIMEOUT_MS)
8753
10224
  );
8754
- if (!settled) {
10225
+ if (!drainSettled) {
8755
10226
  logActivity(state, {
8756
10227
  type: "info",
8757
10228
  message: "Shutdown drain timed out with work still in flight \u2014 leaving it for restart recovery"
@@ -8759,6 +10230,9 @@ async function cleanup(state, opts = {}) {
8759
10230
  if (state.interactive) displayStatus(state);
8760
10231
  }
8761
10232
  }
10233
+ if (opts.graceful && state.channelDriver && flushCredentials && drainSettled) {
10234
+ await flushCredentials("credential_flush_final", true);
10235
+ }
8762
10236
  await timeShutdownPhase(state, durations, "offline_notify", () => notifyOffline(state));
8763
10237
  if (state.connection) {
8764
10238
  const connection = state.connection;
@@ -8767,24 +10241,83 @@ async function cleanup(state, opts = {}) {
8767
10241
  }
8768
10242
  if (state.opencodeProcess) {
8769
10243
  const opencodeProcess = state.opencodeProcess;
8770
- await timeShutdownPhase(state, durations, "opencode_stop", () => stopOpenCode(opencodeProcess));
10244
+ const result = await timeShutdownPhase(
10245
+ state,
10246
+ durations,
10247
+ "opencode_stop",
10248
+ () => stopOpenCodeAndWait(opencodeProcess, CHILD_STOP_TIMEOUT_MS)
10249
+ );
8771
10250
  if (state.interactive) {
8772
- logActivity(state, { type: "info", message: "Stopped OpenCode process" });
10251
+ logActivity(state, { type: "info", message: `Stopped OpenCode process (${result.outcome})` });
8773
10252
  displayStatus(state);
8774
10253
  } else {
8775
- log2(state, "Stopped OpenCode process");
10254
+ log2(state, `Stopped OpenCode process (${result.outcome})`);
8776
10255
  }
8777
10256
  state.opencodeProcess = null;
8778
10257
  }
10258
+ if (state.litestreamProcess) {
10259
+ const litestreamProcess = state.litestreamProcess;
10260
+ const result = await timeShutdownPhase(
10261
+ state,
10262
+ durations,
10263
+ "litestream_stop",
10264
+ () => stopSessionDbReplication(litestreamProcess, CHILD_STOP_TIMEOUT_MS)
10265
+ );
10266
+ log2(state, `Stopped litestream replication (${result.outcome})`);
10267
+ state.litestreamProcess = null;
10268
+ }
8779
10269
  return durations;
8780
10270
  }
10271
+ async function beginGracefulShutdown(state, trigger) {
10272
+ if (state.shuttingDown) return;
10273
+ state.shuttingDown = true;
10274
+ const shutdownStartedAt = Date.now();
10275
+ const shutdownMessage = trigger === "recycle" ? "Recycle requested \u2014 finishing in-flight work, then exiting" : "Shutting down...";
10276
+ if (state.interactive) {
10277
+ logActivity(state, { type: "info", message: shutdownMessage });
10278
+ displayStatus(state);
10279
+ } else {
10280
+ log2(state, shutdownMessage);
10281
+ }
10282
+ const durations = await cleanup(state, { graceful: true });
10283
+ const telemetryBudgetMs = Number(process.env.EVIDENT_TELEMETRY_SHUTDOWN_MS) || TELEMETRY_SHUTDOWN_TIMEOUT_MS;
10284
+ await timeShutdownPhase(state, durations, "telemetry_flush", async () => {
10285
+ let timer;
10286
+ const flushed = shutdownTelemetry().then(
10287
+ () => true,
10288
+ (error2) => {
10289
+ log2(
10290
+ state,
10291
+ `Telemetry flush failed during shutdown: ${error2 instanceof Error ? error2.message : String(error2)}`,
10292
+ "warn"
10293
+ );
10294
+ return true;
10295
+ }
10296
+ );
10297
+ const timedOut = new Promise((resolve4) => {
10298
+ timer = setTimeout(() => resolve4(false), telemetryBudgetMs);
10299
+ });
10300
+ if (!await Promise.race([flushed, timedOut])) {
10301
+ log2(state, `Telemetry flush exceeded ${telemetryBudgetMs}ms \u2014 exiting anyway`, "warn");
10302
+ }
10303
+ clearTimeout(timer);
10304
+ });
10305
+ const breakdown = Object.entries(durations).map(([phase, ms]) => `${phase}=${ms}ms`).join(" ");
10306
+ log2(state, `Shutdown complete in ${Date.now() - shutdownStartedAt}ms (${breakdown})`);
10307
+ process.exit(0);
10308
+ }
8781
10309
  async function run(options) {
8782
10310
  const interactive = isInteractive(options.json);
8783
10311
  let logLevel;
8784
10312
  let fileSyncDirectories;
8785
10313
  try {
8786
10314
  logLevel = resolveLogLevel(options);
8787
- fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir4());
10315
+ fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir5());
10316
+ if (options.restoreSessionDb && !options.sessionDbNoReplicateMarker) {
10317
+ throw new Error(
10318
+ "--restore-session-db requires --session-db-no-replicate-marker <path>; restore failures must block Litestream replication"
10319
+ );
10320
+ }
8788
10321
  } catch (error2) {
8789
10322
  const message = error2 instanceof Error ? error2.message : String(error2);
8790
10323
  if (options.json) {
@@ -8808,7 +10341,9 @@ async function run(options) {
8808
10341
  connected: false,
8809
10342
  opencodeConnected: false,
8810
10343
  opencodeVersion: null,
10344
+ sessionDbProvenanceAnomaly: false,
8811
10345
  opencodeProcess: null,
10346
+ litestreamProcess: null,
8812
10347
  connection: null,
8813
10348
  channelDriver: null,
8814
10349
  running: true,
@@ -8822,9 +10357,23 @@ async function run(options) {
8822
10357
  openaiUsageTimer: null,
8823
10358
  openaiUsageRearm: null,
8824
10359
  resourceUsageTimer: null,
10360
+ credentialSync: null,
8825
10361
  authHeader: ""
8826
10362
  };
8827
10363
  setTelemetryAuthProvider(() => ({ authHeader: state.authHeader, agentId: state.agentId }));
10364
+ if (options.credentialSyncMarker) {
10365
+ state.credentialSync = createCredentialSync({
10366
+ markerPath: options.credentialSyncMarker,
10367
+ env: process.env,
10368
+ log: (message, level = "info") => {
10369
+ if (level === "error") {
10370
+ logActivity(state, { type: "error", error: message });
10371
+ } else {
10372
+ logActivity(state, { type: "info", level, message });
10373
+ }
10374
+ }
10375
+ });
10376
+ }
8828
10377
  if (fileSyncDirectories.length > 0) {
8829
10378
  log2(state, `File sync enabled for: ${fileSyncDirectories.join(", ")}`);
8830
10379
  } else {
@@ -8850,43 +10399,7 @@ async function run(options) {
8850
10399
  "warn"
8851
10400
  );
8852
10401
  }
8853
- const handleSignal = async () => {
8854
- if (state.shuttingDown) return;
8855
- state.shuttingDown = true;
8856
- const shutdownStartedAt = Date.now();
8857
- if (state.interactive) {
8858
- logActivity(state, { type: "info", message: "Shutting down..." });
8859
- displayStatus(state);
8860
- } else {
8861
- log2(state, "Shutting down...");
8862
- }
8863
- const durations = await cleanup(state, { graceful: true });
8864
- const telemetryBudgetMs = Number(process.env.EVIDENT_TELEMETRY_SHUTDOWN_MS) || TELEMETRY_SHUTDOWN_TIMEOUT_MS;
8865
- await timeShutdownPhase(state, durations, "telemetry_flush", async () => {
8866
- let timer;
8867
- const flushed = shutdownTelemetry().then(
8868
- () => true,
8869
- (error2) => {
8870
- log2(
8871
- state,
8872
- `Telemetry flush failed during shutdown: ${error2 instanceof Error ? error2.message : String(error2)}`,
8873
- "warn"
8874
- );
8875
- return true;
8876
- }
8877
- );
8878
- const timedOut = new Promise((resolve3) => {
8879
- timer = setTimeout(() => resolve3(false), telemetryBudgetMs);
8880
- });
8881
- if (!await Promise.race([flushed, timedOut])) {
8882
- log2(state, `Telemetry flush exceeded ${telemetryBudgetMs}ms \u2014 exiting anyway`, "warn");
8883
- }
8884
- clearTimeout(timer);
8885
- });
8886
- const breakdown = Object.entries(durations).map(([phase, ms]) => `${phase}=${ms}ms`).join(" ");
8887
- log2(state, `Shutdown complete in ${Date.now() - shutdownStartedAt}ms (${breakdown})`);
8888
- process.exit(0);
8889
- };
10402
+ const handleSignal = () => beginGracefulShutdown(state, "signal");
8890
10403
  process.on("SIGINT", handleSignal);
8891
10404
  process.on("SIGTERM", handleSignal);
8892
10405
  try {
@@ -9016,7 +10529,68 @@ async function run(options) {
9016
10529
  } else {
9017
10530
  log2(state, "Not running in a MicroVM (MICROVM_ID unset) \u2014 nothing to report", "debug");
9018
10531
  }
10532
+ if (options.restoreRunnerCredentials) {
10533
+ log2(state, "Restoring runner credentials before starting OpenCode");
10534
+ const credentialContext = {
10535
+ env: process.env,
10536
+ log: (message, level = "info") => {
10537
+ if (level === "error") {
10538
+ logActivity(state, { type: "error", error: message });
10539
+ } else {
10540
+ logActivity(state, { type: "info", level, message });
10541
+ }
10542
+ }
10543
+ };
10544
+ const githubTokenPopulated = await installRunnerSecret(credentialContext);
10545
+ await restoreCredentialStores(credentialContext);
10546
+ if (githubTokenPopulated) await configureGitHubAccess(credentialContext);
10547
+ }
10548
+ state.credentialSync?.arm();
10549
+ let sessionDbVerifyFatal = false;
10550
+ if (!options.restoreSessionDb) {
10551
+ log2(state, "Skipping session-DB restore: --restore-session-db was not passed", "debug");
10552
+ } else {
10553
+ const health = await checkOpenCodeHealth(state.port);
10554
+ if (health.healthy) {
10555
+ log2(
10556
+ state,
10557
+ "Skipping session-DB restore: OpenCode is already serving this database",
10558
+ "debug"
10559
+ );
10560
+ } else {
10561
+ const result = await restoreAndVerifySessionDb({
10562
+ dbPath: sessionDbPath(),
10563
+ litestreamConfig: options.litestreamConfig,
10564
+ noReplicateMarker: options.sessionDbNoReplicateMarker,
10565
+ env: process.env,
10566
+ log: (message, level = "info") => {
10567
+ if (level === "error") {
10568
+ logActivity(state, { type: "error", error: message });
10569
+ } else {
10570
+ logActivity(state, { type: "info", level, message });
10571
+ }
10572
+ },
10573
+ reportRecovery: (record) => reportSessionDbRecoveryRecord(state, record)
10574
+ });
10575
+ sessionDbVerifyFatal = result.verifyFatal;
10576
+ }
10577
+ }
9019
10578
  reportSessionDbRecovery(state);
10579
+ if (sessionDbVerifyFatal) {
10580
+ throw new Error(
10581
+ "SESSION-DB-INTEGRITY-EXHAUSTED: the corrupt session DB could not be proven separated from the active backup prefix or removed from disk"
10582
+ );
10583
+ }
10584
+ applyRunnerOpenCodeConfig({
10585
+ overlayPath: options.opencodeConfigOverlay,
10586
+ log: (message, level = "info") => {
10587
+ if (level === "error") {
10588
+ logActivity(state, { type: "error", error: message });
10589
+ } else {
10590
+ logActivity(state, { type: "info", level, message });
10591
+ }
10592
+ }
10593
+ });
9020
10594
  const { timeoutMs: opencodeStartTimeoutMs, warnings: opencodeStartTimeoutWarnings } = resolveOpenCodeStartTimeoutMs(options, process.env);
9021
10595
  for (const warning2 of opencodeStartTimeoutWarnings) {
9022
10596
  logActivity(state, { type: "info", level: "warn", message: warning2 });
@@ -9025,6 +10599,7 @@ async function run(options) {
9025
10599
  for (const warning2 of maxActiveSessionsWarnings) {
9026
10600
  logActivity(state, { type: "info", level: "warn", message: warning2 });
9027
10601
  }
10602
+ const preBootMigrationIds = readSessionDbMigrationIds(sessionDbPath());
9028
10603
  const ocSpinner = interactive && !state.json ? ora3("Checking OpenCode...").start() : null;
9029
10604
  try {
9030
10605
  const oc = await ensureOpenCodeRunning({
@@ -9032,11 +10607,41 @@ async function run(options) {
9032
10607
  interactive: state.interactive,
9033
10608
  agentId: state.agentId,
9034
10609
  log: (message) => log2(state, message),
9035
- startTimeoutMs: opencodeStartTimeoutMs
10610
+ startTimeoutMs: opencodeStartTimeoutMs,
10611
+ inheritStdio: Boolean(options.opencodePidFile)
9036
10612
  });
9037
10613
  state.port = oc.port;
9038
- state.opencodeProcess = oc.process;
10614
+ state.opencodeProcess = options.opencodePidFile ? null : oc.process;
9039
10615
  state.opencodeVersion = oc.version;
10616
+ if (options.opencodePidFile && oc.process?.pid !== void 0) {
10617
+ try {
10618
+ writeFileSync6(options.opencodePidFile, `${oc.process.pid}
10619
+ `, { mode: 384 });
10620
+ chmodSync3(options.opencodePidFile, 384);
10621
+ } catch (error2) {
10622
+ logActivity(state, {
10623
+ type: "error",
10624
+ error: `Failed to write OpenCode pid file ${options.opencodePidFile}: ${error2 instanceof Error ? error2.message : String(error2)}`
10625
+ });
10626
+ }
10627
+ }
10628
+ if (state.opencodeVersion !== null) {
10629
+ const provenance = checkSessionDbProvenance({
10630
+ dbPath: sessionDbPath(),
10631
+ currentVersion: state.opencodeVersion,
10632
+ homeDir: homedir5(),
10633
+ env: process.env
10634
+ });
10635
+ if (provenance.anomaly) {
10636
+ state.sessionDbProvenanceAnomaly = true;
10637
+ logSessionDbProvenanceMismatch(
10638
+ state,
10639
+ provenance,
10640
+ state.opencodeVersion,
10641
+ preBootMigrationIds?.length ?? null
10642
+ );
10643
+ }
10644
+ }
9040
10645
  state.opencodeConnected = oc.notReadyReason === null;
9041
10646
  const version2 = state.opencodeVersion ? ` (v${state.opencodeVersion})` : "";
9042
10647
  ocSpinner?.succeed(`OpenCode running on port ${state.port}${version2}`);
@@ -9073,6 +10678,108 @@ async function run(options) {
9073
10678
  ocSpinner?.fail(error2.message);
9074
10679
  throw error2;
9075
10680
  }
10681
+ if (options.litestreamPidFile) {
10682
+ if (options.sessionDbNoReplicateMarker && existsSync3(options.sessionDbNoReplicateMarker)) {
10683
+ log2(
10684
+ state,
10685
+ `Skipping Litestream replication because ${options.sessionDbNoReplicateMarker} marks this session database unsafe to replicate`
10686
+ );
10687
+ } else if (!options.litestreamConfig) {
10688
+ logActivity(state, {
10689
+ type: "info",
10690
+ level: "warn",
10691
+ message: "Skipping Litestream replication because no configuration file was provided"
10692
+ });
10693
+ } else {
10694
+ let existingPid;
10695
+ if (existsSync3(options.litestreamPidFile)) {
10696
+ try {
10697
+ const rawPid = readFileSync6(options.litestreamPidFile, "utf8").trim();
10698
+ const parsedPid = Number(rawPid);
10699
+ if (/^\d+$/.test(rawPid) && Number.isSafeInteger(parsedPid) && parsedPid > 0) {
10700
+ existingPid = parsedPid;
10701
+ }
10702
+ } catch (error2) {
10703
+ logActivity(state, {
10704
+ type: "info",
10705
+ level: "warn",
10706
+ message: `Could not read Litestream pid file ${options.litestreamPidFile}; checking for a new process: ${error2 instanceof Error ? error2.message : String(error2)}`
10707
+ });
10708
+ }
10709
+ }
10710
+ if (existingPid !== void 0 && isProcessAlive(existingPid)) {
10711
+ log2(state, `Litestream replication is already running with pid ${existingPid}`);
10712
+ } else {
10713
+ const litestreamProcess = startSessionDbReplication(options.litestreamConfig);
10714
+ state.litestreamProcess = null;
10715
+ let failureHandled = false;
10716
+ const reportImageOwnedReplicationFailure = (message) => {
10717
+ if (failureHandled || state.shuttingDown || !state.running) return;
10718
+ failureHandled = true;
10719
+ logActivity(state, { type: "error", error: message });
10720
+ if (state.interactive) displayStatus(state);
10721
+ };
10722
+ litestreamProcess.on("exit", (code, signal) => {
10723
+ reportImageOwnedReplicationFailure(
10724
+ `Litestream replication stopped unexpectedly (code: ${code ?? "null"}, signal: ${signal ?? "none"})`
10725
+ );
10726
+ });
10727
+ litestreamProcess.on("error", (error2) => {
10728
+ reportImageOwnedReplicationFailure(
10729
+ `Litestream replication failed: ${error2 instanceof Error ? error2.message : String(error2)}`
10730
+ );
10731
+ });
10732
+ try {
10733
+ if (litestreamProcess.pid !== void 0) {
10734
+ writeFileSync6(options.litestreamPidFile, `${litestreamProcess.pid}
10735
+ `, {
10736
+ mode: 384
10737
+ });
10738
+ chmodSync3(options.litestreamPidFile, 384);
10739
+ }
10740
+ } catch (error2) {
10741
+ logActivity(state, {
10742
+ type: "error",
10743
+ error: `Failed to write Litestream pid file ${options.litestreamPidFile}: ${error2 instanceof Error ? error2.message : String(error2)}`
10744
+ });
10745
+ }
10746
+ log2(state, `Started litestream replication with config ${options.litestreamConfig}`);
10747
+ }
10748
+ }
10749
+ } else if (options.litestreamConfig) {
10750
+ const litestreamProcess = startSessionDbReplication(options.litestreamConfig);
10751
+ state.litestreamProcess = litestreamProcess;
10752
+ let failureHandled = false;
10753
+ const failRunForReplication = (message) => {
10754
+ if (failureHandled || state.shuttingDown || !state.running) return;
10755
+ failureHandled = true;
10756
+ state.shuttingDown = true;
10757
+ logActivity(state, { type: "error", error: message });
10758
+ if (state.interactive) displayStatus(state);
10759
+ void (async () => {
10760
+ try {
10761
+ await cleanup(state);
10762
+ await shutdownTelemetry();
10763
+ } catch (error2) {
10764
+ console.error(
10765
+ `[run] replication failure cleanup failed: ${error2 instanceof Error ? error2.message : String(error2)}`
10766
+ );
10767
+ }
10768
+ process.exit(1);
10769
+ })();
10770
+ };
10771
+ litestreamProcess.on("exit", (code, signal) => {
10772
+ failRunForReplication(
10773
+ `Litestream replication stopped unexpectedly (code: ${code ?? "null"}, signal: ${signal ?? "none"})`
10774
+ );
10775
+ });
10776
+ litestreamProcess.on("error", (error2) => {
10777
+ failRunForReplication(
10778
+ `Litestream replication failed: ${error2 instanceof Error ? error2.message : String(error2)}`
10779
+ );
10780
+ });
10781
+ log2(state, `Started litestream replication with config ${options.litestreamConfig}`);
10782
+ }
9076
10783
  const tunnelSpinner = interactive && !state.json ? ora3("Connecting tunnel...").start() : null;
9077
10784
  const channelDriver = new ChannelDriver({
9078
10785
  agentId: state.agentId,
@@ -9084,7 +10791,7 @@ async function run(options) {
9084
10791
  // #559: the `--enable-file-sync-to` allow-list. Empty ⇒ pending files are
9085
10792
  // REJECTED with `file_sync_disabled` on the ack, not silently ignored.
9086
10793
  fileSyncDirectories,
9087
- homeDir: homedir4(),
10794
+ homeDir: homedir5(),
9088
10795
  maxActiveSessions,
9089
10796
  log: (entry) => (
9090
10797
  // Thread the driver's real level straight through so `debug`/`warn`
@@ -9230,7 +10937,17 @@ async function run(options) {
9230
10937
  setTimer: (timer) => {
9231
10938
  state.openaiUsageTimer = timer;
9232
10939
  },
9233
- fetchUsage: () => getOpenAiUsage(state.port),
10940
+ fetchUsage: async () => {
10941
+ const usage = await getOpenAiUsage(state.port);
10942
+ if (usage.subscription === null) {
10943
+ logActivity(state, {
10944
+ type: "info",
10945
+ level: "debug",
10946
+ message: "OpenAI usage subscription could not be identified from the local credential"
10947
+ });
10948
+ }
10949
+ return usage;
10950
+ },
9234
10951
  report: (usage) => reportOpenAiUsage(state.agentId, state.authHeader, usage),
9235
10952
  isLocalCredentialProblem: isLocalCredentialProblem2,
9236
10953
  forcedOnHint: "connect a ChatGPT account to this runner, or run `opencode auth login`",
@@ -9276,7 +10993,7 @@ async function run(options) {
9276
10993
  }
9277
10994
 
9278
10995
  // src/index.ts
9279
- var { version } = createRequire(import.meta.url)("../package.json");
10996
+ var { version } = createRequire2(import.meta.url)("../package.json");
9280
10997
  var program = new Command();
9281
10998
  program.name("evident").description("Run OpenCode locally and connect it to Evident").version(version).option(
9282
10999
  "--endpoint <url>",
@@ -9333,6 +11050,30 @@ program.command("run").description("Connect to Evident and process messages").op
9333
11050
  ).option(
9334
11051
  "--tunnel-ready-file <path>",
9335
11052
  "Path to write once the tunnel is connected (opt-in; unused unless an operator/image sets it)"
11053
+ ).option(
11054
+ "--litestream-config <path>",
11055
+ "Replicate the OpenCode session database with `litestream replicate` using this config file (written by the runner image). Omit to disable replication."
11056
+ ).option(
11057
+ "--opencode-pid-file <path>",
11058
+ "Record the OpenCode pid here and leave the process running at shutdown for the runner image's lifecycle hooks to stop."
11059
+ ).option(
11060
+ "--litestream-pid-file <path>",
11061
+ "Record the Litestream pid here and leave the process running at shutdown for the runner image's lifecycle hooks to stop."
11062
+ ).option(
11063
+ "--session-db-no-replicate-marker <path>",
11064
+ "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."
11065
+ ).option(
11066
+ "--restore-session-db",
11067
+ "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."
11068
+ ).option(
11069
+ "--restore-runner-credentials",
11070
+ "Restore the hosted runner secret and persisted credential stores before starting OpenCode."
11071
+ ).option(
11072
+ "--opencode-config-overlay <path>",
11073
+ "Apply this runner-provided OpenCode config before starting OpenCode."
11074
+ ).option(
11075
+ "--credential-sync-marker <path>",
11076
+ "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."
9336
11077
  ).action(
9337
11078
  (options) => {
9338
11079
  run({
@@ -9364,7 +11105,15 @@ program.command("run").description("Connect to Evident and process messages").op
9364
11105
  // Raw values — expansion/validation is single-sourced in run.ts's
9365
11106
  // resolveFileSyncDirectories.
9366
11107
  enableFileSyncTo: options.enableFileSyncTo,
9367
- tunnelReadyFile: options.tunnelReadyFile
11108
+ tunnelReadyFile: options.tunnelReadyFile,
11109
+ litestreamConfig: options.litestreamConfig,
11110
+ opencodePidFile: options.opencodePidFile,
11111
+ litestreamPidFile: options.litestreamPidFile,
11112
+ sessionDbNoReplicateMarker: options.sessionDbNoReplicateMarker,
11113
+ restoreSessionDb: options.restoreSessionDb,
11114
+ restoreRunnerCredentials: options.restoreRunnerCredentials,
11115
+ opencodeConfigOverlay: options.opencodeConfigOverlay,
11116
+ credentialSyncMarker: options.credentialSyncMarker
9368
11117
  });
9369
11118
  }
9370
11119
  );