@evident-ai/cli 3.6.1-dev.57b3e59 → 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;
@@ -1180,6 +1219,7 @@ async function claudeUsage() {
1180
1219
 
1181
1220
  // src/commands/mcp-authorize.ts
1182
1221
  import { createServer } from "node:http";
1222
+ import { randomBytes } from "node:crypto";
1183
1223
  import open2 from "open";
1184
1224
 
1185
1225
  // ../../packages/types/src/agents/index.ts
@@ -1485,12 +1525,14 @@ function stripQuery(url) {
1485
1525
 
1486
1526
  // src/commands/mcp-authorize.ts
1487
1527
  var API_TIMEOUT_MS = 1e4;
1488
- var CALLBACK_OK_HTML = '<!doctype html><html><head><meta charset="utf-8"><title>Sign-in received</title></head><body><p>Sign-in response received. You can close this window.</p></body></html>';
1489
- var CALLBACK_REJECTED_HTML = '<!doctype html><html><head><meta charset="utf-8"><title>Invalid response</title></head><body><p>This sign-in response was not accepted.</p></body></html>';
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"]);
1490
1531
  var ApiHttpError = class extends Error {
1491
- constructor(status2) {
1492
- super(`Evident API returned HTTP ${status2}`);
1532
+ constructor(status2, operation) {
1533
+ super(`Evident API returned HTTP ${status2} while ${operation}`);
1493
1534
  this.status = status2;
1535
+ this.operation = operation;
1494
1536
  }
1495
1537
  };
1496
1538
  var CallbackExpiredError = class extends Error {
@@ -1521,7 +1563,7 @@ async function requestJson(path, credentials2, cancelSignal, operation, body) {
1521
1563
  response = await fetch(`${getApiUrlConfig()}${path}`, {
1522
1564
  method,
1523
1565
  headers: {
1524
- Authorization: getAuthHeader(credentials2),
1566
+ ...buildAuthHeaders(credentials2),
1525
1567
  ...body === void 0 ? {} : { "Content-Type": "application/json" }
1526
1568
  },
1527
1569
  body: body === void 0 ? void 0 : JSON.stringify(body),
@@ -1537,7 +1579,7 @@ async function requestJson(path, credentials2, cancelSignal, operation, body) {
1537
1579
  `Could not reach Evident while ${operation}: ${detail}. Check --endpoint or EVIDENT_API_URL and retry.`
1538
1580
  );
1539
1581
  }
1540
- if (!response.ok) throw new ApiHttpError(response.status);
1582
+ if (!response.ok) throw new ApiHttpError(response.status, operation);
1541
1583
  try {
1542
1584
  return await response.json();
1543
1585
  } catch (error2) {
@@ -1553,76 +1595,400 @@ async function requestJson(path, credentials2, cancelSignal, operation, body) {
1553
1595
  cancelSignal.removeEventListener("abort", onCancel);
1554
1596
  }
1555
1597
  }
1556
- function callbackResponse(response, status2, html) {
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) {
1557
1783
  response.writeHead(status2, {
1558
1784
  "Content-Type": "text/html; charset=utf-8",
1559
1785
  "Cache-Control": "no-store",
1560
- "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'",
1561
- "X-Content-Type-Options": "nosniff"
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
+ }
1562
1845
  });
1563
- response.end(html);
1846
+ return true;
1847
+ }
1848
+ function rejectedCallbackResponse(response, status2) {
1849
+ const page = callbackPage();
1850
+ callbackResponse(response, status2, page.html, page.nonce);
1564
1851
  }
1565
1852
  function parseCallbackRequest(request3) {
1566
1853
  if (request3.method !== "GET" || !request3.url || !request3.url.startsWith("/") || request3.url.length > 16384) {
1567
- return void 0;
1854
+ return { reason: "malformed_response" };
1568
1855
  }
1569
1856
  if (request3.headers["transfer-encoding"] || Number(request3.headers["content-length"] ?? 0) > 0) {
1570
- return void 0;
1857
+ return { reason: "malformed_response" };
1571
1858
  }
1572
1859
  const callbackBase = `http://${MCP_LOOPBACK_REDIRECT_POLICY.host}`;
1573
- if (!URL.canParse(request3.url, callbackBase)) return void 0;
1860
+ if (!URL.canParse(request3.url, callbackBase)) return { reason: "malformed_response" };
1574
1861
  const url = new URL(request3.url, callbackBase);
1575
- if (url.pathname !== MCP_LOOPBACK_REDIRECT_POLICY.path || url.hash) return void 0;
1576
- const allowedParams = /* @__PURE__ */ new Set(["state", "code", "error", "error_description"]);
1577
- for (const [key] of url.searchParams) {
1578
- if (!allowedParams.has(key) || url.searchParams.getAll(key).length !== 1) return void 0;
1579
- }
1580
- const state = url.searchParams.get("state");
1581
- const code = url.searchParams.get("code");
1582
- const error2 = url.searchParams.get("error");
1583
- const errorDescription = url.searchParams.get("error_description");
1584
- 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)) {
1585
- return void 0;
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" };
1586
1893
  }
1587
1894
  return {
1588
- state,
1589
- ...code === null ? {} : { code },
1590
- ...error2 === null ? {} : { error: error2 },
1591
- ...errorDescription === null ? {} : { error_description: errorDescription }
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
+ }
1592
1902
  };
1593
1903
  }
1594
- function handleCallbackRequest(request3, response, waiter) {
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;
1595
1938
  if (!request3.url || !request3.url.startsWith("/") || !URL.canParse(request3.url, `http://${MCP_LOOPBACK_REDIRECT_POLICY.host}`)) {
1596
- callbackResponse(response, 400, CALLBACK_REJECTED_HTML);
1939
+ rejectCallback(response, options, "malformed_response");
1597
1940
  return;
1598
1941
  }
1599
1942
  const pathname = new URL(request3.url, `http://${MCP_LOOPBACK_REDIRECT_POLICY.host}`).pathname;
1600
1943
  if (pathname !== MCP_LOOPBACK_REDIRECT_POLICY.path) {
1601
- callbackResponse(response, 404, CALLBACK_REJECTED_HTML);
1944
+ rejectedCallbackResponse(response, 404);
1602
1945
  return;
1603
1946
  }
1604
1947
  if (request3.method !== "GET") {
1605
1948
  response.setHeader("Allow", "GET");
1606
- callbackResponse(response, 405, CALLBACK_REJECTED_HTML);
1949
+ rejectedCallbackResponse(response, 405);
1607
1950
  return;
1608
1951
  }
1609
1952
  if (waiter.accepted) {
1610
- callbackResponse(response, 409, CALLBACK_REJECTED_HTML);
1953
+ rejectedCallbackResponse(response, 409);
1954
+ return;
1955
+ }
1956
+ const parsed = parseCallbackRequest(request3);
1957
+ if (!("callback" in parsed)) {
1958
+ rejectCallback(response, options, parsed.reason);
1611
1959
  return;
1612
1960
  }
1613
- const callback = parseCallbackRequest(request3);
1614
- if (!callback || !waiter.expectedState || !waiter.expiresAtMs || Date.now() >= waiter.expiresAtMs || callback.state !== waiter.expectedState) {
1615
- callbackResponse(response, 400, CALLBACK_REJECTED_HTML);
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);
1616
1979
  return;
1617
1980
  }
1618
1981
  waiter.accepted = true;
1619
- response.writeHead(200, {
1620
- "Content-Type": "text/html; charset=utf-8",
1621
- "Cache-Control": "no-store",
1622
- "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'",
1623
- "X-Content-Type-Options": "nosniff"
1624
- });
1625
- response.end(CALLBACK_OK_HTML, () => waiter.resolve?.(callback));
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
+ );
1626
1992
  }
1627
1993
  function listen(server, port) {
1628
1994
  return new Promise((resolve6, reject) => {
@@ -1642,8 +2008,10 @@ function listen(server, port) {
1642
2008
  function isAddressInUse(error2) {
1643
2009
  return typeof error2 === "object" && error2 !== null && "code" in error2 && error2.code === "EADDRINUSE";
1644
2010
  }
1645
- async function bindCallbackListener(waiter) {
1646
- const createListener = () => createServer((request3, response) => handleCallbackRequest(request3, response, waiter));
2011
+ async function bindCallbackListener(waiter, options, page) {
2012
+ const createListener = () => createServer(
2013
+ (request3, response) => handleCallbackRequest(request3, response, waiter, options, page)
2014
+ );
1647
2015
  try {
1648
2016
  const server2 = createListener();
1649
2017
  return { server: server2, port: await listen(server2, MCP_LOOPBACK_REDIRECT_POLICY.preferred_port) };
@@ -1709,22 +2077,23 @@ function authorizationState(authorizationUrl) {
1709
2077
  return { url, state: states[0] };
1710
2078
  }
1711
2079
  function apiFailureMessage(error2) {
2080
+ const context = `Evident returned HTTP ${error2.status} while ${error2.operation}.`;
1712
2081
  switch (error2.status) {
1713
2082
  case 400:
1714
- return "Evident rejected the local sign-in response. Retry the command; if it continues, update the CLI and try again.";
2083
+ return `${context} Retry the command; if it continues, update the CLI and try again.`;
1715
2084
  case 401:
1716
- return "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.";
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.`;
1717
2086
  case 403:
1718
- return "Only workspace owners and admins can authorize MCP connections. Ask a workspace admin for access.";
2087
+ return `${context} Only workspace owners and admins can authorize MCP connections. Ask a workspace admin for access.`;
1719
2088
  case 404:
1720
- return "The MCP proxy or connection was not found. Check both IDs and try again.";
2089
+ return `${context} Confirm the proxy and connection IDs and that this CLI user can access the proxy.`;
1721
2090
  case 409:
1722
- return "This connection does not support local sign-in. Use its hosted authorization flow in Evident.";
2091
+ return `${context} This connection does not support local sign-in. Use its hosted authorization flow in Evident.`;
1723
2092
  case 502:
1724
2093
  case 503:
1725
- return "The Evident MCP authorization service is unavailable. Retry shortly or contact your workspace admin.";
2094
+ return `${context} The Evident MCP authorization service is unavailable. Retry shortly or contact your workspace admin.`;
1726
2095
  default:
1727
- return `Evident rejected the request with HTTP ${error2.status}. Check your endpoint and retry.`;
2096
+ return `${context} Check your endpoint and retry.`;
1728
2097
  }
1729
2098
  }
1730
2099
  function completionFailureMessage(reason) {
@@ -1735,6 +2104,14 @@ function completionFailureMessage(reason) {
1735
2104
  return "This sign-in was already used. Start a new authorization.";
1736
2105
  case "state_expired":
1737
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.";
1738
2115
  case "provider_denied":
1739
2116
  return "The provider denied the sign-in. Retry and approve the requested access.";
1740
2117
  case "provider_error":
@@ -1758,20 +2135,21 @@ function printLink(options, url, reason) {
1758
2135
  printWarning(reason ?? "Open this authorization URL in your browser:");
1759
2136
  console.log(url.href);
1760
2137
  }
1761
- function printResult(options, proxyId, connectionId, error2) {
2138
+ function printResult(options, proxyId, connectionId, error2, successMessage = "MCP connection authorized.", reason) {
1762
2139
  if (options.json) {
1763
2140
  console.log(
1764
2141
  JSON.stringify({
1765
2142
  ok: !error2,
1766
2143
  proxy_id: proxyId,
1767
2144
  connection_id: connectionId,
1768
- ...error2 ? { error: error2 } : {}
2145
+ ...error2 ? { error: error2 } : {},
2146
+ ...reason ? { reason } : {}
1769
2147
  })
1770
2148
  );
1771
2149
  } else if (error2) {
1772
2150
  printError(error2);
1773
2151
  } else {
1774
- printSuccess("MCP connection authorized.");
2152
+ printSuccess(successMessage);
1775
2153
  }
1776
2154
  }
1777
2155
  function errorMessage(error2) {
@@ -1794,12 +2172,32 @@ function validateConnectionList(value) {
1794
2172
  return value.mcp_proxy_connections;
1795
2173
  }
1796
2174
  function validateBeginResponse(value) {
1797
- if (!value || typeof value.authorization_url !== "string" || typeof value.expires_at !== "string" || !Number.isFinite(Date.parse(value.expires_at))) {
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)) {
1798
2176
  throw new Error(
1799
2177
  "Evident returned an invalid local authorization attempt. Update the CLI and retry."
1800
2178
  );
1801
2179
  }
1802
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
+ }
1803
2201
  function closeServer(server, force) {
1804
2202
  if (!server.listening) return Promise.resolve();
1805
2203
  return new Promise((resolve6, reject) => {
@@ -1843,10 +2241,17 @@ async function authorizeMcpConnection(proxyId, connectionId, options = {}) {
1843
2241
  return;
1844
2242
  }
1845
2243
  const waiter = { accepted: false };
2244
+ const page = {
2245
+ capability: randomBytes(32).toString("base64url"),
2246
+ phase: "waiting",
2247
+ terminalRead: false
2248
+ };
1846
2249
  let server;
1847
2250
  let closePromise;
1848
2251
  let closeFailureLogged = false;
1849
2252
  let failure;
2253
+ let successMessage = "MCP connection authorized.";
2254
+ let completionReason;
1850
2255
  const cancelController = new AbortController();
1851
2256
  const closeListener = (force = false) => {
1852
2257
  if (!server || closePromise) return closePromise ?? Promise.resolve();
@@ -1863,15 +2268,23 @@ async function authorizeMcpConnection(proxyId, connectionId, options = {}) {
1863
2268
  });
1864
2269
  };
1865
2270
  try {
1866
- const listener = await bindCallbackListener(waiter);
2271
+ const listener = await bindCallbackListener(waiter, options, page);
1867
2272
  server = listener.server;
1868
2273
  process.once("SIGINT", onSigint);
1869
- if (listener.port !== MCP_LOOPBACK_REDIRECT_POLICY.preferred_port) {
1870
- const notice = `Port ${MCP_LOOPBACK_REDIRECT_POLICY.preferred_port} is busy; using an ephemeral local port.`;
1871
- if (options.json)
1872
- console.error(JSON.stringify({ event: "listener_fallback", message: notice }));
1873
- else printWarning(notice);
1874
- }
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
+ );
1875
2288
  const connectionList = await requestJson(
1876
2289
  apiPath(proxyId),
1877
2290
  credentials2,
@@ -1889,7 +2302,7 @@ async function authorizeMcpConnection(proxyId, connectionId, options = {}) {
1889
2302
  if (connection.auth_kind !== "oauth2") {
1890
2303
  throw new Error("This MCP connection does not support OAuth authorization.");
1891
2304
  }
1892
- const redirectUri = `${MCP_LOOPBACK_REDIRECT_POLICY.scheme}://${MCP_LOOPBACK_REDIRECT_POLICY.host}:${listener.port}${MCP_LOOPBACK_REDIRECT_POLICY.path}`;
2305
+ reportProgress(options, "authorization_starting", "Starting authorization with Evident.");
1893
2306
  const begin = await requestJson(
1894
2307
  apiPath(proxyId, connectionId, "begin"),
1895
2308
  credentials2,
@@ -1900,6 +2313,8 @@ async function authorizeMcpConnection(proxyId, connectionId, options = {}) {
1900
2313
  validateBeginResponse(begin);
1901
2314
  const { url: authorizationUrl, state } = authorizationState(begin.authorization_url);
1902
2315
  waiter.expectedState = state;
2316
+ waiter.expectedIssuer = begin.issuer;
2317
+ waiter.issuerParameterSupported = begin.authorization_response_iss_parameter_supported;
1903
2318
  const expiresAtMs = Date.parse(begin.expires_at);
1904
2319
  if (expiresAtMs <= Date.now()) throw new CallbackExpiredError();
1905
2320
  waiter.expiresAtMs = expiresAtMs;
@@ -1907,16 +2322,31 @@ async function authorizeMcpConnection(proxyId, connectionId, options = {}) {
1907
2322
  (callback2) => ({ ok: true, callback: callback2 }),
1908
2323
  (error2) => ({ ok: false, error: error2 })
1909
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
+ };
1910
2338
  let callback;
1911
2339
  if (options.noBrowser) {
1912
- printLink(options, authorizationUrl);
1913
- const outcome = await callbackOutcome;
1914
- if (!outcome.ok) requestFailed(outcome.error);
1915
- callback = outcome.callback;
2340
+ callback = await waitForCallbackWithProgress("Open this authorization URL in your browser:");
1916
2341
  } else {
1917
- const browserOutcome = open2(authorizationUrl.href).then(
1918
- () => ({ ok: true }),
1919
- (error2) => ({ ok: false, error: error2 })
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 })
1920
2350
  );
1921
2351
  const first = await Promise.race([
1922
2352
  browserOutcome.then((outcome) => ({ kind: "browser", outcome })),
@@ -1927,24 +2357,43 @@ async function authorizeMcpConnection(proxyId, connectionId, options = {}) {
1927
2357
  callback = first.outcome.callback;
1928
2358
  } else {
1929
2359
  if (!first.outcome.ok) {
1930
- const detail = first.outcome.error instanceof Error ? ` (${first.outcome.error.message})` : "";
1931
- printLink(
1932
- options,
1933
- authorizationUrl,
1934
- `Could not open the browser automatically${detail}. Open this URL:`
2360
+ callback = await waitForCallbackWithProgress(
2361
+ "Could not open the browser automatically. Open this URL:"
1935
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
+ }
1936
2384
  }
1937
- const outcome = await callbackOutcome;
1938
- if (!outcome.ok) requestFailed(outcome.error);
1939
- callback = outcome.callback;
1940
2385
  }
1941
2386
  }
2387
+ reportProgress(options, "forwarding_callback", "Forwarding the sign-in response to Evident.");
1942
2388
  const completionBody = {
1943
2389
  state: callback.state,
1944
2390
  ...callback.code === void 0 ? {} : { code: callback.code },
1945
2391
  ...callback.error === void 0 ? {} : { error: callback.error },
1946
- ...callback.error_description === void 0 ? {} : { error_description: callback.error_description }
2392
+ ...callback.error_description === void 0 ? {} : { error_description: callback.error_description },
2393
+ ...callback.iss === void 0 ? {} : { iss: callback.iss }
1947
2394
  };
2395
+ reportProgress(options, "completing_authorization", "Completing authorization with Evident.");
2396
+ page.phase = "completing";
1948
2397
  const completion = await requestJson(
1949
2398
  apiPath(proxyId, connectionId, "complete"),
1950
2399
  credentials2,
@@ -1952,12 +2401,36 @@ async function authorizeMcpConnection(proxyId, connectionId, options = {}) {
1952
2401
  "completing local authorization",
1953
2402
  completionBody
1954
2403
  );
1955
- if (completion.outcome !== "success") failure = completionFailureMessage(completion.reason);
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
+ }
1956
2421
  } catch (error2) {
1957
- failure = errorMessage(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
+ }
1958
2428
  } finally {
1959
- process.removeListener("SIGINT", onSigint);
1960
2429
  try {
2430
+ if (waiter.accepted && isTerminalPagePhase(page.phase) && !cancelController.signal.aborted) {
2431
+ await waitForTerminalStatusRead(page, cancelController.signal);
2432
+ }
2433
+ process.removeListener("SIGINT", onSigint);
1961
2434
  await closeListener();
1962
2435
  } catch (error2) {
1963
2436
  const detail = error2 instanceof Error ? error2.message : String(error2);
@@ -1969,11 +2442,12 @@ async function authorizeMcpConnection(proxyId, connectionId, options = {}) {
1969
2442
  failure ??= "The local callback listener could not be closed cleanly. Check for a lingering process and retry.";
1970
2443
  }
1971
2444
  }
1972
- printResult(options, proxyId, connectionId, failure);
2445
+ printResult(options, proxyId, connectionId, failure, successMessage, completionReason);
1973
2446
  if (failure) process.exitCode = cancelController.signal.aborted ? 130 : 1;
1974
2447
  }
1975
2448
 
1976
2449
  // src/commands/run.ts
2450
+ import { randomUUID as randomUUID2 } from "node:crypto";
1977
2451
  import { chmodSync as chmodSync3, existsSync as existsSync3, readFileSync as readFileSync12, writeFileSync as writeFileSync9 } from "node:fs";
1978
2452
  import { homedir as homedir9 } from "node:os";
1979
2453
  import { isAbsolute as isAbsolute6, join as join17, parse, resolve as resolvePath2 } from "node:path";
@@ -1981,8 +2455,11 @@ import chalk7 from "chalk";
1981
2455
  import ora4 from "ora";
1982
2456
  import { select as select4 } from "@inquirer/prompts";
1983
2457
 
2458
+ // src/lib/opencode-start-timeout.ts
2459
+ var OPENCODE_START_TIMEOUT_ENV = "EVIDENT_OPENCODE_START_TIMEOUT";
2460
+
1984
2461
  // src/lib/telemetry.ts
1985
- var CLI_VERSION = (true ? "3.6.1-dev.57b3e59" : 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";
1986
2463
  function getCliVersion() {
1987
2464
  return CLI_VERSION;
1988
2465
  }
@@ -3825,7 +4302,7 @@ function isRecord3(value) {
3825
4302
  }
3826
4303
  function isWatermark(value) {
3827
4304
  if (!isRecord3(value)) return false;
3828
- 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");
3829
4306
  }
3830
4307
  function isMissingFile3(error2) {
3831
4308
  return error2 instanceof Error && "code" in error2 && error2.code === "ENOENT";
@@ -4006,6 +4483,37 @@ function isJson(body) {
4006
4483
  return false;
4007
4484
  }
4008
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
+ }
4009
4517
  async function uploadSessionArchive(key, body, options) {
4010
4518
  const bytes = Buffer.from(body);
4011
4519
  if (bytes.byteLength > MAX_SESSION_ARCHIVE_BYTES) {
@@ -4028,7 +4536,13 @@ async function uploadSessionArchive(key, body, options) {
4028
4536
  );
4029
4537
  }
4030
4538
  if (result.timedOut) return transportFailure(bytes.byteLength, "timeout");
4031
- 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
+ }
4032
4546
  if (result.code === EXIT_ARCHIVE_CONFIG_MISSING) {
4033
4547
  return { kind: "config-missing", bytes: bytes.byteLength };
4034
4548
  }
@@ -4246,6 +4760,14 @@ async function runSessionArchive({
4246
4760
  uploadFailures: 0,
4247
4761
  skippedBudget: 0,
4248
4762
  skippedBudgetIds: [],
4763
+ skippedChanged: 0,
4764
+ skippedChangedSessions: [],
4765
+ skippedUnknown: 0,
4766
+ skippedUnknownIds: [],
4767
+ inventoryNeverArchived: 0,
4768
+ inventoryPriorFailures: 0,
4769
+ inventoryKnownChanged: 0,
4770
+ outcomesReconciled: false,
4249
4771
  neverWatermarkedFailures: 0,
4250
4772
  unmappedIds: [],
4251
4773
  conflictedIds: [],
@@ -4262,6 +4784,8 @@ async function runSessionArchive({
4262
4784
  parent: 0
4263
4785
  },
4264
4786
  archivedSessionIds: [],
4787
+ uploadedSessions: [],
4788
+ unchangedSessions: [],
4265
4789
  failures: [],
4266
4790
  staleSince: null
4267
4791
  };
@@ -4285,17 +4809,44 @@ async function runSessionArchive({
4285
4809
  }
4286
4810
  summary.unresolved = summary.unmappedIds.length + summary.conflictedIds.length;
4287
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;
4288
4824
  const failedWatermarks = [];
4825
+ const priorFailureUploads = [];
4289
4826
  const recordFailedWatermark = (watermark) => {
4290
4827
  if (watermark) failedWatermarks.push(watermark.uploaded_at);
4291
4828
  else summary.neverWatermarkedFailures++;
4292
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
+ };
4293
4845
  for (let index = 0; index < ordered.length; index++) {
4294
4846
  const session = ordered[index];
4295
4847
  const remainingMs = Math.floor(deadline - now());
4296
4848
  if (remainingMs <= 0 || deps.signal?.aborted) {
4297
- summary.skippedBudgetIds.push(...ordered.slice(index).map(({ id }) => id));
4298
- summary.skippedBudget = summary.skippedBudgetIds.length;
4849
+ recordBudgetSkip(index);
4299
4850
  break;
4300
4851
  }
4301
4852
  const resolution = resolutions.get(session.id) ?? { reason: "unmapped" };
@@ -4320,8 +4871,7 @@ async function runSessionArchive({
4320
4871
  messages = await exportMessages(deps.client, session.id, exportBudget.signal);
4321
4872
  } catch (error2) {
4322
4873
  if (isBudgetExpired(deadline, now, deps.signal) || exportBudget.signal.aborted) {
4323
- summary.skippedBudgetIds.push(...ordered.slice(index).map(({ id }) => id));
4324
- summary.skippedBudget = summary.skippedBudgetIds.length;
4874
+ recordBudgetSkip(index);
4325
4875
  break;
4326
4876
  }
4327
4877
  summary.failed++;
@@ -4339,8 +4889,7 @@ async function runSessionArchive({
4339
4889
  exportBudget.dispose();
4340
4890
  }
4341
4891
  if (isBudgetExpired(deadline, now, deps.signal) || exportBudget.signal.aborted) {
4342
- summary.skippedBudgetIds.push(...ordered.slice(index).map(({ id }) => id));
4343
- summary.skippedBudget = summary.skippedBudgetIds.length;
4892
+ recordBudgetSkip(index);
4344
4893
  break;
4345
4894
  }
4346
4895
  try {
@@ -4359,12 +4908,21 @@ async function runSessionArchive({
4359
4908
  if (existing?.fingerprint === snapshot.content_fingerprint) {
4360
4909
  summary.unchanged++;
4361
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
+ });
4362
4920
  continue;
4363
4921
  }
4364
4922
  const uploadRemainingMs = Math.floor(deadline - now());
4365
4923
  if (uploadRemainingMs <= 0 || deps.signal?.aborted) {
4366
- summary.skippedBudgetIds.push(...ordered.slice(index).map(({ id }) => id));
4367
- summary.skippedBudget = summary.skippedBudgetIds.length;
4924
+ knownChanged.set(session.id, "fingerprint-differs");
4925
+ recordBudgetSkip(index);
4368
4926
  break;
4369
4927
  }
4370
4928
  summary.uploadAttempts++;
@@ -4373,7 +4931,8 @@ async function runSessionArchive({
4373
4931
  try {
4374
4932
  outcome = await upload(key, JSON.stringify(snapshot), {
4375
4933
  timeoutMs: Math.min(uploadRemainingMs, SESSION_ARCHIVE_UPLOAD_TIMEOUT_MS),
4376
- signal: uploadBudget.signal
4934
+ signal: uploadBudget.signal,
4935
+ onMetadataDecodeError: (field, reason) => deps.onMetadataDecodeError?.(field, reason, session.id)
4377
4936
  });
4378
4937
  } finally {
4379
4938
  uploadBudget.dispose();
@@ -4396,19 +4955,31 @@ async function runSessionArchive({
4396
4955
  });
4397
4956
  recordFailedWatermark(existing);
4398
4957
  if (uploadBudget.signal.aborted) {
4399
- summary.skippedBudgetIds.push(...ordered.slice(index + 1).map(({ id }) => id));
4400
- summary.skippedBudget = summary.skippedBudgetIds.length;
4958
+ recordBudgetSkip(index + 1);
4401
4959
  break;
4402
4960
  }
4403
4961
  continue;
4404
4962
  }
4405
4963
  summary.uploaded++;
4406
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);
4407
4976
  const watermark = {
4408
4977
  fingerprint: snapshot.content_fingerprint,
4409
4978
  uploaded_at: new Date(now()).toISOString(),
4410
4979
  key,
4411
- conversation_id: conversationId
4980
+ conversation_id: conversationId,
4981
+ version_id: outcome.versionId,
4982
+ etag: outcome.etag
4412
4983
  };
4413
4984
  try {
4414
4985
  writeWatermark(deps.watermarkPath, session.id, watermark, deps.watermarks);
@@ -4422,8 +4993,7 @@ async function runSessionArchive({
4422
4993
  }
4423
4994
  } catch (error2) {
4424
4995
  if (isBudgetExpired(deadline, now, deps.signal)) {
4425
- summary.skippedBudgetIds.push(...ordered.slice(index).map(({ id }) => id));
4426
- summary.skippedBudget = summary.skippedBudgetIds.length;
4996
+ recordBudgetSkip(index);
4427
4997
  break;
4428
4998
  }
4429
4999
  summary.failed++;
@@ -4436,10 +5006,115 @@ async function runSessionArchive({
4436
5006
  recordFailedWatermark(deps.watermarks.get(session.id));
4437
5007
  }
4438
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;
4439
5015
  summary.staleSince = failedWatermarks.sort()[0] ?? null;
4440
5016
  return summary;
4441
5017
  }
4442
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
+
4443
5118
  // src/lib/opencode/auth.ts
4444
5119
  function buildOpenCodeBasicAuthHeader(password) {
4445
5120
  return `Basic ${Buffer.from(["opencode", password].join(":")).toString("base64")}`;
@@ -4546,9 +5221,11 @@ async function checkOpenCode2Health(port, password) {
4546
5221
  return { healthy: false, error: message };
4547
5222
  }
4548
5223
  }
4549
- async function waitForOpenCodeHealth(port, timeoutMs = 3e4) {
5224
+ async function waitForOpenCodeHealth(port, timeoutMs = 3e4, stopEarly) {
4550
5225
  const startTime = Date.now();
4551
5226
  while (Date.now() - startTime < timeoutMs) {
5227
+ const earlyStopReason = stopEarly?.();
5228
+ if (earlyStopReason) return { healthy: false, error: earlyStopReason };
4552
5229
  const health = await checkOpenCodeHealth(port);
4553
5230
  if (health.healthy || health.authFailed) {
4554
5231
  return health;
@@ -4557,9 +5234,11 @@ async function waitForOpenCodeHealth(port, timeoutMs = 3e4) {
4557
5234
  }
4558
5235
  return { healthy: false, error: "Timeout waiting for OpenCode to be healthy" };
4559
5236
  }
4560
- async function waitForOpenCode2Health(port, password, timeoutMs = 3e4) {
5237
+ async function waitForOpenCode2Health(port, password, timeoutMs = 3e4, stopEarly) {
4561
5238
  const startTime = Date.now();
4562
5239
  while (Date.now() - startTime < timeoutMs) {
5240
+ const earlyStopReason = stopEarly?.();
5241
+ if (earlyStopReason) return { healthy: false, error: earlyStopReason };
4563
5242
  const health = await checkOpenCode2Health(port, password);
4564
5243
  if (health.healthy || health.authFailed) {
4565
5244
  return health;
@@ -7628,7 +8307,7 @@ function reportedOpenCodeVersion(input) {
7628
8307
 
7629
8308
  // src/lib/opencode/process.ts
7630
8309
  import { execSync, spawn as spawn3 } from "child_process";
7631
- import { randomBytes } from "node:crypto";
8310
+ import { randomBytes as randomBytes2 } from "node:crypto";
7632
8311
 
7633
8312
  // src/lib/process-stop.ts
7634
8313
  async function stopProcessAndWait(child, timeoutMs, sendTerm, sendKill) {
@@ -7743,28 +8422,29 @@ function getProcessCwd(pid) {
7743
8422
  }
7744
8423
  return void 0;
7745
8424
  }
7746
- function isPortInUse(port) {
7747
- const platform = process.platform;
7748
- try {
7749
- if (platform === "darwin" || platform === "linux") {
7750
- execSync(`lsof -i :${port} -sTCP:LISTEN 2>/dev/null`, {
7751
- encoding: "utf-8",
7752
- stdio: ["pipe", "pipe", "pipe"]
7753
- });
7754
- 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})`;
7755
8439
  }
7756
- } catch {
7757
- }
7758
- return false;
7759
- }
7760
- function findAvailablePort(startPort, maxAttempts = 10) {
7761
- for (let i = 0; i < maxAttempts; i++) {
7762
- const port = startPort + i;
7763
- if (!isPortInUse(port)) {
7764
- return port;
8440
+ if (child.signalCode !== null && child.signalCode !== void 0) {
8441
+ return `it was killed by ${child.signalCode} before it answered`;
7765
8442
  }
7766
- }
7767
- 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
+ };
7768
8448
  }
7769
8449
  function findProcessesByPattern(pgrepPattern, psPattern) {
7770
8450
  const instances = [];
@@ -7906,7 +8586,7 @@ async function startOpenCode(port, options = {}) {
7906
8586
  return child;
7907
8587
  }
7908
8588
  async function startOpenCode2(port, options = {}) {
7909
- const password = randomBytes(24).toString("hex");
8589
+ const password = randomBytes2(24).toString("hex");
7910
8590
  let command = options.command ?? "opencode2";
7911
8591
  const logLevel = options.inheritStdio ? ["--log-level", resolveOpenCode2LogLevel(process.env)] : [];
7912
8592
  let args = ["serve", "--port", port.toString(), "--hostname", "127.0.0.1", ...logLevel];
@@ -7954,6 +8634,144 @@ function stopOpenCodeAndWait(opencodeProcess, timeoutMs) {
7954
8634
  );
7955
8635
  }
7956
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;
8733
+ }
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);
8742
+ }
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))
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 };
8773
+ }
8774
+
7957
8775
  // src/lib/opencode/install.ts
7958
8776
  import { execSync as execSync2 } from "child_process";
7959
8777
  import chalk4 from "chalk";
@@ -15941,12 +16759,19 @@ import chalk5 from "chalk";
15941
16759
  import ora2 from "ora";
15942
16760
  import { select as select2 } from "@inquirer/prompts";
15943
16761
  var INTERACTIVE_START_TIMEOUT_MS = 3e4;
15944
- function checkNonInteractivePortConflict(port, isPortInUseFn) {
15945
- 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) {
15946
16766
  throw new Error(
15947
16767
  `Port ${port} is already in use by a non-OpenCode process. Free it or pass --port.`
15948
16768
  );
15949
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
+ );
15950
16775
  }
15951
16776
  function unknownPasswordError(port) {
15952
16777
  return new Error(
@@ -16003,24 +16828,29 @@ async function ensureOpenCodeRunning(ctx) {
16003
16828
  }
16004
16829
  }
16005
16830
  if (!ctx.interactive) {
16006
- checkNonInteractivePortConflict(ctx.port, isPortInUse);
16831
+ const reclaimOutcome = await reclaimNonInteractivePort(ctx.port, {
16832
+ imageManaged: ctx.inheritStdio === true
16833
+ });
16007
16834
  ctx.log(`OpenCode is not running on port ${ctx.port}. Starting it automatically...`);
16008
16835
  const proc = await startOpenCode(ctx.port, { inheritStdio: ctx.inheritStdio });
16009
- 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);
16010
16838
  if (!health.healthy) {
16011
16839
  if (health.authFailed) {
16012
16840
  return {
16013
16841
  port: ctx.port,
16014
16842
  process: proc,
16015
16843
  version: null,
16016
- 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 } : {}
16017
16846
  };
16018
16847
  }
16019
16848
  return {
16020
16849
  port: ctx.port,
16021
16850
  process: proc,
16022
16851
  version: null,
16023
- 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 } : {}
16024
16854
  };
16025
16855
  }
16026
16856
  ctx.log(`OpenCode started on port ${ctx.port}${health.version ? ` (v${health.version})` : ""}`);
@@ -16028,14 +16858,15 @@ async function ensureOpenCodeRunning(ctx) {
16028
16858
  port: ctx.port,
16029
16859
  process: proc,
16030
16860
  version: health.version ?? null,
16031
- notReadyReason: null
16861
+ notReadyReason: null,
16862
+ ...reclaimOutcome ? { reclaimOutcome } : {}
16032
16863
  };
16033
16864
  }
16034
16865
  let port = ctx.port;
16035
- if (isPortInUse(port)) {
16866
+ if (await isPortInUse(port)) {
16036
16867
  console.log(chalk5.yellow(`
16037
16868
  Port ${port} is already in use.`));
16038
- const alternativePort = findAvailablePort(port + 1);
16869
+ const alternativePort = await findAvailablePort(port + 1);
16039
16870
  if (alternativePort) {
16040
16871
  const useAlternative = await select2({
16041
16872
  message: `Use port ${alternativePort} instead?`,
@@ -16082,13 +16913,15 @@ Port ${port} is already in use.`));
16082
16913
  if (action === "start") {
16083
16914
  const spinner = ora2("Starting OpenCode...").start();
16084
16915
  const proc = await startOpenCode(port, { inheritStdio: ctx.inheritStdio });
16085
- 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);
16086
16918
  if (!health.healthy) {
16087
16919
  spinner.fail("Failed to start OpenCode");
16088
16920
  if (health.authFailed) {
16089
16921
  throw unknownPasswordError(port);
16090
16922
  }
16091
- throw new Error("OpenCode failed to start");
16923
+ const exitReason = stopEarly();
16924
+ throw new Error(`OpenCode failed to start${exitReason ? `: ${exitReason}` : ""}`);
16092
16925
  }
16093
16926
  spinner.stop();
16094
16927
  return { port, process: proc, version: health.version ?? null, notReadyReason: null };
@@ -16127,40 +16960,24 @@ async function ensureOpenCode2Running(ctx) {
16127
16960
  }
16128
16961
  let port = ctx.port;
16129
16962
  if (!ctx.interactive) {
16130
- checkNonInteractivePortConflict(port, isPortInUse);
16131
- } else if (isPortInUse(port)) {
16132
- console.log(chalk6.yellow(`
16133
- Port ${port} is already in use.`));
16134
- const alternativePort = findAvailablePort(port + 1);
16135
- if (alternativePort) {
16136
- const useAlternative = await select3({
16137
- message: `Use port ${alternativePort} instead?`,
16138
- choices: [
16139
- { name: `Yes, use port ${alternativePort}`, value: "yes" },
16140
- { name: "No, I will free the port manually", value: "no" }
16141
- ]
16142
- });
16143
- if (useAlternative === "yes") {
16144
- port = alternativePort;
16145
- } else {
16146
- throw new Error(`Port ${ctx.port} is in use`);
16147
- }
16148
- }
16149
- }
16150
- if (!ctx.interactive) {
16963
+ const reclaimOutcome = await reclaimNonInteractivePort(port, {
16964
+ imageManaged: ctx.inheritStdio === true
16965
+ });
16151
16966
  ctx.log(`OpenCode V2 is not running on port ${port}. Starting it automatically...`);
16152
16967
  const { child: proc, password } = await startOpenCode2(port, {
16153
16968
  inheritStdio: ctx.inheritStdio,
16154
16969
  command: ctx.command
16155
16970
  });
16156
- 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);
16157
16973
  if (!health.healthy) {
16158
16974
  return {
16159
16975
  port,
16160
16976
  process: proc,
16161
16977
  version: null,
16162
- notReadyReason: `it did not become healthy within ${Math.round(ctx.startTimeoutMs / 1e3)}s`,
16163
- 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 } : {}
16164
16981
  };
16165
16982
  }
16166
16983
  ctx.log(`OpenCode V2 started on port ${port}${health.version ? ` (v${health.version})` : ""}`);
@@ -16169,8 +16986,27 @@ Port ${port} is already in use.`));
16169
16986
  process: proc,
16170
16987
  version: health.version ?? null,
16171
16988
  notReadyReason: null,
16172
- password
16989
+ password,
16990
+ ...reclaimOutcome ? { reclaimOutcome } : {}
16173
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
+ }
16174
17010
  }
16175
17011
  const command = ctx.command ?? "opencode2";
16176
17012
  const action = await select3({
@@ -16207,10 +17043,17 @@ Port ${port} is already in use.`));
16207
17043
  inheritStdio: ctx.inheritStdio,
16208
17044
  command: ctx.command
16209
17045
  });
16210
- 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
+ );
16211
17053
  if (!health.healthy) {
16212
17054
  spinner.fail("Failed to start OpenCode V2");
16213
- throw new Error("OpenCode V2 failed to start");
17055
+ const exitReason = stopEarly();
17056
+ throw new Error(`OpenCode V2 failed to start${exitReason ? `: ${exitReason}` : ""}`);
16214
17057
  }
16215
17058
  spinner.stop();
16216
17059
  return {
@@ -16506,7 +17349,7 @@ async function configureGitHubAccess({ env, log: log3 }) {
16506
17349
  }
16507
17350
 
16508
17351
  // src/lib/opencode/config-overlay.ts
16509
- import { execFileSync as execFileSync2 } from "node:child_process";
17352
+ import { execFileSync as execFileSync3 } from "node:child_process";
16510
17353
  import { copyFileSync, existsSync as existsSync2, statSync as statSync6 } from "node:fs";
16511
17354
  import { isAbsolute as isAbsolute5, join as join15, resolve as resolve5 } from "node:path";
16512
17355
  function parseConfigContent(content) {
@@ -16548,7 +17391,7 @@ function applyRunnerOpenCodeConfig({
16548
17391
  }
16549
17392
  copyFileSync(source, join15(cwd, target));
16550
17393
  try {
16551
- execFileSync2("git", ["-C", cwd, "update-index", "--skip-worktree", target], {
17394
+ execFileSync3("git", ["-C", cwd, "update-index", "--skip-worktree", target], {
16552
17395
  stdio: "ignore"
16553
17396
  });
16554
17397
  } catch (error2) {
@@ -17318,7 +18161,6 @@ function resolveFileSyncExactFiles(raw, homeDir) {
17318
18161
  }
17319
18162
  var DEFAULT_OPENCODE_START_TIMEOUT_SECONDS = 180;
17320
18163
  var MAX_OPENCODE_START_TIMEOUT_SECONDS = 3600;
17321
- var OPENCODE_START_TIMEOUT_ENV = "EVIDENT_OPENCODE_START_TIMEOUT";
17322
18164
  var OPENCODE_VERSION_ENV = "EVIDENT_OPENCODE_VERSION";
17323
18165
  function resolveOpenCodeVersion(options, env = process.env) {
17324
18166
  let raw;
@@ -17942,6 +18784,8 @@ var SESSION_CLEANUP_MAX_DELETES_PER_SWEEP = 100;
17942
18784
  var SESSION_CLEANUP_MAX_ISOLATED_DELETE_FAILURES = 2;
17943
18785
  var SESSION_CLEANUP_GIVE_UP_AFTER_FAILURES = 2;
17944
18786
  var MAX_SESSION_DELETE_BODY_LENGTH = 200;
18787
+ var SESSION_ARCHIVE_FAILURE_DIAGNOSTIC_BUDGET = 3;
18788
+ var SESSION_ARCHIVE_MANIFEST_BUDGET_MS = 500;
17945
18789
  function shouldWarnForReclaimSkip(reason) {
17946
18790
  if (reason !== "sqlite-unavailable" && reason !== "disk-exhaustion") return false;
17947
18791
  const version2 = /^v(\d+)\.(\d+)\.(\d+)$/.exec(process.version);
@@ -17965,18 +18809,52 @@ function logSessionArchiveActivity(state, phase, entry) {
17965
18809
  logActivity(state, {
17966
18810
  ...entry,
17967
18811
  source: "cli.session-archive",
17968
- metadata: { ...entry.metadata, phase }
18812
+ // The forwarder drops metadata beyond its 20-entry cap in insertion order.
18813
+ metadata: { phase, ...entry.metadata }
17969
18814
  });
17970
18815
  }
17971
- function logSessionArchiveSummary(state, phase, summary) {
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
+ }
18829
+ });
18830
+ }
18831
+ function logSessionArchiveSummary(state, phase, summary, reconciliation) {
17972
18832
  const everyUploadFailed = summary.uploadAttempts > 0 && summary.uploadFailures === summary.uploadAttempts;
17973
- const staleSince = everyUploadFailed && summary.staleSince !== null ? `; archive stale since ${summary.staleSince}` : "";
17974
18833
  const neverWatermarked = summary.neverWatermarkedFailures > 0 ? `; ${summary.neverWatermarkedFailures} failed session(s) had no prior successful upload` : "";
17975
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
+ }
17976
18852
  logSessionArchiveActivity(state, phase, {
17977
18853
  type: "info",
17978
18854
  level: warning2 ? "warn" : "info",
17979
- 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.
17980
18858
  metadata: {
17981
18859
  outcome: "archive-run-complete",
17982
18860
  sessions_inspected: summary.inspected,
@@ -17987,7 +18865,6 @@ function logSessionArchiveSummary(state, phase, summary) {
17987
18865
  uploads_failed: summary.uploadFailures,
17988
18866
  sessions_skipped_budget: summary.skippedBudget,
17989
18867
  sessions_unmapped: summary.unmappedIds.length,
17990
- sessions_unresolved: summary.unresolved,
17991
18868
  sessions_conflicted: summary.conflicts,
17992
18869
  sessions_reconciliation_incomplete: summary.reconciliationIncomplete,
17993
18870
  binding_reconciliation_complete: summary.reconciliationComplete,
@@ -17997,11 +18874,10 @@ function logSessionArchiveSummary(state, phase, summary) {
17997
18874
  bindings_from_invocation: summary.bindingSourceCounts.invocation,
17998
18875
  bindings_from_history: summary.bindingSourceCounts.history,
17999
18876
  bindings_from_parent: summary.bindingSourceCounts.parent,
18000
- sessions_without_prior_watermark: summary.neverWatermarkedFailures,
18001
- ...everyUploadFailed && summary.staleSince !== null ? { stale_since: summary.staleSince } : {}
18877
+ sessions_without_prior_watermark: summary.neverWatermarkedFailures
18002
18878
  }
18003
18879
  });
18004
- for (const failure of summary.failures) {
18880
+ const logFailure = (failure) => {
18005
18881
  const permanentSizeFailure = failure.reason === "too-large";
18006
18882
  const hasPayloadDetails = failure.bytes !== void 0 && failure.byteLimit !== void 0 && failure.messageCount !== void 0 && failure.partCount !== void 0;
18007
18883
  const payloadDetails = hasPayloadDetails ? `; payload bytes=${failure.bytes} limit=${failure.byteLimit} messages=${failure.messageCount} parts=${failure.partCount}` : "";
@@ -18024,7 +18900,9 @@ function logSessionArchiveSummary(state, phase, summary) {
18024
18900
  } : {}
18025
18901
  }
18026
18902
  });
18027
- }
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);
18028
18906
  if (summary.unmappedIds.length > 0) {
18029
18907
  logSessionArchiveActivity(state, phase, {
18030
18908
  type: "info",
@@ -18048,6 +18926,117 @@ function logSessionArchiveSummary(state, phase, summary) {
18048
18926
  });
18049
18927
  }
18050
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
+ }
18051
19040
  async function drainSessionDeletionReports(state) {
18052
19041
  const path = sessionDeletionReportPath(homedir9(), process.env);
18053
19042
  let delivered = 0;
@@ -18465,14 +19454,10 @@ function runSessionArchiveTask(state, phase, budgetMs, work) {
18465
19454
  }
18466
19455
  const controller = new AbortController();
18467
19456
  state.sessionArchiveAbortController = controller;
19457
+ let budgetExceeded = false;
18468
19458
  const timeout = setTimeout(() => {
19459
+ budgetExceeded = true;
18469
19460
  controller.abort();
18470
- logSessionArchiveActivity(state, phase, {
18471
- type: "info",
18472
- level: "warn",
18473
- message: `Session archive exceeded ${budgetMs}ms; remaining sessions were not confirmed archived`,
18474
- metadata: { outcome: "archive-budget-exceeded", budget_ms: budgetMs }
18475
- });
18476
19461
  }, budgetMs);
18477
19462
  const task = Promise.resolve().then(() => work(controller.signal)).catch((error2) => {
18478
19463
  logSessionArchiveActivity(state, phase, {
@@ -18483,6 +19468,19 @@ function runSessionArchiveTask(state, phase, budgetMs, work) {
18483
19468
  });
18484
19469
  return null;
18485
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
+ }
18486
19484
  clearTimeout(timeout);
18487
19485
  if (state.sessionArchiveInFlight === task) {
18488
19486
  state.sessionArchiveInFlight = null;
@@ -18493,10 +19491,7 @@ function runSessionArchiveTask(state, phase, budgetMs, work) {
18493
19491
  return task;
18494
19492
  }
18495
19493
  async function runSessionArchiveBatch(state, phase, sessions, budgetMs, signal) {
18496
- const config = state.sessionArchiveConfig;
18497
- const client = state.opencodeClient;
18498
- const watermarkPath = state.sessionArchiveWatermarkPath;
18499
- if (!client || !config.keyPrefix || !watermarkPath || !state.agentId) {
19494
+ if (!hasSessionArchivePrerequisites(state)) {
18500
19495
  logSessionArchiveActivity(state, phase, {
18501
19496
  type: "info",
18502
19497
  level: "warn",
@@ -18505,6 +19500,9 @@ async function runSessionArchiveBatch(state, phase, sessions, budgetMs, signal)
18505
19500
  });
18506
19501
  return null;
18507
19502
  }
19503
+ const config = state.sessionArchiveConfig;
19504
+ const client = state.opencodeClient;
19505
+ const watermarkPath = state.sessionArchiveWatermarkPath;
18508
19506
  const bindings = readSessionBindings(
18509
19507
  sessionBindingLedgerPath(homedir9(), process.env),
18510
19508
  (message) => logSessionArchiveActivity(state, phase, {
@@ -18521,23 +19519,6 @@ async function runSessionArchiveBatch(state, phase, sessions, budgetMs, signal)
18521
19519
  sessions,
18522
19520
  signal
18523
19521
  });
18524
- if (!reconciliation.complete) {
18525
- const failure = reconciliation.failures[0];
18526
- 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}`;
18527
- logSessionArchiveActivity(state, phase, {
18528
- type: "info",
18529
- level: "warn",
18530
- message: `Session archive: binding reconciliation incomplete for runner ${state.agentId}; ${reconciliation.failures.length} chunk(s) failed (${detail}), unresolved sessions will not replace existing archives`,
18531
- metadata: {
18532
- outcome: "binding-reconciliation-incomplete",
18533
- runner_id: state.agentId,
18534
- failed_chunks: reconciliation.failures.length,
18535
- first_failed_chunk: failure.chunk,
18536
- first_failure_kind: failure.kind,
18537
- ...failure.status !== void 0 ? { http_status: failure.status } : {}
18538
- }
18539
- });
18540
- }
18541
19522
  const summary = await runSessionArchive({
18542
19523
  sessions,
18543
19524
  deps: {
@@ -18548,40 +19529,97 @@ async function runSessionArchiveBatch(state, phase, sessions, budgetMs, signal)
18548
19529
  projection: reconciliation.projection,
18549
19530
  reconciliationComplete: reconciliation.complete,
18550
19531
  watermarks: state.sessionArchiveWatermarks,
19532
+ priorFailureIds: state.sessionArchivePriorFailureIds,
18551
19533
  watermarkPath,
18552
19534
  signal,
19535
+ onMetadataDecodeError: (field, reason, sessionId) => logSessionArchiveMetadataDecodeFailure(state, phase, { field, reason, sessionId }),
18553
19536
  upload: uploadSessionArchive,
18554
19537
  exportMessages: exportSessionMessages,
18555
19538
  recordWatermark: recordUpload
18556
19539
  },
18557
19540
  budgetMs
18558
19541
  });
18559
- logSessionArchiveSummary(state, phase, summary);
19542
+ logSessionArchiveSummary(state, phase, summary, reconciliation);
18560
19543
  return summary;
18561
19544
  }
18562
19545
  async function runSessionArchiveFleet(state, phase, budgetMs, signal) {
19546
+ state.sessionArchivePassSequence++;
18563
19547
  const startedAt = Date.now();
18564
- const enumeration = await listAllSessions(state.port, state.opencodeClient ?? void 0, signal);
18565
- if (enumeration.sessions === null) {
18566
- const interrupted = signal.aborted;
18567
- logSessionArchiveActivity(state, phase, {
18568
- type: "info",
18569
- level: "warn",
18570
- 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`,
18571
- metadata: {
18572
- outcome: interrupted ? "enumeration-interrupted" : "enumeration-refused",
18573
- ...!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);
18574
19580
  }
18575
- });
18576
- 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();
18577
19591
  }
18578
- return runSessionArchiveBatch(
18579
- state,
18580
- phase,
18581
- enumeration.sessions,
18582
- Math.max(0, budgetMs - (Date.now() - startedAt)),
18583
- signal
18584
- );
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;
18585
19623
  }
18586
19624
  async function runSessionArchiveShutdownFlush(state, budgetMs) {
18587
19625
  const deadline = Date.now() + budgetMs;
@@ -18604,7 +19642,13 @@ async function runSessionArchiveShutdownFlush(state, budgetMs) {
18604
19642
  type: "info",
18605
19643
  level: "warn",
18606
19644
  message: `Session archive exceeded ${budgetMs}ms while stopping a prior run; remaining sessions were not confirmed archived`,
18607
- 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
+ }
18608
19652
  });
18609
19653
  return null;
18610
19654
  }
@@ -18615,7 +19659,13 @@ async function runSessionArchiveShutdownFlush(state, budgetMs) {
18615
19659
  type: "info",
18616
19660
  level: "warn",
18617
19661
  message: `Session archive exceeded ${budgetMs}ms while stopping a prior run; remaining sessions were not confirmed archived`,
18618
- 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
+ }
18619
19669
  });
18620
19670
  return null;
18621
19671
  }
@@ -18639,6 +19689,7 @@ function scheduleSessionArchive(state) {
18639
19689
  metadata: { outcome: "watermark-read-failed" }
18640
19690
  })
18641
19691
  );
19692
+ state.sessionArchiveWatermarkFileLoaded = state.sessionArchiveWatermarks.size > 0;
18642
19693
  logSessionArchiveActivity(state, "startup", {
18643
19694
  type: "info",
18644
19695
  message: `Session archive enabled (interval=${config.intervalMs}ms)`,
@@ -19148,9 +20199,13 @@ async function run(options) {
19148
20199
  ),
19149
20200
  sessionArchiveTimers: [],
19150
20201
  sessionArchiveWatermarks: /* @__PURE__ */ new Map(),
20202
+ sessionArchivePriorFailureIds: /* @__PURE__ */ new Set(),
19151
20203
  sessionArchiveWatermarkPath: null,
19152
20204
  sessionArchiveInFlight: null,
19153
20205
  sessionArchiveAbortController: null,
20206
+ sessionArchiveBootId: randomUUID2(),
20207
+ sessionArchivePassSequence: 0,
20208
+ sessionArchiveWatermarkFileLoaded: false,
19154
20209
  sessionDeleteFailures: /* @__PURE__ */ new Map(),
19155
20210
  claudeUsageTimer: null,
19156
20211
  claudeUsageRearm: null,
@@ -19611,7 +20666,7 @@ async function run(options) {
19611
20666
  port: state.port,
19612
20667
  interactive: state.interactive,
19613
20668
  agentId: state.agentId,
19614
- log: (message) => log2(state, message),
20669
+ log: (message, level = "info") => log2(state, message, level),
19615
20670
  startTimeoutMs: opencodeStartTimeoutMs,
19616
20671
  inheritStdio: Boolean(options.opencodePidFile),
19617
20672
  command: opencodeV2Command
@@ -19619,10 +20674,15 @@ async function run(options) {
19619
20674
  port: state.port,
19620
20675
  interactive: state.interactive,
19621
20676
  agentId: state.agentId,
19622
- log: (message) => log2(state, message),
20677
+ log: (message, level = "info") => log2(state, message, level),
19623
20678
  startTimeoutMs: opencodeStartTimeoutMs,
19624
20679
  inheritStdio: Boolean(options.opencodePidFile)
19625
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
+ }
19626
20686
  state.port = oc.port;
19627
20687
  state.opencodeProcess = options.opencodePidFile ? null : oc.process;
19628
20688
  state.opencodeVersion = oc.version;
@@ -19666,7 +20726,7 @@ async function run(options) {
19666
20726
  password: state.opencodePassword
19667
20727
  });
19668
20728
  state.opencodeClient = openCodeClient;
19669
- 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) {
19670
20730
  try {
19671
20731
  writeFileSync9(options.opencodePidFile, `${oc.process.pid}
19672
20732
  `, { mode: 384 });
@@ -19677,6 +20737,12 @@ async function run(options) {
19677
20737
  error: `Failed to write OpenCode pid file ${options.opencodePidFile}: ${error2 instanceof Error ? error2.message : String(error2)}`
19678
20738
  });
19679
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
+ });
19680
20746
  }
19681
20747
  if (state.opencodeVersion !== null) {
19682
20748
  const provenance = checkSessionDbProvenance({
@@ -19723,7 +20789,7 @@ async function run(options) {
19723
20789
  const version2 = state.opencodeVersion ? ` (v${state.opencodeVersion})` : "";
19724
20790
  ocSpinner?.succeed(`OpenCode running on port ${state.port}${version2}`);
19725
20791
  if (!state.interactive && oc.notReadyReason !== null) {
19726
- 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.`;
19727
20793
  logActivity(state, { type: "info", level: "warn", message });
19728
20794
  } else {
19729
20795
  const versionWarning = buildOpenCodeVersionWarning(
@@ -20133,24 +21199,89 @@ async function run(options) {
20133
21199
  }
20134
21200
  }
20135
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
+
20136
21262
  // src/index.ts
20137
21263
  var version = getCliVersion();
20138
21264
  var program = new Command();
20139
21265
  program.name("evident").description("Run OpenCode locally and connect it to Evident").version(version).option(
20140
21266
  "--endpoint <url>",
20141
21267
  "Evident API base URL (default: production; e.g. http://localhost:3001)"
20142
- ).option("--tunnel <url>", "Tunnel WebSocket URL (default: production; e.g. ws://localhost:8787)").hook("preAction", (thisCommand) => {
20143
- const { endpoint: endpoint2, tunnel } = thisCommand.optsWithGlobals();
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();
20144
21273
  if (endpoint2) {
20145
21274
  setEndpoint(endpoint2);
20146
21275
  }
20147
21276
  if (tunnel) {
20148
21277
  setTunnelUrl(tunnel);
20149
21278
  }
21279
+ setTeamSelection(team);
20150
21280
  });
20151
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);
20152
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 }));
20153
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);
20154
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(
20155
21286
  (proxyId, connectionId, options) => authorizeMcpConnection(proxyId, connectionId, {
20156
21287
  noBrowser: options.browser === false,