@evident-ai/cli 3.4.1-dev.8b081ae → 3.4.1-dev.90d85e0

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
@@ -11,8 +11,8 @@ import chalk2 from "chalk";
11
11
 
12
12
  // src/lib/config.ts
13
13
  import Conf from "conf";
14
- import { chmodSync, existsSync, statSync } from "fs";
15
- import { dirname } from "path";
14
+ import { chmodSync, existsSync, statSync } from "node:fs";
15
+ import { dirname } from "node:path";
16
16
  var PRODUCTION_API_URL = "https://api.production.evident.run/v1";
17
17
  var PRODUCTION_TUNNEL_URL = "wss://tunnel.production.evident.run";
18
18
  var defaults = {
@@ -371,14 +371,14 @@ function blank() {
371
371
  console.log();
372
372
  }
373
373
  function waitForEnter(prompt = "Press Enter to continue...") {
374
- return new Promise((resolve3) => {
374
+ return new Promise((resolve4) => {
375
375
  process.stdout.write(chalk.dim(prompt));
376
376
  const handler = () => {
377
377
  process.stdin.removeListener("data", handler);
378
378
  process.stdin.setRawMode?.(false);
379
379
  process.stdin.pause();
380
380
  console.log();
381
- resolve3();
381
+ resolve4();
382
382
  };
383
383
  if (process.stdin.isTTY) {
384
384
  process.stdin.setRawMode?.(true);
@@ -388,7 +388,7 @@ function waitForEnter(prompt = "Press Enter to continue...") {
388
388
  });
389
389
  }
390
390
  function sleep(ms) {
391
- return new Promise((resolve3) => setTimeout(resolve3, ms));
391
+ return new Promise((resolve4) => setTimeout(resolve4, ms));
392
392
  }
393
393
 
394
394
  // src/commands/login.ts
@@ -466,19 +466,19 @@ async function tokenLogin() {
466
466
  );
467
467
  blank();
468
468
  process.stdout.write("Paste token: ");
469
- const token = await new Promise((resolve3) => {
469
+ const token = await new Promise((resolve4) => {
470
470
  let data = "";
471
471
  process.stdin.setEncoding("utf8");
472
472
  process.stdin.on("data", (chunk) => {
473
473
  data += chunk;
474
474
  });
475
475
  process.stdin.on("end", () => {
476
- resolve3(data.trim());
476
+ resolve4(data.trim());
477
477
  });
478
478
  if (process.stdin.isTTY) {
479
479
  process.stdin.once("data", (chunk) => {
480
480
  process.stdin.pause();
481
- resolve3(chunk.toString().trim());
481
+ resolve4(chunk.toString().trim());
482
482
  });
483
483
  process.stdin.resume();
484
484
  }
@@ -763,6 +763,13 @@ function toReportedOpenAiWindow(window) {
763
763
  resets_at: window.resetsAt
764
764
  };
765
765
  }
766
+ function toReportedOpenAiSubscription(snapshot) {
767
+ if (!snapshot.subscription) return null;
768
+ return {
769
+ owner_email: snapshot.subscription.ownerEmail,
770
+ plan_type: snapshot.subscription.planType
771
+ };
772
+ }
766
773
  async function reportOpenAiUsage(agentId, authHeader, snapshot) {
767
774
  try {
768
775
  const apiUrl = getApiUrlConfig();
@@ -773,7 +780,8 @@ async function reportOpenAiUsage(agentId, authHeader, snapshot) {
773
780
  primary: toReportedOpenAiWindow(snapshot.primary),
774
781
  secondary: toReportedOpenAiWindow(snapshot.secondary),
775
782
  has_credits: snapshot.hasCredits,
776
- credits_unlimited: snapshot.creditsUnlimited
783
+ credits_unlimited: snapshot.creditsUnlimited,
784
+ subscription: toReportedOpenAiSubscription(snapshot)
777
785
  }),
778
786
  signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
779
787
  });
@@ -797,6 +805,7 @@ async function reportResourceUsage(agentId, authHeader, usage) {
797
805
  headers: { Authorization: authHeader, "Content-Type": "application/json" },
798
806
  body: JSON.stringify({
799
807
  cpu_percent: usage.cpuPercent,
808
+ cpu_peak_percent: usage.cpuPeakPercent,
800
809
  cpu_count: usage.cpuCount,
801
810
  memory_total_bytes: usage.memoryTotalBytes,
802
811
  memory_available_bytes: usage.memoryAvailableBytes,
@@ -1000,10 +1009,10 @@ async function status(options = {}) {
1000
1009
  }
1001
1010
 
1002
1011
  // src/lib/claude-usage.ts
1003
- import { execFileSync } from "child_process";
1004
- import { readFileSync } from "fs";
1005
- import { homedir } from "os";
1006
- import { join } from "path";
1012
+ import { execFileSync } from "node:child_process";
1013
+ import { readFileSync } from "node:fs";
1014
+ import { homedir } from "node:os";
1015
+ import { join } from "node:path";
1007
1016
  var CLAUDE_USAGE_URL = "https://api.anthropic.com/api/oauth/usage";
1008
1017
  var CLAUDE_PROFILE_URL = "https://api.anthropic.com/api/oauth/profile";
1009
1018
  var CLAUDE_PROFILE_TIMEOUT_MS = 2e3;
@@ -1183,9 +1192,10 @@ async function claudeUsage() {
1183
1192
  }
1184
1193
 
1185
1194
  // src/commands/run.ts
1186
- import { homedir as homedir4 } from "os";
1187
- import { isAbsolute as isAbsolute2, join as join7, parse, resolve as resolvePath } from "path";
1188
- import chalk6 from "chalk";
1195
+ import { chmodSync as chmodSync3, existsSync as existsSync3, readFileSync as readFileSync6, writeFileSync as writeFileSync6 } from "node:fs";
1196
+ import { homedir as homedir5 } from "node:os";
1197
+ import { isAbsolute as isAbsolute3, join as join9, parse, resolve as resolvePath2 } from "node:path";
1198
+ import chalk7 from "chalk";
1189
1199
 
1190
1200
  // ../../packages/types/src/agents/index.ts
1191
1201
  var MICROVM_MAX_LIFETIME_MS = 8 * 60 * 6e4;
@@ -1206,6 +1216,7 @@ var TelemetryEventTypes = {
1206
1216
  // ../../packages/types/src/tunnel/index.ts
1207
1217
  var MAX_FRAME_BYTES = 256 * 1024;
1208
1218
  var TUNNEL_DRAIN_PING_PATH = "/__evident/drain";
1219
+ var TUNNEL_USAGE_REARM_PING_PATH = "/__evident/usage-rearm";
1209
1220
 
1210
1221
  // ../../packages/types/src/runner-files.ts
1211
1222
  var MAX_FILE_PUSH_BYTES = 64 * 1024;
@@ -1243,7 +1254,7 @@ function stripQuery(url) {
1243
1254
 
1244
1255
  // src/commands/run.ts
1245
1256
  import ora3 from "ora";
1246
- import { select as select3 } from "@inquirer/prompts";
1257
+ import { select as select4 } from "@inquirer/prompts";
1247
1258
 
1248
1259
  // src/lib/telemetry.ts
1249
1260
  var CLI_VERSION = (true ? "3.0.0" : void 0) ?? process.env.npm_package_version ?? "unknown";
@@ -1494,8 +1505,8 @@ function forwardRunnerActivity(entry, context) {
1494
1505
  }
1495
1506
 
1496
1507
  // src/lib/opencode/session-db-recovery-report.ts
1497
- import { readFileSync as readFileSync2, unlinkSync } from "fs";
1498
- import { join as join2 } from "path";
1508
+ import { readFileSync as readFileSync2, unlinkSync } from "node:fs";
1509
+ import { join as join2 } from "node:path";
1499
1510
  function sessionDbRecoveryReportPath(homeDir, env) {
1500
1511
  const override = env.EVIDENT_SESSION_DB_RECOVERY_REPORT?.trim();
1501
1512
  return override || join2(homeDir, ".local", "state", "evident", "session-db-recovery.jsonl");
@@ -1524,7 +1535,14 @@ function drainSessionDbRecoveryReport({
1524
1535
  skippedLines++;
1525
1536
  return [];
1526
1537
  }
1527
- return [value];
1538
+ return [
1539
+ {
1540
+ ...value,
1541
+ provenance_reason: value.provenance_reason ?? null,
1542
+ provenance_migration_delta: value.provenance_migration_delta ?? null,
1543
+ replication_suspended: value.replication_suspended ?? false
1544
+ }
1545
+ ];
1528
1546
  } catch (error2) {
1529
1547
  skippedLines++;
1530
1548
  console.error(
@@ -1549,12 +1567,39 @@ function buildSessionDbRecoveryActivity(record) {
1549
1567
  const level = record.severity === "warning" ? "warn" : record.severity === "error" ? "error" : null;
1550
1568
  if (!level) return null;
1551
1569
  const noVerifiedPoint = record.verified_restore_point ? ` The verified restore point is ${record.verified_restore_point}.` : " No verified restore point is known.";
1570
+ const replication = record.replication_suspended ? " This start is not backing up its new session history; restart after fixing the cause." : "";
1571
+ const giveupMessage = (() => {
1572
+ switch (record.reason) {
1573
+ case "restore_deadline_exceeded":
1574
+ 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.";
1575
+ case "restore_tool_unusable":
1576
+ case "classification_unrecognised":
1577
+ 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.";
1578
+ case "synchroniser_config_unevaluable":
1579
+ case "synchroniser_config_incomplete":
1580
+ 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.";
1581
+ case "synchroniser_config_unresolved":
1582
+ 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.";
1583
+ case "litestream_config_unavailable":
1584
+ 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.";
1585
+ case "classification_fatal":
1586
+ 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.";
1587
+ default:
1588
+ return null;
1589
+ }
1590
+ })();
1591
+ if (giveupMessage)
1592
+ return {
1593
+ level,
1594
+ metadata: withoutContractFields(record),
1595
+ message: `${giveupMessage}${replication}`
1596
+ };
1552
1597
  switch (record.outcome) {
1553
1598
  case "fresh_session_db":
1554
1599
  return {
1555
1600
  level,
1556
1601
  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.`
1602
+ 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
1603
  };
1559
1604
  case "restore_retried":
1560
1605
  return {
@@ -1592,7 +1637,7 @@ function buildSessionDbRecoveryActivity(record) {
1592
1637
  return {
1593
1638
  level,
1594
1639
  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."
1640
+ 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
1641
  };
1597
1642
  case "session_db_boot_refused":
1598
1643
  return {
@@ -1600,6 +1645,12 @@ function buildSessionDbRecoveryActivity(record) {
1600
1645
  metadata: withoutContractFields(record),
1601
1646
  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
1647
  };
1648
+ case "schema_provenance_mismatch":
1649
+ return {
1650
+ level,
1651
+ metadata: withoutContractFields(record),
1652
+ 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.`
1653
+ };
1603
1654
  default:
1604
1655
  return null;
1605
1656
  }
@@ -1614,7 +1665,8 @@ var OUTCOMES = /* @__PURE__ */ new Set([
1614
1665
  "fresh_session_db",
1615
1666
  "history_rolled_back",
1616
1667
  "restore_misconfigured",
1617
- "session_db_boot_refused"
1668
+ "session_db_boot_refused",
1669
+ "schema_provenance_mismatch"
1618
1670
  ]);
1619
1671
  var STAGES = /* @__PURE__ */ new Set(["restore", "verify"]);
1620
1672
  var SEVERITIES = /* @__PURE__ */ new Set(["warning", "error"]);
@@ -1632,7 +1684,7 @@ var STRING_OR_NULL_FIELDS = ["quarantine_destination", "verified_restore_point"]
1632
1684
  function isSessionDbRecoveryRecord(value) {
1633
1685
  if (!value || typeof value !== "object" || Array.isArray(value)) return false;
1634
1686
  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(
1687
+ 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
1688
  (field) => record[field] === null || typeof record[field] === "string"
1637
1689
  );
1638
1690
  }
@@ -1661,11 +1713,667 @@ async function waitForOpenCodeHealth(port, timeoutMs = 3e4) {
1661
1713
  if (health.healthy) {
1662
1714
  return health;
1663
1715
  }
1664
- await new Promise((resolve3) => setTimeout(resolve3, 1e3));
1716
+ await new Promise((resolve4) => setTimeout(resolve4, 1e3));
1665
1717
  }
1666
1718
  return { healthy: false, error: "Timeout waiting for OpenCode to be healthy" };
1667
1719
  }
1668
1720
 
1721
+ // src/lib/opencode/session-db-boot.ts
1722
+ import { spawn as spawn2 } from "node:child_process";
1723
+ import { mkdirSync, statSync as statSync2, unlinkSync as unlinkSync2, writeFileSync } from "node:fs";
1724
+ import { homedir as homedir2 } from "node:os";
1725
+ import { dirname as dirname2, resolve as resolvePath } from "node:path";
1726
+
1727
+ // src/lib/runner-synchroniser.ts
1728
+ import { spawn } from "node:child_process";
1729
+ function appendError(stderr, error2) {
1730
+ const message = error2 instanceof Error ? error2.message : String(error2);
1731
+ return stderr === "" ? message : `${stderr}
1732
+ ${message}`;
1733
+ }
1734
+ function runSynchroniser(args, opts) {
1735
+ return new Promise((resolve4) => {
1736
+ let child;
1737
+ let stdout = "";
1738
+ let stderr = "";
1739
+ let settled = false;
1740
+ const timer = {};
1741
+ let abortListener;
1742
+ let spawnListener;
1743
+ const finish = (result) => {
1744
+ if (settled) return;
1745
+ settled = true;
1746
+ if (timer.handle) clearTimeout(timer.handle);
1747
+ if (abortListener) opts.signal?.removeEventListener("abort", abortListener);
1748
+ if (spawnListener) child.removeListener("spawn", spawnListener);
1749
+ resolve4(result);
1750
+ };
1751
+ try {
1752
+ child = spawn("runner-synchroniser", args, {
1753
+ env: opts.env ?? process.env,
1754
+ stdio: ["ignore", "pipe", "pipe"]
1755
+ });
1756
+ } catch (error2) {
1757
+ finish({ code: null, stdout, stderr: appendError(stderr, error2), timedOut: false });
1758
+ return;
1759
+ }
1760
+ child.stdout?.setEncoding("utf8");
1761
+ child.stdout?.on("data", (chunk) => {
1762
+ stdout += chunk;
1763
+ });
1764
+ child.stderr?.setEncoding("utf8");
1765
+ child.stderr?.on("data", (chunk) => {
1766
+ stderr += chunk;
1767
+ });
1768
+ child.once("error", (error2) => {
1769
+ finish({ code: null, stdout, stderr: appendError(stderr, error2), timedOut: false });
1770
+ });
1771
+ child.once("close", (code) => {
1772
+ finish({ code, stdout, stderr, timedOut: false });
1773
+ });
1774
+ if (opts.signal) {
1775
+ const killChild = () => {
1776
+ if (child.pid === void 0) {
1777
+ if (!spawnListener) {
1778
+ spawnListener = killChild;
1779
+ child.once("spawn", spawnListener);
1780
+ }
1781
+ return;
1782
+ }
1783
+ child.kill("SIGKILL");
1784
+ };
1785
+ abortListener = killChild;
1786
+ if (opts.signal.aborted) {
1787
+ abortListener();
1788
+ } else {
1789
+ opts.signal.addEventListener("abort", abortListener, { once: true });
1790
+ if (opts.signal.aborted) abortListener();
1791
+ }
1792
+ }
1793
+ timer.handle = setTimeout(
1794
+ () => {
1795
+ child.kill("SIGKILL");
1796
+ finish({ code: null, stdout, stderr, timedOut: true });
1797
+ },
1798
+ Math.max(0, opts.timeoutMs)
1799
+ );
1800
+ });
1801
+ }
1802
+
1803
+ // src/lib/opencode/session-db-boot.ts
1804
+ var SESSION_DB_RESTORE_TIMEOUT_MS = 3e5;
1805
+ var SESSION_DB_VERIFY_TIMEOUT_MS = 12e4;
1806
+ var SESSION_DB_SYNCHRONISER_TIMEOUT_MS = 12e4;
1807
+ var SESSION_DB_VERIFY_WALKBACK_BUDGET_SECONDS = 120;
1808
+ function commandError(result) {
1809
+ return result.stderr.trim() || `process exited with code ${result.code ?? "null"}`;
1810
+ }
1811
+ function reportRecord(stage, outcome, reason, litestreamExitCode, options) {
1812
+ options.reportRecovery({
1813
+ v: 1,
1814
+ event: "session_db_recovery",
1815
+ at: (/* @__PURE__ */ new Date()).toISOString(),
1816
+ stage,
1817
+ outcome,
1818
+ severity: "error",
1819
+ reason,
1820
+ litestream_exit_code: litestreamExitCode,
1821
+ attempt: null,
1822
+ replica_objects: null,
1823
+ replica_bytes: null,
1824
+ quarantine_destination: null,
1825
+ quarantined_objects: null,
1826
+ quarantine_failed_objects: null,
1827
+ quarantined_bytes: null,
1828
+ verified_restore_point: null,
1829
+ restore_points_tried: null,
1830
+ provenance_reason: null,
1831
+ provenance_migration_delta: null,
1832
+ replication_suspended: stage === "restore"
1833
+ });
1834
+ }
1835
+ function clearMarker(options) {
1836
+ if (!options.noReplicateMarker) return;
1837
+ try {
1838
+ unlinkSync2(options.noReplicateMarker);
1839
+ } catch (error2) {
1840
+ if (error2 instanceof Error && "code" in error2 && error2.code === "ENOENT") return;
1841
+ options.log(
1842
+ `Could not clear the previous session-DB no-replicate marker ${options.noReplicateMarker}: ${error2 instanceof Error ? error2.message : String(error2)}`,
1843
+ "warn"
1844
+ );
1845
+ }
1846
+ }
1847
+ function markNoReplicate(options, message) {
1848
+ if (options.noReplicateMarker) {
1849
+ try {
1850
+ mkdirSync(dirname2(options.noReplicateMarker), { recursive: true });
1851
+ writeFileSync(options.noReplicateMarker, "");
1852
+ } catch (error2) {
1853
+ options.log(
1854
+ `Could not write session-DB no-replicate marker ${options.noReplicateMarker}: ${error2 instanceof Error ? error2.message : String(error2)}`,
1855
+ "error"
1856
+ );
1857
+ }
1858
+ }
1859
+ options.log(`SESSION-DB-NO-REPLICATE: ${message}`, "warn");
1860
+ }
1861
+ function discardSessionDbDebris(options) {
1862
+ for (const path of [options.dbPath, `${options.dbPath}-wal`, `${options.dbPath}-shm`]) {
1863
+ try {
1864
+ unlinkSync2(path);
1865
+ } catch (error2) {
1866
+ if (error2 instanceof Error && "code" in error2 && error2.code === "ENOENT") continue;
1867
+ options.log(
1868
+ `Could not remove session-DB debris ${path}: ${error2 instanceof Error ? error2.message : String(error2)}`,
1869
+ "warn"
1870
+ );
1871
+ }
1872
+ }
1873
+ }
1874
+ function splitDiagnostics(text) {
1875
+ return text.split("\n").map((line) => line.trim()).filter((line) => line.length > 0);
1876
+ }
1877
+ function logSynchroniserDiagnostics(result, options) {
1878
+ for (const line of splitDiagnostics(result.stderr)) options.log(line, "warn");
1879
+ }
1880
+ function parseSingleQuotedAssignment(line) {
1881
+ const match = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(line);
1882
+ if (!match || !match[2].startsWith("'")) return null;
1883
+ const valueSource = match[2];
1884
+ let value = "";
1885
+ for (let index = 1; index < valueSource.length; index++) {
1886
+ const character = valueSource[index];
1887
+ if (character !== "'") {
1888
+ value += character;
1889
+ continue;
1890
+ }
1891
+ if (index === valueSource.length - 1) return [match[1], value];
1892
+ if (valueSource.slice(index + 1, index + 4) !== "\\''") return null;
1893
+ value += "'";
1894
+ index += 3;
1895
+ }
1896
+ return null;
1897
+ }
1898
+ function parseSynchroniserEnv(stdout) {
1899
+ const values = {};
1900
+ for (const line of stdout.split("\n")) {
1901
+ if (line.trim() === "") continue;
1902
+ const assignment = parseSingleQuotedAssignment(line);
1903
+ if (!assignment) return null;
1904
+ values[assignment[0]] = assignment[1];
1905
+ }
1906
+ return values;
1907
+ }
1908
+ function runCommand(command, args, options) {
1909
+ return new Promise((resolve4) => {
1910
+ let child;
1911
+ let stdout = "";
1912
+ let stderr = "";
1913
+ let settled = false;
1914
+ const finish = (result) => {
1915
+ if (settled) return;
1916
+ settled = true;
1917
+ if (timer) clearTimeout(timer);
1918
+ resolve4(result);
1919
+ };
1920
+ try {
1921
+ child = spawn2(command, args, {
1922
+ env: options.env,
1923
+ stdio: ["ignore", "pipe", "pipe"]
1924
+ });
1925
+ } catch (error2) {
1926
+ resolve4({
1927
+ code: null,
1928
+ stdout,
1929
+ stderr: error2 instanceof Error ? error2.message : String(error2),
1930
+ timedOut: false
1931
+ });
1932
+ return;
1933
+ }
1934
+ child.stdout?.setEncoding("utf8");
1935
+ child.stdout?.on("data", (chunk) => {
1936
+ stdout += chunk;
1937
+ });
1938
+ child.stderr?.setEncoding("utf8");
1939
+ child.stderr?.on("data", (chunk) => {
1940
+ stderr += chunk;
1941
+ });
1942
+ child.once("error", (error2) => {
1943
+ finish({
1944
+ code: null,
1945
+ stdout,
1946
+ stderr: stderr === "" ? error2.message : `${stderr}
1947
+ ${error2.message}`,
1948
+ timedOut: false
1949
+ });
1950
+ });
1951
+ child.once("close", (code) => finish({ code, stdout, stderr, timedOut: false }));
1952
+ const timer = setTimeout(
1953
+ () => {
1954
+ child.kill("SIGKILL");
1955
+ finish({ code: null, stdout, stderr, timedOut: true });
1956
+ },
1957
+ Math.max(0, options.timeoutMs)
1958
+ );
1959
+ });
1960
+ }
1961
+ async function ensureLitestreamConfig(options, env) {
1962
+ const configPath = options.litestreamConfig;
1963
+ if (!configPath) {
1964
+ markNoReplicate(options, "no Litestream configuration path was provided");
1965
+ reportRecord(
1966
+ "restore",
1967
+ "restore_misconfigured",
1968
+ "litestream_config_unavailable",
1969
+ null,
1970
+ options
1971
+ );
1972
+ return null;
1973
+ }
1974
+ try {
1975
+ if (statSync2(configPath).size > 0) return configPath;
1976
+ } catch (error2) {
1977
+ if (!(error2 instanceof Error && "code" in error2 && error2.code === "ENOENT")) {
1978
+ options.log(
1979
+ `Could not inspect ${configPath}: ${error2 instanceof Error ? error2.message : String(error2)}`,
1980
+ "warn"
1981
+ );
1982
+ }
1983
+ }
1984
+ const rendered = await runSynchroniser(["litestream-config"], {
1985
+ timeoutMs: SESSION_DB_SYNCHRONISER_TIMEOUT_MS,
1986
+ env
1987
+ });
1988
+ logSynchroniserDiagnostics(rendered, options);
1989
+ if (rendered.timedOut || rendered.code !== 0) {
1990
+ options.log(
1991
+ `Could not generate ${configPath}: runner-synchroniser litestream-config failed (${commandError(rendered)})`,
1992
+ "error"
1993
+ );
1994
+ markNoReplicate(options, `could not generate ${configPath}`);
1995
+ reportRecord(
1996
+ "restore",
1997
+ "restore_misconfigured",
1998
+ "litestream_config_unavailable",
1999
+ null,
2000
+ options
2001
+ );
2002
+ return null;
2003
+ }
2004
+ try {
2005
+ mkdirSync(dirname2(configPath), { recursive: true });
2006
+ writeFileSync(configPath, rendered.stdout);
2007
+ } catch (error2) {
2008
+ options.log(
2009
+ `Could not write ${configPath}: ${error2 instanceof Error ? error2.message : String(error2)}`,
2010
+ "error"
2011
+ );
2012
+ markNoReplicate(options, `could not generate ${configPath}`);
2013
+ reportRecord(
2014
+ "restore",
2015
+ "restore_misconfigured",
2016
+ "litestream_config_unavailable",
2017
+ null,
2018
+ options
2019
+ );
2020
+ return null;
2021
+ }
2022
+ const version2 = await runCommand("litestream", ["version"], {
2023
+ env,
2024
+ timeoutMs: 1e4
2025
+ });
2026
+ const litestreamVersion = version2.code === 0 ? version2.stdout.trim() || "unknown" : "unknown";
2027
+ const regionEmpty = !/^\s*region:\s*\S+/m.test(rendered.stdout);
2028
+ options.log(
2029
+ `litestream ${litestreamVersion}; AWS_REGION=${env.AWS_REGION ?? "<unset>"} AWS_DEFAULT_REGION=${env.AWS_DEFAULT_REGION ?? "<unset>"}; rendered litestream.yml region empty: ${regionEmpty ? "yes" : "no"}`
2030
+ );
2031
+ return configPath;
2032
+ }
2033
+ function restoreGiveUp(options, reason, message, litestreamExitCode, outcome = "fresh_session_db") {
2034
+ discardSessionDbDebris(options);
2035
+ markNoReplicate(options, message);
2036
+ reportRecord("restore", outcome, reason, litestreamExitCode, options);
2037
+ }
2038
+ async function restoreSessionDb(options, configPath, env) {
2039
+ const restored = await runCommand(
2040
+ "litestream",
2041
+ ["restore", "-config", configPath, "-if-db-not-exists", "-if-replica-exists", options.dbPath],
2042
+ { env, timeoutMs: SESSION_DB_RESTORE_TIMEOUT_MS }
2043
+ );
2044
+ for (const line of splitDiagnostics(restored.stderr)) options.log(line, "warn");
2045
+ if (restored.timedOut || restored.code === 124 || restored.code === 137) {
2046
+ restoreGiveUp(
2047
+ options,
2048
+ "restore_deadline_exceeded",
2049
+ `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`,
2050
+ restored.code ?? 124
2051
+ );
2052
+ return;
2053
+ }
2054
+ if (restored.code === null || restored.code === 125 || restored.code === 126 || restored.code === 127) {
2055
+ options.log(`litestream restore could not run (${commandError(restored)})`, "error");
2056
+ restoreGiveUp(
2057
+ options,
2058
+ "restore_tool_unusable",
2059
+ `restore tool is broken (${commandError(restored)}); opencode starts with a fresh session DB and nothing is replicated this boot`,
2060
+ restored.code
2061
+ );
2062
+ return;
2063
+ }
2064
+ const classified = await runSynchroniser(
2065
+ [
2066
+ "session-db-classify",
2067
+ String(restored.code ?? 1),
2068
+ "1",
2069
+ "--on-unusable-replica=leave",
2070
+ "--fresh-db-fallback"
2071
+ ],
2072
+ { timeoutMs: SESSION_DB_SYNCHRONISER_TIMEOUT_MS, env }
2073
+ );
2074
+ logSynchroniserDiagnostics(classified, options);
2075
+ const classifyCode = classified.code;
2076
+ switch (classifyCode) {
2077
+ case 0:
2078
+ return;
2079
+ case 31:
2080
+ acknowledgeSessionDbRecoveryReport(sessionDbRecoveryReportPath(homedir2(), env));
2081
+ options.log(
2082
+ "SESSION-DB-REPLICA-UNUSABLE: booting with a fresh opencode.db and replicating into the existing prefix this boot",
2083
+ "warn"
2084
+ );
2085
+ return;
2086
+ case 32:
2087
+ acknowledgeSessionDbRecoveryReport(sessionDbRecoveryReportPath(homedir2(), env));
2088
+ discardSessionDbDebris(options);
2089
+ markNoReplicate(
2090
+ options,
2091
+ "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"
2092
+ );
2093
+ return;
2094
+ case 30:
2095
+ restoreGiveUp(
2096
+ options,
2097
+ "classification_fatal",
2098
+ "session-db-classify returned fatal (30); see the FATAL message above",
2099
+ restored.code,
2100
+ "restore_misconfigured"
2101
+ );
2102
+ return;
2103
+ default:
2104
+ restoreGiveUp(
2105
+ options,
2106
+ "classification_unrecognised",
2107
+ `session-db-classify exited ${classifyCode ?? "null"}, which is none of its documented answers`,
2108
+ restored.code
2109
+ );
2110
+ }
2111
+ }
2112
+ async function verifySessionDb(options, configPath, env) {
2113
+ if (!options.noReplicateMarker || !fileExists(options.noReplicateMarker)) {
2114
+ const result = await runSynchroniser(["session-db-verify", configPath], {
2115
+ timeoutMs: SESSION_DB_VERIFY_TIMEOUT_MS,
2116
+ env: {
2117
+ ...env,
2118
+ // The synchroniser reads this value in SECONDS. Keep this at 120, not
2119
+ // 120_000, so the walkback gives up before the outer process bound.
2120
+ EVIDENT_SESSION_DB_WALKBACK_BUDGET_SECONDS: String(
2121
+ SESSION_DB_VERIFY_WALKBACK_BUDGET_SECONDS
2122
+ )
2123
+ }
2124
+ });
2125
+ logSynchroniserDiagnostics(result, options);
2126
+ if (result.timedOut || result.code === 124 || result.code === 137) {
2127
+ options.log(
2128
+ `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`,
2129
+ "warn"
2130
+ );
2131
+ return false;
2132
+ }
2133
+ if (result.code === 34) {
2134
+ reportRecord(
2135
+ "verify",
2136
+ "session_db_boot_refused",
2137
+ result.stderr.includes("SESSION-DB-LOCAL-DISCARD-FAILED") ? "local_discard_failed" : "replica_separation_unproven",
2138
+ null,
2139
+ options
2140
+ );
2141
+ return true;
2142
+ }
2143
+ if (result.code === 33) {
2144
+ options.log(
2145
+ "SESSION-DB-INTEGRITY-EXHAUSTED: booting continues and litestream still replicates, starting an empty backup chain after the corrupt replica was separated.",
2146
+ "warn"
2147
+ );
2148
+ return false;
2149
+ }
2150
+ if (result.code !== 0) {
2151
+ options.log(
2152
+ `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`,
2153
+ "warn"
2154
+ );
2155
+ }
2156
+ return false;
2157
+ }
2158
+ options.log(
2159
+ "skipping session-DB verification: this boot's session DB was not proven safe to replicate",
2160
+ "debug"
2161
+ );
2162
+ return false;
2163
+ }
2164
+ function fileExists(path) {
2165
+ try {
2166
+ statSync2(path);
2167
+ return true;
2168
+ } catch (error2) {
2169
+ if (error2 instanceof Error && "code" in error2 && error2.code === "ENOENT") return false;
2170
+ return true;
2171
+ }
2172
+ }
2173
+ async function restoreAndVerifySessionDb(options) {
2174
+ const env = options.env ?? process.env;
2175
+ clearMarker(options);
2176
+ acknowledgeSessionDbRecoveryReport(sessionDbRecoveryReportPath(homedir2(), env));
2177
+ const synchroniserEnv = await runSynchroniser(["env"], {
2178
+ timeoutMs: SESSION_DB_SYNCHRONISER_TIMEOUT_MS,
2179
+ env
2180
+ });
2181
+ logSynchroniserDiagnostics(synchroniserEnv, options);
2182
+ if (synchroniserEnv.timedOut || synchroniserEnv.code !== 0) {
2183
+ options.log(
2184
+ `runner-synchroniser env could not resolve the session-DB configuration (${commandError(synchroniserEnv)})`,
2185
+ "error"
2186
+ );
2187
+ markNoReplicate(
2188
+ options,
2189
+ "could not resolve the runner-synchroniser configuration (see the ERROR above)"
2190
+ );
2191
+ reportRecord(
2192
+ "restore",
2193
+ "restore_misconfigured",
2194
+ "synchroniser_config_unresolved",
2195
+ null,
2196
+ options
2197
+ );
2198
+ return { verifyFatal: false };
2199
+ }
2200
+ const values = parseSynchroniserEnv(synchroniserEnv.stdout);
2201
+ if (!values) {
2202
+ markNoReplicate(
2203
+ options,
2204
+ "the runner-synchroniser configuration could not be evaluated; the installed bundle likely does not match this hook"
2205
+ );
2206
+ reportRecord(
2207
+ "restore",
2208
+ "restore_misconfigured",
2209
+ "synchroniser_config_unevaluable",
2210
+ null,
2211
+ options
2212
+ );
2213
+ return { verifyFatal: false };
2214
+ }
2215
+ const synchroniserDbPath = values.OPENCODE_DB_PATH;
2216
+ if (!synchroniserDbPath) {
2217
+ markNoReplicate(
2218
+ options,
2219
+ "run_synchroniser env did not define OPENCODE_DB_PATH; the installed runner-synchroniser build likely does not match this hook"
2220
+ );
2221
+ reportRecord(
2222
+ "restore",
2223
+ "restore_misconfigured",
2224
+ "synchroniser_config_incomplete",
2225
+ null,
2226
+ options
2227
+ );
2228
+ return { verifyFatal: false };
2229
+ }
2230
+ if (resolvePath(synchroniserDbPath) !== resolvePath(options.dbPath)) {
2231
+ options.log(
2232
+ `runner-synchroniser reported OPENCODE_DB_PATH=${synchroniserDbPath}, but OpenCode uses ${options.dbPath}; continuing with OpenCode's session-DB path`,
2233
+ "warn"
2234
+ );
2235
+ }
2236
+ if (!values.PERSISTENCE_BUCKET) {
2237
+ options.log(
2238
+ "SESSION-DB-PERSISTENCE-DISABLED: LITESTREAM_BUCKET/LITESTREAM_PREFIX are not both set; opencode starts with a fresh session DB and nothing is replicated.",
2239
+ "warn"
2240
+ );
2241
+ return { verifyFatal: false };
2242
+ }
2243
+ const configPath = await ensureLitestreamConfig(options, env);
2244
+ if (!configPath) return { verifyFatal: false };
2245
+ await restoreSessionDb(options, configPath, env);
2246
+ if (options.noReplicateMarker && fileExists(options.noReplicateMarker)) {
2247
+ return { verifyFatal: false };
2248
+ }
2249
+ return { verifyFatal: await verifySessionDb(options, configPath, env) };
2250
+ }
2251
+
2252
+ // src/lib/opencode/session-db-provenance.ts
2253
+ import { createRequire } from "node:module";
2254
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "node:fs";
2255
+ import { dirname as dirname3, join as join3 } from "node:path";
2256
+ var require2 = createRequire(import.meta.url);
2257
+ function readSessionDbMigrationIds(dbPath) {
2258
+ let db;
2259
+ try {
2260
+ const { DatabaseSync } = require2("node:sqlite");
2261
+ db = new DatabaseSync(dbPath, { readOnly: true });
2262
+ const columns = db.prepare("PRAGMA table_info(migration)").all();
2263
+ const hasExpectedShape = columns.length === 2 && columns.some(
2264
+ (column) => column.name === "id" && typeof column.type === "string" && column.type.toUpperCase() === "TEXT" && column.pk === 1
2265
+ ) && columns.some(
2266
+ (column) => column.name === "time_completed" && typeof column.type === "string" && column.type.toUpperCase() === "INTEGER" && column.notnull === 1 && column.pk === 0
2267
+ );
2268
+ if (!hasExpectedShape) {
2269
+ console.warn(`[readSessionDbMigrationIds] unsupported migration table shape in ${dbPath}`);
2270
+ return null;
2271
+ }
2272
+ const rows = db.prepare("SELECT id FROM migration ORDER BY id").all();
2273
+ if (rows.some((row) => typeof row.id !== "string")) return null;
2274
+ return rows.map((row) => row.id);
2275
+ } catch (error2) {
2276
+ console.warn(
2277
+ `[readSessionDbMigrationIds] could not read migration history from ${dbPath}: ${error2 instanceof Error ? error2.message : String(error2)}`
2278
+ );
2279
+ return null;
2280
+ } finally {
2281
+ try {
2282
+ db?.close();
2283
+ } catch (error2) {
2284
+ console.warn(
2285
+ `[readSessionDbMigrationIds] could not close ${dbPath}: ${error2 instanceof Error ? error2.message : String(error2)}`
2286
+ );
2287
+ }
2288
+ }
2289
+ }
2290
+ function sessionDbProvenanceStatePath(homeDir, env) {
2291
+ const override = env.EVIDENT_SESSION_DB_PROVENANCE_STATE?.trim();
2292
+ return override || join3(homeDir, ".local", "state", "evident", "session-db-provenance.json");
2293
+ }
2294
+ function loadSessionDbProvenanceState(path) {
2295
+ let value;
2296
+ try {
2297
+ value = JSON.parse(readFileSync3(path, "utf8"));
2298
+ } catch (error2) {
2299
+ if (error2 instanceof Error && "code" in error2 && error2.code === "ENOENT") return {};
2300
+ console.error(
2301
+ `[session-db-provenance] could not read ${path}: ${error2 instanceof Error ? error2.message : String(error2)}`
2302
+ );
2303
+ return {};
2304
+ }
2305
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
2306
+ console.error(`[session-db-provenance] ignored malformed state in ${path}`);
2307
+ return {};
2308
+ }
2309
+ const state = {};
2310
+ for (const [dbPath, record] of Object.entries(value)) {
2311
+ if (!isSessionDbProvenanceRecord(record)) {
2312
+ console.error(`[session-db-provenance] ignored malformed state in ${path}`);
2313
+ return {};
2314
+ }
2315
+ state[dbPath] = record;
2316
+ }
2317
+ return state;
2318
+ }
2319
+ function saveSessionDbProvenanceState(path, state) {
2320
+ try {
2321
+ mkdirSync2(dirname3(path), { recursive: true });
2322
+ writeFileSync2(path, `${JSON.stringify(state, null, 2)}
2323
+ `, "utf8");
2324
+ } catch (error2) {
2325
+ console.error(
2326
+ `[session-db-provenance] could not write ${path}: ${error2 instanceof Error ? error2.message : String(error2)}`
2327
+ );
2328
+ }
2329
+ }
2330
+ function evaluateSessionDbProvenance(input) {
2331
+ const { currentVersion, currentIds, previous } = input;
2332
+ if (!previous) return { anomaly: false, reason: null };
2333
+ const current = new Set(currentIds);
2334
+ const prior = new Set(previous.migrationIds);
2335
+ for (const id of prior) {
2336
+ if (!current.has(id)) return { anomaly: true, reason: "migration-history-regressed" };
2337
+ }
2338
+ if (current.size > prior.size && previous.opencodeVersion === currentVersion) {
2339
+ return { anomaly: true, reason: "foreign-version-migrations" };
2340
+ }
2341
+ return { anomaly: false, reason: null };
2342
+ }
2343
+ function checkSessionDbProvenance(input) {
2344
+ const { dbPath, currentVersion, homeDir, env } = input;
2345
+ const path = sessionDbProvenanceStatePath(homeDir, env);
2346
+ const state = loadSessionDbProvenanceState(path);
2347
+ const previous = state[dbPath];
2348
+ const currentIds = readSessionDbMigrationIds(dbPath);
2349
+ if (currentIds === null) {
2350
+ return {
2351
+ anomaly: false,
2352
+ reason: null,
2353
+ recordedVersion: previous?.opencodeVersion ?? null,
2354
+ migrationDelta: null
2355
+ };
2356
+ }
2357
+ const decision = evaluateSessionDbProvenance({ currentVersion, currentIds, previous });
2358
+ const migrationDelta = previous ? new Set(currentIds).size - new Set(previous.migrationIds).size : null;
2359
+ state[dbPath] = {
2360
+ opencodeVersion: currentVersion,
2361
+ migrationIds: currentIds,
2362
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
2363
+ };
2364
+ saveSessionDbProvenanceState(path, state);
2365
+ return {
2366
+ ...decision,
2367
+ recordedVersion: previous?.opencodeVersion ?? null,
2368
+ migrationDelta
2369
+ };
2370
+ }
2371
+ function isSessionDbProvenanceRecord(value) {
2372
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
2373
+ const record = value;
2374
+ return typeof record.opencodeVersion === "string" && Array.isArray(record.migrationIds) && record.migrationIds.every((id) => typeof id === "string") && typeof record.updatedAt === "string";
2375
+ }
2376
+
1669
2377
  // src/lib/opencode/opencode-version-gate.ts
1670
2378
  var QUEUE_VALIDATED_OPENCODE_VERSIONS = ["1.17.11", "1.18.3"];
1671
2379
  function isQueueValidatedVersion(version2) {
@@ -1680,7 +2388,7 @@ function buildOpenCodeVersionWarning(version2) {
1680
2388
  }
1681
2389
 
1682
2390
  // src/lib/opencode/process.ts
1683
- import { execSync, spawn } from "child_process";
2391
+ import { execSync, spawn as spawn3 } from "child_process";
1684
2392
 
1685
2393
  // src/lib/process-stop.ts
1686
2394
  async function stopProcessAndWait(child, timeoutMs, sendTerm, sendKill) {
@@ -1690,7 +2398,7 @@ async function stopProcessAndWait(child, timeoutMs, sendTerm, sendKill) {
1690
2398
  if (child.exitCode !== null || child.signalCode !== null) {
1691
2399
  return { outcome: "exited", code: child.exitCode, signal: child.signalCode };
1692
2400
  }
1693
- return new Promise((resolve3, reject) => {
2401
+ return new Promise((resolve4, reject) => {
1694
2402
  let forced = false;
1695
2403
  let settled = false;
1696
2404
  const timer = setTimeout(() => {
@@ -1710,7 +2418,7 @@ async function stopProcessAndWait(child, timeoutMs, sendTerm, sendKill) {
1710
2418
  settled = true;
1711
2419
  clearTimeout(timer);
1712
2420
  child.removeListener("exit", onExit);
1713
- resolve3(result);
2421
+ resolve4(result);
1714
2422
  };
1715
2423
  const fail = (error2) => {
1716
2424
  if (settled) return;
@@ -1786,14 +2494,14 @@ function findAvailablePort(startPort, maxAttempts = 10) {
1786
2494
  }
1787
2495
  return null;
1788
2496
  }
1789
- function findOpenCodeProcesses() {
2497
+ function findProcessesByPattern(pgrepPattern, psPattern) {
1790
2498
  const instances = [];
1791
2499
  try {
1792
2500
  const platform = process.platform;
1793
2501
  if (platform === "darwin" || platform === "linux") {
1794
2502
  let pids = [];
1795
2503
  try {
1796
- const pgrepOutput = execSync('pgrep -f "opencode serve|opencode-serve"', {
2504
+ const pgrepOutput = execSync(`pgrep -f "${pgrepPattern}"`, {
1797
2505
  encoding: "utf-8",
1798
2506
  stdio: ["pipe", "pipe", "pipe"]
1799
2507
  }).trim();
@@ -1802,7 +2510,7 @@ function findOpenCodeProcesses() {
1802
2510
  }
1803
2511
  } catch {
1804
2512
  try {
1805
- const psOutput = execSync('ps aux | grep -E "opencode (serve|--port)" | grep -v grep', {
2513
+ const psOutput = execSync(`ps aux | grep -E "${psPattern}" | grep -v grep`, {
1806
2514
  encoding: "utf-8",
1807
2515
  stdio: ["pipe", "pipe", "pipe"]
1808
2516
  }).trim();
@@ -1848,6 +2556,9 @@ function findOpenCodeProcesses() {
1848
2556
  }
1849
2557
  return instances;
1850
2558
  }
2559
+ function findOpenCodeProcesses() {
2560
+ return findProcessesByPattern("opencode serve|opencode-serve", "opencode (serve|--port)");
2561
+ }
1851
2562
  async function scanPortsForOpenCode() {
1852
2563
  const instances = [];
1853
2564
  const checks = OPENCODE_PORT_RANGE.map(async (port) => {
@@ -1892,18 +2603,27 @@ async function findHealthyOpenCodeInstances() {
1892
2603
  }
1893
2604
  return healthy;
1894
2605
  }
1895
- async function startOpenCode(port) {
2606
+ async function startOpenCode(port, options = {}) {
1896
2607
  let command = "opencode";
1897
- let args = ["serve", "--port", port.toString(), "--hostname", "127.0.0.1"];
2608
+ const printLogs = options.inheritStdio ? ["--print-logs"] : [];
2609
+ let args = ["serve", "--port", port.toString(), "--hostname", "127.0.0.1", ...printLogs];
1898
2610
  try {
1899
2611
  execSync("which opencode", { stdio: "ignore" });
1900
2612
  } catch {
1901
2613
  command = "npx";
1902
- args = ["opencode", "serve", "--port", port.toString(), "--hostname", "127.0.0.1"];
1903
- }
1904
- const child = spawn(command, args, {
2614
+ args = [
2615
+ "opencode",
2616
+ "serve",
2617
+ "--port",
2618
+ port.toString(),
2619
+ "--hostname",
2620
+ "127.0.0.1",
2621
+ ...printLogs
2622
+ ];
2623
+ }
2624
+ const child = spawn3(command, args, {
1905
2625
  detached: true,
1906
- stdio: "ignore",
2626
+ stdio: options.inheritStdio ? "inherit" : "ignore",
1907
2627
  cwd: process.cwd()
1908
2628
  });
1909
2629
  return child;
@@ -1942,6 +2662,19 @@ function isOpenCodeInstalled() {
1942
2662
  return false;
1943
2663
  }
1944
2664
  }
2665
+ function isOpenCode2Installed() {
2666
+ try {
2667
+ const platform = process.platform;
2668
+ if (platform === "win32") {
2669
+ execSync2("where opencode2", { stdio: "ignore" });
2670
+ } else {
2671
+ execSync2("which opencode2", { stdio: "ignore" });
2672
+ }
2673
+ return true;
2674
+ } catch {
2675
+ return false;
2676
+ }
2677
+ }
1945
2678
  async function promptOpenCodeInstall(interactive) {
1946
2679
  if (!interactive) {
1947
2680
  console.log(
@@ -1951,7 +2684,11 @@ async function promptOpenCodeInstall(interactive) {
1951
2684
  install_url: OPENCODE_INSTALL_URL,
1952
2685
  install_commands: {
1953
2686
  npm: "npm install -g opencode-ai",
1954
- curl: "curl -fsSL https://opencode.ai/install.sh | sh"
2687
+ curl: "curl -fsSL https://opencode.ai/install.sh | sh",
2688
+ v2: {
2689
+ npm: "npm install -g @opencode-ai/cli@beta",
2690
+ curl: "curl -fsSL https://opencode.ai/v2/install | bash"
2691
+ }
1955
2692
  }
1956
2693
  })
1957
2694
  );
@@ -2208,6 +2945,7 @@ async function createOpenCodeSession(port, directory) {
2208
2945
  return data.id;
2209
2946
  }
2210
2947
  async function getModelAttachmentCapability(port, model) {
2948
+ const { model: baseModel } = splitModelVariant(model);
2211
2949
  try {
2212
2950
  const res = await timedFetch(`${opencodeBase(port)}/config/providers`);
2213
2951
  if (!res.ok) {
@@ -2224,9 +2962,9 @@ async function getModelAttachmentCapability(port, model) {
2224
2962
  );
2225
2963
  return null;
2226
2964
  }
2227
- const slash = model ? model.indexOf("/") : -1;
2228
- const providerId = slash > 0 ? model.slice(0, slash) : void 0;
2229
- let modelId = slash > 0 ? model.slice(slash + 1) : void 0;
2965
+ const slash = baseModel ? baseModel.indexOf("/") : -1;
2966
+ const providerId = slash > 0 ? baseModel.slice(0, slash) : void 0;
2967
+ let modelId = slash > 0 ? baseModel.slice(slash + 1) : void 0;
2230
2968
  const defaults2 = body?.default && typeof body.default === "object" ? body.default : void 0;
2231
2969
  let provider = providerId ? providers.find((p) => p?.id === providerId) : void 0;
2232
2970
  if (!provider && !providerId) {
@@ -2306,6 +3044,29 @@ async function buildFileParts(attachments, capable) {
2306
3044
  }
2307
3045
  return { parts, outcomes, capabilityUnknown };
2308
3046
  }
3047
+ function splitModelVariant(raw) {
3048
+ const value = raw?.trim();
3049
+ if (!value) return {};
3050
+ const hashIndex = value.indexOf("#");
3051
+ if (hashIndex === -1) return { model: value };
3052
+ const model = value.slice(0, hashIndex).trim() || void 0;
3053
+ const variant = value.slice(hashIndex + 1).trim() || void 0;
3054
+ return { model, variant };
3055
+ }
3056
+ function applyModelOptions(body, options) {
3057
+ if (options?.agent) body.agent = options.agent;
3058
+ const { model, variant } = splitModelVariant(options?.model);
3059
+ if (model) {
3060
+ const slashIndex = model.indexOf("/");
3061
+ if (slashIndex !== -1) {
3062
+ body.model = {
3063
+ providerID: model.substring(0, slashIndex),
3064
+ modelID: model.substring(slashIndex + 1)
3065
+ };
3066
+ }
3067
+ }
3068
+ if (variant) body.variant = variant;
3069
+ }
2309
3070
  function messageText(m) {
2310
3071
  if (!m || !Array.isArray(m.parts)) return "";
2311
3072
  return m.parts.filter((p) => p.type === "text" && typeof p.text === "string").map((p) => p.text).join("");
@@ -2330,18 +3091,7 @@ async function sendPromptAsync(port, sessionId, content, options, attachments) {
2330
3091
  const body = {
2331
3092
  parts
2332
3093
  };
2333
- if (options?.agent) {
2334
- body.agent = options.agent;
2335
- }
2336
- if (options?.model) {
2337
- const slashIndex = options.model.indexOf("/");
2338
- if (slashIndex !== -1) {
2339
- body.model = {
2340
- providerID: options.model.substring(0, slashIndex),
2341
- modelID: options.model.substring(slashIndex + 1)
2342
- };
2343
- }
2344
- }
3094
+ applyModelOptions(body, options);
2345
3095
  const res = await timedFetch(`${opencodeBase(port)}/session/${sessionId}/prompt_async`, {
2346
3096
  method: "POST",
2347
3097
  headers: { "Content-Type": "application/json" },
@@ -2349,7 +3099,10 @@ async function sendPromptAsync(port, sessionId, content, options, attachments) {
2349
3099
  });
2350
3100
  if (res.status < 200 || res.status >= 300) {
2351
3101
  const text = await res.text().catch(() => "");
2352
- throw new Error(`OpenCode prompt_async failed: HTTP ${res.status}${text ? `: ${text}` : ""}`);
3102
+ const { variant } = splitModelVariant(options?.model);
3103
+ throw new Error(
3104
+ `OpenCode prompt_async failed: HTTP ${res.status}${text ? `: ${text}` : ""}${variant ? ` (variant: ${variant})` : ""}`
3105
+ );
2353
3106
  }
2354
3107
  const READ_BACK_ATTEMPTS = 5;
2355
3108
  const READ_BACK_DELAY_MS = 150;
@@ -2373,7 +3126,7 @@ async function sendPromptAsync(port, sessionId, content, options, attachments) {
2373
3126
  }
2374
3127
  }
2375
3128
  if (attempt < READ_BACK_ATTEMPTS - 1) {
2376
- await new Promise((resolve3) => setTimeout(resolve3, READ_BACK_DELAY_MS));
3129
+ await new Promise((resolve4) => setTimeout(resolve4, READ_BACK_DELAY_MS));
2377
3130
  }
2378
3131
  }
2379
3132
  return null;
@@ -2419,6 +3172,44 @@ function findLastAssistantReplyFor(messages, userMessageId) {
2419
3172
  }
2420
3173
  return lastOk ?? last;
2421
3174
  }
3175
+ function collectSubagentSessions(messages, userMessageId) {
3176
+ if (!messages || messages.length === 0) return [];
3177
+ const byParent = messages.filter(
3178
+ (message) => roleOf(message) === "assistant" && parentIdOf(message) === userMessageId
3179
+ );
3180
+ const assistants = byParent.length > 0 ? byParent : [];
3181
+ if (assistants.length === 0) {
3182
+ const userIndex = messages.findIndex((message) => idOf(message) === userMessageId);
3183
+ if (userIndex === -1) return [];
3184
+ for (let i = userIndex + 1; i < messages.length; i++) {
3185
+ const message = messages[i];
3186
+ if (roleOf(message) === "user") break;
3187
+ if (roleOf(message) === "assistant") assistants.push(message);
3188
+ }
3189
+ }
3190
+ const refs = [];
3191
+ const seen = /* @__PURE__ */ new Set();
3192
+ for (const message of assistants) {
3193
+ const parts = Array.isArray(message.parts) ? message.parts : [];
3194
+ for (const part of parts) {
3195
+ if (!part || typeof part !== "object" || part.type !== "tool" || part.tool !== "task")
3196
+ continue;
3197
+ const state = part.state;
3198
+ if (!state || typeof state !== "object") continue;
3199
+ const metadata = state.metadata;
3200
+ if (!metadata || typeof metadata !== "object") continue;
3201
+ const sessionId = metadata.sessionId;
3202
+ if (typeof sessionId !== "string" || sessionId.length === 0 || seen.has(sessionId)) continue;
3203
+ seen.add(sessionId);
3204
+ const start = state.time?.start;
3205
+ refs.push({
3206
+ sessionId,
3207
+ startedAtMs: typeof start === "number" && Number.isFinite(start) ? start : null
3208
+ });
3209
+ }
3210
+ }
3211
+ return refs;
3212
+ }
2422
3213
  function messageUsage(messages, userMessageId) {
2423
3214
  if (!messages || messages.length === 0) return null;
2424
3215
  const byParentAll = messages.filter(
@@ -2547,8 +3338,7 @@ function isAbortedTerminalReply(messages, userMessageId) {
2547
3338
  }
2548
3339
  return false;
2549
3340
  }
2550
- function messageFailure(messages, userMessageId) {
2551
- const reply = findLastAssistantReplyFor(messages, userMessageId);
3341
+ function classifyReplyAuthError(reply) {
2552
3342
  const error2 = errorOf(reply);
2553
3343
  if (error2 == null || typeof error2 !== "object") return null;
2554
3344
  const e = error2;
@@ -2573,6 +3363,32 @@ function messageFailure(messages, userMessageId) {
2573
3363
  }
2574
3364
  return null;
2575
3365
  }
3366
+ function messageFailure(messages, userMessageId) {
3367
+ return classifyReplyAuthError(findLastAssistantReplyFor(messages, userMessageId));
3368
+ }
3369
+ function findLatestSubagentAuthOutcome(messages, sinceMs) {
3370
+ if (!messages || messages.length === 0) return null;
3371
+ for (let i = messages.length - 1; i >= 0; i--) {
3372
+ const message = messages[i];
3373
+ if (roleOf(message) !== "assistant") continue;
3374
+ const created = createdOf(message);
3375
+ if (sinceMs !== null && typeof created === "number" && created < sinceMs) continue;
3376
+ const failure = classifyReplyAuthError(message);
3377
+ if (failure) {
3378
+ if (!failure.providerId) return null;
3379
+ return { providerId: failure.providerId, outcome: "failed", failure };
3380
+ }
3381
+ const providerId = message.info?.providerID;
3382
+ if (errorOf(message) == null && typeof providerId === "string" && providerId.length > 0) {
3383
+ return { providerId, outcome: "succeeded" };
3384
+ }
3385
+ return null;
3386
+ }
3387
+ return null;
3388
+ }
3389
+ function findSubagentAuthOutcome(messages, sinceMs) {
3390
+ return findLatestSubagentAuthOutcome(messages, sinceMs);
3391
+ }
2576
3392
  function applyZeroProviderFallback(classified, hasConfiguredProvider, replyProviderId, replyModelId = null) {
2577
3393
  if (classified != null) return classified;
2578
3394
  if (hasConfiguredProvider !== false) return null;
@@ -2726,13 +3542,13 @@ function resolveSessionCleanupConfig(flags, env = process.env) {
2726
3542
  }
2727
3543
 
2728
3544
  // src/lib/opencode/session-db-size.ts
2729
- import { statSync as statSync2 } from "fs";
2730
- import { join as join3 } from "path";
3545
+ import { statSync as statSync3 } from "node:fs";
3546
+ import { join as join4 } from "node:path";
2731
3547
  var LARGE_DB_THRESHOLD_BYTES = 268435456;
2732
3548
  function statSessionDbBytes(homeDir) {
2733
- const dbPath = join3(homeDir, ".local", "share", "opencode", "opencode.db");
3549
+ const dbPath = join4(homeDir, ".local", "share", "opencode", "opencode.db");
2734
3550
  try {
2735
- return statSync2(dbPath).size;
3551
+ return statSync3(dbPath).size;
2736
3552
  } catch (err) {
2737
3553
  const isMissingFile = err instanceof Error && "code" in err && err.code === "ENOENT";
2738
3554
  if (!isMissingFile) {
@@ -2758,11 +3574,15 @@ function buildSessionStoreSizeWarning(input) {
2758
3574
  }
2759
3575
 
2760
3576
  // src/lib/opencode/session-db-reclaim.ts
2761
- import { statSync as statSync3, statfsSync } from "fs";
2762
- import { dirname as dirname2 } from "path";
3577
+ import { statSync as statSync4, statfsSync } from "node:fs";
3578
+ import { dirname as dirname4 } from "node:path";
3579
+ function errorMessage(error2) {
3580
+ if (!(error2 instanceof Error)) return String(error2);
3581
+ return error2.cause instanceof Error ? error2.cause.message : error2.message;
3582
+ }
2763
3583
  function insufficientSpaceReason(dbPath, requiredBytes) {
2764
3584
  try {
2765
- const fsStats = statfsSync(dirname2(dbPath));
3585
+ const fsStats = statfsSync(dirname4(dbPath));
2766
3586
  const availableBytes = fsStats.bavail * fsStats.bsize;
2767
3587
  if (availableBytes < requiredBytes) {
2768
3588
  return `only ${availableBytes} bytes free, need ${requiredBytes} for a second copy`;
@@ -2785,17 +3605,17 @@ async function probeReclaimAvailability(input) {
2785
3605
  const { dbPath, requiredBytes } = input;
2786
3606
  let sqlite;
2787
3607
  try {
2788
- sqlite = await import("sqlite");
3608
+ sqlite = await import("node:sqlite");
2789
3609
  } catch (err) {
2790
- console.warn(
2791
- `[probeReclaimAvailability] node:sqlite unavailable for ${dbPath}: ${err instanceof Error ? err.message : String(err)}`
2792
- );
2793
- return "sqlite-unavailable";
3610
+ const detail = `Node ${process.version}: ${errorMessage(err)}`;
3611
+ console.warn(`[probeReclaimAvailability] node:sqlite unavailable for ${dbPath}: ` + detail);
3612
+ return { reason: "sqlite-unavailable", detail };
2794
3613
  }
2795
3614
  let autoVacuum = null;
2796
3615
  try {
2797
3616
  const db = new sqlite.DatabaseSync(dbPath, { readOnly: true });
2798
3617
  try {
3618
+ db.exec("PRAGMA busy_timeout=5000");
2799
3619
  autoVacuum = db.prepare("PRAGMA auto_vacuum").get().auto_vacuum;
2800
3620
  } finally {
2801
3621
  db.close();
@@ -2806,23 +3626,25 @@ async function probeReclaimAvailability(input) {
2806
3626
  );
2807
3627
  }
2808
3628
  if (autoVacuum !== 0) return null;
2809
- return insufficientSpaceReason(dbPath, requiredBytes) !== null ? "insufficient-disk-space" : null;
3629
+ return insufficientSpaceReason(dbPath, requiredBytes) !== null ? { reason: "insufficient-disk-space" } : null;
2810
3630
  }
2811
3631
  async function reclaimSessionDbSpace(input) {
2812
3632
  const { dbPath, maxPages, allowFullVacuum = true } = input;
2813
3633
  let sqlite;
2814
3634
  try {
2815
- sqlite = await import("sqlite");
3635
+ sqlite = await import("node:sqlite");
2816
3636
  } catch (err) {
3637
+ const detail = `Node ${process.version}: ${errorMessage(err)}`;
2817
3638
  console.warn(
2818
- `[reclaimSessionDbSpace] node:sqlite unavailable (need Node >=22.5, >=22.13 unflagged) for ${dbPath}: ${err instanceof Error ? err.message : String(err)}`
3639
+ `[reclaimSessionDbSpace] node:sqlite unavailable (need Node >=22.5, >=22.13 unflagged) for ${dbPath}: ${detail}`
2819
3640
  );
2820
- return { ok: false, skipped: "sqlite-unavailable" };
3641
+ return { ok: false, skipped: "sqlite-unavailable", detail };
2821
3642
  }
2822
3643
  const { DatabaseSync } = sqlite;
2823
3644
  let db;
2824
3645
  try {
2825
3646
  db = new DatabaseSync(dbPath);
3647
+ db.exec("PRAGMA busy_timeout=5000");
2826
3648
  const autoVacuum = db.prepare("PRAGMA auto_vacuum").get().auto_vacuum;
2827
3649
  if (autoVacuum === 0) {
2828
3650
  if (!allowFullVacuum) {
@@ -2831,7 +3653,7 @@ async function reclaimSessionDbSpace(input) {
2831
3653
  );
2832
3654
  return { ok: false, skipped: "full-vacuum-blocked" };
2833
3655
  }
2834
- const fileBytesForGuard = statSync3(dbPath).size;
3656
+ const fileBytesForGuard = statSync4(dbPath).size;
2835
3657
  const skipReason = insufficientSpaceReason(dbPath, fileBytesForGuard);
2836
3658
  if (skipReason !== null) {
2837
3659
  console.warn(
@@ -2859,10 +3681,12 @@ async function reclaimSessionDbSpace(input) {
2859
3681
  );
2860
3682
  return { ok: false, skipped: "auto-vacuum-not-applicable" };
2861
3683
  } catch (err) {
2862
- console.error(
2863
- `[reclaimSessionDbSpace] reclaim failed for ${dbPath}: ${err instanceof Error ? err.message : String(err)}`
2864
- );
2865
- return { ok: false, skipped: "reclaim-error" };
3684
+ console.error(`[reclaimSessionDbSpace] reclaim failed for ${dbPath}: ` + errorMessage(err));
3685
+ return {
3686
+ ok: false,
3687
+ skipped: "reclaim-error",
3688
+ detail: errorMessage(err)
3689
+ };
2866
3690
  } finally {
2867
3691
  db?.close();
2868
3692
  }
@@ -2903,7 +3727,6 @@ var StreamForwarder = class {
2903
3727
  handleFrame(frame) {
2904
3728
  switch (frame.type) {
2905
3729
  case "open":
2906
- this.callbacks.onOpen?.(frame.sid, frame.method, frame.path);
2907
3730
  void this.handleOpen(frame);
2908
3731
  break;
2909
3732
  case "req_data":
@@ -2939,12 +3762,21 @@ var StreamForwarder = class {
2939
3762
  const { sid, method, path, headers, has_body } = frame;
2940
3763
  const correlationId = headers?.[CORRELATION_ID_HEADER];
2941
3764
  const startedAt = Date.now();
3765
+ if (path !== TUNNEL_DRAIN_PING_PATH && path !== TUNNEL_USAGE_REARM_PING_PATH) {
3766
+ this.callbacks.onOpen?.(sid, method, path);
3767
+ }
2942
3768
  if (path === TUNNEL_DRAIN_PING_PATH) {
2943
3769
  this.callbacks.onDrainPing?.();
2944
3770
  this.send({ type: "head", sid, status: 204, headers: {} });
2945
3771
  this.send({ type: "res_end", sid });
2946
3772
  return;
2947
3773
  }
3774
+ if (path === TUNNEL_USAGE_REARM_PING_PATH) {
3775
+ this.callbacks.onUsageRearmPing?.();
3776
+ this.send({ type: "head", sid, status: 204, headers: {} });
3777
+ this.send({ type: "res_end", sid });
3778
+ return;
3779
+ }
2948
3780
  if (process.env.DEBUG) {
2949
3781
  log("debug", "agent_request", {
2950
3782
  correlation_id: correlationId,
@@ -2959,12 +3791,12 @@ var StreamForwarder = class {
2959
3791
  let endBody;
2960
3792
  if (has_body) {
2961
3793
  const chunks = [];
2962
- bodyPromise = new Promise((resolve3) => {
3794
+ bodyPromise = new Promise((resolve4) => {
2963
3795
  pushBody = (buf) => {
2964
3796
  chunks.push(buf);
2965
3797
  };
2966
3798
  endBody = () => {
2967
- resolve3(Buffer.concat(chunks));
3799
+ resolve4(Buffer.concat(chunks));
2968
3800
  };
2969
3801
  });
2970
3802
  }
@@ -3089,11 +3921,12 @@ function connectTunnel(options) {
3089
3921
  onResponse,
3090
3922
  onInfo,
3091
3923
  onWarning,
3092
- onDrainPing
3924
+ onDrainPing,
3925
+ onUsageRearmPing
3093
3926
  } = options;
3094
3927
  const tunnelUrl = getTunnelUrlConfig();
3095
3928
  const url = `${tunnelUrl}/tunnel/${agentId}/connect`;
3096
- return new Promise((resolve3, reject) => {
3929
+ return new Promise((resolve4, reject) => {
3097
3930
  const ws = new WebSocket2(url, {
3098
3931
  headers: {
3099
3932
  Authorization: authHeader
@@ -3101,7 +3934,8 @@ function connectTunnel(options) {
3101
3934
  });
3102
3935
  const forwarder = new StreamForwarder(ws, port, {
3103
3936
  onHead: () => onResponse?.(),
3104
- onDrainPing: () => onDrainPing?.()
3937
+ onDrainPing: () => onDrainPing?.(),
3938
+ onUsageRearmPing: () => onUsageRearmPing?.()
3105
3939
  });
3106
3940
  const connectionTimeout = setTimeout(() => {
3107
3941
  ws.close();
@@ -3144,8 +3978,8 @@ function connectTunnel(options) {
3144
3978
  try {
3145
3979
  message = JSON.parse(data.toString());
3146
3980
  } catch (error2) {
3147
- const errorMessage = error2 instanceof Error ? error2.message : "Unknown error";
3148
- onError?.(`Failed to handle message: ${errorMessage}`);
3981
+ const errorMessage3 = error2 instanceof Error ? error2.message : "Unknown error";
3982
+ onError?.(`Failed to handle message: ${errorMessage3}`);
3149
3983
  return;
3150
3984
  }
3151
3985
  if (isStreamFrame(message)) {
@@ -3157,7 +3991,7 @@ function connectTunnel(options) {
3157
3991
  clearTimeout(connectionTimeout);
3158
3992
  const connectedAgentId = message.agent_id ?? agentId;
3159
3993
  onConnected?.(connectedAgentId);
3160
- resolve3({
3994
+ resolve4({
3161
3995
  ws,
3162
3996
  close: () => ws.close(1e3, "CLI shutdown")
3163
3997
  });
@@ -3262,6 +4096,7 @@ var RunnerConnection = class {
3262
4096
  onError: (error2) => events.onError?.(error2),
3263
4097
  onResponse: () => events.onResponse?.(),
3264
4098
  onDrainPing: () => events.onDrainPing?.(),
4099
+ onUsageRearmPing: () => events.onUsageRearmPing?.(),
3265
4100
  onInfo: (message) => events.onInfo?.(message),
3266
4101
  onWarning: (message) => events.onWarning?.(message)
3267
4102
  });
@@ -3288,10 +4123,10 @@ var RunnerConnection = class {
3288
4123
  };
3289
4124
 
3290
4125
  // src/lib/tunnel/ready-marker.ts
3291
- import { writeFileSync } from "fs";
4126
+ import { writeFileSync as writeFileSync3 } from "node:fs";
3292
4127
  function writeTunnelReadyMarker(path, agentId) {
3293
4128
  try {
3294
- writeFileSync(path, `${agentId}
4129
+ writeFileSync3(path, `${agentId}
3295
4130
  `);
3296
4131
  return { ok: true };
3297
4132
  } catch (error2) {
@@ -3300,9 +4135,9 @@ function writeTunnelReadyMarker(path, agentId) {
3300
4135
  }
3301
4136
 
3302
4137
  // src/lib/replication.ts
3303
- import { spawn as spawn2 } from "child_process";
4138
+ import { spawn as spawn4 } from "node:child_process";
3304
4139
  function startSessionDbReplication(configPath) {
3305
- return spawn2("litestream", ["replicate", "-config", configPath], {
4140
+ return spawn4("litestream", ["replicate", "-config", configPath], {
3306
4141
  stdio: "inherit"
3307
4142
  });
3308
4143
  }
@@ -3315,10 +4150,36 @@ async function stopSessionDbReplication(child, timeoutMs) {
3315
4150
  );
3316
4151
  }
3317
4152
 
4153
+ // src/lib/process-liveness.ts
4154
+ import { readFileSync as readFileSync4 } from "node:fs";
4155
+ function isProcessAlive(pid) {
4156
+ try {
4157
+ process.kill(pid, 0);
4158
+ } catch (error2) {
4159
+ const code = error2.code;
4160
+ if (code === "ESRCH") return false;
4161
+ if (code === "EPERM") return true;
4162
+ console.error(
4163
+ `[process-liveness] could not probe process ${pid}: ${error2 instanceof Error ? error2.message : String(error2)}`
4164
+ );
4165
+ return false;
4166
+ }
4167
+ if (process.platform !== "linux") return true;
4168
+ try {
4169
+ const status2 = readFileSync4(`/proc/${pid}/status`, "utf8");
4170
+ return !/^State:\s+Z(?:\s|$)/m.test(status2);
4171
+ } catch (error2) {
4172
+ console.error(
4173
+ `[process-liveness] could not inspect /proc/${pid}/status: ${error2 instanceof Error ? error2.message : String(error2)}`
4174
+ );
4175
+ return true;
4176
+ }
4177
+ }
4178
+
3318
4179
  // src/lib/openai-usage.ts
3319
- import { readFileSync as readFileSync3 } from "fs";
3320
- import { homedir as homedir2 } from "os";
3321
- import { join as join4 } from "path";
4180
+ import { readFileSync as readFileSync5 } from "node:fs";
4181
+ import { homedir as homedir3 } from "node:os";
4182
+ import { join as join5 } from "node:path";
3322
4183
  var CODEX_RESPONSES_URL = "https://chatgpt.com/backend-api/codex/responses";
3323
4184
  var OPENCODE_AUTH_SEGMENTS = [".local", "share", "opencode", "auth.json"];
3324
4185
  var OpenAiUsageError = class extends Error {
@@ -3332,7 +4193,7 @@ function isLocalCredentialProblem2(err) {
3332
4193
  }
3333
4194
  function readOpenCodeChatGptCredentials() {
3334
4195
  try {
3335
- const raw = readFileSync3(join4(homedir2(), ...OPENCODE_AUTH_SEGMENTS), "utf-8");
4196
+ const raw = readFileSync5(join5(homedir3(), ...OPENCODE_AUTH_SEGMENTS), "utf-8");
3336
4197
  let parsed;
3337
4198
  try {
3338
4199
  parsed = JSON.parse(raw);
@@ -3354,6 +4215,23 @@ function readOpenCodeChatGptCredentials() {
3354
4215
  return null;
3355
4216
  }
3356
4217
  }
4218
+ function parseChatGptIdentity(accessToken) {
4219
+ const segments = accessToken.split(".");
4220
+ if (segments.length !== 3) return null;
4221
+ let payload;
4222
+ try {
4223
+ const parsed = JSON.parse(Buffer.from(segments[1], "base64url").toString("utf8"));
4224
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return null;
4225
+ payload = parsed;
4226
+ } catch {
4227
+ return null;
4228
+ }
4229
+ const profile = payload["https://api.openai.com/profile"];
4230
+ const auth = payload["https://api.openai.com/auth"];
4231
+ const ownerEmail = typeof profile?.email === "string" ? profile.email.trim() || null : null;
4232
+ const planType = typeof auth?.chatgpt_plan_type === "string" ? auth.chatgpt_plan_type.trim() || null : null;
4233
+ return ownerEmail === null && planType === null ? null : { ownerEmail, planType };
4234
+ }
3357
4235
  function toWindow2(headers, name) {
3358
4236
  const utilizationHeader = headers.get(`x-codex-${name}-used-percent`);
3359
4237
  const windowMinutesHeader = headers.get(`x-codex-${name}-window-minutes`);
@@ -3429,6 +4307,7 @@ async function getOpenAiUsage(port) {
3429
4307
  "credentials_expired"
3430
4308
  );
3431
4309
  }
4310
+ const subscription = parseChatGptIdentity(credentials2.accessToken);
3432
4311
  const models = await resolveProbeModels(port);
3433
4312
  if (models.length === 0) {
3434
4313
  throw new OpenAiUsageError("No supported OpenAI probe model is available.", "no_probe_model");
@@ -3461,7 +4340,7 @@ async function getOpenAiUsage(port) {
3461
4340
  "no_usable_window"
3462
4341
  );
3463
4342
  }
3464
- return usage;
4343
+ return { ...usage, subscription };
3465
4344
  }
3466
4345
  if (res.status === 401) {
3467
4346
  throw new OpenAiUsageError(
@@ -3576,8 +4455,8 @@ function resolveResourceUsageReportingEnabled(flagValue, env) {
3576
4455
  }
3577
4456
 
3578
4457
  // src/lib/resource-usage.ts
3579
- import { cpus, totalmem, freemem } from "os";
3580
- import { statfsSync as statfsSync2 } from "fs";
4458
+ import { cpus, totalmem, freemem } from "node:os";
4459
+ import { statfsSync as statfsSync2 } from "node:fs";
3581
4460
 
3582
4461
  // src/lib/ecs-task-metadata.ts
3583
4462
  var ECS_METADATA_TIMEOUT_MS = 2e3;
@@ -3662,58 +4541,97 @@ function readDisk(homeDir) {
3662
4541
  };
3663
4542
  }
3664
4543
  }
3665
- function createResourceUsageCollector(homeDir) {
3666
- let previous = readCpuSample();
3667
- return async () => {
4544
+ var CPU_PEAK_WINDOW_MS = 6e4;
4545
+ var CPU_PEAK_WINDOW_SAMPLE_COUNT = 4;
4546
+ var CPU_PEAK_SAMPLE_INTERVAL_MS = CPU_PEAK_WINDOW_MS / CPU_PEAK_WINDOW_SAMPLE_COUNT;
4547
+ function createCpuPeakSampler() {
4548
+ const sampleHistory = new Array(CPU_PEAK_WINDOW_SAMPLE_COUNT);
4549
+ sampleHistory[0] = readCpuSample();
4550
+ let nextSampleIndex = 1;
4551
+ let sampleCount = 1;
4552
+ let peak = null;
4553
+ const timer = setInterval(() => {
3668
4554
  const current = readCpuSample();
3669
- const hostCpuPercent = cpuPercentBetween(previous, current);
3670
- const hostCpuCount = cpus().length;
3671
- previous = current;
3672
- const disk = readDisk(homeDir);
3673
- const opencodeDbBytes = statSessionDbBytes(homeDir);
3674
- const { limits, warning: ecsWarning } = await readEcsTaskLimits(process.env);
3675
- const warnings = [];
3676
- if (disk.warning) warnings.push(disk.warning);
3677
- if (ecsWarning) warnings.push(ecsWarning);
3678
- let cpuPercent = hostCpuPercent;
3679
- let cpuCount = hostCpuCount;
3680
- let memoryTotalBytes = totalmem();
3681
- let memoryAvailableBytes = freemem();
3682
- if (limits !== null) {
3683
- cpuCount = limits.cpuCount;
3684
- memoryTotalBytes = limits.memoryTotalBytes;
3685
- memoryAvailableBytes = clamp(
3686
- limits.memoryTotalBytes - (totalmem() - freemem()),
3687
- 0,
3688
- limits.memoryTotalBytes
3689
- );
3690
- cpuPercent = hostCpuPercent === null ? null : clamp(round2(hostCpuPercent * hostCpuCount / limits.cpuCount), 0, 100);
4555
+ const sampleFromWindowAgo = sampleCount === CPU_PEAK_WINDOW_SAMPLE_COUNT ? sampleHistory[nextSampleIndex] : void 0;
4556
+ if (sampleFromWindowAgo !== void 0) {
4557
+ const percentage = cpuPercentBetween(sampleFromWindowAgo, current);
4558
+ if (percentage !== null) {
4559
+ peak = peak === null ? percentage : Math.max(peak, percentage);
4560
+ }
3691
4561
  }
3692
- return {
3693
- usage: {
3694
- cpuPercent,
3695
- cpuCount,
3696
- memoryTotalBytes,
3697
- memoryAvailableBytes,
3698
- diskTotalBytes: disk.totalBytes,
3699
- diskFreeBytes: disk.freeBytes,
3700
- opencodeDbBytes
3701
- },
3702
- warnings
3703
- };
4562
+ sampleHistory[nextSampleIndex] = current;
4563
+ nextSampleIndex = (nextSampleIndex + 1) % CPU_PEAK_WINDOW_SAMPLE_COUNT;
4564
+ sampleCount = Math.min(sampleCount + 1, CPU_PEAK_WINDOW_SAMPLE_COUNT);
4565
+ }, CPU_PEAK_SAMPLE_INTERVAL_MS);
4566
+ return {
4567
+ takeAndReset: () => {
4568
+ const currentPeak = peak;
4569
+ peak = null;
4570
+ return currentPeak;
4571
+ },
4572
+ stop: () => clearInterval(timer)
4573
+ };
4574
+ }
4575
+ function createResourceUsageCollector(homeDir) {
4576
+ let previous = readCpuSample();
4577
+ const cpuPeakSampler = createCpuPeakSampler();
4578
+ return {
4579
+ collect: async () => {
4580
+ const current = readCpuSample();
4581
+ const hostCpuPercent = cpuPercentBetween(previous, current);
4582
+ const hostCpuPeakPercent = cpuPeakSampler.takeAndReset();
4583
+ const hostCpuCount = cpus().length;
4584
+ previous = current;
4585
+ const disk = readDisk(homeDir);
4586
+ const opencodeDbBytes = statSessionDbBytes(homeDir);
4587
+ const { limits, warning: ecsWarning } = await readEcsTaskLimits(process.env);
4588
+ const warnings = [];
4589
+ if (disk.warning) warnings.push(disk.warning);
4590
+ if (ecsWarning) warnings.push(ecsWarning);
4591
+ let cpuPercent = hostCpuPercent;
4592
+ let cpuPeakPercent = hostCpuPeakPercent;
4593
+ let cpuCount = hostCpuCount;
4594
+ let memoryTotalBytes = totalmem();
4595
+ let memoryAvailableBytes = freemem();
4596
+ if (limits !== null) {
4597
+ cpuCount = limits.cpuCount;
4598
+ memoryTotalBytes = limits.memoryTotalBytes;
4599
+ memoryAvailableBytes = clamp(
4600
+ limits.memoryTotalBytes - (totalmem() - freemem()),
4601
+ 0,
4602
+ limits.memoryTotalBytes
4603
+ );
4604
+ cpuPercent = hostCpuPercent === null ? null : clamp(round2(hostCpuPercent * hostCpuCount / limits.cpuCount), 0, 100);
4605
+ cpuPeakPercent = hostCpuPeakPercent === null ? null : clamp(round2(hostCpuPeakPercent * hostCpuCount / limits.cpuCount), 0, 100);
4606
+ }
4607
+ return {
4608
+ usage: {
4609
+ cpuPercent,
4610
+ cpuPeakPercent,
4611
+ cpuCount,
4612
+ memoryTotalBytes,
4613
+ memoryAvailableBytes,
4614
+ diskTotalBytes: disk.totalBytes,
4615
+ diskFreeBytes: disk.freeBytes,
4616
+ opencodeDbBytes
4617
+ },
4618
+ warnings
4619
+ };
4620
+ },
4621
+ stop: cpuPeakSampler.stop
3704
4622
  };
3705
4623
  }
3706
4624
 
3707
4625
  // src/lib/channels/driver.ts
3708
- import { homedir as homedir3 } from "os";
4626
+ import { homedir as homedir4 } from "node:os";
3709
4627
 
3710
4628
  // src/lib/runner-file-sync.ts
3711
- import { join as join6 } from "path";
4629
+ import { join as join7 } from "node:path";
3712
4630
 
3713
4631
  // src/lib/file-push.ts
3714
- import { randomUUID } from "crypto";
3715
- import { chmod, mkdir, open as open2, realpath, rename, unlink } from "fs/promises";
3716
- import { basename, dirname as dirname3, isAbsolute, join as join5, relative, resolve as resolve2, sep } from "path";
4632
+ import { randomUUID } from "node:crypto";
4633
+ import { chmod, mkdir, open as open2, realpath, rename, unlink } from "node:fs/promises";
4634
+ import { basename, dirname as dirname5, isAbsolute, join as join6, relative, resolve as resolve2, sep } from "node:path";
3717
4635
  var FILE_MODE = 384;
3718
4636
  var DIRECTORY_MODE = 448;
3719
4637
  async function writePushedFile(request) {
@@ -3744,9 +4662,9 @@ async function writePushedFile(request) {
3744
4662
  }
3745
4663
  try {
3746
4664
  const { existingAncestor, missingSegments } = await resolveNearestExistingAncestor(
3747
- dirname3(candidate)
4665
+ dirname5(candidate)
3748
4666
  );
3749
- const realTarget = join5(existingAncestor, ...missingSegments, basename(candidate));
4667
+ const realTarget = join6(existingAncestor, ...missingSegments, basename(candidate));
3750
4668
  const allowedDirectory = await findContainingAllowedDirectory(allowedDirectories, realTarget);
3751
4669
  if (allowedDirectory === null) {
3752
4670
  return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
@@ -3756,8 +4674,8 @@ async function writePushedFile(request) {
3756
4674
  }
3757
4675
  if (missingSegments.length > 0) {
3758
4676
  await createMissingDirectories(existingAncestor, missingSegments);
3759
- const realParent = await realpath(dirname3(realTarget));
3760
- if (realParent !== dirname3(realTarget) || !contains(allowedDirectory, realTarget)) {
4677
+ const realParent = await realpath(dirname5(realTarget));
4678
+ if (realParent !== dirname5(realTarget) || !contains(allowedDirectory, realTarget)) {
3761
4679
  return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
3762
4680
  path: realTarget,
3763
4681
  bytes,
@@ -3782,7 +4700,7 @@ function expandAndValidate(requestedPath, homeDir) {
3782
4700
  if (requestedPath.trim() === "" || requestedPath.includes("\0")) {
3783
4701
  return null;
3784
4702
  }
3785
- const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join5(homeDir, requestedPath.slice(2)) : requestedPath;
4703
+ const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join6(homeDir, requestedPath.slice(2)) : requestedPath;
3786
4704
  if (expanded.split(/[/\\]/).includes("..")) {
3787
4705
  return null;
3788
4706
  }
@@ -3800,7 +4718,7 @@ async function resolveNearestExistingAncestor(directory) {
3800
4718
  try {
3801
4719
  return { existingAncestor: await realpath(current), missingSegments };
3802
4720
  } catch (err) {
3803
- const parent = dirname3(current);
4721
+ const parent = dirname5(current);
3804
4722
  if (err.code !== "ENOENT" || parent === current) {
3805
4723
  throw err;
3806
4724
  }
@@ -3855,13 +4773,13 @@ function contains(realDirectory, realTarget) {
3855
4773
  async function createMissingDirectories(existingAncestor, missingSegments) {
3856
4774
  let current = existingAncestor;
3857
4775
  for (const segment of missingSegments) {
3858
- current = join5(current, segment);
4776
+ current = join6(current, segment);
3859
4777
  await mkdir(current, { recursive: true, mode: DIRECTORY_MODE });
3860
4778
  await chmod(current, DIRECTORY_MODE);
3861
4779
  }
3862
4780
  }
3863
4781
  async function writeAtomically(realTarget, content) {
3864
- const temporaryPath = join5(dirname3(realTarget), `.evident-push-${randomUUID()}.tmp`);
4782
+ const temporaryPath = join6(dirname5(realTarget), `.evident-push-${randomUUID()}.tmp`);
3865
4783
  let handle;
3866
4784
  try {
3867
4785
  handle = await open2(temporaryPath, "wx", FILE_MODE);
@@ -3991,12 +4909,12 @@ var NOT_APPLIED = {
3991
4909
  opencodeAuthApplied: false
3992
4910
  };
3993
4911
  function isClaudeCredentialPath(requestedPath, homeDir) {
3994
- const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join6(homeDir, requestedPath.slice(2)) : requestedPath;
3995
- return expanded === join6(homeDir, ...CLAUDE_CREDENTIALS_SEGMENTS);
4912
+ const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join7(homeDir, requestedPath.slice(2)) : requestedPath;
4913
+ return expanded === join7(homeDir, ...CLAUDE_CREDENTIALS_SEGMENTS);
3996
4914
  }
3997
4915
  function isOpenCodeAuthPath(requestedPath, homeDir) {
3998
- const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join6(homeDir, requestedPath.slice(2)) : requestedPath;
3999
- return expanded === join6(homeDir, ...OPENCODE_AUTH_SEGMENTS);
4916
+ const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join7(homeDir, requestedPath.slice(2)) : requestedPath;
4917
+ return expanded === join7(homeDir, ...OPENCODE_AUTH_SEGMENTS);
4000
4918
  }
4001
4919
  async function applyOne(options, file) {
4002
4920
  const label = `${file.id.slice(0, 8)} (${file.path})`;
@@ -4523,6 +5441,7 @@ var ChannelDriver = class _ChannelDriver {
4523
5441
  * and stops opencode.
4524
5442
  */
4525
5443
  stopped = false;
5444
+ recycleRequestedFlag = false;
4526
5445
  constructor(config) {
4527
5446
  this.agentId = config.agentId;
4528
5447
  this.port = config.port;
@@ -4542,7 +5461,7 @@ var ChannelDriver = class _ChannelDriver {
4542
5461
  this.stuckQueuedMs = config.stuckQueuedMs ?? DEFAULT_STUCK_QUEUED_MS;
4543
5462
  this.now = config.now ?? (() => Date.now());
4544
5463
  this.fileSyncDirectories = config.fileSyncDirectories ?? [];
4545
- this.homeDir = config.homeDir ?? homedir3();
5464
+ this.homeDir = config.homeDir ?? homedir4();
4546
5465
  this.maxActiveSessions = config.maxActiveSessions;
4547
5466
  this.watcherStallMs = config.watcherStallMs ?? WATCHER_STALL_MS;
4548
5467
  this.wedgeWarningIntervalMs = config.wedgeWarningIntervalMs ?? WEDGE_WARNING_INTERVAL_MS;
@@ -4628,6 +5547,9 @@ var ChannelDriver = class _ChannelDriver {
4628
5547
  let dispatched = 0;
4629
5548
  try {
4630
5549
  const conversations = await this.getPendingConversations();
5550
+ if (this.recycleRequestedFlag) {
5551
+ this.stop();
5552
+ }
4631
5553
  if (conversations.length > 0) {
4632
5554
  const total = conversations.reduce((sum, c) => sum + (c.pending_message_count ?? 0), 0);
4633
5555
  this.log({
@@ -4756,6 +5678,14 @@ var ChannelDriver = class _ChannelDriver {
4756
5678
  stop() {
4757
5679
  this.stopped = true;
4758
5680
  }
5681
+ /**
5682
+ * The server clears this request when a new MicroVM identity is recorded, so a
5683
+ * same-VM tunnel reconnect does not consume it. This is a plain read rather
5684
+ * than a consume; `run.ts` guards the action once-only.
5685
+ */
5686
+ get recycleRequested() {
5687
+ return this.recycleRequestedFlag;
5688
+ }
4759
5689
  /**
4760
5690
  * Wait (up to `timeoutMs`) for in-flight watcher work to settle during a
4761
5691
  * graceful shutdown, so a turn whose reply is ready — or completes within the
@@ -4893,7 +5823,7 @@ var ChannelDriver = class _ChannelDriver {
4893
5823
  this.signalDispatchNotStarted(conv, message, "session_existence_unknown");
4894
5824
  break;
4895
5825
  }
4896
- const errorMessage = err instanceof Error ? err.message : String(err);
5826
+ const errorMessage3 = err instanceof Error ? err.message : String(err);
4897
5827
  this.sessions.delete(conv.id);
4898
5828
  this.supersede(conv.id, sessionId);
4899
5829
  this.log({
@@ -4902,7 +5832,7 @@ var ChannelDriver = class _ChannelDriver {
4902
5832
  conversation_id: conv.id,
4903
5833
  message_id: message.id
4904
5834
  });
4905
- await this.markFailed(conv.id, message.id, null, errorMessage).catch((markErr) => {
5835
+ await this.markFailed(conv.id, message.id, null, errorMessage3).catch((markErr) => {
4906
5836
  this.log({
4907
5837
  level: "warn",
4908
5838
  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)}`,
@@ -4913,7 +5843,7 @@ var ChannelDriver = class _ChannelDriver {
4913
5843
  });
4914
5844
  this.log({
4915
5845
  level: "error",
4916
- message: `Message ${message.id.slice(0, 8)} dispatch failed: ${errorMessage}`,
5846
+ message: `Message ${message.id.slice(0, 8)} dispatch failed: ${errorMessage3}`,
4917
5847
  conversation_id: conv.id,
4918
5848
  message_id: message.id
4919
5849
  });
@@ -4934,14 +5864,14 @@ var ChannelDriver = class _ChannelDriver {
4934
5864
  this.unconfirmedDispatchFailures.delete(message.id);
4935
5865
  this.sessions.delete(conv.id);
4936
5866
  this.supersede(conv.id, sessionId);
4937
- 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.`;
5867
+ const errorMessage3 = `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.`;
4938
5868
  this.log({
4939
5869
  level: "error",
4940
- message: errorMessage,
5870
+ message: errorMessage3,
4941
5871
  conversation_id: conv.id,
4942
5872
  message_id: message.id
4943
5873
  });
4944
- await this.markFailed(conv.id, message.id, null, errorMessage).catch((markErr) => {
5874
+ await this.markFailed(conv.id, message.id, null, errorMessage3).catch((markErr) => {
4945
5875
  this.log({
4946
5876
  level: "warn",
4947
5877
  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)}`,
@@ -5275,6 +6205,9 @@ var ChannelDriver = class _ChannelDriver {
5275
6205
  });
5276
6206
  await this.markFailed(conv.id, message.id, sessionId, error2, usage, failure);
5277
6207
  }
6208
+ if (ocId !== null) {
6209
+ await this.reportSubagentAuthFailures(conv.id, ocId, message.id, messages);
6210
+ }
5278
6211
  } catch (err) {
5279
6212
  if (err instanceof ChannelAuthError) throw err;
5280
6213
  this.log({
@@ -6239,6 +7172,12 @@ var ChannelDriver = class _ChannelDriver {
6239
7172
  return;
6240
7173
  }
6241
7174
  inFlight.done = true;
7175
+ await this.reportSubagentAuthFailures(
7176
+ watcher.conv.id,
7177
+ inFlight.opencodeMessageId,
7178
+ inFlight.evidentMessageId,
7179
+ messages
7180
+ );
6242
7181
  }
6243
7182
  this.removeInFlight(watcher, inFlight.evidentMessageId);
6244
7183
  return;
@@ -6481,6 +7420,12 @@ var ChannelDriver = class _ChannelDriver {
6481
7420
  return;
6482
7421
  }
6483
7422
  inFlight.done = true;
7423
+ await this.reportSubagentAuthFailures(
7424
+ watcher.conv.id,
7425
+ inFlight.opencodeMessageId,
7426
+ inFlight.evidentMessageId,
7427
+ messages
7428
+ );
6484
7429
  }
6485
7430
  this.removeInFlight(watcher, inFlight.evidentMessageId);
6486
7431
  }
@@ -6651,6 +7596,7 @@ var ChannelDriver = class _ChannelDriver {
6651
7596
  });
6652
7597
  return;
6653
7598
  }
7599
+ await this.reportSubagentAuthFailures(row.conversation_id, ocId ?? "", row.id, messages);
6654
7600
  this.dontRedispatch.delete(row.id);
6655
7601
  void this.postSignal(row.conversation_id, row.id, "readopt_failed");
6656
7602
  return;
@@ -6812,6 +7758,9 @@ var ChannelDriver = class _ChannelDriver {
6812
7758
  });
6813
7759
  return;
6814
7760
  }
7761
+ if (ocId !== null) {
7762
+ await this.reportSubagentAuthFailures(row.conversation_id, ocId, row.id, messages);
7763
+ }
6815
7764
  this.dontRedispatch.delete(row.id);
6816
7765
  void this.postSignal(row.conversation_id, row.id, "readopt_done");
6817
7766
  }
@@ -6905,14 +7854,14 @@ var ChannelDriver = class _ChannelDriver {
6905
7854
  this.unconfirmedDispatchFailures.delete(row.id);
6906
7855
  this.sessions.delete(readoptConv.id);
6907
7856
  this.supersede(readoptConv.id, sessionId);
6908
- 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.`;
7857
+ const errorMessage3 = `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.`;
6909
7858
  this.log({
6910
7859
  level: "error",
6911
- message: errorMessage,
7860
+ message: errorMessage3,
6912
7861
  conversation_id: row.conversation_id,
6913
7862
  message_id: row.id
6914
7863
  });
6915
- await this.markFailed(row.conversation_id, row.id, null, errorMessage).catch((markErr) => {
7864
+ await this.markFailed(row.conversation_id, row.id, null, errorMessage3).catch((markErr) => {
6916
7865
  this.log({
6917
7866
  level: "warn",
6918
7867
  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)}`,
@@ -7527,6 +8476,7 @@ var ChannelDriver = class _ChannelDriver {
7527
8476
  throw new Error(`Failed to get pending conversations: HTTP ${res.status}`);
7528
8477
  }
7529
8478
  const data = await res.json();
8479
+ this.recycleRequestedFlag = data.recycle_requested === true;
7530
8480
  let conversations = data.conversations;
7531
8481
  if (this.conversationFilter) {
7532
8482
  conversations = conversations.filter((c) => c.id === this.conversationFilter);
@@ -7762,6 +8712,111 @@ var ChannelDriver = class _ChannelDriver {
7762
8712
  reply?.info?.modelID ?? null
7763
8713
  );
7764
8714
  }
8715
+ async recordSubagentModelAuthFailure(failure, conversationId, messageId) {
8716
+ const providerId = failure.providerId ?? "(unknown)";
8717
+ try {
8718
+ const res = await this.fetchImpl(
8719
+ `${this.apiUrl}/runners/${this.agentId}/model-auth-failures`,
8720
+ {
8721
+ method: "POST",
8722
+ headers: { Authorization: this.getAuthHeader(), "Content-Type": "application/json" },
8723
+ body: JSON.stringify({
8724
+ provider_id: failure.providerId,
8725
+ model_id: failure.modelId,
8726
+ reason: failure.reason
8727
+ })
8728
+ }
8729
+ );
8730
+ if (!res.ok) {
8731
+ this.log({
8732
+ level: "warn",
8733
+ message: `Sub-agent model-auth report for provider ${providerId} (${failure.reason}) returned HTTP ${res.status} (conversation ${conversationId.slice(0, 8)}, message ${messageId.slice(0, 8)})`,
8734
+ conversation_id: conversationId,
8735
+ message_id: messageId
8736
+ });
8737
+ }
8738
+ } catch (err) {
8739
+ this.log({
8740
+ level: "warn",
8741
+ message: `Sub-agent model-auth report for provider ${providerId} (${failure.reason}) failed with status network-error (conversation ${conversationId.slice(0, 8)}, message ${messageId.slice(0, 8)}): ${err instanceof Error ? err.message : String(err)}`,
8742
+ conversation_id: conversationId,
8743
+ message_id: messageId
8744
+ });
8745
+ }
8746
+ }
8747
+ async clearSubagentModelAuthFailure(providerId, conversationId, messageId) {
8748
+ try {
8749
+ const res = await this.fetchImpl(
8750
+ `${this.apiUrl}/runners/${this.agentId}/model-auth-failures/${encodeURIComponent(providerId)}`,
8751
+ {
8752
+ method: "DELETE",
8753
+ headers: { Authorization: this.getAuthHeader() }
8754
+ }
8755
+ );
8756
+ if (!res.ok) {
8757
+ this.log({
8758
+ level: "warn",
8759
+ message: `Sub-agent model-auth clear for provider ${providerId} returned HTTP ${res.status} (conversation ${conversationId.slice(0, 8)}, message ${messageId.slice(0, 8)})`,
8760
+ conversation_id: conversationId,
8761
+ message_id: messageId
8762
+ });
8763
+ }
8764
+ } catch (err) {
8765
+ this.log({
8766
+ level: "warn",
8767
+ message: `Sub-agent model-auth clear for provider ${providerId} failed with status network-error (conversation ${conversationId.slice(0, 8)}, message ${messageId.slice(0, 8)}): ${err instanceof Error ? err.message : String(err)}`,
8768
+ conversation_id: conversationId,
8769
+ message_id: messageId
8770
+ });
8771
+ }
8772
+ }
8773
+ async reportSubagentAuthFailures(conversationId, opencodeMessageId, evidentMessageId, messages) {
8774
+ const refs = collectSubagentSessions(messages, opencodeMessageId);
8775
+ if (refs.length === 0) return;
8776
+ const failedProviders = /* @__PURE__ */ new Map();
8777
+ const succeededProviders = /* @__PURE__ */ new Set();
8778
+ for (const ref of refs) {
8779
+ try {
8780
+ const childMessages = await getSessionMessages(this.port, ref.sessionId);
8781
+ if (childMessages === null) {
8782
+ this.log({
8783
+ level: "debug",
8784
+ message: `Could not read sub-agent session ${ref.sessionId} while checking credential failures \u2014 skipping it`,
8785
+ conversation_id: conversationId,
8786
+ message_id: evidentMessageId
8787
+ });
8788
+ continue;
8789
+ }
8790
+ const outcome = findSubagentAuthOutcome(childMessages, ref.startedAtMs);
8791
+ if (!outcome) continue;
8792
+ if (outcome.outcome === "failed") {
8793
+ failedProviders.set(outcome.providerId, outcome.failure);
8794
+ } else {
8795
+ succeededProviders.add(outcome.providerId);
8796
+ }
8797
+ } catch (err) {
8798
+ this.log({
8799
+ level: "warn",
8800
+ message: `Failed to inspect sub-agent session ${ref.sessionId} for credential failures (conversation ${conversationId.slice(0, 8)}, message ${evidentMessageId.slice(0, 8)}): ${err instanceof Error ? err.message : String(err)}`,
8801
+ conversation_id: conversationId,
8802
+ message_id: evidentMessageId
8803
+ });
8804
+ }
8805
+ }
8806
+ for (const [providerId, failure] of failedProviders) {
8807
+ this.log({
8808
+ level: "warn",
8809
+ message: `Sub-agent turn failed on provider ${providerId} (${failure.reason}) \u2014 recording credential evidence`,
8810
+ conversation_id: conversationId,
8811
+ message_id: evidentMessageId
8812
+ });
8813
+ await this.recordSubagentModelAuthFailure(failure, conversationId, evidentMessageId);
8814
+ }
8815
+ for (const providerId of succeededProviders) {
8816
+ if (failedProviders.has(providerId)) continue;
8817
+ await this.clearSubagentModelAuthFailure(providerId, conversationId, evidentMessageId);
8818
+ }
8819
+ }
7765
8820
  /**
7766
8821
  * Best-effort, SINGLE-ATTEMPT runner→server telemetry ping
7767
8822
  * (queued-followup-redrive). `POST .../messages/:id/signal {signal, ...extra}`
@@ -7915,6 +8970,13 @@ import chalk5 from "chalk";
7915
8970
  import ora2 from "ora";
7916
8971
  import { select as select2 } from "@inquirer/prompts";
7917
8972
  var INTERACTIVE_START_TIMEOUT_MS = 3e4;
8973
+ function checkNonInteractivePortConflict(port, isPortInUseFn) {
8974
+ if (isPortInUseFn(port)) {
8975
+ throw new Error(
8976
+ `Port ${port} is already in use by a non-OpenCode process. Free it or pass --port.`
8977
+ );
8978
+ }
8979
+ }
7918
8980
  async function ensureOpenCodeRunning(ctx) {
7919
8981
  const healthCheck = await checkOpenCodeHealth(ctx.port);
7920
8982
  if (healthCheck.healthy) {
@@ -7962,8 +9024,9 @@ async function ensureOpenCodeRunning(ctx) {
7962
9024
  }
7963
9025
  }
7964
9026
  if (!ctx.interactive) {
9027
+ checkNonInteractivePortConflict(ctx.port, isPortInUse);
7965
9028
  ctx.log(`OpenCode is not running on port ${ctx.port}. Starting it automatically...`);
7966
- const proc = await startOpenCode(ctx.port);
9029
+ const proc = await startOpenCode(ctx.port, { inheritStdio: ctx.inheritStdio });
7967
9030
  const health = await waitForOpenCodeHealth(ctx.port, ctx.startTimeoutMs);
7968
9031
  if (!health.healthy) {
7969
9032
  return {
@@ -8031,7 +9094,7 @@ Port ${port} is already in use.`));
8031
9094
  }
8032
9095
  if (action === "start") {
8033
9096
  const spinner = ora2("Starting OpenCode...").start();
8034
- const proc = await startOpenCode(port);
9097
+ const proc = await startOpenCode(port, { inheritStdio: ctx.inheritStdio });
8035
9098
  const health = await waitForOpenCodeHealth(port, INTERACTIVE_START_TIMEOUT_MS);
8036
9099
  if (!health.healthy) {
8037
9100
  spinner.fail("Failed to start OpenCode");
@@ -8043,89 +9106,766 @@ Port ${port} is already in use.`));
8043
9106
  return { port, process: null, version: null, notReadyReason: "you chose to continue without it" };
8044
9107
  }
8045
9108
 
8046
- // src/commands/run.ts
8047
- var MAX_ACTIVITY_LOG_ENTRIES = 10;
8048
- var CHANNEL_POLL_INTERVAL_MS = Number(process.env.EVIDENT_CHANNEL_POLL_INTERVAL_MS) || 2e3;
8049
- var CHANNEL_STUCK_QUEUED_MS = Number(process.env.EVIDENT_STUCK_QUEUED_MS) || void 0;
8050
- var SHUTDOWN_DRAIN_TIMEOUT_MS = Number(process.env.EVIDENT_SHUTDOWN_DRAIN_MS) || 25e3;
8051
- var TELEMETRY_SHUTDOWN_TIMEOUT_MS = 5e3;
8052
- var CHILD_STOP_TIMEOUT_MS = 1e4;
8053
- function resolveLogLevel(options) {
8054
- const accepted = Object.keys(LOG_LEVELS);
8055
- const validate = (value, source) => {
8056
- const normalized = value.trim().toLowerCase();
8057
- if (!accepted.includes(normalized)) {
8058
- throw new Error(
8059
- `Invalid log level "${value}"${source}; expected one of ${accepted.join(", ")}`
8060
- );
8061
- }
8062
- return normalized;
8063
- };
8064
- if (options.logLevel !== void 0) {
8065
- return validate(options.logLevel, " (--log-level)");
8066
- }
8067
- if (options.verbose) {
8068
- return "debug";
8069
- }
8070
- const env = process.env.EVIDENT_LOG_LEVEL;
8071
- if (env !== void 0 && env !== "") {
8072
- return validate(env, " (EVIDENT_LOG_LEVEL)");
8073
- }
8074
- return "info";
8075
- }
8076
- function resolveFileSyncDirectories(raw, homeDir) {
8077
- const directories = [];
8078
- for (const entry of raw ?? []) {
8079
- const trimmed = entry.trim();
8080
- if (trimmed === "") {
8081
- throw new Error("--enable-file-sync-to requires a directory path (got an empty value)");
8082
- }
8083
- const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join7(homeDir, trimmed.slice(2)) : trimmed;
8084
- if (!isAbsolute2(expanded)) {
8085
- throw new Error(`--enable-file-sync-to requires an absolute directory path; got "${entry}"`);
8086
- }
8087
- const normalized = resolvePath(expanded);
8088
- if (parse(normalized).root === normalized) {
8089
- throw new Error(
8090
- `--enable-file-sync-to will not allow-list the filesystem root ("${entry}"); name the specific directory the credentials belong in (for example ~/.claude)`
8091
- );
9109
+ // src/commands/ensure-opencode-v2.ts
9110
+ import chalk6 from "chalk";
9111
+ import { select as select3 } from "@inquirer/prompts";
9112
+ async function probeOpenCode2WithoutPassword(port) {
9113
+ try {
9114
+ const response = await fetch(`http://127.0.0.1:${port}/global/health`, {
9115
+ signal: AbortSignal.timeout(2e3)
9116
+ });
9117
+ if (response.status === 401) {
9118
+ return { healthy: false, authFailed: true, error: "HTTP 401" };
8092
9119
  }
8093
- if (!directories.includes(normalized)) {
8094
- directories.push(normalized);
9120
+ if (!response.ok) {
9121
+ return { healthy: false, error: `HTTP ${response.status}` };
8095
9122
  }
9123
+ return { healthy: true };
9124
+ } catch (error2) {
9125
+ return {
9126
+ healthy: false,
9127
+ error: error2 instanceof Error ? error2.message : "Unknown error"
9128
+ };
8096
9129
  }
8097
- if (directories.length > MAX_FILE_SYNC_DIRECTORIES) {
8098
- throw new Error(
8099
- `--enable-file-sync-to accepts at most ${MAX_FILE_SYNC_DIRECTORIES} directories; got ${directories.length}`
8100
- );
8101
- }
8102
- return directories;
8103
9130
  }
8104
- var DEFAULT_OPENCODE_START_TIMEOUT_SECONDS = 180;
8105
- var MAX_OPENCODE_START_TIMEOUT_SECONDS = 3600;
8106
- var OPENCODE_START_TIMEOUT_ENV = "EVIDENT_OPENCODE_START_TIMEOUT";
8107
- function resolveOpenCodeStartTimeoutMs(options, env = process.env) {
8108
- const defaultMs = DEFAULT_OPENCODE_START_TIMEOUT_SECONDS * 1e3;
8109
- let raw;
8110
- let source;
8111
- if (options.opencodeStartTimeout !== void 0) {
8112
- raw = options.opencodeStartTimeout;
8113
- source = "--opencode-start-timeout";
8114
- } else if (env[OPENCODE_START_TIMEOUT_ENV] !== void 0 && env[OPENCODE_START_TIMEOUT_ENV] !== "") {
8115
- raw = env[OPENCODE_START_TIMEOUT_ENV];
8116
- source = OPENCODE_START_TIMEOUT_ENV;
8117
- } else {
8118
- return { timeoutMs: defaultMs, warnings: [] };
9131
+ function unknownPasswordError(port) {
9132
+ return new Error(
9133
+ `OpenCode V2 (opencode2) is already running on port ${port} with a password this runner doesn't know. Free the port or pass --port.`
9134
+ );
9135
+ }
9136
+ function v2SessionSupportIncompleteError() {
9137
+ return new Error(
9138
+ "OpenCode V2 (opencode2) session support is incomplete \u2014 see https://github.com/sroze/evident/issues/2075. Not starting a new opencode2 process."
9139
+ );
9140
+ }
9141
+ async function ensureOpenCode2Running(ctx) {
9142
+ const initialHealth = await probeOpenCode2WithoutPassword(ctx.port);
9143
+ if (initialHealth.authFailed) {
9144
+ throw unknownPasswordError(ctx.port);
8119
9145
  }
8120
- const trimmed = raw.trim();
8121
- const seconds = Number(trimmed);
8122
- const isPositiveInteger = /^\d+$/.test(trimmed) && Number.isInteger(seconds) && seconds > 0;
8123
- if (!isPositiveInteger || seconds > MAX_OPENCODE_START_TIMEOUT_SECONDS) {
9146
+ if (initialHealth.healthy) {
8124
9147
  return {
8125
- timeoutMs: defaultMs,
8126
- warnings: [
8127
- `Ignoring invalid ${source} "${raw}": expected a positive integer number of seconds (at most ${MAX_OPENCODE_START_TIMEOUT_SECONDS}); using the default ${DEFAULT_OPENCODE_START_TIMEOUT_SECONDS}s`
8128
- ]
9148
+ port: ctx.port,
9149
+ process: null,
9150
+ version: null,
9151
+ notReadyReason: null,
9152
+ password: null
9153
+ };
9154
+ }
9155
+ if (!isOpenCode2Installed()) {
9156
+ throw new Error(
9157
+ "OpenCode V2 (opencode2) is not installed. Install it with: npm install -g @opencode-ai/cli@beta"
9158
+ );
9159
+ }
9160
+ let port = ctx.port;
9161
+ if (!ctx.interactive) {
9162
+ checkNonInteractivePortConflict(port, isPortInUse);
9163
+ } else if (isPortInUse(port)) {
9164
+ console.log(chalk6.yellow(`
9165
+ Port ${port} is already in use.`));
9166
+ const alternativePort = findAvailablePort(port + 1);
9167
+ if (alternativePort) {
9168
+ const useAlternative = await select3({
9169
+ message: `Use port ${alternativePort} instead?`,
9170
+ choices: [
9171
+ { name: `Yes, use port ${alternativePort}`, value: "yes" },
9172
+ { name: "No, I will free the port manually", value: "no" }
9173
+ ]
9174
+ });
9175
+ if (useAlternative === "yes") {
9176
+ port = alternativePort;
9177
+ } else {
9178
+ throw new Error(`Port ${ctx.port} is in use`);
9179
+ }
9180
+ }
9181
+ }
9182
+ if (!ctx.interactive) {
9183
+ throw v2SessionSupportIncompleteError();
9184
+ }
9185
+ console.log(chalk6.yellow(`
9186
+ ${v2SessionSupportIncompleteError().message}`));
9187
+ const action = await select3({
9188
+ message: "OpenCode V2 is not running. What would you like to do?",
9189
+ choices: [
9190
+ {
9191
+ name: "Show me the command",
9192
+ value: "manual",
9193
+ description: "Display the command to run manually"
9194
+ },
9195
+ {
9196
+ name: "Continue without OpenCode V2",
9197
+ value: "continue",
9198
+ description: "Requests will fail until OpenCode V2 starts"
9199
+ }
9200
+ ]
9201
+ });
9202
+ if (action === "manual") {
9203
+ blank();
9204
+ console.log(chalk6.bold("Run this command in another terminal:"));
9205
+ blank();
9206
+ console.log(` ${chalk6.cyan(`opencode2 serve --port ${port}`)}`);
9207
+ blank();
9208
+ throw new Error("Please start OpenCode V2 manually");
9209
+ }
9210
+ return {
9211
+ port,
9212
+ process: null,
9213
+ version: null,
9214
+ notReadyReason: "you chose to continue without OpenCode V2",
9215
+ password: null
9216
+ };
9217
+ }
9218
+
9219
+ // src/lib/runner-credentials.ts
9220
+ import { chmodSync as chmodSync2, writeFileSync as writeFileSync4 } from "node:fs";
9221
+ import { spawn as spawn5 } from "node:child_process";
9222
+ var RUNNER_SECRET_FETCH_TIMEOUT_MS = 6e4;
9223
+ var CREDENTIAL_RESTORE_TIMEOUT_MS = 6e4;
9224
+ var GITHUB_PROBE_TIMEOUT_MS = 1e4;
9225
+ var GIT_CONFIG_GLOBAL = "/tmp/gitconfig";
9226
+ var GIT_CREDENTIAL_HELPER = "/tmp/git-credential-helper.sh";
9227
+ function commandError2(result) {
9228
+ return result.stderr.trim() || `process exited with code ${result.code ?? "null"}`;
9229
+ }
9230
+ var runCommand2 = (command, args, opts) => {
9231
+ return new Promise((resolve4) => {
9232
+ let child;
9233
+ let stdout = "";
9234
+ let stderr = "";
9235
+ let settled = false;
9236
+ const timer = {};
9237
+ const finish = (result) => {
9238
+ if (settled) return;
9239
+ settled = true;
9240
+ if (timer.handle) clearTimeout(timer.handle);
9241
+ resolve4(result);
9242
+ };
9243
+ try {
9244
+ child = spawn5(command, args, { env: opts.env, stdio: ["ignore", "pipe", "pipe"] });
9245
+ } catch (error2) {
9246
+ finish({
9247
+ code: null,
9248
+ stdout,
9249
+ stderr: error2 instanceof Error ? error2.message : String(error2),
9250
+ timedOut: false
9251
+ });
9252
+ return;
9253
+ }
9254
+ child.stdout?.setEncoding("utf8");
9255
+ child.stdout?.on("data", (chunk) => {
9256
+ stdout += chunk;
9257
+ });
9258
+ child.stderr?.setEncoding("utf8");
9259
+ child.stderr?.on("data", (chunk) => {
9260
+ stderr += chunk;
9261
+ });
9262
+ child.once("error", (error2) => {
9263
+ finish({
9264
+ code: null,
9265
+ stdout,
9266
+ stderr: stderr === "" ? error2.message : `${stderr}
9267
+ ${error2.message}`,
9268
+ timedOut: false
9269
+ });
9270
+ });
9271
+ child.once("close", (code) => finish({ code, stdout, stderr, timedOut: false }));
9272
+ timer.handle = setTimeout(
9273
+ () => {
9274
+ child.kill("SIGKILL");
9275
+ finish({ code: null, stdout, stderr, timedOut: true });
9276
+ },
9277
+ Math.max(0, opts.timeoutMs)
9278
+ );
9279
+ });
9280
+ };
9281
+ function isEnvironmentObject(value) {
9282
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9283
+ }
9284
+ function secretFailure(marker, detail, log3) {
9285
+ const message = `${marker}: ${detail}`;
9286
+ log3(message, "error");
9287
+ return new Error(message);
9288
+ }
9289
+ async function installRunnerSecret({
9290
+ env,
9291
+ log: log3,
9292
+ commandRunner
9293
+ }) {
9294
+ const arn = env.RUNNER_SECRET_ARN?.trim();
9295
+ if (!arn) {
9296
+ log3("runner secret is not configured; continuing without GitHub and MCP credentials");
9297
+ return false;
9298
+ }
9299
+ const result = await (commandRunner ?? runCommand2)(
9300
+ "aws",
9301
+ [
9302
+ "secretsmanager",
9303
+ "get-secret-value",
9304
+ "--secret-id",
9305
+ arn,
9306
+ "--query",
9307
+ "SecretString",
9308
+ "--output",
9309
+ "text"
9310
+ ],
9311
+ { env, timeoutMs: RUNNER_SECRET_FETCH_TIMEOUT_MS }
9312
+ );
9313
+ if (result.timedOut) {
9314
+ throw secretFailure(
9315
+ "CREDENTIAL-RESTORE-TIMEOUT",
9316
+ `runner-secret did not finish within ${RUNNER_SECRET_FETCH_TIMEOUT_MS}ms`,
9317
+ log3
9318
+ );
9319
+ }
9320
+ if (result.code !== 0) {
9321
+ throw secretFailure("RUNNER-SECRET-UNREADABLE", commandError2(result), log3);
9322
+ }
9323
+ let payload;
9324
+ try {
9325
+ payload = JSON.parse(result.stdout);
9326
+ } catch (error2) {
9327
+ log3(
9328
+ `RUNNER-SECRET-UNPARSEABLE: secret value is not a JSON object (${error2 instanceof Error ? error2.message : String(error2)})`,
9329
+ "warn"
9330
+ );
9331
+ return false;
9332
+ }
9333
+ if (!isEnvironmentObject(payload)) {
9334
+ log3("RUNNER-SECRET-UNPARSEABLE: secret value is not a JSON object", "warn");
9335
+ return false;
9336
+ }
9337
+ let populated = 0;
9338
+ let skipped = 0;
9339
+ let githubTokenPopulated = false;
9340
+ for (const [key, value] of Object.entries(payload)) {
9341
+ if (typeof value !== "string" || value.length === 0) continue;
9342
+ if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key)) {
9343
+ log3(
9344
+ `RUNNER-SECRET-KEY-SKIPPED: ${JSON.stringify(key)} is not a valid environment variable name`,
9345
+ "warn"
9346
+ );
9347
+ skipped += 1;
9348
+ continue;
9349
+ }
9350
+ env[key] = value;
9351
+ populated += 1;
9352
+ if (key === "GH_TOKEN") githubTokenPopulated = true;
9353
+ }
9354
+ if (populated === 0) {
9355
+ log3(
9356
+ "RUNNER-SECRET-UNPOPULATED: populate the runner secret as documented in infrastructure/evident-runner/MICROVM.md",
9357
+ "warn"
9358
+ );
9359
+ } else {
9360
+ log3(
9361
+ `RUNNER-SECRET-OK: exported ${populated} secret values; skipped ${skipped} invalid environment variable names`
9362
+ );
9363
+ }
9364
+ return githubTokenPopulated;
9365
+ }
9366
+ function restoreFailure(operation, result, log3) {
9367
+ const message = `CREDENTIAL-RESTORE-FAILED: ${operation} failed: ${commandError2(result)}`;
9368
+ log3(message, "error");
9369
+ return new Error(message);
9370
+ }
9371
+ async function runCredentialRestore(args, operation, log3, synchroniserRunner) {
9372
+ const result = await synchroniserRunner(args, { timeoutMs: CREDENTIAL_RESTORE_TIMEOUT_MS });
9373
+ if (result.timedOut) {
9374
+ log3(
9375
+ `CREDENTIAL-RESTORE-TIMEOUT: ${operation} did not finish within ${CREDENTIAL_RESTORE_TIMEOUT_MS}ms; continuing without it`,
9376
+ "warn"
9377
+ );
9378
+ return result;
9379
+ }
9380
+ if (result.code !== 0) throw restoreFailure(operation, result, log3);
9381
+ return result;
9382
+ }
9383
+ async function restoreCredentialStores({
9384
+ env,
9385
+ log: log3,
9386
+ synchroniserRunner = runSynchroniser
9387
+ }) {
9388
+ await runCredentialRestore(["restore", "claude"], "restore-claude", log3, synchroniserRunner);
9389
+ await runCredentialRestore(["restore", "opencode"], "restore-opencode", log3, synchroniserRunner);
9390
+ const result = await synchroniserRunner(["model-auth-ready"], {
9391
+ timeoutMs: CREDENTIAL_RESTORE_TIMEOUT_MS
9392
+ });
9393
+ if (result.timedOut) {
9394
+ log3(
9395
+ `CREDENTIAL-RESTORE-TIMEOUT: model-auth-ready did not finish within ${CREDENTIAL_RESTORE_TIMEOUT_MS}ms; continuing without it`,
9396
+ "warn"
9397
+ );
9398
+ return;
9399
+ }
9400
+ switch (result.code) {
9401
+ case 0:
9402
+ return;
9403
+ case 10:
9404
+ log3(
9405
+ `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.`,
9406
+ "warn"
9407
+ );
9408
+ return;
9409
+ default:
9410
+ log3("could not determine whether this VM has model credentials", "warn");
9411
+ }
9412
+ }
9413
+ var GIT_CREDENTIAL_HELPER_CONTENT = [
9414
+ "#!/usr/bin/env bash",
9415
+ '[ "$1" = get ] || exit 0',
9416
+ "echo username=x-access-token",
9417
+ 'echo "password=${GH_TOKEN}"',
9418
+ ""
9419
+ ].join("\n");
9420
+ async function probeGitHubAccess({ env, log: log3 }) {
9421
+ const auth = await runCommand2("gh", ["api", "user", "--jq", ".login"], {
9422
+ env,
9423
+ timeoutMs: GITHUB_PROBE_TIMEOUT_MS
9424
+ });
9425
+ if (auth.timedOut) {
9426
+ log3(`GITHUB-PROBE-TIMEOUT: auth probe exceeded ${GITHUB_PROBE_TIMEOUT_MS}ms`, "warn");
9427
+ return;
9428
+ }
9429
+ if (auth.code !== 0) {
9430
+ log3(`GITHUB-AUTH-REJECTED: ${commandError2(auth)}`, "warn");
9431
+ return;
9432
+ }
9433
+ log3(`GITHUB-AUTH-OK: ${auth.stdout.trim()}`, "debug");
9434
+ const remote = await runCommand2("git", ["-C", process.cwd(), "remote", "get-url", "origin"], {
9435
+ env,
9436
+ timeoutMs: GITHUB_PROBE_TIMEOUT_MS
9437
+ });
9438
+ if (remote.code !== 0 || remote.timedOut) return;
9439
+ const repo = remote.stdout.trim().replace(/^(?:https:\/\/github\.com\/|git@github\.com:)/, "").replace(/\.git$/, "");
9440
+ if (!repo) return;
9441
+ const repository = await runCommand2("gh", ["api", `repos/${repo}`, "--jq", ".full_name"], {
9442
+ env,
9443
+ timeoutMs: GITHUB_PROBE_TIMEOUT_MS
9444
+ });
9445
+ if (repository.timedOut) {
9446
+ log3(
9447
+ `GITHUB-PROBE-TIMEOUT: repository probe for ${repo} exceeded ${GITHUB_PROBE_TIMEOUT_MS}ms`,
9448
+ "warn"
9449
+ );
9450
+ } else if (repository.code !== 0) {
9451
+ log3(`GITHUB-REPO-INACCESSIBLE: ${repo}: ${commandError2(repository)}`, "warn");
9452
+ }
9453
+ }
9454
+ async function configureGitHubAccess({ env, log: log3 }) {
9455
+ if (!env.GH_TOKEN) {
9456
+ log3("GITHUB-CREDENTIALS-MISSING: GH_TOKEN is unavailable; see RUNNER-SECRET-* above", "warn");
9457
+ return;
9458
+ }
9459
+ try {
9460
+ env.GIT_CONFIG_GLOBAL = GIT_CONFIG_GLOBAL;
9461
+ writeFileSync4(GIT_CONFIG_GLOBAL, "");
9462
+ writeFileSync4(GIT_CREDENTIAL_HELPER, GIT_CREDENTIAL_HELPER_CONTENT, { mode: 448 });
9463
+ chmodSync2(GIT_CREDENTIAL_HELPER, 448);
9464
+ const config = [
9465
+ ["user.name", env.GIT_USER_NAME ?? "evident-bot"],
9466
+ ["user.email", env.GIT_USER_EMAIL ?? "evident-bot@users.noreply.github.com"],
9467
+ ["init.defaultBranch", "main"],
9468
+ ["credential.https://github.com.helper", GIT_CREDENTIAL_HELPER]
9469
+ ];
9470
+ for (const [key, value] of config) {
9471
+ const result = await runCommand2("git", ["config", "--global", key, value], {
9472
+ env,
9473
+ timeoutMs: GITHUB_PROBE_TIMEOUT_MS
9474
+ });
9475
+ if (result.timedOut || result.code !== 0) throw new Error(commandError2(result));
9476
+ }
9477
+ } catch (error2) {
9478
+ log3(
9479
+ `GITHUB-SETUP-FAILED: could not configure local git credentials; continuing without GitHub access (${error2 instanceof Error ? error2.message : String(error2)})`,
9480
+ "warn"
9481
+ );
9482
+ return;
9483
+ }
9484
+ void probeGitHubAccess({ env, log: log3 }).catch((error2) => {
9485
+ log3(
9486
+ `GITHUB-SETUP-FAILED: GitHub access probe failed: ${error2 instanceof Error ? error2.message : String(error2)}`,
9487
+ "warn"
9488
+ );
9489
+ });
9490
+ }
9491
+
9492
+ // src/lib/opencode/config-overlay.ts
9493
+ import { execFileSync as execFileSync2 } from "node:child_process";
9494
+ import { copyFileSync, existsSync as existsSync2, statSync as statSync5 } from "node:fs";
9495
+ import { isAbsolute as isAbsolute2, join as join8, resolve as resolve3 } from "node:path";
9496
+ function isFile(filePath) {
9497
+ return existsSync2(filePath) && statSync5(filePath).isFile();
9498
+ }
9499
+ function applyRunnerOpenCodeConfig({
9500
+ overlayPath,
9501
+ cwd = process.cwd(),
9502
+ log: log3
9503
+ }) {
9504
+ if (!overlayPath) {
9505
+ log3("runner OpenCode config is not configured; using the baked project config", "debug");
9506
+ return;
9507
+ }
9508
+ const source = isAbsolute2(overlayPath) ? overlayPath : resolve3(cwd, overlayPath);
9509
+ const target = isFile(join8(cwd, "opencode.jsonc")) ? "opencode.jsonc" : "opencode.json";
9510
+ if (!isFile(source)) {
9511
+ log3(
9512
+ `RUNNER-OPENCODE-CONFIG-MISSING: ${source} is not a file; headless turns will wedge on the first external-directory permission prompt (#563)`,
9513
+ "error"
9514
+ );
9515
+ return;
9516
+ }
9517
+ copyFileSync(source, join8(cwd, target));
9518
+ try {
9519
+ execFileSync2("git", ["-C", cwd, "update-index", "--skip-worktree", target], {
9520
+ stdio: "ignore"
9521
+ });
9522
+ } catch (error2) {
9523
+ const detail = error2 instanceof Error ? error2.message : String(error2);
9524
+ log3(`could not mark ${target} skip-worktree: ${detail}; it may show as a local change`, "warn");
9525
+ }
9526
+ log3(`Applied runner OpenCode config ${source} to ${join8(cwd, target)}`);
9527
+ }
9528
+
9529
+ // src/lib/credential-sync.ts
9530
+ import { renameSync, writeFileSync as writeFileSync5 } from "node:fs";
9531
+ var CREDENTIAL_SYNC_TICK_TIMEOUT_MS = 3e4;
9532
+ var CREDENTIAL_FLUSH_DEADLINE_MS = 8e3;
9533
+ var CREDENTIAL_FLUSH_ABORT_GRACE_MS = 500;
9534
+ var DEFAULT_CREDENTIAL_SYNC_INTERVAL_SECONDS = 60;
9535
+ var STORES = ["claude", "opencode"];
9536
+ var MAX_FLUSH_PASSES = 2;
9537
+ function outcomesWith(outcome) {
9538
+ return { claude: outcome, opencode: outcome };
9539
+ }
9540
+ function errorMessage2(error2) {
9541
+ return error2 instanceof Error ? error2.message : String(error2);
9542
+ }
9543
+ function waitForSettlement(promise, timeoutMs) {
9544
+ return new Promise((resolve4) => {
9545
+ let settled = false;
9546
+ const timer = setTimeout(() => finish(false), Math.max(0, timeoutMs));
9547
+ const finish = (value) => {
9548
+ if (settled) return;
9549
+ settled = true;
9550
+ clearTimeout(timer);
9551
+ resolve4(value);
9552
+ };
9553
+ promise.then(
9554
+ () => finish(true),
9555
+ () => finish(true)
9556
+ );
9557
+ });
9558
+ }
9559
+ function writeMarker(markerPath, outcomes, log3) {
9560
+ const body = `${STORES.map((store) => `${store}=${outcomes[store]}`).join("\n")}
9561
+ `;
9562
+ const temporaryPath = `${markerPath}.tmp`;
9563
+ try {
9564
+ writeFileSync5(temporaryPath, body, { mode: 384 });
9565
+ renameSync(temporaryPath, markerPath);
9566
+ } catch (error2) {
9567
+ log3(`CREDENTIAL-FLUSH-MARKER-UNWRITABLE: ${markerPath}: ${errorMessage2(error2)}`, "warn");
9568
+ }
9569
+ }
9570
+ function intervalSeconds(env, log3) {
9571
+ const raw = env.CREDS_SYNC_INTERVAL;
9572
+ if (raw === void 0 || /^[1-9][0-9]*$/.test(raw) && Number.isSafeInteger(Number(raw))) {
9573
+ return raw === void 0 ? DEFAULT_CREDENTIAL_SYNC_INTERVAL_SECONDS : Number(raw);
9574
+ }
9575
+ log3(
9576
+ `CREDENTIAL-SYNC-INTERVAL-INVALID: CREDS_SYNC_INTERVAL='${raw}' is not a positive integer; using ${DEFAULT_CREDENTIAL_SYNC_INTERVAL_SECONDS}s`,
9577
+ "warn"
9578
+ );
9579
+ return DEFAULT_CREDENTIAL_SYNC_INTERVAL_SECONDS;
9580
+ }
9581
+ async function runFlushStore(store, env, synchroniserRunner, log3, deadlineAt) {
9582
+ const remainingMs = deadlineAt - Date.now();
9583
+ if (remainingMs <= 0) return { outcome: "timeout", orphaned: false };
9584
+ const controller = new AbortController();
9585
+ let result;
9586
+ let failed = false;
9587
+ const completion = Promise.resolve().then(
9588
+ () => synchroniserRunner(["sync-once", store], {
9589
+ timeoutMs: remainingMs,
9590
+ env,
9591
+ signal: controller.signal
9592
+ })
9593
+ ).then(
9594
+ (value) => {
9595
+ result = value;
9596
+ },
9597
+ (error2) => {
9598
+ failed = true;
9599
+ log3(`CREDENTIAL-FLUSH-ERROR: ${store}: ${errorMessage2(error2)}`, "warn");
9600
+ }
9601
+ );
9602
+ const abortTimer = setTimeout(() => controller.abort(), remainingMs);
9603
+ const settledBeforeDeadline = await waitForSettlement(completion, remainingMs);
9604
+ clearTimeout(abortTimer);
9605
+ if (!settledBeforeDeadline) {
9606
+ controller.abort();
9607
+ const settledAfterAbort = await waitForSettlement(completion, CREDENTIAL_FLUSH_ABORT_GRACE_MS);
9608
+ if (!settledAfterAbort) return { outcome: "timeout", orphaned: true };
9609
+ return { outcome: "timeout", orphaned: false };
9610
+ }
9611
+ if (failed || !result) return { outcome: "failed", orphaned: false };
9612
+ if (result.timedOut || Date.now() >= deadlineAt) {
9613
+ return { outcome: "timeout", orphaned: false };
9614
+ }
9615
+ return { outcome: result.code === 0 ? "ok" : "failed", orphaned: false };
9616
+ }
9617
+ function createCredentialSync({
9618
+ markerPath,
9619
+ env,
9620
+ log: log3,
9621
+ synchroniserRunner = runSynchroniser
9622
+ }) {
9623
+ const persistenceDisabled = !env.PERSISTENCE_BUCKET;
9624
+ let disabled = persistenceDisabled;
9625
+ let armed = false;
9626
+ let stopped = false;
9627
+ let timer;
9628
+ let inFlight;
9629
+ let activeTickAbort;
9630
+ let lastTickFailed;
9631
+ let flushPromise;
9632
+ const scheduleTick = (intervalMs, startTick2) => {
9633
+ if (stopped) return;
9634
+ timer = setTimeout(() => {
9635
+ timer = void 0;
9636
+ startTick2();
9637
+ }, intervalMs);
9638
+ };
9639
+ const startTick = (intervalMs) => {
9640
+ if (stopped) return;
9641
+ const controller = new AbortController();
9642
+ activeTickAbort = controller;
9643
+ const tick = (async () => {
9644
+ const outcomes = {
9645
+ claude: "failed",
9646
+ opencode: "failed"
9647
+ };
9648
+ for (const store of STORES) {
9649
+ if (controller.signal.aborted) break;
9650
+ try {
9651
+ const result = await synchroniserRunner(["sync-once", store], {
9652
+ timeoutMs: CREDENTIAL_SYNC_TICK_TIMEOUT_MS,
9653
+ env,
9654
+ signal: controller.signal
9655
+ });
9656
+ outcomes[store] = !result.timedOut && result.code === 0 ? "ok" : "failed";
9657
+ } catch (error2) {
9658
+ outcomes[store] = "failed";
9659
+ log3(`CREDENTIAL-SYNC-TICK-ERROR: ${store}: ${errorMessage2(error2)}`, "debug");
9660
+ }
9661
+ }
9662
+ const failed = STORES.some((store) => outcomes[store] === "failed");
9663
+ log3(
9664
+ `CREDENTIAL-SYNC-TICK: claude=${outcomes.claude}, opencode=${outcomes.opencode}`,
9665
+ "debug"
9666
+ );
9667
+ if (failed && lastTickFailed !== true) {
9668
+ log3(
9669
+ "CREDENTIAL-SYNC-FAILED: an interval credential sync failed; retrying on the next tick",
9670
+ "warn"
9671
+ );
9672
+ } else if (!failed && lastTickFailed === true) {
9673
+ log3("CREDENTIAL-SYNC-RECOVERED: interval credential sync succeeded again", "warn");
9674
+ }
9675
+ lastTickFailed = failed;
9676
+ })().finally(() => {
9677
+ if (activeTickAbort === controller) activeTickAbort = void 0;
9678
+ if (inFlight === tick) inFlight = void 0;
9679
+ scheduleTick(intervalMs, () => startTick(intervalMs));
9680
+ });
9681
+ inFlight = tick;
9682
+ };
9683
+ const performFlush = async () => {
9684
+ stopped = true;
9685
+ if (timer) {
9686
+ clearTimeout(timer);
9687
+ timer = void 0;
9688
+ }
9689
+ const deadlineAt = Date.now() + CREDENTIAL_FLUSH_DEADLINE_MS;
9690
+ if (inFlight) {
9691
+ const settled = await waitForSettlement(inFlight, CREDENTIAL_FLUSH_DEADLINE_MS);
9692
+ if (!settled) {
9693
+ activeTickAbort?.abort();
9694
+ const settledAfterAbort = await waitForSettlement(
9695
+ inFlight,
9696
+ CREDENTIAL_FLUSH_ABORT_GRACE_MS
9697
+ );
9698
+ if (!settledAfterAbort) {
9699
+ log3(
9700
+ "CREDENTIAL-FLUSH-ORPHANED-TICK: a sync-once child could not be proven settled; skipping the boundary flush rather than becoming a second writer",
9701
+ "warn"
9702
+ );
9703
+ return { outcomes: outcomesWith("timeout"), orphaned: true };
9704
+ }
9705
+ }
9706
+ }
9707
+ if (disabled) return { outcomes: outcomesWith("skipped"), orphaned: false };
9708
+ const outcomes = outcomesWith("timeout");
9709
+ for (const store of STORES) {
9710
+ const result = await runFlushStore(store, env, synchroniserRunner, log3, deadlineAt);
9711
+ if (result.orphaned) {
9712
+ log3(
9713
+ "CREDENTIAL-FLUSH-ORPHANED-CHILD: a flush sync-once child could not be proven settled; refusing another flush pass rather than becoming a second writer",
9714
+ "warn"
9715
+ );
9716
+ return { outcomes: outcomesWith("timeout"), orphaned: true };
9717
+ }
9718
+ outcomes[store] = result.outcome;
9719
+ }
9720
+ return { outcomes, orphaned: false };
9721
+ };
9722
+ let flushPasses = 0;
9723
+ let lastFlush;
9724
+ return {
9725
+ arm() {
9726
+ if (stopped || armed) return;
9727
+ armed = true;
9728
+ if (persistenceDisabled) {
9729
+ disabled = true;
9730
+ log3(
9731
+ "CREDENTIAL-SYNC-DISABLED: LITESTREAM_BUCKET/LITESTREAM_PREFIX are not both set; no interval credential sync this boot",
9732
+ "warn"
9733
+ );
9734
+ return;
9735
+ }
9736
+ disabled = false;
9737
+ const intervalMs = intervalSeconds(env, log3) * 1e3;
9738
+ scheduleTick(intervalMs, () => startTick(intervalMs));
9739
+ },
9740
+ async stopAndFlush(publish) {
9741
+ let result;
9742
+ const runningFlush = flushPromise;
9743
+ if (runningFlush) {
9744
+ result = await runningFlush;
9745
+ } else if (flushPasses >= MAX_FLUSH_PASSES || lastFlush?.orphaned) {
9746
+ result = lastFlush ?? { outcomes: outcomesWith("timeout"), orphaned: true };
9747
+ } else {
9748
+ flushPasses++;
9749
+ const currentFlush = performFlush();
9750
+ flushPromise = currentFlush;
9751
+ try {
9752
+ result = await currentFlush;
9753
+ lastFlush = result;
9754
+ } finally {
9755
+ if (flushPromise === currentFlush) flushPromise = void 0;
9756
+ }
9757
+ }
9758
+ if (publish) writeMarker(markerPath, result.outcomes, log3);
9759
+ return result.outcomes;
9760
+ }
9761
+ };
9762
+ }
9763
+
9764
+ // src/commands/run.ts
9765
+ var MAX_ACTIVITY_LOG_ENTRIES = 10;
9766
+ var CHANNEL_POLL_INTERVAL_MS = Number(process.env.EVIDENT_CHANNEL_POLL_INTERVAL_MS) || 2e3;
9767
+ var CHANNEL_STUCK_QUEUED_MS = Number(process.env.EVIDENT_STUCK_QUEUED_MS) || void 0;
9768
+ var SHUTDOWN_DRAIN_TIMEOUT_MS = Number(process.env.EVIDENT_SHUTDOWN_DRAIN_MS) || 25e3;
9769
+ var TELEMETRY_SHUTDOWN_TIMEOUT_MS = 5e3;
9770
+ var CHILD_STOP_TIMEOUT_MS = 1e4;
9771
+ function resolveLogLevel(options) {
9772
+ const accepted = Object.keys(LOG_LEVELS);
9773
+ const validate = (value, source) => {
9774
+ const normalized = value.trim().toLowerCase();
9775
+ if (!accepted.includes(normalized)) {
9776
+ throw new Error(
9777
+ `Invalid log level "${value}"${source}; expected one of ${accepted.join(", ")}`
9778
+ );
9779
+ }
9780
+ return normalized;
9781
+ };
9782
+ if (options.logLevel !== void 0) {
9783
+ return validate(options.logLevel, " (--log-level)");
9784
+ }
9785
+ if (options.verbose) {
9786
+ return "debug";
9787
+ }
9788
+ const env = process.env.EVIDENT_LOG_LEVEL;
9789
+ if (env !== void 0 && env !== "") {
9790
+ return validate(env, " (EVIDENT_LOG_LEVEL)");
9791
+ }
9792
+ return "info";
9793
+ }
9794
+ function resolveFileSyncDirectories(raw, homeDir) {
9795
+ const directories = [];
9796
+ for (const entry of raw ?? []) {
9797
+ const trimmed = entry.trim();
9798
+ if (trimmed === "") {
9799
+ throw new Error("--enable-file-sync-to requires a directory path (got an empty value)");
9800
+ }
9801
+ const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join9(homeDir, trimmed.slice(2)) : trimmed;
9802
+ if (!isAbsolute3(expanded)) {
9803
+ throw new Error(`--enable-file-sync-to requires an absolute directory path; got "${entry}"`);
9804
+ }
9805
+ const normalized = resolvePath2(expanded);
9806
+ if (parse(normalized).root === normalized) {
9807
+ throw new Error(
9808
+ `--enable-file-sync-to will not allow-list the filesystem root ("${entry}"); name the specific directory the credentials belong in (for example ~/.claude)`
9809
+ );
9810
+ }
9811
+ if (!directories.includes(normalized)) {
9812
+ directories.push(normalized);
9813
+ }
9814
+ }
9815
+ if (directories.length > MAX_FILE_SYNC_DIRECTORIES) {
9816
+ throw new Error(
9817
+ `--enable-file-sync-to accepts at most ${MAX_FILE_SYNC_DIRECTORIES} directories; got ${directories.length}`
9818
+ );
9819
+ }
9820
+ return directories;
9821
+ }
9822
+ var DEFAULT_OPENCODE_START_TIMEOUT_SECONDS = 180;
9823
+ var MAX_OPENCODE_START_TIMEOUT_SECONDS = 3600;
9824
+ var OPENCODE_START_TIMEOUT_ENV = "EVIDENT_OPENCODE_START_TIMEOUT";
9825
+ var OPENCODE_VERSION_ENV = "EVIDENT_OPENCODE_VERSION";
9826
+ function resolveOpenCodeVersion(options, env = process.env) {
9827
+ let raw;
9828
+ let source;
9829
+ if (options.opencodeVersion !== void 0) {
9830
+ raw = options.opencodeVersion;
9831
+ source = "--opencode-version";
9832
+ } else if (env[OPENCODE_VERSION_ENV] !== void 0 && env[OPENCODE_VERSION_ENV] !== "") {
9833
+ raw = env[OPENCODE_VERSION_ENV];
9834
+ source = OPENCODE_VERSION_ENV;
9835
+ } else {
9836
+ return { version: "v1", warnings: [] };
9837
+ }
9838
+ const normalized = raw.trim().toLowerCase();
9839
+ if (normalized !== "v1" && normalized !== "v2") {
9840
+ return {
9841
+ version: "v1",
9842
+ warnings: [`Ignoring invalid ${source} "${raw}": expected v1 or v2; using the default v1`]
9843
+ };
9844
+ }
9845
+ return { version: normalized, warnings: [] };
9846
+ }
9847
+ function resolveOpenCodeStartTimeoutMs(options, env = process.env) {
9848
+ const defaultMs = DEFAULT_OPENCODE_START_TIMEOUT_SECONDS * 1e3;
9849
+ let raw;
9850
+ let source;
9851
+ if (options.opencodeStartTimeout !== void 0) {
9852
+ raw = options.opencodeStartTimeout;
9853
+ source = "--opencode-start-timeout";
9854
+ } else if (env[OPENCODE_START_TIMEOUT_ENV] !== void 0 && env[OPENCODE_START_TIMEOUT_ENV] !== "") {
9855
+ raw = env[OPENCODE_START_TIMEOUT_ENV];
9856
+ source = OPENCODE_START_TIMEOUT_ENV;
9857
+ } else {
9858
+ return { timeoutMs: defaultMs, warnings: [] };
9859
+ }
9860
+ const trimmed = raw.trim();
9861
+ const seconds = Number(trimmed);
9862
+ const isPositiveInteger = /^\d+$/.test(trimmed) && Number.isInteger(seconds) && seconds > 0;
9863
+ if (!isPositiveInteger || seconds > MAX_OPENCODE_START_TIMEOUT_SECONDS) {
9864
+ return {
9865
+ timeoutMs: defaultMs,
9866
+ warnings: [
9867
+ `Ignoring invalid ${source} "${raw}": expected a positive integer number of seconds (at most ${MAX_OPENCODE_START_TIMEOUT_SECONDS}); using the default ${DEFAULT_OPENCODE_START_TIMEOUT_SECONDS}s`
9868
+ ]
8129
9869
  };
8130
9870
  }
8131
9871
  return { timeoutMs: seconds * 1e3, warnings: [] };
@@ -8170,7 +9910,7 @@ function log2(state, message, level = "info") {
8170
9910
  })
8171
9911
  );
8172
9912
  } else if (!state.interactive) {
8173
- const prefix = level === "error" ? chalk6.red("\u2717") : level === "warn" ? chalk6.yellow("!") : level === "debug" ? chalk6.dim("\xB7") : chalk6.green("\u2022");
9913
+ const prefix = level === "error" ? chalk7.red("\u2717") : level === "warn" ? chalk7.yellow("!") : level === "debug" ? chalk7.dim("\xB7") : chalk7.green("\u2022");
8174
9914
  console.log(`${prefix} ${message}`);
8175
9915
  }
8176
9916
  }
@@ -8200,7 +9940,7 @@ function logActivity(state, entry) {
8200
9940
  }
8201
9941
  function reportSessionDbRecovery(state) {
8202
9942
  try {
8203
- const report = drainSessionDbRecoveryReport({ homeDir: homedir4(), env: process.env });
9943
+ const report = drainSessionDbRecoveryReport({ homeDir: homedir5(), env: process.env });
8204
9944
  for (const record of report.records) {
8205
9945
  const activity = buildSessionDbRecoveryActivity(record);
8206
9946
  if (!activity) throw new Error("could not map session-DB recovery record");
@@ -8218,21 +9958,31 @@ function reportSessionDbRecovery(state) {
8218
9958
  );
8219
9959
  }
8220
9960
  }
9961
+ function reportSessionDbRecoveryRecord(state, record) {
9962
+ const activity = buildSessionDbRecoveryActivity(record);
9963
+ if (!activity) throw new Error("could not map session-DB recovery record");
9964
+ logActivity(state, {
9965
+ type: activity.level === "error" ? "error" : "info",
9966
+ level: activity.level,
9967
+ ...activity.level === "error" ? { error: activity.message } : { message: activity.message },
9968
+ metadata: activity.metadata
9969
+ });
9970
+ }
8221
9971
  function displayStatus(state) {
8222
9972
  if (!state.interactive) return;
8223
9973
  const attempt = state.connection?.reconnectAttempt ?? 0;
8224
- const tunnel = state.connected ? chalk6.green("tunnel: connected") : attempt > 0 ? chalk6.yellow(`tunnel: reconnecting (#${attempt})`) : chalk6.yellow("tunnel: connecting");
8225
- const opencode = state.opencodeConnected ? chalk6.green(`opencode: :${state.port}`) : chalk6.red(`opencode: :${state.port} (down)`);
8226
- const messages = state.messageCount > 0 ? chalk6.dim(` \xB7 ${state.messageCount} processed`) : "";
9974
+ const tunnel = state.connected ? chalk7.green("tunnel: connected") : attempt > 0 ? chalk7.yellow(`tunnel: reconnecting (#${attempt})`) : chalk7.yellow("tunnel: connecting");
9975
+ const opencode = state.opencodeConnected ? chalk7.green(`opencode: :${state.port}`) : chalk7.red(`opencode: :${state.port} (down)`);
9976
+ const messages = state.messageCount > 0 ? chalk7.dim(` \xB7 ${state.messageCount} processed`) : "";
8227
9977
  const last = state.activityLog[state.activityLog.length - 1];
8228
- const detail = last ? chalk6.dim(` \xB7 ${last.type === "error" ? last.error ?? "" : last.message ?? ""}`) : "";
9978
+ const detail = last ? chalk7.dim(` \xB7 ${last.type === "error" ? last.error ?? "" : last.message ?? ""}`) : "";
8229
9979
  const agent = state.agentName ?? state.agentId;
8230
9980
  console.log(
8231
- `${chalk6.bold("Evident")} ${chalk6.dim(agent)} ${tunnel} ${opencode}${messages}${detail}`
9981
+ `${chalk7.bold("Evident")} ${chalk7.dim(agent)} ${tunnel} ${opencode}${messages}${detail}`
8232
9982
  );
8233
9983
  }
8234
9984
  async function promptForLogin(promptMessage, successMessage) {
8235
- const action = await select3({
9985
+ const action = await select4({
8236
9986
  message: promptMessage,
8237
9987
  choices: [
8238
9988
  {
@@ -8248,7 +9998,7 @@ async function promptForLogin(promptMessage, successMessage) {
8248
9998
  ]
8249
9999
  });
8250
10000
  if (action === "exit") {
8251
- console.log(chalk6.dim(`
10001
+ console.log(chalk7.dim(`
8252
10002
  You can log in later by running: ${getCliName()} login`));
8253
10003
  process.exit(0);
8254
10004
  }
@@ -8259,7 +10009,7 @@ You can log in later by running: ${getCliName()} login`));
8259
10009
  process.exit(1);
8260
10010
  }
8261
10011
  blank();
8262
- console.log(chalk6.green(successMessage));
10012
+ console.log(chalk7.green(successMessage));
8263
10013
  blank();
8264
10014
  return { token: credentials2.token, authType: "bearer", user: credentials2.user };
8265
10015
  }
@@ -8272,12 +10022,12 @@ async function handleAuthError(state, error2) {
8272
10022
  if (state.interactive) displayStatus(state);
8273
10023
  if (!state.interactive) {
8274
10024
  blank();
8275
- console.log(chalk6.red("Authentication expired"));
8276
- console.log(chalk6.dim("Your authentication token is no longer valid."));
10025
+ console.log(chalk7.red("Authentication expired"));
10026
+ console.log(chalk7.dim("Your authentication token is no longer valid."));
8277
10027
  blank();
8278
- console.log(chalk6.dim("To fix this:"));
8279
- console.log(chalk6.dim(` 1. Run '${getCliName()} login' to re-authenticate`));
8280
- console.log(chalk6.dim(" 2. Restart this command"));
10028
+ console.log(chalk7.dim("To fix this:"));
10029
+ console.log(chalk7.dim(` 1. Run '${getCliName()} login' to re-authenticate`));
10030
+ console.log(chalk7.dim(" 2. Restart this command"));
8281
10031
  blank();
8282
10032
  await cleanup(state);
8283
10033
  await shutdownTelemetry();
@@ -8285,7 +10035,7 @@ async function handleAuthError(state, error2) {
8285
10035
  return { success: false };
8286
10036
  }
8287
10037
  blank();
8288
- console.log(chalk6.yellow("Your authentication has expired."));
10038
+ console.log(chalk7.yellow("Your authentication has expired."));
8289
10039
  blank();
8290
10040
  try {
8291
10041
  const credentials2 = await promptForLogin(
@@ -8330,6 +10080,10 @@ async function driveChannels(state, driver) {
8330
10080
  consecutiveDrainFailures = 0;
8331
10081
  unreachableMs = 0;
8332
10082
  state.messageCount += processed;
10083
+ if (driver.recycleRequested) {
10084
+ await beginGracefulShutdown(state, "recycle");
10085
+ return;
10086
+ }
8333
10087
  const proxiedActivity = state.lastProxiedActivityAt !== lastSeenProxiedActivityAt;
8334
10088
  lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
8335
10089
  const fileActivitySnapshot = driver.fileSyncActivity();
@@ -8372,8 +10126,8 @@ async function driveChannels(state, driver) {
8372
10126
  state.running = false;
8373
10127
  break;
8374
10128
  }
8375
- const errorMessage = error2 instanceof Error ? error2.message : String(error2);
8376
- logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage}` });
10129
+ const errorMessage3 = error2 instanceof Error ? error2.message : String(error2);
10130
+ logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage3}` });
8377
10131
  if (state.interactive) displayStatus(state);
8378
10132
  if (driver.hasInFlightWatchers()) {
8379
10133
  consecutiveDrainFailures = 0;
@@ -8390,7 +10144,7 @@ async function driveChannels(state, driver) {
8390
10144
  }
8391
10145
  }
8392
10146
  }
8393
- await new Promise((resolve3) => setTimeout(resolve3, CHANNEL_POLL_INTERVAL_MS));
10147
+ await new Promise((resolve4) => setTimeout(resolve4, CHANNEL_POLL_INTERVAL_MS));
8394
10148
  const cycleMs = performance.now() - cycleStartedAtMs;
8395
10149
  if (idleThisCycle) idleMs += cycleMs;
8396
10150
  if (unreachableThisCycle) unreachableMs += cycleMs;
@@ -8411,9 +10165,54 @@ async function driveChannels(state, driver) {
8411
10165
  }
8412
10166
  }
8413
10167
  var SESSION_CLEANUP_FIRST_SWEEP_MS = 1e4;
8414
- var SESSION_DB_RECLAIM_MAX_PAGES = 2e3;
10168
+ var SESSION_DB_RECLAIM_MAX_PAGES = 2e4;
10169
+ function shouldWarnForReclaimSkip(reason) {
10170
+ if (reason !== "sqlite-unavailable") return false;
10171
+ const version2 = /^v(\d+)\.(\d+)\.(\d+)$/.exec(process.version);
10172
+ if (!version2) return false;
10173
+ const major = Number(version2[1]);
10174
+ const minor = Number(version2[2]);
10175
+ const patch = Number(version2[3]);
10176
+ return major > 22 || major === 22 && (minor > 13 || minor === 13 && patch >= 0);
10177
+ }
8415
10178
  function sessionDbPath() {
8416
- return join7(homedir4(), ".local", "share", "opencode", "opencode.db");
10179
+ return join9(homedir5(), ".local", "share", "opencode", "opencode.db");
10180
+ }
10181
+ function logSessionDbProvenanceMismatch(state, provenance, currentVersion, preBootMigrationCount) {
10182
+ const record = {
10183
+ v: 1,
10184
+ event: "session_db_recovery",
10185
+ at: (/* @__PURE__ */ new Date()).toISOString(),
10186
+ stage: "verify",
10187
+ outcome: "schema_provenance_mismatch",
10188
+ severity: "error",
10189
+ reason: provenance.reason ?? "schema-provenance-mismatch",
10190
+ litestream_exit_code: null,
10191
+ attempt: null,
10192
+ replica_objects: null,
10193
+ replica_bytes: null,
10194
+ quarantine_destination: null,
10195
+ quarantined_objects: null,
10196
+ quarantine_failed_objects: null,
10197
+ quarantined_bytes: null,
10198
+ verified_restore_point: null,
10199
+ restore_points_tried: null,
10200
+ provenance_reason: provenance.reason,
10201
+ provenance_migration_delta: provenance.migrationDelta,
10202
+ replication_suspended: false,
10203
+ dbPath: sessionDbPath(),
10204
+ recorded_version: provenance.recordedVersion,
10205
+ current_version: currentVersion,
10206
+ provenance_pre_boot_migration_count: preBootMigrationCount
10207
+ };
10208
+ const activity = buildSessionDbRecoveryActivity(record);
10209
+ if (!activity) throw new Error("could not map session-DB provenance activity");
10210
+ logActivity(state, {
10211
+ type: activity.level === "error" ? "error" : "info",
10212
+ level: activity.level,
10213
+ ...activity.level === "error" ? { error: activity.message } : { message: activity.message },
10214
+ metadata: activity.metadata
10215
+ });
8417
10216
  }
8418
10217
  async function runSweep(state, driver, config) {
8419
10218
  const mode = `age=${config.maxAgeMs ?? "\u2014"} count=${config.maxCount ?? "\u2014"}`;
@@ -8460,7 +10259,7 @@ async function runSweep(state, driver, config) {
8460
10259
  const reclaimResult = await reclaimSessionDbSpace({
8461
10260
  dbPath: sessionDbPath(),
8462
10261
  maxPages: SESSION_DB_RECLAIM_MAX_PAGES,
8463
- allowFullVacuum: protectedNow.size === 0
10262
+ allowFullVacuum: protectedNow.size === 0 && !state.sessionDbProvenanceAnomaly
8464
10263
  });
8465
10264
  if (reclaimResult.ok) {
8466
10265
  const beforeMib = (reclaimResult.beforeBytes / 1024 / 1024).toFixed(1);
@@ -8473,7 +10272,7 @@ async function runSweep(state, driver, config) {
8473
10272
  } else {
8474
10273
  logActivity(state, {
8475
10274
  type: "info",
8476
- message: `Session cleanup: session-db space reclaim skipped (${reclaimResult.skipped})`
10275
+ message: `Session cleanup: session-db space reclaim skipped (${reclaimResult.skipped})` + (reclaimResult.detail ? `: ${reclaimResult.detail}` : "")
8477
10276
  });
8478
10277
  }
8479
10278
  } catch (error2) {
@@ -8496,13 +10295,20 @@ function scheduleSessionCleanup(state, driver, options) {
8496
10295
  for (const warning2 of config.warnings) {
8497
10296
  logActivity(state, { type: "info", level: "warn", message: `Session cleanup: ${warning2}` });
8498
10297
  }
8499
- const dbBytes = statSessionDbBytes(homedir4());
10298
+ const dbBytes = statSessionDbBytes(homedir5());
8500
10299
  void (async () => {
8501
- const reclaimSkipReason = dbBytes !== null && config.enabled ? await probeReclaimAvailability({ dbPath: sessionDbPath(), requiredBytes: dbBytes }) : null;
10300
+ const reclaimAvailability = dbBytes !== null && config.enabled ? await probeReclaimAvailability({ dbPath: sessionDbPath(), requiredBytes: dbBytes }) : null;
10301
+ if (reclaimAvailability !== null) {
10302
+ logActivity(state, {
10303
+ type: "info",
10304
+ level: shouldWarnForReclaimSkip(reclaimAvailability.reason) ? "warn" : "info",
10305
+ message: `Session cleanup: reclaim preflight skipped (${reclaimAvailability.reason})` + (reclaimAvailability.detail ? `: ${reclaimAvailability.detail}` : "")
10306
+ });
10307
+ }
8502
10308
  const sizeWarning = buildSessionStoreSizeWarning({
8503
10309
  dbBytes,
8504
10310
  cleanupEnabled: config.enabled,
8505
- reclaimSkipReason
10311
+ reclaimSkipReason: reclaimAvailability?.reason ?? null
8506
10312
  });
8507
10313
  if (sizeWarning !== null) {
8508
10314
  logActivity(state, { type: "info", level: "warn", message: sizeWarning });
@@ -8697,7 +10503,8 @@ function scheduleResourceUsageReporting(state, options) {
8697
10503
  });
8698
10504
  return;
8699
10505
  }
8700
- const collect = createResourceUsageCollector(homedir4());
10506
+ const { collect, stop } = createResourceUsageCollector(homedir5());
10507
+ state.stopResourceUsageSampling = stop;
8701
10508
  let consecutiveFailures = 0;
8702
10509
  const tick = async () => {
8703
10510
  try {
@@ -8807,21 +10614,41 @@ async function cleanup(state, opts = {}) {
8807
10614
  clearTimeout(state.resourceUsageTimer);
8808
10615
  state.resourceUsageTimer = null;
8809
10616
  }
10617
+ state.stopResourceUsageSampling?.();
10618
+ state.stopResourceUsageSampling = null;
10619
+ const credentialSync = state.credentialSync;
10620
+ const flushCredentials = credentialSync ? async (phase, publish) => {
10621
+ await timeShutdownPhase(state, durations, phase, async () => {
10622
+ const outcomes = await credentialSync.stopAndFlush(publish);
10623
+ const level = Object.values(outcomes).every((outcome) => outcome === "ok") ? "info" : "warn";
10624
+ log2(
10625
+ state,
10626
+ `Credential flush: claude=${outcomes.claude}, opencode=${outcomes.opencode}`,
10627
+ level
10628
+ );
10629
+ });
10630
+ } : void 0;
10631
+ let drainSettled = true;
8810
10632
  if (opts.graceful && state.channelDriver) {
8811
10633
  state.channelDriver.stop();
10634
+ }
10635
+ if (flushCredentials) {
10636
+ await flushCredentials("credential_flush", !(opts.graceful && state.channelDriver));
10637
+ }
10638
+ if (opts.graceful && state.channelDriver) {
8812
10639
  log2(state, "Draining in-flight channel work before shutdown...");
8813
10640
  if (state.interactive) {
8814
10641
  logActivity(state, { type: "info", message: "Draining in-flight work before shutdown..." });
8815
10642
  displayStatus(state);
8816
10643
  }
8817
10644
  const driver = state.channelDriver;
8818
- const settled = await timeShutdownPhase(
10645
+ drainSettled = await timeShutdownPhase(
8819
10646
  state,
8820
10647
  durations,
8821
10648
  "drain",
8822
10649
  () => driver.waitForInFlight(SHUTDOWN_DRAIN_TIMEOUT_MS)
8823
10650
  );
8824
- if (!settled) {
10651
+ if (!drainSettled) {
8825
10652
  logActivity(state, {
8826
10653
  type: "info",
8827
10654
  message: "Shutdown drain timed out with work still in flight \u2014 leaving it for restart recovery"
@@ -8829,6 +10656,9 @@ async function cleanup(state, opts = {}) {
8829
10656
  if (state.interactive) displayStatus(state);
8830
10657
  }
8831
10658
  }
10659
+ if (opts.graceful && state.channelDriver && flushCredentials && drainSettled) {
10660
+ await flushCredentials("credential_flush_final", true);
10661
+ }
8832
10662
  await timeShutdownPhase(state, durations, "offline_notify", () => notifyOffline(state));
8833
10663
  if (state.connection) {
8834
10664
  const connection = state.connection;
@@ -8864,13 +10694,56 @@ async function cleanup(state, opts = {}) {
8864
10694
  }
8865
10695
  return durations;
8866
10696
  }
10697
+ async function beginGracefulShutdown(state, trigger) {
10698
+ if (state.shuttingDown) return;
10699
+ state.shuttingDown = true;
10700
+ const shutdownStartedAt = Date.now();
10701
+ const shutdownMessage = trigger === "recycle" ? "Recycle requested \u2014 finishing in-flight work, then exiting" : "Shutting down...";
10702
+ if (state.interactive) {
10703
+ logActivity(state, { type: "info", message: shutdownMessage });
10704
+ displayStatus(state);
10705
+ } else {
10706
+ log2(state, shutdownMessage);
10707
+ }
10708
+ const durations = await cleanup(state, { graceful: true });
10709
+ const telemetryBudgetMs = Number(process.env.EVIDENT_TELEMETRY_SHUTDOWN_MS) || TELEMETRY_SHUTDOWN_TIMEOUT_MS;
10710
+ await timeShutdownPhase(state, durations, "telemetry_flush", async () => {
10711
+ let timer;
10712
+ const flushed = shutdownTelemetry().then(
10713
+ () => true,
10714
+ (error2) => {
10715
+ log2(
10716
+ state,
10717
+ `Telemetry flush failed during shutdown: ${error2 instanceof Error ? error2.message : String(error2)}`,
10718
+ "warn"
10719
+ );
10720
+ return true;
10721
+ }
10722
+ );
10723
+ const timedOut = new Promise((resolve4) => {
10724
+ timer = setTimeout(() => resolve4(false), telemetryBudgetMs);
10725
+ });
10726
+ if (!await Promise.race([flushed, timedOut])) {
10727
+ log2(state, `Telemetry flush exceeded ${telemetryBudgetMs}ms \u2014 exiting anyway`, "warn");
10728
+ }
10729
+ clearTimeout(timer);
10730
+ });
10731
+ const breakdown = Object.entries(durations).map(([phase, ms]) => `${phase}=${ms}ms`).join(" ");
10732
+ log2(state, `Shutdown complete in ${Date.now() - shutdownStartedAt}ms (${breakdown})`);
10733
+ process.exit(0);
10734
+ }
8867
10735
  async function run(options) {
8868
10736
  const interactive = isInteractive(options.json);
8869
10737
  let logLevel;
8870
10738
  let fileSyncDirectories;
8871
10739
  try {
8872
10740
  logLevel = resolveLogLevel(options);
8873
- fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir4());
10741
+ fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir5());
10742
+ if (options.restoreSessionDb && !options.sessionDbNoReplicateMarker) {
10743
+ throw new Error(
10744
+ "--restore-session-db requires --session-db-no-replicate-marker <path>; restore failures must block Litestream replication"
10745
+ );
10746
+ }
8874
10747
  } catch (error2) {
8875
10748
  const message = error2 instanceof Error ? error2.message : String(error2);
8876
10749
  if (options.json) {
@@ -8894,6 +10767,7 @@ async function run(options) {
8894
10767
  connected: false,
8895
10768
  opencodeConnected: false,
8896
10769
  opencodeVersion: null,
10770
+ sessionDbProvenanceAnomaly: false,
8897
10771
  opencodeProcess: null,
8898
10772
  litestreamProcess: null,
8899
10773
  connection: null,
@@ -8909,9 +10783,24 @@ async function run(options) {
8909
10783
  openaiUsageTimer: null,
8910
10784
  openaiUsageRearm: null,
8911
10785
  resourceUsageTimer: null,
10786
+ stopResourceUsageSampling: null,
10787
+ credentialSync: null,
8912
10788
  authHeader: ""
8913
10789
  };
8914
10790
  setTelemetryAuthProvider(() => ({ authHeader: state.authHeader, agentId: state.agentId }));
10791
+ if (options.credentialSyncMarker) {
10792
+ state.credentialSync = createCredentialSync({
10793
+ markerPath: options.credentialSyncMarker,
10794
+ env: process.env,
10795
+ log: (message, level = "info") => {
10796
+ if (level === "error") {
10797
+ logActivity(state, { type: "error", error: message });
10798
+ } else {
10799
+ logActivity(state, { type: "info", level, message });
10800
+ }
10801
+ }
10802
+ });
10803
+ }
8915
10804
  if (fileSyncDirectories.length > 0) {
8916
10805
  log2(state, `File sync enabled for: ${fileSyncDirectories.join(", ")}`);
8917
10806
  } else {
@@ -8937,43 +10826,7 @@ async function run(options) {
8937
10826
  "warn"
8938
10827
  );
8939
10828
  }
8940
- const handleSignal = async () => {
8941
- if (state.shuttingDown) return;
8942
- state.shuttingDown = true;
8943
- const shutdownStartedAt = Date.now();
8944
- if (state.interactive) {
8945
- logActivity(state, { type: "info", message: "Shutting down..." });
8946
- displayStatus(state);
8947
- } else {
8948
- log2(state, "Shutting down...");
8949
- }
8950
- const durations = await cleanup(state, { graceful: true });
8951
- const telemetryBudgetMs = Number(process.env.EVIDENT_TELEMETRY_SHUTDOWN_MS) || TELEMETRY_SHUTDOWN_TIMEOUT_MS;
8952
- await timeShutdownPhase(state, durations, "telemetry_flush", async () => {
8953
- let timer;
8954
- const flushed = shutdownTelemetry().then(
8955
- () => true,
8956
- (error2) => {
8957
- log2(
8958
- state,
8959
- `Telemetry flush failed during shutdown: ${error2 instanceof Error ? error2.message : String(error2)}`,
8960
- "warn"
8961
- );
8962
- return true;
8963
- }
8964
- );
8965
- const timedOut = new Promise((resolve3) => {
8966
- timer = setTimeout(() => resolve3(false), telemetryBudgetMs);
8967
- });
8968
- if (!await Promise.race([flushed, timedOut])) {
8969
- log2(state, `Telemetry flush exceeded ${telemetryBudgetMs}ms \u2014 exiting anyway`, "warn");
8970
- }
8971
- clearTimeout(timer);
8972
- });
8973
- const breakdown = Object.entries(durations).map(([phase, ms]) => `${phase}=${ms}ms`).join(" ");
8974
- log2(state, `Shutdown complete in ${Date.now() - shutdownStartedAt}ms (${breakdown})`);
8975
- process.exit(0);
8976
- };
10829
+ const handleSignal = () => beginGracefulShutdown(state, "signal");
8977
10830
  process.on("SIGINT", handleSignal);
8978
10831
  process.on("SIGTERM", handleSignal);
8979
10832
  try {
@@ -8983,15 +10836,15 @@ async function run(options) {
8983
10836
  printError("Authentication required");
8984
10837
  blank();
8985
10838
  console.log(
8986
- chalk6.dim("Set EVIDENT_RUNNER_KEY (or EVIDENT_AGENT_KEY) environment variable for CI")
10839
+ chalk7.dim("Set EVIDENT_RUNNER_KEY (or EVIDENT_AGENT_KEY) environment variable for CI")
8987
10840
  );
8988
- console.log(chalk6.dim("Or run `evident login` for interactive authentication"));
10841
+ console.log(chalk7.dim("Or run `evident login` for interactive authentication"));
8989
10842
  blank();
8990
10843
  process.exit(1);
8991
10844
  return;
8992
10845
  }
8993
10846
  blank();
8994
- console.log(chalk6.yellow("You are not logged in to Evident."));
10847
+ console.log(chalk7.yellow("You are not logged in to Evident."));
8995
10848
  blank();
8996
10849
  credentials2 = await promptForLogin(
8997
10850
  "Would you like to log in now?",
@@ -9041,7 +10894,7 @@ async function run(options) {
9041
10894
  );
9042
10895
  blank();
9043
10896
  console.log(
9044
- chalk6.dim(
10897
+ chalk7.dim(
9045
10898
  "Either provide --runner/--agent <id> or set EVIDENT_RUNNER_KEY/EVIDENT_AGENT_KEY"
9046
10899
  )
9047
10900
  );
@@ -9064,15 +10917,15 @@ async function run(options) {
9064
10917
  );
9065
10918
  if (interactive && !state.json) {
9066
10919
  blank();
9067
- console.log(chalk6.bold("Evident Run"));
9068
- console.log(chalk6.dim("-".repeat(40)));
10920
+ console.log(chalk7.bold("Evident Run"));
10921
+ console.log(chalk7.dim("-".repeat(40)));
9069
10922
  }
9070
10923
  const spinner = interactive && !state.json ? ora3("Validating runner...").start() : null;
9071
10924
  let validation = await getAgentInfo(state.agentId, state.authHeader);
9072
10925
  if (!validation.valid && validation.authFailed && interactive) {
9073
10926
  spinner?.fail("Authentication failed");
9074
10927
  blank();
9075
- console.log(chalk6.yellow("Your authentication token is invalid or expired."));
10928
+ console.log(chalk7.yellow("Your authentication token is invalid or expired."));
9076
10929
  blank();
9077
10930
  credentials2 = await promptForLogin(
9078
10931
  "Would you like to log in again?",
@@ -9103,27 +10956,133 @@ async function run(options) {
9103
10956
  } else {
9104
10957
  log2(state, "Not running in a MicroVM (MICROVM_ID unset) \u2014 nothing to report", "debug");
9105
10958
  }
10959
+ if (options.restoreRunnerCredentials) {
10960
+ log2(state, "Restoring runner credentials before starting OpenCode");
10961
+ const credentialContext = {
10962
+ env: process.env,
10963
+ log: (message, level = "info") => {
10964
+ if (level === "error") {
10965
+ logActivity(state, { type: "error", error: message });
10966
+ } else {
10967
+ logActivity(state, { type: "info", level, message });
10968
+ }
10969
+ }
10970
+ };
10971
+ const githubTokenPopulated = await installRunnerSecret(credentialContext);
10972
+ await restoreCredentialStores(credentialContext);
10973
+ if (githubTokenPopulated) await configureGitHubAccess(credentialContext);
10974
+ }
10975
+ state.credentialSync?.arm();
10976
+ let sessionDbVerifyFatal = false;
10977
+ if (!options.restoreSessionDb) {
10978
+ log2(state, "Skipping session-DB restore: --restore-session-db was not passed", "debug");
10979
+ } else {
10980
+ const health = await checkOpenCodeHealth(state.port);
10981
+ if (health.healthy) {
10982
+ log2(
10983
+ state,
10984
+ "Skipping session-DB restore: OpenCode is already serving this database",
10985
+ "debug"
10986
+ );
10987
+ } else {
10988
+ const result = await restoreAndVerifySessionDb({
10989
+ dbPath: sessionDbPath(),
10990
+ litestreamConfig: options.litestreamConfig,
10991
+ noReplicateMarker: options.sessionDbNoReplicateMarker,
10992
+ env: process.env,
10993
+ log: (message, level = "info") => {
10994
+ if (level === "error") {
10995
+ logActivity(state, { type: "error", error: message });
10996
+ } else {
10997
+ logActivity(state, { type: "info", level, message });
10998
+ }
10999
+ },
11000
+ reportRecovery: (record) => reportSessionDbRecoveryRecord(state, record)
11001
+ });
11002
+ sessionDbVerifyFatal = result.verifyFatal;
11003
+ }
11004
+ }
9106
11005
  reportSessionDbRecovery(state);
11006
+ if (sessionDbVerifyFatal) {
11007
+ throw new Error(
11008
+ "SESSION-DB-INTEGRITY-EXHAUSTED: the corrupt session DB could not be proven separated from the active backup prefix or removed from disk"
11009
+ );
11010
+ }
11011
+ applyRunnerOpenCodeConfig({
11012
+ overlayPath: options.opencodeConfigOverlay,
11013
+ log: (message, level = "info") => {
11014
+ if (level === "error") {
11015
+ logActivity(state, { type: "error", error: message });
11016
+ } else {
11017
+ logActivity(state, { type: "info", level, message });
11018
+ }
11019
+ }
11020
+ });
9107
11021
  const { timeoutMs: opencodeStartTimeoutMs, warnings: opencodeStartTimeoutWarnings } = resolveOpenCodeStartTimeoutMs(options, process.env);
9108
11022
  for (const warning2 of opencodeStartTimeoutWarnings) {
9109
11023
  logActivity(state, { type: "info", level: "warn", message: warning2 });
9110
11024
  }
11025
+ const { version: opencodeVersion, warnings: opencodeVersionWarnings } = resolveOpenCodeVersion(
11026
+ options,
11027
+ process.env
11028
+ );
11029
+ for (const warning2 of opencodeVersionWarnings) {
11030
+ logActivity(state, { type: "info", level: "warn", message: warning2 });
11031
+ }
9111
11032
  const { value: maxActiveSessions, warnings: maxActiveSessionsWarnings } = resolveMaxActiveSessions(options, process.env);
9112
11033
  for (const warning2 of maxActiveSessionsWarnings) {
9113
11034
  logActivity(state, { type: "info", level: "warn", message: warning2 });
9114
11035
  }
11036
+ const preBootMigrationIds = readSessionDbMigrationIds(sessionDbPath());
9115
11037
  const ocSpinner = interactive && !state.json ? ora3("Checking OpenCode...").start() : null;
9116
11038
  try {
9117
- const oc = await ensureOpenCodeRunning({
11039
+ const oc = opencodeVersion === "v2" ? await ensureOpenCode2Running({
9118
11040
  port: state.port,
9119
11041
  interactive: state.interactive,
9120
11042
  agentId: state.agentId,
9121
11043
  log: (message) => log2(state, message),
9122
- startTimeoutMs: opencodeStartTimeoutMs
11044
+ startTimeoutMs: opencodeStartTimeoutMs,
11045
+ inheritStdio: Boolean(options.opencodePidFile)
11046
+ }) : await ensureOpenCodeRunning({
11047
+ port: state.port,
11048
+ interactive: state.interactive,
11049
+ agentId: state.agentId,
11050
+ log: (message) => log2(state, message),
11051
+ startTimeoutMs: opencodeStartTimeoutMs,
11052
+ inheritStdio: Boolean(options.opencodePidFile)
9123
11053
  });
9124
11054
  state.port = oc.port;
9125
- state.opencodeProcess = oc.process;
11055
+ state.opencodeProcess = options.opencodePidFile ? null : oc.process;
9126
11056
  state.opencodeVersion = oc.version;
11057
+ if (options.opencodePidFile && oc.process?.pid !== void 0) {
11058
+ try {
11059
+ writeFileSync6(options.opencodePidFile, `${oc.process.pid}
11060
+ `, { mode: 384 });
11061
+ chmodSync3(options.opencodePidFile, 384);
11062
+ } catch (error2) {
11063
+ logActivity(state, {
11064
+ type: "error",
11065
+ error: `Failed to write OpenCode pid file ${options.opencodePidFile}: ${error2 instanceof Error ? error2.message : String(error2)}`
11066
+ });
11067
+ }
11068
+ }
11069
+ if (state.opencodeVersion !== null) {
11070
+ const provenance = checkSessionDbProvenance({
11071
+ dbPath: sessionDbPath(),
11072
+ currentVersion: state.opencodeVersion,
11073
+ homeDir: homedir5(),
11074
+ env: process.env
11075
+ });
11076
+ if (provenance.anomaly) {
11077
+ state.sessionDbProvenanceAnomaly = true;
11078
+ logSessionDbProvenanceMismatch(
11079
+ state,
11080
+ provenance,
11081
+ state.opencodeVersion,
11082
+ preBootMigrationIds?.length ?? null
11083
+ );
11084
+ }
11085
+ }
9127
11086
  state.opencodeConnected = oc.notReadyReason === null;
9128
11087
  const version2 = state.opencodeVersion ? ` (v${state.opencodeVersion})` : "";
9129
11088
  ocSpinner?.succeed(`OpenCode running on port ${state.port}${version2}`);
@@ -9146,10 +11105,10 @@ async function run(options) {
9146
11105
  if (state.interactive && !state.json) {
9147
11106
  logActivity(state, { type: "info", level: "warn", message: noProviderWarning });
9148
11107
  blank();
9149
- console.log(chalk6.yellow("\u26A0 No OpenCode model provider is configured."));
11108
+ console.log(chalk7.yellow("\u26A0 No OpenCode model provider is configured."));
9150
11109
  console.log(
9151
- chalk6.dim(
9152
- `Run ${chalk6.cyan("opencode auth login")} to set one up \u2014 messages will fail until then.`
11110
+ chalk7.dim(
11111
+ `Run ${chalk7.cyan("opencode auth login")} to set one up \u2014 messages will fail until then.`
9153
11112
  )
9154
11113
  );
9155
11114
  blank();
@@ -9160,7 +11119,75 @@ async function run(options) {
9160
11119
  ocSpinner?.fail(error2.message);
9161
11120
  throw error2;
9162
11121
  }
9163
- if (options.litestreamConfig) {
11122
+ if (options.litestreamPidFile) {
11123
+ if (options.sessionDbNoReplicateMarker && existsSync3(options.sessionDbNoReplicateMarker)) {
11124
+ log2(
11125
+ state,
11126
+ `Skipping Litestream replication because ${options.sessionDbNoReplicateMarker} marks this session database unsafe to replicate`
11127
+ );
11128
+ } else if (!options.litestreamConfig) {
11129
+ logActivity(state, {
11130
+ type: "info",
11131
+ level: "warn",
11132
+ message: "Skipping Litestream replication because no configuration file was provided"
11133
+ });
11134
+ } else {
11135
+ let existingPid;
11136
+ if (existsSync3(options.litestreamPidFile)) {
11137
+ try {
11138
+ const rawPid = readFileSync6(options.litestreamPidFile, "utf8").trim();
11139
+ const parsedPid = Number(rawPid);
11140
+ if (/^\d+$/.test(rawPid) && Number.isSafeInteger(parsedPid) && parsedPid > 0) {
11141
+ existingPid = parsedPid;
11142
+ }
11143
+ } catch (error2) {
11144
+ logActivity(state, {
11145
+ type: "info",
11146
+ level: "warn",
11147
+ message: `Could not read Litestream pid file ${options.litestreamPidFile}; checking for a new process: ${error2 instanceof Error ? error2.message : String(error2)}`
11148
+ });
11149
+ }
11150
+ }
11151
+ if (existingPid !== void 0 && isProcessAlive(existingPid)) {
11152
+ log2(state, `Litestream replication is already running with pid ${existingPid}`);
11153
+ } else {
11154
+ const litestreamProcess = startSessionDbReplication(options.litestreamConfig);
11155
+ state.litestreamProcess = null;
11156
+ let failureHandled = false;
11157
+ const reportImageOwnedReplicationFailure = (message) => {
11158
+ if (failureHandled || state.shuttingDown || !state.running) return;
11159
+ failureHandled = true;
11160
+ logActivity(state, { type: "error", error: message });
11161
+ if (state.interactive) displayStatus(state);
11162
+ };
11163
+ litestreamProcess.on("exit", (code, signal) => {
11164
+ reportImageOwnedReplicationFailure(
11165
+ `Litestream replication stopped unexpectedly (code: ${code ?? "null"}, signal: ${signal ?? "none"})`
11166
+ );
11167
+ });
11168
+ litestreamProcess.on("error", (error2) => {
11169
+ reportImageOwnedReplicationFailure(
11170
+ `Litestream replication failed: ${error2 instanceof Error ? error2.message : String(error2)}`
11171
+ );
11172
+ });
11173
+ try {
11174
+ if (litestreamProcess.pid !== void 0) {
11175
+ writeFileSync6(options.litestreamPidFile, `${litestreamProcess.pid}
11176
+ `, {
11177
+ mode: 384
11178
+ });
11179
+ chmodSync3(options.litestreamPidFile, 384);
11180
+ }
11181
+ } catch (error2) {
11182
+ logActivity(state, {
11183
+ type: "error",
11184
+ error: `Failed to write Litestream pid file ${options.litestreamPidFile}: ${error2 instanceof Error ? error2.message : String(error2)}`
11185
+ });
11186
+ }
11187
+ log2(state, `Started litestream replication with config ${options.litestreamConfig}`);
11188
+ }
11189
+ }
11190
+ } else if (options.litestreamConfig) {
9164
11191
  const litestreamProcess = startSessionDbReplication(options.litestreamConfig);
9165
11192
  state.litestreamProcess = litestreamProcess;
9166
11193
  let failureHandled = false;
@@ -9205,7 +11232,7 @@ async function run(options) {
9205
11232
  // #559: the `--enable-file-sync-to` allow-list. Empty ⇒ pending files are
9206
11233
  // REJECTED with `file_sync_disabled` on the ack, not silently ignored.
9207
11234
  fileSyncDirectories,
9208
- homeDir: homedir4(),
11235
+ homeDir: homedir5(),
9209
11236
  maxActiveSessions,
9210
11237
  log: (entry) => (
9211
11238
  // Thread the driver's real level straight through so `debug`/`warn`
@@ -9331,6 +11358,18 @@ async function run(options) {
9331
11358
  if (state.interactive) displayStatus(state);
9332
11359
  });
9333
11360
  },
11361
+ // Both loops are rearmed because `rearm()` is idempotent for the
11362
+ // provider that did not just connect, and is a no-op when reporting is off.
11363
+ onUsageRearmPing: () => {
11364
+ if (!state.running) return;
11365
+ logActivity(state, {
11366
+ type: "info",
11367
+ level: "debug",
11368
+ message: "Usage rearm ping received"
11369
+ });
11370
+ state.claudeUsageRearm?.();
11371
+ state.openaiUsageRearm?.();
11372
+ },
9334
11373
  onInfo: (message) => logActivity(state, { type: "info", message })
9335
11374
  }
9336
11375
  });
@@ -9351,7 +11390,17 @@ async function run(options) {
9351
11390
  setTimer: (timer) => {
9352
11391
  state.openaiUsageTimer = timer;
9353
11392
  },
9354
- fetchUsage: () => getOpenAiUsage(state.port),
11393
+ fetchUsage: async () => {
11394
+ const usage = await getOpenAiUsage(state.port);
11395
+ if (usage.subscription === null) {
11396
+ logActivity(state, {
11397
+ type: "info",
11398
+ level: "debug",
11399
+ message: "OpenAI usage subscription could not be identified from the local credential"
11400
+ });
11401
+ }
11402
+ return usage;
11403
+ },
9355
11404
  report: (usage) => reportOpenAiUsage(state.agentId, state.authHeader, usage),
9356
11405
  isLocalCredentialProblem: isLocalCredentialProblem2,
9357
11406
  forcedOnHint: "connect a ChatGPT account to this runner, or run `opencode auth login`",
@@ -9397,7 +11446,7 @@ async function run(options) {
9397
11446
  }
9398
11447
 
9399
11448
  // src/index.ts
9400
- var { version } = createRequire(import.meta.url)("../package.json");
11449
+ var { version } = createRequire2(import.meta.url)("../package.json");
9401
11450
  var program = new Command();
9402
11451
  program.name("evident").description("Run OpenCode locally and connect it to Evident").version(version).option(
9403
11452
  "--endpoint <url>",
@@ -9425,6 +11474,9 @@ program.command("run").description("Connect to Evident and process messages").op
9425
11474
  ).option("-v, --verbose", "Alias for --log-level debug (ignored if --log-level is set)").option("-c, --conversation <id>", "Process only this specific conversation").option("--idle-timeout <seconds>", "Exit after N seconds idle").option(
9426
11475
  "--opencode-start-timeout <seconds>",
9427
11476
  "Seconds to wait for OpenCode to become healthy when the runner starts it (default: 180). Env: EVIDENT_OPENCODE_START_TIMEOUT"
11477
+ ).option(
11478
+ "--opencode-version <v1|v2>",
11479
+ "Which OpenCode major version to launch: v1 or v2 (default: v1). Env: EVIDENT_OPENCODE_VERSION"
9428
11480
  ).option("--json", "Output in JSON format").option(
9429
11481
  "--session-cleanup-max-age <duration>",
9430
11482
  "Delete OpenCode sessions idle longer than this (e.g. 7d, 24h). Enables cleanup. Env: EVIDENT_SESSION_CLEANUP_MAX_AGE"
@@ -9457,6 +11509,27 @@ program.command("run").description("Connect to Evident and process messages").op
9457
11509
  ).option(
9458
11510
  "--litestream-config <path>",
9459
11511
  "Replicate the OpenCode session database with `litestream replicate` using this config file (written by the runner image). Omit to disable replication."
11512
+ ).option(
11513
+ "--opencode-pid-file <path>",
11514
+ "Record the OpenCode pid here and leave the process running at shutdown for the runner image's lifecycle hooks to stop."
11515
+ ).option(
11516
+ "--litestream-pid-file <path>",
11517
+ "Record the Litestream pid here and leave the process running at shutdown for the runner image's lifecycle hooks to stop."
11518
+ ).option(
11519
+ "--session-db-no-replicate-marker <path>",
11520
+ "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."
11521
+ ).option(
11522
+ "--restore-session-db",
11523
+ "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."
11524
+ ).option(
11525
+ "--restore-runner-credentials",
11526
+ "Restore the hosted runner secret and persisted credential stores before starting OpenCode."
11527
+ ).option(
11528
+ "--opencode-config-overlay <path>",
11529
+ "Apply this runner-provided OpenCode config before starting OpenCode."
11530
+ ).option(
11531
+ "--credential-sync-marker <path>",
11532
+ "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."
9460
11533
  ).action(
9461
11534
  (options) => {
9462
11535
  run({
@@ -9472,6 +11545,7 @@ program.command("run").description("Connect to Evident and process messages").op
9472
11545
  // Raw string — validation/precedence is single-sourced in run.ts's
9473
11546
  // resolveOpenCodeStartTimeoutMs (flag > EVIDENT_OPENCODE_START_TIMEOUT > 180s default).
9474
11547
  opencodeStartTimeout: options.opencodeStartTimeout,
11548
+ opencodeVersion: options.opencodeVersion,
9475
11549
  json: options.json,
9476
11550
  // Raw strings — the resolver in run.ts single-sources parsing (M1).
9477
11551
  sessionCleanupMaxAge: options.sessionCleanupMaxAge,
@@ -9489,7 +11563,14 @@ program.command("run").description("Connect to Evident and process messages").op
9489
11563
  // resolveFileSyncDirectories.
9490
11564
  enableFileSyncTo: options.enableFileSyncTo,
9491
11565
  tunnelReadyFile: options.tunnelReadyFile,
9492
- litestreamConfig: options.litestreamConfig
11566
+ litestreamConfig: options.litestreamConfig,
11567
+ opencodePidFile: options.opencodePidFile,
11568
+ litestreamPidFile: options.litestreamPidFile,
11569
+ sessionDbNoReplicateMarker: options.sessionDbNoReplicateMarker,
11570
+ restoreSessionDb: options.restoreSessionDb,
11571
+ restoreRunnerCredentials: options.restoreRunnerCredentials,
11572
+ opencodeConfigOverlay: options.opencodeConfigOverlay,
11573
+ credentialSyncMarker: options.credentialSyncMarker
9493
11574
  });
9494
11575
  }
9495
11576
  );