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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/index.ts
4
- import { createRequire } from "module";
4
+ import { createRequire as createRequire2 } from "module";
5
5
  import { Command } from "commander";
6
6
 
7
7
  // src/commands/login.ts
@@ -371,14 +371,14 @@ function blank() {
371
371
  console.log();
372
372
  }
373
373
  function waitForEnter(prompt = "Press Enter to continue...") {
374
- return new Promise((resolve3) => {
374
+ return new Promise((resolve4) => {
375
375
  process.stdout.write(chalk.dim(prompt));
376
376
  const handler = () => {
377
377
  process.stdin.removeListener("data", handler);
378
378
  process.stdin.setRawMode?.(false);
379
379
  process.stdin.pause();
380
380
  console.log();
381
- resolve3();
381
+ resolve4();
382
382
  };
383
383
  if (process.stdin.isTTY) {
384
384
  process.stdin.setRawMode?.(true);
@@ -388,7 +388,7 @@ function waitForEnter(prompt = "Press Enter to continue...") {
388
388
  });
389
389
  }
390
390
  function sleep(ms) {
391
- return new Promise((resolve3) => setTimeout(resolve3, ms));
391
+ return new Promise((resolve4) => setTimeout(resolve4, ms));
392
392
  }
393
393
 
394
394
  // src/commands/login.ts
@@ -466,19 +466,19 @@ async function tokenLogin() {
466
466
  );
467
467
  blank();
468
468
  process.stdout.write("Paste token: ");
469
- const token = await new Promise((resolve3) => {
469
+ const token = await new Promise((resolve4) => {
470
470
  let data = "";
471
471
  process.stdin.setEncoding("utf8");
472
472
  process.stdin.on("data", (chunk) => {
473
473
  data += chunk;
474
474
  });
475
475
  process.stdin.on("end", () => {
476
- resolve3(data.trim());
476
+ resolve4(data.trim());
477
477
  });
478
478
  if (process.stdin.isTTY) {
479
479
  process.stdin.once("data", (chunk) => {
480
480
  process.stdin.pause();
481
- resolve3(chunk.toString().trim());
481
+ resolve4(chunk.toString().trim());
482
482
  });
483
483
  process.stdin.resume();
484
484
  }
@@ -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
  });
@@ -754,6 +763,13 @@ function toReportedOpenAiWindow(window) {
754
763
  resets_at: window.resetsAt
755
764
  };
756
765
  }
766
+ function toReportedOpenAiSubscription(snapshot) {
767
+ if (!snapshot.subscription) return null;
768
+ return {
769
+ owner_email: snapshot.subscription.ownerEmail,
770
+ plan_type: snapshot.subscription.planType
771
+ };
772
+ }
757
773
  async function reportOpenAiUsage(agentId, authHeader, snapshot) {
758
774
  try {
759
775
  const apiUrl = getApiUrlConfig();
@@ -764,7 +780,8 @@ async function reportOpenAiUsage(agentId, authHeader, snapshot) {
764
780
  primary: toReportedOpenAiWindow(snapshot.primary),
765
781
  secondary: toReportedOpenAiWindow(snapshot.secondary),
766
782
  has_credits: snapshot.hasCredits,
767
- credits_unlimited: snapshot.creditsUnlimited
783
+ credits_unlimited: snapshot.creditsUnlimited,
784
+ subscription: toReportedOpenAiSubscription(snapshot)
768
785
  }),
769
786
  signal: AbortSignal.timeout(BEST_EFFORT_NOTIFY_TIMEOUT_MS)
770
787
  });
@@ -788,6 +805,7 @@ async function reportResourceUsage(agentId, authHeader, usage) {
788
805
  headers: { Authorization: authHeader, "Content-Type": "application/json" },
789
806
  body: JSON.stringify({
790
807
  cpu_percent: usage.cpuPercent,
808
+ cpu_peak_percent: usage.cpuPeakPercent,
791
809
  cpu_count: usage.cpuCount,
792
810
  memory_total_bytes: usage.memoryTotalBytes,
793
811
  memory_available_bytes: usage.memoryAvailableBytes,
@@ -996,7 +1014,10 @@ import { readFileSync } from "fs";
996
1014
  import { homedir } from "os";
997
1015
  import { join } from "path";
998
1016
  var CLAUDE_USAGE_URL = "https://api.anthropic.com/api/oauth/usage";
1017
+ var CLAUDE_PROFILE_URL = "https://api.anthropic.com/api/oauth/profile";
1018
+ var CLAUDE_PROFILE_TIMEOUT_MS = 2e3;
999
1019
  var KEYCHAIN_SERVICE = "Claude Code-credentials";
1020
+ var cachedOwner = null;
1000
1021
  var CLAUDE_CREDENTIALS_SEGMENTS = [".claude", ".credentials.json"];
1001
1022
  function parseClaudeCliCredentials(raw) {
1002
1023
  let parsed;
@@ -1070,6 +1091,47 @@ function toWindow(value) {
1070
1091
  }
1071
1092
  return { utilization: window.utilization, resetsAt };
1072
1093
  }
1094
+ function ownerLookupFailure(error2) {
1095
+ const name = error2?.name;
1096
+ return name === "TimeoutError" || name === "AbortError" ? "timed out" : "request failed";
1097
+ }
1098
+ async function getClaudeUsageOwner(accessToken) {
1099
+ if (cachedOwner?.accessToken === accessToken) {
1100
+ return { owner: cachedOwner.owner, ownerLookupError: null };
1101
+ }
1102
+ try {
1103
+ const response = await fetch(CLAUDE_PROFILE_URL, {
1104
+ headers: {
1105
+ Authorization: `Bearer ${accessToken}`,
1106
+ "Content-Type": "application/json",
1107
+ "anthropic-version": "2023-06-01"
1108
+ },
1109
+ signal: AbortSignal.timeout(CLAUDE_PROFILE_TIMEOUT_MS)
1110
+ });
1111
+ if (!response.ok) {
1112
+ return { owner: null, ownerLookupError: `HTTP ${response.status}` };
1113
+ }
1114
+ let body;
1115
+ try {
1116
+ body = await response.json();
1117
+ } catch (error2) {
1118
+ return { owner: null, ownerLookupError: "malformed response" };
1119
+ }
1120
+ const profile = body;
1121
+ if (typeof profile.account?.email !== "string" || !profile.account.email.trim()) {
1122
+ return { owner: null, ownerLookupError: "malformed response" };
1123
+ }
1124
+ const owner = {
1125
+ email: profile.account.email,
1126
+ organizationName: typeof profile.organization?.name === "string" && profile.organization.name.trim() ? profile.organization.name.trim() : null,
1127
+ rateLimitTier: typeof profile.organization?.rate_limit_tier === "string" && profile.organization.rate_limit_tier.trim() ? profile.organization.rate_limit_tier.trim() : null
1128
+ };
1129
+ cachedOwner = { accessToken, owner };
1130
+ return { owner, ownerLookupError: null };
1131
+ } catch (error2) {
1132
+ return { owner: null, ownerLookupError: ownerLookupFailure(error2) };
1133
+ }
1134
+ }
1073
1135
  async function getClaudeUsage() {
1074
1136
  const credentials2 = readClaudeCliCredentials();
1075
1137
  if (!credentials2) {
@@ -1089,15 +1151,19 @@ async function getClaudeUsage() {
1089
1151
  Authorization: `Bearer ${credentials2.accessToken}`,
1090
1152
  "Content-Type": "application/json",
1091
1153
  "anthropic-version": "2023-06-01"
1092
- }
1154
+ },
1155
+ signal: AbortSignal.timeout(CLAUDE_PROFILE_TIMEOUT_MS)
1093
1156
  });
1094
1157
  if (!res.ok) {
1095
1158
  throw new ClaudeUsageError(`Claude usage request failed: HTTP ${res.status}`, "request_failed");
1096
1159
  }
1097
1160
  const body = await res.json();
1161
+ const { owner, ownerLookupError } = await getClaudeUsageOwner(credentials2.accessToken);
1098
1162
  return {
1099
1163
  fiveHour: toWindow(body.five_hour),
1100
- sevenDay: toWindow(body.seven_day)
1164
+ sevenDay: toWindow(body.seven_day),
1165
+ owner,
1166
+ ownerLookupError
1101
1167
  };
1102
1168
  }
1103
1169
 
@@ -1126,8 +1192,9 @@ async function claudeUsage() {
1126
1192
  }
1127
1193
 
1128
1194
  // 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";
1195
+ import { chmodSync as chmodSync3, existsSync as existsSync3, readFileSync as readFileSync6, writeFileSync as writeFileSync6 } from "fs";
1196
+ import { homedir as homedir5 } from "os";
1197
+ import { isAbsolute as isAbsolute3, join as join9, parse, resolve as resolvePath2 } from "path";
1131
1198
  import chalk6 from "chalk";
1132
1199
 
1133
1200
  // ../../packages/types/src/agents/index.ts
@@ -1467,7 +1534,14 @@ function drainSessionDbRecoveryReport({
1467
1534
  skippedLines++;
1468
1535
  return [];
1469
1536
  }
1470
- return [value];
1537
+ return [
1538
+ {
1539
+ ...value,
1540
+ provenance_reason: value.provenance_reason ?? null,
1541
+ provenance_migration_delta: value.provenance_migration_delta ?? null,
1542
+ replication_suspended: value.replication_suspended ?? false
1543
+ }
1544
+ ];
1471
1545
  } catch (error2) {
1472
1546
  skippedLines++;
1473
1547
  console.error(
@@ -1492,12 +1566,39 @@ function buildSessionDbRecoveryActivity(record) {
1492
1566
  const level = record.severity === "warning" ? "warn" : record.severity === "error" ? "error" : null;
1493
1567
  if (!level) return null;
1494
1568
  const noVerifiedPoint = record.verified_restore_point ? ` The verified restore point is ${record.verified_restore_point}.` : " No verified restore point is known.";
1569
+ const replication = record.replication_suspended ? " This start is not backing up its new session history; restart after fixing the cause." : "";
1570
+ const giveupMessage = (() => {
1571
+ switch (record.reason) {
1572
+ case "restore_deadline_exceeded":
1573
+ return "The restore did not finish before this startup deadline. Earlier sessions are unavailable for this start; collect the SESSION-DB-RESTORE-TRUNCATED boot log before retrying.";
1574
+ case "restore_tool_unusable":
1575
+ case "classification_unrecognised":
1576
+ return "The restore or classification tool produced an unsupported result. Inspect the named boot marker or log and repair the runner image or bundle before restarting.";
1577
+ case "synchroniser_config_unevaluable":
1578
+ case "synchroniser_config_incomplete":
1579
+ return "The installed hook and synchroniser bundle could not agree on configuration. Inspect the named boot marker or log and repair the runner image or bundle before restarting.";
1580
+ case "synchroniser_config_unresolved":
1581
+ return "The synchroniser configuration could not be resolved. Inspect the preceding boot error and repair the identified runner image, bundle, or local environment before restarting.";
1582
+ case "litestream_config_unavailable":
1583
+ return "The local Litestream configuration could not be generated or written. Inspect the preceding boot error and repair the runner image, bundle, local environment, or write permissions before restarting.";
1584
+ case "classification_fatal":
1585
+ return "Session history could not be restored because backup setup could not be established. Inspect the named boot marker or log and repair the identified backup configuration or permissions.";
1586
+ default:
1587
+ return null;
1588
+ }
1589
+ })();
1590
+ if (giveupMessage)
1591
+ return {
1592
+ level,
1593
+ metadata: withoutContractFields(record),
1594
+ message: `${giveupMessage}${replication}`
1595
+ };
1495
1596
  switch (record.outcome) {
1496
1597
  case "fresh_session_db":
1497
1598
  return {
1498
1599
  level,
1499
1600
  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.`
1601
+ message: `This runner started with a fresh session database. Earlier sessions are unavailable, and queued conversation or session references from before this start may no longer resolve.${noVerifiedPoint} Review the runner's backup configuration before relying on restored session history.${replication}`
1501
1602
  };
1502
1603
  case "restore_retried":
1503
1604
  return {
@@ -1535,7 +1636,19 @@ function buildSessionDbRecoveryActivity(record) {
1535
1636
  return {
1536
1637
  level,
1537
1638
  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."
1639
+ message: `This runner started without restoring session history because it could not verify where its session history is backed up. Nothing in the backup was changed; check the runner backup configuration and permissions.${replication}`
1640
+ };
1641
+ case "session_db_boot_refused":
1642
+ return {
1643
+ level,
1644
+ metadata: withoutContractFields(record),
1645
+ message: `This runner did not come online because its damaged session database could not be safely separated from its active backup or proven removed. Backed-up session history remains readable at ${record.quarantine_destination ?? "its original location or the quarantine destination named in the boot logs"}; any local session-database files that remain were left in place and nothing opened or wrote them. See the runner boot logs for SESSION-DB-LOCAL-DISCARD-FAILED details.`
1646
+ };
1647
+ case "schema_provenance_mismatch":
1648
+ return {
1649
+ level,
1650
+ metadata: withoutContractFields(record),
1651
+ message: `Session database schema provenance mismatch for ${record.dbPath ?? record.db_path ?? "unknown"}: recorded version=${record.recorded_version ?? "unknown"}, current version=${record.current_version ?? "unknown"}, reason=${record.provenance_reason ?? "unknown"}, migration delta=${record.provenance_migration_delta ?? "unknown"}. Inspect the session database and runner backup before continuing.`
1539
1652
  };
1540
1653
  default:
1541
1654
  return null;
@@ -1550,7 +1663,9 @@ var OUTCOMES = /* @__PURE__ */ new Set([
1550
1663
  "restore_retried",
1551
1664
  "fresh_session_db",
1552
1665
  "history_rolled_back",
1553
- "restore_misconfigured"
1666
+ "restore_misconfigured",
1667
+ "session_db_boot_refused",
1668
+ "schema_provenance_mismatch"
1554
1669
  ]);
1555
1670
  var STAGES = /* @__PURE__ */ new Set(["restore", "verify"]);
1556
1671
  var SEVERITIES = /* @__PURE__ */ new Set(["warning", "error"]);
@@ -1568,7 +1683,7 @@ var STRING_OR_NULL_FIELDS = ["quarantine_destination", "verified_restore_point"]
1568
1683
  function isSessionDbRecoveryRecord(value) {
1569
1684
  if (!value || typeof value !== "object" || Array.isArray(value)) return false;
1570
1685
  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(
1686
+ return record.v === 1 && record.event === "session_db_recovery" && typeof record.at === "string" && STAGES.has(record.stage) && OUTCOMES.has(record.outcome) && SEVERITIES.has(record.severity) && typeof record.reason === "string" && (record.replication_suspended === void 0 || typeof record.replication_suspended === "boolean") && (record.provenance_reason === void 0 || record.provenance_reason === null || typeof record.provenance_reason === "string") && (record.provenance_migration_delta === void 0 || record.provenance_migration_delta === null || Number.isInteger(record.provenance_migration_delta)) && NUMBER_FIELDS.every((field) => record[field] === null || Number.isInteger(record[field])) && STRING_OR_NULL_FIELDS.every(
1572
1687
  (field) => record[field] === null || typeof record[field] === "string"
1573
1688
  );
1574
1689
  }
@@ -1597,215 +1712,933 @@ async function waitForOpenCodeHealth(port, timeoutMs = 3e4) {
1597
1712
  if (health.healthy) {
1598
1713
  return health;
1599
1714
  }
1600
- await new Promise((resolve3) => setTimeout(resolve3, 1e3));
1715
+ await new Promise((resolve4) => setTimeout(resolve4, 1e3));
1601
1716
  }
1602
1717
  return { healthy: false, error: "Timeout waiting for OpenCode to be healthy" };
1603
1718
  }
1604
1719
 
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
- }
1720
+ // src/lib/opencode/session-db-boot.ts
1721
+ import { spawn as spawn2 } from "child_process";
1722
+ import { mkdirSync, statSync as statSync2, unlinkSync as unlinkSync2, writeFileSync } from "fs";
1723
+ import { homedir as homedir2 } from "os";
1724
+ import { dirname as dirname2, resolve as resolvePath } from "path";
1617
1725
 
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);
1726
+ // src/lib/runner-synchroniser.ts
1727
+ import { spawn } from "child_process";
1728
+ function appendError(stderr, error2) {
1729
+ const message = error2 instanceof Error ? error2.message : String(error2);
1730
+ return stderr === "" ? message : `${stderr}
1731
+ ${message}`;
1732
+ }
1733
+ function runSynchroniser(args, opts) {
1734
+ return new Promise((resolve4) => {
1735
+ let child;
1736
+ let stdout = "";
1737
+ let stderr = "";
1738
+ let settled = false;
1739
+ const timer = {};
1740
+ let abortListener;
1741
+ let spawnListener;
1742
+ const finish = (result) => {
1743
+ if (settled) return;
1744
+ settled = true;
1745
+ if (timer.handle) clearTimeout(timer.handle);
1746
+ if (abortListener) opts.signal?.removeEventListener("abort", abortListener);
1747
+ if (spawnListener) child.removeListener("spawn", spawnListener);
1748
+ resolve4(result);
1749
+ };
1750
+ try {
1751
+ child = spawn("runner-synchroniser", args, {
1752
+ env: opts.env ?? process.env,
1753
+ stdio: ["ignore", "pipe", "pipe"]
1754
+ });
1755
+ } catch (error2) {
1756
+ finish({ code: null, stdout, stderr: appendError(stderr, error2), timedOut: false });
1757
+ return;
1758
+ }
1759
+ child.stdout?.setEncoding("utf8");
1760
+ child.stdout?.on("data", (chunk) => {
1761
+ stdout += chunk;
1762
+ });
1763
+ child.stderr?.setEncoding("utf8");
1764
+ child.stderr?.on("data", (chunk) => {
1765
+ stderr += chunk;
1766
+ });
1767
+ child.once("error", (error2) => {
1768
+ finish({ code: null, stdout, stderr: appendError(stderr, error2), timedOut: false });
1769
+ });
1770
+ child.once("close", (code) => {
1771
+ finish({ code, stdout, stderr, timedOut: false });
1772
+ });
1773
+ if (opts.signal) {
1774
+ const killChild = () => {
1775
+ if (child.pid === void 0) {
1776
+ if (!spawnListener) {
1777
+ spawnListener = killChild;
1778
+ child.once("spawn", spawnListener);
1779
+ }
1780
+ return;
1633
1781
  }
1782
+ child.kill("SIGKILL");
1783
+ };
1784
+ abortListener = killChild;
1785
+ if (opts.signal.aborted) {
1786
+ abortListener();
1787
+ } else {
1788
+ opts.signal.addEventListener("abort", abortListener, { once: true });
1789
+ if (opts.signal.aborted) abortListener();
1634
1790
  }
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
1791
  }
1642
- } catch {
1643
- }
1644
- return void 0;
1792
+ timer.handle = setTimeout(
1793
+ () => {
1794
+ child.kill("SIGKILL");
1795
+ finish({ code: null, stdout, stderr, timedOut: true });
1796
+ },
1797
+ Math.max(0, opts.timeoutMs)
1798
+ );
1799
+ });
1645
1800
  }
1646
- function isPortInUse(port) {
1647
- const platform = process.platform;
1801
+
1802
+ // src/lib/opencode/session-db-boot.ts
1803
+ var SESSION_DB_RESTORE_TIMEOUT_MS = 3e5;
1804
+ var SESSION_DB_VERIFY_TIMEOUT_MS = 12e4;
1805
+ var SESSION_DB_SYNCHRONISER_TIMEOUT_MS = 12e4;
1806
+ var SESSION_DB_VERIFY_WALKBACK_BUDGET_SECONDS = 120;
1807
+ function commandError(result) {
1808
+ return result.stderr.trim() || `process exited with code ${result.code ?? "null"}`;
1809
+ }
1810
+ function reportRecord(stage, outcome, reason, litestreamExitCode, options) {
1811
+ options.reportRecovery({
1812
+ v: 1,
1813
+ event: "session_db_recovery",
1814
+ at: (/* @__PURE__ */ new Date()).toISOString(),
1815
+ stage,
1816
+ outcome,
1817
+ severity: "error",
1818
+ reason,
1819
+ litestream_exit_code: litestreamExitCode,
1820
+ attempt: null,
1821
+ replica_objects: null,
1822
+ replica_bytes: null,
1823
+ quarantine_destination: null,
1824
+ quarantined_objects: null,
1825
+ quarantine_failed_objects: null,
1826
+ quarantined_bytes: null,
1827
+ verified_restore_point: null,
1828
+ restore_points_tried: null,
1829
+ provenance_reason: null,
1830
+ provenance_migration_delta: null,
1831
+ replication_suspended: stage === "restore"
1832
+ });
1833
+ }
1834
+ function clearMarker(options) {
1835
+ if (!options.noReplicateMarker) return;
1648
1836
  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 {
1837
+ unlinkSync2(options.noReplicateMarker);
1838
+ } catch (error2) {
1839
+ if (error2 instanceof Error && "code" in error2 && error2.code === "ENOENT") return;
1840
+ options.log(
1841
+ `Could not clear the previous session-DB no-replicate marker ${options.noReplicateMarker}: ${error2 instanceof Error ? error2.message : String(error2)}`,
1842
+ "warn"
1843
+ );
1657
1844
  }
1658
- return false;
1659
1845
  }
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;
1846
+ function markNoReplicate(options, message) {
1847
+ if (options.noReplicateMarker) {
1848
+ try {
1849
+ mkdirSync(dirname2(options.noReplicateMarker), { recursive: true });
1850
+ writeFileSync(options.noReplicateMarker, "");
1851
+ } catch (error2) {
1852
+ options.log(
1853
+ `Could not write session-DB no-replicate marker ${options.noReplicateMarker}: ${error2 instanceof Error ? error2.message : String(error2)}`,
1854
+ "error"
1855
+ );
1665
1856
  }
1666
1857
  }
1667
- return null;
1858
+ options.log(`SESSION-DB-NO-REPLICATE: ${message}`, "warn");
1668
1859
  }
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
- }
1860
+ function discardSessionDbDebris(options) {
1861
+ for (const path of [options.dbPath, `${options.dbPath}-wal`, `${options.dbPath}-shm`]) {
1862
+ try {
1863
+ unlinkSync2(path);
1864
+ } catch (error2) {
1865
+ if (error2 instanceof Error && "code" in error2 && error2.code === "ENOENT") continue;
1866
+ options.log(
1867
+ `Could not remove session-DB debris ${path}: ${error2 instanceof Error ? error2.message : String(error2)}`,
1868
+ "warn"
1869
+ );
1723
1870
  }
1724
- } catch (err) {
1725
- console.warn(
1726
- `findOpenCodeProcesses: process detection failed: ${err instanceof Error ? err.message : String(err)}`
1727
- );
1728
1871
  }
1729
- return instances;
1730
1872
  }
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;
1873
+ function splitDiagnostics(text) {
1874
+ return text.split("\n").map((line) => line.trim()).filter((line) => line.length > 0);
1759
1875
  }
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 });
1876
+ function logSynchroniserDiagnostics(result, options) {
1877
+ for (const line of splitDiagnostics(result.stderr)) options.log(line, "warn");
1878
+ }
1879
+ function parseSingleQuotedAssignment(line) {
1880
+ const match = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(line);
1881
+ if (!match || !match[2].startsWith("'")) return null;
1882
+ const valueSource = match[2];
1883
+ let value = "";
1884
+ for (let index = 1; index < valueSource.length; index++) {
1885
+ const character = valueSource[index];
1886
+ if (character !== "'") {
1887
+ value += character;
1888
+ continue;
1767
1889
  }
1890
+ if (index === valueSource.length - 1) return [match[1], value];
1891
+ if (valueSource.slice(index + 1, index + 4) !== "\\''") return null;
1892
+ value += "'";
1893
+ index += 3;
1768
1894
  }
1769
- if (healthy.length === 0) {
1770
- const scanned = await scanPortsForOpenCode();
1771
- return scanned;
1772
- }
1773
- return healthy;
1895
+ return null;
1774
1896
  }
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()
1897
+ function parseSynchroniserEnv(stdout) {
1898
+ const values = {};
1899
+ for (const line of stdout.split("\n")) {
1900
+ if (line.trim() === "") continue;
1901
+ const assignment = parseSingleQuotedAssignment(line);
1902
+ if (!assignment) return null;
1903
+ values[assignment[0]] = assignment[1];
1904
+ }
1905
+ return values;
1906
+ }
1907
+ function runCommand(command, args, options) {
1908
+ return new Promise((resolve4) => {
1909
+ let child;
1910
+ let stdout = "";
1911
+ let stderr = "";
1912
+ let settled = false;
1913
+ const finish = (result) => {
1914
+ if (settled) return;
1915
+ settled = true;
1916
+ if (timer) clearTimeout(timer);
1917
+ resolve4(result);
1918
+ };
1919
+ try {
1920
+ child = spawn2(command, args, {
1921
+ env: options.env,
1922
+ stdio: ["ignore", "pipe", "pipe"]
1923
+ });
1924
+ } catch (error2) {
1925
+ resolve4({
1926
+ code: null,
1927
+ stdout,
1928
+ stderr: error2 instanceof Error ? error2.message : String(error2),
1929
+ timedOut: false
1930
+ });
1931
+ return;
1932
+ }
1933
+ child.stdout?.setEncoding("utf8");
1934
+ child.stdout?.on("data", (chunk) => {
1935
+ stdout += chunk;
1936
+ });
1937
+ child.stderr?.setEncoding("utf8");
1938
+ child.stderr?.on("data", (chunk) => {
1939
+ stderr += chunk;
1940
+ });
1941
+ child.once("error", (error2) => {
1942
+ finish({
1943
+ code: null,
1944
+ stdout,
1945
+ stderr: stderr === "" ? error2.message : `${stderr}
1946
+ ${error2.message}`,
1947
+ timedOut: false
1948
+ });
1949
+ });
1950
+ child.once("close", (code) => finish({ code, stdout, stderr, timedOut: false }));
1951
+ const timer = setTimeout(
1952
+ () => {
1953
+ child.kill("SIGKILL");
1954
+ finish({ code: null, stdout, stderr, timedOut: true });
1955
+ },
1956
+ Math.max(0, options.timeoutMs)
1957
+ );
1788
1958
  });
1789
- return child;
1790
1959
  }
1791
- function stopOpenCode(opencodeProcess) {
1792
- if (!opencodeProcess || !opencodeProcess.pid) {
1793
- return;
1960
+ async function ensureLitestreamConfig(options, env) {
1961
+ const configPath = options.litestreamConfig;
1962
+ if (!configPath) {
1963
+ markNoReplicate(options, "no Litestream configuration path was provided");
1964
+ reportRecord(
1965
+ "restore",
1966
+ "restore_misconfigured",
1967
+ "litestream_config_unavailable",
1968
+ null,
1969
+ options
1970
+ );
1971
+ return null;
1794
1972
  }
1795
1973
  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") {
1974
+ if (statSync2(configPath).size > 0) return configPath;
1975
+ } catch (error2) {
1976
+ if (!(error2 instanceof Error && "code" in error2 && error2.code === "ENOENT")) {
1977
+ options.log(
1978
+ `Could not inspect ${configPath}: ${error2 instanceof Error ? error2.message : String(error2)}`,
1979
+ "warn"
1980
+ );
1981
+ }
1982
+ }
1983
+ const rendered = await runSynchroniser(["litestream-config"], {
1984
+ timeoutMs: SESSION_DB_SYNCHRONISER_TIMEOUT_MS,
1985
+ env
1986
+ });
1987
+ logSynchroniserDiagnostics(rendered, options);
1988
+ if (rendered.timedOut || rendered.code !== 0) {
1989
+ options.log(
1990
+ `Could not generate ${configPath}: runner-synchroniser litestream-config failed (${commandError(rendered)})`,
1991
+ "error"
1992
+ );
1993
+ markNoReplicate(options, `could not generate ${configPath}`);
1994
+ reportRecord(
1995
+ "restore",
1996
+ "restore_misconfigured",
1997
+ "litestream_config_unavailable",
1998
+ null,
1999
+ options
2000
+ );
2001
+ return null;
2002
+ }
2003
+ try {
2004
+ mkdirSync(dirname2(configPath), { recursive: true });
2005
+ writeFileSync(configPath, rendered.stdout);
2006
+ } catch (error2) {
2007
+ options.log(
2008
+ `Could not write ${configPath}: ${error2 instanceof Error ? error2.message : String(error2)}`,
2009
+ "error"
2010
+ );
2011
+ markNoReplicate(options, `could not generate ${configPath}`);
2012
+ reportRecord(
2013
+ "restore",
2014
+ "restore_misconfigured",
2015
+ "litestream_config_unavailable",
2016
+ null,
2017
+ options
2018
+ );
2019
+ return null;
2020
+ }
2021
+ const version2 = await runCommand("litestream", ["version"], {
2022
+ env,
2023
+ timeoutMs: 1e4
2024
+ });
2025
+ const litestreamVersion = version2.code === 0 ? version2.stdout.trim() || "unknown" : "unknown";
2026
+ const regionEmpty = !/^\s*region:\s*\S+/m.test(rendered.stdout);
2027
+ options.log(
2028
+ `litestream ${litestreamVersion}; AWS_REGION=${env.AWS_REGION ?? "<unset>"} AWS_DEFAULT_REGION=${env.AWS_DEFAULT_REGION ?? "<unset>"}; rendered litestream.yml region empty: ${regionEmpty ? "yes" : "no"}`
2029
+ );
2030
+ return configPath;
2031
+ }
2032
+ function restoreGiveUp(options, reason, message, litestreamExitCode, outcome = "fresh_session_db") {
2033
+ discardSessionDbDebris(options);
2034
+ markNoReplicate(options, message);
2035
+ reportRecord("restore", outcome, reason, litestreamExitCode, options);
2036
+ }
2037
+ async function restoreSessionDb(options, configPath, env) {
2038
+ const restored = await runCommand(
2039
+ "litestream",
2040
+ ["restore", "-config", configPath, "-if-db-not-exists", "-if-replica-exists", options.dbPath],
2041
+ { env, timeoutMs: SESSION_DB_RESTORE_TIMEOUT_MS }
2042
+ );
2043
+ for (const line of splitDiagnostics(restored.stderr)) options.log(line, "warn");
2044
+ if (restored.timedOut || restored.code === 124 || restored.code === 137) {
2045
+ restoreGiveUp(
2046
+ options,
2047
+ "restore_deadline_exceeded",
2048
+ `SESSION-DB-RESTORE-TRUNCATED: litestream restore did not finish within ${SESSION_DB_RESTORE_TIMEOUT_MS}ms; opencode starts with a fresh session DB and nothing is replicated this boot`,
2049
+ restored.code ?? 124
2050
+ );
2051
+ return;
2052
+ }
2053
+ if (restored.code === null || restored.code === 125 || restored.code === 126 || restored.code === 127) {
2054
+ options.log(`litestream restore could not run (${commandError(restored)})`, "error");
2055
+ restoreGiveUp(
2056
+ options,
2057
+ "restore_tool_unusable",
2058
+ `restore tool is broken (${commandError(restored)}); opencode starts with a fresh session DB and nothing is replicated this boot`,
2059
+ restored.code
2060
+ );
2061
+ return;
2062
+ }
2063
+ const classified = await runSynchroniser(
2064
+ [
2065
+ "session-db-classify",
2066
+ String(restored.code ?? 1),
2067
+ "1",
2068
+ "--on-unusable-replica=leave",
2069
+ "--fresh-db-fallback"
2070
+ ],
2071
+ { timeoutMs: SESSION_DB_SYNCHRONISER_TIMEOUT_MS, env }
2072
+ );
2073
+ logSynchroniserDiagnostics(classified, options);
2074
+ const classifyCode = classified.code;
2075
+ switch (classifyCode) {
2076
+ case 0:
2077
+ return;
2078
+ case 31:
2079
+ acknowledgeSessionDbRecoveryReport(sessionDbRecoveryReportPath(homedir2(), env));
2080
+ options.log(
2081
+ "SESSION-DB-REPLICA-UNUSABLE: booting with a fresh opencode.db and replicating into the existing prefix this boot",
2082
+ "warn"
2083
+ );
2084
+ return;
2085
+ case 32:
2086
+ acknowledgeSessionDbRecoveryReport(sessionDbRecoveryReportPath(homedir2(), env));
2087
+ discardSessionDbDebris(options);
2088
+ markNoReplicate(
2089
+ options,
2090
+ "session-db-classify asked for another restore attempt (32), but this boot has budget for only one; treating it as a give-up rather than retrying"
2091
+ );
2092
+ return;
2093
+ case 30:
2094
+ restoreGiveUp(
2095
+ options,
2096
+ "classification_fatal",
2097
+ "session-db-classify returned fatal (30); see the FATAL message above",
2098
+ restored.code,
2099
+ "restore_misconfigured"
2100
+ );
2101
+ return;
2102
+ default:
2103
+ restoreGiveUp(
2104
+ options,
2105
+ "classification_unrecognised",
2106
+ `session-db-classify exited ${classifyCode ?? "null"}, which is none of its documented answers`,
2107
+ restored.code
2108
+ );
2109
+ }
2110
+ }
2111
+ async function verifySessionDb(options, configPath, env) {
2112
+ if (!options.noReplicateMarker || !fileExists(options.noReplicateMarker)) {
2113
+ const result = await runSynchroniser(["session-db-verify", configPath], {
2114
+ timeoutMs: SESSION_DB_VERIFY_TIMEOUT_MS,
2115
+ env: {
2116
+ ...env,
2117
+ // The synchroniser reads this value in SECONDS. Keep this at 120, not
2118
+ // 120_000, so the walkback gives up before the outer process bound.
2119
+ EVIDENT_SESSION_DB_WALKBACK_BUDGET_SECONDS: String(
2120
+ SESSION_DB_VERIFY_WALKBACK_BUDGET_SECONDS
2121
+ )
2122
+ }
2123
+ });
2124
+ logSynchroniserDiagnostics(result, options);
2125
+ if (result.timedOut || result.code === 124 || result.code === 137) {
2126
+ options.log(
2127
+ `SESSION-DB-VERIFY-TIMEOUT: verification did not finish within its ${SESSION_DB_VERIFY_TIMEOUT_MS}ms deadline; continuing with the restored opencode.db as-is, unverified`,
2128
+ "warn"
2129
+ );
2130
+ return false;
2131
+ }
2132
+ if (result.code === 34) {
2133
+ reportRecord(
2134
+ "verify",
2135
+ "session_db_boot_refused",
2136
+ result.stderr.includes("SESSION-DB-LOCAL-DISCARD-FAILED") ? "local_discard_failed" : "replica_separation_unproven",
2137
+ null,
2138
+ options
2139
+ );
2140
+ return true;
2141
+ }
2142
+ if (result.code === 33) {
2143
+ options.log(
2144
+ "SESSION-DB-INTEGRITY-EXHAUSTED: booting continues and litestream still replicates, starting an empty backup chain after the corrupt replica was separated.",
2145
+ "warn"
2146
+ );
2147
+ return false;
2148
+ }
2149
+ if (result.code !== 0) {
2150
+ options.log(
2151
+ `SESSION-DB-VERIFY-UNKNOWN: session-db-verify exited ${result.code ?? "null"}, which is none of its documented answers; continuing with the restored opencode.db as-is`,
2152
+ "warn"
2153
+ );
2154
+ }
2155
+ return false;
2156
+ }
2157
+ options.log(
2158
+ "skipping session-DB verification: this boot's session DB was not proven safe to replicate",
2159
+ "debug"
2160
+ );
2161
+ return false;
2162
+ }
2163
+ function fileExists(path) {
2164
+ try {
2165
+ statSync2(path);
2166
+ return true;
2167
+ } catch (error2) {
2168
+ if (error2 instanceof Error && "code" in error2 && error2.code === "ENOENT") return false;
2169
+ return true;
2170
+ }
2171
+ }
2172
+ async function restoreAndVerifySessionDb(options) {
2173
+ const env = options.env ?? process.env;
2174
+ clearMarker(options);
2175
+ acknowledgeSessionDbRecoveryReport(sessionDbRecoveryReportPath(homedir2(), env));
2176
+ const synchroniserEnv = await runSynchroniser(["env"], {
2177
+ timeoutMs: SESSION_DB_SYNCHRONISER_TIMEOUT_MS,
2178
+ env
2179
+ });
2180
+ logSynchroniserDiagnostics(synchroniserEnv, options);
2181
+ if (synchroniserEnv.timedOut || synchroniserEnv.code !== 0) {
2182
+ options.log(
2183
+ `runner-synchroniser env could not resolve the session-DB configuration (${commandError(synchroniserEnv)})`,
2184
+ "error"
2185
+ );
2186
+ markNoReplicate(
2187
+ options,
2188
+ "could not resolve the runner-synchroniser configuration (see the ERROR above)"
2189
+ );
2190
+ reportRecord(
2191
+ "restore",
2192
+ "restore_misconfigured",
2193
+ "synchroniser_config_unresolved",
2194
+ null,
2195
+ options
2196
+ );
2197
+ return { verifyFatal: false };
2198
+ }
2199
+ const values = parseSynchroniserEnv(synchroniserEnv.stdout);
2200
+ if (!values) {
2201
+ markNoReplicate(
2202
+ options,
2203
+ "the runner-synchroniser configuration could not be evaluated; the installed bundle likely does not match this hook"
2204
+ );
2205
+ reportRecord(
2206
+ "restore",
2207
+ "restore_misconfigured",
2208
+ "synchroniser_config_unevaluable",
2209
+ null,
2210
+ options
2211
+ );
2212
+ return { verifyFatal: false };
2213
+ }
2214
+ const synchroniserDbPath = values.OPENCODE_DB_PATH;
2215
+ if (!synchroniserDbPath) {
2216
+ markNoReplicate(
2217
+ options,
2218
+ "run_synchroniser env did not define OPENCODE_DB_PATH; the installed runner-synchroniser build likely does not match this hook"
2219
+ );
2220
+ reportRecord(
2221
+ "restore",
2222
+ "restore_misconfigured",
2223
+ "synchroniser_config_incomplete",
2224
+ null,
2225
+ options
2226
+ );
2227
+ return { verifyFatal: false };
2228
+ }
2229
+ if (resolvePath(synchroniserDbPath) !== resolvePath(options.dbPath)) {
2230
+ options.log(
2231
+ `runner-synchroniser reported OPENCODE_DB_PATH=${synchroniserDbPath}, but OpenCode uses ${options.dbPath}; continuing with OpenCode's session-DB path`,
2232
+ "warn"
2233
+ );
2234
+ }
2235
+ if (!values.PERSISTENCE_BUCKET) {
2236
+ options.log(
2237
+ "SESSION-DB-PERSISTENCE-DISABLED: LITESTREAM_BUCKET/LITESTREAM_PREFIX are not both set; opencode starts with a fresh session DB and nothing is replicated.",
2238
+ "warn"
2239
+ );
2240
+ return { verifyFatal: false };
2241
+ }
2242
+ const configPath = await ensureLitestreamConfig(options, env);
2243
+ if (!configPath) return { verifyFatal: false };
2244
+ await restoreSessionDb(options, configPath, env);
2245
+ if (options.noReplicateMarker && fileExists(options.noReplicateMarker)) {
2246
+ return { verifyFatal: false };
2247
+ }
2248
+ return { verifyFatal: await verifySessionDb(options, configPath, env) };
2249
+ }
2250
+
2251
+ // src/lib/opencode/session-db-provenance.ts
2252
+ import { createRequire } from "module";
2253
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
2254
+ import { dirname as dirname3, join as join3 } from "path";
2255
+ var require2 = createRequire(import.meta.url);
2256
+ function readSessionDbMigrationIds(dbPath) {
2257
+ let db;
2258
+ try {
2259
+ const { DatabaseSync } = require2("node:sqlite");
2260
+ db = new DatabaseSync(dbPath, { readOnly: true });
2261
+ const columns = db.prepare("PRAGMA table_info(migration)").all();
2262
+ const hasExpectedShape = columns.length === 2 && columns.some(
2263
+ (column) => column.name === "id" && typeof column.type === "string" && column.type.toUpperCase() === "TEXT" && column.pk === 1
2264
+ ) && columns.some(
2265
+ (column) => column.name === "time_completed" && typeof column.type === "string" && column.type.toUpperCase() === "INTEGER" && column.notnull === 1 && column.pk === 0
2266
+ );
2267
+ if (!hasExpectedShape) {
2268
+ console.warn(`[readSessionDbMigrationIds] unsupported migration table shape in ${dbPath}`);
2269
+ return null;
2270
+ }
2271
+ const rows = db.prepare("SELECT id FROM migration ORDER BY id").all();
2272
+ if (rows.some((row) => typeof row.id !== "string")) return null;
2273
+ return rows.map((row) => row.id);
2274
+ } catch (error2) {
2275
+ console.warn(
2276
+ `[readSessionDbMigrationIds] could not read migration history from ${dbPath}: ${error2 instanceof Error ? error2.message : String(error2)}`
2277
+ );
2278
+ return null;
2279
+ } finally {
2280
+ try {
2281
+ db?.close();
2282
+ } catch (error2) {
1803
2283
  console.warn(
1804
- `stopOpenCode: kill failed: ${err instanceof Error ? err.message : String(err)}`
2284
+ `[readSessionDbMigrationIds] could not close ${dbPath}: ${error2 instanceof Error ? error2.message : String(error2)}`
1805
2285
  );
1806
2286
  }
1807
2287
  }
1808
2288
  }
2289
+ function sessionDbProvenanceStatePath(homeDir, env) {
2290
+ const override = env.EVIDENT_SESSION_DB_PROVENANCE_STATE?.trim();
2291
+ return override || join3(homeDir, ".local", "state", "evident", "session-db-provenance.json");
2292
+ }
2293
+ function loadSessionDbProvenanceState(path) {
2294
+ let value;
2295
+ try {
2296
+ value = JSON.parse(readFileSync3(path, "utf8"));
2297
+ } catch (error2) {
2298
+ if (error2 instanceof Error && "code" in error2 && error2.code === "ENOENT") return {};
2299
+ console.error(
2300
+ `[session-db-provenance] could not read ${path}: ${error2 instanceof Error ? error2.message : String(error2)}`
2301
+ );
2302
+ return {};
2303
+ }
2304
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
2305
+ console.error(`[session-db-provenance] ignored malformed state in ${path}`);
2306
+ return {};
2307
+ }
2308
+ const state = {};
2309
+ for (const [dbPath, record] of Object.entries(value)) {
2310
+ if (!isSessionDbProvenanceRecord(record)) {
2311
+ console.error(`[session-db-provenance] ignored malformed state in ${path}`);
2312
+ return {};
2313
+ }
2314
+ state[dbPath] = record;
2315
+ }
2316
+ return state;
2317
+ }
2318
+ function saveSessionDbProvenanceState(path, state) {
2319
+ try {
2320
+ mkdirSync2(dirname3(path), { recursive: true });
2321
+ writeFileSync2(path, `${JSON.stringify(state, null, 2)}
2322
+ `, "utf8");
2323
+ } catch (error2) {
2324
+ console.error(
2325
+ `[session-db-provenance] could not write ${path}: ${error2 instanceof Error ? error2.message : String(error2)}`
2326
+ );
2327
+ }
2328
+ }
2329
+ function evaluateSessionDbProvenance(input) {
2330
+ const { currentVersion, currentIds, previous } = input;
2331
+ if (!previous) return { anomaly: false, reason: null };
2332
+ const current = new Set(currentIds);
2333
+ const prior = new Set(previous.migrationIds);
2334
+ for (const id of prior) {
2335
+ if (!current.has(id)) return { anomaly: true, reason: "migration-history-regressed" };
2336
+ }
2337
+ if (current.size > prior.size && previous.opencodeVersion === currentVersion) {
2338
+ return { anomaly: true, reason: "foreign-version-migrations" };
2339
+ }
2340
+ return { anomaly: false, reason: null };
2341
+ }
2342
+ function checkSessionDbProvenance(input) {
2343
+ const { dbPath, currentVersion, homeDir, env } = input;
2344
+ const path = sessionDbProvenanceStatePath(homeDir, env);
2345
+ const state = loadSessionDbProvenanceState(path);
2346
+ const previous = state[dbPath];
2347
+ const currentIds = readSessionDbMigrationIds(dbPath);
2348
+ if (currentIds === null) {
2349
+ return {
2350
+ anomaly: false,
2351
+ reason: null,
2352
+ recordedVersion: previous?.opencodeVersion ?? null,
2353
+ migrationDelta: null
2354
+ };
2355
+ }
2356
+ const decision = evaluateSessionDbProvenance({ currentVersion, currentIds, previous });
2357
+ const migrationDelta = previous ? new Set(currentIds).size - new Set(previous.migrationIds).size : null;
2358
+ state[dbPath] = {
2359
+ opencodeVersion: currentVersion,
2360
+ migrationIds: currentIds,
2361
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
2362
+ };
2363
+ saveSessionDbProvenanceState(path, state);
2364
+ return {
2365
+ ...decision,
2366
+ recordedVersion: previous?.opencodeVersion ?? null,
2367
+ migrationDelta
2368
+ };
2369
+ }
2370
+ function isSessionDbProvenanceRecord(value) {
2371
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
2372
+ const record = value;
2373
+ return typeof record.opencodeVersion === "string" && Array.isArray(record.migrationIds) && record.migrationIds.every((id) => typeof id === "string") && typeof record.updatedAt === "string";
2374
+ }
2375
+
2376
+ // src/lib/opencode/opencode-version-gate.ts
2377
+ var QUEUE_VALIDATED_OPENCODE_VERSIONS = ["1.17.11", "1.18.3"];
2378
+ function isQueueValidatedVersion(version2) {
2379
+ if (!version2) return false;
2380
+ return QUEUE_VALIDATED_OPENCODE_VERSIONS.includes(version2);
2381
+ }
2382
+ function buildOpenCodeVersionWarning(version2) {
2383
+ if (isQueueValidatedVersion(version2)) return null;
2384
+ const detected = version2 ? `v${version2}` : "unknown";
2385
+ const validated = QUEUE_VALIDATED_OPENCODE_VERSIONS.map((v) => `v${v}`).join(", ");
2386
+ 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.`;
2387
+ }
2388
+
2389
+ // src/lib/opencode/process.ts
2390
+ import { execSync, spawn as spawn3 } from "child_process";
2391
+
2392
+ // src/lib/process-stop.ts
2393
+ async function stopProcessAndWait(child, timeoutMs, sendTerm, sendKill) {
2394
+ if (!child.pid) {
2395
+ return { outcome: "not-running", code: child.exitCode, signal: child.signalCode };
2396
+ }
2397
+ if (child.exitCode !== null || child.signalCode !== null) {
2398
+ return { outcome: "exited", code: child.exitCode, signal: child.signalCode };
2399
+ }
2400
+ return new Promise((resolve4, reject) => {
2401
+ let forced = false;
2402
+ let settled = false;
2403
+ const timer = setTimeout(() => {
2404
+ forced = true;
2405
+ try {
2406
+ sendKill();
2407
+ } catch (error2) {
2408
+ if (error2.code === "ESRCH") {
2409
+ finish({ outcome: "exited", code: child.exitCode, signal: child.signalCode });
2410
+ } else {
2411
+ fail(error2);
2412
+ }
2413
+ }
2414
+ }, timeoutMs);
2415
+ const finish = (result) => {
2416
+ if (settled) return;
2417
+ settled = true;
2418
+ clearTimeout(timer);
2419
+ child.removeListener("exit", onExit);
2420
+ resolve4(result);
2421
+ };
2422
+ const fail = (error2) => {
2423
+ if (settled) return;
2424
+ settled = true;
2425
+ clearTimeout(timer);
2426
+ child.removeListener("exit", onExit);
2427
+ reject(error2);
2428
+ };
2429
+ const onExit = (code, signal) => {
2430
+ finish({ outcome: forced ? "killed" : "exited", code, signal });
2431
+ };
2432
+ child.once("exit", onExit);
2433
+ try {
2434
+ sendTerm();
2435
+ } catch (error2) {
2436
+ if (error2.code === "ESRCH") {
2437
+ finish({ outcome: "exited", code: child.exitCode, signal: child.signalCode });
2438
+ } else {
2439
+ fail(error2);
2440
+ }
2441
+ return;
2442
+ }
2443
+ });
2444
+ }
2445
+
2446
+ // src/lib/opencode/process.ts
2447
+ var OPENCODE_PORT_RANGE = [4096, 4097, 4098, 4099, 4100];
2448
+ function getProcessCwd(pid) {
2449
+ const platform = process.platform;
2450
+ try {
2451
+ if (platform === "darwin") {
2452
+ const output = execSync(`lsof -a -p ${pid} -d cwd -Fn 2>/dev/null`, {
2453
+ encoding: "utf-8",
2454
+ stdio: ["pipe", "pipe", "pipe"]
2455
+ }).trim();
2456
+ const lines = output.split("\n");
2457
+ for (const line of lines) {
2458
+ if (line.startsWith("n") && !line.startsWith("n ")) {
2459
+ return line.slice(1);
2460
+ }
2461
+ }
2462
+ } else if (platform === "linux") {
2463
+ const output = execSync(`readlink /proc/${pid}/cwd 2>/dev/null`, {
2464
+ encoding: "utf-8",
2465
+ stdio: ["pipe", "pipe", "pipe"]
2466
+ }).trim();
2467
+ if (output) return output;
2468
+ }
2469
+ } catch {
2470
+ }
2471
+ return void 0;
2472
+ }
2473
+ function isPortInUse(port) {
2474
+ const platform = process.platform;
2475
+ try {
2476
+ if (platform === "darwin" || platform === "linux") {
2477
+ execSync(`lsof -i :${port} -sTCP:LISTEN 2>/dev/null`, {
2478
+ encoding: "utf-8",
2479
+ stdio: ["pipe", "pipe", "pipe"]
2480
+ });
2481
+ return true;
2482
+ }
2483
+ } catch {
2484
+ }
2485
+ return false;
2486
+ }
2487
+ function findAvailablePort(startPort, maxAttempts = 10) {
2488
+ for (let i = 0; i < maxAttempts; i++) {
2489
+ const port = startPort + i;
2490
+ if (!isPortInUse(port)) {
2491
+ return port;
2492
+ }
2493
+ }
2494
+ return null;
2495
+ }
2496
+ function findOpenCodeProcesses() {
2497
+ const instances = [];
2498
+ try {
2499
+ const platform = process.platform;
2500
+ if (platform === "darwin" || platform === "linux") {
2501
+ let pids = [];
2502
+ try {
2503
+ const pgrepOutput = execSync('pgrep -f "opencode serve|opencode-serve"', {
2504
+ encoding: "utf-8",
2505
+ stdio: ["pipe", "pipe", "pipe"]
2506
+ }).trim();
2507
+ if (pgrepOutput) {
2508
+ pids = pgrepOutput.split("\n").map((p) => parseInt(p.trim(), 10)).filter((p) => !isNaN(p));
2509
+ }
2510
+ } catch {
2511
+ try {
2512
+ const psOutput = execSync('ps aux | grep -E "opencode (serve|--port)" | grep -v grep', {
2513
+ encoding: "utf-8",
2514
+ stdio: ["pipe", "pipe", "pipe"]
2515
+ }).trim();
2516
+ if (psOutput) {
2517
+ for (const line of psOutput.split("\n")) {
2518
+ const parts = line.trim().split(/\s+/);
2519
+ if (parts.length >= 2) {
2520
+ const pid = parseInt(parts[1], 10);
2521
+ if (!isNaN(pid)) pids.push(pid);
2522
+ }
2523
+ }
2524
+ }
2525
+ } catch (err) {
2526
+ console.warn(
2527
+ `findOpenCodeProcesses: ps fallback failed: ${err instanceof Error ? err.message : String(err)}`
2528
+ );
2529
+ }
2530
+ }
2531
+ for (const pid of pids) {
2532
+ try {
2533
+ const lsofOutput = execSync(`lsof -Pan -p ${pid} -i TCP -sTCP:LISTEN 2>/dev/null`, {
2534
+ encoding: "utf-8",
2535
+ stdio: ["pipe", "pipe", "pipe"]
2536
+ }).trim();
2537
+ for (const line of lsofOutput.split("\n")) {
2538
+ const portMatch = line.match(/:(\d+)\s+\(LISTEN\)/);
2539
+ if (portMatch) {
2540
+ const port = parseInt(portMatch[1], 10);
2541
+ if (!isNaN(port) && !instances.some((i) => i.port === port)) {
2542
+ const cwd = getProcessCwd(pid);
2543
+ instances.push({ pid, port, cwd });
2544
+ }
2545
+ }
2546
+ }
2547
+ } catch {
2548
+ }
2549
+ }
2550
+ }
2551
+ } catch (err) {
2552
+ console.warn(
2553
+ `findOpenCodeProcesses: process detection failed: ${err instanceof Error ? err.message : String(err)}`
2554
+ );
2555
+ }
2556
+ return instances;
2557
+ }
2558
+ async function scanPortsForOpenCode() {
2559
+ const instances = [];
2560
+ const checks = OPENCODE_PORT_RANGE.map(async (port) => {
2561
+ const health = await checkOpenCodeHealth(port);
2562
+ if (health.healthy) {
2563
+ let pid = 0;
2564
+ try {
2565
+ const lsofOutput = execSync(`lsof -ti :${port} -sTCP:LISTEN 2>/dev/null`, {
2566
+ encoding: "utf-8",
2567
+ stdio: ["pipe", "pipe", "pipe"]
2568
+ }).trim();
2569
+ if (lsofOutput) {
2570
+ pid = parseInt(lsofOutput.split("\n")[0], 10) || 0;
2571
+ }
2572
+ } catch {
2573
+ }
2574
+ const cwd = pid ? getProcessCwd(pid) : void 0;
2575
+ return { pid, port, cwd, version: health.version };
2576
+ }
2577
+ return null;
2578
+ });
2579
+ const results = await Promise.all(checks);
2580
+ for (const result of results) {
2581
+ if (result) {
2582
+ instances.push(result);
2583
+ }
2584
+ }
2585
+ return instances;
2586
+ }
2587
+ async function findHealthyOpenCodeInstances() {
2588
+ const processes = findOpenCodeProcesses();
2589
+ const healthy = [];
2590
+ for (const proc of processes) {
2591
+ const health = await checkOpenCodeHealth(proc.port);
2592
+ if (health.healthy) {
2593
+ healthy.push({ ...proc, version: health.version });
2594
+ }
2595
+ }
2596
+ if (healthy.length === 0) {
2597
+ const scanned = await scanPortsForOpenCode();
2598
+ return scanned;
2599
+ }
2600
+ return healthy;
2601
+ }
2602
+ async function startOpenCode(port, options = {}) {
2603
+ let command = "opencode";
2604
+ const printLogs = options.inheritStdio ? ["--print-logs"] : [];
2605
+ let args = ["serve", "--port", port.toString(), "--hostname", "127.0.0.1", ...printLogs];
2606
+ try {
2607
+ execSync("which opencode", { stdio: "ignore" });
2608
+ } catch {
2609
+ command = "npx";
2610
+ args = [
2611
+ "opencode",
2612
+ "serve",
2613
+ "--port",
2614
+ port.toString(),
2615
+ "--hostname",
2616
+ "127.0.0.1",
2617
+ ...printLogs
2618
+ ];
2619
+ }
2620
+ const child = spawn3(command, args, {
2621
+ detached: true,
2622
+ stdio: options.inheritStdio ? "inherit" : "ignore",
2623
+ cwd: process.cwd()
2624
+ });
2625
+ return child;
2626
+ }
2627
+ function stopOpenCodeAndWait(opencodeProcess, timeoutMs) {
2628
+ const sendSignal = (signal) => {
2629
+ if (process.platform === "win32") {
2630
+ opencodeProcess.kill(signal);
2631
+ } else {
2632
+ process.kill(-opencodeProcess.pid, signal);
2633
+ }
2634
+ };
2635
+ return stopProcessAndWait(
2636
+ opencodeProcess,
2637
+ timeoutMs,
2638
+ () => sendSignal("SIGTERM"),
2639
+ () => sendSignal("SIGKILL")
2640
+ );
2641
+ }
1809
2642
 
1810
2643
  // src/lib/opencode/install.ts
1811
2644
  import { execSync as execSync2 } from "child_process";
@@ -2091,6 +2924,7 @@ async function createOpenCodeSession(port, directory) {
2091
2924
  return data.id;
2092
2925
  }
2093
2926
  async function getModelAttachmentCapability(port, model) {
2927
+ const { model: baseModel } = splitModelVariant(model);
2094
2928
  try {
2095
2929
  const res = await timedFetch(`${opencodeBase(port)}/config/providers`);
2096
2930
  if (!res.ok) {
@@ -2107,9 +2941,9 @@ async function getModelAttachmentCapability(port, model) {
2107
2941
  );
2108
2942
  return null;
2109
2943
  }
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;
2944
+ const slash = baseModel ? baseModel.indexOf("/") : -1;
2945
+ const providerId = slash > 0 ? baseModel.slice(0, slash) : void 0;
2946
+ let modelId = slash > 0 ? baseModel.slice(slash + 1) : void 0;
2113
2947
  const defaults2 = body?.default && typeof body.default === "object" ? body.default : void 0;
2114
2948
  let provider = providerId ? providers.find((p) => p?.id === providerId) : void 0;
2115
2949
  if (!provider && !providerId) {
@@ -2189,6 +3023,29 @@ async function buildFileParts(attachments, capable) {
2189
3023
  }
2190
3024
  return { parts, outcomes, capabilityUnknown };
2191
3025
  }
3026
+ function splitModelVariant(raw) {
3027
+ const value = raw?.trim();
3028
+ if (!value) return {};
3029
+ const hashIndex = value.indexOf("#");
3030
+ if (hashIndex === -1) return { model: value };
3031
+ const model = value.slice(0, hashIndex).trim() || void 0;
3032
+ const variant = value.slice(hashIndex + 1).trim() || void 0;
3033
+ return { model, variant };
3034
+ }
3035
+ function applyModelOptions(body, options) {
3036
+ if (options?.agent) body.agent = options.agent;
3037
+ const { model, variant } = splitModelVariant(options?.model);
3038
+ if (model) {
3039
+ const slashIndex = model.indexOf("/");
3040
+ if (slashIndex !== -1) {
3041
+ body.model = {
3042
+ providerID: model.substring(0, slashIndex),
3043
+ modelID: model.substring(slashIndex + 1)
3044
+ };
3045
+ }
3046
+ }
3047
+ if (variant) body.variant = variant;
3048
+ }
2192
3049
  function messageText(m) {
2193
3050
  if (!m || !Array.isArray(m.parts)) return "";
2194
3051
  return m.parts.filter((p) => p.type === "text" && typeof p.text === "string").map((p) => p.text).join("");
@@ -2213,18 +3070,7 @@ async function sendPromptAsync(port, sessionId, content, options, attachments) {
2213
3070
  const body = {
2214
3071
  parts
2215
3072
  };
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
- }
3073
+ applyModelOptions(body, options);
2228
3074
  const res = await timedFetch(`${opencodeBase(port)}/session/${sessionId}/prompt_async`, {
2229
3075
  method: "POST",
2230
3076
  headers: { "Content-Type": "application/json" },
@@ -2232,7 +3078,10 @@ async function sendPromptAsync(port, sessionId, content, options, attachments) {
2232
3078
  });
2233
3079
  if (res.status < 200 || res.status >= 300) {
2234
3080
  const text = await res.text().catch(() => "");
2235
- throw new Error(`OpenCode prompt_async failed: HTTP ${res.status}${text ? `: ${text}` : ""}`);
3081
+ const { variant } = splitModelVariant(options?.model);
3082
+ throw new Error(
3083
+ `OpenCode prompt_async failed: HTTP ${res.status}${text ? `: ${text}` : ""}${variant ? ` (variant: ${variant})` : ""}`
3084
+ );
2236
3085
  }
2237
3086
  const READ_BACK_ATTEMPTS = 5;
2238
3087
  const READ_BACK_DELAY_MS = 150;
@@ -2256,7 +3105,7 @@ async function sendPromptAsync(port, sessionId, content, options, attachments) {
2256
3105
  }
2257
3106
  }
2258
3107
  if (attempt < READ_BACK_ATTEMPTS - 1) {
2259
- await new Promise((resolve3) => setTimeout(resolve3, READ_BACK_DELAY_MS));
3108
+ await new Promise((resolve4) => setTimeout(resolve4, READ_BACK_DELAY_MS));
2260
3109
  }
2261
3110
  }
2262
3111
  return null;
@@ -2387,7 +3236,7 @@ function isPreamblePinnedRunning(messages, userMessageId) {
2387
3236
  return completedOf(reply) != null && finishOf(reply) === "tool-calls";
2388
3237
  }
2389
3238
  function isB2AbandonmentConfirmed(params) {
2390
- return params.pinnedForMs >= params.minPinnedMs && params.descendantOngoing === false;
3239
+ return params.pinnedForMs >= params.minPinnedMs && params.descendantOngoing === false && params.rootOngoing === false;
2391
3240
  }
2392
3241
  function isAmbiguousTerminalFinish(m) {
2393
3242
  if (completedOf(m) == null) return false;
@@ -2400,7 +3249,7 @@ function isAmbiguousFinishPinnedRunning(messages, userMessageId) {
2400
3249
  return isAmbiguousTerminalFinish(reply);
2401
3250
  }
2402
3251
  function isAmbiguousFinishResolved(params) {
2403
- return params.sessionOngoing === false || params.pinnedForMs >= params.maxPinnedMs;
3252
+ return params.sessionOngoing === false || params.sessionOngoing !== true && params.pinnedForMs >= params.maxPinnedMs;
2404
3253
  }
2405
3254
  function messageError(messages, userMessageId) {
2406
3255
  const reply = findLastAssistantReplyFor(messages, userMessageId);
@@ -2609,13 +3458,13 @@ function resolveSessionCleanupConfig(flags, env = process.env) {
2609
3458
  }
2610
3459
 
2611
3460
  // src/lib/opencode/session-db-size.ts
2612
- import { statSync as statSync2 } from "fs";
2613
- import { join as join3 } from "path";
3461
+ import { statSync as statSync3 } from "fs";
3462
+ import { join as join4 } from "path";
2614
3463
  var LARGE_DB_THRESHOLD_BYTES = 268435456;
2615
3464
  function statSessionDbBytes(homeDir) {
2616
- const dbPath = join3(homeDir, ".local", "share", "opencode", "opencode.db");
3465
+ const dbPath = join4(homeDir, ".local", "share", "opencode", "opencode.db");
2617
3466
  try {
2618
- return statSync2(dbPath).size;
3467
+ return statSync3(dbPath).size;
2619
3468
  } catch (err) {
2620
3469
  const isMissingFile = err instanceof Error && "code" in err && err.code === "ENOENT";
2621
3470
  if (!isMissingFile) {
@@ -2641,11 +3490,11 @@ function buildSessionStoreSizeWarning(input) {
2641
3490
  }
2642
3491
 
2643
3492
  // src/lib/opencode/session-db-reclaim.ts
2644
- import { statSync as statSync3, statfsSync } from "fs";
2645
- import { dirname as dirname2 } from "path";
3493
+ import { statSync as statSync4, statfsSync } from "fs";
3494
+ import { dirname as dirname4 } from "path";
2646
3495
  function insufficientSpaceReason(dbPath, requiredBytes) {
2647
3496
  try {
2648
- const fsStats = statfsSync(dirname2(dbPath));
3497
+ const fsStats = statfsSync(dirname4(dbPath));
2649
3498
  const availableBytes = fsStats.bavail * fsStats.bsize;
2650
3499
  if (availableBytes < requiredBytes) {
2651
3500
  return `only ${availableBytes} bytes free, need ${requiredBytes} for a second copy`;
@@ -2714,7 +3563,7 @@ async function reclaimSessionDbSpace(input) {
2714
3563
  );
2715
3564
  return { ok: false, skipped: "full-vacuum-blocked" };
2716
3565
  }
2717
- const fileBytesForGuard = statSync3(dbPath).size;
3566
+ const fileBytesForGuard = statSync4(dbPath).size;
2718
3567
  const skipReason = insufficientSpaceReason(dbPath, fileBytesForGuard);
2719
3568
  if (skipReason !== null) {
2720
3569
  console.warn(
@@ -2842,12 +3691,12 @@ var StreamForwarder = class {
2842
3691
  let endBody;
2843
3692
  if (has_body) {
2844
3693
  const chunks = [];
2845
- bodyPromise = new Promise((resolve3) => {
3694
+ bodyPromise = new Promise((resolve4) => {
2846
3695
  pushBody = (buf) => {
2847
3696
  chunks.push(buf);
2848
3697
  };
2849
3698
  endBody = () => {
2850
- resolve3(Buffer.concat(chunks));
3699
+ resolve4(Buffer.concat(chunks));
2851
3700
  };
2852
3701
  });
2853
3702
  }
@@ -2976,7 +3825,7 @@ function connectTunnel(options) {
2976
3825
  } = options;
2977
3826
  const tunnelUrl = getTunnelUrlConfig();
2978
3827
  const url = `${tunnelUrl}/tunnel/${agentId}/connect`;
2979
- return new Promise((resolve3, reject) => {
3828
+ return new Promise((resolve4, reject) => {
2980
3829
  const ws = new WebSocket2(url, {
2981
3830
  headers: {
2982
3831
  Authorization: authHeader
@@ -3027,8 +3876,8 @@ function connectTunnel(options) {
3027
3876
  try {
3028
3877
  message = JSON.parse(data.toString());
3029
3878
  } catch (error2) {
3030
- const errorMessage = error2 instanceof Error ? error2.message : "Unknown error";
3031
- onError?.(`Failed to handle message: ${errorMessage}`);
3879
+ const errorMessage2 = error2 instanceof Error ? error2.message : "Unknown error";
3880
+ onError?.(`Failed to handle message: ${errorMessage2}`);
3032
3881
  return;
3033
3882
  }
3034
3883
  if (isStreamFrame(message)) {
@@ -3040,7 +3889,7 @@ function connectTunnel(options) {
3040
3889
  clearTimeout(connectionTimeout);
3041
3890
  const connectedAgentId = message.agent_id ?? agentId;
3042
3891
  onConnected?.(connectedAgentId);
3043
- resolve3({
3892
+ resolve4({
3044
3893
  ws,
3045
3894
  close: () => ws.close(1e3, "CLI shutdown")
3046
3895
  });
@@ -3170,22 +4019,64 @@ var RunnerConnection = class {
3170
4019
  }
3171
4020
  };
3172
4021
 
3173
- // src/lib/tunnel/ready-marker.ts
3174
- import { writeFileSync } from "fs";
3175
- function writeTunnelReadyMarker(path, agentId) {
4022
+ // src/lib/tunnel/ready-marker.ts
4023
+ import { writeFileSync as writeFileSync3 } from "fs";
4024
+ function writeTunnelReadyMarker(path, agentId) {
4025
+ try {
4026
+ writeFileSync3(path, `${agentId}
4027
+ `);
4028
+ return { ok: true };
4029
+ } catch (error2) {
4030
+ return { ok: false, error: error2 instanceof Error ? error2.message : String(error2) };
4031
+ }
4032
+ }
4033
+
4034
+ // src/lib/replication.ts
4035
+ import { spawn as spawn4 } from "child_process";
4036
+ function startSessionDbReplication(configPath) {
4037
+ return spawn4("litestream", ["replicate", "-config", configPath], {
4038
+ stdio: "inherit"
4039
+ });
4040
+ }
4041
+ async function stopSessionDbReplication(child, timeoutMs) {
4042
+ return stopProcessAndWait(
4043
+ child,
4044
+ timeoutMs,
4045
+ () => child.kill("SIGTERM"),
4046
+ () => child.kill("SIGKILL")
4047
+ );
4048
+ }
4049
+
4050
+ // src/lib/process-liveness.ts
4051
+ import { readFileSync as readFileSync4 } from "fs";
4052
+ function isProcessAlive(pid) {
3176
4053
  try {
3177
- writeFileSync(path, `${agentId}
3178
- `);
3179
- return { ok: true };
4054
+ process.kill(pid, 0);
3180
4055
  } catch (error2) {
3181
- return { ok: false, error: error2 instanceof Error ? error2.message : String(error2) };
4056
+ const code = error2.code;
4057
+ if (code === "ESRCH") return false;
4058
+ if (code === "EPERM") return true;
4059
+ console.error(
4060
+ `[process-liveness] could not probe process ${pid}: ${error2 instanceof Error ? error2.message : String(error2)}`
4061
+ );
4062
+ return false;
4063
+ }
4064
+ if (process.platform !== "linux") return true;
4065
+ try {
4066
+ const status2 = readFileSync4(`/proc/${pid}/status`, "utf8");
4067
+ return !/^State:\s+Z(?:\s|$)/m.test(status2);
4068
+ } catch (error2) {
4069
+ console.error(
4070
+ `[process-liveness] could not inspect /proc/${pid}/status: ${error2 instanceof Error ? error2.message : String(error2)}`
4071
+ );
4072
+ return true;
3182
4073
  }
3183
4074
  }
3184
4075
 
3185
4076
  // 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";
4077
+ import { readFileSync as readFileSync5 } from "fs";
4078
+ import { homedir as homedir3 } from "os";
4079
+ import { join as join5 } from "path";
3189
4080
  var CODEX_RESPONSES_URL = "https://chatgpt.com/backend-api/codex/responses";
3190
4081
  var OPENCODE_AUTH_SEGMENTS = [".local", "share", "opencode", "auth.json"];
3191
4082
  var OpenAiUsageError = class extends Error {
@@ -3199,7 +4090,7 @@ function isLocalCredentialProblem2(err) {
3199
4090
  }
3200
4091
  function readOpenCodeChatGptCredentials() {
3201
4092
  try {
3202
- const raw = readFileSync3(join4(homedir2(), ...OPENCODE_AUTH_SEGMENTS), "utf-8");
4093
+ const raw = readFileSync5(join5(homedir3(), ...OPENCODE_AUTH_SEGMENTS), "utf-8");
3203
4094
  let parsed;
3204
4095
  try {
3205
4096
  parsed = JSON.parse(raw);
@@ -3221,6 +4112,23 @@ function readOpenCodeChatGptCredentials() {
3221
4112
  return null;
3222
4113
  }
3223
4114
  }
4115
+ function parseChatGptIdentity(accessToken) {
4116
+ const segments = accessToken.split(".");
4117
+ if (segments.length !== 3) return null;
4118
+ let payload;
4119
+ try {
4120
+ const parsed = JSON.parse(Buffer.from(segments[1], "base64url").toString("utf8"));
4121
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return null;
4122
+ payload = parsed;
4123
+ } catch {
4124
+ return null;
4125
+ }
4126
+ const profile = payload["https://api.openai.com/profile"];
4127
+ const auth = payload["https://api.openai.com/auth"];
4128
+ const ownerEmail = typeof profile?.email === "string" ? profile.email.trim() || null : null;
4129
+ const planType = typeof auth?.chatgpt_plan_type === "string" ? auth.chatgpt_plan_type.trim() || null : null;
4130
+ return ownerEmail === null && planType === null ? null : { ownerEmail, planType };
4131
+ }
3224
4132
  function toWindow2(headers, name) {
3225
4133
  const utilizationHeader = headers.get(`x-codex-${name}-used-percent`);
3226
4134
  const windowMinutesHeader = headers.get(`x-codex-${name}-window-minutes`);
@@ -3296,6 +4204,7 @@ async function getOpenAiUsage(port) {
3296
4204
  "credentials_expired"
3297
4205
  );
3298
4206
  }
4207
+ const subscription = parseChatGptIdentity(credentials2.accessToken);
3299
4208
  const models = await resolveProbeModels(port);
3300
4209
  if (models.length === 0) {
3301
4210
  throw new OpenAiUsageError("No supported OpenAI probe model is available.", "no_probe_model");
@@ -3328,7 +4237,7 @@ async function getOpenAiUsage(port) {
3328
4237
  "no_usable_window"
3329
4238
  );
3330
4239
  }
3331
- return usage;
4240
+ return { ...usage, subscription };
3332
4241
  }
3333
4242
  if (res.status === 401) {
3334
4243
  throw new OpenAiUsageError(
@@ -3529,58 +4438,97 @@ function readDisk(homeDir) {
3529
4438
  };
3530
4439
  }
3531
4440
  }
3532
- function createResourceUsageCollector(homeDir) {
3533
- let previous = readCpuSample();
3534
- return async () => {
4441
+ var CPU_PEAK_WINDOW_MS = 6e4;
4442
+ var CPU_PEAK_WINDOW_SAMPLE_COUNT = 4;
4443
+ var CPU_PEAK_SAMPLE_INTERVAL_MS = CPU_PEAK_WINDOW_MS / CPU_PEAK_WINDOW_SAMPLE_COUNT;
4444
+ function createCpuPeakSampler() {
4445
+ const sampleHistory = new Array(CPU_PEAK_WINDOW_SAMPLE_COUNT);
4446
+ sampleHistory[0] = readCpuSample();
4447
+ let nextSampleIndex = 1;
4448
+ let sampleCount = 1;
4449
+ let peak = null;
4450
+ const timer = setInterval(() => {
3535
4451
  const current = readCpuSample();
3536
- const hostCpuPercent = cpuPercentBetween(previous, current);
3537
- const hostCpuCount = cpus().length;
3538
- previous = current;
3539
- const disk = readDisk(homeDir);
3540
- const opencodeDbBytes = statSessionDbBytes(homeDir);
3541
- const { limits, warning: ecsWarning } = await readEcsTaskLimits(process.env);
3542
- const warnings = [];
3543
- if (disk.warning) warnings.push(disk.warning);
3544
- if (ecsWarning) warnings.push(ecsWarning);
3545
- let cpuPercent = hostCpuPercent;
3546
- let cpuCount = hostCpuCount;
3547
- let memoryTotalBytes = totalmem();
3548
- let memoryAvailableBytes = freemem();
3549
- if (limits !== null) {
3550
- cpuCount = limits.cpuCount;
3551
- memoryTotalBytes = limits.memoryTotalBytes;
3552
- memoryAvailableBytes = clamp(
3553
- limits.memoryTotalBytes - (totalmem() - freemem()),
3554
- 0,
3555
- limits.memoryTotalBytes
3556
- );
3557
- cpuPercent = hostCpuPercent === null ? null : clamp(round2(hostCpuPercent * hostCpuCount / limits.cpuCount), 0, 100);
4452
+ const sampleFromWindowAgo = sampleCount === CPU_PEAK_WINDOW_SAMPLE_COUNT ? sampleHistory[nextSampleIndex] : void 0;
4453
+ if (sampleFromWindowAgo !== void 0) {
4454
+ const percentage = cpuPercentBetween(sampleFromWindowAgo, current);
4455
+ if (percentage !== null) {
4456
+ peak = peak === null ? percentage : Math.max(peak, percentage);
4457
+ }
3558
4458
  }
3559
- return {
3560
- usage: {
3561
- cpuPercent,
3562
- cpuCount,
3563
- memoryTotalBytes,
3564
- memoryAvailableBytes,
3565
- diskTotalBytes: disk.totalBytes,
3566
- diskFreeBytes: disk.freeBytes,
3567
- opencodeDbBytes
3568
- },
3569
- warnings
3570
- };
4459
+ sampleHistory[nextSampleIndex] = current;
4460
+ nextSampleIndex = (nextSampleIndex + 1) % CPU_PEAK_WINDOW_SAMPLE_COUNT;
4461
+ sampleCount = Math.min(sampleCount + 1, CPU_PEAK_WINDOW_SAMPLE_COUNT);
4462
+ }, CPU_PEAK_SAMPLE_INTERVAL_MS);
4463
+ return {
4464
+ takeAndReset: () => {
4465
+ const currentPeak = peak;
4466
+ peak = null;
4467
+ return currentPeak;
4468
+ },
4469
+ stop: () => clearInterval(timer)
4470
+ };
4471
+ }
4472
+ function createResourceUsageCollector(homeDir) {
4473
+ let previous = readCpuSample();
4474
+ const cpuPeakSampler = createCpuPeakSampler();
4475
+ return {
4476
+ collect: async () => {
4477
+ const current = readCpuSample();
4478
+ const hostCpuPercent = cpuPercentBetween(previous, current);
4479
+ const hostCpuPeakPercent = cpuPeakSampler.takeAndReset();
4480
+ const hostCpuCount = cpus().length;
4481
+ previous = current;
4482
+ const disk = readDisk(homeDir);
4483
+ const opencodeDbBytes = statSessionDbBytes(homeDir);
4484
+ const { limits, warning: ecsWarning } = await readEcsTaskLimits(process.env);
4485
+ const warnings = [];
4486
+ if (disk.warning) warnings.push(disk.warning);
4487
+ if (ecsWarning) warnings.push(ecsWarning);
4488
+ let cpuPercent = hostCpuPercent;
4489
+ let cpuPeakPercent = hostCpuPeakPercent;
4490
+ let cpuCount = hostCpuCount;
4491
+ let memoryTotalBytes = totalmem();
4492
+ let memoryAvailableBytes = freemem();
4493
+ if (limits !== null) {
4494
+ cpuCount = limits.cpuCount;
4495
+ memoryTotalBytes = limits.memoryTotalBytes;
4496
+ memoryAvailableBytes = clamp(
4497
+ limits.memoryTotalBytes - (totalmem() - freemem()),
4498
+ 0,
4499
+ limits.memoryTotalBytes
4500
+ );
4501
+ cpuPercent = hostCpuPercent === null ? null : clamp(round2(hostCpuPercent * hostCpuCount / limits.cpuCount), 0, 100);
4502
+ cpuPeakPercent = hostCpuPeakPercent === null ? null : clamp(round2(hostCpuPeakPercent * hostCpuCount / limits.cpuCount), 0, 100);
4503
+ }
4504
+ return {
4505
+ usage: {
4506
+ cpuPercent,
4507
+ cpuPeakPercent,
4508
+ cpuCount,
4509
+ memoryTotalBytes,
4510
+ memoryAvailableBytes,
4511
+ diskTotalBytes: disk.totalBytes,
4512
+ diskFreeBytes: disk.freeBytes,
4513
+ opencodeDbBytes
4514
+ },
4515
+ warnings
4516
+ };
4517
+ },
4518
+ stop: cpuPeakSampler.stop
3571
4519
  };
3572
4520
  }
3573
4521
 
3574
4522
  // src/lib/channels/driver.ts
3575
- import { homedir as homedir3 } from "os";
4523
+ import { homedir as homedir4 } from "os";
3576
4524
 
3577
4525
  // src/lib/runner-file-sync.ts
3578
- import { join as join6 } from "path";
4526
+ import { join as join7 } from "path";
3579
4527
 
3580
4528
  // src/lib/file-push.ts
3581
4529
  import { randomUUID } from "crypto";
3582
4530
  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";
4531
+ import { basename, dirname as dirname5, isAbsolute, join as join6, relative, resolve as resolve2, sep } from "path";
3584
4532
  var FILE_MODE = 384;
3585
4533
  var DIRECTORY_MODE = 448;
3586
4534
  async function writePushedFile(request) {
@@ -3611,9 +4559,9 @@ async function writePushedFile(request) {
3611
4559
  }
3612
4560
  try {
3613
4561
  const { existingAncestor, missingSegments } = await resolveNearestExistingAncestor(
3614
- dirname3(candidate)
4562
+ dirname5(candidate)
3615
4563
  );
3616
- const realTarget = join5(existingAncestor, ...missingSegments, basename(candidate));
4564
+ const realTarget = join6(existingAncestor, ...missingSegments, basename(candidate));
3617
4565
  const allowedDirectory = await findContainingAllowedDirectory(allowedDirectories, realTarget);
3618
4566
  if (allowedDirectory === null) {
3619
4567
  return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
@@ -3623,8 +4571,8 @@ async function writePushedFile(request) {
3623
4571
  }
3624
4572
  if (missingSegments.length > 0) {
3625
4573
  await createMissingDirectories(existingAncestor, missingSegments);
3626
- const realParent = await realpath(dirname3(realTarget));
3627
- if (realParent !== dirname3(realTarget) || !contains(allowedDirectory, realTarget)) {
4574
+ const realParent = await realpath(dirname5(realTarget));
4575
+ if (realParent !== dirname5(realTarget) || !contains(allowedDirectory, realTarget)) {
3628
4576
  return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
3629
4577
  path: realTarget,
3630
4578
  bytes,
@@ -3649,7 +4597,7 @@ function expandAndValidate(requestedPath, homeDir) {
3649
4597
  if (requestedPath.trim() === "" || requestedPath.includes("\0")) {
3650
4598
  return null;
3651
4599
  }
3652
- const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join5(homeDir, requestedPath.slice(2)) : requestedPath;
4600
+ const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join6(homeDir, requestedPath.slice(2)) : requestedPath;
3653
4601
  if (expanded.split(/[/\\]/).includes("..")) {
3654
4602
  return null;
3655
4603
  }
@@ -3667,7 +4615,7 @@ async function resolveNearestExistingAncestor(directory) {
3667
4615
  try {
3668
4616
  return { existingAncestor: await realpath(current), missingSegments };
3669
4617
  } catch (err) {
3670
- const parent = dirname3(current);
4618
+ const parent = dirname5(current);
3671
4619
  if (err.code !== "ENOENT" || parent === current) {
3672
4620
  throw err;
3673
4621
  }
@@ -3722,13 +4670,13 @@ function contains(realDirectory, realTarget) {
3722
4670
  async function createMissingDirectories(existingAncestor, missingSegments) {
3723
4671
  let current = existingAncestor;
3724
4672
  for (const segment of missingSegments) {
3725
- current = join5(current, segment);
4673
+ current = join6(current, segment);
3726
4674
  await mkdir(current, { recursive: true, mode: DIRECTORY_MODE });
3727
4675
  await chmod(current, DIRECTORY_MODE);
3728
4676
  }
3729
4677
  }
3730
4678
  async function writeAtomically(realTarget, content) {
3731
- const temporaryPath = join5(dirname3(realTarget), `.evident-push-${randomUUID()}.tmp`);
4679
+ const temporaryPath = join6(dirname5(realTarget), `.evident-push-${randomUUID()}.tmp`);
3732
4680
  let handle;
3733
4681
  try {
3734
4682
  handle = await open2(temporaryPath, "wx", FILE_MODE);
@@ -3858,12 +4806,12 @@ var NOT_APPLIED = {
3858
4806
  opencodeAuthApplied: false
3859
4807
  };
3860
4808
  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);
4809
+ const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join7(homeDir, requestedPath.slice(2)) : requestedPath;
4810
+ return expanded === join7(homeDir, ...CLAUDE_CREDENTIALS_SEGMENTS);
3863
4811
  }
3864
4812
  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);
4813
+ const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join7(homeDir, requestedPath.slice(2)) : requestedPath;
4814
+ return expanded === join7(homeDir, ...OPENCODE_AUTH_SEGMENTS);
3867
4815
  }
3868
4816
  async function applyOne(options, file) {
3869
4817
  const label = `${file.id.slice(0, 8)} (${file.path})`;
@@ -4390,6 +5338,7 @@ var ChannelDriver = class _ChannelDriver {
4390
5338
  * and stops opencode.
4391
5339
  */
4392
5340
  stopped = false;
5341
+ recycleRequestedFlag = false;
4393
5342
  constructor(config) {
4394
5343
  this.agentId = config.agentId;
4395
5344
  this.port = config.port;
@@ -4409,7 +5358,7 @@ var ChannelDriver = class _ChannelDriver {
4409
5358
  this.stuckQueuedMs = config.stuckQueuedMs ?? DEFAULT_STUCK_QUEUED_MS;
4410
5359
  this.now = config.now ?? (() => Date.now());
4411
5360
  this.fileSyncDirectories = config.fileSyncDirectories ?? [];
4412
- this.homeDir = config.homeDir ?? homedir3();
5361
+ this.homeDir = config.homeDir ?? homedir4();
4413
5362
  this.maxActiveSessions = config.maxActiveSessions;
4414
5363
  this.watcherStallMs = config.watcherStallMs ?? WATCHER_STALL_MS;
4415
5364
  this.wedgeWarningIntervalMs = config.wedgeWarningIntervalMs ?? WEDGE_WARNING_INTERVAL_MS;
@@ -4495,6 +5444,9 @@ var ChannelDriver = class _ChannelDriver {
4495
5444
  let dispatched = 0;
4496
5445
  try {
4497
5446
  const conversations = await this.getPendingConversations();
5447
+ if (this.recycleRequestedFlag) {
5448
+ this.stop();
5449
+ }
4498
5450
  if (conversations.length > 0) {
4499
5451
  const total = conversations.reduce((sum, c) => sum + (c.pending_message_count ?? 0), 0);
4500
5452
  this.log({
@@ -4623,6 +5575,14 @@ var ChannelDriver = class _ChannelDriver {
4623
5575
  stop() {
4624
5576
  this.stopped = true;
4625
5577
  }
5578
+ /**
5579
+ * The server clears this request when a new MicroVM identity is recorded, so a
5580
+ * same-VM tunnel reconnect does not consume it. This is a plain read rather
5581
+ * than a consume; `run.ts` guards the action once-only.
5582
+ */
5583
+ get recycleRequested() {
5584
+ return this.recycleRequestedFlag;
5585
+ }
4626
5586
  /**
4627
5587
  * Wait (up to `timeoutMs`) for in-flight watcher work to settle during a
4628
5588
  * graceful shutdown, so a turn whose reply is ready — or completes within the
@@ -4760,7 +5720,7 @@ var ChannelDriver = class _ChannelDriver {
4760
5720
  this.signalDispatchNotStarted(conv, message, "session_existence_unknown");
4761
5721
  break;
4762
5722
  }
4763
- const errorMessage = err instanceof Error ? err.message : String(err);
5723
+ const errorMessage2 = err instanceof Error ? err.message : String(err);
4764
5724
  this.sessions.delete(conv.id);
4765
5725
  this.supersede(conv.id, sessionId);
4766
5726
  this.log({
@@ -4769,7 +5729,7 @@ var ChannelDriver = class _ChannelDriver {
4769
5729
  conversation_id: conv.id,
4770
5730
  message_id: message.id
4771
5731
  });
4772
- await this.markFailed(conv.id, message.id, null, errorMessage).catch((markErr) => {
5732
+ await this.markFailed(conv.id, message.id, null, errorMessage2).catch((markErr) => {
4773
5733
  this.log({
4774
5734
  level: "warn",
4775
5735
  message: `markFailed PATCH for message ${message.id.slice(0, 8)} (conversation ${conv.id.slice(0, 8)}) failed (best-effort, not retried): ${markErr instanceof Error ? markErr.message : String(markErr)}`,
@@ -4780,7 +5740,7 @@ var ChannelDriver = class _ChannelDriver {
4780
5740
  });
4781
5741
  this.log({
4782
5742
  level: "error",
4783
- message: `Message ${message.id.slice(0, 8)} dispatch failed: ${errorMessage}`,
5743
+ message: `Message ${message.id.slice(0, 8)} dispatch failed: ${errorMessage2}`,
4784
5744
  conversation_id: conv.id,
4785
5745
  message_id: message.id
4786
5746
  });
@@ -4801,14 +5761,14 @@ var ChannelDriver = class _ChannelDriver {
4801
5761
  this.unconfirmedDispatchFailures.delete(message.id);
4802
5762
  this.sessions.delete(conv.id);
4803
5763
  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.`;
5764
+ const errorMessage2 = `OpenCode accepted this message ${streak} times in a row but never confirmed its assigned id (session ${sessionId.slice(0, 8)}'s message list could not be read back) \u2014 the session was abandoned; a fresh one is used for further messages.`;
4805
5765
  this.log({
4806
5766
  level: "error",
4807
- message: errorMessage,
5767
+ message: errorMessage2,
4808
5768
  conversation_id: conv.id,
4809
5769
  message_id: message.id
4810
5770
  });
4811
- await this.markFailed(conv.id, message.id, null, errorMessage).catch((markErr) => {
5771
+ await this.markFailed(conv.id, message.id, null, errorMessage2).catch((markErr) => {
4812
5772
  this.log({
4813
5773
  level: "warn",
4814
5774
  message: `markFailed PATCH for message ${message.id.slice(0, 8)} (conversation ${conv.id.slice(0, 8)}) failed (best-effort, not retried): ${markErr instanceof Error ? markErr.message : String(markErr)}`,
@@ -5676,6 +6636,7 @@ var ChannelDriver = class _ChannelDriver {
5676
6636
  deliveryDeadlineAnchored: false,
5677
6637
  b2PinnedSinceMs: 0,
5678
6638
  b2LastDescendantCheckMs: 0,
6639
+ b2RootOngoingHeldLogged: false,
5679
6640
  b2AbandonedSignalled: false,
5680
6641
  ambiguousPinnedSinceMs: 0,
5681
6642
  ambiguousResolved: false
@@ -5770,6 +6731,7 @@ var ChannelDriver = class _ChannelDriver {
5770
6731
  deliveryDeadlineAnchored: false,
5771
6732
  b2PinnedSinceMs: 0,
5772
6733
  b2LastDescendantCheckMs: 0,
6734
+ b2RootOngoingHeldLogged: false,
5773
6735
  b2AbandonedSignalled: false,
5774
6736
  ambiguousPinnedSinceMs: 0,
5775
6737
  ambiguousResolved: false
@@ -6123,6 +7085,7 @@ var ChannelDriver = class _ChannelDriver {
6123
7085
  if (snapshotReadable) {
6124
7086
  inFlight.b2PinnedSinceMs = 0;
6125
7087
  inFlight.b2LastDescendantCheckMs = 0;
7088
+ inFlight.b2RootOngoingHeldLogged = false;
6126
7089
  inFlight.b2AbandonedSignalled = false;
6127
7090
  }
6128
7091
  } else {
@@ -6134,11 +7097,15 @@ var ChannelDriver = class _ChannelDriver {
6134
7097
  const pinnedForMs = this.now() - inFlight.b2PinnedSinceMs;
6135
7098
  if (pinnedForMs >= B2_ABANDONMENT_MIN_PINNED_MS && this.now() - inFlight.b2LastDescendantCheckMs >= B2_ABANDONMENT_RECHECK_MS) {
6136
7099
  inFlight.b2LastDescendantCheckMs = this.now();
6137
- const descendantOngoing = await this.isAnyDescendantSessionOngoing(sessionId);
7100
+ const [descendantOngoing, rootOngoing] = await Promise.all([
7101
+ this.isAnyDescendantSessionOngoing(sessionId),
7102
+ isSessionOngoing(this.port, sessionId)
7103
+ ]);
6138
7104
  if (isB2AbandonmentConfirmed({
6139
7105
  pinnedForMs,
6140
7106
  minPinnedMs: B2_ABANDONMENT_MIN_PINNED_MS,
6141
- descendantOngoing
7107
+ descendantOngoing,
7108
+ rootOngoing
6142
7109
  })) {
6143
7110
  inFlight.b2AbandonedSignalled = true;
6144
7111
  this.log({
@@ -6147,12 +7114,26 @@ var ChannelDriver = class _ChannelDriver {
6147
7114
  conversation_id: conv.id,
6148
7115
  message_id: id
6149
7116
  });
7117
+ const reply = findLastAssistantReplyFor(messages, inFlight.opencodeMessageId);
6150
7118
  void this.postSignal(conv.id, id, "b2_abandoned_resolved", {
6151
- watched_for_ms: pinnedForMs
7119
+ watched_for_ms: pinnedForMs,
7120
+ finish: reply?.info?.finish ?? reply?.finish,
7121
+ ...rootOngoing != null ? { root_ongoing: rootOngoing } : {},
7122
+ ...descendantOngoing != null ? { descendant_ongoing: descendantOngoing } : {},
7123
+ opencode_message_id: inFlight.opencodeMessageId
6152
7124
  });
6153
7125
  await this.settleMessageDone(sessionId, watcher, inFlight, messages);
6154
7126
  return;
6155
7127
  }
7128
+ if (rootOngoing === true && !inFlight.b2RootOngoingHeldLogged) {
7129
+ inFlight.b2RootOngoingHeldLogged = true;
7130
+ this.log({
7131
+ level: "warn",
7132
+ message: `Message ${id.slice(0, 8)} b2-pinned for ${Math.round(pinnedForMs / 1e3)}s with root_ongoing=${rootOngoing} and descendant_ongoing=${descendantOngoing} \u2014 holding until OpenCode confirms the root is idle`,
7133
+ conversation_id: conv.id,
7134
+ message_id: id
7135
+ });
7136
+ }
6156
7137
  }
6157
7138
  }
6158
7139
  const ambiguousPinnedNow = activelyRunning && isAmbiguousFinishPinnedRunning(messages, inFlight.opencodeMessageId);
@@ -6751,14 +7732,14 @@ var ChannelDriver = class _ChannelDriver {
6751
7732
  this.unconfirmedDispatchFailures.delete(row.id);
6752
7733
  this.sessions.delete(readoptConv.id);
6753
7734
  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.`;
7735
+ const errorMessage2 = `OpenCode accepted this re-dispatched message ${streak} times in a row but never confirmed its assigned id (session ${sessionId.slice(0, 8)}'s message list could not be read back) \u2014 the session was abandoned; a fresh one is used for further messages.`;
6755
7736
  this.log({
6756
7737
  level: "error",
6757
- message: errorMessage,
7738
+ message: errorMessage2,
6758
7739
  conversation_id: row.conversation_id,
6759
7740
  message_id: row.id
6760
7741
  });
6761
- await this.markFailed(row.conversation_id, row.id, null, errorMessage).catch((markErr) => {
7742
+ await this.markFailed(row.conversation_id, row.id, null, errorMessage2).catch((markErr) => {
6762
7743
  this.log({
6763
7744
  level: "warn",
6764
7745
  message: `markFailed PATCH for message ${row.id.slice(0, 8)} (conversation ${row.conversation_id.slice(0, 8)}) failed (best-effort, not retried): ${markErr instanceof Error ? markErr.message : String(markErr)}`,
@@ -7373,6 +8354,7 @@ var ChannelDriver = class _ChannelDriver {
7373
8354
  throw new Error(`Failed to get pending conversations: HTTP ${res.status}`);
7374
8355
  }
7375
8356
  const data = await res.json();
8357
+ this.recycleRequestedFlag = data.recycle_requested === true;
7376
8358
  let conversations = data.conversations;
7377
8359
  if (this.conversationFilter) {
7378
8360
  conversations = conversations.filter((c) => c.id === this.conversationFilter);
@@ -7797,96 +8779,641 @@ async function ensureOpenCodeRunning(ctx) {
7797
8779
  blank();
7798
8780
  throw new Error(`OpenCode not running on port ${ctx.port}`);
7799
8781
  }
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");
8782
+ if (!isOpenCodeInstalled()) {
8783
+ if (!ctx.interactive) {
8784
+ throw new Error("OpenCode is not installed. Install it with: npm install -g opencode-ai");
8785
+ }
8786
+ const result = await promptOpenCodeInstall(true);
8787
+ if (result === "exit") process.exit(0);
8788
+ if (result !== "installed" && !isOpenCodeInstalled()) {
8789
+ throw new Error("OpenCode is not installed");
8790
+ }
8791
+ }
8792
+ if (!ctx.interactive) {
8793
+ ctx.log(`OpenCode is not running on port ${ctx.port}. Starting it automatically...`);
8794
+ const proc = await startOpenCode(ctx.port, { inheritStdio: ctx.inheritStdio });
8795
+ const health = await waitForOpenCodeHealth(ctx.port, ctx.startTimeoutMs);
8796
+ if (!health.healthy) {
8797
+ return {
8798
+ port: ctx.port,
8799
+ process: proc,
8800
+ version: null,
8801
+ notReadyReason: `it did not become healthy within ${Math.round(ctx.startTimeoutMs / 1e3)}s`
8802
+ };
8803
+ }
8804
+ ctx.log(`OpenCode started on port ${ctx.port}${health.version ? ` (v${health.version})` : ""}`);
8805
+ return {
8806
+ port: ctx.port,
8807
+ process: proc,
8808
+ version: health.version ?? null,
8809
+ notReadyReason: null
8810
+ };
8811
+ }
8812
+ let port = ctx.port;
8813
+ if (isPortInUse(port)) {
8814
+ console.log(chalk5.yellow(`
8815
+ Port ${port} is already in use.`));
8816
+ const alternativePort = findAvailablePort(port + 1);
8817
+ if (alternativePort) {
8818
+ const useAlternative = await select2({
8819
+ message: `Use port ${alternativePort} instead?`,
8820
+ choices: [
8821
+ { name: `Yes, use port ${alternativePort}`, value: "yes" },
8822
+ { name: "No, I will free the port manually", value: "no" }
8823
+ ]
8824
+ });
8825
+ if (useAlternative === "yes") {
8826
+ port = alternativePort;
8827
+ } else {
8828
+ throw new Error(`Port ${ctx.port} is in use`);
8829
+ }
8830
+ }
8831
+ }
8832
+ const action = await select2({
8833
+ message: "OpenCode is not running. What would you like to do?",
8834
+ choices: [
8835
+ {
8836
+ name: "Start OpenCode for me",
8837
+ value: "start",
8838
+ description: `Run 'opencode serve --port ${port}'`
8839
+ },
8840
+ {
8841
+ name: "Show me the command",
8842
+ value: "manual",
8843
+ description: "Display the command to run manually"
8844
+ },
8845
+ {
8846
+ name: "Continue without OpenCode",
8847
+ value: "continue",
8848
+ description: "Requests will fail until OpenCode starts"
8849
+ }
8850
+ ]
8851
+ });
8852
+ if (action === "manual") {
8853
+ blank();
8854
+ console.log(chalk5.bold("Run this command in another terminal:"));
8855
+ blank();
8856
+ console.log(` ${chalk5.cyan(`opencode serve --port ${port}`)}`);
8857
+ blank();
8858
+ throw new Error("Please start OpenCode manually");
8859
+ }
8860
+ if (action === "start") {
8861
+ const spinner = ora2("Starting OpenCode...").start();
8862
+ const proc = await startOpenCode(port, { inheritStdio: ctx.inheritStdio });
8863
+ const health = await waitForOpenCodeHealth(port, INTERACTIVE_START_TIMEOUT_MS);
8864
+ if (!health.healthy) {
8865
+ spinner.fail("Failed to start OpenCode");
8866
+ throw new Error("OpenCode failed to start");
8867
+ }
8868
+ spinner.stop();
8869
+ return { port, process: proc, version: health.version ?? null, notReadyReason: null };
8870
+ }
8871
+ return { port, process: null, version: null, notReadyReason: "you chose to continue without it" };
8872
+ }
8873
+
8874
+ // src/lib/runner-credentials.ts
8875
+ import { chmodSync as chmodSync2, writeFileSync as writeFileSync4 } from "fs";
8876
+ import { spawn as spawn5 } from "child_process";
8877
+ var RUNNER_SECRET_FETCH_TIMEOUT_MS = 6e4;
8878
+ var CREDENTIAL_RESTORE_TIMEOUT_MS = 6e4;
8879
+ var GITHUB_PROBE_TIMEOUT_MS = 1e4;
8880
+ var GIT_CONFIG_GLOBAL = "/tmp/gitconfig";
8881
+ var GIT_CREDENTIAL_HELPER = "/tmp/git-credential-helper.sh";
8882
+ function commandError2(result) {
8883
+ return result.stderr.trim() || `process exited with code ${result.code ?? "null"}`;
8884
+ }
8885
+ var runCommand2 = (command, args, opts) => {
8886
+ return new Promise((resolve4) => {
8887
+ let child;
8888
+ let stdout = "";
8889
+ let stderr = "";
8890
+ let settled = false;
8891
+ const timer = {};
8892
+ const finish = (result) => {
8893
+ if (settled) return;
8894
+ settled = true;
8895
+ if (timer.handle) clearTimeout(timer.handle);
8896
+ resolve4(result);
8897
+ };
8898
+ try {
8899
+ child = spawn5(command, args, { env: opts.env, stdio: ["ignore", "pipe", "pipe"] });
8900
+ } catch (error2) {
8901
+ finish({
8902
+ code: null,
8903
+ stdout,
8904
+ stderr: error2 instanceof Error ? error2.message : String(error2),
8905
+ timedOut: false
8906
+ });
8907
+ return;
8908
+ }
8909
+ child.stdout?.setEncoding("utf8");
8910
+ child.stdout?.on("data", (chunk) => {
8911
+ stdout += chunk;
8912
+ });
8913
+ child.stderr?.setEncoding("utf8");
8914
+ child.stderr?.on("data", (chunk) => {
8915
+ stderr += chunk;
8916
+ });
8917
+ child.once("error", (error2) => {
8918
+ finish({
8919
+ code: null,
8920
+ stdout,
8921
+ stderr: stderr === "" ? error2.message : `${stderr}
8922
+ ${error2.message}`,
8923
+ timedOut: false
8924
+ });
8925
+ });
8926
+ child.once("close", (code) => finish({ code, stdout, stderr, timedOut: false }));
8927
+ timer.handle = setTimeout(
8928
+ () => {
8929
+ child.kill("SIGKILL");
8930
+ finish({ code: null, stdout, stderr, timedOut: true });
8931
+ },
8932
+ Math.max(0, opts.timeoutMs)
8933
+ );
8934
+ });
8935
+ };
8936
+ function isEnvironmentObject(value) {
8937
+ return typeof value === "object" && value !== null && !Array.isArray(value);
8938
+ }
8939
+ function secretFailure(marker, detail, log3) {
8940
+ const message = `${marker}: ${detail}`;
8941
+ log3(message, "error");
8942
+ return new Error(message);
8943
+ }
8944
+ async function installRunnerSecret({
8945
+ env,
8946
+ log: log3,
8947
+ commandRunner
8948
+ }) {
8949
+ const arn = env.RUNNER_SECRET_ARN?.trim();
8950
+ if (!arn) {
8951
+ log3("runner secret is not configured; continuing without GitHub and MCP credentials");
8952
+ return false;
8953
+ }
8954
+ const result = await (commandRunner ?? runCommand2)(
8955
+ "aws",
8956
+ [
8957
+ "secretsmanager",
8958
+ "get-secret-value",
8959
+ "--secret-id",
8960
+ arn,
8961
+ "--query",
8962
+ "SecretString",
8963
+ "--output",
8964
+ "text"
8965
+ ],
8966
+ { env, timeoutMs: RUNNER_SECRET_FETCH_TIMEOUT_MS }
8967
+ );
8968
+ if (result.timedOut) {
8969
+ throw secretFailure(
8970
+ "CREDENTIAL-RESTORE-TIMEOUT",
8971
+ `runner-secret did not finish within ${RUNNER_SECRET_FETCH_TIMEOUT_MS}ms`,
8972
+ log3
8973
+ );
8974
+ }
8975
+ if (result.code !== 0) {
8976
+ throw secretFailure("RUNNER-SECRET-UNREADABLE", commandError2(result), log3);
8977
+ }
8978
+ let payload;
8979
+ try {
8980
+ payload = JSON.parse(result.stdout);
8981
+ } catch (error2) {
8982
+ log3(
8983
+ `RUNNER-SECRET-UNPARSEABLE: secret value is not a JSON object (${error2 instanceof Error ? error2.message : String(error2)})`,
8984
+ "warn"
8985
+ );
8986
+ return false;
8987
+ }
8988
+ if (!isEnvironmentObject(payload)) {
8989
+ log3("RUNNER-SECRET-UNPARSEABLE: secret value is not a JSON object", "warn");
8990
+ return false;
8991
+ }
8992
+ let populated = 0;
8993
+ let skipped = 0;
8994
+ let githubTokenPopulated = false;
8995
+ for (const [key, value] of Object.entries(payload)) {
8996
+ if (typeof value !== "string" || value.length === 0) continue;
8997
+ if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key)) {
8998
+ log3(
8999
+ `RUNNER-SECRET-KEY-SKIPPED: ${JSON.stringify(key)} is not a valid environment variable name`,
9000
+ "warn"
9001
+ );
9002
+ skipped += 1;
9003
+ continue;
9004
+ }
9005
+ env[key] = value;
9006
+ populated += 1;
9007
+ if (key === "GH_TOKEN") githubTokenPopulated = true;
9008
+ }
9009
+ if (populated === 0) {
9010
+ log3(
9011
+ "RUNNER-SECRET-UNPOPULATED: populate the runner secret as documented in infrastructure/evident-runner/MICROVM.md",
9012
+ "warn"
9013
+ );
9014
+ } else {
9015
+ log3(
9016
+ `RUNNER-SECRET-OK: exported ${populated} secret values; skipped ${skipped} invalid environment variable names`
9017
+ );
9018
+ }
9019
+ return githubTokenPopulated;
9020
+ }
9021
+ function restoreFailure(operation, result, log3) {
9022
+ const message = `CREDENTIAL-RESTORE-FAILED: ${operation} failed: ${commandError2(result)}`;
9023
+ log3(message, "error");
9024
+ return new Error(message);
9025
+ }
9026
+ async function runCredentialRestore(args, operation, log3, synchroniserRunner) {
9027
+ const result = await synchroniserRunner(args, { timeoutMs: CREDENTIAL_RESTORE_TIMEOUT_MS });
9028
+ if (result.timedOut) {
9029
+ log3(
9030
+ `CREDENTIAL-RESTORE-TIMEOUT: ${operation} did not finish within ${CREDENTIAL_RESTORE_TIMEOUT_MS}ms; continuing without it`,
9031
+ "warn"
9032
+ );
9033
+ return result;
9034
+ }
9035
+ if (result.code !== 0) throw restoreFailure(operation, result, log3);
9036
+ return result;
9037
+ }
9038
+ async function restoreCredentialStores({
9039
+ env,
9040
+ log: log3,
9041
+ synchroniserRunner = runSynchroniser
9042
+ }) {
9043
+ await runCredentialRestore(["restore", "claude"], "restore-claude", log3, synchroniserRunner);
9044
+ await runCredentialRestore(["restore", "opencode"], "restore-opencode", log3, synchroniserRunner);
9045
+ const result = await synchroniserRunner(["model-auth-ready"], {
9046
+ timeoutMs: CREDENTIAL_RESTORE_TIMEOUT_MS
9047
+ });
9048
+ if (result.timedOut) {
9049
+ log3(
9050
+ `CREDENTIAL-RESTORE-TIMEOUT: model-auth-ready did not finish within ${CREDENTIAL_RESTORE_TIMEOUT_MS}ms; continuing without it`,
9051
+ "warn"
9052
+ );
9053
+ return;
9054
+ }
9055
+ switch (result.code) {
9056
+ case 0:
9057
+ return;
9058
+ case 10:
9059
+ log3(
9060
+ `no model credentials under s3://${env.LITESTREAM_BUCKET ?? ""}/${env.LITESTREAM_PREFIX ?? ""}/ (neither claude/credentials.json nor opencode/auth.json yielded valid JSON) and neither ANTHROPIC_API_KEY nor OPENAI_API_KEY is set. This VM boots and connects; a turn that needs a model provider fails until one is connected. See 'Seeding a credential store' in infrastructure/evident-runner/MICROVM.md.`,
9061
+ "warn"
9062
+ );
9063
+ return;
9064
+ default:
9065
+ log3("could not determine whether this VM has model credentials", "warn");
9066
+ }
9067
+ }
9068
+ var GIT_CREDENTIAL_HELPER_CONTENT = [
9069
+ "#!/usr/bin/env bash",
9070
+ '[ "$1" = get ] || exit 0',
9071
+ "echo username=x-access-token",
9072
+ 'echo "password=${GH_TOKEN}"',
9073
+ ""
9074
+ ].join("\n");
9075
+ async function probeGitHubAccess({ env, log: log3 }) {
9076
+ const auth = await runCommand2("gh", ["api", "user", "--jq", ".login"], {
9077
+ env,
9078
+ timeoutMs: GITHUB_PROBE_TIMEOUT_MS
9079
+ });
9080
+ if (auth.timedOut) {
9081
+ log3(`GITHUB-PROBE-TIMEOUT: auth probe exceeded ${GITHUB_PROBE_TIMEOUT_MS}ms`, "warn");
9082
+ return;
9083
+ }
9084
+ if (auth.code !== 0) {
9085
+ log3(`GITHUB-AUTH-REJECTED: ${commandError2(auth)}`, "warn");
9086
+ return;
9087
+ }
9088
+ log3(`GITHUB-AUTH-OK: ${auth.stdout.trim()}`, "debug");
9089
+ const remote = await runCommand2("git", ["-C", process.cwd(), "remote", "get-url", "origin"], {
9090
+ env,
9091
+ timeoutMs: GITHUB_PROBE_TIMEOUT_MS
9092
+ });
9093
+ if (remote.code !== 0 || remote.timedOut) return;
9094
+ const repo = remote.stdout.trim().replace(/^(?:https:\/\/github\.com\/|git@github\.com:)/, "").replace(/\.git$/, "");
9095
+ if (!repo) return;
9096
+ const repository = await runCommand2("gh", ["api", `repos/${repo}`, "--jq", ".full_name"], {
9097
+ env,
9098
+ timeoutMs: GITHUB_PROBE_TIMEOUT_MS
9099
+ });
9100
+ if (repository.timedOut) {
9101
+ log3(
9102
+ `GITHUB-PROBE-TIMEOUT: repository probe for ${repo} exceeded ${GITHUB_PROBE_TIMEOUT_MS}ms`,
9103
+ "warn"
9104
+ );
9105
+ } else if (repository.code !== 0) {
9106
+ log3(`GITHUB-REPO-INACCESSIBLE: ${repo}: ${commandError2(repository)}`, "warn");
9107
+ }
9108
+ }
9109
+ async function configureGitHubAccess({ env, log: log3 }) {
9110
+ if (!env.GH_TOKEN) {
9111
+ log3("GITHUB-CREDENTIALS-MISSING: GH_TOKEN is unavailable; see RUNNER-SECRET-* above", "warn");
9112
+ return;
9113
+ }
9114
+ try {
9115
+ env.GIT_CONFIG_GLOBAL = GIT_CONFIG_GLOBAL;
9116
+ writeFileSync4(GIT_CONFIG_GLOBAL, "");
9117
+ writeFileSync4(GIT_CREDENTIAL_HELPER, GIT_CREDENTIAL_HELPER_CONTENT, { mode: 448 });
9118
+ chmodSync2(GIT_CREDENTIAL_HELPER, 448);
9119
+ const config = [
9120
+ ["user.name", env.GIT_USER_NAME ?? "evident-bot"],
9121
+ ["user.email", env.GIT_USER_EMAIL ?? "evident-bot@users.noreply.github.com"],
9122
+ ["init.defaultBranch", "main"],
9123
+ ["credential.https://github.com.helper", GIT_CREDENTIAL_HELPER]
9124
+ ];
9125
+ for (const [key, value] of config) {
9126
+ const result = await runCommand2("git", ["config", "--global", key, value], {
9127
+ env,
9128
+ timeoutMs: GITHUB_PROBE_TIMEOUT_MS
9129
+ });
9130
+ if (result.timedOut || result.code !== 0) throw new Error(commandError2(result));
9131
+ }
9132
+ } catch (error2) {
9133
+ log3(
9134
+ `GITHUB-SETUP-FAILED: could not configure local git credentials; continuing without GitHub access (${error2 instanceof Error ? error2.message : String(error2)})`,
9135
+ "warn"
9136
+ );
9137
+ return;
9138
+ }
9139
+ void probeGitHubAccess({ env, log: log3 }).catch((error2) => {
9140
+ log3(
9141
+ `GITHUB-SETUP-FAILED: GitHub access probe failed: ${error2 instanceof Error ? error2.message : String(error2)}`,
9142
+ "warn"
9143
+ );
9144
+ });
9145
+ }
9146
+
9147
+ // src/lib/opencode/config-overlay.ts
9148
+ import { execFileSync as execFileSync2 } from "child_process";
9149
+ import { copyFileSync, existsSync as existsSync2, statSync as statSync5 } from "fs";
9150
+ import { isAbsolute as isAbsolute2, join as join8, resolve as resolve3 } from "path";
9151
+ function isFile(filePath) {
9152
+ return existsSync2(filePath) && statSync5(filePath).isFile();
9153
+ }
9154
+ function applyRunnerOpenCodeConfig({
9155
+ overlayPath,
9156
+ cwd = process.cwd(),
9157
+ log: log3
9158
+ }) {
9159
+ if (!overlayPath) {
9160
+ log3("runner OpenCode config is not configured; using the baked project config", "debug");
9161
+ return;
9162
+ }
9163
+ const source = isAbsolute2(overlayPath) ? overlayPath : resolve3(cwd, overlayPath);
9164
+ const target = isFile(join8(cwd, "opencode.jsonc")) ? "opencode.jsonc" : "opencode.json";
9165
+ if (!isFile(source)) {
9166
+ log3(
9167
+ `RUNNER-OPENCODE-CONFIG-MISSING: ${source} is not a file; headless turns will wedge on the first external-directory permission prompt (#563)`,
9168
+ "error"
9169
+ );
9170
+ return;
9171
+ }
9172
+ copyFileSync(source, join8(cwd, target));
9173
+ try {
9174
+ execFileSync2("git", ["-C", cwd, "update-index", "--skip-worktree", target], {
9175
+ stdio: "ignore"
9176
+ });
9177
+ } catch (error2) {
9178
+ const detail = error2 instanceof Error ? error2.message : String(error2);
9179
+ log3(`could not mark ${target} skip-worktree: ${detail}; it may show as a local change`, "warn");
9180
+ }
9181
+ log3(`Applied runner OpenCode config ${source} to ${join8(cwd, target)}`);
9182
+ }
9183
+
9184
+ // src/lib/credential-sync.ts
9185
+ import { renameSync, writeFileSync as writeFileSync5 } from "fs";
9186
+ var CREDENTIAL_SYNC_TICK_TIMEOUT_MS = 3e4;
9187
+ var CREDENTIAL_FLUSH_DEADLINE_MS = 8e3;
9188
+ var CREDENTIAL_FLUSH_ABORT_GRACE_MS = 500;
9189
+ var DEFAULT_CREDENTIAL_SYNC_INTERVAL_SECONDS = 60;
9190
+ var STORES = ["claude", "opencode"];
9191
+ var MAX_FLUSH_PASSES = 2;
9192
+ function outcomesWith(outcome) {
9193
+ return { claude: outcome, opencode: outcome };
9194
+ }
9195
+ function errorMessage(error2) {
9196
+ return error2 instanceof Error ? error2.message : String(error2);
9197
+ }
9198
+ function waitForSettlement(promise, timeoutMs) {
9199
+ return new Promise((resolve4) => {
9200
+ let settled = false;
9201
+ const timer = setTimeout(() => finish(false), Math.max(0, timeoutMs));
9202
+ const finish = (value) => {
9203
+ if (settled) return;
9204
+ settled = true;
9205
+ clearTimeout(timer);
9206
+ resolve4(value);
9207
+ };
9208
+ promise.then(
9209
+ () => finish(true),
9210
+ () => finish(true)
9211
+ );
9212
+ });
9213
+ }
9214
+ function writeMarker(markerPath, outcomes, log3) {
9215
+ const body = `${STORES.map((store) => `${store}=${outcomes[store]}`).join("\n")}
9216
+ `;
9217
+ const temporaryPath = `${markerPath}.tmp`;
9218
+ try {
9219
+ writeFileSync5(temporaryPath, body, { mode: 384 });
9220
+ renameSync(temporaryPath, markerPath);
9221
+ } catch (error2) {
9222
+ log3(`CREDENTIAL-FLUSH-MARKER-UNWRITABLE: ${markerPath}: ${errorMessage(error2)}`, "warn");
9223
+ }
9224
+ }
9225
+ function intervalSeconds(env, log3) {
9226
+ const raw = env.CREDS_SYNC_INTERVAL;
9227
+ if (raw === void 0 || /^[1-9][0-9]*$/.test(raw) && Number.isSafeInteger(Number(raw))) {
9228
+ return raw === void 0 ? DEFAULT_CREDENTIAL_SYNC_INTERVAL_SECONDS : Number(raw);
9229
+ }
9230
+ log3(
9231
+ `CREDENTIAL-SYNC-INTERVAL-INVALID: CREDS_SYNC_INTERVAL='${raw}' is not a positive integer; using ${DEFAULT_CREDENTIAL_SYNC_INTERVAL_SECONDS}s`,
9232
+ "warn"
9233
+ );
9234
+ return DEFAULT_CREDENTIAL_SYNC_INTERVAL_SECONDS;
9235
+ }
9236
+ async function runFlushStore(store, env, synchroniserRunner, log3, deadlineAt) {
9237
+ const remainingMs = deadlineAt - Date.now();
9238
+ if (remainingMs <= 0) return { outcome: "timeout", orphaned: false };
9239
+ const controller = new AbortController();
9240
+ let result;
9241
+ let failed = false;
9242
+ const completion = Promise.resolve().then(
9243
+ () => synchroniserRunner(["sync-once", store], {
9244
+ timeoutMs: remainingMs,
9245
+ env,
9246
+ signal: controller.signal
9247
+ })
9248
+ ).then(
9249
+ (value) => {
9250
+ result = value;
9251
+ },
9252
+ (error2) => {
9253
+ failed = true;
9254
+ log3(`CREDENTIAL-FLUSH-ERROR: ${store}: ${errorMessage(error2)}`, "warn");
7808
9255
  }
7809
- }
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`
9256
+ );
9257
+ const abortTimer = setTimeout(() => controller.abort(), remainingMs);
9258
+ const settledBeforeDeadline = await waitForSettlement(completion, remainingMs);
9259
+ clearTimeout(abortTimer);
9260
+ if (!settledBeforeDeadline) {
9261
+ controller.abort();
9262
+ const settledAfterAbort = await waitForSettlement(completion, CREDENTIAL_FLUSH_ABORT_GRACE_MS);
9263
+ if (!settledAfterAbort) return { outcome: "timeout", orphaned: true };
9264
+ return { outcome: "timeout", orphaned: false };
9265
+ }
9266
+ if (failed || !result) return { outcome: "failed", orphaned: false };
9267
+ if (result.timedOut || Date.now() >= deadlineAt) {
9268
+ return { outcome: "timeout", orphaned: false };
9269
+ }
9270
+ return { outcome: result.code === 0 ? "ok" : "failed", orphaned: false };
9271
+ }
9272
+ function createCredentialSync({
9273
+ markerPath,
9274
+ env,
9275
+ log: log3,
9276
+ synchroniserRunner = runSynchroniser
9277
+ }) {
9278
+ const persistenceDisabled = !env.PERSISTENCE_BUCKET;
9279
+ let disabled = persistenceDisabled;
9280
+ let armed = false;
9281
+ let stopped = false;
9282
+ let timer;
9283
+ let inFlight;
9284
+ let activeTickAbort;
9285
+ let lastTickFailed;
9286
+ let flushPromise;
9287
+ const scheduleTick = (intervalMs, startTick2) => {
9288
+ if (stopped) return;
9289
+ timer = setTimeout(() => {
9290
+ timer = void 0;
9291
+ startTick2();
9292
+ }, intervalMs);
9293
+ };
9294
+ const startTick = (intervalMs) => {
9295
+ if (stopped) return;
9296
+ const controller = new AbortController();
9297
+ activeTickAbort = controller;
9298
+ const tick = (async () => {
9299
+ const outcomes = {
9300
+ claude: "failed",
9301
+ opencode: "failed"
7820
9302
  };
9303
+ for (const store of STORES) {
9304
+ if (controller.signal.aborted) break;
9305
+ try {
9306
+ const result = await synchroniserRunner(["sync-once", store], {
9307
+ timeoutMs: CREDENTIAL_SYNC_TICK_TIMEOUT_MS,
9308
+ env,
9309
+ signal: controller.signal
9310
+ });
9311
+ outcomes[store] = !result.timedOut && result.code === 0 ? "ok" : "failed";
9312
+ } catch (error2) {
9313
+ outcomes[store] = "failed";
9314
+ log3(`CREDENTIAL-SYNC-TICK-ERROR: ${store}: ${errorMessage(error2)}`, "debug");
9315
+ }
9316
+ }
9317
+ const failed = STORES.some((store) => outcomes[store] === "failed");
9318
+ log3(
9319
+ `CREDENTIAL-SYNC-TICK: claude=${outcomes.claude}, opencode=${outcomes.opencode}`,
9320
+ "debug"
9321
+ );
9322
+ if (failed && lastTickFailed !== true) {
9323
+ log3(
9324
+ "CREDENTIAL-SYNC-FAILED: an interval credential sync failed; retrying on the next tick",
9325
+ "warn"
9326
+ );
9327
+ } else if (!failed && lastTickFailed === true) {
9328
+ log3("CREDENTIAL-SYNC-RECOVERED: interval credential sync succeeded again", "warn");
9329
+ }
9330
+ lastTickFailed = failed;
9331
+ })().finally(() => {
9332
+ if (activeTickAbort === controller) activeTickAbort = void 0;
9333
+ if (inFlight === tick) inFlight = void 0;
9334
+ scheduleTick(intervalMs, () => startTick(intervalMs));
9335
+ });
9336
+ inFlight = tick;
9337
+ };
9338
+ const performFlush = async () => {
9339
+ stopped = true;
9340
+ if (timer) {
9341
+ clearTimeout(timer);
9342
+ timer = void 0;
9343
+ }
9344
+ const deadlineAt = Date.now() + CREDENTIAL_FLUSH_DEADLINE_MS;
9345
+ if (inFlight) {
9346
+ const settled = await waitForSettlement(inFlight, CREDENTIAL_FLUSH_DEADLINE_MS);
9347
+ if (!settled) {
9348
+ activeTickAbort?.abort();
9349
+ const settledAfterAbort = await waitForSettlement(
9350
+ inFlight,
9351
+ CREDENTIAL_FLUSH_ABORT_GRACE_MS
9352
+ );
9353
+ if (!settledAfterAbort) {
9354
+ log3(
9355
+ "CREDENTIAL-FLUSH-ORPHANED-TICK: a sync-once child could not be proven settled; skipping the boundary flush rather than becoming a second writer",
9356
+ "warn"
9357
+ );
9358
+ return { outcomes: outcomesWith("timeout"), orphaned: true };
9359
+ }
9360
+ }
7821
9361
  }
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`);
9362
+ if (disabled) return { outcomes: outcomesWith("skipped"), orphaned: false };
9363
+ const outcomes = outcomesWith("timeout");
9364
+ for (const store of STORES) {
9365
+ const result = await runFlushStore(store, env, synchroniserRunner, log3, deadlineAt);
9366
+ if (result.orphaned) {
9367
+ log3(
9368
+ "CREDENTIAL-FLUSH-ORPHANED-CHILD: a flush sync-once child could not be proven settled; refusing another flush pass rather than becoming a second writer",
9369
+ "warn"
9370
+ );
9371
+ return { outcomes: outcomesWith("timeout"), orphaned: true };
7847
9372
  }
9373
+ outcomes[store] = result.outcome;
7848
9374
  }
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"
9375
+ return { outcomes, orphaned: false };
9376
+ };
9377
+ let flushPasses = 0;
9378
+ let lastFlush;
9379
+ return {
9380
+ arm() {
9381
+ if (stopped || armed) return;
9382
+ armed = true;
9383
+ if (persistenceDisabled) {
9384
+ disabled = true;
9385
+ log3(
9386
+ "CREDENTIAL-SYNC-DISABLED: LITESTREAM_BUCKET/LITESTREAM_PREFIX are not both set; no interval credential sync this boot",
9387
+ "warn"
9388
+ );
9389
+ return;
7867
9390
  }
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");
9391
+ disabled = false;
9392
+ const intervalMs = intervalSeconds(env, log3) * 1e3;
9393
+ scheduleTick(intervalMs, () => startTick(intervalMs));
9394
+ },
9395
+ async stopAndFlush(publish) {
9396
+ let result;
9397
+ const runningFlush = flushPromise;
9398
+ if (runningFlush) {
9399
+ result = await runningFlush;
9400
+ } else if (flushPasses >= MAX_FLUSH_PASSES || lastFlush?.orphaned) {
9401
+ result = lastFlush ?? { outcomes: outcomesWith("timeout"), orphaned: true };
9402
+ } else {
9403
+ flushPasses++;
9404
+ const currentFlush = performFlush();
9405
+ flushPromise = currentFlush;
9406
+ try {
9407
+ result = await currentFlush;
9408
+ lastFlush = result;
9409
+ } finally {
9410
+ if (flushPromise === currentFlush) flushPromise = void 0;
9411
+ }
9412
+ }
9413
+ if (publish) writeMarker(markerPath, result.outcomes, log3);
9414
+ return result.outcomes;
7885
9415
  }
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" };
9416
+ };
7890
9417
  }
7891
9418
 
7892
9419
  // src/commands/run.ts
@@ -7895,6 +9422,7 @@ var CHANNEL_POLL_INTERVAL_MS = Number(process.env.EVIDENT_CHANNEL_POLL_INTERVAL_
7895
9422
  var CHANNEL_STUCK_QUEUED_MS = Number(process.env.EVIDENT_STUCK_QUEUED_MS) || void 0;
7896
9423
  var SHUTDOWN_DRAIN_TIMEOUT_MS = Number(process.env.EVIDENT_SHUTDOWN_DRAIN_MS) || 25e3;
7897
9424
  var TELEMETRY_SHUTDOWN_TIMEOUT_MS = 5e3;
9425
+ var CHILD_STOP_TIMEOUT_MS = 1e4;
7898
9426
  function resolveLogLevel(options) {
7899
9427
  const accepted = Object.keys(LOG_LEVELS);
7900
9428
  const validate = (value, source) => {
@@ -7925,11 +9453,11 @@ function resolveFileSyncDirectories(raw, homeDir) {
7925
9453
  if (trimmed === "") {
7926
9454
  throw new Error("--enable-file-sync-to requires a directory path (got an empty value)");
7927
9455
  }
7928
- const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join7(homeDir, trimmed.slice(2)) : trimmed;
7929
- if (!isAbsolute2(expanded)) {
9456
+ const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join9(homeDir, trimmed.slice(2)) : trimmed;
9457
+ if (!isAbsolute3(expanded)) {
7930
9458
  throw new Error(`--enable-file-sync-to requires an absolute directory path; got "${entry}"`);
7931
9459
  }
7932
- const normalized = resolvePath(expanded);
9460
+ const normalized = resolvePath2(expanded);
7933
9461
  if (parse(normalized).root === normalized) {
7934
9462
  throw new Error(
7935
9463
  `--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 +9573,7 @@ function logActivity(state, entry) {
8045
9573
  }
8046
9574
  function reportSessionDbRecovery(state) {
8047
9575
  try {
8048
- const report = drainSessionDbRecoveryReport({ homeDir: homedir4(), env: process.env });
9576
+ const report = drainSessionDbRecoveryReport({ homeDir: homedir5(), env: process.env });
8049
9577
  for (const record of report.records) {
8050
9578
  const activity = buildSessionDbRecoveryActivity(record);
8051
9579
  if (!activity) throw new Error("could not map session-DB recovery record");
@@ -8063,6 +9591,16 @@ function reportSessionDbRecovery(state) {
8063
9591
  );
8064
9592
  }
8065
9593
  }
9594
+ function reportSessionDbRecoveryRecord(state, record) {
9595
+ const activity = buildSessionDbRecoveryActivity(record);
9596
+ if (!activity) throw new Error("could not map session-DB recovery record");
9597
+ logActivity(state, {
9598
+ type: activity.level === "error" ? "error" : "info",
9599
+ level: activity.level,
9600
+ ...activity.level === "error" ? { error: activity.message } : { message: activity.message },
9601
+ metadata: activity.metadata
9602
+ });
9603
+ }
8066
9604
  function displayStatus(state) {
8067
9605
  if (!state.interactive) return;
8068
9606
  const attempt = state.connection?.reconnectAttempt ?? 0;
@@ -8175,6 +9713,10 @@ async function driveChannels(state, driver) {
8175
9713
  consecutiveDrainFailures = 0;
8176
9714
  unreachableMs = 0;
8177
9715
  state.messageCount += processed;
9716
+ if (driver.recycleRequested) {
9717
+ await beginGracefulShutdown(state, "recycle");
9718
+ return;
9719
+ }
8178
9720
  const proxiedActivity = state.lastProxiedActivityAt !== lastSeenProxiedActivityAt;
8179
9721
  lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
8180
9722
  const fileActivitySnapshot = driver.fileSyncActivity();
@@ -8217,8 +9759,8 @@ async function driveChannels(state, driver) {
8217
9759
  state.running = false;
8218
9760
  break;
8219
9761
  }
8220
- const errorMessage = error2 instanceof Error ? error2.message : String(error2);
8221
- logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage}` });
9762
+ const errorMessage2 = error2 instanceof Error ? error2.message : String(error2);
9763
+ logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage2}` });
8222
9764
  if (state.interactive) displayStatus(state);
8223
9765
  if (driver.hasInFlightWatchers()) {
8224
9766
  consecutiveDrainFailures = 0;
@@ -8235,7 +9777,7 @@ async function driveChannels(state, driver) {
8235
9777
  }
8236
9778
  }
8237
9779
  }
8238
- await new Promise((resolve3) => setTimeout(resolve3, CHANNEL_POLL_INTERVAL_MS));
9780
+ await new Promise((resolve4) => setTimeout(resolve4, CHANNEL_POLL_INTERVAL_MS));
8239
9781
  const cycleMs = performance.now() - cycleStartedAtMs;
8240
9782
  if (idleThisCycle) idleMs += cycleMs;
8241
9783
  if (unreachableThisCycle) unreachableMs += cycleMs;
@@ -8258,7 +9800,43 @@ async function driveChannels(state, driver) {
8258
9800
  var SESSION_CLEANUP_FIRST_SWEEP_MS = 1e4;
8259
9801
  var SESSION_DB_RECLAIM_MAX_PAGES = 2e3;
8260
9802
  function sessionDbPath() {
8261
- return join7(homedir4(), ".local", "share", "opencode", "opencode.db");
9803
+ return join9(homedir5(), ".local", "share", "opencode", "opencode.db");
9804
+ }
9805
+ function logSessionDbProvenanceMismatch(state, provenance, currentVersion, preBootMigrationCount) {
9806
+ const record = {
9807
+ v: 1,
9808
+ event: "session_db_recovery",
9809
+ at: (/* @__PURE__ */ new Date()).toISOString(),
9810
+ stage: "verify",
9811
+ outcome: "schema_provenance_mismatch",
9812
+ severity: "error",
9813
+ reason: provenance.reason ?? "schema-provenance-mismatch",
9814
+ litestream_exit_code: null,
9815
+ attempt: null,
9816
+ replica_objects: null,
9817
+ replica_bytes: null,
9818
+ quarantine_destination: null,
9819
+ quarantined_objects: null,
9820
+ quarantine_failed_objects: null,
9821
+ quarantined_bytes: null,
9822
+ verified_restore_point: null,
9823
+ restore_points_tried: null,
9824
+ provenance_reason: provenance.reason,
9825
+ provenance_migration_delta: provenance.migrationDelta,
9826
+ replication_suspended: false,
9827
+ dbPath: sessionDbPath(),
9828
+ recorded_version: provenance.recordedVersion,
9829
+ current_version: currentVersion,
9830
+ provenance_pre_boot_migration_count: preBootMigrationCount
9831
+ };
9832
+ const activity = buildSessionDbRecoveryActivity(record);
9833
+ if (!activity) throw new Error("could not map session-DB provenance activity");
9834
+ logActivity(state, {
9835
+ type: activity.level === "error" ? "error" : "info",
9836
+ level: activity.level,
9837
+ ...activity.level === "error" ? { error: activity.message } : { message: activity.message },
9838
+ metadata: activity.metadata
9839
+ });
8262
9840
  }
8263
9841
  async function runSweep(state, driver, config) {
8264
9842
  const mode = `age=${config.maxAgeMs ?? "\u2014"} count=${config.maxCount ?? "\u2014"}`;
@@ -8305,7 +9883,7 @@ async function runSweep(state, driver, config) {
8305
9883
  const reclaimResult = await reclaimSessionDbSpace({
8306
9884
  dbPath: sessionDbPath(),
8307
9885
  maxPages: SESSION_DB_RECLAIM_MAX_PAGES,
8308
- allowFullVacuum: protectedNow.size === 0
9886
+ allowFullVacuum: protectedNow.size === 0 && !state.sessionDbProvenanceAnomaly
8309
9887
  });
8310
9888
  if (reclaimResult.ok) {
8311
9889
  const beforeMib = (reclaimResult.beforeBytes / 1024 / 1024).toFixed(1);
@@ -8341,7 +9919,7 @@ function scheduleSessionCleanup(state, driver, options) {
8341
9919
  for (const warning2 of config.warnings) {
8342
9920
  logActivity(state, { type: "info", level: "warn", message: `Session cleanup: ${warning2}` });
8343
9921
  }
8344
- const dbBytes = statSessionDbBytes(homedir4());
9922
+ const dbBytes = statSessionDbBytes(homedir5());
8345
9923
  void (async () => {
8346
9924
  const reclaimSkipReason = dbBytes !== null && config.enabled ? await probeReclaimAvailability({ dbPath: sessionDbPath(), requiredBytes: dbBytes }) : null;
8347
9925
  const sizeWarning = buildSessionStoreSizeWarning({
@@ -8500,7 +10078,17 @@ function scheduleClaudeUsageReporting(state, options) {
8500
10078
  setTimer: (timer) => {
8501
10079
  state.claudeUsageTimer = timer;
8502
10080
  },
8503
- fetchUsage: getClaudeUsage,
10081
+ fetchUsage: async () => {
10082
+ const usage = await getClaudeUsage();
10083
+ if (usage.ownerLookupError) {
10084
+ logActivity(state, {
10085
+ type: "info",
10086
+ level: "debug",
10087
+ message: `Claude usage owner lookup failed: ${usage.ownerLookupError}`
10088
+ });
10089
+ }
10090
+ return usage;
10091
+ },
8504
10092
  report: (usage) => reportClaudeUsage(state.agentId, state.authHeader, usage),
8505
10093
  isLocalCredentialProblem,
8506
10094
  forcedOnHint: "run `claude` to sign in",
@@ -8532,7 +10120,8 @@ function scheduleResourceUsageReporting(state, options) {
8532
10120
  });
8533
10121
  return;
8534
10122
  }
8535
- const collect = createResourceUsageCollector(homedir4());
10123
+ const { collect, stop } = createResourceUsageCollector(homedir5());
10124
+ state.stopResourceUsageSampling = stop;
8536
10125
  let consecutiveFailures = 0;
8537
10126
  const tick = async () => {
8538
10127
  try {
@@ -8642,21 +10231,41 @@ async function cleanup(state, opts = {}) {
8642
10231
  clearTimeout(state.resourceUsageTimer);
8643
10232
  state.resourceUsageTimer = null;
8644
10233
  }
10234
+ state.stopResourceUsageSampling?.();
10235
+ state.stopResourceUsageSampling = null;
10236
+ const credentialSync = state.credentialSync;
10237
+ const flushCredentials = credentialSync ? async (phase, publish) => {
10238
+ await timeShutdownPhase(state, durations, phase, async () => {
10239
+ const outcomes = await credentialSync.stopAndFlush(publish);
10240
+ const level = Object.values(outcomes).every((outcome) => outcome === "ok") ? "info" : "warn";
10241
+ log2(
10242
+ state,
10243
+ `Credential flush: claude=${outcomes.claude}, opencode=${outcomes.opencode}`,
10244
+ level
10245
+ );
10246
+ });
10247
+ } : void 0;
10248
+ let drainSettled = true;
8645
10249
  if (opts.graceful && state.channelDriver) {
8646
10250
  state.channelDriver.stop();
10251
+ }
10252
+ if (flushCredentials) {
10253
+ await flushCredentials("credential_flush", !(opts.graceful && state.channelDriver));
10254
+ }
10255
+ if (opts.graceful && state.channelDriver) {
8647
10256
  log2(state, "Draining in-flight channel work before shutdown...");
8648
10257
  if (state.interactive) {
8649
10258
  logActivity(state, { type: "info", message: "Draining in-flight work before shutdown..." });
8650
10259
  displayStatus(state);
8651
10260
  }
8652
10261
  const driver = state.channelDriver;
8653
- const settled = await timeShutdownPhase(
10262
+ drainSettled = await timeShutdownPhase(
8654
10263
  state,
8655
10264
  durations,
8656
10265
  "drain",
8657
10266
  () => driver.waitForInFlight(SHUTDOWN_DRAIN_TIMEOUT_MS)
8658
10267
  );
8659
- if (!settled) {
10268
+ if (!drainSettled) {
8660
10269
  logActivity(state, {
8661
10270
  type: "info",
8662
10271
  message: "Shutdown drain timed out with work still in flight \u2014 leaving it for restart recovery"
@@ -8664,6 +10273,9 @@ async function cleanup(state, opts = {}) {
8664
10273
  if (state.interactive) displayStatus(state);
8665
10274
  }
8666
10275
  }
10276
+ if (opts.graceful && state.channelDriver && flushCredentials && drainSettled) {
10277
+ await flushCredentials("credential_flush_final", true);
10278
+ }
8667
10279
  await timeShutdownPhase(state, durations, "offline_notify", () => notifyOffline(state));
8668
10280
  if (state.connection) {
8669
10281
  const connection = state.connection;
@@ -8672,24 +10284,83 @@ async function cleanup(state, opts = {}) {
8672
10284
  }
8673
10285
  if (state.opencodeProcess) {
8674
10286
  const opencodeProcess = state.opencodeProcess;
8675
- await timeShutdownPhase(state, durations, "opencode_stop", () => stopOpenCode(opencodeProcess));
10287
+ const result = await timeShutdownPhase(
10288
+ state,
10289
+ durations,
10290
+ "opencode_stop",
10291
+ () => stopOpenCodeAndWait(opencodeProcess, CHILD_STOP_TIMEOUT_MS)
10292
+ );
8676
10293
  if (state.interactive) {
8677
- logActivity(state, { type: "info", message: "Stopped OpenCode process" });
10294
+ logActivity(state, { type: "info", message: `Stopped OpenCode process (${result.outcome})` });
8678
10295
  displayStatus(state);
8679
10296
  } else {
8680
- log2(state, "Stopped OpenCode process");
10297
+ log2(state, `Stopped OpenCode process (${result.outcome})`);
8681
10298
  }
8682
10299
  state.opencodeProcess = null;
8683
10300
  }
10301
+ if (state.litestreamProcess) {
10302
+ const litestreamProcess = state.litestreamProcess;
10303
+ const result = await timeShutdownPhase(
10304
+ state,
10305
+ durations,
10306
+ "litestream_stop",
10307
+ () => stopSessionDbReplication(litestreamProcess, CHILD_STOP_TIMEOUT_MS)
10308
+ );
10309
+ log2(state, `Stopped litestream replication (${result.outcome})`);
10310
+ state.litestreamProcess = null;
10311
+ }
8684
10312
  return durations;
8685
10313
  }
10314
+ async function beginGracefulShutdown(state, trigger) {
10315
+ if (state.shuttingDown) return;
10316
+ state.shuttingDown = true;
10317
+ const shutdownStartedAt = Date.now();
10318
+ const shutdownMessage = trigger === "recycle" ? "Recycle requested \u2014 finishing in-flight work, then exiting" : "Shutting down...";
10319
+ if (state.interactive) {
10320
+ logActivity(state, { type: "info", message: shutdownMessage });
10321
+ displayStatus(state);
10322
+ } else {
10323
+ log2(state, shutdownMessage);
10324
+ }
10325
+ const durations = await cleanup(state, { graceful: true });
10326
+ const telemetryBudgetMs = Number(process.env.EVIDENT_TELEMETRY_SHUTDOWN_MS) || TELEMETRY_SHUTDOWN_TIMEOUT_MS;
10327
+ await timeShutdownPhase(state, durations, "telemetry_flush", async () => {
10328
+ let timer;
10329
+ const flushed = shutdownTelemetry().then(
10330
+ () => true,
10331
+ (error2) => {
10332
+ log2(
10333
+ state,
10334
+ `Telemetry flush failed during shutdown: ${error2 instanceof Error ? error2.message : String(error2)}`,
10335
+ "warn"
10336
+ );
10337
+ return true;
10338
+ }
10339
+ );
10340
+ const timedOut = new Promise((resolve4) => {
10341
+ timer = setTimeout(() => resolve4(false), telemetryBudgetMs);
10342
+ });
10343
+ if (!await Promise.race([flushed, timedOut])) {
10344
+ log2(state, `Telemetry flush exceeded ${telemetryBudgetMs}ms \u2014 exiting anyway`, "warn");
10345
+ }
10346
+ clearTimeout(timer);
10347
+ });
10348
+ const breakdown = Object.entries(durations).map(([phase, ms]) => `${phase}=${ms}ms`).join(" ");
10349
+ log2(state, `Shutdown complete in ${Date.now() - shutdownStartedAt}ms (${breakdown})`);
10350
+ process.exit(0);
10351
+ }
8686
10352
  async function run(options) {
8687
10353
  const interactive = isInteractive(options.json);
8688
10354
  let logLevel;
8689
10355
  let fileSyncDirectories;
8690
10356
  try {
8691
10357
  logLevel = resolveLogLevel(options);
8692
- fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir4());
10358
+ fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir5());
10359
+ if (options.restoreSessionDb && !options.sessionDbNoReplicateMarker) {
10360
+ throw new Error(
10361
+ "--restore-session-db requires --session-db-no-replicate-marker <path>; restore failures must block Litestream replication"
10362
+ );
10363
+ }
8693
10364
  } catch (error2) {
8694
10365
  const message = error2 instanceof Error ? error2.message : String(error2);
8695
10366
  if (options.json) {
@@ -8713,7 +10384,9 @@ async function run(options) {
8713
10384
  connected: false,
8714
10385
  opencodeConnected: false,
8715
10386
  opencodeVersion: null,
10387
+ sessionDbProvenanceAnomaly: false,
8716
10388
  opencodeProcess: null,
10389
+ litestreamProcess: null,
8717
10390
  connection: null,
8718
10391
  channelDriver: null,
8719
10392
  running: true,
@@ -8727,9 +10400,24 @@ async function run(options) {
8727
10400
  openaiUsageTimer: null,
8728
10401
  openaiUsageRearm: null,
8729
10402
  resourceUsageTimer: null,
10403
+ stopResourceUsageSampling: null,
10404
+ credentialSync: null,
8730
10405
  authHeader: ""
8731
10406
  };
8732
10407
  setTelemetryAuthProvider(() => ({ authHeader: state.authHeader, agentId: state.agentId }));
10408
+ if (options.credentialSyncMarker) {
10409
+ state.credentialSync = createCredentialSync({
10410
+ markerPath: options.credentialSyncMarker,
10411
+ env: process.env,
10412
+ log: (message, level = "info") => {
10413
+ if (level === "error") {
10414
+ logActivity(state, { type: "error", error: message });
10415
+ } else {
10416
+ logActivity(state, { type: "info", level, message });
10417
+ }
10418
+ }
10419
+ });
10420
+ }
8733
10421
  if (fileSyncDirectories.length > 0) {
8734
10422
  log2(state, `File sync enabled for: ${fileSyncDirectories.join(", ")}`);
8735
10423
  } else {
@@ -8755,43 +10443,7 @@ async function run(options) {
8755
10443
  "warn"
8756
10444
  );
8757
10445
  }
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
- };
10446
+ const handleSignal = () => beginGracefulShutdown(state, "signal");
8795
10447
  process.on("SIGINT", handleSignal);
8796
10448
  process.on("SIGTERM", handleSignal);
8797
10449
  try {
@@ -8921,7 +10573,68 @@ async function run(options) {
8921
10573
  } else {
8922
10574
  log2(state, "Not running in a MicroVM (MICROVM_ID unset) \u2014 nothing to report", "debug");
8923
10575
  }
10576
+ if (options.restoreRunnerCredentials) {
10577
+ log2(state, "Restoring runner credentials before starting OpenCode");
10578
+ const credentialContext = {
10579
+ env: process.env,
10580
+ log: (message, level = "info") => {
10581
+ if (level === "error") {
10582
+ logActivity(state, { type: "error", error: message });
10583
+ } else {
10584
+ logActivity(state, { type: "info", level, message });
10585
+ }
10586
+ }
10587
+ };
10588
+ const githubTokenPopulated = await installRunnerSecret(credentialContext);
10589
+ await restoreCredentialStores(credentialContext);
10590
+ if (githubTokenPopulated) await configureGitHubAccess(credentialContext);
10591
+ }
10592
+ state.credentialSync?.arm();
10593
+ let sessionDbVerifyFatal = false;
10594
+ if (!options.restoreSessionDb) {
10595
+ log2(state, "Skipping session-DB restore: --restore-session-db was not passed", "debug");
10596
+ } else {
10597
+ const health = await checkOpenCodeHealth(state.port);
10598
+ if (health.healthy) {
10599
+ log2(
10600
+ state,
10601
+ "Skipping session-DB restore: OpenCode is already serving this database",
10602
+ "debug"
10603
+ );
10604
+ } else {
10605
+ const result = await restoreAndVerifySessionDb({
10606
+ dbPath: sessionDbPath(),
10607
+ litestreamConfig: options.litestreamConfig,
10608
+ noReplicateMarker: options.sessionDbNoReplicateMarker,
10609
+ env: process.env,
10610
+ log: (message, level = "info") => {
10611
+ if (level === "error") {
10612
+ logActivity(state, { type: "error", error: message });
10613
+ } else {
10614
+ logActivity(state, { type: "info", level, message });
10615
+ }
10616
+ },
10617
+ reportRecovery: (record) => reportSessionDbRecoveryRecord(state, record)
10618
+ });
10619
+ sessionDbVerifyFatal = result.verifyFatal;
10620
+ }
10621
+ }
8924
10622
  reportSessionDbRecovery(state);
10623
+ if (sessionDbVerifyFatal) {
10624
+ throw new Error(
10625
+ "SESSION-DB-INTEGRITY-EXHAUSTED: the corrupt session DB could not be proven separated from the active backup prefix or removed from disk"
10626
+ );
10627
+ }
10628
+ applyRunnerOpenCodeConfig({
10629
+ overlayPath: options.opencodeConfigOverlay,
10630
+ log: (message, level = "info") => {
10631
+ if (level === "error") {
10632
+ logActivity(state, { type: "error", error: message });
10633
+ } else {
10634
+ logActivity(state, { type: "info", level, message });
10635
+ }
10636
+ }
10637
+ });
8925
10638
  const { timeoutMs: opencodeStartTimeoutMs, warnings: opencodeStartTimeoutWarnings } = resolveOpenCodeStartTimeoutMs(options, process.env);
8926
10639
  for (const warning2 of opencodeStartTimeoutWarnings) {
8927
10640
  logActivity(state, { type: "info", level: "warn", message: warning2 });
@@ -8930,6 +10643,7 @@ async function run(options) {
8930
10643
  for (const warning2 of maxActiveSessionsWarnings) {
8931
10644
  logActivity(state, { type: "info", level: "warn", message: warning2 });
8932
10645
  }
10646
+ const preBootMigrationIds = readSessionDbMigrationIds(sessionDbPath());
8933
10647
  const ocSpinner = interactive && !state.json ? ora3("Checking OpenCode...").start() : null;
8934
10648
  try {
8935
10649
  const oc = await ensureOpenCodeRunning({
@@ -8937,11 +10651,41 @@ async function run(options) {
8937
10651
  interactive: state.interactive,
8938
10652
  agentId: state.agentId,
8939
10653
  log: (message) => log2(state, message),
8940
- startTimeoutMs: opencodeStartTimeoutMs
10654
+ startTimeoutMs: opencodeStartTimeoutMs,
10655
+ inheritStdio: Boolean(options.opencodePidFile)
8941
10656
  });
8942
10657
  state.port = oc.port;
8943
- state.opencodeProcess = oc.process;
10658
+ state.opencodeProcess = options.opencodePidFile ? null : oc.process;
8944
10659
  state.opencodeVersion = oc.version;
10660
+ if (options.opencodePidFile && oc.process?.pid !== void 0) {
10661
+ try {
10662
+ writeFileSync6(options.opencodePidFile, `${oc.process.pid}
10663
+ `, { mode: 384 });
10664
+ chmodSync3(options.opencodePidFile, 384);
10665
+ } catch (error2) {
10666
+ logActivity(state, {
10667
+ type: "error",
10668
+ error: `Failed to write OpenCode pid file ${options.opencodePidFile}: ${error2 instanceof Error ? error2.message : String(error2)}`
10669
+ });
10670
+ }
10671
+ }
10672
+ if (state.opencodeVersion !== null) {
10673
+ const provenance = checkSessionDbProvenance({
10674
+ dbPath: sessionDbPath(),
10675
+ currentVersion: state.opencodeVersion,
10676
+ homeDir: homedir5(),
10677
+ env: process.env
10678
+ });
10679
+ if (provenance.anomaly) {
10680
+ state.sessionDbProvenanceAnomaly = true;
10681
+ logSessionDbProvenanceMismatch(
10682
+ state,
10683
+ provenance,
10684
+ state.opencodeVersion,
10685
+ preBootMigrationIds?.length ?? null
10686
+ );
10687
+ }
10688
+ }
8945
10689
  state.opencodeConnected = oc.notReadyReason === null;
8946
10690
  const version2 = state.opencodeVersion ? ` (v${state.opencodeVersion})` : "";
8947
10691
  ocSpinner?.succeed(`OpenCode running on port ${state.port}${version2}`);
@@ -8978,6 +10722,108 @@ async function run(options) {
8978
10722
  ocSpinner?.fail(error2.message);
8979
10723
  throw error2;
8980
10724
  }
10725
+ if (options.litestreamPidFile) {
10726
+ if (options.sessionDbNoReplicateMarker && existsSync3(options.sessionDbNoReplicateMarker)) {
10727
+ log2(
10728
+ state,
10729
+ `Skipping Litestream replication because ${options.sessionDbNoReplicateMarker} marks this session database unsafe to replicate`
10730
+ );
10731
+ } else if (!options.litestreamConfig) {
10732
+ logActivity(state, {
10733
+ type: "info",
10734
+ level: "warn",
10735
+ message: "Skipping Litestream replication because no configuration file was provided"
10736
+ });
10737
+ } else {
10738
+ let existingPid;
10739
+ if (existsSync3(options.litestreamPidFile)) {
10740
+ try {
10741
+ const rawPid = readFileSync6(options.litestreamPidFile, "utf8").trim();
10742
+ const parsedPid = Number(rawPid);
10743
+ if (/^\d+$/.test(rawPid) && Number.isSafeInteger(parsedPid) && parsedPid > 0) {
10744
+ existingPid = parsedPid;
10745
+ }
10746
+ } catch (error2) {
10747
+ logActivity(state, {
10748
+ type: "info",
10749
+ level: "warn",
10750
+ message: `Could not read Litestream pid file ${options.litestreamPidFile}; checking for a new process: ${error2 instanceof Error ? error2.message : String(error2)}`
10751
+ });
10752
+ }
10753
+ }
10754
+ if (existingPid !== void 0 && isProcessAlive(existingPid)) {
10755
+ log2(state, `Litestream replication is already running with pid ${existingPid}`);
10756
+ } else {
10757
+ const litestreamProcess = startSessionDbReplication(options.litestreamConfig);
10758
+ state.litestreamProcess = null;
10759
+ let failureHandled = false;
10760
+ const reportImageOwnedReplicationFailure = (message) => {
10761
+ if (failureHandled || state.shuttingDown || !state.running) return;
10762
+ failureHandled = true;
10763
+ logActivity(state, { type: "error", error: message });
10764
+ if (state.interactive) displayStatus(state);
10765
+ };
10766
+ litestreamProcess.on("exit", (code, signal) => {
10767
+ reportImageOwnedReplicationFailure(
10768
+ `Litestream replication stopped unexpectedly (code: ${code ?? "null"}, signal: ${signal ?? "none"})`
10769
+ );
10770
+ });
10771
+ litestreamProcess.on("error", (error2) => {
10772
+ reportImageOwnedReplicationFailure(
10773
+ `Litestream replication failed: ${error2 instanceof Error ? error2.message : String(error2)}`
10774
+ );
10775
+ });
10776
+ try {
10777
+ if (litestreamProcess.pid !== void 0) {
10778
+ writeFileSync6(options.litestreamPidFile, `${litestreamProcess.pid}
10779
+ `, {
10780
+ mode: 384
10781
+ });
10782
+ chmodSync3(options.litestreamPidFile, 384);
10783
+ }
10784
+ } catch (error2) {
10785
+ logActivity(state, {
10786
+ type: "error",
10787
+ error: `Failed to write Litestream pid file ${options.litestreamPidFile}: ${error2 instanceof Error ? error2.message : String(error2)}`
10788
+ });
10789
+ }
10790
+ log2(state, `Started litestream replication with config ${options.litestreamConfig}`);
10791
+ }
10792
+ }
10793
+ } else if (options.litestreamConfig) {
10794
+ const litestreamProcess = startSessionDbReplication(options.litestreamConfig);
10795
+ state.litestreamProcess = litestreamProcess;
10796
+ let failureHandled = false;
10797
+ const failRunForReplication = (message) => {
10798
+ if (failureHandled || state.shuttingDown || !state.running) return;
10799
+ failureHandled = true;
10800
+ state.shuttingDown = true;
10801
+ logActivity(state, { type: "error", error: message });
10802
+ if (state.interactive) displayStatus(state);
10803
+ void (async () => {
10804
+ try {
10805
+ await cleanup(state);
10806
+ await shutdownTelemetry();
10807
+ } catch (error2) {
10808
+ console.error(
10809
+ `[run] replication failure cleanup failed: ${error2 instanceof Error ? error2.message : String(error2)}`
10810
+ );
10811
+ }
10812
+ process.exit(1);
10813
+ })();
10814
+ };
10815
+ litestreamProcess.on("exit", (code, signal) => {
10816
+ failRunForReplication(
10817
+ `Litestream replication stopped unexpectedly (code: ${code ?? "null"}, signal: ${signal ?? "none"})`
10818
+ );
10819
+ });
10820
+ litestreamProcess.on("error", (error2) => {
10821
+ failRunForReplication(
10822
+ `Litestream replication failed: ${error2 instanceof Error ? error2.message : String(error2)}`
10823
+ );
10824
+ });
10825
+ log2(state, `Started litestream replication with config ${options.litestreamConfig}`);
10826
+ }
8981
10827
  const tunnelSpinner = interactive && !state.json ? ora3("Connecting tunnel...").start() : null;
8982
10828
  const channelDriver = new ChannelDriver({
8983
10829
  agentId: state.agentId,
@@ -8989,7 +10835,7 @@ async function run(options) {
8989
10835
  // #559: the `--enable-file-sync-to` allow-list. Empty ⇒ pending files are
8990
10836
  // REJECTED with `file_sync_disabled` on the ack, not silently ignored.
8991
10837
  fileSyncDirectories,
8992
- homeDir: homedir4(),
10838
+ homeDir: homedir5(),
8993
10839
  maxActiveSessions,
8994
10840
  log: (entry) => (
8995
10841
  // Thread the driver's real level straight through so `debug`/`warn`
@@ -9135,7 +10981,17 @@ async function run(options) {
9135
10981
  setTimer: (timer) => {
9136
10982
  state.openaiUsageTimer = timer;
9137
10983
  },
9138
- fetchUsage: () => getOpenAiUsage(state.port),
10984
+ fetchUsage: async () => {
10985
+ const usage = await getOpenAiUsage(state.port);
10986
+ if (usage.subscription === null) {
10987
+ logActivity(state, {
10988
+ type: "info",
10989
+ level: "debug",
10990
+ message: "OpenAI usage subscription could not be identified from the local credential"
10991
+ });
10992
+ }
10993
+ return usage;
10994
+ },
9139
10995
  report: (usage) => reportOpenAiUsage(state.agentId, state.authHeader, usage),
9140
10996
  isLocalCredentialProblem: isLocalCredentialProblem2,
9141
10997
  forcedOnHint: "connect a ChatGPT account to this runner, or run `opencode auth login`",
@@ -9181,7 +11037,7 @@ async function run(options) {
9181
11037
  }
9182
11038
 
9183
11039
  // src/index.ts
9184
- var { version } = createRequire(import.meta.url)("../package.json");
11040
+ var { version } = createRequire2(import.meta.url)("../package.json");
9185
11041
  var program = new Command();
9186
11042
  program.name("evident").description("Run OpenCode locally and connect it to Evident").version(version).option(
9187
11043
  "--endpoint <url>",
@@ -9238,6 +11094,30 @@ program.command("run").description("Connect to Evident and process messages").op
9238
11094
  ).option(
9239
11095
  "--tunnel-ready-file <path>",
9240
11096
  "Path to write once the tunnel is connected (opt-in; unused unless an operator/image sets it)"
11097
+ ).option(
11098
+ "--litestream-config <path>",
11099
+ "Replicate the OpenCode session database with `litestream replicate` using this config file (written by the runner image). Omit to disable replication."
11100
+ ).option(
11101
+ "--opencode-pid-file <path>",
11102
+ "Record the OpenCode pid here and leave the process running at shutdown for the runner image's lifecycle hooks to stop."
11103
+ ).option(
11104
+ "--litestream-pid-file <path>",
11105
+ "Record the Litestream pid here and leave the process running at shutdown for the runner image's lifecycle hooks to stop."
11106
+ ).option(
11107
+ "--session-db-no-replicate-marker <path>",
11108
+ "Read this marker as a gate before starting Litestream; the session-DB restore writes it when this boot's database is not safe to replicate."
11109
+ ).option(
11110
+ "--restore-session-db",
11111
+ "Restore and verify the OpenCode session database before starting OpenCode; requires --litestream-config for the replica and --session-db-no-replicate-marker for give-up records."
11112
+ ).option(
11113
+ "--restore-runner-credentials",
11114
+ "Restore the hosted runner secret and persisted credential stores before starting OpenCode."
11115
+ ).option(
11116
+ "--opencode-config-overlay <path>",
11117
+ "Apply this runner-provided OpenCode config before starting OpenCode."
11118
+ ).option(
11119
+ "--credential-sync-marker <path>",
11120
+ "Own the interval credential sync and write this marker once the shutdown flush has finished, so the runner image's lifecycle hooks can wait on it."
9241
11121
  ).action(
9242
11122
  (options) => {
9243
11123
  run({
@@ -9269,7 +11149,15 @@ program.command("run").description("Connect to Evident and process messages").op
9269
11149
  // Raw values — expansion/validation is single-sourced in run.ts's
9270
11150
  // resolveFileSyncDirectories.
9271
11151
  enableFileSyncTo: options.enableFileSyncTo,
9272
- tunnelReadyFile: options.tunnelReadyFile
11152
+ tunnelReadyFile: options.tunnelReadyFile,
11153
+ litestreamConfig: options.litestreamConfig,
11154
+ opencodePidFile: options.opencodePidFile,
11155
+ litestreamPidFile: options.litestreamPidFile,
11156
+ sessionDbNoReplicateMarker: options.sessionDbNoReplicateMarker,
11157
+ restoreSessionDb: options.restoreSessionDb,
11158
+ restoreRunnerCredentials: options.restoreRunnerCredentials,
11159
+ opencodeConfigOverlay: options.opencodeConfigOverlay,
11160
+ credentialSyncMarker: options.credentialSyncMarker
9273
11161
  });
9274
11162
  }
9275
11163
  );