@evident-ai/cli 3.6.1-dev.547a214 → 3.6.1-dev.5c4c582

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,4 +1,9 @@
1
1
  #!/usr/bin/env node
2
+ var __defProp = Object.defineProperty;
3
+ var __export = (target, all) => {
4
+ for (var name in all)
5
+ __defProp(target, name, { get: all[name], enumerable: true });
6
+ };
2
7
 
3
8
  // src/index.ts
4
9
  import { Command } from "commander";
@@ -9,6 +14,24 @@ import ora from "ora";
9
14
  import chalk2 from "chalk";
10
15
 
11
16
  // src/lib/config.ts
17
+ var config_exports = {};
18
+ __export(config_exports, {
19
+ clearAllCredentials: () => clearAllCredentials,
20
+ clearCredentials: () => clearCredentials,
21
+ clearManagedInferenceCredential: () => clearManagedInferenceCredential,
22
+ credentials: () => credentials,
23
+ getApiUrlConfig: () => getApiUrlConfig,
24
+ getCliName: () => getCliName,
25
+ getCredentials: () => getCredentials,
26
+ getManagedInferenceCredential: () => getManagedInferenceCredential,
27
+ getTeamSelection: () => getTeamSelection,
28
+ getTunnelUrlConfig: () => getTunnelUrlConfig,
29
+ setCredentials: () => setCredentials,
30
+ setEndpoint: () => setEndpoint,
31
+ setManagedInferenceCredential: () => setManagedInferenceCredential,
32
+ setTeamSelection: () => setTeamSelection,
33
+ setTunnelUrl: () => setTunnelUrl
34
+ });
12
35
  import Conf from "conf";
13
36
  import { chmodSync, existsSync, statSync } from "node:fs";
14
37
  import { dirname } from "node:path";
@@ -20,6 +43,7 @@ var defaults = {
20
43
  };
21
44
  var endpointOverride;
22
45
  var tunnelOverride;
46
+ var teamOverride;
23
47
  function setEndpoint(url) {
24
48
  if (!url) {
25
49
  endpointOverride = void 0;
@@ -31,6 +55,13 @@ function setEndpoint(url) {
31
55
  function setTunnelUrl(url) {
32
56
  tunnelOverride = url ? url.replace(/\/+$/, "") : void 0;
33
57
  }
58
+ function setTeamSelection(id) {
59
+ const trimmed = id?.trim();
60
+ teamOverride = trimmed || void 0;
61
+ }
62
+ function getTeamSelection() {
63
+ return teamOverride ?? (process.env.EVIDENT_TEAM?.trim() || void 0);
64
+ }
34
65
  function getApiUrl() {
35
66
  return endpointOverride ?? process.env.EVIDENT_API_URL ?? defaults.apiUrl;
36
67
  }
@@ -579,6 +610,14 @@ function getAuthHeader(credentials2) {
579
610
  }
580
611
  return `Bearer ${credentials2.token}`;
581
612
  }
613
+ function buildAuthHeaders(credentials2) {
614
+ const headers = { Authorization: getAuthHeader(credentials2) };
615
+ const team = Object.hasOwn(config_exports, "getTeamSelection") ? getTeamSelection() : void 0;
616
+ if (credentials2.authType === "bearer" && team) {
617
+ headers["X-Evident-Team"] = team;
618
+ }
619
+ return headers;
620
+ }
582
621
  function isInteractive(jsonOutput) {
583
622
  if (jsonOutput) return false;
584
623
  if (process.env.CI) return false;
@@ -1178,11 +1217,10 @@ async function claudeUsage() {
1178
1217
  }
1179
1218
  }
1180
1219
 
1181
- // src/commands/run.ts
1182
- import { chmodSync as chmodSync3, existsSync as existsSync3, readFileSync as readFileSync12, writeFileSync as writeFileSync9 } from "node:fs";
1183
- import { homedir as homedir9 } from "node:os";
1184
- import { isAbsolute as isAbsolute6, join as join17, parse, resolve as resolvePath2 } from "node:path";
1185
- import chalk7 from "chalk";
1220
+ // src/commands/mcp-authorize.ts
1221
+ import { createServer } from "node:http";
1222
+ import { randomBytes } from "node:crypto";
1223
+ import open2 from "open";
1186
1224
 
1187
1225
  // ../../packages/types/src/agents/index.ts
1188
1226
  var MICROVM_MAX_LIFETIME_MS = 8 * 60 * 6e4;
@@ -1443,6 +1481,14 @@ function buildCredentialProxyNativeConfig({
1443
1481
  };
1444
1482
  }
1445
1483
 
1484
+ // ../../packages/types/src/mcp-proxies.ts
1485
+ var MCP_LOOPBACK_REDIRECT_POLICY = {
1486
+ scheme: "http",
1487
+ host: "127.0.0.1",
1488
+ path: "/callback",
1489
+ preferred_port: 18443
1490
+ };
1491
+
1446
1492
  // ../../packages/types/src/logging/index.ts
1447
1493
  var CORRELATION_ID_HEADER = "x-evident-correlation-id";
1448
1494
  var FORWARD_FAILURE_REASON_HEADER = "X-Evident-Failure-Reason";
@@ -1477,12 +1523,943 @@ function stripQuery(url) {
1477
1523
  }
1478
1524
  }
1479
1525
 
1526
+ // src/commands/mcp-authorize.ts
1527
+ var API_TIMEOUT_MS = 1e4;
1528
+ var CALLBACK_PAGE_FINAL_READ_TIMEOUT_MS = 2e3;
1529
+ var COMPLETION_UNCONFIRMED_MESSAGE = "Completion could not be confirmed; check the connection in Evident before retrying.";
1530
+ var KNOWN_CALLBACK_PARAMETERS = /* @__PURE__ */ new Set(["state", "code", "error", "error_description", "iss"]);
1531
+ var ApiHttpError = class extends Error {
1532
+ constructor(status2, operation) {
1533
+ super(`Evident API returned HTTP ${status2} while ${operation}`);
1534
+ this.status = status2;
1535
+ this.operation = operation;
1536
+ }
1537
+ };
1538
+ var CallbackExpiredError = class extends Error {
1539
+ constructor() {
1540
+ super("The local sign-in attempt expired before the provider returned.");
1541
+ }
1542
+ };
1543
+ var InterruptedError = class extends Error {
1544
+ constructor() {
1545
+ super("Authorization was interrupted.");
1546
+ }
1547
+ };
1548
+ function apiPath(proxyId, connectionId, suffix) {
1549
+ const path = `/mcp-proxies/${encodeURIComponent(proxyId)}`;
1550
+ if (!connectionId) return path + "/connections";
1551
+ return `${path}/connections/${encodeURIComponent(connectionId)}/local-authorization/${suffix}`;
1552
+ }
1553
+ async function requestJson(path, credentials2, cancelSignal, operation, body) {
1554
+ const method = body === void 0 ? "GET" : "POST";
1555
+ const requestController = new AbortController();
1556
+ const onCancel = () => requestController.abort();
1557
+ const timeout = setTimeout(() => requestController.abort(), API_TIMEOUT_MS);
1558
+ cancelSignal.addEventListener("abort", onCancel, { once: true });
1559
+ if (cancelSignal.aborted) onCancel();
1560
+ try {
1561
+ let response;
1562
+ try {
1563
+ response = await fetch(`${getApiUrlConfig()}${path}`, {
1564
+ method,
1565
+ headers: {
1566
+ ...buildAuthHeaders(credentials2),
1567
+ ...body === void 0 ? {} : { "Content-Type": "application/json" }
1568
+ },
1569
+ body: body === void 0 ? void 0 : JSON.stringify(body),
1570
+ signal: requestController.signal
1571
+ });
1572
+ } catch (error2) {
1573
+ if (cancelSignal.aborted) throw new InterruptedError();
1574
+ if (requestController.signal.aborted) {
1575
+ throw new Error(`Evident timed out while ${operation} after ${API_TIMEOUT_MS}ms.`);
1576
+ }
1577
+ const detail = error2 instanceof Error ? error2.message : String(error2);
1578
+ throw new Error(
1579
+ `Could not reach Evident while ${operation}: ${detail}. Check --endpoint or EVIDENT_API_URL and retry.`
1580
+ );
1581
+ }
1582
+ if (!response.ok) throw new ApiHttpError(response.status, operation);
1583
+ try {
1584
+ return await response.json();
1585
+ } catch (error2) {
1586
+ if (cancelSignal.aborted) throw new InterruptedError();
1587
+ if (requestController.signal.aborted) {
1588
+ throw new Error(`Evident timed out while ${operation} after ${API_TIMEOUT_MS}ms.`);
1589
+ }
1590
+ const detail = error2 instanceof Error ? error2.message : String(error2);
1591
+ throw new Error(`Evident returned an invalid response while ${operation}: ${detail}`);
1592
+ }
1593
+ } finally {
1594
+ clearTimeout(timeout);
1595
+ cancelSignal.removeEventListener("abort", onCancel);
1596
+ }
1597
+ }
1598
+ function callbackPage(statusPath) {
1599
+ const nonce = randomBytes(18).toString("base64url");
1600
+ const statusMarkup = statusPath ? `<main class="card" id="callback-page" data-status-url="${statusPath}" role="status" aria-live="polite" aria-atomic="true">
1601
+ <span class="dot" aria-hidden="true"></span>
1602
+ <h1 id="status-heading">Provider response received</h1>
1603
+ <p id="status-message">Your provider response is here. Evident is preparing the connection.</p>
1604
+ <ol class="steps" aria-label="Authorization progress">
1605
+ <li data-step="provider" data-state="done"><span class="step-mark" aria-hidden="true">\u2713</span><span>Provider response received</span></li>
1606
+ <li data-step="evident" data-state="pending"><span class="step-mark" aria-hidden="true">2</span><span>Evident completes authorization</span></li>
1607
+ <li data-step="connection" data-state="pending"><span class="step-mark" aria-hidden="true">3</span><span>Review tools in Evident</span></li>
1608
+ </ol>
1609
+ <p class="footnote" id="status-footnote">Keep this page open while Evident finishes. The terminal shows the same progress.</p>
1610
+ </main>` : `<main class="card" role="status">
1611
+ <span class="dot" aria-hidden="true"></span>
1612
+ <h1>Sign-in response not accepted</h1>
1613
+ <p>This response wasn\u2019t accepted. Return to the terminal for details, then retry authorization if needed.</p>
1614
+ </main>`;
1615
+ const script = statusPath ? `<script nonce="${nonce}">
1616
+ history.replaceState(null, '', location.pathname);
1617
+ const page = document.getElementById('callback-page');
1618
+ const statusUrl = page.dataset.statusUrl;
1619
+ const views = {
1620
+ received: {
1621
+ heading: 'Provider response received',
1622
+ message: 'Your provider response is here. Evident is preparing the connection.',
1623
+ footnote: 'Keep this page open while Evident finishes. The terminal shows the same progress.',
1624
+ steps: ['done', 'pending', 'pending'],
1625
+ },
1626
+ completing: {
1627
+ heading: 'Evident is finishing setup',
1628
+ message: 'Evident received the response and is completing authorization.',
1629
+ footnote: 'This can take a moment. The terminal shows the same progress.',
1630
+ steps: ['done', 'current', 'pending'],
1631
+ },
1632
+ success: {
1633
+ heading: 'Authorization confirmed',
1634
+ message:
1635
+ 'Evident confirmed authorization. Review the discovered tools in Evident to choose which to enable.',
1636
+ footnote: 'You can close this window.',
1637
+ steps: ['done', 'done', 'current'],
1638
+ },
1639
+ tools_pending: {
1640
+ heading: 'Authorization confirmed',
1641
+ message: 'Evident authorized the connection, but its tools are still being prepared.',
1642
+ footnote: 'Check the connection in Evident for tool status. You can close this window.',
1643
+ steps: ['done', 'done', 'current'],
1644
+ },
1645
+ failed: {
1646
+ heading: 'Sign-in did not finish',
1647
+ message: 'Evident could not complete setup. Check the terminal for the next step.',
1648
+ footnote: 'You can close this window after reading the terminal.',
1649
+ steps: ['done', 'failed', 'pending'],
1650
+ },
1651
+ unconfirmed: {
1652
+ heading: 'Completion could not be confirmed',
1653
+ message: 'Check the connection in Evident before retrying.',
1654
+ footnote: 'The terminal has the same status. Check the connection before starting another sign-in.',
1655
+ steps: ['done', 'uncertain', 'pending'],
1656
+ },
1657
+ };
1658
+ const terminalPhases = new Set(['success', 'tools_pending', 'failed', 'unconfirmed']);
1659
+ function showView(phase, view) {
1660
+ document.body.dataset.phase = phase;
1661
+ document.getElementById('status-heading').textContent = view.heading;
1662
+ document.getElementById('status-message').textContent = view.message;
1663
+ document.getElementById('status-footnote').textContent = view.footnote;
1664
+ ['provider', 'evident', 'connection'].forEach((name, index) => {
1665
+ const step = document.querySelector('[data-step="' + name + '"]');
1666
+ const state = view.steps[index];
1667
+ step.dataset.state = state;
1668
+ step.querySelector('.step-mark').textContent = state === 'done' ? '\u2713' : String(index + 1);
1669
+ });
1670
+ }
1671
+ async function poll() {
1672
+ try {
1673
+ const response = await fetch(statusUrl, {
1674
+ cache: 'no-store',
1675
+ credentials: 'omit',
1676
+ redirect: 'error',
1677
+ headers: { Accept: 'application/json' },
1678
+ });
1679
+ if (!response.ok) throw new Error('status unavailable');
1680
+ const result = await response.json();
1681
+ const view = views[result.phase];
1682
+ if (!view) throw new Error('unknown status');
1683
+ showView(result.phase, view);
1684
+ if (terminalPhases.has(result.phase)) return;
1685
+ } catch (_error) {
1686
+ document.getElementById('status-message').textContent =
1687
+ 'Evident is still finishing. Check the terminal for the latest status.';
1688
+ }
1689
+ window.setTimeout(poll, 400);
1690
+ }
1691
+ document.addEventListener('DOMContentLoaded', poll, { once: true });
1692
+ </script>` : `<script nonce="${nonce}">history.replaceState(null, '', location.pathname);</script>`;
1693
+ const html = `<!doctype html>
1694
+ <html lang="en">
1695
+ <head>
1696
+ <meta charset="utf-8" />
1697
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
1698
+ <meta name="robots" content="noindex" />
1699
+ <meta name="referrer" content="no-referrer" />
1700
+ <title>Sign-in \xB7 Evident</title>
1701
+ <style nonce="${nonce}">
1702
+ :root { color-scheme: light dark; }
1703
+ * { box-sizing: border-box; }
1704
+ body {
1705
+ margin: 0;
1706
+ min-height: 100vh;
1707
+ display: flex;
1708
+ align-items: center;
1709
+ justify-content: center;
1710
+ padding: 24px;
1711
+ font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
1712
+ background: #0b0d12;
1713
+ color: #e6e8ee;
1714
+ }
1715
+ .card {
1716
+ width: 100%;
1717
+ max-width: 420px;
1718
+ text-align: center;
1719
+ background: #12151c;
1720
+ border: 1px solid #232838;
1721
+ border-radius: 16px;
1722
+ padding: 36px 24px;
1723
+ box-shadow: 0 10px 40px rgba(0, 0, 0, 0.35);
1724
+ }
1725
+ .dot {
1726
+ width: 12px;
1727
+ height: 12px;
1728
+ border-radius: 50%;
1729
+ background: #f59e0b;
1730
+ display: inline-block;
1731
+ margin-bottom: 20px;
1732
+ box-shadow: 0 0 0 4px rgba(245, 158, 11, 0.15);
1733
+ }
1734
+ body[data-phase="success"] .dot {
1735
+ background: #34d399;
1736
+ box-shadow: 0 0 0 4px rgba(52, 211, 153, 0.15);
1737
+ }
1738
+ body[data-phase="failed"] .dot {
1739
+ background: #fb7185;
1740
+ box-shadow: 0 0 0 4px rgba(251, 113, 133, 0.15);
1741
+ }
1742
+ h1 { font-size: 20px; margin: 0 0 8px; font-weight: 600; }
1743
+ p { margin: 0; color: #9aa2b4; font-size: 14px; line-height: 1.5; }
1744
+ .steps { list-style: none; margin: 24px 0 0; padding: 0; text-align: left; }
1745
+ .steps li {
1746
+ display: flex;
1747
+ align-items: center;
1748
+ gap: 12px;
1749
+ min-height: 48px;
1750
+ border-top: 1px solid #232838;
1751
+ color: #9aa2b4;
1752
+ font-size: 14px;
1753
+ }
1754
+ .step-mark {
1755
+ width: 24px;
1756
+ height: 24px;
1757
+ border: 1px solid #42495b;
1758
+ border-radius: 50%;
1759
+ display: inline-flex;
1760
+ align-items: center;
1761
+ justify-content: center;
1762
+ flex: 0 0 auto;
1763
+ font-size: 12px;
1764
+ }
1765
+ [data-state="done"] { color: #e6e8ee !important; }
1766
+ [data-state="done"] .step-mark { border-color: #34d399; color: #34d399; }
1767
+ [data-state="current"] { color: #e6e8ee !important; }
1768
+ [data-state="current"] .step-mark { border-color: #f59e0b; color: #fbbf24; }
1769
+ [data-state="failed"] .step-mark { border-color: #fb7185; color: #fb7185; }
1770
+ [data-state="uncertain"] .step-mark { border-color: #f59e0b; color: #fbbf24; }
1771
+ .footnote { margin-top: 20px; font-size: 12px; }
1772
+ @media (max-width: 480px) {
1773
+ body { padding: 16px; }
1774
+ .card { padding: 32px 20px; }
1775
+ }
1776
+ </style>
1777
+ </head>
1778
+ <body>${statusMarkup}${script}</body>
1779
+ </html>`;
1780
+ return { html, nonce };
1781
+ }
1782
+ function callbackResponse(response, status2, html, nonce, onFinish) {
1783
+ response.writeHead(status2, {
1784
+ "Content-Type": "text/html; charset=utf-8",
1785
+ "Cache-Control": "no-store",
1786
+ Pragma: "no-cache",
1787
+ "Content-Security-Policy": `default-src 'none'; script-src 'nonce-${nonce}'; style-src 'nonce-${nonce}'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`,
1788
+ "X-Content-Type-Options": "nosniff",
1789
+ "X-Frame-Options": "DENY",
1790
+ "Referrer-Policy": "no-referrer",
1791
+ "Cross-Origin-Resource-Policy": "same-origin"
1792
+ });
1793
+ response.end(html, onFinish);
1794
+ }
1795
+ function statusResponse(response, status2, phase, onFinish) {
1796
+ response.writeHead(status2, {
1797
+ "Content-Type": "application/json; charset=utf-8",
1798
+ "Cache-Control": "no-store",
1799
+ Pragma: "no-cache",
1800
+ "Content-Security-Policy": "default-src 'none'; frame-ancestors 'none'",
1801
+ "X-Content-Type-Options": "nosniff",
1802
+ "X-Frame-Options": "DENY",
1803
+ "Referrer-Policy": "no-referrer",
1804
+ "Cross-Origin-Resource-Policy": "same-origin"
1805
+ });
1806
+ response.end(phase ? JSON.stringify({ phase }) : "", onFinish);
1807
+ }
1808
+ function isTerminalPagePhase(phase) {
1809
+ return phase === "success" || phase === "tools_pending" || phase === "failed" || phase === "unconfirmed";
1810
+ }
1811
+ function waitForTerminalStatusRead(page, signal) {
1812
+ if (page.terminalRead || signal.aborted) return Promise.resolve();
1813
+ return new Promise((resolve6) => {
1814
+ let settled = false;
1815
+ const finish = () => {
1816
+ if (settled) return;
1817
+ settled = true;
1818
+ clearTimeout(timer);
1819
+ signal.removeEventListener("abort", finish);
1820
+ if (page.notifyTerminalRead === finish) page.notifyTerminalRead = void 0;
1821
+ resolve6();
1822
+ };
1823
+ const timer = setTimeout(finish, CALLBACK_PAGE_FINAL_READ_TIMEOUT_MS);
1824
+ page.notifyTerminalRead = finish;
1825
+ signal.addEventListener("abort", finish, { once: true });
1826
+ if (signal.aborted) finish();
1827
+ });
1828
+ }
1829
+ function handleStatusRequest(request3, response, page) {
1830
+ if (!request3.url?.startsWith("/_status/")) return false;
1831
+ const statusPath = `/_status/${page.capability}`;
1832
+ const base = page.origin ?? `http://${MCP_LOOPBACK_REDIRECT_POLICY.host}`;
1833
+ const url = URL.canParse(request3.url, base) ? new URL(request3.url, base) : void 0;
1834
+ const fetchSite = request3.headers["sec-fetch-site"];
1835
+ if (request3.method !== "GET" || !url || url.pathname !== statusPath || url.search || request3.headers.host !== page.host || fetchSite !== void 0 && fetchSite !== "same-origin" || request3.headers.origin !== void 0 && request3.headers.origin !== page.origin || request3.headers["transfer-encoding"] !== void 0 || Number(request3.headers["content-length"] ?? 0) > 0) {
1836
+ statusResponse(response, 404);
1837
+ return true;
1838
+ }
1839
+ const phase = page.phase;
1840
+ statusResponse(response, 200, phase, () => {
1841
+ if (isTerminalPagePhase(phase)) {
1842
+ page.terminalRead = true;
1843
+ page.notifyTerminalRead?.();
1844
+ }
1845
+ });
1846
+ return true;
1847
+ }
1848
+ function rejectedCallbackResponse(response, status2) {
1849
+ const page = callbackPage();
1850
+ callbackResponse(response, status2, page.html, page.nonce);
1851
+ }
1852
+ function parseCallbackRequest(request3) {
1853
+ if (request3.method !== "GET" || !request3.url || !request3.url.startsWith("/") || request3.url.length > 16384) {
1854
+ return { reason: "malformed_response" };
1855
+ }
1856
+ if (request3.headers["transfer-encoding"] || Number(request3.headers["content-length"] ?? 0) > 0) {
1857
+ return { reason: "malformed_response" };
1858
+ }
1859
+ const callbackBase = `http://${MCP_LOOPBACK_REDIRECT_POLICY.host}`;
1860
+ if (!URL.canParse(request3.url, callbackBase)) return { reason: "malformed_response" };
1861
+ const url = new URL(request3.url, callbackBase);
1862
+ if (url.pathname !== MCP_LOOPBACK_REDIRECT_POLICY.path || url.hash) {
1863
+ return { reason: "malformed_response" };
1864
+ }
1865
+ for (const parameter of url.search.slice(1).split("&")) {
1866
+ const separator = parameter.indexOf("=");
1867
+ const rawKey = separator === -1 ? parameter : parameter.slice(0, separator);
1868
+ let key;
1869
+ try {
1870
+ key = decodeURIComponent(rawKey.replaceAll("+", " "));
1871
+ } catch (_error) {
1872
+ continue;
1873
+ }
1874
+ if (!KNOWN_CALLBACK_PARAMETERS.has(key)) continue;
1875
+ const rawValue = separator === -1 ? "" : parameter.slice(separator + 1);
1876
+ try {
1877
+ decodeURIComponent(rawValue.replaceAll("+", " "));
1878
+ } catch (_error) {
1879
+ return { reason: "malformed_response" };
1880
+ }
1881
+ }
1882
+ const params = url.searchParams;
1883
+ for (const key of ["state", "code", "error", "error_description", "iss"]) {
1884
+ if (params.getAll(key).length > 1) return { reason: "malformed_response" };
1885
+ }
1886
+ const state = params.get("state");
1887
+ const code = params.get("code");
1888
+ const error2 = params.get("error");
1889
+ const errorDescription = params.get("error_description");
1890
+ const issuer = params.get("iss");
1891
+ if (!state || state.length > 2048 || Boolean(code) === Boolean(error2) || code !== null && (!code || code.length > 8192) || error2 !== null && (!error2 || error2.length > 256) || errorDescription !== null && (!error2 || errorDescription.length > 2048) || issuer !== null && (!issuer || issuer.length > 2048)) {
1892
+ return { reason: "malformed_response" };
1893
+ }
1894
+ return {
1895
+ callback: {
1896
+ state,
1897
+ ...code === null ? {} : { code },
1898
+ ...error2 === null ? {} : { error: error2 },
1899
+ ...errorDescription === null ? {} : { error_description: errorDescription },
1900
+ ...issuer === null ? {} : { iss: issuer }
1901
+ }
1902
+ };
1903
+ }
1904
+ function reportProgress(options, event, message, details = {}) {
1905
+ if (options.json) {
1906
+ console.error(JSON.stringify({ event, ...details }));
1907
+ } else {
1908
+ console.error(message);
1909
+ }
1910
+ }
1911
+ function rejectCallback(response, options, reason) {
1912
+ rejectedCallbackResponse(response, 400);
1913
+ reportProgress(options, "callback_rejected", callbackRejectionMessage(reason), {
1914
+ reason,
1915
+ action: "still_waiting"
1916
+ });
1917
+ }
1918
+ function callbackRejectionMessage(reason) {
1919
+ switch (reason) {
1920
+ case "malformed_response":
1921
+ return "The callback had a malformed response; authorization is still waiting for a valid response. Retry authorization if needed.";
1922
+ case "state_mismatch":
1923
+ return "The callback had a state mismatch; authorization is still waiting for a valid response. Retry authorization if needed.";
1924
+ case "issuer_missing":
1925
+ return "The callback was missing its issuer; authorization is still waiting for a valid response. Update the provider or retry authorization.";
1926
+ case "issuer_mismatch":
1927
+ return "The callback had an issuer mismatch; authorization is still waiting for a valid response. Retry authorization if needed.";
1928
+ case "issuer_unavailable":
1929
+ return "The Evident endpoint has issuer validation unavailable; authorization is still waiting for a valid response. Update the endpoint or start a new authorization.";
1930
+ case "attempt_not_ready":
1931
+ return "The authorization attempt is not ready yet; authorization is still waiting for a valid response while Evident finishes starting it.";
1932
+ case "attempt_expired":
1933
+ return "The authorization attempt expired; authorization is still waiting for a valid response. Start a new authorization.";
1934
+ }
1935
+ }
1936
+ function handleCallbackRequest(request3, response, waiter, options, page) {
1937
+ if (handleStatusRequest(request3, response, page)) return;
1938
+ if (!request3.url || !request3.url.startsWith("/") || !URL.canParse(request3.url, `http://${MCP_LOOPBACK_REDIRECT_POLICY.host}`)) {
1939
+ rejectCallback(response, options, "malformed_response");
1940
+ return;
1941
+ }
1942
+ const pathname = new URL(request3.url, `http://${MCP_LOOPBACK_REDIRECT_POLICY.host}`).pathname;
1943
+ if (pathname !== MCP_LOOPBACK_REDIRECT_POLICY.path) {
1944
+ rejectedCallbackResponse(response, 404);
1945
+ return;
1946
+ }
1947
+ if (request3.method !== "GET") {
1948
+ response.setHeader("Allow", "GET");
1949
+ rejectedCallbackResponse(response, 405);
1950
+ return;
1951
+ }
1952
+ if (waiter.accepted) {
1953
+ rejectedCallbackResponse(response, 409);
1954
+ return;
1955
+ }
1956
+ const parsed = parseCallbackRequest(request3);
1957
+ if (!("callback" in parsed)) {
1958
+ rejectCallback(response, options, parsed.reason);
1959
+ return;
1960
+ }
1961
+ const callback = parsed.callback;
1962
+ const expiresAtMs = waiter.expiresAtMs;
1963
+ let rejectionReason;
1964
+ if (expiresAtMs === void 0) {
1965
+ rejectionReason = "attempt_not_ready";
1966
+ } else if (Date.now() >= expiresAtMs) {
1967
+ rejectionReason = "attempt_expired";
1968
+ } else if (!waiter.expectedState || callback.state !== waiter.expectedState) {
1969
+ rejectionReason = "state_mismatch";
1970
+ } else if (waiter.issuerParameterSupported && callback.iss === void 0) {
1971
+ rejectionReason = "issuer_missing";
1972
+ } else if (callback.iss !== void 0 && waiter.expectedIssuer === void 0) {
1973
+ rejectionReason = "issuer_unavailable";
1974
+ } else if (callback.iss !== void 0 && callback.iss !== waiter.expectedIssuer) {
1975
+ rejectionReason = "issuer_mismatch";
1976
+ }
1977
+ if (rejectionReason) {
1978
+ rejectCallback(response, options, rejectionReason);
1979
+ return;
1980
+ }
1981
+ waiter.accepted = true;
1982
+ page.phase = "received";
1983
+ reportProgress(options, "callback_received", "Provider sign-in response received.");
1984
+ const callbackPageResponse = callbackPage(`/_status/${page.capability}`);
1985
+ callbackResponse(
1986
+ response,
1987
+ 200,
1988
+ callbackPageResponse.html,
1989
+ callbackPageResponse.nonce,
1990
+ () => waiter.resolve?.(callback)
1991
+ );
1992
+ }
1993
+ function listen(server, port) {
1994
+ return new Promise((resolve6, reject) => {
1995
+ const onError = (error2) => reject(error2);
1996
+ server.once("error", onError);
1997
+ server.listen(port, MCP_LOOPBACK_REDIRECT_POLICY.host, () => {
1998
+ server.removeListener("error", onError);
1999
+ const address = server.address();
2000
+ if (!address || typeof address === "string") {
2001
+ reject(new Error("The local callback listener did not report a TCP port."));
2002
+ return;
2003
+ }
2004
+ resolve6(address.port);
2005
+ });
2006
+ });
2007
+ }
2008
+ function isAddressInUse(error2) {
2009
+ return typeof error2 === "object" && error2 !== null && "code" in error2 && error2.code === "EADDRINUSE";
2010
+ }
2011
+ async function bindCallbackListener(waiter, options, page) {
2012
+ const createListener = () => createServer(
2013
+ (request3, response) => handleCallbackRequest(request3, response, waiter, options, page)
2014
+ );
2015
+ try {
2016
+ const server2 = createListener();
2017
+ return { server: server2, port: await listen(server2, MCP_LOOPBACK_REDIRECT_POLICY.preferred_port) };
2018
+ } catch (error2) {
2019
+ if (!isAddressInUse(error2)) {
2020
+ throw new Error(
2021
+ `Could not listen on 127.0.0.1:${MCP_LOOPBACK_REDIRECT_POLICY.preferred_port}: ${error2 instanceof Error ? error2.message : String(error2)}`
2022
+ );
2023
+ }
2024
+ }
2025
+ const server = createListener();
2026
+ try {
2027
+ return { server, port: await listen(server, 0) };
2028
+ } catch (error2) {
2029
+ throw new Error(
2030
+ `Could not bind the local callback listener on preferred port ${MCP_LOOPBACK_REDIRECT_POLICY.preferred_port} or an ephemeral port: ${error2 instanceof Error ? error2.message : String(error2)}`
2031
+ );
2032
+ }
2033
+ }
2034
+ function waitForCallback(waiter, expiresAtMs, signal) {
2035
+ return new Promise((resolve6, reject) => {
2036
+ const remainingMs = expiresAtMs - Date.now();
2037
+ if (remainingMs <= 0) {
2038
+ reject(new CallbackExpiredError());
2039
+ return;
2040
+ }
2041
+ if (signal.aborted) {
2042
+ reject(new InterruptedError());
2043
+ return;
2044
+ }
2045
+ let settled = false;
2046
+ function settle(callback, error2) {
2047
+ if (settled) return;
2048
+ settled = true;
2049
+ clearTimeout(timer);
2050
+ signal.removeEventListener("abort", onAbort);
2051
+ waiter.resolve = void 0;
2052
+ if (error2) reject(error2);
2053
+ else resolve6(callback);
2054
+ }
2055
+ const onAbort = () => settle(void 0, new InterruptedError());
2056
+ const timer = setTimeout(() => settle(void 0, new CallbackExpiredError()), remainingMs);
2057
+ waiter.expiresAtMs = expiresAtMs;
2058
+ waiter.resolve = (callback) => settle(callback);
2059
+ timer.unref?.();
2060
+ signal.addEventListener("abort", onAbort, { once: true });
2061
+ if (signal.aborted) onAbort();
2062
+ });
2063
+ }
2064
+ function authorizationState(authorizationUrl) {
2065
+ let url;
2066
+ try {
2067
+ url = new URL(authorizationUrl);
2068
+ } catch (error2) {
2069
+ throw new Error(
2070
+ `Evident returned an invalid authorization URL: ${error2 instanceof Error ? error2.message : String(error2)}`
2071
+ );
2072
+ }
2073
+ const states = url.searchParams.getAll("state");
2074
+ if (url.protocol !== "https:" || url.username || url.password || url.hash || states.length !== 1 || !states[0]) {
2075
+ throw new Error("Evident returned an unsafe or incomplete authorization URL.");
2076
+ }
2077
+ return { url, state: states[0] };
2078
+ }
2079
+ function apiFailureMessage(error2) {
2080
+ const context = `Evident returned HTTP ${error2.status} while ${error2.operation}.`;
2081
+ switch (error2.status) {
2082
+ case 400:
2083
+ return `${context} Retry the command; if it continues, update the CLI and try again.`;
2084
+ case 401:
2085
+ return `${context} Your Evident user session is missing or expired. If EVIDENT_TOKEN is set, update or unset it; otherwise run \`evident login\` for the selected endpoint, then retry.`;
2086
+ case 403:
2087
+ return `${context} Only workspace owners and admins can authorize MCP connections. Ask a workspace admin for access.`;
2088
+ case 404:
2089
+ return `${context} Confirm the proxy and connection IDs and that this CLI user can access the proxy.`;
2090
+ case 409:
2091
+ return `${context} This connection does not support local sign-in. Use its hosted authorization flow in Evident.`;
2092
+ case 502:
2093
+ case 503:
2094
+ return `${context} The Evident MCP authorization service is unavailable. Retry shortly or contact your workspace admin.`;
2095
+ default:
2096
+ return `${context} Check your endpoint and retry.`;
2097
+ }
2098
+ }
2099
+ function completionFailureMessage(reason) {
2100
+ switch (reason) {
2101
+ case "state_unknown":
2102
+ return "This sign-in was started by another user or could not be found. Start a new authorization from the same user account.";
2103
+ case "state_consumed":
2104
+ return "This sign-in was already used. Start a new authorization.";
2105
+ case "state_expired":
2106
+ return "This sign-in attempt expired. Start a new authorization.";
2107
+ case "issuer_unavailable":
2108
+ return "This sign-in attempt predates issuer validation. Start a new authorization.";
2109
+ case "issuer_missing":
2110
+ return "The provider response did not include its required issuer. Start a new authorization and update the CLI if needed.";
2111
+ case "issuer_mismatch":
2112
+ return "The provider response came from an unexpected issuer. Start a new authorization and contact support if it continues.";
2113
+ case "invalid_response":
2114
+ return "The provider returned an invalid sign-in response. Start a new authorization.";
2115
+ case "provider_denied":
2116
+ return "The provider denied the sign-in. Retry and approve the requested access.";
2117
+ case "provider_error":
2118
+ return "The provider could not complete sign-in. Retry, or contact the provider if it continues.";
2119
+ case "exchange_failed":
2120
+ return "The provider sign-in completed, but Evident could not exchange the authorization. Retry or contact support.";
2121
+ case "reconcile_failed":
2122
+ case "tools_pending":
2123
+ return "Sign-in completed, but Evident could not finish setting up this connection. Retry or contact support.";
2124
+ case "not_configured":
2125
+ return "Local authorization is not configured for this Evident environment. Contact your workspace admin.";
2126
+ default:
2127
+ return "Evident could not complete this sign-in. Start a new authorization and try again.";
2128
+ }
2129
+ }
2130
+ function printLink(options, url, reason) {
2131
+ if (options.json) {
2132
+ console.error(JSON.stringify({ event: "authorization_required", authorization_url: url.href }));
2133
+ return;
2134
+ }
2135
+ printWarning(reason ?? "Open this authorization URL in your browser:");
2136
+ console.log(url.href);
2137
+ }
2138
+ function printResult(options, proxyId, connectionId, error2, successMessage = "MCP connection authorized.", reason) {
2139
+ if (options.json) {
2140
+ console.log(
2141
+ JSON.stringify({
2142
+ ok: !error2,
2143
+ proxy_id: proxyId,
2144
+ connection_id: connectionId,
2145
+ ...error2 ? { error: error2 } : {},
2146
+ ...reason ? { reason } : {}
2147
+ })
2148
+ );
2149
+ } else if (error2) {
2150
+ printError(error2);
2151
+ } else {
2152
+ printSuccess(successMessage);
2153
+ }
2154
+ }
2155
+ function errorMessage(error2) {
2156
+ if (error2 instanceof ApiHttpError) return apiFailureMessage(error2);
2157
+ if (error2 instanceof CallbackExpiredError) {
2158
+ return "The sign-in attempt expired before the provider returned. Run the command again.";
2159
+ }
2160
+ if (error2 instanceof InterruptedError) return "Authorization was interrupted.";
2161
+ if (error2 instanceof Error) return error2.message;
2162
+ return `Authorization failed: ${String(error2)}`;
2163
+ }
2164
+ function requestFailed(reason) {
2165
+ if (reason instanceof Error) throw reason;
2166
+ throw new Error(`Authorization failed: ${String(reason)}`);
2167
+ }
2168
+ function validateConnectionList(value) {
2169
+ if (!value || !Array.isArray(value.mcp_proxy_connections)) {
2170
+ throw new Error("Evident returned an invalid MCP connection list. Update the CLI and retry.");
2171
+ }
2172
+ return value.mcp_proxy_connections;
2173
+ }
2174
+ function validateBeginResponse(value) {
2175
+ if (!value || typeof value.authorization_url !== "string" || typeof value.expires_at !== "string" || !Number.isFinite(Date.parse(value.expires_at)) || value.issuer !== void 0 && (typeof value.issuer !== "string" || value.issuer.length === 0 || value.issuer.length > 2048) || value.authorization_response_iss_parameter_supported !== void 0 && typeof value.authorization_response_iss_parameter_supported !== "boolean" || value.issuer === void 0 !== (value.authorization_response_iss_parameter_supported === void 0)) {
2176
+ throw new Error(
2177
+ "Evident returned an invalid local authorization attempt. Update the CLI and retry."
2178
+ );
2179
+ }
2180
+ }
2181
+ async function startBrowser(url) {
2182
+ const child = await open2(url);
2183
+ let signalFailure = () => void 0;
2184
+ const failure = new Promise((resolve6) => {
2185
+ signalFailure = resolve6;
2186
+ });
2187
+ child.once("error", signalFailure);
2188
+ child.once("close", (code) => {
2189
+ if (code !== 0) signalFailure();
2190
+ });
2191
+ await new Promise((resolve6, reject) => {
2192
+ if (child.pid !== void 0) {
2193
+ resolve6();
2194
+ return;
2195
+ }
2196
+ child.once("spawn", resolve6);
2197
+ child.once("error", reject);
2198
+ });
2199
+ return { failure };
2200
+ }
2201
+ function closeServer(server, force) {
2202
+ if (!server.listening) return Promise.resolve();
2203
+ return new Promise((resolve6, reject) => {
2204
+ server.close((error2) => error2 ? reject(error2) : resolve6());
2205
+ if (force) server.closeAllConnections();
2206
+ });
2207
+ }
2208
+ async function authorizeMcpConnection(proxyId, connectionId, options = {}) {
2209
+ let credentials2;
2210
+ try {
2211
+ credentials2 = await getAuthCredentials();
2212
+ } catch (error2) {
2213
+ const kind = error2 instanceof Error ? error2.name : "unknown error";
2214
+ printResult(
2215
+ options,
2216
+ proxyId,
2217
+ connectionId,
2218
+ `Could not read the saved Evident credentials (${kind}). Check keychain access or run evident login again.`
2219
+ );
2220
+ process.exitCode = 1;
2221
+ return;
2222
+ }
2223
+ if (!credentials2) {
2224
+ printResult(
2225
+ options,
2226
+ proxyId,
2227
+ connectionId,
2228
+ "No credentials found. Run `evident login` and retry."
2229
+ );
2230
+ process.exitCode = 1;
2231
+ return;
2232
+ }
2233
+ if (credentials2.authType !== "bearer") {
2234
+ printResult(
2235
+ options,
2236
+ proxyId,
2237
+ connectionId,
2238
+ "MCP authorization requires a user login, not a runner key. Unset EVIDENT_RUNNER_KEY/EVIDENT_AGENT_KEY, then run `evident login`."
2239
+ );
2240
+ process.exitCode = 1;
2241
+ return;
2242
+ }
2243
+ const waiter = { accepted: false };
2244
+ const page = {
2245
+ capability: randomBytes(32).toString("base64url"),
2246
+ phase: "waiting",
2247
+ terminalRead: false
2248
+ };
2249
+ let server;
2250
+ let closePromise;
2251
+ let closeFailureLogged = false;
2252
+ let failure;
2253
+ let successMessage = "MCP connection authorized.";
2254
+ let completionReason;
2255
+ const cancelController = new AbortController();
2256
+ const closeListener = (force = false) => {
2257
+ if (!server || closePromise) return closePromise ?? Promise.resolve();
2258
+ closePromise = closeServer(server, force);
2259
+ return closePromise;
2260
+ };
2261
+ const onSigint = () => {
2262
+ cancelController.abort();
2263
+ void closeListener(true).catch((error2) => {
2264
+ closeFailureLogged = true;
2265
+ console.error(
2266
+ `[mcp authorize] listener shutdown failed for proxy_id=${JSON.stringify(proxyId)} connection_id=${JSON.stringify(connectionId)}: ${error2 instanceof Error ? error2.message : String(error2)}`
2267
+ );
2268
+ });
2269
+ };
2270
+ try {
2271
+ const listener = await bindCallbackListener(waiter, options, page);
2272
+ server = listener.server;
2273
+ process.once("SIGINT", onSigint);
2274
+ page.host = `${MCP_LOOPBACK_REDIRECT_POLICY.host}:${listener.port}`;
2275
+ page.origin = `${MCP_LOOPBACK_REDIRECT_POLICY.scheme}://${page.host}`;
2276
+ const redirectUri = `${MCP_LOOPBACK_REDIRECT_POLICY.scheme}://${MCP_LOOPBACK_REDIRECT_POLICY.host}:${listener.port}${MCP_LOOPBACK_REDIRECT_POLICY.path}`;
2277
+ const fallback = listener.port !== MCP_LOOPBACK_REDIRECT_POLICY.preferred_port;
2278
+ reportProgress(
2279
+ options,
2280
+ fallback ? "listener_fallback" : "listener_ready",
2281
+ fallback ? `Port ${MCP_LOOPBACK_REDIRECT_POLICY.preferred_port} is busy; listening at ${redirectUri}.` : `Listening for the sign-in response at ${redirectUri}.`,
2282
+ {
2283
+ callback_url: redirectUri,
2284
+ ...fallback ? { preferred_port: MCP_LOOPBACK_REDIRECT_POLICY.preferred_port } : {},
2285
+ port: listener.port
2286
+ }
2287
+ );
2288
+ const connectionList = await requestJson(
2289
+ apiPath(proxyId),
2290
+ credentials2,
2291
+ cancelController.signal,
2292
+ "checking the MCP connection"
2293
+ );
2294
+ const connection = validateConnectionList(connectionList).find(
2295
+ (candidate) => candidate.connection_id === connectionId
2296
+ );
2297
+ if (!connection)
2298
+ throw new Error("The MCP connection was not found. Check the connection ID and try again.");
2299
+ if (connection.authorization_mode !== "local") {
2300
+ throw new Error("This connection uses hosted sign-in. Authorize it from Evident instead.");
2301
+ }
2302
+ if (connection.auth_kind !== "oauth2") {
2303
+ throw new Error("This MCP connection does not support OAuth authorization.");
2304
+ }
2305
+ reportProgress(options, "authorization_starting", "Starting authorization with Evident.");
2306
+ const begin = await requestJson(
2307
+ apiPath(proxyId, connectionId, "begin"),
2308
+ credentials2,
2309
+ cancelController.signal,
2310
+ "starting local authorization",
2311
+ { redirect_uri: redirectUri }
2312
+ );
2313
+ validateBeginResponse(begin);
2314
+ const { url: authorizationUrl, state } = authorizationState(begin.authorization_url);
2315
+ waiter.expectedState = state;
2316
+ waiter.expectedIssuer = begin.issuer;
2317
+ waiter.issuerParameterSupported = begin.authorization_response_iss_parameter_supported;
2318
+ const expiresAtMs = Date.parse(begin.expires_at);
2319
+ if (expiresAtMs <= Date.now()) throw new CallbackExpiredError();
2320
+ waiter.expiresAtMs = expiresAtMs;
2321
+ const callbackOutcome = waitForCallback(waiter, expiresAtMs, cancelController.signal).then(
2322
+ (callback2) => ({ ok: true, callback: callback2 }),
2323
+ (error2) => ({ ok: false, error: error2 })
2324
+ );
2325
+ const waitForCallbackWithProgress = (linkReason) => {
2326
+ if (linkReason) printLink(options, authorizationUrl, linkReason);
2327
+ reportProgress(
2328
+ options,
2329
+ "waiting_for_callback",
2330
+ "Waiting for the provider to return to this computer."
2331
+ );
2332
+ return (async () => {
2333
+ const outcome = await callbackOutcome;
2334
+ if (!outcome.ok) requestFailed(outcome.error);
2335
+ return outcome.callback;
2336
+ })();
2337
+ };
2338
+ let callback;
2339
+ if (options.noBrowser) {
2340
+ callback = await waitForCallbackWithProgress("Open this authorization URL in your browser:");
2341
+ } else {
2342
+ reportProgress(
2343
+ options,
2344
+ "opening_browser",
2345
+ "Opening the provider authorization page in your browser."
2346
+ );
2347
+ const browserOutcome = startBrowser(authorizationUrl.href).then(
2348
+ ({ failure: browserFailure }) => ({ ok: true, failure: browserFailure }),
2349
+ () => ({ ok: false })
2350
+ );
2351
+ const first = await Promise.race([
2352
+ browserOutcome.then((outcome) => ({ kind: "browser", outcome })),
2353
+ callbackOutcome.then((outcome) => ({ kind: "callback", outcome }))
2354
+ ]);
2355
+ if (first.kind === "callback") {
2356
+ if (!first.outcome.ok) requestFailed(first.outcome.error);
2357
+ callback = first.outcome.callback;
2358
+ } else {
2359
+ if (!first.outcome.ok) {
2360
+ callback = await waitForCallbackWithProgress(
2361
+ "Could not open the browser automatically. Open this URL:"
2362
+ );
2363
+ } else {
2364
+ const callbackWait = waitForCallbackWithProgress();
2365
+ const waitOutcome = await Promise.race([
2366
+ callbackWait.then(
2367
+ (value) => ({ kind: "callback", value }),
2368
+ (error2) => ({ kind: "callback_error", error: error2 })
2369
+ ),
2370
+ first.outcome.failure.then(() => ({ kind: "browser_failure" }))
2371
+ ]);
2372
+ if (waitOutcome.kind === "callback") {
2373
+ callback = waitOutcome.value;
2374
+ } else if (waitOutcome.kind === "callback_error") {
2375
+ requestFailed(waitOutcome.error);
2376
+ } else {
2377
+ printLink(
2378
+ options,
2379
+ authorizationUrl,
2380
+ "The browser could not keep the authorization page open. Open this URL:"
2381
+ );
2382
+ callback = await callbackWait;
2383
+ }
2384
+ }
2385
+ }
2386
+ }
2387
+ reportProgress(options, "forwarding_callback", "Forwarding the sign-in response to Evident.");
2388
+ const completionBody = {
2389
+ state: callback.state,
2390
+ ...callback.code === void 0 ? {} : { code: callback.code },
2391
+ ...callback.error === void 0 ? {} : { error: callback.error },
2392
+ ...callback.error_description === void 0 ? {} : { error_description: callback.error_description },
2393
+ ...callback.iss === void 0 ? {} : { iss: callback.iss }
2394
+ };
2395
+ reportProgress(options, "completing_authorization", "Completing authorization with Evident.");
2396
+ page.phase = "completing";
2397
+ const completion = await requestJson(
2398
+ apiPath(proxyId, connectionId, "complete"),
2399
+ credentials2,
2400
+ cancelController.signal,
2401
+ "completing local authorization",
2402
+ completionBody
2403
+ );
2404
+ if (completion.outcome === "success") {
2405
+ if (completion.reason === "tools_pending") {
2406
+ completionReason = completion.reason;
2407
+ page.phase = "tools_pending";
2408
+ reportProgress(
2409
+ options,
2410
+ "tools_pending",
2411
+ "Authorization confirmed; Evident is still preparing its tools."
2412
+ );
2413
+ successMessage = "MCP connection authorized. Evident is still preparing its tools.";
2414
+ } else {
2415
+ page.phase = "success";
2416
+ }
2417
+ } else {
2418
+ page.phase = "failed";
2419
+ failure = completionFailureMessage(completion.reason);
2420
+ }
2421
+ } catch (error2) {
2422
+ if (waiter.accepted && !isTerminalPagePhase(page.phase)) {
2423
+ page.phase = "unconfirmed";
2424
+ failure = `${COMPLETION_UNCONFIRMED_MESSAGE} ${errorMessage(error2)}`;
2425
+ } else {
2426
+ failure = errorMessage(error2);
2427
+ }
2428
+ } finally {
2429
+ try {
2430
+ if (waiter.accepted && isTerminalPagePhase(page.phase) && !cancelController.signal.aborted) {
2431
+ await waitForTerminalStatusRead(page, cancelController.signal);
2432
+ }
2433
+ process.removeListener("SIGINT", onSigint);
2434
+ await closeListener();
2435
+ } catch (error2) {
2436
+ const detail = error2 instanceof Error ? error2.message : String(error2);
2437
+ if (!closeFailureLogged) {
2438
+ console.error(
2439
+ `[mcp authorize] listener teardown failed for proxy_id=${JSON.stringify(proxyId)} connection_id=${JSON.stringify(connectionId)}: ${detail}`
2440
+ );
2441
+ }
2442
+ failure ??= "The local callback listener could not be closed cleanly. Check for a lingering process and retry.";
2443
+ }
2444
+ }
2445
+ printResult(options, proxyId, connectionId, failure, successMessage, completionReason);
2446
+ if (failure) process.exitCode = cancelController.signal.aborted ? 130 : 1;
2447
+ }
2448
+
1480
2449
  // src/commands/run.ts
2450
+ import { randomUUID as randomUUID2 } from "node:crypto";
2451
+ import { chmodSync as chmodSync3, existsSync as existsSync3, readFileSync as readFileSync12, writeFileSync as writeFileSync9 } from "node:fs";
2452
+ import { homedir as homedir9 } from "node:os";
2453
+ import { isAbsolute as isAbsolute6, join as join17, parse, resolve as resolvePath2 } from "node:path";
2454
+ import chalk7 from "chalk";
1481
2455
  import ora4 from "ora";
1482
2456
  import { select as select4 } from "@inquirer/prompts";
1483
2457
 
2458
+ // src/lib/opencode-start-timeout.ts
2459
+ var OPENCODE_START_TIMEOUT_ENV = "EVIDENT_OPENCODE_START_TIMEOUT";
2460
+
1484
2461
  // src/lib/telemetry.ts
1485
- var CLI_VERSION = (true ? "3.6.1-dev.547a214" : void 0) ?? process.env.npm_package_version ?? "unknown";
2462
+ var CLI_VERSION = (true ? "3.6.1-dev.5c4c582" : void 0) ?? process.env.npm_package_version ?? "unknown";
1486
2463
  function getCliVersion() {
1487
2464
  return CLI_VERSION;
1488
2465
  }
@@ -1679,7 +2656,7 @@ var SESSION_DB_RECLAIM_CHUNK_PAGES = 100;
1679
2656
  var SESSION_DB_RECLAIM_TIME_BUDGET_MS = 500;
1680
2657
  var SESSION_DB_RECLAIM_PAGE_CEILING = 4e4;
1681
2658
  var SESSION_DB_RECLAIM_BUSY_TIMEOUT_MS = 5e3;
1682
- function errorMessage(error2) {
2659
+ function errorMessage2(error2) {
1683
2660
  if (!(error2 instanceof Error)) return String(error2);
1684
2661
  return error2.cause instanceof Error ? error2.cause.message : error2.message;
1685
2662
  }
@@ -1813,7 +2790,7 @@ async function probeReclaimAvailability(input) {
1813
2790
  try {
1814
2791
  sqlite = await import("node:sqlite");
1815
2792
  } catch (err) {
1816
- const detail = `Node ${process.version}: ${errorMessage(err)}`;
2793
+ const detail = `Node ${process.version}: ${errorMessage2(err)}`;
1817
2794
  console.warn(`[probeReclaimAvailability] node:sqlite unavailable for ${dbPath}: ` + detail);
1818
2795
  return { reason: "sqlite-unavailable", detail };
1819
2796
  }
@@ -1848,7 +2825,7 @@ async function reclaimSessionDbSpace(input) {
1848
2825
  try {
1849
2826
  sqlite = await import("node:sqlite");
1850
2827
  } catch (err) {
1851
- const detail = `Node ${process.version}: ${errorMessage(err)}`;
2828
+ const detail = `Node ${process.version}: ${errorMessage2(err)}`;
1852
2829
  console.warn(
1853
2830
  `[reclaimSessionDbSpace] node:sqlite unavailable (need Node >=22.5, >=22.13 unflagged) for ${dbPath}: ${detail}`
1854
2831
  );
@@ -1959,11 +2936,11 @@ async function reclaimSessionDbSpace(input) {
1959
2936
  );
1960
2937
  return { ok: false, skipped: "auto-vacuum-not-applicable" };
1961
2938
  } catch (err) {
1962
- console.error(`[reclaimSessionDbSpace] reclaim failed for ${dbPath}: ` + errorMessage(err));
2939
+ console.error(`[reclaimSessionDbSpace] reclaim failed for ${dbPath}: ` + errorMessage2(err));
1963
2940
  return {
1964
2941
  ok: false,
1965
2942
  skipped: isSessionStoreWriteFailure(err) ? "disk-exhaustion" : "reclaim-error",
1966
- detail: errorMessage(err)
2943
+ detail: errorMessage2(err)
1967
2944
  };
1968
2945
  } finally {
1969
2946
  db?.close();
@@ -3115,7 +4092,7 @@ function buildSessionArchive(input) {
3115
4092
  function isRecord2(value) {
3116
4093
  return typeof value === "object" && value !== null && !Array.isArray(value);
3117
4094
  }
3118
- function errorMessage2(error2) {
4095
+ function errorMessage3(error2) {
3119
4096
  return error2 instanceof Error ? error2.message : String(error2);
3120
4097
  }
3121
4098
  function invalidResponse(version2, sessionId, path, reason) {
@@ -3133,7 +4110,7 @@ async function requestPage(client, sessionId, path, signal) {
3133
4110
  } catch (error2) {
3134
4111
  throw new SessionArchiveExportError(
3135
4112
  "request-failed",
3136
- `OpenCode ${client.version} session ${sessionId} request GET ${path} failed: ${errorMessage2(error2)}`
4113
+ `OpenCode ${client.version} session ${sessionId} request GET ${path} failed: ${errorMessage3(error2)}`
3137
4114
  );
3138
4115
  }
3139
4116
  if (response.status === 404) {
@@ -3154,7 +4131,7 @@ async function requestPage(client, sessionId, path, signal) {
3154
4131
  } catch (error2) {
3155
4132
  throw new SessionArchiveExportError(
3156
4133
  "request-failed",
3157
- `OpenCode ${client.version} session ${sessionId} response body from GET ${path} could not be read: ${errorMessage2(error2)}`
4134
+ `OpenCode ${client.version} session ${sessionId} response body from GET ${path} could not be read: ${errorMessage3(error2)}`
3158
4135
  );
3159
4136
  }
3160
4137
  try {
@@ -3189,7 +4166,7 @@ function v1NextCursor(response, sessionId, path) {
3189
4166
  } catch (error2) {
3190
4167
  throw new SessionArchiveExportError(
3191
4168
  "pagination-failed",
3192
- `OpenCode v1 session ${sessionId} returned an invalid next Link for GET ${path}: ${errorMessage2(error2)}`
4169
+ `OpenCode v1 session ${sessionId} returned an invalid next Link for GET ${path}: ${errorMessage3(error2)}`
3193
4170
  );
3194
4171
  }
3195
4172
  }
@@ -3325,7 +4302,7 @@ function isRecord3(value) {
3325
4302
  }
3326
4303
  function isWatermark(value) {
3327
4304
  if (!isRecord3(value)) return false;
3328
- return typeof value.fingerprint === "string" && typeof value.uploaded_at === "string" && typeof value.key === "string" && (!("conversation_id" in value) || value.conversation_id === null || typeof value.conversation_id === "string");
4305
+ return typeof value.fingerprint === "string" && typeof value.uploaded_at === "string" && typeof value.key === "string" && (!("conversation_id" in value) || value.conversation_id === null || typeof value.conversation_id === "string") && (!("version_id" in value) || value.version_id === null || typeof value.version_id === "string") && (!("etag" in value) || value.etag === null || typeof value.etag === "string");
3329
4306
  }
3330
4307
  function isMissingFile3(error2) {
3331
4308
  return error2 instanceof Error && "code" in error2 && error2.code === "ENOENT";
@@ -3506,6 +4483,37 @@ function isJson(body) {
3506
4483
  return false;
3507
4484
  }
3508
4485
  }
4486
+ function parseArchivePutMetadata(stderr, onMetadataDecodeError) {
4487
+ const prefix = "ARCHIVE-PUT: outcome=ok ";
4488
+ const lines = stderr.split(/\r?\n/);
4489
+ for (let index = lines.length - 1; index >= 0; index -= 1) {
4490
+ const line = lines[index];
4491
+ if (line === void 0) continue;
4492
+ const prefixIndex = line.indexOf(prefix);
4493
+ if (prefixIndex === -1) continue;
4494
+ const record = line.slice(prefixIndex + prefix.length);
4495
+ const versionMatch = /(?:^|\s)version_id=(\S*)/.exec(record);
4496
+ const etagMatch = /(?:^|\s)etag=(\S*)/.exec(record);
4497
+ const decode = (value, field) => {
4498
+ if (value === void 0 || value === "") return null;
4499
+ try {
4500
+ return decodeURIComponent(value);
4501
+ } catch (error2) {
4502
+ onMetadataDecodeError?.(
4503
+ field,
4504
+ error2 instanceof URIError ? "uri-malformed" : "decode-failed"
4505
+ );
4506
+ return null;
4507
+ }
4508
+ };
4509
+ return {
4510
+ metadataReported: versionMatch !== null || etagMatch !== null,
4511
+ versionId: decode(versionMatch?.[1], "version_id"),
4512
+ etag: decode(etagMatch?.[1], "etag")
4513
+ };
4514
+ }
4515
+ return { metadataReported: false, versionId: null, etag: null };
4516
+ }
3509
4517
  async function uploadSessionArchive(key, body, options) {
3510
4518
  const bytes = Buffer.from(body);
3511
4519
  if (bytes.byteLength > MAX_SESSION_ARCHIVE_BYTES) {
@@ -3528,7 +4536,13 @@ async function uploadSessionArchive(key, body, options) {
3528
4536
  );
3529
4537
  }
3530
4538
  if (result.timedOut) return transportFailure(bytes.byteLength, "timeout");
3531
- if (result.code === 0) return { kind: "ok", bytes: bytes.byteLength };
4539
+ if (result.code === 0) {
4540
+ return {
4541
+ kind: "ok",
4542
+ bytes: bytes.byteLength,
4543
+ ...parseArchivePutMetadata(result.stderr, options.onMetadataDecodeError)
4544
+ };
4545
+ }
3532
4546
  if (result.code === EXIT_ARCHIVE_CONFIG_MISSING) {
3533
4547
  return { kind: "config-missing", bytes: bytes.byteLength };
3534
4548
  }
@@ -3746,6 +4760,14 @@ async function runSessionArchive({
3746
4760
  uploadFailures: 0,
3747
4761
  skippedBudget: 0,
3748
4762
  skippedBudgetIds: [],
4763
+ skippedChanged: 0,
4764
+ skippedChangedSessions: [],
4765
+ skippedUnknown: 0,
4766
+ skippedUnknownIds: [],
4767
+ inventoryNeverArchived: 0,
4768
+ inventoryPriorFailures: 0,
4769
+ inventoryKnownChanged: 0,
4770
+ outcomesReconciled: false,
3749
4771
  neverWatermarkedFailures: 0,
3750
4772
  unmappedIds: [],
3751
4773
  conflictedIds: [],
@@ -3762,6 +4784,8 @@ async function runSessionArchive({
3762
4784
  parent: 0
3763
4785
  },
3764
4786
  archivedSessionIds: [],
4787
+ uploadedSessions: [],
4788
+ unchangedSessions: [],
3765
4789
  failures: [],
3766
4790
  staleSince: null
3767
4791
  };
@@ -3785,17 +4809,44 @@ async function runSessionArchive({
3785
4809
  }
3786
4810
  summary.unresolved = summary.unmappedIds.length + summary.conflictedIds.length;
3787
4811
  summary.conflicts = summary.conflictedIds.length;
4812
+ const priorFailureIds = deps.priorFailureIds ?? /* @__PURE__ */ new Set();
4813
+ const knownChanged = /* @__PURE__ */ new Map();
4814
+ for (const session of sessions) {
4815
+ if (!deps.watermarks.has(session.id)) {
4816
+ knownChanged.set(session.id, "no-prior-archive");
4817
+ summary.inventoryNeverArchived++;
4818
+ } else if (priorFailureIds.has(session.id)) {
4819
+ knownChanged.set(session.id, "prior-attempt-failed");
4820
+ summary.inventoryPriorFailures++;
4821
+ }
4822
+ }
4823
+ summary.inventoryKnownChanged = knownChanged.size;
3788
4824
  const failedWatermarks = [];
4825
+ const priorFailureUploads = [];
3789
4826
  const recordFailedWatermark = (watermark) => {
3790
4827
  if (watermark) failedWatermarks.push(watermark.uploaded_at);
3791
4828
  else summary.neverWatermarkedFailures++;
3792
4829
  };
4830
+ const recordBudgetSkip = (startIndex) => {
4831
+ const skippedIds = ordered.slice(startIndex).map(({ id }) => id);
4832
+ summary.skippedBudgetIds.push(...skippedIds);
4833
+ summary.skippedBudget = summary.skippedBudgetIds.length;
4834
+ for (const sessionId of skippedIds) {
4835
+ const reason = knownChanged.get(sessionId);
4836
+ if (reason) {
4837
+ summary.skippedChangedSessions.push({ sessionId, reason });
4838
+ summary.skippedChanged++;
4839
+ } else {
4840
+ summary.skippedUnknownIds.push(sessionId);
4841
+ summary.skippedUnknown++;
4842
+ }
4843
+ }
4844
+ };
3793
4845
  for (let index = 0; index < ordered.length; index++) {
3794
4846
  const session = ordered[index];
3795
4847
  const remainingMs = Math.floor(deadline - now());
3796
4848
  if (remainingMs <= 0 || deps.signal?.aborted) {
3797
- summary.skippedBudgetIds.push(...ordered.slice(index).map(({ id }) => id));
3798
- summary.skippedBudget = summary.skippedBudgetIds.length;
4849
+ recordBudgetSkip(index);
3799
4850
  break;
3800
4851
  }
3801
4852
  const resolution = resolutions.get(session.id) ?? { reason: "unmapped" };
@@ -3820,8 +4871,7 @@ async function runSessionArchive({
3820
4871
  messages = await exportMessages(deps.client, session.id, exportBudget.signal);
3821
4872
  } catch (error2) {
3822
4873
  if (isBudgetExpired(deadline, now, deps.signal) || exportBudget.signal.aborted) {
3823
- summary.skippedBudgetIds.push(...ordered.slice(index).map(({ id }) => id));
3824
- summary.skippedBudget = summary.skippedBudgetIds.length;
4874
+ recordBudgetSkip(index);
3825
4875
  break;
3826
4876
  }
3827
4877
  summary.failed++;
@@ -3839,8 +4889,7 @@ async function runSessionArchive({
3839
4889
  exportBudget.dispose();
3840
4890
  }
3841
4891
  if (isBudgetExpired(deadline, now, deps.signal) || exportBudget.signal.aborted) {
3842
- summary.skippedBudgetIds.push(...ordered.slice(index).map(({ id }) => id));
3843
- summary.skippedBudget = summary.skippedBudgetIds.length;
4892
+ recordBudgetSkip(index);
3844
4893
  break;
3845
4894
  }
3846
4895
  try {
@@ -3859,12 +4908,21 @@ async function runSessionArchive({
3859
4908
  if (existing?.fingerprint === snapshot.content_fingerprint) {
3860
4909
  summary.unchanged++;
3861
4910
  summary.archivedSessionIds.push(session.id);
4911
+ summary.unchangedSessions.push({
4912
+ sessionId: session.id,
4913
+ fingerprint: snapshot.content_fingerprint,
4914
+ watermarkKey: existing.key,
4915
+ watermarkFingerprint: existing.fingerprint,
4916
+ watermarkVersionId: existing.version_id ?? null,
4917
+ watermarkEtag: existing.etag ?? null,
4918
+ watermarkUploadedAt: existing.uploaded_at
4919
+ });
3862
4920
  continue;
3863
4921
  }
3864
4922
  const uploadRemainingMs = Math.floor(deadline - now());
3865
4923
  if (uploadRemainingMs <= 0 || deps.signal?.aborted) {
3866
- summary.skippedBudgetIds.push(...ordered.slice(index).map(({ id }) => id));
3867
- summary.skippedBudget = summary.skippedBudgetIds.length;
4924
+ knownChanged.set(session.id, "fingerprint-differs");
4925
+ recordBudgetSkip(index);
3868
4926
  break;
3869
4927
  }
3870
4928
  summary.uploadAttempts++;
@@ -3873,7 +4931,8 @@ async function runSessionArchive({
3873
4931
  try {
3874
4932
  outcome = await upload(key, JSON.stringify(snapshot), {
3875
4933
  timeoutMs: Math.min(uploadRemainingMs, SESSION_ARCHIVE_UPLOAD_TIMEOUT_MS),
3876
- signal: uploadBudget.signal
4934
+ signal: uploadBudget.signal,
4935
+ onMetadataDecodeError: (field, reason) => deps.onMetadataDecodeError?.(field, reason, session.id)
3877
4936
  });
3878
4937
  } finally {
3879
4938
  uploadBudget.dispose();
@@ -3896,19 +4955,31 @@ async function runSessionArchive({
3896
4955
  });
3897
4956
  recordFailedWatermark(existing);
3898
4957
  if (uploadBudget.signal.aborted) {
3899
- summary.skippedBudgetIds.push(...ordered.slice(index + 1).map(({ id }) => id));
3900
- summary.skippedBudget = summary.skippedBudgetIds.length;
4958
+ recordBudgetSkip(index + 1);
3901
4959
  break;
3902
4960
  }
3903
4961
  continue;
3904
4962
  }
3905
4963
  summary.uploaded++;
3906
4964
  summary.archivedSessionIds.push(session.id);
4965
+ const uploadRecord = {
4966
+ sessionId: session.id,
4967
+ key,
4968
+ fingerprint: snapshot.content_fingerprint,
4969
+ versionId: outcome.versionId,
4970
+ etag: outcome.etag,
4971
+ metadataReported: outcome.metadataReported,
4972
+ retriedPriorFailure: priorFailureIds.has(session.id)
4973
+ };
4974
+ if (uploadRecord.retriedPriorFailure) priorFailureUploads.push(uploadRecord);
4975
+ else summary.uploadedSessions.push(uploadRecord);
3907
4976
  const watermark = {
3908
4977
  fingerprint: snapshot.content_fingerprint,
3909
4978
  uploaded_at: new Date(now()).toISOString(),
3910
4979
  key,
3911
- conversation_id: conversationId
4980
+ conversation_id: conversationId,
4981
+ version_id: outcome.versionId,
4982
+ etag: outcome.etag
3912
4983
  };
3913
4984
  try {
3914
4985
  writeWatermark(deps.watermarkPath, session.id, watermark, deps.watermarks);
@@ -3922,8 +4993,7 @@ async function runSessionArchive({
3922
4993
  }
3923
4994
  } catch (error2) {
3924
4995
  if (isBudgetExpired(deadline, now, deps.signal)) {
3925
- summary.skippedBudgetIds.push(...ordered.slice(index).map(({ id }) => id));
3926
- summary.skippedBudget = summary.skippedBudgetIds.length;
4996
+ recordBudgetSkip(index);
3927
4997
  break;
3928
4998
  }
3929
4999
  summary.failed++;
@@ -3936,10 +5006,115 @@ async function runSessionArchive({
3936
5006
  recordFailedWatermark(deps.watermarks.get(session.id));
3937
5007
  }
3938
5008
  }
5009
+ summary.uploadedSessions = [...priorFailureUploads, ...summary.uploadedSessions];
5010
+ for (const sessionId of summary.archivedSessionIds) priorFailureIds.delete(sessionId);
5011
+ for (const failure of summary.failures) {
5012
+ if (!failure.archived) priorFailureIds.add(failure.sessionId);
5013
+ }
5014
+ summary.outcomesReconciled = summary.uploaded + summary.unchanged + summary.failed + summary.skippedChanged + summary.skippedUnknown === summary.inspected;
3939
5015
  summary.staleSince = failedWatermarks.sort()[0] ?? null;
3940
5016
  return summary;
3941
5017
  }
3942
5018
 
5019
+ // src/lib/opencode/session-archive-manifest.ts
5020
+ var SESSION_ARCHIVE_MANIFEST_SCHEMA_VERSION = 1;
5021
+ function sessionArchiveManifestKey(keyPrefix, identity) {
5022
+ return `${keyPrefix.replace(/\/+$/, "")}/archive-audit/${identity.bootId}-${String(identity.passSequence).padStart(4, "0")}-${identity.phase}.json`;
5023
+ }
5024
+ function buildSessionArchiveManifest(identity, summary) {
5025
+ const failedSessions = summary?.failures.filter(({ archived }) => !archived) ?? [];
5026
+ const watermarkWriteFailures = new Set(
5027
+ summary?.failures.filter(({ archived }) => archived).map(({ sessionId }) => sessionId)
5028
+ );
5029
+ const sessions = summary ? [
5030
+ ...summary.uploadedSessions.map((upload) => ({
5031
+ id: upload.sessionId,
5032
+ outcome: "uploaded",
5033
+ archive_key: upload.key,
5034
+ fingerprint: upload.fingerprint,
5035
+ version_id: upload.versionId,
5036
+ etag: upload.etag,
5037
+ object_metadata_reported: upload.metadataReported,
5038
+ retried_prior_failure: upload.retriedPriorFailure,
5039
+ ...watermarkWriteFailures.has(upload.sessionId) ? { watermark_write_failed: true } : {}
5040
+ })),
5041
+ ...summary.unchangedSessions.map((unchanged) => ({
5042
+ id: unchanged.sessionId,
5043
+ outcome: "unchanged",
5044
+ fingerprint: unchanged.fingerprint,
5045
+ watermark_fingerprint: unchanged.watermarkFingerprint,
5046
+ watermark_key: unchanged.watermarkKey,
5047
+ watermark_version_id: unchanged.watermarkVersionId,
5048
+ watermark_etag: unchanged.watermarkEtag,
5049
+ watermark_uploaded_at: unchanged.watermarkUploadedAt
5050
+ })),
5051
+ ...failedSessions.map((failure) => ({
5052
+ id: failure.sessionId,
5053
+ outcome: "failed",
5054
+ failure_outcome: failure.outcome,
5055
+ ...failure.reason !== void 0 ? { reason: failure.reason } : {},
5056
+ ...failure.bytes !== void 0 ? { payload_bytes: failure.bytes } : {},
5057
+ ...failure.byteLimit !== void 0 ? { payload_limit_bytes: failure.byteLimit } : {},
5058
+ ...failure.messageCount !== void 0 ? { message_count: failure.messageCount } : {},
5059
+ ...failure.partCount !== void 0 ? { part_count: failure.partCount } : {},
5060
+ ...failure.exitCode !== void 0 ? { exit_code: failure.exitCode } : {}
5061
+ })),
5062
+ ...summary.skippedChangedSessions.map((skipped) => ({
5063
+ id: skipped.sessionId,
5064
+ outcome: "skipped-changed",
5065
+ reason: skipped.reason
5066
+ })),
5067
+ ...summary.skippedUnknownIds.map((sessionId) => ({
5068
+ id: sessionId,
5069
+ outcome: "skipped-unknown"
5070
+ }))
5071
+ ] : [];
5072
+ return {
5073
+ schema_version: SESSION_ARCHIVE_MANIFEST_SCHEMA_VERSION,
5074
+ runner_id: identity.runnerId,
5075
+ boot_id: identity.bootId,
5076
+ pass_sequence: identity.passSequence,
5077
+ phase: identity.phase,
5078
+ started_at: identity.startedAt,
5079
+ completed_at: identity.completedAt,
5080
+ budget_ms: identity.budgetMs,
5081
+ enumeration_complete: identity.enumerationComplete,
5082
+ enumeration_reason: identity.enumerationReason,
5083
+ watermark_file_present: identity.watermarkFilePresent,
5084
+ watermarks_loaded: identity.watermarksLoaded,
5085
+ inspected: summary?.inspected ?? 0,
5086
+ counts: {
5087
+ uploaded: summary?.uploaded ?? 0,
5088
+ unchanged: summary?.unchanged ?? 0,
5089
+ failed: failedSessions.length,
5090
+ skipped_changed: summary?.skippedChanged ?? 0,
5091
+ skipped_unknown: summary?.skippedUnknown ?? 0
5092
+ },
5093
+ outcomes_reconciled: summary?.outcomesReconciled ?? null,
5094
+ inventory_never_archived: summary?.inventoryNeverArchived ?? 0,
5095
+ inventory_prior_failures: summary?.inventoryPriorFailures ?? 0,
5096
+ sessions
5097
+ };
5098
+ }
5099
+ async function uploadSessionArchiveManifest({
5100
+ keyPrefix,
5101
+ identity,
5102
+ summary,
5103
+ timeoutMs,
5104
+ signal,
5105
+ onMetadataDecodeError,
5106
+ upload
5107
+ }) {
5108
+ const key = sessionArchiveManifestKey(keyPrefix, identity);
5109
+ const manifest = buildSessionArchiveManifest(identity, summary);
5110
+ const outcome = await (upload ?? uploadSessionArchive)(key, JSON.stringify(manifest), {
5111
+ timeoutMs,
5112
+ signal,
5113
+ onMetadataDecodeError
5114
+ });
5115
+ return { key, outcome };
5116
+ }
5117
+
3943
5118
  // src/lib/opencode/auth.ts
3944
5119
  function buildOpenCodeBasicAuthHeader(password) {
3945
5120
  return `Basic ${Buffer.from(["opencode", password].join(":")).toString("base64")}`;
@@ -4046,9 +5221,11 @@ async function checkOpenCode2Health(port, password) {
4046
5221
  return { healthy: false, error: message };
4047
5222
  }
4048
5223
  }
4049
- async function waitForOpenCodeHealth(port, timeoutMs = 3e4) {
5224
+ async function waitForOpenCodeHealth(port, timeoutMs = 3e4, stopEarly) {
4050
5225
  const startTime = Date.now();
4051
5226
  while (Date.now() - startTime < timeoutMs) {
5227
+ const earlyStopReason = stopEarly?.();
5228
+ if (earlyStopReason) return { healthy: false, error: earlyStopReason };
4052
5229
  const health = await checkOpenCodeHealth(port);
4053
5230
  if (health.healthy || health.authFailed) {
4054
5231
  return health;
@@ -4057,9 +5234,11 @@ async function waitForOpenCodeHealth(port, timeoutMs = 3e4) {
4057
5234
  }
4058
5235
  return { healthy: false, error: "Timeout waiting for OpenCode to be healthy" };
4059
5236
  }
4060
- async function waitForOpenCode2Health(port, password, timeoutMs = 3e4) {
5237
+ async function waitForOpenCode2Health(port, password, timeoutMs = 3e4, stopEarly) {
4061
5238
  const startTime = Date.now();
4062
5239
  while (Date.now() - startTime < timeoutMs) {
5240
+ const earlyStopReason = stopEarly?.();
5241
+ if (earlyStopReason) return { healthy: false, error: earlyStopReason };
4063
5242
  const health = await checkOpenCode2Health(port, password);
4064
5243
  if (health.healthy || health.authFailed) {
4065
5244
  return health;
@@ -5713,8 +6892,8 @@ function classifyReplyAuthError(reply) {
5713
6892
  };
5714
6893
  }
5715
6894
  }
5716
- const errorMessage4 = typeof data?.message === "string" ? data.message : typeof e.message === "string" ? e.message : null;
5717
- if (errorMessage4 !== null && CLAUDE_AUTH_EXPIRY_MESSAGES.some((knownMessage) => errorMessage4.includes(knownMessage))) {
6895
+ const errorMessage5 = typeof data?.message === "string" ? data.message : typeof e.message === "string" ? e.message : null;
6896
+ if (errorMessage5 !== null && CLAUDE_AUTH_EXPIRY_MESSAGES.some((knownMessage) => errorMessage5.includes(knownMessage))) {
5718
6897
  return {
5719
6898
  kind: "model_auth",
5720
6899
  providerId: typeof data?.providerID === "string" && data.providerID || replyProviderId,
@@ -5769,7 +6948,7 @@ function hasRunningAssistantExcept(messages, exceptUserMessageId) {
5769
6948
  (m) => roleOf2(m) === "assistant" && parentIdOf2(m) !== exceptUserMessageId && isAssistantInFlight(m)
5770
6949
  );
5771
6950
  }
5772
- function hasLaterSiblingTurnStarted(messages, userMessageId, siblingUserMessageIds) {
6951
+ function hasLaterSiblingTurnStarted(messages, userMessageId, siblingUserMessageIds, apiVersion) {
5773
6952
  if (!messages || messages.length === 0) return false;
5774
6953
  const userIndex = messages.findIndex((message) => idOf2(message) === userMessageId);
5775
6954
  if (userIndex === -1) return false;
@@ -5783,7 +6962,7 @@ function hasLaterSiblingTurnStarted(messages, userMessageId, siblingUserMessageI
5783
6962
  if (laterUserMessageId === void 0 || !siblingUserMessageIds.has(laterUserMessageId)) {
5784
6963
  return false;
5785
6964
  }
5786
- if (messages.some(
6965
+ if (apiVersion === "v2" || messages.some(
5787
6966
  (candidate) => roleOf2(candidate) === "assistant" && parentIdOf2(candidate) === laterUserMessageId
5788
6967
  )) {
5789
6968
  hasStartedLaterUser = true;
@@ -7128,7 +8307,7 @@ function reportedOpenCodeVersion(input) {
7128
8307
 
7129
8308
  // src/lib/opencode/process.ts
7130
8309
  import { execSync, spawn as spawn3 } from "child_process";
7131
- import { randomBytes } from "node:crypto";
8310
+ import { randomBytes as randomBytes2 } from "node:crypto";
7132
8311
 
7133
8312
  // src/lib/process-stop.ts
7134
8313
  async function stopProcessAndWait(child, timeoutMs, sendTerm, sendKill) {
@@ -7243,28 +8422,29 @@ function getProcessCwd(pid) {
7243
8422
  }
7244
8423
  return void 0;
7245
8424
  }
7246
- function isPortInUse(port) {
7247
- const platform = process.platform;
7248
- try {
7249
- if (platform === "darwin" || platform === "linux") {
7250
- execSync(`lsof -i :${port} -sTCP:LISTEN 2>/dev/null`, {
7251
- encoding: "utf-8",
7252
- stdio: ["pipe", "pipe", "pipe"]
7253
- });
7254
- return true;
8425
+ function watchOpenCodeExit(child, log3) {
8426
+ let spawnError = null;
8427
+ child.once("error", (error2) => {
8428
+ spawnError = error2;
8429
+ const code = spawnError.code ?? "unknown error";
8430
+ log3(
8431
+ `[watchOpenCodeExit] OpenCode command ${child.spawnfile ?? "unknown"} could not be spawned: ${code}: ${spawnError.message}`,
8432
+ "error"
8433
+ );
8434
+ });
8435
+ return () => {
8436
+ if (spawnError) {
8437
+ const code = spawnError.code ?? "unknown error";
8438
+ return `it could not be spawned (${code}: ${spawnError.message})`;
7255
8439
  }
7256
- } catch {
7257
- }
7258
- return false;
7259
- }
7260
- function findAvailablePort(startPort, maxAttempts = 10) {
7261
- for (let i = 0; i < maxAttempts; i++) {
7262
- const port = startPort + i;
7263
- if (!isPortInUse(port)) {
7264
- return port;
8440
+ if (child.signalCode !== null && child.signalCode !== void 0) {
8441
+ return `it was killed by ${child.signalCode} before it answered`;
7265
8442
  }
7266
- }
7267
- return null;
8443
+ if (child.exitCode !== null && child.exitCode !== void 0) {
8444
+ return `it exited with status ${child.exitCode} before it answered`;
8445
+ }
8446
+ return null;
8447
+ };
7268
8448
  }
7269
8449
  function findProcessesByPattern(pgrepPattern, psPattern) {
7270
8450
  const instances = [];
@@ -7406,7 +8586,7 @@ async function startOpenCode(port, options = {}) {
7406
8586
  return child;
7407
8587
  }
7408
8588
  async function startOpenCode2(port, options = {}) {
7409
- const password = randomBytes(24).toString("hex");
8589
+ const password = randomBytes2(24).toString("hex");
7410
8590
  let command = options.command ?? "opencode2";
7411
8591
  const logLevel = options.inheritStdio ? ["--log-level", resolveOpenCode2LogLevel(process.env)] : [];
7412
8592
  let args = ["serve", "--port", port.toString(), "--hostname", "127.0.0.1", ...logLevel];
@@ -7430,28 +8610,166 @@ async function startOpenCode2(port, options = {}) {
7430
8610
  ];
7431
8611
  }
7432
8612
  }
7433
- const child = spawn3(command, args, {
7434
- env: { ...process.env, OPENCODE_SERVER_PASSWORD: password },
7435
- detached: true,
7436
- stdio: options.inheritStdio ? "inherit" : "ignore",
7437
- cwd: process.cwd()
7438
- });
7439
- return { child, password };
8613
+ const child = spawn3(command, args, {
8614
+ env: { ...process.env, OPENCODE_SERVER_PASSWORD: password },
8615
+ detached: true,
8616
+ stdio: options.inheritStdio ? "inherit" : "ignore",
8617
+ cwd: process.cwd()
8618
+ });
8619
+ return { child, password };
8620
+ }
8621
+ function stopOpenCodeAndWait(opencodeProcess, timeoutMs) {
8622
+ const sendSignal = (signal) => {
8623
+ if (process.platform === "win32") {
8624
+ opencodeProcess.kill(signal);
8625
+ } else {
8626
+ process.kill(-opencodeProcess.pid, signal);
8627
+ }
8628
+ };
8629
+ return stopProcessAndWait(
8630
+ opencodeProcess,
8631
+ timeoutMs,
8632
+ () => sendSignal("SIGTERM"),
8633
+ () => sendSignal("SIGKILL")
8634
+ );
8635
+ }
8636
+
8637
+ // src/lib/opencode/port.ts
8638
+ import { execFileSync as execFileSync2 } from "node:child_process";
8639
+ import { createServer as createServer2 } from "node:net";
8640
+ var HOLDER_LOOKUP_TIMEOUT_MS = 250;
8641
+ var RECLAIM_SIGNAL_WAIT_MS = 250;
8642
+ var RECLAIM_POLL_INTERVAL_MS = 25;
8643
+ function isPortInUse(port) {
8644
+ return new Promise((resolve6) => {
8645
+ const server = createServer2();
8646
+ server.once("error", () => resolve6(true));
8647
+ server.listen({ port, host: "127.0.0.1", exclusive: true }, () => {
8648
+ server.close(() => resolve6(false));
8649
+ });
8650
+ });
8651
+ }
8652
+ async function findAvailablePort(startPort, maxAttempts = 10) {
8653
+ for (let i = 0; i < maxAttempts; i++) {
8654
+ const port = startPort + i;
8655
+ if (!await isPortInUse(port)) return port;
8656
+ }
8657
+ return null;
8658
+ }
8659
+ function outputText(value) {
8660
+ if (typeof value === "string") return value;
8661
+ if (Buffer.isBuffer(value)) return value.toString("utf8");
8662
+ return value === void 0 || value === null ? "" : String(value);
8663
+ }
8664
+ function holderPids(stdout) {
8665
+ const tokens = stdout.trim() ? stdout.trim().split(/\s+/) : [];
8666
+ if (tokens.length === 0) return [];
8667
+ if (!tokens.every((token) => /^\d+$/.test(token))) return null;
8668
+ return tokens.map(Number);
8669
+ }
8670
+ function isExecTimeout(error2) {
8671
+ if (!error2 || typeof error2 !== "object") return false;
8672
+ const candidate = error2;
8673
+ return candidate.code === "ETIMEDOUT" || candidate.killed === true && candidate.signal === "SIGKILL";
8674
+ }
8675
+ function listLoopbackPortHolders(port) {
8676
+ try {
8677
+ const stdout = outputText(
8678
+ execFileSync2("fuser", ["-n", "tcp", String(port)], {
8679
+ encoding: "utf8",
8680
+ stdio: ["ignore", "pipe", "pipe"],
8681
+ // The resume path must not wait indefinitely on a broken /proc read.
8682
+ timeout: HOLDER_LOOKUP_TIMEOUT_MS,
8683
+ killSignal: "SIGKILL"
8684
+ })
8685
+ );
8686
+ const pids = holderPids(stdout);
8687
+ return pids !== null && pids.length > 0 ? pids : { error: "fuser failed to identify the port holder" };
8688
+ } catch (error2) {
8689
+ const candidate = error2;
8690
+ const stdout = outputText(candidate.stdout);
8691
+ const stderr = outputText(candidate.stderr);
8692
+ const pids = holderPids(stdout);
8693
+ if (pids === null) return { error: "fuser failed to identify the port holder" };
8694
+ if (pids.length > 0) return pids;
8695
+ if (candidate.code === "ENOENT") return { error: "fuser is unavailable" };
8696
+ if (isExecTimeout(error2)) return { error: "fuser timed out while identifying the port holder" };
8697
+ if (candidate.status === 1 && stderr.trim() === "") return [];
8698
+ return { error: "fuser failed to identify the port holder" };
8699
+ }
8700
+ }
8701
+ async function identifyHolders(listHolders) {
8702
+ let timer;
8703
+ const timeout = new Promise((resolve6) => {
8704
+ timer = setTimeout(
8705
+ () => resolve6({ error: "holder identification timed out" }),
8706
+ HOLDER_LOOKUP_TIMEOUT_MS
8707
+ );
8708
+ });
8709
+ try {
8710
+ return await Promise.race([Promise.resolve().then(listHolders), timeout]);
8711
+ } catch (error2) {
8712
+ return {
8713
+ error: `holder identification failed: ${error2 instanceof Error ? error2.message : String(error2)}`
8714
+ };
8715
+ } finally {
8716
+ if (timer !== void 0) clearTimeout(timer);
8717
+ }
8718
+ }
8719
+ function isErrno(error2, code) {
8720
+ return error2 !== null && typeof error2 === "object" && "code" in error2 && error2.code === code;
8721
+ }
8722
+ function signalHolders(pids, signal) {
8723
+ let failure = null;
8724
+ for (const pid of pids) {
8725
+ try {
8726
+ process.kill(pid, signal);
8727
+ } catch (error2) {
8728
+ if (isErrno(error2, "ESRCH")) continue;
8729
+ failure ??= `could not send ${signal} to holder ${pid}: ${error2 instanceof Error ? error2.message : String(error2)}`;
8730
+ }
8731
+ }
8732
+ return failure;
7440
8733
  }
7441
- function stopOpenCodeAndWait(opencodeProcess, timeoutMs) {
7442
- const sendSignal = (signal) => {
7443
- if (process.platform === "win32") {
7444
- opencodeProcess.kill(signal);
7445
- } else {
7446
- process.kill(-opencodeProcess.pid, signal);
8734
+ async function waitForPortFree(port, waitMs) {
8735
+ const deadline = Date.now() + waitMs;
8736
+ let probeError;
8737
+ for (; ; ) {
8738
+ try {
8739
+ if (!await isPortInUse(port)) return { free: true };
8740
+ } catch (error2) {
8741
+ probeError = error2 instanceof Error ? error2.message : String(error2);
7447
8742
  }
7448
- };
7449
- return stopProcessAndWait(
7450
- opencodeProcess,
7451
- timeoutMs,
7452
- () => sendSignal("SIGTERM"),
7453
- () => sendSignal("SIGKILL")
8743
+ const remaining = deadline - Date.now();
8744
+ if (remaining <= 0) return { free: false, detail: probeError };
8745
+ await new Promise(
8746
+ (resolve6) => setTimeout(resolve6, Math.min(RECLAIM_POLL_INTERVAL_MS, remaining))
8747
+ );
8748
+ }
8749
+ }
8750
+ async function reclaimLoopbackPort(port, options = {}) {
8751
+ const holderResult = await identifyHolders(
8752
+ options.listHolders ?? (() => listLoopbackPortHolders(port))
7454
8753
  );
8754
+ if (!Array.isArray(holderResult)) {
8755
+ return { kind: "blocked", port, detail: holderResult.error };
8756
+ }
8757
+ if (holderResult.length === 0) return { kind: "no-holder", port };
8758
+ const termFailure = signalHolders(holderResult, "SIGTERM");
8759
+ const afterTerm = await waitForPortFree(port, RECLAIM_SIGNAL_WAIT_MS);
8760
+ if (afterTerm.free && termFailure === null) {
8761
+ return { kind: "freed", port, pids: holderResult, usedSigkill: false };
8762
+ }
8763
+ const killFailure = signalHolders(holderResult, "SIGKILL");
8764
+ const afterKill = await waitForPortFree(port, RECLAIM_SIGNAL_WAIT_MS);
8765
+ if (!afterKill.free) {
8766
+ return {
8767
+ kind: "blocked",
8768
+ port,
8769
+ detail: afterKill.detail ?? termFailure ?? killFailure ?? "the port remained in use after SIGTERM and SIGKILL"
8770
+ };
8771
+ }
8772
+ return { kind: "freed", port, pids: holderResult, usedSigkill: true };
7455
8773
  }
7456
8774
 
7457
8775
  // src/lib/opencode/install.ts
@@ -7671,7 +8989,7 @@ function buildSessionStoreSizeWarning(input) {
7671
8989
  import { statSync as statSync5 } from "node:fs";
7672
8990
  import { homedir as homedir5 } from "node:os";
7673
8991
  import { join as join11 } from "node:path";
7674
- import { open as open2, stat } from "node:fs/promises";
8992
+ import { open as open3, stat } from "node:fs/promises";
7675
8993
  var DEFAULT_POLL_INTERVAL_MS = 1e3;
7676
8994
  function resolveOpenCodeLogPath(homeDir = homedir5(), env = process.env) {
7677
8995
  const dataDir = env.XDG_DATA_HOME || join11(homeDir, ".local", "share");
@@ -7725,7 +9043,7 @@ function tailOpenCodeLogFile(logPath, onChunk, opts = {}) {
7725
9043
  inode = current.ino;
7726
9044
  if (current.size === offset) return;
7727
9045
  const length = current.size - offset;
7728
- const fh = await open2(logPath, "r");
9046
+ const fh = await open3(logPath, "r");
7729
9047
  try {
7730
9048
  const buf = Buffer.alloc(length);
7731
9049
  const { bytesRead } = await fh.read(buf, 0, length, offset);
@@ -7758,7 +9076,7 @@ import WebSocket from "ws";
7758
9076
 
7759
9077
  // src/lib/file-read.ts
7760
9078
  import { constants } from "node:fs";
7761
- import { open as open3, realpath as realpath2, stat as stat2 } from "node:fs/promises";
9079
+ import { open as open4, realpath as realpath2, stat as stat2 } from "node:fs/promises";
7762
9080
  import { extname, isAbsolute as isAbsolute3, resolve as resolve4 } from "node:path";
7763
9081
  import { homedir as homedir6 } from "node:os";
7764
9082
 
@@ -7808,7 +9126,7 @@ var FILE_MIME_TYPES = {
7808
9126
  ".mp4": "video/mp4",
7809
9127
  ".mov": "video/quicktime"
7810
9128
  };
7811
- async function readProjectFile(projectRoot, method, requestedPath, openFile = open3) {
9129
+ async function readProjectFile(projectRoot, method, requestedPath, openFile = open4) {
7812
9130
  if (method !== "GET") return refuse(405, "method_not_allowed");
7813
9131
  if (!projectRoot || !isAbsolute3(projectRoot)) return refuse(503, "project_root_unavailable");
7814
9132
  if (!requestedPath || requestedPath.length > 4096 || requestedPath.includes("\0")) {
@@ -8381,8 +9699,8 @@ function connectTunnel(options) {
8381
9699
  }
8382
9700
  forwarder.handleBinaryBodyFrame(frame.sid, frame.payload);
8383
9701
  } catch (error2) {
8384
- const errorMessage4 = error2 instanceof Error ? error2.message : "Unknown error";
8385
- onError?.(`Failed to handle binary message: ${errorMessage4}`);
9702
+ const errorMessage5 = error2 instanceof Error ? error2.message : "Unknown error";
9703
+ onError?.(`Failed to handle binary message: ${errorMessage5}`);
8386
9704
  }
8387
9705
  return;
8388
9706
  }
@@ -8390,8 +9708,8 @@ function connectTunnel(options) {
8390
9708
  try {
8391
9709
  message = JSON.parse(data.toString());
8392
9710
  } catch (error2) {
8393
- const errorMessage4 = error2 instanceof Error ? error2.message : "Unknown error";
8394
- onError?.(`Failed to handle message: ${errorMessage4}`);
9711
+ const errorMessage5 = error2 instanceof Error ? error2.message : "Unknown error";
9712
+ onError?.(`Failed to handle message: ${errorMessage5}`);
8395
9713
  return;
8396
9714
  }
8397
9715
  if (isStreamFrame(message)) {
@@ -8970,7 +10288,7 @@ import { join as join14 } from "node:path";
8970
10288
 
8971
10289
  // src/lib/file-push.ts
8972
10290
  import { randomUUID } from "node:crypto";
8973
- import { chmod, mkdir, open as open4, realpath as realpath3, rename, unlink } from "node:fs/promises";
10291
+ import { chmod, mkdir, open as open5, realpath as realpath3, rename, unlink } from "node:fs/promises";
8974
10292
  import { basename as basename3, dirname as dirname10, isAbsolute as isAbsolute4, join as join13 } from "node:path";
8975
10293
  var FILE_MODE = 384;
8976
10294
  var DIRECTORY_MODE = 448;
@@ -9103,7 +10421,7 @@ async function writeAtomically(realTarget, content) {
9103
10421
  const temporaryPath = join13(dirname10(realTarget), `.evident-push-${randomUUID()}.tmp`);
9104
10422
  let handle;
9105
10423
  try {
9106
- handle = await open4(temporaryPath, "wx", FILE_MODE);
10424
+ handle = await open5(temporaryPath, "wx", FILE_MODE);
9107
10425
  await handle.writeFile(content);
9108
10426
  await handle.chmod(FILE_MODE);
9109
10427
  await handle.close();
@@ -10304,12 +11622,12 @@ var ChannelDriver = class _ChannelDriver {
10304
11622
  this.sessions.delete(conversationId);
10305
11623
  this.supersede(conversationId, sessionId);
10306
11624
  const dispatchDescription = source === "readopt" ? "re-dispatched message" : "message";
10307
- const errorMessage4 = `OpenCode accepted this ${dispatchDescription} once, but its assigned id was never confirmed after ${attempts} attempts to match it up \u2014 the message was deliberately not sent again, so no duplicate turn was created; session ${sessionId.slice(0, 8)} was abandoned; a fresh one is used for further messages.`;
10308
- this.untrackableAck.set(messageId, errorMessage4);
11625
+ const errorMessage5 = `OpenCode accepted this ${dispatchDescription} once, but its assigned id was never confirmed after ${attempts} attempts to match it up \u2014 the message was deliberately not sent again, so no duplicate turn was created; session ${sessionId.slice(0, 8)} was abandoned; a fresh one is used for further messages.`;
11626
+ this.untrackableAck.set(messageId, errorMessage5);
10309
11627
  this.untrackableAckSessionIds.set(messageId, null);
10310
11628
  this.log({
10311
11629
  level: "error",
10312
- message: errorMessage4,
11630
+ message: errorMessage5,
10313
11631
  conversation_id: conversationId,
10314
11632
  message_id: messageId
10315
11633
  });
@@ -10317,7 +11635,7 @@ var ChannelDriver = class _ChannelDriver {
10317
11635
  conversationId,
10318
11636
  messageId,
10319
11637
  null,
10320
- errorMessage4
11638
+ errorMessage5
10321
11639
  );
10322
11640
  if (reportError !== null) {
10323
11641
  this.log({
@@ -10498,12 +11816,12 @@ var ChannelDriver = class _ChannelDriver {
10498
11816
  conversation_id: conv.id,
10499
11817
  message_id: message.id
10500
11818
  });
10501
- const errorMessage4 = this.untrackableAck.get(message.id);
11819
+ const errorMessage5 = this.untrackableAck.get(message.id);
10502
11820
  const reportError = await this.reportUntrackableAck(
10503
11821
  conv.id,
10504
11822
  message.id,
10505
11823
  null,
10506
- errorMessage4
11824
+ errorMessage5
10507
11825
  );
10508
11826
  if (reportError === null) {
10509
11827
  continue;
@@ -10591,7 +11909,7 @@ var ChannelDriver = class _ChannelDriver {
10591
11909
  const hasProviderAndModel = dispatchedModel !== null && separator > 0 && separator < dispatchedModel.length - 1;
10592
11910
  const providerId = hasProviderAndModel ? dispatchedModel.slice(0, separator) : null;
10593
11911
  const modelId = hasProviderAndModel ? dispatchedModel.slice(separator + 1) : null;
10594
- const errorMessage4 = `Provider namespace not loaded on this runner: ${message.opencode_model}. Refused before dispatch; no turn was started.`;
11912
+ const errorMessage5 = `Provider namespace not loaded on this runner: ${message.opencode_model}. Refused before dispatch; no turn was started.`;
10595
11913
  this.log({
10596
11914
  level: "error",
10597
11915
  message: `Refusing message ${message.id.slice(0, 8)} in conversation ${conv.id.slice(0, 8)}: provider namespace ${providerId ?? "(unknown)"} is not loaded; no turn was started`,
@@ -10599,7 +11917,7 @@ var ChannelDriver = class _ChannelDriver {
10599
11917
  message_id: message.id
10600
11918
  });
10601
11919
  try {
10602
- await this.markFailed(conv.id, message.id, sessionId, errorMessage4, void 0, {
11920
+ await this.markFailed(conv.id, message.id, sessionId, errorMessage5, void 0, {
10603
11921
  classification: {
10604
11922
  kind: "model_auth",
10605
11923
  providerId,
@@ -10677,12 +11995,12 @@ var ChannelDriver = class _ChannelDriver {
10677
11995
  } catch (err) {
10678
11996
  if (err instanceof ChannelAuthError) throw err;
10679
11997
  if (this.isV2 && err instanceof OpenCodeV2PromptAckError) {
10680
- const errorMessage5 = err instanceof Error ? err.message : String(err);
10681
- this.untrackableAck.set(message.id, errorMessage5);
11998
+ const errorMessage6 = err instanceof Error ? err.message : String(err);
11999
+ this.untrackableAck.set(message.id, errorMessage6);
10682
12000
  this.untrackableAckSessionIds.set(message.id, null);
10683
12001
  this.log({
10684
12002
  level: "error",
10685
- message: `V2 prompt dispatch for message ${message.id.slice(0, 8)} failed after a positive ack with no usable id: ${errorMessage5}`,
12003
+ message: `V2 prompt dispatch for message ${message.id.slice(0, 8)} failed after a positive ack with no usable id: ${errorMessage6}`,
10686
12004
  conversation_id: conv.id,
10687
12005
  message_id: message.id
10688
12006
  });
@@ -10690,7 +12008,7 @@ var ChannelDriver = class _ChannelDriver {
10690
12008
  conv.id,
10691
12009
  message.id,
10692
12010
  null,
10693
- errorMessage5
12011
+ errorMessage6
10694
12012
  );
10695
12013
  if (markError !== null) {
10696
12014
  this.log({
@@ -10729,7 +12047,7 @@ var ChannelDriver = class _ChannelDriver {
10729
12047
  await this.failV2ModelSwitch(conv, message, sessionId, err);
10730
12048
  break;
10731
12049
  }
10732
- const errorMessage4 = err instanceof Error ? err.message : String(err);
12050
+ const errorMessage5 = err instanceof Error ? err.message : String(err);
10733
12051
  this.sessions.delete(conv.id);
10734
12052
  this.supersede(conv.id, sessionId);
10735
12053
  this.log({
@@ -10738,7 +12056,7 @@ var ChannelDriver = class _ChannelDriver {
10738
12056
  conversation_id: conv.id,
10739
12057
  message_id: message.id
10740
12058
  });
10741
- await this.markFailed(conv.id, message.id, null, errorMessage4).catch((markErr) => {
12059
+ await this.markFailed(conv.id, message.id, null, errorMessage5).catch((markErr) => {
10742
12060
  this.log({
10743
12061
  level: "warn",
10744
12062
  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)}`,
@@ -10749,7 +12067,7 @@ var ChannelDriver = class _ChannelDriver {
10749
12067
  });
10750
12068
  this.log({
10751
12069
  level: "error",
10752
- message: `Message ${message.id.slice(0, 8)} dispatch failed: ${errorMessage4}`,
12070
+ message: `Message ${message.id.slice(0, 8)} dispatch failed: ${errorMessage5}`,
10753
12071
  conversation_id: conv.id,
10754
12072
  message_id: message.id
10755
12073
  });
@@ -11034,7 +12352,12 @@ var ChannelDriver = class _ChannelDriver {
11034
12352
  this.watchers.get(sessionId),
11035
12353
  message.id
11036
12354
  );
11037
- if (hasLaterSiblingTurnStarted(messages, ocId ?? "", siblingOcIds)) {
12355
+ if (hasLaterSiblingTurnStarted(
12356
+ messages,
12357
+ ocId ?? "",
12358
+ siblingOcIds,
12359
+ this.openCodeClient.version
12360
+ )) {
11038
12361
  this.log({
11039
12362
  level: "warn",
11040
12363
  message: `Re-drive: OpenCode already served a later, different Evident message's turn in session ${sessionId.slice(0, 8)} while message ${message.id.slice(0, 8)} produced no reply \u2014 re-dispatching instead of reattaching to someone else's turn`,
@@ -12673,7 +13996,12 @@ var ChannelDriver = class _ChannelDriver {
12673
13996
  return;
12674
13997
  }
12675
13998
  const siblingOcIds = this.siblingOpencodeMessageIds(watcher, inFlight.evidentMessageId);
12676
- const skippedByOpencode = state === "queued" && hasLaterSiblingTurnStarted(messages, inFlight.opencodeMessageId, siblingOcIds);
13999
+ const skippedByOpencode = state === "queued" && hasLaterSiblingTurnStarted(
14000
+ messages,
14001
+ inFlight.opencodeMessageId,
14002
+ siblingOcIds,
14003
+ this.openCodeClient.version
14004
+ );
12677
14005
  const pastStuckBound = this.now() - inFlight.dispatchedAt >= this.stuckQueuedMs;
12678
14006
  const sessionIdle = state === "queued" && !hasRunningAssistantExcept(messages, inFlight.opencodeMessageId);
12679
14007
  if (state === "queued" && pastStuckBound && (sessionIdle || skippedByOpencode) && !inFlight.stuckReported) {
@@ -13684,12 +15012,12 @@ var ChannelDriver = class _ChannelDriver {
13684
15012
  conversation_id: row.conversation_id,
13685
15013
  message_id: row.id
13686
15014
  });
13687
- const errorMessage4 = this.untrackableAck.get(row.id);
15015
+ const errorMessage5 = this.untrackableAck.get(row.id);
13688
15016
  const reportError = await this.reportUntrackableAck(
13689
15017
  row.conversation_id,
13690
15018
  row.id,
13691
15019
  this.untrackableAckSessionIds.get(row.id) ?? null,
13692
- errorMessage4
15020
+ errorMessage5
13693
15021
  );
13694
15022
  if (reportError !== null) {
13695
15023
  this.log({
@@ -14008,14 +15336,14 @@ var ChannelDriver = class _ChannelDriver {
14008
15336
  this.awaitingReadopt.delete(row.id);
14009
15337
  if (err instanceof ChannelAuthError) throw err;
14010
15338
  if (this.isV2) {
14011
- const errorMessage4 = err instanceof Error ? err.message : String(err);
15339
+ const errorMessage5 = err instanceof Error ? err.message : String(err);
14012
15340
  const invalidPromptAck = err instanceof OpenCodeV2PromptAckError;
14013
15341
  if (!invalidPromptAck) {
14014
15342
  const exists = await this.sessionExists(sessionId);
14015
15343
  if (exists === false) {
14016
15344
  this.log({
14017
15345
  level: "warn",
14018
- message: `Re-adopt: message ${row.id.slice(0, 8)} dispatch hit a session (${sessionId.slice(0, 8)}) that was deleted mid-dispatch \u2014 deferring to the next drain: ${errorMessage4}`,
15346
+ message: `Re-adopt: message ${row.id.slice(0, 8)} dispatch hit a session (${sessionId.slice(0, 8)}) that was deleted mid-dispatch \u2014 deferring to the next drain: ${errorMessage5}`,
14019
15347
  conversation_id: row.conversation_id,
14020
15348
  message_id: row.id
14021
15349
  });
@@ -14025,7 +15353,7 @@ var ChannelDriver = class _ChannelDriver {
14025
15353
  if (exists === null) {
14026
15354
  this.log({
14027
15355
  level: "warn",
14028
- message: `Re-adopt: message ${row.id.slice(0, 8)} dispatch failed and session (${sessionId.slice(0, 8)}) existence could not be confirmed \u2014 deferring to the next drain: ${errorMessage4}`,
15356
+ message: `Re-adopt: message ${row.id.slice(0, 8)} dispatch failed and session (${sessionId.slice(0, 8)}) existence could not be confirmed \u2014 deferring to the next drain: ${errorMessage5}`,
14029
15357
  conversation_id: row.conversation_id,
14030
15358
  message_id: row.id
14031
15359
  });
@@ -14033,7 +15361,7 @@ var ChannelDriver = class _ChannelDriver {
14033
15361
  return;
14034
15362
  }
14035
15363
  } else {
14036
- this.untrackableAck.set(row.id, errorMessage4);
15364
+ this.untrackableAck.set(row.id, errorMessage5);
14037
15365
  this.untrackableAckSessionIds.set(row.id, sessionId);
14038
15366
  }
14039
15367
  if (err instanceof OpenCodeV2ModelSwitchError) {
@@ -14042,7 +15370,7 @@ var ChannelDriver = class _ChannelDriver {
14042
15370
  }
14043
15371
  this.log({
14044
15372
  level: "error",
14045
- message: `V2 re-adopt dispatch for message ${row.id.slice(0, 8)} failed: ${errorMessage4}`,
15373
+ message: `V2 re-adopt dispatch for message ${row.id.slice(0, 8)} failed: ${errorMessage5}`,
14046
15374
  conversation_id: row.conversation_id,
14047
15375
  message_id: row.id
14048
15376
  });
@@ -14051,7 +15379,7 @@ var ChannelDriver = class _ChannelDriver {
14051
15379
  row.conversation_id,
14052
15380
  row.id,
14053
15381
  sessionId,
14054
- errorMessage4
15382
+ errorMessage5
14055
15383
  );
14056
15384
  if (markError !== null) {
14057
15385
  this.log({
@@ -14062,7 +15390,7 @@ var ChannelDriver = class _ChannelDriver {
14062
15390
  });
14063
15391
  }
14064
15392
  } else {
14065
- await this.markFailed(row.conversation_id, row.id, sessionId, errorMessage4).catch(
15393
+ await this.markFailed(row.conversation_id, row.id, sessionId, errorMessage5).catch(
14066
15394
  (markErr) => {
14067
15395
  this.log({
14068
15396
  level: "warn",
@@ -15046,9 +16374,9 @@ var ChannelDriver = class _ChannelDriver {
15046
16374
  * trackable. Callers use the returned error to keep their path-specific logging
15047
16375
  * while the same report payload can be retried on a later drain.
15048
16376
  */
15049
- async reportUntrackableAck(conversationId, messageId, sessionId, errorMessage4) {
16377
+ async reportUntrackableAck(conversationId, messageId, sessionId, errorMessage5) {
15050
16378
  try {
15051
- await this.markFailed(conversationId, messageId, sessionId, errorMessage4);
16379
+ await this.markFailed(conversationId, messageId, sessionId, errorMessage5);
15052
16380
  return null;
15053
16381
  } catch (err) {
15054
16382
  this.signalUntrackableAck(conversationId, messageId);
@@ -15431,12 +16759,19 @@ import chalk5 from "chalk";
15431
16759
  import ora2 from "ora";
15432
16760
  import { select as select2 } from "@inquirer/prompts";
15433
16761
  var INTERACTIVE_START_TIMEOUT_MS = 3e4;
15434
- function checkNonInteractivePortConflict(port, isPortInUseFn) {
15435
- if (isPortInUseFn(port)) {
16762
+ async function reclaimNonInteractivePort(port, options) {
16763
+ const isPortInUseFn = options.isPortInUse ?? isPortInUse;
16764
+ if (!await isPortInUseFn(port)) return void 0;
16765
+ if (!options.imageManaged) {
15436
16766
  throw new Error(
15437
16767
  `Port ${port} is already in use by a non-OpenCode process. Free it or pass --port.`
15438
16768
  );
15439
16769
  }
16770
+ const outcome = await (options.reclaimLoopbackPort ?? reclaimLoopbackPort)(port);
16771
+ if (outcome.kind !== "blocked") return outcome;
16772
+ throw new Error(
16773
+ `Port ${port} is held by an unresponsive process. Evident tried to reclaim it but could not free it: ${outcome.detail}. Stop the holder manually or pass --port.`
16774
+ );
15440
16775
  }
15441
16776
  function unknownPasswordError(port) {
15442
16777
  return new Error(
@@ -15493,24 +16828,29 @@ async function ensureOpenCodeRunning(ctx) {
15493
16828
  }
15494
16829
  }
15495
16830
  if (!ctx.interactive) {
15496
- checkNonInteractivePortConflict(ctx.port, isPortInUse);
16831
+ const reclaimOutcome = await reclaimNonInteractivePort(ctx.port, {
16832
+ imageManaged: ctx.inheritStdio === true
16833
+ });
15497
16834
  ctx.log(`OpenCode is not running on port ${ctx.port}. Starting it automatically...`);
15498
16835
  const proc = await startOpenCode(ctx.port, { inheritStdio: ctx.inheritStdio });
15499
- const health = await waitForOpenCodeHealth(ctx.port, ctx.startTimeoutMs);
16836
+ const stopEarly = watchOpenCodeExit(proc, ctx.log);
16837
+ const health = await waitForOpenCodeHealth(ctx.port, ctx.startTimeoutMs, stopEarly);
15500
16838
  if (!health.healthy) {
15501
16839
  if (health.authFailed) {
15502
16840
  return {
15503
16841
  port: ctx.port,
15504
16842
  process: proc,
15505
16843
  version: null,
15506
- notReadyReason: "it is answering with an authentication challenge, likely because OPENCODE_SERVER_PASSWORD is set in the environment of the process that started it; a longer start timeout will not resolve this"
16844
+ notReadyReason: "it is answering with an authentication challenge, likely because OPENCODE_SERVER_PASSWORD is set in the environment of the process that started it",
16845
+ ...reclaimOutcome ? { reclaimOutcome } : {}
15507
16846
  };
15508
16847
  }
15509
16848
  return {
15510
16849
  port: ctx.port,
15511
16850
  process: proc,
15512
16851
  version: null,
15513
- notReadyReason: `it did not become healthy within ${Math.round(ctx.startTimeoutMs / 1e3)}s`
16852
+ notReadyReason: stopEarly() ?? `it did not become healthy within ${Math.round(ctx.startTimeoutMs / 1e3)}s; raise the wait with --opencode-start-timeout <seconds> (env ${OPENCODE_START_TIMEOUT_ENV})`,
16853
+ ...reclaimOutcome ? { reclaimOutcome } : {}
15514
16854
  };
15515
16855
  }
15516
16856
  ctx.log(`OpenCode started on port ${ctx.port}${health.version ? ` (v${health.version})` : ""}`);
@@ -15518,14 +16858,15 @@ async function ensureOpenCodeRunning(ctx) {
15518
16858
  port: ctx.port,
15519
16859
  process: proc,
15520
16860
  version: health.version ?? null,
15521
- notReadyReason: null
16861
+ notReadyReason: null,
16862
+ ...reclaimOutcome ? { reclaimOutcome } : {}
15522
16863
  };
15523
16864
  }
15524
16865
  let port = ctx.port;
15525
- if (isPortInUse(port)) {
16866
+ if (await isPortInUse(port)) {
15526
16867
  console.log(chalk5.yellow(`
15527
16868
  Port ${port} is already in use.`));
15528
- const alternativePort = findAvailablePort(port + 1);
16869
+ const alternativePort = await findAvailablePort(port + 1);
15529
16870
  if (alternativePort) {
15530
16871
  const useAlternative = await select2({
15531
16872
  message: `Use port ${alternativePort} instead?`,
@@ -15572,13 +16913,15 @@ Port ${port} is already in use.`));
15572
16913
  if (action === "start") {
15573
16914
  const spinner = ora2("Starting OpenCode...").start();
15574
16915
  const proc = await startOpenCode(port, { inheritStdio: ctx.inheritStdio });
15575
- const health = await waitForOpenCodeHealth(port, INTERACTIVE_START_TIMEOUT_MS);
16916
+ const stopEarly = watchOpenCodeExit(proc, ctx.log);
16917
+ const health = await waitForOpenCodeHealth(port, INTERACTIVE_START_TIMEOUT_MS, stopEarly);
15576
16918
  if (!health.healthy) {
15577
16919
  spinner.fail("Failed to start OpenCode");
15578
16920
  if (health.authFailed) {
15579
16921
  throw unknownPasswordError(port);
15580
16922
  }
15581
- throw new Error("OpenCode failed to start");
16923
+ const exitReason = stopEarly();
16924
+ throw new Error(`OpenCode failed to start${exitReason ? `: ${exitReason}` : ""}`);
15582
16925
  }
15583
16926
  spinner.stop();
15584
16927
  return { port, process: proc, version: health.version ?? null, notReadyReason: null };
@@ -15617,40 +16960,24 @@ async function ensureOpenCode2Running(ctx) {
15617
16960
  }
15618
16961
  let port = ctx.port;
15619
16962
  if (!ctx.interactive) {
15620
- checkNonInteractivePortConflict(port, isPortInUse);
15621
- } else if (isPortInUse(port)) {
15622
- console.log(chalk6.yellow(`
15623
- Port ${port} is already in use.`));
15624
- const alternativePort = findAvailablePort(port + 1);
15625
- if (alternativePort) {
15626
- const useAlternative = await select3({
15627
- message: `Use port ${alternativePort} instead?`,
15628
- choices: [
15629
- { name: `Yes, use port ${alternativePort}`, value: "yes" },
15630
- { name: "No, I will free the port manually", value: "no" }
15631
- ]
15632
- });
15633
- if (useAlternative === "yes") {
15634
- port = alternativePort;
15635
- } else {
15636
- throw new Error(`Port ${ctx.port} is in use`);
15637
- }
15638
- }
15639
- }
15640
- if (!ctx.interactive) {
16963
+ const reclaimOutcome = await reclaimNonInteractivePort(port, {
16964
+ imageManaged: ctx.inheritStdio === true
16965
+ });
15641
16966
  ctx.log(`OpenCode V2 is not running on port ${port}. Starting it automatically...`);
15642
16967
  const { child: proc, password } = await startOpenCode2(port, {
15643
16968
  inheritStdio: ctx.inheritStdio,
15644
16969
  command: ctx.command
15645
16970
  });
15646
- const health = await waitForOpenCode2Health(port, password, ctx.startTimeoutMs);
16971
+ const stopEarly = watchOpenCodeExit(proc, ctx.log);
16972
+ const health = await waitForOpenCode2Health(port, password, ctx.startTimeoutMs, stopEarly);
15647
16973
  if (!health.healthy) {
15648
16974
  return {
15649
16975
  port,
15650
16976
  process: proc,
15651
16977
  version: null,
15652
- notReadyReason: `it did not become healthy within ${Math.round(ctx.startTimeoutMs / 1e3)}s`,
15653
- password
16978
+ notReadyReason: stopEarly() ?? `it did not become healthy within ${Math.round(ctx.startTimeoutMs / 1e3)}s; raise the wait with --opencode-start-timeout <seconds> (env ${OPENCODE_START_TIMEOUT_ENV})`,
16979
+ password,
16980
+ ...reclaimOutcome ? { reclaimOutcome } : {}
15654
16981
  };
15655
16982
  }
15656
16983
  ctx.log(`OpenCode V2 started on port ${port}${health.version ? ` (v${health.version})` : ""}`);
@@ -15659,8 +16986,27 @@ Port ${port} is already in use.`));
15659
16986
  process: proc,
15660
16987
  version: health.version ?? null,
15661
16988
  notReadyReason: null,
15662
- password
16989
+ password,
16990
+ ...reclaimOutcome ? { reclaimOutcome } : {}
15663
16991
  };
16992
+ } else if (await isPortInUse(port)) {
16993
+ console.log(chalk6.yellow(`
16994
+ Port ${port} is already in use.`));
16995
+ const alternativePort = await findAvailablePort(port + 1);
16996
+ if (alternativePort) {
16997
+ const useAlternative = await select3({
16998
+ message: `Use port ${alternativePort} instead?`,
16999
+ choices: [
17000
+ { name: `Yes, use port ${alternativePort}`, value: "yes" },
17001
+ { name: "No, I will free the port manually", value: "no" }
17002
+ ]
17003
+ });
17004
+ if (useAlternative === "yes") {
17005
+ port = alternativePort;
17006
+ } else {
17007
+ throw new Error(`Port ${ctx.port} is in use`);
17008
+ }
17009
+ }
15664
17010
  }
15665
17011
  const command = ctx.command ?? "opencode2";
15666
17012
  const action = await select3({
@@ -15697,10 +17043,17 @@ Port ${port} is already in use.`));
15697
17043
  inheritStdio: ctx.inheritStdio,
15698
17044
  command: ctx.command
15699
17045
  });
15700
- const health = await waitForOpenCode2Health(port, password, INTERACTIVE_START_TIMEOUT_MS2);
17046
+ const stopEarly = watchOpenCodeExit(proc, ctx.log);
17047
+ const health = await waitForOpenCode2Health(
17048
+ port,
17049
+ password,
17050
+ INTERACTIVE_START_TIMEOUT_MS2,
17051
+ stopEarly
17052
+ );
15701
17053
  if (!health.healthy) {
15702
17054
  spinner.fail("Failed to start OpenCode V2");
15703
- throw new Error("OpenCode V2 failed to start");
17055
+ const exitReason = stopEarly();
17056
+ throw new Error(`OpenCode V2 failed to start${exitReason ? `: ${exitReason}` : ""}`);
15704
17057
  }
15705
17058
  spinner.stop();
15706
17059
  return {
@@ -15996,7 +17349,7 @@ async function configureGitHubAccess({ env, log: log3 }) {
15996
17349
  }
15997
17350
 
15998
17351
  // src/lib/opencode/config-overlay.ts
15999
- import { execFileSync as execFileSync2 } from "node:child_process";
17352
+ import { execFileSync as execFileSync3 } from "node:child_process";
16000
17353
  import { copyFileSync, existsSync as existsSync2, statSync as statSync6 } from "node:fs";
16001
17354
  import { isAbsolute as isAbsolute5, join as join15, resolve as resolve5 } from "node:path";
16002
17355
  function parseConfigContent(content) {
@@ -16038,7 +17391,7 @@ function applyRunnerOpenCodeConfig({
16038
17391
  }
16039
17392
  copyFileSync(source, join15(cwd, target));
16040
17393
  try {
16041
- execFileSync2("git", ["-C", cwd, "update-index", "--skip-worktree", target], {
17394
+ execFileSync3("git", ["-C", cwd, "update-index", "--skip-worktree", target], {
16042
17395
  stdio: "ignore"
16043
17396
  });
16044
17397
  } catch (error2) {
@@ -16212,7 +17565,7 @@ var MAX_FLUSH_PASSES = 2;
16212
17565
  function outcomesWith(outcome) {
16213
17566
  return { claude: outcome, opencode: outcome };
16214
17567
  }
16215
- function errorMessage3(error2) {
17568
+ function errorMessage4(error2) {
16216
17569
  return error2 instanceof Error ? error2.message : String(error2);
16217
17570
  }
16218
17571
  function waitForSettlement(promise, timeoutMs) {
@@ -16239,7 +17592,7 @@ function writeMarker(markerPath, outcomes, log3) {
16239
17592
  writeFileSync8(temporaryPath, body, { mode: 384 });
16240
17593
  renameSync(temporaryPath, markerPath);
16241
17594
  } catch (error2) {
16242
- log3(`CREDENTIAL-FLUSH-MARKER-UNWRITABLE: ${markerPath}: ${errorMessage3(error2)}`, "warn");
17595
+ log3(`CREDENTIAL-FLUSH-MARKER-UNWRITABLE: ${markerPath}: ${errorMessage4(error2)}`, "warn");
16243
17596
  }
16244
17597
  }
16245
17598
  function intervalSeconds(env, log3) {
@@ -16271,7 +17624,7 @@ async function runFlushStore(store, env, synchroniserRunner, log3, deadlineAt) {
16271
17624
  },
16272
17625
  (error2) => {
16273
17626
  failed = true;
16274
- log3(`CREDENTIAL-FLUSH-ERROR: ${store}: ${errorMessage3(error2)}`, "warn");
17627
+ log3(`CREDENTIAL-FLUSH-ERROR: ${store}: ${errorMessage4(error2)}`, "warn");
16275
17628
  }
16276
17629
  );
16277
17630
  const abortTimer = setTimeout(() => controller.abort(), remainingMs);
@@ -16331,7 +17684,7 @@ function createCredentialSync({
16331
17684
  outcomes[store] = !result.timedOut && result.code === 0 ? "ok" : "failed";
16332
17685
  } catch (error2) {
16333
17686
  outcomes[store] = "failed";
16334
- log3(`CREDENTIAL-SYNC-TICK-ERROR: ${store}: ${errorMessage3(error2)}`, "debug");
17687
+ log3(`CREDENTIAL-SYNC-TICK-ERROR: ${store}: ${errorMessage4(error2)}`, "debug");
16335
17688
  }
16336
17689
  }
16337
17690
  const failed = STORES.some((store) => outcomes[store] === "failed");
@@ -16808,7 +18161,6 @@ function resolveFileSyncExactFiles(raw, homeDir) {
16808
18161
  }
16809
18162
  var DEFAULT_OPENCODE_START_TIMEOUT_SECONDS = 180;
16810
18163
  var MAX_OPENCODE_START_TIMEOUT_SECONDS = 3600;
16811
- var OPENCODE_START_TIMEOUT_ENV = "EVIDENT_OPENCODE_START_TIMEOUT";
16812
18164
  var OPENCODE_VERSION_ENV = "EVIDENT_OPENCODE_VERSION";
16813
18165
  function resolveOpenCodeVersion(options, env = process.env) {
16814
18166
  let raw;
@@ -17336,8 +18688,8 @@ async function driveChannels(state, driver) {
17336
18688
  state.running = false;
17337
18689
  break;
17338
18690
  }
17339
- const errorMessage4 = error2 instanceof Error ? error2.message : String(error2);
17340
- logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage4}` });
18691
+ const errorMessage5 = error2 instanceof Error ? error2.message : String(error2);
18692
+ logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage5}` });
17341
18693
  if (state.interactive) displayStatus(state);
17342
18694
  if (driver.hasInFlightWatchers()) {
17343
18695
  consecutiveDrainFailures = 0;
@@ -17432,6 +18784,8 @@ var SESSION_CLEANUP_MAX_DELETES_PER_SWEEP = 100;
17432
18784
  var SESSION_CLEANUP_MAX_ISOLATED_DELETE_FAILURES = 2;
17433
18785
  var SESSION_CLEANUP_GIVE_UP_AFTER_FAILURES = 2;
17434
18786
  var MAX_SESSION_DELETE_BODY_LENGTH = 200;
18787
+ var SESSION_ARCHIVE_FAILURE_DIAGNOSTIC_BUDGET = 3;
18788
+ var SESSION_ARCHIVE_MANIFEST_BUDGET_MS = 500;
17435
18789
  function shouldWarnForReclaimSkip(reason) {
17436
18790
  if (reason !== "sqlite-unavailable" && reason !== "disk-exhaustion") return false;
17437
18791
  const version2 = /^v(\d+)\.(\d+)\.(\d+)$/.exec(process.version);
@@ -17455,18 +18809,52 @@ function logSessionArchiveActivity(state, phase, entry) {
17455
18809
  logActivity(state, {
17456
18810
  ...entry,
17457
18811
  source: "cli.session-archive",
17458
- metadata: { ...entry.metadata, phase }
18812
+ // The forwarder drops metadata beyond its 20-entry cap in insertion order.
18813
+ metadata: { phase, ...entry.metadata }
18814
+ });
18815
+ }
18816
+ function logSessionArchiveMetadataDecodeFailure(state, phase, details) {
18817
+ const subject = details.sessionId ? `session ${details.sessionId}` : "audit manifest";
18818
+ logSessionArchiveActivity(state, phase, {
18819
+ type: "info",
18820
+ level: "warn",
18821
+ message: `Session archive: ${subject} upload returned malformed ${details.field} metadata; the upload succeeded without that value`,
18822
+ metadata: {
18823
+ outcome: "archive-upload-metadata-malformed",
18824
+ metadata_field: details.field,
18825
+ metadata_decode_reason: details.reason,
18826
+ ...details.sessionId ? { session_id: details.sessionId } : {},
18827
+ ...details.manifestKey ? { manifest_key: details.manifestKey } : {}
18828
+ }
17459
18829
  });
17460
18830
  }
17461
- function logSessionArchiveSummary(state, phase, summary) {
18831
+ function logSessionArchiveSummary(state, phase, summary, reconciliation) {
17462
18832
  const everyUploadFailed = summary.uploadAttempts > 0 && summary.uploadFailures === summary.uploadAttempts;
17463
- const staleSince = everyUploadFailed && summary.staleSince !== null ? `; archive stale since ${summary.staleSince}` : "";
17464
18833
  const neverWatermarked = summary.neverWatermarkedFailures > 0 ? `; ${summary.neverWatermarkedFailures} failed session(s) had no prior successful upload` : "";
17465
18834
  const warning2 = summary.failed > 0 || summary.failures.length > 0 || everyUploadFailed || !summary.reconciliationComplete;
18835
+ if (!reconciliation.complete) {
18836
+ const failure = reconciliation.failures[0];
18837
+ const detail = failure.kind === "http" ? `HTTP ${failure.status} for chunk ${failure.chunk}` : failure.kind === "network" ? `network failure for chunk ${failure.chunk}: ${redactDiagnosticText(failure.message ?? "unknown error").slice(0, 200)}` : `invalid response for chunk ${failure.chunk}`;
18838
+ logSessionArchiveActivity(state, phase, {
18839
+ type: "info",
18840
+ level: "warn",
18841
+ message: `Session archive: binding reconciliation incomplete for runner ${state.agentId}; ${reconciliation.failures.length} chunk(s) failed (${detail}), unresolved sessions will not replace existing archives`,
18842
+ metadata: {
18843
+ outcome: "binding-reconciliation-incomplete",
18844
+ runner_id: state.agentId,
18845
+ failed_chunks: reconciliation.failures.length,
18846
+ first_failed_chunk: failure.chunk,
18847
+ first_failure_kind: failure.kind,
18848
+ ...failure.status !== void 0 ? { http_status: failure.status } : {}
18849
+ }
18850
+ });
18851
+ }
17466
18852
  logSessionArchiveActivity(state, phase, {
17467
18853
  type: "info",
17468
18854
  level: warning2 ? "warn" : "info",
17469
- message: `Session archive: inspected ${summary.inspected}, uploaded ${summary.uploaded}, unchanged ${summary.unchanged}, failed ${summary.failed}, skipped budget ${summary.skippedBudget}, unmapped ${summary.unmappedIds.length}, conflicts ${summary.conflicts}, reconciliation incomplete ${summary.reconciliationIncomplete}; bindings ledger ${summary.bindingSourceCounts.ledger}, watermark ${summary.bindingSourceCounts.watermark}, current ${summary.bindingSourceCounts.current}, invocation ${summary.bindingSourceCounts.invocation}, history ${summary.bindingSourceCounts.history}, parent ${summary.bindingSourceCounts.parent}` + staleSince + neverWatermarked,
18855
+ message: `Session archive: inspected ${summary.inspected}, uploaded ${summary.uploaded}, unchanged ${summary.unchanged}, failed ${summary.failed}, skipped budget ${summary.skippedBudget}, unmapped ${summary.unmappedIds.length}, conflicts ${summary.conflicts}, reconciliation incomplete ${summary.reconciliationIncomplete}; bindings ledger ${summary.bindingSourceCounts.ledger}, watermark ${summary.bindingSourceCounts.watermark}, current ${summary.bindingSourceCounts.current}, invocation ${summary.bindingSourceCounts.invocation}, history ${summary.bindingSourceCounts.history}, parent ${summary.bindingSourceCounts.parent}` + neverWatermarked,
18856
+ // Keep this summary at the forwarder's 20-entry metadata cap; phase is
18857
+ // prepended by logSessionArchiveActivity.
17470
18858
  metadata: {
17471
18859
  outcome: "archive-run-complete",
17472
18860
  sessions_inspected: summary.inspected,
@@ -17477,7 +18865,6 @@ function logSessionArchiveSummary(state, phase, summary) {
17477
18865
  uploads_failed: summary.uploadFailures,
17478
18866
  sessions_skipped_budget: summary.skippedBudget,
17479
18867
  sessions_unmapped: summary.unmappedIds.length,
17480
- sessions_unresolved: summary.unresolved,
17481
18868
  sessions_conflicted: summary.conflicts,
17482
18869
  sessions_reconciliation_incomplete: summary.reconciliationIncomplete,
17483
18870
  binding_reconciliation_complete: summary.reconciliationComplete,
@@ -17487,11 +18874,10 @@ function logSessionArchiveSummary(state, phase, summary) {
17487
18874
  bindings_from_invocation: summary.bindingSourceCounts.invocation,
17488
18875
  bindings_from_history: summary.bindingSourceCounts.history,
17489
18876
  bindings_from_parent: summary.bindingSourceCounts.parent,
17490
- sessions_without_prior_watermark: summary.neverWatermarkedFailures,
17491
- ...everyUploadFailed && summary.staleSince !== null ? { stale_since: summary.staleSince } : {}
18877
+ sessions_without_prior_watermark: summary.neverWatermarkedFailures
17492
18878
  }
17493
18879
  });
17494
- for (const failure of summary.failures) {
18880
+ const logFailure = (failure) => {
17495
18881
  const permanentSizeFailure = failure.reason === "too-large";
17496
18882
  const hasPayloadDetails = failure.bytes !== void 0 && failure.byteLimit !== void 0 && failure.messageCount !== void 0 && failure.partCount !== void 0;
17497
18883
  const payloadDetails = hasPayloadDetails ? `; payload bytes=${failure.bytes} limit=${failure.byteLimit} messages=${failure.messageCount} parts=${failure.partCount}` : "";
@@ -17514,7 +18900,9 @@ function logSessionArchiveSummary(state, phase, summary) {
17514
18900
  } : {}
17515
18901
  }
17516
18902
  });
17517
- }
18903
+ };
18904
+ const failuresToLog = phase === "sweep" ? summary.failures : summary.failures.slice(0, SESSION_ARCHIVE_FAILURE_DIAGNOSTIC_BUDGET);
18905
+ for (const failure of failuresToLog) logFailure(failure);
17518
18906
  if (summary.unmappedIds.length > 0) {
17519
18907
  logSessionArchiveActivity(state, phase, {
17520
18908
  type: "info",
@@ -17538,6 +18926,117 @@ function logSessionArchiveSummary(state, phase, summary) {
17538
18926
  });
17539
18927
  }
17540
18928
  }
18929
+ function hasSessionArchivePrerequisites(state) {
18930
+ return Boolean(
18931
+ state.opencodeClient && state.sessionArchiveConfig.keyPrefix && state.sessionArchiveWatermarkPath && state.agentId
18932
+ );
18933
+ }
18934
+ async function publishSessionArchiveAudit(state, phase, identity, summary, manifestWindowMs, manifestSignal, parentSignal) {
18935
+ if (!hasSessionArchivePrerequisites(state)) return;
18936
+ const manifestKey = sessionArchiveManifestKey(state.sessionArchiveConfig.keyPrefix, identity);
18937
+ let manifestDurable = false;
18938
+ let manifestVersionId = null;
18939
+ let failure = null;
18940
+ if (parentSignal.aborted) {
18941
+ failure = { kind: "not-attempted", reason: "pass-aborted" };
18942
+ } else if (manifestWindowMs <= 0) {
18943
+ failure = { kind: "not-attempted", reason: "no-manifest-budget" };
18944
+ } else {
18945
+ try {
18946
+ const result = await uploadSessionArchiveManifest({
18947
+ keyPrefix: state.sessionArchiveConfig.keyPrefix,
18948
+ identity,
18949
+ summary,
18950
+ timeoutMs: manifestWindowMs,
18951
+ signal: manifestSignal,
18952
+ upload: uploadSessionArchive,
18953
+ onMetadataDecodeError: (field, reason) => logSessionArchiveMetadataDecodeFailure(state, phase, {
18954
+ field,
18955
+ reason,
18956
+ manifestKey
18957
+ })
18958
+ });
18959
+ if (result.outcome.kind === "ok") {
18960
+ manifestDurable = true;
18961
+ manifestVersionId = result.outcome.versionId;
18962
+ } else {
18963
+ failure = {
18964
+ kind: result.outcome.kind,
18965
+ ..."reason" in result.outcome ? { reason: result.outcome.reason } : {},
18966
+ ..."exitCode" in result.outcome && result.outcome.exitCode !== void 0 ? { exitCode: result.outcome.exitCode } : {}
18967
+ };
18968
+ }
18969
+ } catch (error2) {
18970
+ const diagnostic = redactDiagnosticText(
18971
+ error2 instanceof Error ? error2.message : String(error2)
18972
+ ).replace(/[\r\n]+/g, " ").slice(0, 200);
18973
+ logSessionArchiveActivity(state, phase, {
18974
+ type: "info",
18975
+ level: "warn",
18976
+ message: `Session archive audit manifest upload threw for boot ${identity.bootId}, pass ${identity.passSequence}, phase ${phase}: ${diagnostic}`,
18977
+ metadata: {
18978
+ outcome: "archive-audit-manifest-upload-threw",
18979
+ boot_id: identity.bootId,
18980
+ pass_sequence: identity.passSequence
18981
+ }
18982
+ });
18983
+ failure = { kind: "thrown", reason: "upload-threw" };
18984
+ }
18985
+ }
18986
+ if (failure !== null) {
18987
+ logSessionArchiveActivity(state, phase, {
18988
+ type: "info",
18989
+ level: "warn",
18990
+ message: `Session archive audit manifest was not durable for ${phase} pass ${identity.passSequence}: ${failure.kind}${failure.reason ? ` (${failure.reason})` : ""}`,
18991
+ metadata: {
18992
+ outcome: "archive-audit-manifest-failed",
18993
+ boot_id: identity.bootId,
18994
+ pass_sequence: identity.passSequence,
18995
+ manifest_key: manifestKey,
18996
+ kind: failure.kind,
18997
+ ...failure.reason !== void 0 ? { reason: failure.reason } : {},
18998
+ ...failure.exitCode !== void 0 ? { exit_code: failure.exitCode } : {}
18999
+ }
19000
+ });
19001
+ }
19002
+ const sessionsInspected = summary?.inspected ?? 0;
19003
+ const sessionsUploaded = summary?.uploaded ?? 0;
19004
+ const sessionsUnchanged = summary?.unchanged ?? 0;
19005
+ const sessionsFailed = summary?.failed ?? 0;
19006
+ const sessionsSkippedChanged = summary?.skippedChanged ?? 0;
19007
+ const sessionsSkippedUnknown = summary?.skippedUnknown ?? 0;
19008
+ const outcomesReconciled = summary?.outcomesReconciled ?? null;
19009
+ const retries = summary?.uploadedSessions.filter(({ retriedPriorFailure }) => retriedPriorFailure).length ?? 0;
19010
+ const everyUploadFailed = summary !== null && summary.uploadAttempts > 0 && summary.uploadFailures === summary.uploadAttempts;
19011
+ const level = summary === null || !summary.outcomesReconciled || summary.skippedChanged > 0 ? "warn" : "info";
19012
+ const message = summary === null ? `Session archive audit: ${phase} pass could not enumerate the session store (${identity.enumerationReason ?? "unknown"}); no session was inspected` : `Session archive audit: inspected ${sessionsInspected}, uploaded ${sessionsUploaded}, unchanged ${sessionsUnchanged}, failed ${sessionsFailed}, skipped known changed ${sessionsSkippedChanged}, skipped unknown ${sessionsSkippedUnknown}; outcomes reconciled ${outcomesReconciled ? "yes" : "no"}; manifest ${manifestKey}`;
19013
+ logSessionArchiveActivity(state, phase, {
19014
+ type: "info",
19015
+ level,
19016
+ message,
19017
+ metadata: {
19018
+ outcome: "archive-outcome-audit",
19019
+ boot_id: identity.bootId,
19020
+ pass_sequence: identity.passSequence,
19021
+ enumeration_complete: identity.enumerationComplete,
19022
+ sessions_inspected: sessionsInspected,
19023
+ sessions_uploaded: sessionsUploaded,
19024
+ sessions_unchanged: sessionsUnchanged,
19025
+ sessions_failed: sessionsFailed,
19026
+ sessions_skipped_changed: sessionsSkippedChanged,
19027
+ sessions_skipped_unknown: sessionsSkippedUnknown,
19028
+ outcomes_reconciled: outcomesReconciled,
19029
+ manifest_durable: manifestDurable,
19030
+ manifest_key: manifestKey,
19031
+ manifest_version_id: manifestVersionId,
19032
+ watermark_file_present: identity.watermarkFilePresent,
19033
+ watermarks_loaded: identity.watermarksLoaded,
19034
+ uploads_retrying_prior_failures: retries,
19035
+ ...summary === null ? { enumeration_reason: identity.enumerationReason ?? "unknown" } : {},
19036
+ ...everyUploadFailed && summary?.staleSince !== null ? { stale_since: summary.staleSince } : {}
19037
+ }
19038
+ });
19039
+ }
17541
19040
  async function drainSessionDeletionReports(state) {
17542
19041
  const path = sessionDeletionReportPath(homedir9(), process.env);
17543
19042
  let delivered = 0;
@@ -17955,14 +19454,10 @@ function runSessionArchiveTask(state, phase, budgetMs, work) {
17955
19454
  }
17956
19455
  const controller = new AbortController();
17957
19456
  state.sessionArchiveAbortController = controller;
19457
+ let budgetExceeded = false;
17958
19458
  const timeout = setTimeout(() => {
19459
+ budgetExceeded = true;
17959
19460
  controller.abort();
17960
- logSessionArchiveActivity(state, phase, {
17961
- type: "info",
17962
- level: "warn",
17963
- message: `Session archive exceeded ${budgetMs}ms; remaining sessions were not confirmed archived`,
17964
- metadata: { outcome: "archive-budget-exceeded", budget_ms: budgetMs }
17965
- });
17966
19461
  }, budgetMs);
17967
19462
  const task = Promise.resolve().then(() => work(controller.signal)).catch((error2) => {
17968
19463
  logSessionArchiveActivity(state, phase, {
@@ -17973,6 +19468,19 @@ function runSessionArchiveTask(state, phase, budgetMs, work) {
17973
19468
  });
17974
19469
  return null;
17975
19470
  }).finally(() => {
19471
+ if (budgetExceeded) {
19472
+ logSessionArchiveActivity(state, phase, {
19473
+ type: "info",
19474
+ level: "warn",
19475
+ message: `Session archive exceeded ${budgetMs}ms; remaining sessions were not confirmed archived`,
19476
+ metadata: {
19477
+ outcome: "archive-budget-exceeded",
19478
+ budget_ms: budgetMs,
19479
+ boot_id: state.sessionArchiveBootId,
19480
+ pass_sequence: state.sessionArchivePassSequence
19481
+ }
19482
+ });
19483
+ }
17976
19484
  clearTimeout(timeout);
17977
19485
  if (state.sessionArchiveInFlight === task) {
17978
19486
  state.sessionArchiveInFlight = null;
@@ -17983,10 +19491,7 @@ function runSessionArchiveTask(state, phase, budgetMs, work) {
17983
19491
  return task;
17984
19492
  }
17985
19493
  async function runSessionArchiveBatch(state, phase, sessions, budgetMs, signal) {
17986
- const config = state.sessionArchiveConfig;
17987
- const client = state.opencodeClient;
17988
- const watermarkPath = state.sessionArchiveWatermarkPath;
17989
- if (!client || !config.keyPrefix || !watermarkPath || !state.agentId) {
19494
+ if (!hasSessionArchivePrerequisites(state)) {
17990
19495
  logSessionArchiveActivity(state, phase, {
17991
19496
  type: "info",
17992
19497
  level: "warn",
@@ -17995,6 +19500,9 @@ async function runSessionArchiveBatch(state, phase, sessions, budgetMs, signal)
17995
19500
  });
17996
19501
  return null;
17997
19502
  }
19503
+ const config = state.sessionArchiveConfig;
19504
+ const client = state.opencodeClient;
19505
+ const watermarkPath = state.sessionArchiveWatermarkPath;
17998
19506
  const bindings = readSessionBindings(
17999
19507
  sessionBindingLedgerPath(homedir9(), process.env),
18000
19508
  (message) => logSessionArchiveActivity(state, phase, {
@@ -18011,23 +19519,6 @@ async function runSessionArchiveBatch(state, phase, sessions, budgetMs, signal)
18011
19519
  sessions,
18012
19520
  signal
18013
19521
  });
18014
- if (!reconciliation.complete) {
18015
- const failure = reconciliation.failures[0];
18016
- const detail = failure.kind === "http" ? `HTTP ${failure.status} for chunk ${failure.chunk}` : failure.kind === "network" ? `network failure for chunk ${failure.chunk}: ${redactDiagnosticText(failure.message ?? "unknown error").slice(0, 200)}` : `invalid response for chunk ${failure.chunk}`;
18017
- logSessionArchiveActivity(state, phase, {
18018
- type: "info",
18019
- level: "warn",
18020
- message: `Session archive: binding reconciliation incomplete for runner ${state.agentId}; ${reconciliation.failures.length} chunk(s) failed (${detail}), unresolved sessions will not replace existing archives`,
18021
- metadata: {
18022
- outcome: "binding-reconciliation-incomplete",
18023
- runner_id: state.agentId,
18024
- failed_chunks: reconciliation.failures.length,
18025
- first_failed_chunk: failure.chunk,
18026
- first_failure_kind: failure.kind,
18027
- ...failure.status !== void 0 ? { http_status: failure.status } : {}
18028
- }
18029
- });
18030
- }
18031
19522
  const summary = await runSessionArchive({
18032
19523
  sessions,
18033
19524
  deps: {
@@ -18038,40 +19529,97 @@ async function runSessionArchiveBatch(state, phase, sessions, budgetMs, signal)
18038
19529
  projection: reconciliation.projection,
18039
19530
  reconciliationComplete: reconciliation.complete,
18040
19531
  watermarks: state.sessionArchiveWatermarks,
19532
+ priorFailureIds: state.sessionArchivePriorFailureIds,
18041
19533
  watermarkPath,
18042
19534
  signal,
19535
+ onMetadataDecodeError: (field, reason, sessionId) => logSessionArchiveMetadataDecodeFailure(state, phase, { field, reason, sessionId }),
18043
19536
  upload: uploadSessionArchive,
18044
19537
  exportMessages: exportSessionMessages,
18045
19538
  recordWatermark: recordUpload
18046
19539
  },
18047
19540
  budgetMs
18048
19541
  });
18049
- logSessionArchiveSummary(state, phase, summary);
19542
+ logSessionArchiveSummary(state, phase, summary, reconciliation);
18050
19543
  return summary;
18051
19544
  }
18052
19545
  async function runSessionArchiveFleet(state, phase, budgetMs, signal) {
19546
+ state.sessionArchivePassSequence++;
18053
19547
  const startedAt = Date.now();
18054
- const enumeration = await listAllSessions(state.port, state.opencodeClient ?? void 0, signal);
18055
- if (enumeration.sessions === null) {
18056
- const interrupted = signal.aborted;
18057
- logSessionArchiveActivity(state, phase, {
18058
- type: "info",
18059
- level: "warn",
18060
- message: interrupted ? "Session archive: enumeration was interrupted before the complete store was known; no session was marked archived" : `Session archive: could not enumerate the complete session store (${enumeration.reason}); no session was marked archived`,
18061
- metadata: {
18062
- outcome: interrupted ? "enumeration-interrupted" : "enumeration-refused",
18063
- ...!interrupted ? { reason: enumeration.reason } : {}
19548
+ const passDeadline = startedAt + budgetMs;
19549
+ const workDeadline = passDeadline - SESSION_ARCHIVE_MANIFEST_BUDGET_MS;
19550
+ const watermarksLoaded = state.sessionArchiveWatermarks.size;
19551
+ const workBudget = createBudgetSignal(signal, Math.max(0, workDeadline - Date.now()));
19552
+ let summary = null;
19553
+ let enumerationComplete = false;
19554
+ let enumerationReason = null;
19555
+ try {
19556
+ const enumeration = await listAllSessions(
19557
+ state.port,
19558
+ state.opencodeClient ?? void 0,
19559
+ workBudget.signal
19560
+ );
19561
+ if (enumeration.sessions === null) {
19562
+ enumerationComplete = false;
19563
+ enumerationReason = workBudget.signal.aborted ? "enumeration-interrupted" : enumeration.reason;
19564
+ const interrupted = workBudget.signal.aborted;
19565
+ logSessionArchiveActivity(state, phase, {
19566
+ type: "info",
19567
+ level: "warn",
19568
+ message: interrupted ? "Session archive: enumeration was interrupted before the complete store was known; no session was marked archived" : `Session archive: could not enumerate the complete session store (${enumerationReason}); no session was marked archived`,
19569
+ metadata: {
19570
+ outcome: interrupted ? "enumeration-interrupted" : "enumeration-refused",
19571
+ ...!interrupted ? { reason: enumerationReason } : {}
19572
+ }
19573
+ });
19574
+ } else {
19575
+ enumerationComplete = true;
19576
+ enumerationReason = null;
19577
+ const enumeratedIds = new Set(enumeration.sessions.map(({ id }) => id));
19578
+ for (const sessionId of state.sessionArchivePriorFailureIds) {
19579
+ if (!enumeratedIds.has(sessionId)) state.sessionArchivePriorFailureIds.delete(sessionId);
18064
19580
  }
18065
- });
18066
- return null;
19581
+ summary = await runSessionArchiveBatch(
19582
+ state,
19583
+ phase,
19584
+ enumeration.sessions,
19585
+ Math.max(0, workDeadline - Date.now()),
19586
+ workBudget.signal
19587
+ );
19588
+ }
19589
+ } finally {
19590
+ workBudget.dispose();
18067
19591
  }
18068
- return runSessionArchiveBatch(
18069
- state,
18070
- phase,
18071
- enumeration.sessions,
18072
- Math.max(0, budgetMs - (Date.now() - startedAt)),
18073
- signal
18074
- );
19592
+ const manifestWindowMs = Math.max(0, passDeadline - Date.now());
19593
+ const manifestBudget = createBudgetSignal(signal, manifestWindowMs);
19594
+ try {
19595
+ if (summary !== null || !enumerationComplete) {
19596
+ const identity = {
19597
+ runnerId: state.agentId,
19598
+ bootId: state.sessionArchiveBootId,
19599
+ passSequence: state.sessionArchivePassSequence,
19600
+ phase,
19601
+ startedAt: new Date(startedAt).toISOString(),
19602
+ completedAt: new Date(Date.now()).toISOString(),
19603
+ budgetMs,
19604
+ enumerationComplete,
19605
+ enumerationReason,
19606
+ watermarkFilePresent: state.sessionArchiveWatermarkFileLoaded,
19607
+ watermarksLoaded
19608
+ };
19609
+ await publishSessionArchiveAudit(
19610
+ state,
19611
+ phase,
19612
+ identity,
19613
+ summary,
19614
+ manifestWindowMs,
19615
+ manifestBudget.signal,
19616
+ signal
19617
+ );
19618
+ }
19619
+ } finally {
19620
+ manifestBudget.dispose();
19621
+ }
19622
+ return summary;
18075
19623
  }
18076
19624
  async function runSessionArchiveShutdownFlush(state, budgetMs) {
18077
19625
  const deadline = Date.now() + budgetMs;
@@ -18094,7 +19642,13 @@ async function runSessionArchiveShutdownFlush(state, budgetMs) {
18094
19642
  type: "info",
18095
19643
  level: "warn",
18096
19644
  message: `Session archive exceeded ${budgetMs}ms while stopping a prior run; remaining sessions were not confirmed archived`,
18097
- metadata: { outcome: "archive-budget-exceeded", budget_ms: budgetMs }
19645
+ metadata: {
19646
+ outcome: "archive-budget-exceeded",
19647
+ budget_ms: budgetMs,
19648
+ boot_id: state.sessionArchiveBootId,
19649
+ pass_sequence: state.sessionArchivePassSequence,
19650
+ manifest_written: false
19651
+ }
18098
19652
  });
18099
19653
  return null;
18100
19654
  }
@@ -18105,7 +19659,13 @@ async function runSessionArchiveShutdownFlush(state, budgetMs) {
18105
19659
  type: "info",
18106
19660
  level: "warn",
18107
19661
  message: `Session archive exceeded ${budgetMs}ms while stopping a prior run; remaining sessions were not confirmed archived`,
18108
- metadata: { outcome: "archive-budget-exceeded", budget_ms: budgetMs }
19662
+ metadata: {
19663
+ outcome: "archive-budget-exceeded",
19664
+ budget_ms: budgetMs,
19665
+ boot_id: state.sessionArchiveBootId,
19666
+ pass_sequence: state.sessionArchivePassSequence,
19667
+ manifest_written: false
19668
+ }
18109
19669
  });
18110
19670
  return null;
18111
19671
  }
@@ -18129,6 +19689,7 @@ function scheduleSessionArchive(state) {
18129
19689
  metadata: { outcome: "watermark-read-failed" }
18130
19690
  })
18131
19691
  );
19692
+ state.sessionArchiveWatermarkFileLoaded = state.sessionArchiveWatermarks.size > 0;
18132
19693
  logSessionArchiveActivity(state, "startup", {
18133
19694
  type: "info",
18134
19695
  message: `Session archive enabled (interval=${config.intervalMs}ms)`,
@@ -18638,9 +20199,13 @@ async function run(options) {
18638
20199
  ),
18639
20200
  sessionArchiveTimers: [],
18640
20201
  sessionArchiveWatermarks: /* @__PURE__ */ new Map(),
20202
+ sessionArchivePriorFailureIds: /* @__PURE__ */ new Set(),
18641
20203
  sessionArchiveWatermarkPath: null,
18642
20204
  sessionArchiveInFlight: null,
18643
20205
  sessionArchiveAbortController: null,
20206
+ sessionArchiveBootId: randomUUID2(),
20207
+ sessionArchivePassSequence: 0,
20208
+ sessionArchiveWatermarkFileLoaded: false,
18644
20209
  sessionDeleteFailures: /* @__PURE__ */ new Map(),
18645
20210
  claudeUsageTimer: null,
18646
20211
  claudeUsageRearm: null,
@@ -19101,7 +20666,7 @@ async function run(options) {
19101
20666
  port: state.port,
19102
20667
  interactive: state.interactive,
19103
20668
  agentId: state.agentId,
19104
- log: (message) => log2(state, message),
20669
+ log: (message, level = "info") => log2(state, message, level),
19105
20670
  startTimeoutMs: opencodeStartTimeoutMs,
19106
20671
  inheritStdio: Boolean(options.opencodePidFile),
19107
20672
  command: opencodeV2Command
@@ -19109,10 +20674,15 @@ async function run(options) {
19109
20674
  port: state.port,
19110
20675
  interactive: state.interactive,
19111
20676
  agentId: state.agentId,
19112
- log: (message) => log2(state, message),
20677
+ log: (message, level = "info") => log2(state, message, level),
19113
20678
  startTimeoutMs: opencodeStartTimeoutMs,
19114
20679
  inheritStdio: Boolean(options.opencodePidFile)
19115
20680
  });
20681
+ if (oc.reclaimOutcome) {
20682
+ const outcome = oc.reclaimOutcome;
20683
+ const message = outcome.kind === "freed" ? `Reclaimed OpenCode port ${outcome.port}: stopped holder PID(s) ${outcome.pids.join(", ")} with ${outcome.usedSigkill ? "SIGTERM and SIGKILL" : "SIGTERM"} and started a fresh OpenCode.` : `Reclaimed OpenCode port ${outcome.port}: the port freed itself before a holder could be signalled, and a fresh OpenCode was started.`;
20684
+ logActivity(state, { type: "info", level: "warn", message });
20685
+ }
19116
20686
  state.port = oc.port;
19117
20687
  state.opencodeProcess = options.opencodePidFile ? null : oc.process;
19118
20688
  state.opencodeVersion = oc.version;
@@ -19156,7 +20726,7 @@ async function run(options) {
19156
20726
  password: state.opencodePassword
19157
20727
  });
19158
20728
  state.opencodeClient = openCodeClient;
19159
- if (options.opencodePidFile && oc.process?.pid !== void 0) {
20729
+ if (options.opencodePidFile && oc.process?.pid !== void 0 && oc.process.exitCode === null && oc.process.signalCode === null) {
19160
20730
  try {
19161
20731
  writeFileSync9(options.opencodePidFile, `${oc.process.pid}
19162
20732
  `, { mode: 384 });
@@ -19167,6 +20737,12 @@ async function run(options) {
19167
20737
  error: `Failed to write OpenCode pid file ${options.opencodePidFile}: ${error2 instanceof Error ? error2.message : String(error2)}`
19168
20738
  });
19169
20739
  }
20740
+ } else if (options.opencodePidFile && oc.process?.pid !== void 0) {
20741
+ logActivity(state, {
20742
+ type: "info",
20743
+ level: "warn",
20744
+ message: `OpenCode pid file ${options.opencodePidFile} was left unchanged because the process spawned for this run had already exited.`
20745
+ });
19170
20746
  }
19171
20747
  if (state.opencodeVersion !== null) {
19172
20748
  const provenance = checkSessionDbProvenance({
@@ -19213,7 +20789,7 @@ async function run(options) {
19213
20789
  const version2 = state.opencodeVersion ? ` (v${state.opencodeVersion})` : "";
19214
20790
  ocSpinner?.succeed(`OpenCode running on port ${state.port}${version2}`);
19215
20791
  if (!state.interactive && oc.notReadyReason !== null) {
19216
- const message = `OpenCode is not ready on port ${state.port}: ${oc.notReadyReason}. The runner will still come online, but messages will fail until opencode answers \u2014 raise the wait with --opencode-start-timeout <seconds> (env ${OPENCODE_START_TIMEOUT_ENV}).`;
20792
+ const message = `OpenCode is not ready on port ${state.port}: ${oc.notReadyReason}. The runner will still come online, but messages will fail until opencode answers.`;
19217
20793
  logActivity(state, { type: "info", level: "warn", message });
19218
20794
  } else {
19219
20795
  const versionWarning = buildOpenCodeVersionWarning(
@@ -19623,24 +21199,95 @@ async function run(options) {
19623
21199
  }
19624
21200
  }
19625
21201
 
21202
+ // src/commands/teams.ts
21203
+ function printTeam(team, selected) {
21204
+ console.log(`${selected ? "* " : " "}${team.id} ${team.name}`);
21205
+ }
21206
+ function isTeam(value) {
21207
+ return typeof value === "object" && value !== null && typeof value.id === "string" && typeof value.name === "string";
21208
+ }
21209
+ async function teams() {
21210
+ const apiUrl = getApiUrlConfig();
21211
+ let credentials2;
21212
+ try {
21213
+ credentials2 = await getAuthCredentials();
21214
+ } catch (error2) {
21215
+ printError(
21216
+ `Could not read the saved Evident credentials: ${error2 instanceof Error ? error2.message : String(error2)}`
21217
+ );
21218
+ process.exitCode = 1;
21219
+ return;
21220
+ }
21221
+ if (!credentials2) {
21222
+ printError(`Not logged in to ${apiUrl}. Run the \`login\` command to authenticate.`);
21223
+ process.exitCode = 1;
21224
+ return;
21225
+ }
21226
+ try {
21227
+ const response = await fetch(`${apiUrl}/teams`, {
21228
+ headers: buildAuthHeaders(credentials2)
21229
+ });
21230
+ if (!response.ok) {
21231
+ const serverMessage = await readErrorMessage(response);
21232
+ throw new Error(
21233
+ `Evident returned HTTP ${response.status} while listing teams${serverMessage ? `: ${serverMessage}` : ""}`
21234
+ );
21235
+ }
21236
+ const data = await response.json();
21237
+ if (!Array.isArray(data) || !data.every(isTeam)) {
21238
+ throw new Error("Evident returned an invalid team list. Update the CLI and retry.");
21239
+ }
21240
+ const selectedTeam = getTeamSelection();
21241
+ blank();
21242
+ if (data.length === 0) {
21243
+ console.log("No teams found for this account.");
21244
+ blank();
21245
+ return;
21246
+ }
21247
+ for (const team of data) {
21248
+ printTeam(team, team.id === selectedTeam);
21249
+ }
21250
+ if (data.length === 1) {
21251
+ console.log("This is your only team; commands act in it automatically.");
21252
+ } else if (!selectedTeam) {
21253
+ console.log("Choose a team with --team <id> or set EVIDENT_TEAM.");
21254
+ }
21255
+ blank();
21256
+ } catch (error2) {
21257
+ printError(`Could not list teams: ${error2 instanceof Error ? error2.message : String(error2)}`);
21258
+ process.exitCode = 1;
21259
+ }
21260
+ }
21261
+
19626
21262
  // src/index.ts
19627
21263
  var version = getCliVersion();
19628
21264
  var program = new Command();
19629
21265
  program.name("evident").description("Run OpenCode locally and connect it to Evident").version(version).option(
19630
21266
  "--endpoint <url>",
19631
21267
  "Evident API base URL (default: production; e.g. http://localhost:3001)"
19632
- ).option("--tunnel <url>", "Tunnel WebSocket URL (default: production; e.g. ws://localhost:8787)").hook("preAction", (thisCommand) => {
19633
- const { endpoint: endpoint2, tunnel } = thisCommand.opts();
21268
+ ).option("--tunnel <url>", "Tunnel WebSocket URL (default: production; e.g. ws://localhost:8787)").option(
21269
+ "--team <id>",
21270
+ "Evident team ID to act in (Env: EVIDENT_TEAM). Use it when your account belongs to more than one team; list them with evident teams"
21271
+ ).hook("preAction", (thisCommand) => {
21272
+ const { endpoint: endpoint2, tunnel, team } = thisCommand.optsWithGlobals();
19634
21273
  if (endpoint2) {
19635
21274
  setEndpoint(endpoint2);
19636
21275
  }
19637
21276
  if (tunnel) {
19638
21277
  setTunnelUrl(tunnel);
19639
21278
  }
21279
+ setTeamSelection(team);
19640
21280
  });
19641
21281
  program.command("login").description("Authenticate with Evident").option("--token", "Use token-based authentication (for CI/CD)").option("--no-browser", "Do not open the browser automatically").action(login);
19642
21282
  program.command("logout").description("Remove stored credentials for the current endpoint").option("--all", "Remove stored credentials for all endpoints").action((options) => logout({ all: options.all }));
19643
21283
  program.command("whoami").description("Show the currently logged in user").action(whoami);
21284
+ program.command("teams").description("List the teams you belong to").action(teams);
21285
+ program.command("mcp").description("Manage MCP proxy connections").command("authorize").description("Authorize an MCP proxy connection using your local browser").argument("<proxy-id>", "MCP proxy ID").argument("<connection-id>", "MCP connection ID").option("--no-browser", "Do not open the browser automatically").option("--json", "Output the result as JSON").action(
21286
+ (proxyId, connectionId, options) => authorizeMcpConnection(proxyId, connectionId, {
21287
+ noBrowser: options.browser === false,
21288
+ json: options.json
21289
+ })
21290
+ );
19644
21291
  program.command("status").description("Check whether the configured credentials can reach Evident").option("--json", "Output in JSON format").action((options) => status({ json: options.json }));
19645
21292
  program.command("credential-vault-env").description("Print the shell assignment a runner image evals before starting the synchroniser").action(credentialVaultEnv);
19646
21293
  program.command("claude-usage").description("[spike] Show Claude subscription usage (requires a local `claude login`)").action(claudeUsage);