@evident-ai/cli 3.4.1-dev.aa71e9a → 3.4.1-dev.ab61560

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/index.ts
4
- import { createRequire } from "module";
4
+ import { createRequire as createRequire2 } from "module";
5
5
  import { Command } from "commander";
6
6
 
7
7
  // src/commands/login.ts
@@ -371,14 +371,14 @@ function blank() {
371
371
  console.log();
372
372
  }
373
373
  function waitForEnter(prompt = "Press Enter to continue...") {
374
- return new Promise((resolve3) => {
374
+ return new Promise((resolve4) => {
375
375
  process.stdout.write(chalk.dim(prompt));
376
376
  const handler = () => {
377
377
  process.stdin.removeListener("data", handler);
378
378
  process.stdin.setRawMode?.(false);
379
379
  process.stdin.pause();
380
380
  console.log();
381
- resolve3();
381
+ resolve4();
382
382
  };
383
383
  if (process.stdin.isTTY) {
384
384
  process.stdin.setRawMode?.(true);
@@ -388,7 +388,7 @@ function waitForEnter(prompt = "Press Enter to continue...") {
388
388
  });
389
389
  }
390
390
  function sleep(ms) {
391
- return new Promise((resolve3) => setTimeout(resolve3, ms));
391
+ return new Promise((resolve4) => setTimeout(resolve4, ms));
392
392
  }
393
393
 
394
394
  // src/commands/login.ts
@@ -466,19 +466,19 @@ async function tokenLogin() {
466
466
  );
467
467
  blank();
468
468
  process.stdout.write("Paste token: ");
469
- const token = await new Promise((resolve3) => {
469
+ const token = await new Promise((resolve4) => {
470
470
  let data = "";
471
471
  process.stdin.setEncoding("utf8");
472
472
  process.stdin.on("data", (chunk) => {
473
473
  data += chunk;
474
474
  });
475
475
  process.stdin.on("end", () => {
476
- resolve3(data.trim());
476
+ resolve4(data.trim());
477
477
  });
478
478
  if (process.stdin.isTTY) {
479
479
  process.stdin.once("data", (chunk) => {
480
480
  process.stdin.pause();
481
- resolve3(chunk.toString().trim());
481
+ resolve4(chunk.toString().trim());
482
482
  });
483
483
  process.stdin.resume();
484
484
  }
@@ -722,6 +722,14 @@ function toReportedWindow(window) {
722
722
  if (!window) return null;
723
723
  return { utilization: window.utilization, resets_at: window.resetsAt };
724
724
  }
725
+ function toReportedOwner(snapshot) {
726
+ if (!snapshot.owner) return null;
727
+ return {
728
+ email: snapshot.owner.email,
729
+ organization_name: snapshot.owner.organizationName,
730
+ rate_limit_tier: snapshot.owner.rateLimitTier
731
+ };
732
+ }
725
733
  async function reportClaudeUsage(agentId, authHeader, snapshot) {
726
734
  try {
727
735
  const apiUrl = getApiUrlConfig();
@@ -730,7 +738,8 @@ async function reportClaudeUsage(agentId, authHeader, snapshot) {
730
738
  headers: { Authorization: authHeader, "Content-Type": "application/json" },
731
739
  body: JSON.stringify({
732
740
  five_hour: toReportedWindow(snapshot.fiveHour),
733
- seven_day: toReportedWindow(snapshot.sevenDay)
741
+ seven_day: toReportedWindow(snapshot.sevenDay),
742
+ owner: toReportedOwner(snapshot)
734
743
  }),
735
744
  signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
736
745
  });
@@ -996,7 +1005,10 @@ import { readFileSync } from "fs";
996
1005
  import { homedir } from "os";
997
1006
  import { join } from "path";
998
1007
  var CLAUDE_USAGE_URL = "https://api.anthropic.com/api/oauth/usage";
1008
+ var CLAUDE_PROFILE_URL = "https://api.anthropic.com/api/oauth/profile";
1009
+ var CLAUDE_PROFILE_TIMEOUT_MS = 2e3;
999
1010
  var KEYCHAIN_SERVICE = "Claude Code-credentials";
1011
+ var cachedOwner = null;
1000
1012
  var CLAUDE_CREDENTIALS_SEGMENTS = [".claude", ".credentials.json"];
1001
1013
  function parseClaudeCliCredentials(raw) {
1002
1014
  let parsed;
@@ -1070,6 +1082,47 @@ function toWindow(value) {
1070
1082
  }
1071
1083
  return { utilization: window.utilization, resetsAt };
1072
1084
  }
1085
+ function ownerLookupFailure(error2) {
1086
+ const name = error2?.name;
1087
+ return name === "TimeoutError" || name === "AbortError" ? "timed out" : "request failed";
1088
+ }
1089
+ async function getClaudeUsageOwner(accessToken) {
1090
+ if (cachedOwner?.accessToken === accessToken) {
1091
+ return { owner: cachedOwner.owner, ownerLookupError: null };
1092
+ }
1093
+ try {
1094
+ const response = await fetch(CLAUDE_PROFILE_URL, {
1095
+ headers: {
1096
+ Authorization: `Bearer ${accessToken}`,
1097
+ "Content-Type": "application/json",
1098
+ "anthropic-version": "2023-06-01"
1099
+ },
1100
+ signal: AbortSignal.timeout(CLAUDE_PROFILE_TIMEOUT_MS)
1101
+ });
1102
+ if (!response.ok) {
1103
+ return { owner: null, ownerLookupError: `HTTP ${response.status}` };
1104
+ }
1105
+ let body;
1106
+ try {
1107
+ body = await response.json();
1108
+ } catch (error2) {
1109
+ return { owner: null, ownerLookupError: "malformed response" };
1110
+ }
1111
+ const profile = body;
1112
+ if (typeof profile.account?.email !== "string" || !profile.account.email.trim()) {
1113
+ return { owner: null, ownerLookupError: "malformed response" };
1114
+ }
1115
+ const owner = {
1116
+ email: profile.account.email,
1117
+ organizationName: typeof profile.organization?.name === "string" && profile.organization.name.trim() ? profile.organization.name.trim() : null,
1118
+ rateLimitTier: typeof profile.organization?.rate_limit_tier === "string" && profile.organization.rate_limit_tier.trim() ? profile.organization.rate_limit_tier.trim() : null
1119
+ };
1120
+ cachedOwner = { accessToken, owner };
1121
+ return { owner, ownerLookupError: null };
1122
+ } catch (error2) {
1123
+ return { owner: null, ownerLookupError: ownerLookupFailure(error2) };
1124
+ }
1125
+ }
1073
1126
  async function getClaudeUsage() {
1074
1127
  const credentials2 = readClaudeCliCredentials();
1075
1128
  if (!credentials2) {
@@ -1089,15 +1142,19 @@ async function getClaudeUsage() {
1089
1142
  Authorization: `Bearer ${credentials2.accessToken}`,
1090
1143
  "Content-Type": "application/json",
1091
1144
  "anthropic-version": "2023-06-01"
1092
- }
1145
+ },
1146
+ signal: AbortSignal.timeout(CLAUDE_PROFILE_TIMEOUT_MS)
1093
1147
  });
1094
1148
  if (!res.ok) {
1095
1149
  throw new ClaudeUsageError(`Claude usage request failed: HTTP ${res.status}`, "request_failed");
1096
1150
  }
1097
1151
  const body = await res.json();
1152
+ const { owner, ownerLookupError } = await getClaudeUsageOwner(credentials2.accessToken);
1098
1153
  return {
1099
1154
  fiveHour: toWindow(body.five_hour),
1100
- sevenDay: toWindow(body.seven_day)
1155
+ sevenDay: toWindow(body.seven_day),
1156
+ owner,
1157
+ ownerLookupError
1101
1158
  };
1102
1159
  }
1103
1160
 
@@ -1126,8 +1183,9 @@ async function claudeUsage() {
1126
1183
  }
1127
1184
 
1128
1185
  // src/commands/run.ts
1129
- import { homedir as homedir4 } from "os";
1130
- import { isAbsolute as isAbsolute2, join as join7, parse, resolve as resolvePath } from "path";
1186
+ import { chmodSync as chmodSync3, existsSync as existsSync3, readFileSync as readFileSync6, writeFileSync as writeFileSync6 } from "fs";
1187
+ import { homedir as homedir5 } from "os";
1188
+ import { isAbsolute as isAbsolute3, join as join9, parse, resolve as resolvePath2 } from "path";
1131
1189
  import chalk6 from "chalk";
1132
1190
 
1133
1191
  // ../../packages/types/src/agents/index.ts
@@ -1467,7 +1525,14 @@ function drainSessionDbRecoveryReport({
1467
1525
  skippedLines++;
1468
1526
  return [];
1469
1527
  }
1470
- return [value];
1528
+ return [
1529
+ {
1530
+ ...value,
1531
+ provenance_reason: value.provenance_reason ?? null,
1532
+ provenance_migration_delta: value.provenance_migration_delta ?? null,
1533
+ replication_suspended: value.replication_suspended ?? false
1534
+ }
1535
+ ];
1471
1536
  } catch (error2) {
1472
1537
  skippedLines++;
1473
1538
  console.error(
@@ -1492,12 +1557,39 @@ function buildSessionDbRecoveryActivity(record) {
1492
1557
  const level = record.severity === "warning" ? "warn" : record.severity === "error" ? "error" : null;
1493
1558
  if (!level) return null;
1494
1559
  const noVerifiedPoint = record.verified_restore_point ? ` The verified restore point is ${record.verified_restore_point}.` : " No verified restore point is known.";
1560
+ const replication = record.replication_suspended ? " This start is not backing up its new session history; restart after fixing the cause." : "";
1561
+ const giveupMessage = (() => {
1562
+ switch (record.reason) {
1563
+ case "restore_deadline_exceeded":
1564
+ 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.";
1565
+ case "restore_tool_unusable":
1566
+ case "classification_unrecognised":
1567
+ 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.";
1568
+ case "synchroniser_config_unevaluable":
1569
+ case "synchroniser_config_incomplete":
1570
+ 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.";
1571
+ case "synchroniser_config_unresolved":
1572
+ 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.";
1573
+ case "litestream_config_unavailable":
1574
+ 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.";
1575
+ case "classification_fatal":
1576
+ 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.";
1577
+ default:
1578
+ return null;
1579
+ }
1580
+ })();
1581
+ if (giveupMessage)
1582
+ return {
1583
+ level,
1584
+ metadata: withoutContractFields(record),
1585
+ message: `${giveupMessage}${replication}`
1586
+ };
1495
1587
  switch (record.outcome) {
1496
1588
  case "fresh_session_db":
1497
1589
  return {
1498
1590
  level,
1499
1591
  metadata: withoutContractFields(record),
1500
- 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.`
1592
+ 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}`
1501
1593
  };
1502
1594
  case "restore_retried":
1503
1595
  return {
@@ -1535,7 +1627,19 @@ function buildSessionDbRecoveryActivity(record) {
1535
1627
  return {
1536
1628
  level,
1537
1629
  metadata: withoutContractFields(record),
1538
- 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."
1630
+ 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}`
1631
+ };
1632
+ case "session_db_boot_refused":
1633
+ return {
1634
+ level,
1635
+ metadata: withoutContractFields(record),
1636
+ 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.`
1637
+ };
1638
+ case "schema_provenance_mismatch":
1639
+ return {
1640
+ level,
1641
+ metadata: withoutContractFields(record),
1642
+ 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.`
1539
1643
  };
1540
1644
  default:
1541
1645
  return null;
@@ -1550,7 +1654,9 @@ var OUTCOMES = /* @__PURE__ */ new Set([
1550
1654
  "restore_retried",
1551
1655
  "fresh_session_db",
1552
1656
  "history_rolled_back",
1553
- "restore_misconfigured"
1657
+ "restore_misconfigured",
1658
+ "session_db_boot_refused",
1659
+ "schema_provenance_mismatch"
1554
1660
  ]);
1555
1661
  var STAGES = /* @__PURE__ */ new Set(["restore", "verify"]);
1556
1662
  var SEVERITIES = /* @__PURE__ */ new Set(["warning", "error"]);
@@ -1568,7 +1674,7 @@ var STRING_OR_NULL_FIELDS = ["quarantine_destination", "verified_restore_point"]
1568
1674
  function isSessionDbRecoveryRecord(value) {
1569
1675
  if (!value || typeof value !== "object" || Array.isArray(value)) return false;
1570
1676
  const record = value;
1571
- 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(
1677
+ 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(
1572
1678
  (field) => record[field] === null || typeof record[field] === "string"
1573
1679
  );
1574
1680
  }
@@ -1597,214 +1703,932 @@ async function waitForOpenCodeHealth(port, timeoutMs = 3e4) {
1597
1703
  if (health.healthy) {
1598
1704
  return health;
1599
1705
  }
1600
- await new Promise((resolve3) => setTimeout(resolve3, 1e3));
1706
+ await new Promise((resolve4) => setTimeout(resolve4, 1e3));
1601
1707
  }
1602
1708
  return { healthy: false, error: "Timeout waiting for OpenCode to be healthy" };
1603
1709
  }
1604
1710
 
1605
- // src/lib/opencode/opencode-version-gate.ts
1606
- var QUEUE_VALIDATED_OPENCODE_VERSIONS = ["1.17.11", "1.18.3"];
1607
- function isQueueValidatedVersion(version2) {
1608
- if (!version2) return false;
1609
- return QUEUE_VALIDATED_OPENCODE_VERSIONS.includes(version2);
1610
- }
1611
- function buildOpenCodeVersionWarning(version2) {
1612
- if (isQueueValidatedVersion(version2)) return null;
1613
- const detected = version2 ? `v${version2}` : "unknown";
1614
- const validated = QUEUE_VALIDATED_OPENCODE_VERSIONS.map((v) => `v${v}`).join(", ");
1615
- return `Warning: opencode ${detected} is not a queue-validated version (validated: ${validated}). Native message queuing \u2014 which channel (Slack) message handling relies on \u2014 is unverified on this version; queued/follow-up messages may behave unexpectedly. Continuing anyway. Bumping the validated set requires re-running the queue validation.`;
1616
- }
1711
+ // src/lib/opencode/session-db-boot.ts
1712
+ import { spawn as spawn2 } from "child_process";
1713
+ import { mkdirSync, statSync as statSync2, unlinkSync as unlinkSync2, writeFileSync } from "fs";
1714
+ import { homedir as homedir2 } from "os";
1715
+ import { dirname as dirname2, resolve as resolvePath } from "path";
1617
1716
 
1618
- // src/lib/opencode/process.ts
1619
- import { execSync, spawn } from "child_process";
1620
- var OPENCODE_PORT_RANGE = [4096, 4097, 4098, 4099, 4100];
1621
- function getProcessCwd(pid) {
1622
- const platform = process.platform;
1623
- try {
1624
- if (platform === "darwin") {
1625
- const output = execSync(`lsof -a -p ${pid} -d cwd -Fn 2>/dev/null`, {
1626
- encoding: "utf-8",
1627
- stdio: ["pipe", "pipe", "pipe"]
1628
- }).trim();
1629
- const lines = output.split("\n");
1630
- for (const line of lines) {
1631
- if (line.startsWith("n") && !line.startsWith("n ")) {
1632
- return line.slice(1);
1717
+ // src/lib/runner-synchroniser.ts
1718
+ import { spawn } from "child_process";
1719
+ function appendError(stderr, error2) {
1720
+ const message = error2 instanceof Error ? error2.message : String(error2);
1721
+ return stderr === "" ? message : `${stderr}
1722
+ ${message}`;
1723
+ }
1724
+ function runSynchroniser(args, opts) {
1725
+ return new Promise((resolve4) => {
1726
+ let child;
1727
+ let stdout = "";
1728
+ let stderr = "";
1729
+ let settled = false;
1730
+ const timer = {};
1731
+ let abortListener;
1732
+ let spawnListener;
1733
+ const finish = (result) => {
1734
+ if (settled) return;
1735
+ settled = true;
1736
+ if (timer.handle) clearTimeout(timer.handle);
1737
+ if (abortListener) opts.signal?.removeEventListener("abort", abortListener);
1738
+ if (spawnListener) child.removeListener("spawn", spawnListener);
1739
+ resolve4(result);
1740
+ };
1741
+ try {
1742
+ child = spawn("runner-synchroniser", args, {
1743
+ env: opts.env ?? process.env,
1744
+ stdio: ["ignore", "pipe", "pipe"]
1745
+ });
1746
+ } catch (error2) {
1747
+ finish({ code: null, stdout, stderr: appendError(stderr, error2), timedOut: false });
1748
+ return;
1749
+ }
1750
+ child.stdout?.setEncoding("utf8");
1751
+ child.stdout?.on("data", (chunk) => {
1752
+ stdout += chunk;
1753
+ });
1754
+ child.stderr?.setEncoding("utf8");
1755
+ child.stderr?.on("data", (chunk) => {
1756
+ stderr += chunk;
1757
+ });
1758
+ child.once("error", (error2) => {
1759
+ finish({ code: null, stdout, stderr: appendError(stderr, error2), timedOut: false });
1760
+ });
1761
+ child.once("close", (code) => {
1762
+ finish({ code, stdout, stderr, timedOut: false });
1763
+ });
1764
+ if (opts.signal) {
1765
+ const killChild = () => {
1766
+ if (child.pid === void 0) {
1767
+ if (!spawnListener) {
1768
+ spawnListener = killChild;
1769
+ child.once("spawn", spawnListener);
1770
+ }
1771
+ return;
1633
1772
  }
1773
+ child.kill("SIGKILL");
1774
+ };
1775
+ abortListener = killChild;
1776
+ if (opts.signal.aborted) {
1777
+ abortListener();
1778
+ } else {
1779
+ opts.signal.addEventListener("abort", abortListener, { once: true });
1780
+ if (opts.signal.aborted) abortListener();
1634
1781
  }
1635
- } else if (platform === "linux") {
1636
- const output = execSync(`readlink /proc/${pid}/cwd 2>/dev/null`, {
1637
- encoding: "utf-8",
1638
- stdio: ["pipe", "pipe", "pipe"]
1639
- }).trim();
1640
- if (output) return output;
1641
1782
  }
1642
- } catch {
1643
- }
1644
- return void 0;
1783
+ timer.handle = setTimeout(
1784
+ () => {
1785
+ child.kill("SIGKILL");
1786
+ finish({ code: null, stdout, stderr, timedOut: true });
1787
+ },
1788
+ Math.max(0, opts.timeoutMs)
1789
+ );
1790
+ });
1645
1791
  }
1646
- function isPortInUse(port) {
1647
- const platform = process.platform;
1792
+
1793
+ // src/lib/opencode/session-db-boot.ts
1794
+ var SESSION_DB_RESTORE_TIMEOUT_MS = 3e5;
1795
+ var SESSION_DB_VERIFY_TIMEOUT_MS = 12e4;
1796
+ var SESSION_DB_SYNCHRONISER_TIMEOUT_MS = 12e4;
1797
+ var SESSION_DB_VERIFY_WALKBACK_BUDGET_SECONDS = 120;
1798
+ function commandError(result) {
1799
+ return result.stderr.trim() || `process exited with code ${result.code ?? "null"}`;
1800
+ }
1801
+ function reportRecord(stage, outcome, reason, litestreamExitCode, options) {
1802
+ options.reportRecovery({
1803
+ v: 1,
1804
+ event: "session_db_recovery",
1805
+ at: (/* @__PURE__ */ new Date()).toISOString(),
1806
+ stage,
1807
+ outcome,
1808
+ severity: "error",
1809
+ reason,
1810
+ litestream_exit_code: litestreamExitCode,
1811
+ attempt: null,
1812
+ replica_objects: null,
1813
+ replica_bytes: null,
1814
+ quarantine_destination: null,
1815
+ quarantined_objects: null,
1816
+ quarantine_failed_objects: null,
1817
+ quarantined_bytes: null,
1818
+ verified_restore_point: null,
1819
+ restore_points_tried: null,
1820
+ provenance_reason: null,
1821
+ provenance_migration_delta: null,
1822
+ replication_suspended: stage === "restore"
1823
+ });
1824
+ }
1825
+ function clearMarker(options) {
1826
+ if (!options.noReplicateMarker) return;
1648
1827
  try {
1649
- if (platform === "darwin" || platform === "linux") {
1650
- execSync(`lsof -i :${port} -sTCP:LISTEN 2>/dev/null`, {
1651
- encoding: "utf-8",
1652
- stdio: ["pipe", "pipe", "pipe"]
1653
- });
1654
- return true;
1655
- }
1656
- } catch {
1828
+ unlinkSync2(options.noReplicateMarker);
1829
+ } catch (error2) {
1830
+ if (error2 instanceof Error && "code" in error2 && error2.code === "ENOENT") return;
1831
+ options.log(
1832
+ `Could not clear the previous session-DB no-replicate marker ${options.noReplicateMarker}: ${error2 instanceof Error ? error2.message : String(error2)}`,
1833
+ "warn"
1834
+ );
1657
1835
  }
1658
- return false;
1659
1836
  }
1660
- function findAvailablePort(startPort, maxAttempts = 10) {
1661
- for (let i = 0; i < maxAttempts; i++) {
1662
- const port = startPort + i;
1663
- if (!isPortInUse(port)) {
1664
- return port;
1837
+ function markNoReplicate(options, message) {
1838
+ if (options.noReplicateMarker) {
1839
+ try {
1840
+ mkdirSync(dirname2(options.noReplicateMarker), { recursive: true });
1841
+ writeFileSync(options.noReplicateMarker, "");
1842
+ } catch (error2) {
1843
+ options.log(
1844
+ `Could not write session-DB no-replicate marker ${options.noReplicateMarker}: ${error2 instanceof Error ? error2.message : String(error2)}`,
1845
+ "error"
1846
+ );
1665
1847
  }
1666
1848
  }
1667
- return null;
1849
+ options.log(`SESSION-DB-NO-REPLICATE: ${message}`, "warn");
1668
1850
  }
1669
- function findOpenCodeProcesses() {
1670
- const instances = [];
1671
- try {
1672
- const platform = process.platform;
1673
- if (platform === "darwin" || platform === "linux") {
1674
- let pids = [];
1675
- try {
1676
- const pgrepOutput = execSync('pgrep -f "opencode serve|opencode-serve"', {
1677
- encoding: "utf-8",
1678
- stdio: ["pipe", "pipe", "pipe"]
1679
- }).trim();
1680
- if (pgrepOutput) {
1681
- pids = pgrepOutput.split("\n").map((p) => parseInt(p.trim(), 10)).filter((p) => !isNaN(p));
1682
- }
1683
- } catch {
1684
- try {
1685
- const psOutput = execSync('ps aux | grep -E "opencode (serve|--port)" | grep -v grep', {
1686
- encoding: "utf-8",
1687
- stdio: ["pipe", "pipe", "pipe"]
1688
- }).trim();
1689
- if (psOutput) {
1690
- for (const line of psOutput.split("\n")) {
1691
- const parts = line.trim().split(/\s+/);
1692
- if (parts.length >= 2) {
1693
- const pid = parseInt(parts[1], 10);
1694
- if (!isNaN(pid)) pids.push(pid);
1695
- }
1696
- }
1697
- }
1698
- } catch (err) {
1699
- console.warn(
1700
- `findOpenCodeProcesses: ps fallback failed: ${err instanceof Error ? err.message : String(err)}`
1701
- );
1702
- }
1703
- }
1704
- for (const pid of pids) {
1705
- try {
1706
- const lsofOutput = execSync(`lsof -Pan -p ${pid} -i TCP -sTCP:LISTEN 2>/dev/null`, {
1707
- encoding: "utf-8",
1708
- stdio: ["pipe", "pipe", "pipe"]
1709
- }).trim();
1710
- for (const line of lsofOutput.split("\n")) {
1711
- const portMatch = line.match(/:(\d+)\s+\(LISTEN\)/);
1712
- if (portMatch) {
1713
- const port = parseInt(portMatch[1], 10);
1714
- if (!isNaN(port) && !instances.some((i) => i.port === port)) {
1715
- const cwd = getProcessCwd(pid);
1716
- instances.push({ pid, port, cwd });
1717
- }
1718
- }
1719
- }
1720
- } catch {
1721
- }
1722
- }
1851
+ function discardSessionDbDebris(options) {
1852
+ for (const path of [options.dbPath, `${options.dbPath}-wal`, `${options.dbPath}-shm`]) {
1853
+ try {
1854
+ unlinkSync2(path);
1855
+ } catch (error2) {
1856
+ if (error2 instanceof Error && "code" in error2 && error2.code === "ENOENT") continue;
1857
+ options.log(
1858
+ `Could not remove session-DB debris ${path}: ${error2 instanceof Error ? error2.message : String(error2)}`,
1859
+ "warn"
1860
+ );
1723
1861
  }
1724
- } catch (err) {
1725
- console.warn(
1726
- `findOpenCodeProcesses: process detection failed: ${err instanceof Error ? err.message : String(err)}`
1727
- );
1728
1862
  }
1729
- return instances;
1730
1863
  }
1731
- async function scanPortsForOpenCode() {
1732
- const instances = [];
1733
- const checks = OPENCODE_PORT_RANGE.map(async (port) => {
1734
- const health = await checkOpenCodeHealth(port);
1735
- if (health.healthy) {
1736
- let pid = 0;
1737
- try {
1738
- const lsofOutput = execSync(`lsof -ti :${port} -sTCP:LISTEN 2>/dev/null`, {
1739
- encoding: "utf-8",
1740
- stdio: ["pipe", "pipe", "pipe"]
1741
- }).trim();
1742
- if (lsofOutput) {
1743
- pid = parseInt(lsofOutput.split("\n")[0], 10) || 0;
1744
- }
1745
- } catch {
1746
- }
1747
- const cwd = pid ? getProcessCwd(pid) : void 0;
1748
- return { pid, port, cwd, version: health.version };
1749
- }
1750
- return null;
1751
- });
1752
- const results = await Promise.all(checks);
1753
- for (const result of results) {
1754
- if (result) {
1755
- instances.push(result);
1756
- }
1757
- }
1758
- return instances;
1864
+ function splitDiagnostics(text) {
1865
+ return text.split("\n").map((line) => line.trim()).filter((line) => line.length > 0);
1759
1866
  }
1760
- async function findHealthyOpenCodeInstances() {
1761
- const processes = findOpenCodeProcesses();
1762
- const healthy = [];
1763
- for (const proc of processes) {
1764
- const health = await checkOpenCodeHealth(proc.port);
1765
- if (health.healthy) {
1766
- healthy.push({ ...proc, version: health.version });
1867
+ function logSynchroniserDiagnostics(result, options) {
1868
+ for (const line of splitDiagnostics(result.stderr)) options.log(line, "warn");
1869
+ }
1870
+ function parseSingleQuotedAssignment(line) {
1871
+ const match = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(line);
1872
+ if (!match || !match[2].startsWith("'")) return null;
1873
+ const valueSource = match[2];
1874
+ let value = "";
1875
+ for (let index = 1; index < valueSource.length; index++) {
1876
+ const character = valueSource[index];
1877
+ if (character !== "'") {
1878
+ value += character;
1879
+ continue;
1767
1880
  }
1881
+ if (index === valueSource.length - 1) return [match[1], value];
1882
+ if (valueSource.slice(index + 1, index + 4) !== "\\''") return null;
1883
+ value += "'";
1884
+ index += 3;
1768
1885
  }
1769
- if (healthy.length === 0) {
1770
- const scanned = await scanPortsForOpenCode();
1771
- return scanned;
1772
- }
1773
- return healthy;
1886
+ return null;
1774
1887
  }
1775
- async function startOpenCode(port) {
1776
- let command = "opencode";
1777
- let args = ["serve", "--port", port.toString(), "--hostname", "127.0.0.1"];
1778
- try {
1779
- execSync("which opencode", { stdio: "ignore" });
1780
- } catch {
1781
- command = "npx";
1782
- args = ["opencode", "serve", "--port", port.toString(), "--hostname", "127.0.0.1"];
1783
- }
1784
- const child = spawn(command, args, {
1785
- detached: true,
1786
- stdio: "ignore",
1787
- cwd: process.cwd()
1888
+ function parseSynchroniserEnv(stdout) {
1889
+ const values = {};
1890
+ for (const line of stdout.split("\n")) {
1891
+ if (line.trim() === "") continue;
1892
+ const assignment = parseSingleQuotedAssignment(line);
1893
+ if (!assignment) return null;
1894
+ values[assignment[0]] = assignment[1];
1895
+ }
1896
+ return values;
1897
+ }
1898
+ function runCommand(command, args, options) {
1899
+ return new Promise((resolve4) => {
1900
+ let child;
1901
+ let stdout = "";
1902
+ let stderr = "";
1903
+ let settled = false;
1904
+ const finish = (result) => {
1905
+ if (settled) return;
1906
+ settled = true;
1907
+ if (timer) clearTimeout(timer);
1908
+ resolve4(result);
1909
+ };
1910
+ try {
1911
+ child = spawn2(command, args, {
1912
+ env: options.env,
1913
+ stdio: ["ignore", "pipe", "pipe"]
1914
+ });
1915
+ } catch (error2) {
1916
+ resolve4({
1917
+ code: null,
1918
+ stdout,
1919
+ stderr: error2 instanceof Error ? error2.message : String(error2),
1920
+ timedOut: false
1921
+ });
1922
+ return;
1923
+ }
1924
+ child.stdout?.setEncoding("utf8");
1925
+ child.stdout?.on("data", (chunk) => {
1926
+ stdout += chunk;
1927
+ });
1928
+ child.stderr?.setEncoding("utf8");
1929
+ child.stderr?.on("data", (chunk) => {
1930
+ stderr += chunk;
1931
+ });
1932
+ child.once("error", (error2) => {
1933
+ finish({
1934
+ code: null,
1935
+ stdout,
1936
+ stderr: stderr === "" ? error2.message : `${stderr}
1937
+ ${error2.message}`,
1938
+ timedOut: false
1939
+ });
1940
+ });
1941
+ child.once("close", (code) => finish({ code, stdout, stderr, timedOut: false }));
1942
+ const timer = setTimeout(
1943
+ () => {
1944
+ child.kill("SIGKILL");
1945
+ finish({ code: null, stdout, stderr, timedOut: true });
1946
+ },
1947
+ Math.max(0, options.timeoutMs)
1948
+ );
1788
1949
  });
1789
- return child;
1790
1950
  }
1791
- function stopOpenCode(opencodeProcess) {
1792
- if (!opencodeProcess || !opencodeProcess.pid) {
1793
- return;
1951
+ async function ensureLitestreamConfig(options, env) {
1952
+ const configPath = options.litestreamConfig;
1953
+ if (!configPath) {
1954
+ markNoReplicate(options, "no Litestream configuration path was provided");
1955
+ reportRecord(
1956
+ "restore",
1957
+ "restore_misconfigured",
1958
+ "litestream_config_unavailable",
1959
+ null,
1960
+ options
1961
+ );
1962
+ return null;
1794
1963
  }
1795
1964
  try {
1796
- if (process.platform === "win32") {
1797
- opencodeProcess.kill("SIGTERM");
1798
- } else {
1799
- process.kill(-opencodeProcess.pid, "SIGTERM");
1800
- }
1801
- } catch (err) {
1802
- if (err.code !== "ESRCH") {
1803
- console.warn(
1804
- `stopOpenCode: kill failed: ${err instanceof Error ? err.message : String(err)}`
1965
+ if (statSync2(configPath).size > 0) return configPath;
1966
+ } catch (error2) {
1967
+ if (!(error2 instanceof Error && "code" in error2 && error2.code === "ENOENT")) {
1968
+ options.log(
1969
+ `Could not inspect ${configPath}: ${error2 instanceof Error ? error2.message : String(error2)}`,
1970
+ "warn"
1805
1971
  );
1806
1972
  }
1807
1973
  }
1974
+ const rendered = await runSynchroniser(["litestream-config"], {
1975
+ timeoutMs: SESSION_DB_SYNCHRONISER_TIMEOUT_MS,
1976
+ env
1977
+ });
1978
+ logSynchroniserDiagnostics(rendered, options);
1979
+ if (rendered.timedOut || rendered.code !== 0) {
1980
+ options.log(
1981
+ `Could not generate ${configPath}: runner-synchroniser litestream-config failed (${commandError(rendered)})`,
1982
+ "error"
1983
+ );
1984
+ markNoReplicate(options, `could not generate ${configPath}`);
1985
+ reportRecord(
1986
+ "restore",
1987
+ "restore_misconfigured",
1988
+ "litestream_config_unavailable",
1989
+ null,
1990
+ options
1991
+ );
1992
+ return null;
1993
+ }
1994
+ try {
1995
+ mkdirSync(dirname2(configPath), { recursive: true });
1996
+ writeFileSync(configPath, rendered.stdout);
1997
+ } catch (error2) {
1998
+ options.log(
1999
+ `Could not write ${configPath}: ${error2 instanceof Error ? error2.message : String(error2)}`,
2000
+ "error"
2001
+ );
2002
+ markNoReplicate(options, `could not generate ${configPath}`);
2003
+ reportRecord(
2004
+ "restore",
2005
+ "restore_misconfigured",
2006
+ "litestream_config_unavailable",
2007
+ null,
2008
+ options
2009
+ );
2010
+ return null;
2011
+ }
2012
+ const version2 = await runCommand("litestream", ["version"], {
2013
+ env,
2014
+ timeoutMs: 1e4
2015
+ });
2016
+ const litestreamVersion = version2.code === 0 ? version2.stdout.trim() || "unknown" : "unknown";
2017
+ const regionEmpty = !/^\s*region:\s*\S+/m.test(rendered.stdout);
2018
+ options.log(
2019
+ `litestream ${litestreamVersion}; AWS_REGION=${env.AWS_REGION ?? "<unset>"} AWS_DEFAULT_REGION=${env.AWS_DEFAULT_REGION ?? "<unset>"}; rendered litestream.yml region empty: ${regionEmpty ? "yes" : "no"}`
2020
+ );
2021
+ return configPath;
2022
+ }
2023
+ function restoreGiveUp(options, reason, message, litestreamExitCode, outcome = "fresh_session_db") {
2024
+ discardSessionDbDebris(options);
2025
+ markNoReplicate(options, message);
2026
+ reportRecord("restore", outcome, reason, litestreamExitCode, options);
2027
+ }
2028
+ async function restoreSessionDb(options, configPath, env) {
2029
+ const restored = await runCommand(
2030
+ "litestream",
2031
+ ["restore", "-config", configPath, "-if-db-not-exists", "-if-replica-exists", options.dbPath],
2032
+ { env, timeoutMs: SESSION_DB_RESTORE_TIMEOUT_MS }
2033
+ );
2034
+ for (const line of splitDiagnostics(restored.stderr)) options.log(line, "warn");
2035
+ if (restored.timedOut || restored.code === 124 || restored.code === 137) {
2036
+ restoreGiveUp(
2037
+ options,
2038
+ "restore_deadline_exceeded",
2039
+ `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`,
2040
+ restored.code ?? 124
2041
+ );
2042
+ return;
2043
+ }
2044
+ if (restored.code === null || restored.code === 125 || restored.code === 126 || restored.code === 127) {
2045
+ options.log(`litestream restore could not run (${commandError(restored)})`, "error");
2046
+ restoreGiveUp(
2047
+ options,
2048
+ "restore_tool_unusable",
2049
+ `restore tool is broken (${commandError(restored)}); opencode starts with a fresh session DB and nothing is replicated this boot`,
2050
+ restored.code
2051
+ );
2052
+ return;
2053
+ }
2054
+ const classified = await runSynchroniser(
2055
+ [
2056
+ "session-db-classify",
2057
+ String(restored.code ?? 1),
2058
+ "1",
2059
+ "--on-unusable-replica=leave",
2060
+ "--fresh-db-fallback"
2061
+ ],
2062
+ { timeoutMs: SESSION_DB_SYNCHRONISER_TIMEOUT_MS, env }
2063
+ );
2064
+ logSynchroniserDiagnostics(classified, options);
2065
+ const classifyCode = classified.code;
2066
+ switch (classifyCode) {
2067
+ case 0:
2068
+ return;
2069
+ case 31:
2070
+ acknowledgeSessionDbRecoveryReport(sessionDbRecoveryReportPath(homedir2(), env));
2071
+ options.log(
2072
+ "SESSION-DB-REPLICA-UNUSABLE: booting with a fresh opencode.db and replicating into the existing prefix this boot",
2073
+ "warn"
2074
+ );
2075
+ return;
2076
+ case 32:
2077
+ acknowledgeSessionDbRecoveryReport(sessionDbRecoveryReportPath(homedir2(), env));
2078
+ discardSessionDbDebris(options);
2079
+ markNoReplicate(
2080
+ options,
2081
+ "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"
2082
+ );
2083
+ return;
2084
+ case 30:
2085
+ restoreGiveUp(
2086
+ options,
2087
+ "classification_fatal",
2088
+ "session-db-classify returned fatal (30); see the FATAL message above",
2089
+ restored.code,
2090
+ "restore_misconfigured"
2091
+ );
2092
+ return;
2093
+ default:
2094
+ restoreGiveUp(
2095
+ options,
2096
+ "classification_unrecognised",
2097
+ `session-db-classify exited ${classifyCode ?? "null"}, which is none of its documented answers`,
2098
+ restored.code
2099
+ );
2100
+ }
2101
+ }
2102
+ async function verifySessionDb(options, configPath, env) {
2103
+ if (!options.noReplicateMarker || !fileExists(options.noReplicateMarker)) {
2104
+ const result = await runSynchroniser(["session-db-verify", configPath], {
2105
+ timeoutMs: SESSION_DB_VERIFY_TIMEOUT_MS,
2106
+ env: {
2107
+ ...env,
2108
+ // The synchroniser reads this value in SECONDS. Keep this at 120, not
2109
+ // 120_000, so the walkback gives up before the outer process bound.
2110
+ EVIDENT_SESSION_DB_WALKBACK_BUDGET_SECONDS: String(
2111
+ SESSION_DB_VERIFY_WALKBACK_BUDGET_SECONDS
2112
+ )
2113
+ }
2114
+ });
2115
+ logSynchroniserDiagnostics(result, options);
2116
+ if (result.timedOut || result.code === 124 || result.code === 137) {
2117
+ options.log(
2118
+ `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`,
2119
+ "warn"
2120
+ );
2121
+ return false;
2122
+ }
2123
+ if (result.code === 34) {
2124
+ reportRecord(
2125
+ "verify",
2126
+ "session_db_boot_refused",
2127
+ result.stderr.includes("SESSION-DB-LOCAL-DISCARD-FAILED") ? "local_discard_failed" : "replica_separation_unproven",
2128
+ null,
2129
+ options
2130
+ );
2131
+ return true;
2132
+ }
2133
+ if (result.code === 33) {
2134
+ options.log(
2135
+ "SESSION-DB-INTEGRITY-EXHAUSTED: booting continues and litestream still replicates, starting an empty backup chain after the corrupt replica was separated.",
2136
+ "warn"
2137
+ );
2138
+ return false;
2139
+ }
2140
+ if (result.code !== 0) {
2141
+ options.log(
2142
+ `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`,
2143
+ "warn"
2144
+ );
2145
+ }
2146
+ return false;
2147
+ }
2148
+ options.log(
2149
+ "skipping session-DB verification: this boot's session DB was not proven safe to replicate",
2150
+ "debug"
2151
+ );
2152
+ return false;
2153
+ }
2154
+ function fileExists(path) {
2155
+ try {
2156
+ statSync2(path);
2157
+ return true;
2158
+ } catch (error2) {
2159
+ if (error2 instanceof Error && "code" in error2 && error2.code === "ENOENT") return false;
2160
+ return true;
2161
+ }
2162
+ }
2163
+ async function restoreAndVerifySessionDb(options) {
2164
+ const env = options.env ?? process.env;
2165
+ clearMarker(options);
2166
+ acknowledgeSessionDbRecoveryReport(sessionDbRecoveryReportPath(homedir2(), env));
2167
+ const synchroniserEnv = await runSynchroniser(["env"], {
2168
+ timeoutMs: SESSION_DB_SYNCHRONISER_TIMEOUT_MS,
2169
+ env
2170
+ });
2171
+ logSynchroniserDiagnostics(synchroniserEnv, options);
2172
+ if (synchroniserEnv.timedOut || synchroniserEnv.code !== 0) {
2173
+ options.log(
2174
+ `runner-synchroniser env could not resolve the session-DB configuration (${commandError(synchroniserEnv)})`,
2175
+ "error"
2176
+ );
2177
+ markNoReplicate(
2178
+ options,
2179
+ "could not resolve the runner-synchroniser configuration (see the ERROR above)"
2180
+ );
2181
+ reportRecord(
2182
+ "restore",
2183
+ "restore_misconfigured",
2184
+ "synchroniser_config_unresolved",
2185
+ null,
2186
+ options
2187
+ );
2188
+ return { verifyFatal: false };
2189
+ }
2190
+ const values = parseSynchroniserEnv(synchroniserEnv.stdout);
2191
+ if (!values) {
2192
+ markNoReplicate(
2193
+ options,
2194
+ "the runner-synchroniser configuration could not be evaluated; the installed bundle likely does not match this hook"
2195
+ );
2196
+ reportRecord(
2197
+ "restore",
2198
+ "restore_misconfigured",
2199
+ "synchroniser_config_unevaluable",
2200
+ null,
2201
+ options
2202
+ );
2203
+ return { verifyFatal: false };
2204
+ }
2205
+ const synchroniserDbPath = values.OPENCODE_DB_PATH;
2206
+ if (!synchroniserDbPath) {
2207
+ markNoReplicate(
2208
+ options,
2209
+ "run_synchroniser env did not define OPENCODE_DB_PATH; the installed runner-synchroniser build likely does not match this hook"
2210
+ );
2211
+ reportRecord(
2212
+ "restore",
2213
+ "restore_misconfigured",
2214
+ "synchroniser_config_incomplete",
2215
+ null,
2216
+ options
2217
+ );
2218
+ return { verifyFatal: false };
2219
+ }
2220
+ if (resolvePath(synchroniserDbPath) !== resolvePath(options.dbPath)) {
2221
+ options.log(
2222
+ `runner-synchroniser reported OPENCODE_DB_PATH=${synchroniserDbPath}, but OpenCode uses ${options.dbPath}; continuing with OpenCode's session-DB path`,
2223
+ "warn"
2224
+ );
2225
+ }
2226
+ if (!values.PERSISTENCE_BUCKET) {
2227
+ options.log(
2228
+ "SESSION-DB-PERSISTENCE-DISABLED: LITESTREAM_BUCKET/LITESTREAM_PREFIX are not both set; opencode starts with a fresh session DB and nothing is replicated.",
2229
+ "warn"
2230
+ );
2231
+ return { verifyFatal: false };
2232
+ }
2233
+ const configPath = await ensureLitestreamConfig(options, env);
2234
+ if (!configPath) return { verifyFatal: false };
2235
+ await restoreSessionDb(options, configPath, env);
2236
+ if (options.noReplicateMarker && fileExists(options.noReplicateMarker)) {
2237
+ return { verifyFatal: false };
2238
+ }
2239
+ return { verifyFatal: await verifySessionDb(options, configPath, env) };
2240
+ }
2241
+
2242
+ // src/lib/opencode/session-db-provenance.ts
2243
+ import { createRequire } from "module";
2244
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
2245
+ import { dirname as dirname3, join as join3 } from "path";
2246
+ var require2 = createRequire(import.meta.url);
2247
+ function readSessionDbMigrationIds(dbPath) {
2248
+ let db;
2249
+ try {
2250
+ const { DatabaseSync } = require2("node:sqlite");
2251
+ db = new DatabaseSync(dbPath, { readOnly: true });
2252
+ const columns = db.prepare("PRAGMA table_info(migration)").all();
2253
+ const hasExpectedShape = columns.length === 2 && columns.some(
2254
+ (column) => column.name === "id" && typeof column.type === "string" && column.type.toUpperCase() === "TEXT" && column.pk === 1
2255
+ ) && columns.some(
2256
+ (column) => column.name === "time_completed" && typeof column.type === "string" && column.type.toUpperCase() === "INTEGER" && column.notnull === 1 && column.pk === 0
2257
+ );
2258
+ if (!hasExpectedShape) {
2259
+ console.warn(`[readSessionDbMigrationIds] unsupported migration table shape in ${dbPath}`);
2260
+ return null;
2261
+ }
2262
+ const rows = db.prepare("SELECT id FROM migration ORDER BY id").all();
2263
+ if (rows.some((row) => typeof row.id !== "string")) return null;
2264
+ return rows.map((row) => row.id);
2265
+ } catch (error2) {
2266
+ console.warn(
2267
+ `[readSessionDbMigrationIds] could not read migration history from ${dbPath}: ${error2 instanceof Error ? error2.message : String(error2)}`
2268
+ );
2269
+ return null;
2270
+ } finally {
2271
+ try {
2272
+ db?.close();
2273
+ } catch (error2) {
2274
+ console.warn(
2275
+ `[readSessionDbMigrationIds] could not close ${dbPath}: ${error2 instanceof Error ? error2.message : String(error2)}`
2276
+ );
2277
+ }
2278
+ }
2279
+ }
2280
+ function sessionDbProvenanceStatePath(homeDir, env) {
2281
+ const override = env.EVIDENT_SESSION_DB_PROVENANCE_STATE?.trim();
2282
+ return override || join3(homeDir, ".local", "state", "evident", "session-db-provenance.json");
2283
+ }
2284
+ function loadSessionDbProvenanceState(path) {
2285
+ let value;
2286
+ try {
2287
+ value = JSON.parse(readFileSync3(path, "utf8"));
2288
+ } catch (error2) {
2289
+ if (error2 instanceof Error && "code" in error2 && error2.code === "ENOENT") return {};
2290
+ console.error(
2291
+ `[session-db-provenance] could not read ${path}: ${error2 instanceof Error ? error2.message : String(error2)}`
2292
+ );
2293
+ return {};
2294
+ }
2295
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
2296
+ console.error(`[session-db-provenance] ignored malformed state in ${path}`);
2297
+ return {};
2298
+ }
2299
+ const state = {};
2300
+ for (const [dbPath, record] of Object.entries(value)) {
2301
+ if (!isSessionDbProvenanceRecord(record)) {
2302
+ console.error(`[session-db-provenance] ignored malformed state in ${path}`);
2303
+ return {};
2304
+ }
2305
+ state[dbPath] = record;
2306
+ }
2307
+ return state;
2308
+ }
2309
+ function saveSessionDbProvenanceState(path, state) {
2310
+ try {
2311
+ mkdirSync2(dirname3(path), { recursive: true });
2312
+ writeFileSync2(path, `${JSON.stringify(state, null, 2)}
2313
+ `, "utf8");
2314
+ } catch (error2) {
2315
+ console.error(
2316
+ `[session-db-provenance] could not write ${path}: ${error2 instanceof Error ? error2.message : String(error2)}`
2317
+ );
2318
+ }
2319
+ }
2320
+ function evaluateSessionDbProvenance(input) {
2321
+ const { currentVersion, currentIds, previous } = input;
2322
+ if (!previous) return { anomaly: false, reason: null };
2323
+ const current = new Set(currentIds);
2324
+ const prior = new Set(previous.migrationIds);
2325
+ for (const id of prior) {
2326
+ if (!current.has(id)) return { anomaly: true, reason: "migration-history-regressed" };
2327
+ }
2328
+ if (current.size > prior.size && previous.opencodeVersion === currentVersion) {
2329
+ return { anomaly: true, reason: "foreign-version-migrations" };
2330
+ }
2331
+ return { anomaly: false, reason: null };
2332
+ }
2333
+ function checkSessionDbProvenance(input) {
2334
+ const { dbPath, currentVersion, homeDir, env } = input;
2335
+ const path = sessionDbProvenanceStatePath(homeDir, env);
2336
+ const state = loadSessionDbProvenanceState(path);
2337
+ const previous = state[dbPath];
2338
+ const currentIds = readSessionDbMigrationIds(dbPath);
2339
+ if (currentIds === null) {
2340
+ return {
2341
+ anomaly: false,
2342
+ reason: null,
2343
+ recordedVersion: previous?.opencodeVersion ?? null,
2344
+ migrationDelta: null
2345
+ };
2346
+ }
2347
+ const decision = evaluateSessionDbProvenance({ currentVersion, currentIds, previous });
2348
+ const migrationDelta = previous ? new Set(currentIds).size - new Set(previous.migrationIds).size : null;
2349
+ state[dbPath] = {
2350
+ opencodeVersion: currentVersion,
2351
+ migrationIds: currentIds,
2352
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
2353
+ };
2354
+ saveSessionDbProvenanceState(path, state);
2355
+ return {
2356
+ ...decision,
2357
+ recordedVersion: previous?.opencodeVersion ?? null,
2358
+ migrationDelta
2359
+ };
2360
+ }
2361
+ function isSessionDbProvenanceRecord(value) {
2362
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
2363
+ const record = value;
2364
+ return typeof record.opencodeVersion === "string" && Array.isArray(record.migrationIds) && record.migrationIds.every((id) => typeof id === "string") && typeof record.updatedAt === "string";
2365
+ }
2366
+
2367
+ // src/lib/opencode/opencode-version-gate.ts
2368
+ var QUEUE_VALIDATED_OPENCODE_VERSIONS = ["1.17.11", "1.18.3"];
2369
+ function isQueueValidatedVersion(version2) {
2370
+ if (!version2) return false;
2371
+ return QUEUE_VALIDATED_OPENCODE_VERSIONS.includes(version2);
2372
+ }
2373
+ function buildOpenCodeVersionWarning(version2) {
2374
+ if (isQueueValidatedVersion(version2)) return null;
2375
+ const detected = version2 ? `v${version2}` : "unknown";
2376
+ const validated = QUEUE_VALIDATED_OPENCODE_VERSIONS.map((v) => `v${v}`).join(", ");
2377
+ return `Warning: opencode ${detected} is not a queue-validated version (validated: ${validated}). Native message queuing \u2014 which channel (Slack) message handling relies on \u2014 is unverified on this version; queued/follow-up messages may behave unexpectedly. Continuing anyway. Bumping the validated set requires re-running the queue validation.`;
2378
+ }
2379
+
2380
+ // src/lib/opencode/process.ts
2381
+ import { execSync, spawn as spawn3 } from "child_process";
2382
+
2383
+ // src/lib/process-stop.ts
2384
+ async function stopProcessAndWait(child, timeoutMs, sendTerm, sendKill) {
2385
+ if (!child.pid) {
2386
+ return { outcome: "not-running", code: child.exitCode, signal: child.signalCode };
2387
+ }
2388
+ if (child.exitCode !== null || child.signalCode !== null) {
2389
+ return { outcome: "exited", code: child.exitCode, signal: child.signalCode };
2390
+ }
2391
+ return new Promise((resolve4, reject) => {
2392
+ let forced = false;
2393
+ let settled = false;
2394
+ const timer = setTimeout(() => {
2395
+ forced = true;
2396
+ try {
2397
+ sendKill();
2398
+ } catch (error2) {
2399
+ if (error2.code === "ESRCH") {
2400
+ finish({ outcome: "exited", code: child.exitCode, signal: child.signalCode });
2401
+ } else {
2402
+ fail(error2);
2403
+ }
2404
+ }
2405
+ }, timeoutMs);
2406
+ const finish = (result) => {
2407
+ if (settled) return;
2408
+ settled = true;
2409
+ clearTimeout(timer);
2410
+ child.removeListener("exit", onExit);
2411
+ resolve4(result);
2412
+ };
2413
+ const fail = (error2) => {
2414
+ if (settled) return;
2415
+ settled = true;
2416
+ clearTimeout(timer);
2417
+ child.removeListener("exit", onExit);
2418
+ reject(error2);
2419
+ };
2420
+ const onExit = (code, signal) => {
2421
+ finish({ outcome: forced ? "killed" : "exited", code, signal });
2422
+ };
2423
+ child.once("exit", onExit);
2424
+ try {
2425
+ sendTerm();
2426
+ } catch (error2) {
2427
+ if (error2.code === "ESRCH") {
2428
+ finish({ outcome: "exited", code: child.exitCode, signal: child.signalCode });
2429
+ } else {
2430
+ fail(error2);
2431
+ }
2432
+ return;
2433
+ }
2434
+ });
2435
+ }
2436
+
2437
+ // src/lib/opencode/process.ts
2438
+ var OPENCODE_PORT_RANGE = [4096, 4097, 4098, 4099, 4100];
2439
+ function getProcessCwd(pid) {
2440
+ const platform = process.platform;
2441
+ try {
2442
+ if (platform === "darwin") {
2443
+ const output = execSync(`lsof -a -p ${pid} -d cwd -Fn 2>/dev/null`, {
2444
+ encoding: "utf-8",
2445
+ stdio: ["pipe", "pipe", "pipe"]
2446
+ }).trim();
2447
+ const lines = output.split("\n");
2448
+ for (const line of lines) {
2449
+ if (line.startsWith("n") && !line.startsWith("n ")) {
2450
+ return line.slice(1);
2451
+ }
2452
+ }
2453
+ } else if (platform === "linux") {
2454
+ const output = execSync(`readlink /proc/${pid}/cwd 2>/dev/null`, {
2455
+ encoding: "utf-8",
2456
+ stdio: ["pipe", "pipe", "pipe"]
2457
+ }).trim();
2458
+ if (output) return output;
2459
+ }
2460
+ } catch {
2461
+ }
2462
+ return void 0;
2463
+ }
2464
+ function isPortInUse(port) {
2465
+ const platform = process.platform;
2466
+ try {
2467
+ if (platform === "darwin" || platform === "linux") {
2468
+ execSync(`lsof -i :${port} -sTCP:LISTEN 2>/dev/null`, {
2469
+ encoding: "utf-8",
2470
+ stdio: ["pipe", "pipe", "pipe"]
2471
+ });
2472
+ return true;
2473
+ }
2474
+ } catch {
2475
+ }
2476
+ return false;
2477
+ }
2478
+ function findAvailablePort(startPort, maxAttempts = 10) {
2479
+ for (let i = 0; i < maxAttempts; i++) {
2480
+ const port = startPort + i;
2481
+ if (!isPortInUse(port)) {
2482
+ return port;
2483
+ }
2484
+ }
2485
+ return null;
2486
+ }
2487
+ function findOpenCodeProcesses() {
2488
+ const instances = [];
2489
+ try {
2490
+ const platform = process.platform;
2491
+ if (platform === "darwin" || platform === "linux") {
2492
+ let pids = [];
2493
+ try {
2494
+ const pgrepOutput = execSync('pgrep -f "opencode serve|opencode-serve"', {
2495
+ encoding: "utf-8",
2496
+ stdio: ["pipe", "pipe", "pipe"]
2497
+ }).trim();
2498
+ if (pgrepOutput) {
2499
+ pids = pgrepOutput.split("\n").map((p) => parseInt(p.trim(), 10)).filter((p) => !isNaN(p));
2500
+ }
2501
+ } catch {
2502
+ try {
2503
+ const psOutput = execSync('ps aux | grep -E "opencode (serve|--port)" | grep -v grep', {
2504
+ encoding: "utf-8",
2505
+ stdio: ["pipe", "pipe", "pipe"]
2506
+ }).trim();
2507
+ if (psOutput) {
2508
+ for (const line of psOutput.split("\n")) {
2509
+ const parts = line.trim().split(/\s+/);
2510
+ if (parts.length >= 2) {
2511
+ const pid = parseInt(parts[1], 10);
2512
+ if (!isNaN(pid)) pids.push(pid);
2513
+ }
2514
+ }
2515
+ }
2516
+ } catch (err) {
2517
+ console.warn(
2518
+ `findOpenCodeProcesses: ps fallback failed: ${err instanceof Error ? err.message : String(err)}`
2519
+ );
2520
+ }
2521
+ }
2522
+ for (const pid of pids) {
2523
+ try {
2524
+ const lsofOutput = execSync(`lsof -Pan -p ${pid} -i TCP -sTCP:LISTEN 2>/dev/null`, {
2525
+ encoding: "utf-8",
2526
+ stdio: ["pipe", "pipe", "pipe"]
2527
+ }).trim();
2528
+ for (const line of lsofOutput.split("\n")) {
2529
+ const portMatch = line.match(/:(\d+)\s+\(LISTEN\)/);
2530
+ if (portMatch) {
2531
+ const port = parseInt(portMatch[1], 10);
2532
+ if (!isNaN(port) && !instances.some((i) => i.port === port)) {
2533
+ const cwd = getProcessCwd(pid);
2534
+ instances.push({ pid, port, cwd });
2535
+ }
2536
+ }
2537
+ }
2538
+ } catch {
2539
+ }
2540
+ }
2541
+ }
2542
+ } catch (err) {
2543
+ console.warn(
2544
+ `findOpenCodeProcesses: process detection failed: ${err instanceof Error ? err.message : String(err)}`
2545
+ );
2546
+ }
2547
+ return instances;
2548
+ }
2549
+ async function scanPortsForOpenCode() {
2550
+ const instances = [];
2551
+ const checks = OPENCODE_PORT_RANGE.map(async (port) => {
2552
+ const health = await checkOpenCodeHealth(port);
2553
+ if (health.healthy) {
2554
+ let pid = 0;
2555
+ try {
2556
+ const lsofOutput = execSync(`lsof -ti :${port} -sTCP:LISTEN 2>/dev/null`, {
2557
+ encoding: "utf-8",
2558
+ stdio: ["pipe", "pipe", "pipe"]
2559
+ }).trim();
2560
+ if (lsofOutput) {
2561
+ pid = parseInt(lsofOutput.split("\n")[0], 10) || 0;
2562
+ }
2563
+ } catch {
2564
+ }
2565
+ const cwd = pid ? getProcessCwd(pid) : void 0;
2566
+ return { pid, port, cwd, version: health.version };
2567
+ }
2568
+ return null;
2569
+ });
2570
+ const results = await Promise.all(checks);
2571
+ for (const result of results) {
2572
+ if (result) {
2573
+ instances.push(result);
2574
+ }
2575
+ }
2576
+ return instances;
2577
+ }
2578
+ async function findHealthyOpenCodeInstances() {
2579
+ const processes = findOpenCodeProcesses();
2580
+ const healthy = [];
2581
+ for (const proc of processes) {
2582
+ const health = await checkOpenCodeHealth(proc.port);
2583
+ if (health.healthy) {
2584
+ healthy.push({ ...proc, version: health.version });
2585
+ }
2586
+ }
2587
+ if (healthy.length === 0) {
2588
+ const scanned = await scanPortsForOpenCode();
2589
+ return scanned;
2590
+ }
2591
+ return healthy;
2592
+ }
2593
+ async function startOpenCode(port, options = {}) {
2594
+ let command = "opencode";
2595
+ const printLogs = options.inheritStdio ? ["--print-logs"] : [];
2596
+ let args = ["serve", "--port", port.toString(), "--hostname", "127.0.0.1", ...printLogs];
2597
+ try {
2598
+ execSync("which opencode", { stdio: "ignore" });
2599
+ } catch {
2600
+ command = "npx";
2601
+ args = [
2602
+ "opencode",
2603
+ "serve",
2604
+ "--port",
2605
+ port.toString(),
2606
+ "--hostname",
2607
+ "127.0.0.1",
2608
+ ...printLogs
2609
+ ];
2610
+ }
2611
+ const child = spawn3(command, args, {
2612
+ detached: true,
2613
+ stdio: options.inheritStdio ? "inherit" : "ignore",
2614
+ cwd: process.cwd()
2615
+ });
2616
+ return child;
2617
+ }
2618
+ function stopOpenCodeAndWait(opencodeProcess, timeoutMs) {
2619
+ const sendSignal = (signal) => {
2620
+ if (process.platform === "win32") {
2621
+ opencodeProcess.kill(signal);
2622
+ } else {
2623
+ process.kill(-opencodeProcess.pid, signal);
2624
+ }
2625
+ };
2626
+ return stopProcessAndWait(
2627
+ opencodeProcess,
2628
+ timeoutMs,
2629
+ () => sendSignal("SIGTERM"),
2630
+ () => sendSignal("SIGKILL")
2631
+ );
1808
2632
  }
1809
2633
 
1810
2634
  // src/lib/opencode/install.ts
@@ -2091,6 +2915,7 @@ async function createOpenCodeSession(port, directory) {
2091
2915
  return data.id;
2092
2916
  }
2093
2917
  async function getModelAttachmentCapability(port, model) {
2918
+ const { model: baseModel } = splitModelVariant(model);
2094
2919
  try {
2095
2920
  const res = await timedFetch(`${opencodeBase(port)}/config/providers`);
2096
2921
  if (!res.ok) {
@@ -2107,9 +2932,9 @@ async function getModelAttachmentCapability(port, model) {
2107
2932
  );
2108
2933
  return null;
2109
2934
  }
2110
- const slash = model ? model.indexOf("/") : -1;
2111
- const providerId = slash > 0 ? model.slice(0, slash) : void 0;
2112
- let modelId = slash > 0 ? model.slice(slash + 1) : void 0;
2935
+ const slash = baseModel ? baseModel.indexOf("/") : -1;
2936
+ const providerId = slash > 0 ? baseModel.slice(0, slash) : void 0;
2937
+ let modelId = slash > 0 ? baseModel.slice(slash + 1) : void 0;
2113
2938
  const defaults2 = body?.default && typeof body.default === "object" ? body.default : void 0;
2114
2939
  let provider = providerId ? providers.find((p) => p?.id === providerId) : void 0;
2115
2940
  if (!provider && !providerId) {
@@ -2189,6 +3014,29 @@ async function buildFileParts(attachments, capable) {
2189
3014
  }
2190
3015
  return { parts, outcomes, capabilityUnknown };
2191
3016
  }
3017
+ function splitModelVariant(raw) {
3018
+ const value = raw?.trim();
3019
+ if (!value) return {};
3020
+ const hashIndex = value.indexOf("#");
3021
+ if (hashIndex === -1) return { model: value };
3022
+ const model = value.slice(0, hashIndex).trim() || void 0;
3023
+ const variant = value.slice(hashIndex + 1).trim() || void 0;
3024
+ return { model, variant };
3025
+ }
3026
+ function applyModelOptions(body, options) {
3027
+ if (options?.agent) body.agent = options.agent;
3028
+ const { model, variant } = splitModelVariant(options?.model);
3029
+ if (model) {
3030
+ const slashIndex = model.indexOf("/");
3031
+ if (slashIndex !== -1) {
3032
+ body.model = {
3033
+ providerID: model.substring(0, slashIndex),
3034
+ modelID: model.substring(slashIndex + 1)
3035
+ };
3036
+ }
3037
+ }
3038
+ if (variant) body.variant = variant;
3039
+ }
2192
3040
  function messageText(m) {
2193
3041
  if (!m || !Array.isArray(m.parts)) return "";
2194
3042
  return m.parts.filter((p) => p.type === "text" && typeof p.text === "string").map((p) => p.text).join("");
@@ -2213,18 +3061,7 @@ async function sendPromptAsync(port, sessionId, content, options, attachments) {
2213
3061
  const body = {
2214
3062
  parts
2215
3063
  };
2216
- if (options?.agent) {
2217
- body.agent = options.agent;
2218
- }
2219
- if (options?.model) {
2220
- const slashIndex = options.model.indexOf("/");
2221
- if (slashIndex !== -1) {
2222
- body.model = {
2223
- providerID: options.model.substring(0, slashIndex),
2224
- modelID: options.model.substring(slashIndex + 1)
2225
- };
2226
- }
2227
- }
3064
+ applyModelOptions(body, options);
2228
3065
  const res = await timedFetch(`${opencodeBase(port)}/session/${sessionId}/prompt_async`, {
2229
3066
  method: "POST",
2230
3067
  headers: { "Content-Type": "application/json" },
@@ -2232,7 +3069,10 @@ async function sendPromptAsync(port, sessionId, content, options, attachments) {
2232
3069
  });
2233
3070
  if (res.status < 200 || res.status >= 300) {
2234
3071
  const text = await res.text().catch(() => "");
2235
- throw new Error(`OpenCode prompt_async failed: HTTP ${res.status}${text ? `: ${text}` : ""}`);
3072
+ const { variant } = splitModelVariant(options?.model);
3073
+ throw new Error(
3074
+ `OpenCode prompt_async failed: HTTP ${res.status}${text ? `: ${text}` : ""}${variant ? ` (variant: ${variant})` : ""}`
3075
+ );
2236
3076
  }
2237
3077
  const READ_BACK_ATTEMPTS = 5;
2238
3078
  const READ_BACK_DELAY_MS = 150;
@@ -2256,7 +3096,7 @@ async function sendPromptAsync(port, sessionId, content, options, attachments) {
2256
3096
  }
2257
3097
  }
2258
3098
  if (attempt < READ_BACK_ATTEMPTS - 1) {
2259
- await new Promise((resolve3) => setTimeout(resolve3, READ_BACK_DELAY_MS));
3099
+ await new Promise((resolve4) => setTimeout(resolve4, READ_BACK_DELAY_MS));
2260
3100
  }
2261
3101
  }
2262
3102
  return null;
@@ -2387,7 +3227,7 @@ function isPreamblePinnedRunning(messages, userMessageId) {
2387
3227
  return completedOf(reply) != null && finishOf(reply) === "tool-calls";
2388
3228
  }
2389
3229
  function isB2AbandonmentConfirmed(params) {
2390
- return params.pinnedForMs >= params.minPinnedMs && params.descendantOngoing === false;
3230
+ return params.pinnedForMs >= params.minPinnedMs && params.descendantOngoing === false && params.rootOngoing === false;
2391
3231
  }
2392
3232
  function isAmbiguousTerminalFinish(m) {
2393
3233
  if (completedOf(m) == null) return false;
@@ -2400,7 +3240,7 @@ function isAmbiguousFinishPinnedRunning(messages, userMessageId) {
2400
3240
  return isAmbiguousTerminalFinish(reply);
2401
3241
  }
2402
3242
  function isAmbiguousFinishResolved(params) {
2403
- return params.sessionOngoing === false || params.pinnedForMs >= params.maxPinnedMs;
3243
+ return params.sessionOngoing === false || params.sessionOngoing !== true && params.pinnedForMs >= params.maxPinnedMs;
2404
3244
  }
2405
3245
  function messageError(messages, userMessageId) {
2406
3246
  const reply = findLastAssistantReplyFor(messages, userMessageId);
@@ -2609,13 +3449,13 @@ function resolveSessionCleanupConfig(flags, env = process.env) {
2609
3449
  }
2610
3450
 
2611
3451
  // src/lib/opencode/session-db-size.ts
2612
- import { statSync as statSync2 } from "fs";
2613
- import { join as join3 } from "path";
3452
+ import { statSync as statSync3 } from "fs";
3453
+ import { join as join4 } from "path";
2614
3454
  var LARGE_DB_THRESHOLD_BYTES = 268435456;
2615
3455
  function statSessionDbBytes(homeDir) {
2616
- const dbPath = join3(homeDir, ".local", "share", "opencode", "opencode.db");
3456
+ const dbPath = join4(homeDir, ".local", "share", "opencode", "opencode.db");
2617
3457
  try {
2618
- return statSync2(dbPath).size;
3458
+ return statSync3(dbPath).size;
2619
3459
  } catch (err) {
2620
3460
  const isMissingFile = err instanceof Error && "code" in err && err.code === "ENOENT";
2621
3461
  if (!isMissingFile) {
@@ -2641,11 +3481,11 @@ function buildSessionStoreSizeWarning(input) {
2641
3481
  }
2642
3482
 
2643
3483
  // src/lib/opencode/session-db-reclaim.ts
2644
- import { statSync as statSync3, statfsSync } from "fs";
2645
- import { dirname as dirname2 } from "path";
3484
+ import { statSync as statSync4, statfsSync } from "fs";
3485
+ import { dirname as dirname4 } from "path";
2646
3486
  function insufficientSpaceReason(dbPath, requiredBytes) {
2647
3487
  try {
2648
- const fsStats = statfsSync(dirname2(dbPath));
3488
+ const fsStats = statfsSync(dirname4(dbPath));
2649
3489
  const availableBytes = fsStats.bavail * fsStats.bsize;
2650
3490
  if (availableBytes < requiredBytes) {
2651
3491
  return `only ${availableBytes} bytes free, need ${requiredBytes} for a second copy`;
@@ -2714,7 +3554,7 @@ async function reclaimSessionDbSpace(input) {
2714
3554
  );
2715
3555
  return { ok: false, skipped: "full-vacuum-blocked" };
2716
3556
  }
2717
- const fileBytesForGuard = statSync3(dbPath).size;
3557
+ const fileBytesForGuard = statSync4(dbPath).size;
2718
3558
  const skipReason = insufficientSpaceReason(dbPath, fileBytesForGuard);
2719
3559
  if (skipReason !== null) {
2720
3560
  console.warn(
@@ -2842,12 +3682,12 @@ var StreamForwarder = class {
2842
3682
  let endBody;
2843
3683
  if (has_body) {
2844
3684
  const chunks = [];
2845
- bodyPromise = new Promise((resolve3) => {
3685
+ bodyPromise = new Promise((resolve4) => {
2846
3686
  pushBody = (buf) => {
2847
3687
  chunks.push(buf);
2848
3688
  };
2849
3689
  endBody = () => {
2850
- resolve3(Buffer.concat(chunks));
3690
+ resolve4(Buffer.concat(chunks));
2851
3691
  };
2852
3692
  });
2853
3693
  }
@@ -2976,7 +3816,7 @@ function connectTunnel(options) {
2976
3816
  } = options;
2977
3817
  const tunnelUrl = getTunnelUrlConfig();
2978
3818
  const url = `${tunnelUrl}/tunnel/${agentId}/connect`;
2979
- return new Promise((resolve3, reject) => {
3819
+ return new Promise((resolve4, reject) => {
2980
3820
  const ws = new WebSocket2(url, {
2981
3821
  headers: {
2982
3822
  Authorization: authHeader
@@ -3027,8 +3867,8 @@ function connectTunnel(options) {
3027
3867
  try {
3028
3868
  message = JSON.parse(data.toString());
3029
3869
  } catch (error2) {
3030
- const errorMessage = error2 instanceof Error ? error2.message : "Unknown error";
3031
- onError?.(`Failed to handle message: ${errorMessage}`);
3870
+ const errorMessage2 = error2 instanceof Error ? error2.message : "Unknown error";
3871
+ onError?.(`Failed to handle message: ${errorMessage2}`);
3032
3872
  return;
3033
3873
  }
3034
3874
  if (isStreamFrame(message)) {
@@ -3040,7 +3880,7 @@ function connectTunnel(options) {
3040
3880
  clearTimeout(connectionTimeout);
3041
3881
  const connectedAgentId = message.agent_id ?? agentId;
3042
3882
  onConnected?.(connectedAgentId);
3043
- resolve3({
3883
+ resolve4({
3044
3884
  ws,
3045
3885
  close: () => ws.close(1e3, "CLI shutdown")
3046
3886
  });
@@ -3171,10 +4011,10 @@ var RunnerConnection = class {
3171
4011
  };
3172
4012
 
3173
4013
  // src/lib/tunnel/ready-marker.ts
3174
- import { writeFileSync } from "fs";
4014
+ import { writeFileSync as writeFileSync3 } from "fs";
3175
4015
  function writeTunnelReadyMarker(path, agentId) {
3176
4016
  try {
3177
- writeFileSync(path, `${agentId}
4017
+ writeFileSync3(path, `${agentId}
3178
4018
  `);
3179
4019
  return { ok: true };
3180
4020
  } catch (error2) {
@@ -3182,10 +4022,52 @@ function writeTunnelReadyMarker(path, agentId) {
3182
4022
  }
3183
4023
  }
3184
4024
 
4025
+ // src/lib/replication.ts
4026
+ import { spawn as spawn4 } from "child_process";
4027
+ function startSessionDbReplication(configPath) {
4028
+ return spawn4("litestream", ["replicate", "-config", configPath], {
4029
+ stdio: "inherit"
4030
+ });
4031
+ }
4032
+ async function stopSessionDbReplication(child, timeoutMs) {
4033
+ return stopProcessAndWait(
4034
+ child,
4035
+ timeoutMs,
4036
+ () => child.kill("SIGTERM"),
4037
+ () => child.kill("SIGKILL")
4038
+ );
4039
+ }
4040
+
4041
+ // src/lib/process-liveness.ts
4042
+ import { readFileSync as readFileSync4 } from "fs";
4043
+ function isProcessAlive(pid) {
4044
+ try {
4045
+ process.kill(pid, 0);
4046
+ } catch (error2) {
4047
+ const code = error2.code;
4048
+ if (code === "ESRCH") return false;
4049
+ if (code === "EPERM") return true;
4050
+ console.error(
4051
+ `[process-liveness] could not probe process ${pid}: ${error2 instanceof Error ? error2.message : String(error2)}`
4052
+ );
4053
+ return false;
4054
+ }
4055
+ if (process.platform !== "linux") return true;
4056
+ try {
4057
+ const status2 = readFileSync4(`/proc/${pid}/status`, "utf8");
4058
+ return !/^State:\s+Z(?:\s|$)/m.test(status2);
4059
+ } catch (error2) {
4060
+ console.error(
4061
+ `[process-liveness] could not inspect /proc/${pid}/status: ${error2 instanceof Error ? error2.message : String(error2)}`
4062
+ );
4063
+ return true;
4064
+ }
4065
+ }
4066
+
3185
4067
  // src/lib/openai-usage.ts
3186
- import { readFileSync as readFileSync3 } from "fs";
3187
- import { homedir as homedir2 } from "os";
3188
- import { join as join4 } from "path";
4068
+ import { readFileSync as readFileSync5 } from "fs";
4069
+ import { homedir as homedir3 } from "os";
4070
+ import { join as join5 } from "path";
3189
4071
  var CODEX_RESPONSES_URL = "https://chatgpt.com/backend-api/codex/responses";
3190
4072
  var OPENCODE_AUTH_SEGMENTS = [".local", "share", "opencode", "auth.json"];
3191
4073
  var OpenAiUsageError = class extends Error {
@@ -3199,7 +4081,7 @@ function isLocalCredentialProblem2(err) {
3199
4081
  }
3200
4082
  function readOpenCodeChatGptCredentials() {
3201
4083
  try {
3202
- const raw = readFileSync3(join4(homedir2(), ...OPENCODE_AUTH_SEGMENTS), "utf-8");
4084
+ const raw = readFileSync5(join5(homedir3(), ...OPENCODE_AUTH_SEGMENTS), "utf-8");
3203
4085
  let parsed;
3204
4086
  try {
3205
4087
  parsed = JSON.parse(raw);
@@ -3572,15 +4454,15 @@ function createResourceUsageCollector(homeDir) {
3572
4454
  }
3573
4455
 
3574
4456
  // src/lib/channels/driver.ts
3575
- import { homedir as homedir3 } from "os";
4457
+ import { homedir as homedir4 } from "os";
3576
4458
 
3577
4459
  // src/lib/runner-file-sync.ts
3578
- import { join as join6 } from "path";
4460
+ import { join as join7 } from "path";
3579
4461
 
3580
4462
  // src/lib/file-push.ts
3581
4463
  import { randomUUID } from "crypto";
3582
4464
  import { chmod, mkdir, open as open2, realpath, rename, unlink } from "fs/promises";
3583
- import { basename, dirname as dirname3, isAbsolute, join as join5, relative, resolve as resolve2, sep } from "path";
4465
+ import { basename, dirname as dirname5, isAbsolute, join as join6, relative, resolve as resolve2, sep } from "path";
3584
4466
  var FILE_MODE = 384;
3585
4467
  var DIRECTORY_MODE = 448;
3586
4468
  async function writePushedFile(request) {
@@ -3611,9 +4493,9 @@ async function writePushedFile(request) {
3611
4493
  }
3612
4494
  try {
3613
4495
  const { existingAncestor, missingSegments } = await resolveNearestExistingAncestor(
3614
- dirname3(candidate)
4496
+ dirname5(candidate)
3615
4497
  );
3616
- const realTarget = join5(existingAncestor, ...missingSegments, basename(candidate));
4498
+ const realTarget = join6(existingAncestor, ...missingSegments, basename(candidate));
3617
4499
  const allowedDirectory = await findContainingAllowedDirectory(allowedDirectories, realTarget);
3618
4500
  if (allowedDirectory === null) {
3619
4501
  return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
@@ -3623,8 +4505,8 @@ async function writePushedFile(request) {
3623
4505
  }
3624
4506
  if (missingSegments.length > 0) {
3625
4507
  await createMissingDirectories(existingAncestor, missingSegments);
3626
- const realParent = await realpath(dirname3(realTarget));
3627
- if (realParent !== dirname3(realTarget) || !contains(allowedDirectory, realTarget)) {
4508
+ const realParent = await realpath(dirname5(realTarget));
4509
+ if (realParent !== dirname5(realTarget) || !contains(allowedDirectory, realTarget)) {
3628
4510
  return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
3629
4511
  path: realTarget,
3630
4512
  bytes,
@@ -3649,7 +4531,7 @@ function expandAndValidate(requestedPath, homeDir) {
3649
4531
  if (requestedPath.trim() === "" || requestedPath.includes("\0")) {
3650
4532
  return null;
3651
4533
  }
3652
- const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join5(homeDir, requestedPath.slice(2)) : requestedPath;
4534
+ const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join6(homeDir, requestedPath.slice(2)) : requestedPath;
3653
4535
  if (expanded.split(/[/\\]/).includes("..")) {
3654
4536
  return null;
3655
4537
  }
@@ -3667,7 +4549,7 @@ async function resolveNearestExistingAncestor(directory) {
3667
4549
  try {
3668
4550
  return { existingAncestor: await realpath(current), missingSegments };
3669
4551
  } catch (err) {
3670
- const parent = dirname3(current);
4552
+ const parent = dirname5(current);
3671
4553
  if (err.code !== "ENOENT" || parent === current) {
3672
4554
  throw err;
3673
4555
  }
@@ -3722,13 +4604,13 @@ function contains(realDirectory, realTarget) {
3722
4604
  async function createMissingDirectories(existingAncestor, missingSegments) {
3723
4605
  let current = existingAncestor;
3724
4606
  for (const segment of missingSegments) {
3725
- current = join5(current, segment);
4607
+ current = join6(current, segment);
3726
4608
  await mkdir(current, { recursive: true, mode: DIRECTORY_MODE });
3727
4609
  await chmod(current, DIRECTORY_MODE);
3728
4610
  }
3729
4611
  }
3730
4612
  async function writeAtomically(realTarget, content) {
3731
- const temporaryPath = join5(dirname3(realTarget), `.evident-push-${randomUUID()}.tmp`);
4613
+ const temporaryPath = join6(dirname5(realTarget), `.evident-push-${randomUUID()}.tmp`);
3732
4614
  let handle;
3733
4615
  try {
3734
4616
  handle = await open2(temporaryPath, "wx", FILE_MODE);
@@ -3858,12 +4740,12 @@ var NOT_APPLIED = {
3858
4740
  opencodeAuthApplied: false
3859
4741
  };
3860
4742
  function isClaudeCredentialPath(requestedPath, homeDir) {
3861
- const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join6(homeDir, requestedPath.slice(2)) : requestedPath;
3862
- return expanded === join6(homeDir, ...CLAUDE_CREDENTIALS_SEGMENTS);
4743
+ const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join7(homeDir, requestedPath.slice(2)) : requestedPath;
4744
+ return expanded === join7(homeDir, ...CLAUDE_CREDENTIALS_SEGMENTS);
3863
4745
  }
3864
4746
  function isOpenCodeAuthPath(requestedPath, homeDir) {
3865
- const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join6(homeDir, requestedPath.slice(2)) : requestedPath;
3866
- return expanded === join6(homeDir, ...OPENCODE_AUTH_SEGMENTS);
4747
+ const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join7(homeDir, requestedPath.slice(2)) : requestedPath;
4748
+ return expanded === join7(homeDir, ...OPENCODE_AUTH_SEGMENTS);
3867
4749
  }
3868
4750
  async function applyOne(options, file) {
3869
4751
  const label = `${file.id.slice(0, 8)} (${file.path})`;
@@ -4390,6 +5272,7 @@ var ChannelDriver = class _ChannelDriver {
4390
5272
  * and stops opencode.
4391
5273
  */
4392
5274
  stopped = false;
5275
+ recycleRequestedFlag = false;
4393
5276
  constructor(config) {
4394
5277
  this.agentId = config.agentId;
4395
5278
  this.port = config.port;
@@ -4409,7 +5292,7 @@ var ChannelDriver = class _ChannelDriver {
4409
5292
  this.stuckQueuedMs = config.stuckQueuedMs ?? DEFAULT_STUCK_QUEUED_MS;
4410
5293
  this.now = config.now ?? (() => Date.now());
4411
5294
  this.fileSyncDirectories = config.fileSyncDirectories ?? [];
4412
- this.homeDir = config.homeDir ?? homedir3();
5295
+ this.homeDir = config.homeDir ?? homedir4();
4413
5296
  this.maxActiveSessions = config.maxActiveSessions;
4414
5297
  this.watcherStallMs = config.watcherStallMs ?? WATCHER_STALL_MS;
4415
5298
  this.wedgeWarningIntervalMs = config.wedgeWarningIntervalMs ?? WEDGE_WARNING_INTERVAL_MS;
@@ -4495,6 +5378,9 @@ var ChannelDriver = class _ChannelDriver {
4495
5378
  let dispatched = 0;
4496
5379
  try {
4497
5380
  const conversations = await this.getPendingConversations();
5381
+ if (this.recycleRequestedFlag) {
5382
+ this.stop();
5383
+ }
4498
5384
  if (conversations.length > 0) {
4499
5385
  const total = conversations.reduce((sum, c) => sum + (c.pending_message_count ?? 0), 0);
4500
5386
  this.log({
@@ -4623,6 +5509,14 @@ var ChannelDriver = class _ChannelDriver {
4623
5509
  stop() {
4624
5510
  this.stopped = true;
4625
5511
  }
5512
+ /**
5513
+ * The server clears this request when a new MicroVM identity is recorded, so a
5514
+ * same-VM tunnel reconnect does not consume it. This is a plain read rather
5515
+ * than a consume; `run.ts` guards the action once-only.
5516
+ */
5517
+ get recycleRequested() {
5518
+ return this.recycleRequestedFlag;
5519
+ }
4626
5520
  /**
4627
5521
  * Wait (up to `timeoutMs`) for in-flight watcher work to settle during a
4628
5522
  * graceful shutdown, so a turn whose reply is ready — or completes within the
@@ -4760,7 +5654,7 @@ var ChannelDriver = class _ChannelDriver {
4760
5654
  this.signalDispatchNotStarted(conv, message, "session_existence_unknown");
4761
5655
  break;
4762
5656
  }
4763
- const errorMessage = err instanceof Error ? err.message : String(err);
5657
+ const errorMessage2 = err instanceof Error ? err.message : String(err);
4764
5658
  this.sessions.delete(conv.id);
4765
5659
  this.supersede(conv.id, sessionId);
4766
5660
  this.log({
@@ -4769,7 +5663,7 @@ var ChannelDriver = class _ChannelDriver {
4769
5663
  conversation_id: conv.id,
4770
5664
  message_id: message.id
4771
5665
  });
4772
- await this.markFailed(conv.id, message.id, null, errorMessage).catch((markErr) => {
5666
+ await this.markFailed(conv.id, message.id, null, errorMessage2).catch((markErr) => {
4773
5667
  this.log({
4774
5668
  level: "warn",
4775
5669
  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)}`,
@@ -4780,7 +5674,7 @@ var ChannelDriver = class _ChannelDriver {
4780
5674
  });
4781
5675
  this.log({
4782
5676
  level: "error",
4783
- message: `Message ${message.id.slice(0, 8)} dispatch failed: ${errorMessage}`,
5677
+ message: `Message ${message.id.slice(0, 8)} dispatch failed: ${errorMessage2}`,
4784
5678
  conversation_id: conv.id,
4785
5679
  message_id: message.id
4786
5680
  });
@@ -4801,14 +5695,14 @@ var ChannelDriver = class _ChannelDriver {
4801
5695
  this.unconfirmedDispatchFailures.delete(message.id);
4802
5696
  this.sessions.delete(conv.id);
4803
5697
  this.supersede(conv.id, sessionId);
4804
- 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.`;
5698
+ const errorMessage2 = `OpenCode accepted this message ${streak} times in a row but never confirmed its assigned id (session ${sessionId.slice(0, 8)}'s message list could not be read back) \u2014 the session was abandoned; a fresh one is used for further messages.`;
4805
5699
  this.log({
4806
5700
  level: "error",
4807
- message: errorMessage,
5701
+ message: errorMessage2,
4808
5702
  conversation_id: conv.id,
4809
5703
  message_id: message.id
4810
5704
  });
4811
- await this.markFailed(conv.id, message.id, null, errorMessage).catch((markErr) => {
5705
+ await this.markFailed(conv.id, message.id, null, errorMessage2).catch((markErr) => {
4812
5706
  this.log({
4813
5707
  level: "warn",
4814
5708
  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)}`,
@@ -5676,6 +6570,7 @@ var ChannelDriver = class _ChannelDriver {
5676
6570
  deliveryDeadlineAnchored: false,
5677
6571
  b2PinnedSinceMs: 0,
5678
6572
  b2LastDescendantCheckMs: 0,
6573
+ b2RootOngoingHeldLogged: false,
5679
6574
  b2AbandonedSignalled: false,
5680
6575
  ambiguousPinnedSinceMs: 0,
5681
6576
  ambiguousResolved: false
@@ -5770,6 +6665,7 @@ var ChannelDriver = class _ChannelDriver {
5770
6665
  deliveryDeadlineAnchored: false,
5771
6666
  b2PinnedSinceMs: 0,
5772
6667
  b2LastDescendantCheckMs: 0,
6668
+ b2RootOngoingHeldLogged: false,
5773
6669
  b2AbandonedSignalled: false,
5774
6670
  ambiguousPinnedSinceMs: 0,
5775
6671
  ambiguousResolved: false
@@ -6123,6 +7019,7 @@ var ChannelDriver = class _ChannelDriver {
6123
7019
  if (snapshotReadable) {
6124
7020
  inFlight.b2PinnedSinceMs = 0;
6125
7021
  inFlight.b2LastDescendantCheckMs = 0;
7022
+ inFlight.b2RootOngoingHeldLogged = false;
6126
7023
  inFlight.b2AbandonedSignalled = false;
6127
7024
  }
6128
7025
  } else {
@@ -6134,11 +7031,15 @@ var ChannelDriver = class _ChannelDriver {
6134
7031
  const pinnedForMs = this.now() - inFlight.b2PinnedSinceMs;
6135
7032
  if (pinnedForMs >= B2_ABANDONMENT_MIN_PINNED_MS && this.now() - inFlight.b2LastDescendantCheckMs >= B2_ABANDONMENT_RECHECK_MS) {
6136
7033
  inFlight.b2LastDescendantCheckMs = this.now();
6137
- const descendantOngoing = await this.isAnyDescendantSessionOngoing(sessionId);
7034
+ const [descendantOngoing, rootOngoing] = await Promise.all([
7035
+ this.isAnyDescendantSessionOngoing(sessionId),
7036
+ isSessionOngoing(this.port, sessionId)
7037
+ ]);
6138
7038
  if (isB2AbandonmentConfirmed({
6139
7039
  pinnedForMs,
6140
7040
  minPinnedMs: B2_ABANDONMENT_MIN_PINNED_MS,
6141
- descendantOngoing
7041
+ descendantOngoing,
7042
+ rootOngoing
6142
7043
  })) {
6143
7044
  inFlight.b2AbandonedSignalled = true;
6144
7045
  this.log({
@@ -6147,12 +7048,26 @@ var ChannelDriver = class _ChannelDriver {
6147
7048
  conversation_id: conv.id,
6148
7049
  message_id: id
6149
7050
  });
7051
+ const reply = findLastAssistantReplyFor(messages, inFlight.opencodeMessageId);
6150
7052
  void this.postSignal(conv.id, id, "b2_abandoned_resolved", {
6151
- watched_for_ms: pinnedForMs
7053
+ watched_for_ms: pinnedForMs,
7054
+ finish: reply?.info?.finish ?? reply?.finish,
7055
+ ...rootOngoing != null ? { root_ongoing: rootOngoing } : {},
7056
+ ...descendantOngoing != null ? { descendant_ongoing: descendantOngoing } : {},
7057
+ opencode_message_id: inFlight.opencodeMessageId
6152
7058
  });
6153
7059
  await this.settleMessageDone(sessionId, watcher, inFlight, messages);
6154
7060
  return;
6155
7061
  }
7062
+ if (rootOngoing === true && !inFlight.b2RootOngoingHeldLogged) {
7063
+ inFlight.b2RootOngoingHeldLogged = true;
7064
+ this.log({
7065
+ level: "warn",
7066
+ message: `Message ${id.slice(0, 8)} b2-pinned for ${Math.round(pinnedForMs / 1e3)}s with root_ongoing=${rootOngoing} and descendant_ongoing=${descendantOngoing} \u2014 holding until OpenCode confirms the root is idle`,
7067
+ conversation_id: conv.id,
7068
+ message_id: id
7069
+ });
7070
+ }
6156
7071
  }
6157
7072
  }
6158
7073
  const ambiguousPinnedNow = activelyRunning && isAmbiguousFinishPinnedRunning(messages, inFlight.opencodeMessageId);
@@ -6751,14 +7666,14 @@ var ChannelDriver = class _ChannelDriver {
6751
7666
  this.unconfirmedDispatchFailures.delete(row.id);
6752
7667
  this.sessions.delete(readoptConv.id);
6753
7668
  this.supersede(readoptConv.id, sessionId);
6754
- 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.`;
7669
+ const errorMessage2 = `OpenCode accepted this re-dispatched message ${streak} times in a row but never confirmed its assigned id (session ${sessionId.slice(0, 8)}'s message list could not be read back) \u2014 the session was abandoned; a fresh one is used for further messages.`;
6755
7670
  this.log({
6756
7671
  level: "error",
6757
- message: errorMessage,
7672
+ message: errorMessage2,
6758
7673
  conversation_id: row.conversation_id,
6759
7674
  message_id: row.id
6760
7675
  });
6761
- await this.markFailed(row.conversation_id, row.id, null, errorMessage).catch((markErr) => {
7676
+ await this.markFailed(row.conversation_id, row.id, null, errorMessage2).catch((markErr) => {
6762
7677
  this.log({
6763
7678
  level: "warn",
6764
7679
  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)}`,
@@ -7373,6 +8288,7 @@ var ChannelDriver = class _ChannelDriver {
7373
8288
  throw new Error(`Failed to get pending conversations: HTTP ${res.status}`);
7374
8289
  }
7375
8290
  const data = await res.json();
8291
+ this.recycleRequestedFlag = data.recycle_requested === true;
7376
8292
  let conversations = data.conversations;
7377
8293
  if (this.conversationFilter) {
7378
8294
  conversations = conversations.filter((c) => c.id === this.conversationFilter);
@@ -7797,96 +8713,641 @@ async function ensureOpenCodeRunning(ctx) {
7797
8713
  blank();
7798
8714
  throw new Error(`OpenCode not running on port ${ctx.port}`);
7799
8715
  }
7800
- if (!isOpenCodeInstalled()) {
7801
- if (!ctx.interactive) {
7802
- throw new Error("OpenCode is not installed. Install it with: npm install -g opencode-ai");
7803
- }
7804
- const result = await promptOpenCodeInstall(true);
7805
- if (result === "exit") process.exit(0);
7806
- if (result !== "installed" && !isOpenCodeInstalled()) {
7807
- throw new Error("OpenCode is not installed");
7808
- }
8716
+ if (!isOpenCodeInstalled()) {
8717
+ if (!ctx.interactive) {
8718
+ throw new Error("OpenCode is not installed. Install it with: npm install -g opencode-ai");
8719
+ }
8720
+ const result = await promptOpenCodeInstall(true);
8721
+ if (result === "exit") process.exit(0);
8722
+ if (result !== "installed" && !isOpenCodeInstalled()) {
8723
+ throw new Error("OpenCode is not installed");
8724
+ }
8725
+ }
8726
+ if (!ctx.interactive) {
8727
+ ctx.log(`OpenCode is not running on port ${ctx.port}. Starting it automatically...`);
8728
+ const proc = await startOpenCode(ctx.port, { inheritStdio: ctx.inheritStdio });
8729
+ const health = await waitForOpenCodeHealth(ctx.port, ctx.startTimeoutMs);
8730
+ if (!health.healthy) {
8731
+ return {
8732
+ port: ctx.port,
8733
+ process: proc,
8734
+ version: null,
8735
+ notReadyReason: `it did not become healthy within ${Math.round(ctx.startTimeoutMs / 1e3)}s`
8736
+ };
8737
+ }
8738
+ ctx.log(`OpenCode started on port ${ctx.port}${health.version ? ` (v${health.version})` : ""}`);
8739
+ return {
8740
+ port: ctx.port,
8741
+ process: proc,
8742
+ version: health.version ?? null,
8743
+ notReadyReason: null
8744
+ };
8745
+ }
8746
+ let port = ctx.port;
8747
+ if (isPortInUse(port)) {
8748
+ console.log(chalk5.yellow(`
8749
+ Port ${port} is already in use.`));
8750
+ const alternativePort = findAvailablePort(port + 1);
8751
+ if (alternativePort) {
8752
+ const useAlternative = await select2({
8753
+ message: `Use port ${alternativePort} instead?`,
8754
+ choices: [
8755
+ { name: `Yes, use port ${alternativePort}`, value: "yes" },
8756
+ { name: "No, I will free the port manually", value: "no" }
8757
+ ]
8758
+ });
8759
+ if (useAlternative === "yes") {
8760
+ port = alternativePort;
8761
+ } else {
8762
+ throw new Error(`Port ${ctx.port} is in use`);
8763
+ }
8764
+ }
8765
+ }
8766
+ const action = await select2({
8767
+ message: "OpenCode is not running. What would you like to do?",
8768
+ choices: [
8769
+ {
8770
+ name: "Start OpenCode for me",
8771
+ value: "start",
8772
+ description: `Run 'opencode serve --port ${port}'`
8773
+ },
8774
+ {
8775
+ name: "Show me the command",
8776
+ value: "manual",
8777
+ description: "Display the command to run manually"
8778
+ },
8779
+ {
8780
+ name: "Continue without OpenCode",
8781
+ value: "continue",
8782
+ description: "Requests will fail until OpenCode starts"
8783
+ }
8784
+ ]
8785
+ });
8786
+ if (action === "manual") {
8787
+ blank();
8788
+ console.log(chalk5.bold("Run this command in another terminal:"));
8789
+ blank();
8790
+ console.log(` ${chalk5.cyan(`opencode serve --port ${port}`)}`);
8791
+ blank();
8792
+ throw new Error("Please start OpenCode manually");
8793
+ }
8794
+ if (action === "start") {
8795
+ const spinner = ora2("Starting OpenCode...").start();
8796
+ const proc = await startOpenCode(port, { inheritStdio: ctx.inheritStdio });
8797
+ const health = await waitForOpenCodeHealth(port, INTERACTIVE_START_TIMEOUT_MS);
8798
+ if (!health.healthy) {
8799
+ spinner.fail("Failed to start OpenCode");
8800
+ throw new Error("OpenCode failed to start");
8801
+ }
8802
+ spinner.stop();
8803
+ return { port, process: proc, version: health.version ?? null, notReadyReason: null };
8804
+ }
8805
+ return { port, process: null, version: null, notReadyReason: "you chose to continue without it" };
8806
+ }
8807
+
8808
+ // src/lib/runner-credentials.ts
8809
+ import { chmodSync as chmodSync2, writeFileSync as writeFileSync4 } from "fs";
8810
+ import { spawn as spawn5 } from "child_process";
8811
+ var RUNNER_SECRET_FETCH_TIMEOUT_MS = 6e4;
8812
+ var CREDENTIAL_RESTORE_TIMEOUT_MS = 6e4;
8813
+ var GITHUB_PROBE_TIMEOUT_MS = 1e4;
8814
+ var GIT_CONFIG_GLOBAL = "/tmp/gitconfig";
8815
+ var GIT_CREDENTIAL_HELPER = "/tmp/git-credential-helper.sh";
8816
+ function commandError2(result) {
8817
+ return result.stderr.trim() || `process exited with code ${result.code ?? "null"}`;
8818
+ }
8819
+ var runCommand2 = (command, args, opts) => {
8820
+ return new Promise((resolve4) => {
8821
+ let child;
8822
+ let stdout = "";
8823
+ let stderr = "";
8824
+ let settled = false;
8825
+ const timer = {};
8826
+ const finish = (result) => {
8827
+ if (settled) return;
8828
+ settled = true;
8829
+ if (timer.handle) clearTimeout(timer.handle);
8830
+ resolve4(result);
8831
+ };
8832
+ try {
8833
+ child = spawn5(command, args, { env: opts.env, stdio: ["ignore", "pipe", "pipe"] });
8834
+ } catch (error2) {
8835
+ finish({
8836
+ code: null,
8837
+ stdout,
8838
+ stderr: error2 instanceof Error ? error2.message : String(error2),
8839
+ timedOut: false
8840
+ });
8841
+ return;
8842
+ }
8843
+ child.stdout?.setEncoding("utf8");
8844
+ child.stdout?.on("data", (chunk) => {
8845
+ stdout += chunk;
8846
+ });
8847
+ child.stderr?.setEncoding("utf8");
8848
+ child.stderr?.on("data", (chunk) => {
8849
+ stderr += chunk;
8850
+ });
8851
+ child.once("error", (error2) => {
8852
+ finish({
8853
+ code: null,
8854
+ stdout,
8855
+ stderr: stderr === "" ? error2.message : `${stderr}
8856
+ ${error2.message}`,
8857
+ timedOut: false
8858
+ });
8859
+ });
8860
+ child.once("close", (code) => finish({ code, stdout, stderr, timedOut: false }));
8861
+ timer.handle = setTimeout(
8862
+ () => {
8863
+ child.kill("SIGKILL");
8864
+ finish({ code: null, stdout, stderr, timedOut: true });
8865
+ },
8866
+ Math.max(0, opts.timeoutMs)
8867
+ );
8868
+ });
8869
+ };
8870
+ function isEnvironmentObject(value) {
8871
+ return typeof value === "object" && value !== null && !Array.isArray(value);
8872
+ }
8873
+ function secretFailure(marker, detail, log3) {
8874
+ const message = `${marker}: ${detail}`;
8875
+ log3(message, "error");
8876
+ return new Error(message);
8877
+ }
8878
+ async function installRunnerSecret({
8879
+ env,
8880
+ log: log3,
8881
+ commandRunner
8882
+ }) {
8883
+ const arn = env.RUNNER_SECRET_ARN?.trim();
8884
+ if (!arn) {
8885
+ log3("runner secret is not configured; continuing without GitHub and MCP credentials");
8886
+ return false;
8887
+ }
8888
+ const result = await (commandRunner ?? runCommand2)(
8889
+ "aws",
8890
+ [
8891
+ "secretsmanager",
8892
+ "get-secret-value",
8893
+ "--secret-id",
8894
+ arn,
8895
+ "--query",
8896
+ "SecretString",
8897
+ "--output",
8898
+ "text"
8899
+ ],
8900
+ { env, timeoutMs: RUNNER_SECRET_FETCH_TIMEOUT_MS }
8901
+ );
8902
+ if (result.timedOut) {
8903
+ throw secretFailure(
8904
+ "CREDENTIAL-RESTORE-TIMEOUT",
8905
+ `runner-secret did not finish within ${RUNNER_SECRET_FETCH_TIMEOUT_MS}ms`,
8906
+ log3
8907
+ );
8908
+ }
8909
+ if (result.code !== 0) {
8910
+ throw secretFailure("RUNNER-SECRET-UNREADABLE", commandError2(result), log3);
8911
+ }
8912
+ let payload;
8913
+ try {
8914
+ payload = JSON.parse(result.stdout);
8915
+ } catch (error2) {
8916
+ log3(
8917
+ `RUNNER-SECRET-UNPARSEABLE: secret value is not a JSON object (${error2 instanceof Error ? error2.message : String(error2)})`,
8918
+ "warn"
8919
+ );
8920
+ return false;
8921
+ }
8922
+ if (!isEnvironmentObject(payload)) {
8923
+ log3("RUNNER-SECRET-UNPARSEABLE: secret value is not a JSON object", "warn");
8924
+ return false;
8925
+ }
8926
+ let populated = 0;
8927
+ let skipped = 0;
8928
+ let githubTokenPopulated = false;
8929
+ for (const [key, value] of Object.entries(payload)) {
8930
+ if (typeof value !== "string" || value.length === 0) continue;
8931
+ if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key)) {
8932
+ log3(
8933
+ `RUNNER-SECRET-KEY-SKIPPED: ${JSON.stringify(key)} is not a valid environment variable name`,
8934
+ "warn"
8935
+ );
8936
+ skipped += 1;
8937
+ continue;
8938
+ }
8939
+ env[key] = value;
8940
+ populated += 1;
8941
+ if (key === "GH_TOKEN") githubTokenPopulated = true;
8942
+ }
8943
+ if (populated === 0) {
8944
+ log3(
8945
+ "RUNNER-SECRET-UNPOPULATED: populate the runner secret as documented in infrastructure/evident-runner/MICROVM.md",
8946
+ "warn"
8947
+ );
8948
+ } else {
8949
+ log3(
8950
+ `RUNNER-SECRET-OK: exported ${populated} secret values; skipped ${skipped} invalid environment variable names`
8951
+ );
8952
+ }
8953
+ return githubTokenPopulated;
8954
+ }
8955
+ function restoreFailure(operation, result, log3) {
8956
+ const message = `CREDENTIAL-RESTORE-FAILED: ${operation} failed: ${commandError2(result)}`;
8957
+ log3(message, "error");
8958
+ return new Error(message);
8959
+ }
8960
+ async function runCredentialRestore(args, operation, log3, synchroniserRunner) {
8961
+ const result = await synchroniserRunner(args, { timeoutMs: CREDENTIAL_RESTORE_TIMEOUT_MS });
8962
+ if (result.timedOut) {
8963
+ log3(
8964
+ `CREDENTIAL-RESTORE-TIMEOUT: ${operation} did not finish within ${CREDENTIAL_RESTORE_TIMEOUT_MS}ms; continuing without it`,
8965
+ "warn"
8966
+ );
8967
+ return result;
8968
+ }
8969
+ if (result.code !== 0) throw restoreFailure(operation, result, log3);
8970
+ return result;
8971
+ }
8972
+ async function restoreCredentialStores({
8973
+ env,
8974
+ log: log3,
8975
+ synchroniserRunner = runSynchroniser
8976
+ }) {
8977
+ await runCredentialRestore(["restore", "claude"], "restore-claude", log3, synchroniserRunner);
8978
+ await runCredentialRestore(["restore", "opencode"], "restore-opencode", log3, synchroniserRunner);
8979
+ const result = await synchroniserRunner(["model-auth-ready"], {
8980
+ timeoutMs: CREDENTIAL_RESTORE_TIMEOUT_MS
8981
+ });
8982
+ if (result.timedOut) {
8983
+ log3(
8984
+ `CREDENTIAL-RESTORE-TIMEOUT: model-auth-ready did not finish within ${CREDENTIAL_RESTORE_TIMEOUT_MS}ms; continuing without it`,
8985
+ "warn"
8986
+ );
8987
+ return;
8988
+ }
8989
+ switch (result.code) {
8990
+ case 0:
8991
+ return;
8992
+ case 10:
8993
+ log3(
8994
+ `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.`,
8995
+ "warn"
8996
+ );
8997
+ return;
8998
+ default:
8999
+ log3("could not determine whether this VM has model credentials", "warn");
9000
+ }
9001
+ }
9002
+ var GIT_CREDENTIAL_HELPER_CONTENT = [
9003
+ "#!/usr/bin/env bash",
9004
+ '[ "$1" = get ] || exit 0',
9005
+ "echo username=x-access-token",
9006
+ 'echo "password=${GH_TOKEN}"',
9007
+ ""
9008
+ ].join("\n");
9009
+ async function probeGitHubAccess({ env, log: log3 }) {
9010
+ const auth = await runCommand2("gh", ["api", "user", "--jq", ".login"], {
9011
+ env,
9012
+ timeoutMs: GITHUB_PROBE_TIMEOUT_MS
9013
+ });
9014
+ if (auth.timedOut) {
9015
+ log3(`GITHUB-PROBE-TIMEOUT: auth probe exceeded ${GITHUB_PROBE_TIMEOUT_MS}ms`, "warn");
9016
+ return;
9017
+ }
9018
+ if (auth.code !== 0) {
9019
+ log3(`GITHUB-AUTH-REJECTED: ${commandError2(auth)}`, "warn");
9020
+ return;
9021
+ }
9022
+ log3(`GITHUB-AUTH-OK: ${auth.stdout.trim()}`, "debug");
9023
+ const remote = await runCommand2("git", ["-C", process.cwd(), "remote", "get-url", "origin"], {
9024
+ env,
9025
+ timeoutMs: GITHUB_PROBE_TIMEOUT_MS
9026
+ });
9027
+ if (remote.code !== 0 || remote.timedOut) return;
9028
+ const repo = remote.stdout.trim().replace(/^(?:https:\/\/github\.com\/|git@github\.com:)/, "").replace(/\.git$/, "");
9029
+ if (!repo) return;
9030
+ const repository = await runCommand2("gh", ["api", `repos/${repo}`, "--jq", ".full_name"], {
9031
+ env,
9032
+ timeoutMs: GITHUB_PROBE_TIMEOUT_MS
9033
+ });
9034
+ if (repository.timedOut) {
9035
+ log3(
9036
+ `GITHUB-PROBE-TIMEOUT: repository probe for ${repo} exceeded ${GITHUB_PROBE_TIMEOUT_MS}ms`,
9037
+ "warn"
9038
+ );
9039
+ } else if (repository.code !== 0) {
9040
+ log3(`GITHUB-REPO-INACCESSIBLE: ${repo}: ${commandError2(repository)}`, "warn");
9041
+ }
9042
+ }
9043
+ async function configureGitHubAccess({ env, log: log3 }) {
9044
+ if (!env.GH_TOKEN) {
9045
+ log3("GITHUB-CREDENTIALS-MISSING: GH_TOKEN is unavailable; see RUNNER-SECRET-* above", "warn");
9046
+ return;
9047
+ }
9048
+ try {
9049
+ env.GIT_CONFIG_GLOBAL = GIT_CONFIG_GLOBAL;
9050
+ writeFileSync4(GIT_CONFIG_GLOBAL, "");
9051
+ writeFileSync4(GIT_CREDENTIAL_HELPER, GIT_CREDENTIAL_HELPER_CONTENT, { mode: 448 });
9052
+ chmodSync2(GIT_CREDENTIAL_HELPER, 448);
9053
+ const config = [
9054
+ ["user.name", env.GIT_USER_NAME ?? "evident-bot"],
9055
+ ["user.email", env.GIT_USER_EMAIL ?? "evident-bot@users.noreply.github.com"],
9056
+ ["init.defaultBranch", "main"],
9057
+ ["credential.https://github.com.helper", GIT_CREDENTIAL_HELPER]
9058
+ ];
9059
+ for (const [key, value] of config) {
9060
+ const result = await runCommand2("git", ["config", "--global", key, value], {
9061
+ env,
9062
+ timeoutMs: GITHUB_PROBE_TIMEOUT_MS
9063
+ });
9064
+ if (result.timedOut || result.code !== 0) throw new Error(commandError2(result));
9065
+ }
9066
+ } catch (error2) {
9067
+ log3(
9068
+ `GITHUB-SETUP-FAILED: could not configure local git credentials; continuing without GitHub access (${error2 instanceof Error ? error2.message : String(error2)})`,
9069
+ "warn"
9070
+ );
9071
+ return;
9072
+ }
9073
+ void probeGitHubAccess({ env, log: log3 }).catch((error2) => {
9074
+ log3(
9075
+ `GITHUB-SETUP-FAILED: GitHub access probe failed: ${error2 instanceof Error ? error2.message : String(error2)}`,
9076
+ "warn"
9077
+ );
9078
+ });
9079
+ }
9080
+
9081
+ // src/lib/opencode/config-overlay.ts
9082
+ import { execFileSync as execFileSync2 } from "child_process";
9083
+ import { copyFileSync, existsSync as existsSync2, statSync as statSync5 } from "fs";
9084
+ import { isAbsolute as isAbsolute2, join as join8, resolve as resolve3 } from "path";
9085
+ function isFile(filePath) {
9086
+ return existsSync2(filePath) && statSync5(filePath).isFile();
9087
+ }
9088
+ function applyRunnerOpenCodeConfig({
9089
+ overlayPath,
9090
+ cwd = process.cwd(),
9091
+ log: log3
9092
+ }) {
9093
+ if (!overlayPath) {
9094
+ log3("runner OpenCode config is not configured; using the baked project config", "debug");
9095
+ return;
9096
+ }
9097
+ const source = isAbsolute2(overlayPath) ? overlayPath : resolve3(cwd, overlayPath);
9098
+ const target = isFile(join8(cwd, "opencode.jsonc")) ? "opencode.jsonc" : "opencode.json";
9099
+ if (!isFile(source)) {
9100
+ log3(
9101
+ `RUNNER-OPENCODE-CONFIG-MISSING: ${source} is not a file; headless turns will wedge on the first external-directory permission prompt (#563)`,
9102
+ "error"
9103
+ );
9104
+ return;
9105
+ }
9106
+ copyFileSync(source, join8(cwd, target));
9107
+ try {
9108
+ execFileSync2("git", ["-C", cwd, "update-index", "--skip-worktree", target], {
9109
+ stdio: "ignore"
9110
+ });
9111
+ } catch (error2) {
9112
+ const detail = error2 instanceof Error ? error2.message : String(error2);
9113
+ log3(`could not mark ${target} skip-worktree: ${detail}; it may show as a local change`, "warn");
9114
+ }
9115
+ log3(`Applied runner OpenCode config ${source} to ${join8(cwd, target)}`);
9116
+ }
9117
+
9118
+ // src/lib/credential-sync.ts
9119
+ import { renameSync, writeFileSync as writeFileSync5 } from "fs";
9120
+ var CREDENTIAL_SYNC_TICK_TIMEOUT_MS = 3e4;
9121
+ var CREDENTIAL_FLUSH_DEADLINE_MS = 8e3;
9122
+ var CREDENTIAL_FLUSH_ABORT_GRACE_MS = 500;
9123
+ var DEFAULT_CREDENTIAL_SYNC_INTERVAL_SECONDS = 60;
9124
+ var STORES = ["claude", "opencode"];
9125
+ var MAX_FLUSH_PASSES = 2;
9126
+ function outcomesWith(outcome) {
9127
+ return { claude: outcome, opencode: outcome };
9128
+ }
9129
+ function errorMessage(error2) {
9130
+ return error2 instanceof Error ? error2.message : String(error2);
9131
+ }
9132
+ function waitForSettlement(promise, timeoutMs) {
9133
+ return new Promise((resolve4) => {
9134
+ let settled = false;
9135
+ const timer = setTimeout(() => finish(false), Math.max(0, timeoutMs));
9136
+ const finish = (value) => {
9137
+ if (settled) return;
9138
+ settled = true;
9139
+ clearTimeout(timer);
9140
+ resolve4(value);
9141
+ };
9142
+ promise.then(
9143
+ () => finish(true),
9144
+ () => finish(true)
9145
+ );
9146
+ });
9147
+ }
9148
+ function writeMarker(markerPath, outcomes, log3) {
9149
+ const body = `${STORES.map((store) => `${store}=${outcomes[store]}`).join("\n")}
9150
+ `;
9151
+ const temporaryPath = `${markerPath}.tmp`;
9152
+ try {
9153
+ writeFileSync5(temporaryPath, body, { mode: 384 });
9154
+ renameSync(temporaryPath, markerPath);
9155
+ } catch (error2) {
9156
+ log3(`CREDENTIAL-FLUSH-MARKER-UNWRITABLE: ${markerPath}: ${errorMessage(error2)}`, "warn");
9157
+ }
9158
+ }
9159
+ function intervalSeconds(env, log3) {
9160
+ const raw = env.CREDS_SYNC_INTERVAL;
9161
+ if (raw === void 0 || /^[1-9][0-9]*$/.test(raw) && Number.isSafeInteger(Number(raw))) {
9162
+ return raw === void 0 ? DEFAULT_CREDENTIAL_SYNC_INTERVAL_SECONDS : Number(raw);
7809
9163
  }
7810
- if (!ctx.interactive) {
7811
- ctx.log(`OpenCode is not running on port ${ctx.port}. Starting it automatically...`);
7812
- const proc = await startOpenCode(ctx.port);
7813
- const health = await waitForOpenCodeHealth(ctx.port, ctx.startTimeoutMs);
7814
- if (!health.healthy) {
7815
- return {
7816
- port: ctx.port,
7817
- process: proc,
7818
- version: null,
7819
- notReadyReason: `it did not become healthy within ${Math.round(ctx.startTimeoutMs / 1e3)}s`
9164
+ log3(
9165
+ `CREDENTIAL-SYNC-INTERVAL-INVALID: CREDS_SYNC_INTERVAL='${raw}' is not a positive integer; using ${DEFAULT_CREDENTIAL_SYNC_INTERVAL_SECONDS}s`,
9166
+ "warn"
9167
+ );
9168
+ return DEFAULT_CREDENTIAL_SYNC_INTERVAL_SECONDS;
9169
+ }
9170
+ async function runFlushStore(store, env, synchroniserRunner, log3, deadlineAt) {
9171
+ const remainingMs = deadlineAt - Date.now();
9172
+ if (remainingMs <= 0) return { outcome: "timeout", orphaned: false };
9173
+ const controller = new AbortController();
9174
+ let result;
9175
+ let failed = false;
9176
+ const completion = Promise.resolve().then(
9177
+ () => synchroniserRunner(["sync-once", store], {
9178
+ timeoutMs: remainingMs,
9179
+ env,
9180
+ signal: controller.signal
9181
+ })
9182
+ ).then(
9183
+ (value) => {
9184
+ result = value;
9185
+ },
9186
+ (error2) => {
9187
+ failed = true;
9188
+ log3(`CREDENTIAL-FLUSH-ERROR: ${store}: ${errorMessage(error2)}`, "warn");
9189
+ }
9190
+ );
9191
+ const abortTimer = setTimeout(() => controller.abort(), remainingMs);
9192
+ const settledBeforeDeadline = await waitForSettlement(completion, remainingMs);
9193
+ clearTimeout(abortTimer);
9194
+ if (!settledBeforeDeadline) {
9195
+ controller.abort();
9196
+ const settledAfterAbort = await waitForSettlement(completion, CREDENTIAL_FLUSH_ABORT_GRACE_MS);
9197
+ if (!settledAfterAbort) return { outcome: "timeout", orphaned: true };
9198
+ return { outcome: "timeout", orphaned: false };
9199
+ }
9200
+ if (failed || !result) return { outcome: "failed", orphaned: false };
9201
+ if (result.timedOut || Date.now() >= deadlineAt) {
9202
+ return { outcome: "timeout", orphaned: false };
9203
+ }
9204
+ return { outcome: result.code === 0 ? "ok" : "failed", orphaned: false };
9205
+ }
9206
+ function createCredentialSync({
9207
+ markerPath,
9208
+ env,
9209
+ log: log3,
9210
+ synchroniserRunner = runSynchroniser
9211
+ }) {
9212
+ const persistenceDisabled = !env.PERSISTENCE_BUCKET;
9213
+ let disabled = persistenceDisabled;
9214
+ let armed = false;
9215
+ let stopped = false;
9216
+ let timer;
9217
+ let inFlight;
9218
+ let activeTickAbort;
9219
+ let lastTickFailed;
9220
+ let flushPromise;
9221
+ const scheduleTick = (intervalMs, startTick2) => {
9222
+ if (stopped) return;
9223
+ timer = setTimeout(() => {
9224
+ timer = void 0;
9225
+ startTick2();
9226
+ }, intervalMs);
9227
+ };
9228
+ const startTick = (intervalMs) => {
9229
+ if (stopped) return;
9230
+ const controller = new AbortController();
9231
+ activeTickAbort = controller;
9232
+ const tick = (async () => {
9233
+ const outcomes = {
9234
+ claude: "failed",
9235
+ opencode: "failed"
7820
9236
  };
9237
+ for (const store of STORES) {
9238
+ if (controller.signal.aborted) break;
9239
+ try {
9240
+ const result = await synchroniserRunner(["sync-once", store], {
9241
+ timeoutMs: CREDENTIAL_SYNC_TICK_TIMEOUT_MS,
9242
+ env,
9243
+ signal: controller.signal
9244
+ });
9245
+ outcomes[store] = !result.timedOut && result.code === 0 ? "ok" : "failed";
9246
+ } catch (error2) {
9247
+ outcomes[store] = "failed";
9248
+ log3(`CREDENTIAL-SYNC-TICK-ERROR: ${store}: ${errorMessage(error2)}`, "debug");
9249
+ }
9250
+ }
9251
+ const failed = STORES.some((store) => outcomes[store] === "failed");
9252
+ log3(
9253
+ `CREDENTIAL-SYNC-TICK: claude=${outcomes.claude}, opencode=${outcomes.opencode}`,
9254
+ "debug"
9255
+ );
9256
+ if (failed && lastTickFailed !== true) {
9257
+ log3(
9258
+ "CREDENTIAL-SYNC-FAILED: an interval credential sync failed; retrying on the next tick",
9259
+ "warn"
9260
+ );
9261
+ } else if (!failed && lastTickFailed === true) {
9262
+ log3("CREDENTIAL-SYNC-RECOVERED: interval credential sync succeeded again", "warn");
9263
+ }
9264
+ lastTickFailed = failed;
9265
+ })().finally(() => {
9266
+ if (activeTickAbort === controller) activeTickAbort = void 0;
9267
+ if (inFlight === tick) inFlight = void 0;
9268
+ scheduleTick(intervalMs, () => startTick(intervalMs));
9269
+ });
9270
+ inFlight = tick;
9271
+ };
9272
+ const performFlush = async () => {
9273
+ stopped = true;
9274
+ if (timer) {
9275
+ clearTimeout(timer);
9276
+ timer = void 0;
9277
+ }
9278
+ const deadlineAt = Date.now() + CREDENTIAL_FLUSH_DEADLINE_MS;
9279
+ if (inFlight) {
9280
+ const settled = await waitForSettlement(inFlight, CREDENTIAL_FLUSH_DEADLINE_MS);
9281
+ if (!settled) {
9282
+ activeTickAbort?.abort();
9283
+ const settledAfterAbort = await waitForSettlement(
9284
+ inFlight,
9285
+ CREDENTIAL_FLUSH_ABORT_GRACE_MS
9286
+ );
9287
+ if (!settledAfterAbort) {
9288
+ log3(
9289
+ "CREDENTIAL-FLUSH-ORPHANED-TICK: a sync-once child could not be proven settled; skipping the boundary flush rather than becoming a second writer",
9290
+ "warn"
9291
+ );
9292
+ return { outcomes: outcomesWith("timeout"), orphaned: true };
9293
+ }
9294
+ }
7821
9295
  }
7822
- ctx.log(`OpenCode started on port ${ctx.port}${health.version ? ` (v${health.version})` : ""}`);
7823
- return {
7824
- port: ctx.port,
7825
- process: proc,
7826
- version: health.version ?? null,
7827
- notReadyReason: null
7828
- };
7829
- }
7830
- let port = ctx.port;
7831
- if (isPortInUse(port)) {
7832
- console.log(chalk5.yellow(`
7833
- Port ${port} is already in use.`));
7834
- const alternativePort = findAvailablePort(port + 1);
7835
- if (alternativePort) {
7836
- const useAlternative = await select2({
7837
- message: `Use port ${alternativePort} instead?`,
7838
- choices: [
7839
- { name: `Yes, use port ${alternativePort}`, value: "yes" },
7840
- { name: "No, I will free the port manually", value: "no" }
7841
- ]
7842
- });
7843
- if (useAlternative === "yes") {
7844
- port = alternativePort;
7845
- } else {
7846
- throw new Error(`Port ${ctx.port} is in use`);
9296
+ if (disabled) return { outcomes: outcomesWith("skipped"), orphaned: false };
9297
+ const outcomes = outcomesWith("timeout");
9298
+ for (const store of STORES) {
9299
+ const result = await runFlushStore(store, env, synchroniserRunner, log3, deadlineAt);
9300
+ if (result.orphaned) {
9301
+ log3(
9302
+ "CREDENTIAL-FLUSH-ORPHANED-CHILD: a flush sync-once child could not be proven settled; refusing another flush pass rather than becoming a second writer",
9303
+ "warn"
9304
+ );
9305
+ return { outcomes: outcomesWith("timeout"), orphaned: true };
7847
9306
  }
9307
+ outcomes[store] = result.outcome;
7848
9308
  }
7849
- }
7850
- const action = await select2({
7851
- message: "OpenCode is not running. What would you like to do?",
7852
- choices: [
7853
- {
7854
- name: "Start OpenCode for me",
7855
- value: "start",
7856
- description: `Run 'opencode serve --port ${port}'`
7857
- },
7858
- {
7859
- name: "Show me the command",
7860
- value: "manual",
7861
- description: "Display the command to run manually"
7862
- },
7863
- {
7864
- name: "Continue without OpenCode",
7865
- value: "continue",
7866
- description: "Requests will fail until OpenCode starts"
9309
+ return { outcomes, orphaned: false };
9310
+ };
9311
+ let flushPasses = 0;
9312
+ let lastFlush;
9313
+ return {
9314
+ arm() {
9315
+ if (stopped || armed) return;
9316
+ armed = true;
9317
+ if (persistenceDisabled) {
9318
+ disabled = true;
9319
+ log3(
9320
+ "CREDENTIAL-SYNC-DISABLED: LITESTREAM_BUCKET/LITESTREAM_PREFIX are not both set; no interval credential sync this boot",
9321
+ "warn"
9322
+ );
9323
+ return;
7867
9324
  }
7868
- ]
7869
- });
7870
- if (action === "manual") {
7871
- blank();
7872
- console.log(chalk5.bold("Run this command in another terminal:"));
7873
- blank();
7874
- console.log(` ${chalk5.cyan(`opencode serve --port ${port}`)}`);
7875
- blank();
7876
- throw new Error("Please start OpenCode manually");
7877
- }
7878
- if (action === "start") {
7879
- const spinner = ora2("Starting OpenCode...").start();
7880
- const proc = await startOpenCode(port);
7881
- const health = await waitForOpenCodeHealth(port, INTERACTIVE_START_TIMEOUT_MS);
7882
- if (!health.healthy) {
7883
- spinner.fail("Failed to start OpenCode");
7884
- throw new Error("OpenCode failed to start");
9325
+ disabled = false;
9326
+ const intervalMs = intervalSeconds(env, log3) * 1e3;
9327
+ scheduleTick(intervalMs, () => startTick(intervalMs));
9328
+ },
9329
+ async stopAndFlush(publish) {
9330
+ let result;
9331
+ const runningFlush = flushPromise;
9332
+ if (runningFlush) {
9333
+ result = await runningFlush;
9334
+ } else if (flushPasses >= MAX_FLUSH_PASSES || lastFlush?.orphaned) {
9335
+ result = lastFlush ?? { outcomes: outcomesWith("timeout"), orphaned: true };
9336
+ } else {
9337
+ flushPasses++;
9338
+ const currentFlush = performFlush();
9339
+ flushPromise = currentFlush;
9340
+ try {
9341
+ result = await currentFlush;
9342
+ lastFlush = result;
9343
+ } finally {
9344
+ if (flushPromise === currentFlush) flushPromise = void 0;
9345
+ }
9346
+ }
9347
+ if (publish) writeMarker(markerPath, result.outcomes, log3);
9348
+ return result.outcomes;
7885
9349
  }
7886
- spinner.stop();
7887
- return { port, process: proc, version: health.version ?? null, notReadyReason: null };
7888
- }
7889
- return { port, process: null, version: null, notReadyReason: "you chose to continue without it" };
9350
+ };
7890
9351
  }
7891
9352
 
7892
9353
  // src/commands/run.ts
@@ -7895,6 +9356,7 @@ var CHANNEL_POLL_INTERVAL_MS = Number(process.env.EVIDENT_CHANNEL_POLL_INTERVAL_
7895
9356
  var CHANNEL_STUCK_QUEUED_MS = Number(process.env.EVIDENT_STUCK_QUEUED_MS) || void 0;
7896
9357
  var SHUTDOWN_DRAIN_TIMEOUT_MS = Number(process.env.EVIDENT_SHUTDOWN_DRAIN_MS) || 25e3;
7897
9358
  var TELEMETRY_SHUTDOWN_TIMEOUT_MS = 5e3;
9359
+ var CHILD_STOP_TIMEOUT_MS = 1e4;
7898
9360
  function resolveLogLevel(options) {
7899
9361
  const accepted = Object.keys(LOG_LEVELS);
7900
9362
  const validate = (value, source) => {
@@ -7925,11 +9387,11 @@ function resolveFileSyncDirectories(raw, homeDir) {
7925
9387
  if (trimmed === "") {
7926
9388
  throw new Error("--enable-file-sync-to requires a directory path (got an empty value)");
7927
9389
  }
7928
- const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join7(homeDir, trimmed.slice(2)) : trimmed;
7929
- if (!isAbsolute2(expanded)) {
9390
+ const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join9(homeDir, trimmed.slice(2)) : trimmed;
9391
+ if (!isAbsolute3(expanded)) {
7930
9392
  throw new Error(`--enable-file-sync-to requires an absolute directory path; got "${entry}"`);
7931
9393
  }
7932
- const normalized = resolvePath(expanded);
9394
+ const normalized = resolvePath2(expanded);
7933
9395
  if (parse(normalized).root === normalized) {
7934
9396
  throw new Error(
7935
9397
  `--enable-file-sync-to will not allow-list the filesystem root ("${entry}"); name the specific directory the credentials belong in (for example ~/.claude)`
@@ -8045,7 +9507,7 @@ function logActivity(state, entry) {
8045
9507
  }
8046
9508
  function reportSessionDbRecovery(state) {
8047
9509
  try {
8048
- const report = drainSessionDbRecoveryReport({ homeDir: homedir4(), env: process.env });
9510
+ const report = drainSessionDbRecoveryReport({ homeDir: homedir5(), env: process.env });
8049
9511
  for (const record of report.records) {
8050
9512
  const activity = buildSessionDbRecoveryActivity(record);
8051
9513
  if (!activity) throw new Error("could not map session-DB recovery record");
@@ -8063,6 +9525,16 @@ function reportSessionDbRecovery(state) {
8063
9525
  );
8064
9526
  }
8065
9527
  }
9528
+ function reportSessionDbRecoveryRecord(state, record) {
9529
+ const activity = buildSessionDbRecoveryActivity(record);
9530
+ if (!activity) throw new Error("could not map session-DB recovery record");
9531
+ logActivity(state, {
9532
+ type: activity.level === "error" ? "error" : "info",
9533
+ level: activity.level,
9534
+ ...activity.level === "error" ? { error: activity.message } : { message: activity.message },
9535
+ metadata: activity.metadata
9536
+ });
9537
+ }
8066
9538
  function displayStatus(state) {
8067
9539
  if (!state.interactive) return;
8068
9540
  const attempt = state.connection?.reconnectAttempt ?? 0;
@@ -8175,6 +9647,10 @@ async function driveChannels(state, driver) {
8175
9647
  consecutiveDrainFailures = 0;
8176
9648
  unreachableMs = 0;
8177
9649
  state.messageCount += processed;
9650
+ if (driver.recycleRequested) {
9651
+ await beginGracefulShutdown(state, "recycle");
9652
+ return;
9653
+ }
8178
9654
  const proxiedActivity = state.lastProxiedActivityAt !== lastSeenProxiedActivityAt;
8179
9655
  lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
8180
9656
  const fileActivitySnapshot = driver.fileSyncActivity();
@@ -8217,8 +9693,8 @@ async function driveChannels(state, driver) {
8217
9693
  state.running = false;
8218
9694
  break;
8219
9695
  }
8220
- const errorMessage = error2 instanceof Error ? error2.message : String(error2);
8221
- logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage}` });
9696
+ const errorMessage2 = error2 instanceof Error ? error2.message : String(error2);
9697
+ logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage2}` });
8222
9698
  if (state.interactive) displayStatus(state);
8223
9699
  if (driver.hasInFlightWatchers()) {
8224
9700
  consecutiveDrainFailures = 0;
@@ -8235,7 +9711,7 @@ async function driveChannels(state, driver) {
8235
9711
  }
8236
9712
  }
8237
9713
  }
8238
- await new Promise((resolve3) => setTimeout(resolve3, CHANNEL_POLL_INTERVAL_MS));
9714
+ await new Promise((resolve4) => setTimeout(resolve4, CHANNEL_POLL_INTERVAL_MS));
8239
9715
  const cycleMs = performance.now() - cycleStartedAtMs;
8240
9716
  if (idleThisCycle) idleMs += cycleMs;
8241
9717
  if (unreachableThisCycle) unreachableMs += cycleMs;
@@ -8258,7 +9734,43 @@ async function driveChannels(state, driver) {
8258
9734
  var SESSION_CLEANUP_FIRST_SWEEP_MS = 1e4;
8259
9735
  var SESSION_DB_RECLAIM_MAX_PAGES = 2e3;
8260
9736
  function sessionDbPath() {
8261
- return join7(homedir4(), ".local", "share", "opencode", "opencode.db");
9737
+ return join9(homedir5(), ".local", "share", "opencode", "opencode.db");
9738
+ }
9739
+ function logSessionDbProvenanceMismatch(state, provenance, currentVersion, preBootMigrationCount) {
9740
+ const record = {
9741
+ v: 1,
9742
+ event: "session_db_recovery",
9743
+ at: (/* @__PURE__ */ new Date()).toISOString(),
9744
+ stage: "verify",
9745
+ outcome: "schema_provenance_mismatch",
9746
+ severity: "error",
9747
+ reason: provenance.reason ?? "schema-provenance-mismatch",
9748
+ litestream_exit_code: null,
9749
+ attempt: null,
9750
+ replica_objects: null,
9751
+ replica_bytes: null,
9752
+ quarantine_destination: null,
9753
+ quarantined_objects: null,
9754
+ quarantine_failed_objects: null,
9755
+ quarantined_bytes: null,
9756
+ verified_restore_point: null,
9757
+ restore_points_tried: null,
9758
+ provenance_reason: provenance.reason,
9759
+ provenance_migration_delta: provenance.migrationDelta,
9760
+ replication_suspended: false,
9761
+ dbPath: sessionDbPath(),
9762
+ recorded_version: provenance.recordedVersion,
9763
+ current_version: currentVersion,
9764
+ provenance_pre_boot_migration_count: preBootMigrationCount
9765
+ };
9766
+ const activity = buildSessionDbRecoveryActivity(record);
9767
+ if (!activity) throw new Error("could not map session-DB provenance activity");
9768
+ logActivity(state, {
9769
+ type: activity.level === "error" ? "error" : "info",
9770
+ level: activity.level,
9771
+ ...activity.level === "error" ? { error: activity.message } : { message: activity.message },
9772
+ metadata: activity.metadata
9773
+ });
8262
9774
  }
8263
9775
  async function runSweep(state, driver, config) {
8264
9776
  const mode = `age=${config.maxAgeMs ?? "\u2014"} count=${config.maxCount ?? "\u2014"}`;
@@ -8305,7 +9817,7 @@ async function runSweep(state, driver, config) {
8305
9817
  const reclaimResult = await reclaimSessionDbSpace({
8306
9818
  dbPath: sessionDbPath(),
8307
9819
  maxPages: SESSION_DB_RECLAIM_MAX_PAGES,
8308
- allowFullVacuum: protectedNow.size === 0
9820
+ allowFullVacuum: protectedNow.size === 0 && !state.sessionDbProvenanceAnomaly
8309
9821
  });
8310
9822
  if (reclaimResult.ok) {
8311
9823
  const beforeMib = (reclaimResult.beforeBytes / 1024 / 1024).toFixed(1);
@@ -8341,7 +9853,7 @@ function scheduleSessionCleanup(state, driver, options) {
8341
9853
  for (const warning2 of config.warnings) {
8342
9854
  logActivity(state, { type: "info", level: "warn", message: `Session cleanup: ${warning2}` });
8343
9855
  }
8344
- const dbBytes = statSessionDbBytes(homedir4());
9856
+ const dbBytes = statSessionDbBytes(homedir5());
8345
9857
  void (async () => {
8346
9858
  const reclaimSkipReason = dbBytes !== null && config.enabled ? await probeReclaimAvailability({ dbPath: sessionDbPath(), requiredBytes: dbBytes }) : null;
8347
9859
  const sizeWarning = buildSessionStoreSizeWarning({
@@ -8500,7 +10012,17 @@ function scheduleClaudeUsageReporting(state, options) {
8500
10012
  setTimer: (timer) => {
8501
10013
  state.claudeUsageTimer = timer;
8502
10014
  },
8503
- fetchUsage: getClaudeUsage,
10015
+ fetchUsage: async () => {
10016
+ const usage = await getClaudeUsage();
10017
+ if (usage.ownerLookupError) {
10018
+ logActivity(state, {
10019
+ type: "info",
10020
+ level: "debug",
10021
+ message: `Claude usage owner lookup failed: ${usage.ownerLookupError}`
10022
+ });
10023
+ }
10024
+ return usage;
10025
+ },
8504
10026
  report: (usage) => reportClaudeUsage(state.agentId, state.authHeader, usage),
8505
10027
  isLocalCredentialProblem,
8506
10028
  forcedOnHint: "run `claude` to sign in",
@@ -8532,7 +10054,7 @@ function scheduleResourceUsageReporting(state, options) {
8532
10054
  });
8533
10055
  return;
8534
10056
  }
8535
- const collect = createResourceUsageCollector(homedir4());
10057
+ const collect = createResourceUsageCollector(homedir5());
8536
10058
  let consecutiveFailures = 0;
8537
10059
  const tick = async () => {
8538
10060
  try {
@@ -8642,21 +10164,39 @@ async function cleanup(state, opts = {}) {
8642
10164
  clearTimeout(state.resourceUsageTimer);
8643
10165
  state.resourceUsageTimer = null;
8644
10166
  }
10167
+ const credentialSync = state.credentialSync;
10168
+ const flushCredentials = credentialSync ? async (phase, publish) => {
10169
+ await timeShutdownPhase(state, durations, phase, async () => {
10170
+ const outcomes = await credentialSync.stopAndFlush(publish);
10171
+ const level = Object.values(outcomes).every((outcome) => outcome === "ok") ? "info" : "warn";
10172
+ log2(
10173
+ state,
10174
+ `Credential flush: claude=${outcomes.claude}, opencode=${outcomes.opencode}`,
10175
+ level
10176
+ );
10177
+ });
10178
+ } : void 0;
10179
+ let drainSettled = true;
8645
10180
  if (opts.graceful && state.channelDriver) {
8646
10181
  state.channelDriver.stop();
10182
+ }
10183
+ if (flushCredentials) {
10184
+ await flushCredentials("credential_flush", !(opts.graceful && state.channelDriver));
10185
+ }
10186
+ if (opts.graceful && state.channelDriver) {
8647
10187
  log2(state, "Draining in-flight channel work before shutdown...");
8648
10188
  if (state.interactive) {
8649
10189
  logActivity(state, { type: "info", message: "Draining in-flight work before shutdown..." });
8650
10190
  displayStatus(state);
8651
10191
  }
8652
10192
  const driver = state.channelDriver;
8653
- const settled = await timeShutdownPhase(
10193
+ drainSettled = await timeShutdownPhase(
8654
10194
  state,
8655
10195
  durations,
8656
10196
  "drain",
8657
10197
  () => driver.waitForInFlight(SHUTDOWN_DRAIN_TIMEOUT_MS)
8658
10198
  );
8659
- if (!settled) {
10199
+ if (!drainSettled) {
8660
10200
  logActivity(state, {
8661
10201
  type: "info",
8662
10202
  message: "Shutdown drain timed out with work still in flight \u2014 leaving it for restart recovery"
@@ -8664,6 +10204,9 @@ async function cleanup(state, opts = {}) {
8664
10204
  if (state.interactive) displayStatus(state);
8665
10205
  }
8666
10206
  }
10207
+ if (opts.graceful && state.channelDriver && flushCredentials && drainSettled) {
10208
+ await flushCredentials("credential_flush_final", true);
10209
+ }
8667
10210
  await timeShutdownPhase(state, durations, "offline_notify", () => notifyOffline(state));
8668
10211
  if (state.connection) {
8669
10212
  const connection = state.connection;
@@ -8672,24 +10215,83 @@ async function cleanup(state, opts = {}) {
8672
10215
  }
8673
10216
  if (state.opencodeProcess) {
8674
10217
  const opencodeProcess = state.opencodeProcess;
8675
- await timeShutdownPhase(state, durations, "opencode_stop", () => stopOpenCode(opencodeProcess));
10218
+ const result = await timeShutdownPhase(
10219
+ state,
10220
+ durations,
10221
+ "opencode_stop",
10222
+ () => stopOpenCodeAndWait(opencodeProcess, CHILD_STOP_TIMEOUT_MS)
10223
+ );
8676
10224
  if (state.interactive) {
8677
- logActivity(state, { type: "info", message: "Stopped OpenCode process" });
10225
+ logActivity(state, { type: "info", message: `Stopped OpenCode process (${result.outcome})` });
8678
10226
  displayStatus(state);
8679
10227
  } else {
8680
- log2(state, "Stopped OpenCode process");
10228
+ log2(state, `Stopped OpenCode process (${result.outcome})`);
8681
10229
  }
8682
10230
  state.opencodeProcess = null;
8683
10231
  }
10232
+ if (state.litestreamProcess) {
10233
+ const litestreamProcess = state.litestreamProcess;
10234
+ const result = await timeShutdownPhase(
10235
+ state,
10236
+ durations,
10237
+ "litestream_stop",
10238
+ () => stopSessionDbReplication(litestreamProcess, CHILD_STOP_TIMEOUT_MS)
10239
+ );
10240
+ log2(state, `Stopped litestream replication (${result.outcome})`);
10241
+ state.litestreamProcess = null;
10242
+ }
8684
10243
  return durations;
8685
10244
  }
10245
+ async function beginGracefulShutdown(state, trigger) {
10246
+ if (state.shuttingDown) return;
10247
+ state.shuttingDown = true;
10248
+ const shutdownStartedAt = Date.now();
10249
+ const shutdownMessage = trigger === "recycle" ? "Recycle requested \u2014 finishing in-flight work, then exiting" : "Shutting down...";
10250
+ if (state.interactive) {
10251
+ logActivity(state, { type: "info", message: shutdownMessage });
10252
+ displayStatus(state);
10253
+ } else {
10254
+ log2(state, shutdownMessage);
10255
+ }
10256
+ const durations = await cleanup(state, { graceful: true });
10257
+ const telemetryBudgetMs = Number(process.env.EVIDENT_TELEMETRY_SHUTDOWN_MS) || TELEMETRY_SHUTDOWN_TIMEOUT_MS;
10258
+ await timeShutdownPhase(state, durations, "telemetry_flush", async () => {
10259
+ let timer;
10260
+ const flushed = shutdownTelemetry().then(
10261
+ () => true,
10262
+ (error2) => {
10263
+ log2(
10264
+ state,
10265
+ `Telemetry flush failed during shutdown: ${error2 instanceof Error ? error2.message : String(error2)}`,
10266
+ "warn"
10267
+ );
10268
+ return true;
10269
+ }
10270
+ );
10271
+ const timedOut = new Promise((resolve4) => {
10272
+ timer = setTimeout(() => resolve4(false), telemetryBudgetMs);
10273
+ });
10274
+ if (!await Promise.race([flushed, timedOut])) {
10275
+ log2(state, `Telemetry flush exceeded ${telemetryBudgetMs}ms \u2014 exiting anyway`, "warn");
10276
+ }
10277
+ clearTimeout(timer);
10278
+ });
10279
+ const breakdown = Object.entries(durations).map(([phase, ms]) => `${phase}=${ms}ms`).join(" ");
10280
+ log2(state, `Shutdown complete in ${Date.now() - shutdownStartedAt}ms (${breakdown})`);
10281
+ process.exit(0);
10282
+ }
8686
10283
  async function run(options) {
8687
10284
  const interactive = isInteractive(options.json);
8688
10285
  let logLevel;
8689
10286
  let fileSyncDirectories;
8690
10287
  try {
8691
10288
  logLevel = resolveLogLevel(options);
8692
- fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir4());
10289
+ fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir5());
10290
+ if (options.restoreSessionDb && !options.sessionDbNoReplicateMarker) {
10291
+ throw new Error(
10292
+ "--restore-session-db requires --session-db-no-replicate-marker <path>; restore failures must block Litestream replication"
10293
+ );
10294
+ }
8693
10295
  } catch (error2) {
8694
10296
  const message = error2 instanceof Error ? error2.message : String(error2);
8695
10297
  if (options.json) {
@@ -8713,7 +10315,9 @@ async function run(options) {
8713
10315
  connected: false,
8714
10316
  opencodeConnected: false,
8715
10317
  opencodeVersion: null,
10318
+ sessionDbProvenanceAnomaly: false,
8716
10319
  opencodeProcess: null,
10320
+ litestreamProcess: null,
8717
10321
  connection: null,
8718
10322
  channelDriver: null,
8719
10323
  running: true,
@@ -8727,9 +10331,23 @@ async function run(options) {
8727
10331
  openaiUsageTimer: null,
8728
10332
  openaiUsageRearm: null,
8729
10333
  resourceUsageTimer: null,
10334
+ credentialSync: null,
8730
10335
  authHeader: ""
8731
10336
  };
8732
10337
  setTelemetryAuthProvider(() => ({ authHeader: state.authHeader, agentId: state.agentId }));
10338
+ if (options.credentialSyncMarker) {
10339
+ state.credentialSync = createCredentialSync({
10340
+ markerPath: options.credentialSyncMarker,
10341
+ env: process.env,
10342
+ log: (message, level = "info") => {
10343
+ if (level === "error") {
10344
+ logActivity(state, { type: "error", error: message });
10345
+ } else {
10346
+ logActivity(state, { type: "info", level, message });
10347
+ }
10348
+ }
10349
+ });
10350
+ }
8733
10351
  if (fileSyncDirectories.length > 0) {
8734
10352
  log2(state, `File sync enabled for: ${fileSyncDirectories.join(", ")}`);
8735
10353
  } else {
@@ -8755,43 +10373,7 @@ async function run(options) {
8755
10373
  "warn"
8756
10374
  );
8757
10375
  }
8758
- const handleSignal = async () => {
8759
- if (state.shuttingDown) return;
8760
- state.shuttingDown = true;
8761
- const shutdownStartedAt = Date.now();
8762
- if (state.interactive) {
8763
- logActivity(state, { type: "info", message: "Shutting down..." });
8764
- displayStatus(state);
8765
- } else {
8766
- log2(state, "Shutting down...");
8767
- }
8768
- const durations = await cleanup(state, { graceful: true });
8769
- const telemetryBudgetMs = Number(process.env.EVIDENT_TELEMETRY_SHUTDOWN_MS) || TELEMETRY_SHUTDOWN_TIMEOUT_MS;
8770
- await timeShutdownPhase(state, durations, "telemetry_flush", async () => {
8771
- let timer;
8772
- const flushed = shutdownTelemetry().then(
8773
- () => true,
8774
- (error2) => {
8775
- log2(
8776
- state,
8777
- `Telemetry flush failed during shutdown: ${error2 instanceof Error ? error2.message : String(error2)}`,
8778
- "warn"
8779
- );
8780
- return true;
8781
- }
8782
- );
8783
- const timedOut = new Promise((resolve3) => {
8784
- timer = setTimeout(() => resolve3(false), telemetryBudgetMs);
8785
- });
8786
- if (!await Promise.race([flushed, timedOut])) {
8787
- log2(state, `Telemetry flush exceeded ${telemetryBudgetMs}ms \u2014 exiting anyway`, "warn");
8788
- }
8789
- clearTimeout(timer);
8790
- });
8791
- const breakdown = Object.entries(durations).map(([phase, ms]) => `${phase}=${ms}ms`).join(" ");
8792
- log2(state, `Shutdown complete in ${Date.now() - shutdownStartedAt}ms (${breakdown})`);
8793
- process.exit(0);
8794
- };
10376
+ const handleSignal = () => beginGracefulShutdown(state, "signal");
8795
10377
  process.on("SIGINT", handleSignal);
8796
10378
  process.on("SIGTERM", handleSignal);
8797
10379
  try {
@@ -8921,7 +10503,68 @@ async function run(options) {
8921
10503
  } else {
8922
10504
  log2(state, "Not running in a MicroVM (MICROVM_ID unset) \u2014 nothing to report", "debug");
8923
10505
  }
10506
+ if (options.restoreRunnerCredentials) {
10507
+ log2(state, "Restoring runner credentials before starting OpenCode");
10508
+ const credentialContext = {
10509
+ env: process.env,
10510
+ log: (message, level = "info") => {
10511
+ if (level === "error") {
10512
+ logActivity(state, { type: "error", error: message });
10513
+ } else {
10514
+ logActivity(state, { type: "info", level, message });
10515
+ }
10516
+ }
10517
+ };
10518
+ const githubTokenPopulated = await installRunnerSecret(credentialContext);
10519
+ await restoreCredentialStores(credentialContext);
10520
+ if (githubTokenPopulated) await configureGitHubAccess(credentialContext);
10521
+ }
10522
+ state.credentialSync?.arm();
10523
+ let sessionDbVerifyFatal = false;
10524
+ if (!options.restoreSessionDb) {
10525
+ log2(state, "Skipping session-DB restore: --restore-session-db was not passed", "debug");
10526
+ } else {
10527
+ const health = await checkOpenCodeHealth(state.port);
10528
+ if (health.healthy) {
10529
+ log2(
10530
+ state,
10531
+ "Skipping session-DB restore: OpenCode is already serving this database",
10532
+ "debug"
10533
+ );
10534
+ } else {
10535
+ const result = await restoreAndVerifySessionDb({
10536
+ dbPath: sessionDbPath(),
10537
+ litestreamConfig: options.litestreamConfig,
10538
+ noReplicateMarker: options.sessionDbNoReplicateMarker,
10539
+ env: process.env,
10540
+ log: (message, level = "info") => {
10541
+ if (level === "error") {
10542
+ logActivity(state, { type: "error", error: message });
10543
+ } else {
10544
+ logActivity(state, { type: "info", level, message });
10545
+ }
10546
+ },
10547
+ reportRecovery: (record) => reportSessionDbRecoveryRecord(state, record)
10548
+ });
10549
+ sessionDbVerifyFatal = result.verifyFatal;
10550
+ }
10551
+ }
8924
10552
  reportSessionDbRecovery(state);
10553
+ if (sessionDbVerifyFatal) {
10554
+ throw new Error(
10555
+ "SESSION-DB-INTEGRITY-EXHAUSTED: the corrupt session DB could not be proven separated from the active backup prefix or removed from disk"
10556
+ );
10557
+ }
10558
+ applyRunnerOpenCodeConfig({
10559
+ overlayPath: options.opencodeConfigOverlay,
10560
+ log: (message, level = "info") => {
10561
+ if (level === "error") {
10562
+ logActivity(state, { type: "error", error: message });
10563
+ } else {
10564
+ logActivity(state, { type: "info", level, message });
10565
+ }
10566
+ }
10567
+ });
8925
10568
  const { timeoutMs: opencodeStartTimeoutMs, warnings: opencodeStartTimeoutWarnings } = resolveOpenCodeStartTimeoutMs(options, process.env);
8926
10569
  for (const warning2 of opencodeStartTimeoutWarnings) {
8927
10570
  logActivity(state, { type: "info", level: "warn", message: warning2 });
@@ -8930,6 +10573,7 @@ async function run(options) {
8930
10573
  for (const warning2 of maxActiveSessionsWarnings) {
8931
10574
  logActivity(state, { type: "info", level: "warn", message: warning2 });
8932
10575
  }
10576
+ const preBootMigrationIds = readSessionDbMigrationIds(sessionDbPath());
8933
10577
  const ocSpinner = interactive && !state.json ? ora3("Checking OpenCode...").start() : null;
8934
10578
  try {
8935
10579
  const oc = await ensureOpenCodeRunning({
@@ -8937,11 +10581,41 @@ async function run(options) {
8937
10581
  interactive: state.interactive,
8938
10582
  agentId: state.agentId,
8939
10583
  log: (message) => log2(state, message),
8940
- startTimeoutMs: opencodeStartTimeoutMs
10584
+ startTimeoutMs: opencodeStartTimeoutMs,
10585
+ inheritStdio: Boolean(options.opencodePidFile)
8941
10586
  });
8942
10587
  state.port = oc.port;
8943
- state.opencodeProcess = oc.process;
10588
+ state.opencodeProcess = options.opencodePidFile ? null : oc.process;
8944
10589
  state.opencodeVersion = oc.version;
10590
+ if (options.opencodePidFile && oc.process?.pid !== void 0) {
10591
+ try {
10592
+ writeFileSync6(options.opencodePidFile, `${oc.process.pid}
10593
+ `, { mode: 384 });
10594
+ chmodSync3(options.opencodePidFile, 384);
10595
+ } catch (error2) {
10596
+ logActivity(state, {
10597
+ type: "error",
10598
+ error: `Failed to write OpenCode pid file ${options.opencodePidFile}: ${error2 instanceof Error ? error2.message : String(error2)}`
10599
+ });
10600
+ }
10601
+ }
10602
+ if (state.opencodeVersion !== null) {
10603
+ const provenance = checkSessionDbProvenance({
10604
+ dbPath: sessionDbPath(),
10605
+ currentVersion: state.opencodeVersion,
10606
+ homeDir: homedir5(),
10607
+ env: process.env
10608
+ });
10609
+ if (provenance.anomaly) {
10610
+ state.sessionDbProvenanceAnomaly = true;
10611
+ logSessionDbProvenanceMismatch(
10612
+ state,
10613
+ provenance,
10614
+ state.opencodeVersion,
10615
+ preBootMigrationIds?.length ?? null
10616
+ );
10617
+ }
10618
+ }
8945
10619
  state.opencodeConnected = oc.notReadyReason === null;
8946
10620
  const version2 = state.opencodeVersion ? ` (v${state.opencodeVersion})` : "";
8947
10621
  ocSpinner?.succeed(`OpenCode running on port ${state.port}${version2}`);
@@ -8978,6 +10652,108 @@ async function run(options) {
8978
10652
  ocSpinner?.fail(error2.message);
8979
10653
  throw error2;
8980
10654
  }
10655
+ if (options.litestreamPidFile) {
10656
+ if (options.sessionDbNoReplicateMarker && existsSync3(options.sessionDbNoReplicateMarker)) {
10657
+ log2(
10658
+ state,
10659
+ `Skipping Litestream replication because ${options.sessionDbNoReplicateMarker} marks this session database unsafe to replicate`
10660
+ );
10661
+ } else if (!options.litestreamConfig) {
10662
+ logActivity(state, {
10663
+ type: "info",
10664
+ level: "warn",
10665
+ message: "Skipping Litestream replication because no configuration file was provided"
10666
+ });
10667
+ } else {
10668
+ let existingPid;
10669
+ if (existsSync3(options.litestreamPidFile)) {
10670
+ try {
10671
+ const rawPid = readFileSync6(options.litestreamPidFile, "utf8").trim();
10672
+ const parsedPid = Number(rawPid);
10673
+ if (/^\d+$/.test(rawPid) && Number.isSafeInteger(parsedPid) && parsedPid > 0) {
10674
+ existingPid = parsedPid;
10675
+ }
10676
+ } catch (error2) {
10677
+ logActivity(state, {
10678
+ type: "info",
10679
+ level: "warn",
10680
+ message: `Could not read Litestream pid file ${options.litestreamPidFile}; checking for a new process: ${error2 instanceof Error ? error2.message : String(error2)}`
10681
+ });
10682
+ }
10683
+ }
10684
+ if (existingPid !== void 0 && isProcessAlive(existingPid)) {
10685
+ log2(state, `Litestream replication is already running with pid ${existingPid}`);
10686
+ } else {
10687
+ const litestreamProcess = startSessionDbReplication(options.litestreamConfig);
10688
+ state.litestreamProcess = null;
10689
+ let failureHandled = false;
10690
+ const reportImageOwnedReplicationFailure = (message) => {
10691
+ if (failureHandled || state.shuttingDown || !state.running) return;
10692
+ failureHandled = true;
10693
+ logActivity(state, { type: "error", error: message });
10694
+ if (state.interactive) displayStatus(state);
10695
+ };
10696
+ litestreamProcess.on("exit", (code, signal) => {
10697
+ reportImageOwnedReplicationFailure(
10698
+ `Litestream replication stopped unexpectedly (code: ${code ?? "null"}, signal: ${signal ?? "none"})`
10699
+ );
10700
+ });
10701
+ litestreamProcess.on("error", (error2) => {
10702
+ reportImageOwnedReplicationFailure(
10703
+ `Litestream replication failed: ${error2 instanceof Error ? error2.message : String(error2)}`
10704
+ );
10705
+ });
10706
+ try {
10707
+ if (litestreamProcess.pid !== void 0) {
10708
+ writeFileSync6(options.litestreamPidFile, `${litestreamProcess.pid}
10709
+ `, {
10710
+ mode: 384
10711
+ });
10712
+ chmodSync3(options.litestreamPidFile, 384);
10713
+ }
10714
+ } catch (error2) {
10715
+ logActivity(state, {
10716
+ type: "error",
10717
+ error: `Failed to write Litestream pid file ${options.litestreamPidFile}: ${error2 instanceof Error ? error2.message : String(error2)}`
10718
+ });
10719
+ }
10720
+ log2(state, `Started litestream replication with config ${options.litestreamConfig}`);
10721
+ }
10722
+ }
10723
+ } else if (options.litestreamConfig) {
10724
+ const litestreamProcess = startSessionDbReplication(options.litestreamConfig);
10725
+ state.litestreamProcess = litestreamProcess;
10726
+ let failureHandled = false;
10727
+ const failRunForReplication = (message) => {
10728
+ if (failureHandled || state.shuttingDown || !state.running) return;
10729
+ failureHandled = true;
10730
+ state.shuttingDown = true;
10731
+ logActivity(state, { type: "error", error: message });
10732
+ if (state.interactive) displayStatus(state);
10733
+ void (async () => {
10734
+ try {
10735
+ await cleanup(state);
10736
+ await shutdownTelemetry();
10737
+ } catch (error2) {
10738
+ console.error(
10739
+ `[run] replication failure cleanup failed: ${error2 instanceof Error ? error2.message : String(error2)}`
10740
+ );
10741
+ }
10742
+ process.exit(1);
10743
+ })();
10744
+ };
10745
+ litestreamProcess.on("exit", (code, signal) => {
10746
+ failRunForReplication(
10747
+ `Litestream replication stopped unexpectedly (code: ${code ?? "null"}, signal: ${signal ?? "none"})`
10748
+ );
10749
+ });
10750
+ litestreamProcess.on("error", (error2) => {
10751
+ failRunForReplication(
10752
+ `Litestream replication failed: ${error2 instanceof Error ? error2.message : String(error2)}`
10753
+ );
10754
+ });
10755
+ log2(state, `Started litestream replication with config ${options.litestreamConfig}`);
10756
+ }
8981
10757
  const tunnelSpinner = interactive && !state.json ? ora3("Connecting tunnel...").start() : null;
8982
10758
  const channelDriver = new ChannelDriver({
8983
10759
  agentId: state.agentId,
@@ -8989,7 +10765,7 @@ async function run(options) {
8989
10765
  // #559: the `--enable-file-sync-to` allow-list. Empty ⇒ pending files are
8990
10766
  // REJECTED with `file_sync_disabled` on the ack, not silently ignored.
8991
10767
  fileSyncDirectories,
8992
- homeDir: homedir4(),
10768
+ homeDir: homedir5(),
8993
10769
  maxActiveSessions,
8994
10770
  log: (entry) => (
8995
10771
  // Thread the driver's real level straight through so `debug`/`warn`
@@ -9181,7 +10957,7 @@ async function run(options) {
9181
10957
  }
9182
10958
 
9183
10959
  // src/index.ts
9184
- var { version } = createRequire(import.meta.url)("../package.json");
10960
+ var { version } = createRequire2(import.meta.url)("../package.json");
9185
10961
  var program = new Command();
9186
10962
  program.name("evident").description("Run OpenCode locally and connect it to Evident").version(version).option(
9187
10963
  "--endpoint <url>",
@@ -9238,6 +11014,30 @@ program.command("run").description("Connect to Evident and process messages").op
9238
11014
  ).option(
9239
11015
  "--tunnel-ready-file <path>",
9240
11016
  "Path to write once the tunnel is connected (opt-in; unused unless an operator/image sets it)"
11017
+ ).option(
11018
+ "--litestream-config <path>",
11019
+ "Replicate the OpenCode session database with `litestream replicate` using this config file (written by the runner image). Omit to disable replication."
11020
+ ).option(
11021
+ "--opencode-pid-file <path>",
11022
+ "Record the OpenCode pid here and leave the process running at shutdown for the runner image's lifecycle hooks to stop."
11023
+ ).option(
11024
+ "--litestream-pid-file <path>",
11025
+ "Record the Litestream pid here and leave the process running at shutdown for the runner image's lifecycle hooks to stop."
11026
+ ).option(
11027
+ "--session-db-no-replicate-marker <path>",
11028
+ "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."
11029
+ ).option(
11030
+ "--restore-session-db",
11031
+ "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."
11032
+ ).option(
11033
+ "--restore-runner-credentials",
11034
+ "Restore the hosted runner secret and persisted credential stores before starting OpenCode."
11035
+ ).option(
11036
+ "--opencode-config-overlay <path>",
11037
+ "Apply this runner-provided OpenCode config before starting OpenCode."
11038
+ ).option(
11039
+ "--credential-sync-marker <path>",
11040
+ "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."
9241
11041
  ).action(
9242
11042
  (options) => {
9243
11043
  run({
@@ -9269,7 +11069,15 @@ program.command("run").description("Connect to Evident and process messages").op
9269
11069
  // Raw values — expansion/validation is single-sourced in run.ts's
9270
11070
  // resolveFileSyncDirectories.
9271
11071
  enableFileSyncTo: options.enableFileSyncTo,
9272
- tunnelReadyFile: options.tunnelReadyFile
11072
+ tunnelReadyFile: options.tunnelReadyFile,
11073
+ litestreamConfig: options.litestreamConfig,
11074
+ opencodePidFile: options.opencodePidFile,
11075
+ litestreamPidFile: options.litestreamPidFile,
11076
+ sessionDbNoReplicateMarker: options.sessionDbNoReplicateMarker,
11077
+ restoreSessionDb: options.restoreSessionDb,
11078
+ restoreRunnerCredentials: options.restoreRunnerCredentials,
11079
+ opencodeConfigOverlay: options.opencodeConfigOverlay,
11080
+ credentialSyncMarker: options.credentialSyncMarker
9273
11081
  });
9274
11082
  }
9275
11083
  );