@evident-ai/cli 3.6.1-dev.22aa800 → 3.6.1-dev.240ba07

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,9 @@
1
1
  #!/usr/bin/env node
2
+ var __defProp = Object.defineProperty;
3
+ var __export = (target, all) => {
4
+ for (var name in all)
5
+ __defProp(target, name, { get: all[name], enumerable: true });
6
+ };
2
7
 
3
8
  // src/index.ts
4
9
  import { Command } from "commander";
@@ -9,6 +14,24 @@ import ora from "ora";
9
14
  import chalk2 from "chalk";
10
15
 
11
16
  // src/lib/config.ts
17
+ var config_exports = {};
18
+ __export(config_exports, {
19
+ clearAllCredentials: () => clearAllCredentials,
20
+ clearCredentials: () => clearCredentials,
21
+ clearManagedInferenceCredential: () => clearManagedInferenceCredential,
22
+ credentials: () => credentials,
23
+ getApiUrlConfig: () => getApiUrlConfig,
24
+ getCliName: () => getCliName,
25
+ getCredentials: () => getCredentials,
26
+ getManagedInferenceCredential: () => getManagedInferenceCredential,
27
+ getTeamSelection: () => getTeamSelection,
28
+ getTunnelUrlConfig: () => getTunnelUrlConfig,
29
+ setCredentials: () => setCredentials,
30
+ setEndpoint: () => setEndpoint,
31
+ setManagedInferenceCredential: () => setManagedInferenceCredential,
32
+ setTeamSelection: () => setTeamSelection,
33
+ setTunnelUrl: () => setTunnelUrl
34
+ });
12
35
  import Conf from "conf";
13
36
  import { chmodSync, existsSync, statSync } from "node:fs";
14
37
  import { dirname } from "node:path";
@@ -20,6 +43,7 @@ var defaults = {
20
43
  };
21
44
  var endpointOverride;
22
45
  var tunnelOverride;
46
+ var teamOverride;
23
47
  function setEndpoint(url) {
24
48
  if (!url) {
25
49
  endpointOverride = void 0;
@@ -31,6 +55,13 @@ function setEndpoint(url) {
31
55
  function setTunnelUrl(url) {
32
56
  tunnelOverride = url ? url.replace(/\/+$/, "") : void 0;
33
57
  }
58
+ function setTeamSelection(id) {
59
+ const trimmed = id?.trim();
60
+ teamOverride = trimmed || void 0;
61
+ }
62
+ function getTeamSelection() {
63
+ return teamOverride ?? (process.env.EVIDENT_TEAM?.trim() || void 0);
64
+ }
34
65
  function getApiUrl() {
35
66
  return endpointOverride ?? process.env.EVIDENT_API_URL ?? defaults.apiUrl;
36
67
  }
@@ -579,6 +610,14 @@ function getAuthHeader(credentials2) {
579
610
  }
580
611
  return `Bearer ${credentials2.token}`;
581
612
  }
613
+ function buildAuthHeaders(credentials2) {
614
+ const headers = { Authorization: getAuthHeader(credentials2) };
615
+ const team = Object.hasOwn(config_exports, "getTeamSelection") ? getTeamSelection() : void 0;
616
+ if (credentials2.authType === "bearer" && team) {
617
+ headers["X-Evident-Team"] = team;
618
+ }
619
+ return headers;
620
+ }
582
621
  function isInteractive(jsonOutput) {
583
622
  if (jsonOutput) return false;
584
623
  if (process.env.CI) return false;
@@ -1178,11 +1217,10 @@ async function claudeUsage() {
1178
1217
  }
1179
1218
  }
1180
1219
 
1181
- // src/commands/run.ts
1182
- import { chmodSync as chmodSync3, existsSync as existsSync3, readFileSync as readFileSync12, writeFileSync as writeFileSync9 } from "node:fs";
1183
- import { homedir as homedir9 } from "node:os";
1184
- import { isAbsolute as isAbsolute6, join as join17, parse, resolve as resolvePath2 } from "node:path";
1185
- import chalk7 from "chalk";
1220
+ // src/commands/mcp-authorize.ts
1221
+ import { createServer } from "node:http";
1222
+ import { randomBytes } from "node:crypto";
1223
+ import open2 from "open";
1186
1224
 
1187
1225
  // ../../packages/types/src/agents/index.ts
1188
1226
  var MICROVM_MAX_LIFETIME_MS = 8 * 60 * 6e4;
@@ -1234,23 +1272,28 @@ function lastText(assistantRun) {
1234
1272
  }
1235
1273
  return null;
1236
1274
  }
1237
- function effectiveCorrelatedRun(messages, userMessageId) {
1238
- const run2 = correlatedAssistantRun(messages, userMessageId);
1239
- if (lastText(run2) !== null) return run2;
1240
- const userIndex = messages?.findIndex((m) => idOf(m) === userMessageId) ?? -1;
1241
- if (userIndex === -1) return run2;
1275
+ function literalContinueRun(messages, userMessageId) {
1276
+ if (!messages) return [];
1277
+ const userIndex = messages.findIndex((m) => idOf(m) === userMessageId);
1278
+ if (userIndex === -1) return [];
1242
1279
  let continuation;
1243
- for (let i = userIndex + 1; messages && i < messages.length; i++) {
1280
+ for (let i = userIndex + 1; i < messages.length; i++) {
1244
1281
  if (roleOf(messages[i]) === "user") {
1245
1282
  continuation = messages[i];
1246
1283
  break;
1247
1284
  }
1248
1285
  }
1249
1286
  const continuationId = idOf(continuation);
1250
- if (roleOf(continuation) === "user" && textPartsOf(continuation).join("\n").trim().toLowerCase() === "continue" && continuationId) {
1251
- const continuationRun = correlatedAssistantRun(messages, continuationId);
1252
- if (continuationRun.length > 0) return continuationRun;
1287
+ if (roleOf(continuation) !== "user" || textPartsOf(continuation).join("\n").trim().toLowerCase() !== "continue" || !continuationId) {
1288
+ return [];
1253
1289
  }
1290
+ return correlatedAssistantRun(messages, continuationId);
1291
+ }
1292
+ function effectiveCorrelatedRun(messages, userMessageId) {
1293
+ const run2 = correlatedAssistantRun(messages, userMessageId);
1294
+ if (lastText(run2) !== null) return run2;
1295
+ const continuationRun = literalContinueRun(messages, userMessageId);
1296
+ if (continuationRun.length > 0) return continuationRun;
1254
1297
  return run2;
1255
1298
  }
1256
1299
  function extractReplyTextForMessage(messages, opencodeUserMessageId) {
@@ -1438,6 +1481,14 @@ function buildCredentialProxyNativeConfig({
1438
1481
  };
1439
1482
  }
1440
1483
 
1484
+ // ../../packages/types/src/mcp-proxies.ts
1485
+ var MCP_LOOPBACK_REDIRECT_POLICY = {
1486
+ scheme: "http",
1487
+ host: "127.0.0.1",
1488
+ path: "/callback",
1489
+ preferred_port: 18443
1490
+ };
1491
+
1441
1492
  // ../../packages/types/src/logging/index.ts
1442
1493
  var CORRELATION_ID_HEADER = "x-evident-correlation-id";
1443
1494
  var FORWARD_FAILURE_REASON_HEADER = "X-Evident-Failure-Reason";
@@ -1472,12 +1523,943 @@ function stripQuery(url) {
1472
1523
  }
1473
1524
  }
1474
1525
 
1526
+ // src/commands/mcp-authorize.ts
1527
+ var API_TIMEOUT_MS = 1e4;
1528
+ var CALLBACK_PAGE_FINAL_READ_TIMEOUT_MS = 2e3;
1529
+ var COMPLETION_UNCONFIRMED_MESSAGE = "Completion could not be confirmed; check the connection in Evident before retrying.";
1530
+ var KNOWN_CALLBACK_PARAMETERS = /* @__PURE__ */ new Set(["state", "code", "error", "error_description", "iss"]);
1531
+ var ApiHttpError = class extends Error {
1532
+ constructor(status2, operation) {
1533
+ super(`Evident API returned HTTP ${status2} while ${operation}`);
1534
+ this.status = status2;
1535
+ this.operation = operation;
1536
+ }
1537
+ };
1538
+ var CallbackExpiredError = class extends Error {
1539
+ constructor() {
1540
+ super("The local sign-in attempt expired before the provider returned.");
1541
+ }
1542
+ };
1543
+ var InterruptedError = class extends Error {
1544
+ constructor() {
1545
+ super("Authorization was interrupted.");
1546
+ }
1547
+ };
1548
+ function apiPath(proxyId, connectionId, suffix) {
1549
+ const path = `/mcp-proxies/${encodeURIComponent(proxyId)}`;
1550
+ if (!connectionId) return path + "/connections";
1551
+ return `${path}/connections/${encodeURIComponent(connectionId)}/local-authorization/${suffix}`;
1552
+ }
1553
+ async function requestJson(path, credentials2, cancelSignal, operation, body) {
1554
+ const method = body === void 0 ? "GET" : "POST";
1555
+ const requestController = new AbortController();
1556
+ const onCancel = () => requestController.abort();
1557
+ const timeout = setTimeout(() => requestController.abort(), API_TIMEOUT_MS);
1558
+ cancelSignal.addEventListener("abort", onCancel, { once: true });
1559
+ if (cancelSignal.aborted) onCancel();
1560
+ try {
1561
+ let response;
1562
+ try {
1563
+ response = await fetch(`${getApiUrlConfig()}${path}`, {
1564
+ method,
1565
+ headers: {
1566
+ ...buildAuthHeaders(credentials2),
1567
+ ...body === void 0 ? {} : { "Content-Type": "application/json" }
1568
+ },
1569
+ body: body === void 0 ? void 0 : JSON.stringify(body),
1570
+ signal: requestController.signal
1571
+ });
1572
+ } catch (error2) {
1573
+ if (cancelSignal.aborted) throw new InterruptedError();
1574
+ if (requestController.signal.aborted) {
1575
+ throw new Error(`Evident timed out while ${operation} after ${API_TIMEOUT_MS}ms.`);
1576
+ }
1577
+ const detail = error2 instanceof Error ? error2.message : String(error2);
1578
+ throw new Error(
1579
+ `Could not reach Evident while ${operation}: ${detail}. Check --endpoint or EVIDENT_API_URL and retry.`
1580
+ );
1581
+ }
1582
+ if (!response.ok) throw new ApiHttpError(response.status, operation);
1583
+ try {
1584
+ return await response.json();
1585
+ } catch (error2) {
1586
+ if (cancelSignal.aborted) throw new InterruptedError();
1587
+ if (requestController.signal.aborted) {
1588
+ throw new Error(`Evident timed out while ${operation} after ${API_TIMEOUT_MS}ms.`);
1589
+ }
1590
+ const detail = error2 instanceof Error ? error2.message : String(error2);
1591
+ throw new Error(`Evident returned an invalid response while ${operation}: ${detail}`);
1592
+ }
1593
+ } finally {
1594
+ clearTimeout(timeout);
1595
+ cancelSignal.removeEventListener("abort", onCancel);
1596
+ }
1597
+ }
1598
+ function callbackPage(statusPath) {
1599
+ const nonce = randomBytes(18).toString("base64url");
1600
+ const statusMarkup = statusPath ? `<main class="card" id="callback-page" data-status-url="${statusPath}" role="status" aria-live="polite" aria-atomic="true">
1601
+ <span class="dot" aria-hidden="true"></span>
1602
+ <h1 id="status-heading">Provider response received</h1>
1603
+ <p id="status-message">Your provider response is here. Evident is preparing the connection.</p>
1604
+ <ol class="steps" aria-label="Authorization progress">
1605
+ <li data-step="provider" data-state="done"><span class="step-mark" aria-hidden="true">\u2713</span><span>Provider response received</span></li>
1606
+ <li data-step="evident" data-state="pending"><span class="step-mark" aria-hidden="true">2</span><span>Evident completes authorization</span></li>
1607
+ <li data-step="connection" data-state="pending"><span class="step-mark" aria-hidden="true">3</span><span>Review tools in Evident</span></li>
1608
+ </ol>
1609
+ <p class="footnote" id="status-footnote">Keep this page open while Evident finishes. The terminal shows the same progress.</p>
1610
+ </main>` : `<main class="card" role="status">
1611
+ <span class="dot" aria-hidden="true"></span>
1612
+ <h1>Sign-in response not accepted</h1>
1613
+ <p>This response wasn\u2019t accepted. Return to the terminal for details, then retry authorization if needed.</p>
1614
+ </main>`;
1615
+ const script = statusPath ? `<script nonce="${nonce}">
1616
+ history.replaceState(null, '', location.pathname);
1617
+ const page = document.getElementById('callback-page');
1618
+ const statusUrl = page.dataset.statusUrl;
1619
+ const views = {
1620
+ received: {
1621
+ heading: 'Provider response received',
1622
+ message: 'Your provider response is here. Evident is preparing the connection.',
1623
+ footnote: 'Keep this page open while Evident finishes. The terminal shows the same progress.',
1624
+ steps: ['done', 'pending', 'pending'],
1625
+ },
1626
+ completing: {
1627
+ heading: 'Evident is finishing setup',
1628
+ message: 'Evident received the response and is completing authorization.',
1629
+ footnote: 'This can take a moment. The terminal shows the same progress.',
1630
+ steps: ['done', 'current', 'pending'],
1631
+ },
1632
+ success: {
1633
+ heading: 'Authorization confirmed',
1634
+ message:
1635
+ 'Evident confirmed authorization. Review the discovered tools in Evident to choose which to enable.',
1636
+ footnote: 'You can close this window.',
1637
+ steps: ['done', 'done', 'current'],
1638
+ },
1639
+ tools_pending: {
1640
+ heading: 'Authorization confirmed',
1641
+ message: 'Evident authorized the connection, but its tools are still being prepared.',
1642
+ footnote: 'Check the connection in Evident for tool status. You can close this window.',
1643
+ steps: ['done', 'done', 'current'],
1644
+ },
1645
+ failed: {
1646
+ heading: 'Sign-in did not finish',
1647
+ message: 'Evident could not complete setup. Check the terminal for the next step.',
1648
+ footnote: 'You can close this window after reading the terminal.',
1649
+ steps: ['done', 'failed', 'pending'],
1650
+ },
1651
+ unconfirmed: {
1652
+ heading: 'Completion could not be confirmed',
1653
+ message: 'Check the connection in Evident before retrying.',
1654
+ footnote: 'The terminal has the same status. Check the connection before starting another sign-in.',
1655
+ steps: ['done', 'uncertain', 'pending'],
1656
+ },
1657
+ };
1658
+ const terminalPhases = new Set(['success', 'tools_pending', 'failed', 'unconfirmed']);
1659
+ function showView(phase, view) {
1660
+ document.body.dataset.phase = phase;
1661
+ document.getElementById('status-heading').textContent = view.heading;
1662
+ document.getElementById('status-message').textContent = view.message;
1663
+ document.getElementById('status-footnote').textContent = view.footnote;
1664
+ ['provider', 'evident', 'connection'].forEach((name, index) => {
1665
+ const step = document.querySelector('[data-step="' + name + '"]');
1666
+ const state = view.steps[index];
1667
+ step.dataset.state = state;
1668
+ step.querySelector('.step-mark').textContent = state === 'done' ? '\u2713' : String(index + 1);
1669
+ });
1670
+ }
1671
+ async function poll() {
1672
+ try {
1673
+ const response = await fetch(statusUrl, {
1674
+ cache: 'no-store',
1675
+ credentials: 'omit',
1676
+ redirect: 'error',
1677
+ headers: { Accept: 'application/json' },
1678
+ });
1679
+ if (!response.ok) throw new Error('status unavailable');
1680
+ const result = await response.json();
1681
+ const view = views[result.phase];
1682
+ if (!view) throw new Error('unknown status');
1683
+ showView(result.phase, view);
1684
+ if (terminalPhases.has(result.phase)) return;
1685
+ } catch (_error) {
1686
+ document.getElementById('status-message').textContent =
1687
+ 'Evident is still finishing. Check the terminal for the latest status.';
1688
+ }
1689
+ window.setTimeout(poll, 400);
1690
+ }
1691
+ document.addEventListener('DOMContentLoaded', poll, { once: true });
1692
+ </script>` : `<script nonce="${nonce}">history.replaceState(null, '', location.pathname);</script>`;
1693
+ const html = `<!doctype html>
1694
+ <html lang="en">
1695
+ <head>
1696
+ <meta charset="utf-8" />
1697
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
1698
+ <meta name="robots" content="noindex" />
1699
+ <meta name="referrer" content="no-referrer" />
1700
+ <title>Sign-in \xB7 Evident</title>
1701
+ <style nonce="${nonce}">
1702
+ :root { color-scheme: light dark; }
1703
+ * { box-sizing: border-box; }
1704
+ body {
1705
+ margin: 0;
1706
+ min-height: 100vh;
1707
+ display: flex;
1708
+ align-items: center;
1709
+ justify-content: center;
1710
+ padding: 24px;
1711
+ font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
1712
+ background: #0b0d12;
1713
+ color: #e6e8ee;
1714
+ }
1715
+ .card {
1716
+ width: 100%;
1717
+ max-width: 420px;
1718
+ text-align: center;
1719
+ background: #12151c;
1720
+ border: 1px solid #232838;
1721
+ border-radius: 16px;
1722
+ padding: 36px 24px;
1723
+ box-shadow: 0 10px 40px rgba(0, 0, 0, 0.35);
1724
+ }
1725
+ .dot {
1726
+ width: 12px;
1727
+ height: 12px;
1728
+ border-radius: 50%;
1729
+ background: #f59e0b;
1730
+ display: inline-block;
1731
+ margin-bottom: 20px;
1732
+ box-shadow: 0 0 0 4px rgba(245, 158, 11, 0.15);
1733
+ }
1734
+ body[data-phase="success"] .dot {
1735
+ background: #34d399;
1736
+ box-shadow: 0 0 0 4px rgba(52, 211, 153, 0.15);
1737
+ }
1738
+ body[data-phase="failed"] .dot {
1739
+ background: #fb7185;
1740
+ box-shadow: 0 0 0 4px rgba(251, 113, 133, 0.15);
1741
+ }
1742
+ h1 { font-size: 20px; margin: 0 0 8px; font-weight: 600; }
1743
+ p { margin: 0; color: #9aa2b4; font-size: 14px; line-height: 1.5; }
1744
+ .steps { list-style: none; margin: 24px 0 0; padding: 0; text-align: left; }
1745
+ .steps li {
1746
+ display: flex;
1747
+ align-items: center;
1748
+ gap: 12px;
1749
+ min-height: 48px;
1750
+ border-top: 1px solid #232838;
1751
+ color: #9aa2b4;
1752
+ font-size: 14px;
1753
+ }
1754
+ .step-mark {
1755
+ width: 24px;
1756
+ height: 24px;
1757
+ border: 1px solid #42495b;
1758
+ border-radius: 50%;
1759
+ display: inline-flex;
1760
+ align-items: center;
1761
+ justify-content: center;
1762
+ flex: 0 0 auto;
1763
+ font-size: 12px;
1764
+ }
1765
+ [data-state="done"] { color: #e6e8ee !important; }
1766
+ [data-state="done"] .step-mark { border-color: #34d399; color: #34d399; }
1767
+ [data-state="current"] { color: #e6e8ee !important; }
1768
+ [data-state="current"] .step-mark { border-color: #f59e0b; color: #fbbf24; }
1769
+ [data-state="failed"] .step-mark { border-color: #fb7185; color: #fb7185; }
1770
+ [data-state="uncertain"] .step-mark { border-color: #f59e0b; color: #fbbf24; }
1771
+ .footnote { margin-top: 20px; font-size: 12px; }
1772
+ @media (max-width: 480px) {
1773
+ body { padding: 16px; }
1774
+ .card { padding: 32px 20px; }
1775
+ }
1776
+ </style>
1777
+ </head>
1778
+ <body>${statusMarkup}${script}</body>
1779
+ </html>`;
1780
+ return { html, nonce };
1781
+ }
1782
+ function callbackResponse(response, status2, html, nonce, onFinish) {
1783
+ response.writeHead(status2, {
1784
+ "Content-Type": "text/html; charset=utf-8",
1785
+ "Cache-Control": "no-store",
1786
+ Pragma: "no-cache",
1787
+ "Content-Security-Policy": `default-src 'none'; script-src 'nonce-${nonce}'; style-src 'nonce-${nonce}'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`,
1788
+ "X-Content-Type-Options": "nosniff",
1789
+ "X-Frame-Options": "DENY",
1790
+ "Referrer-Policy": "no-referrer",
1791
+ "Cross-Origin-Resource-Policy": "same-origin"
1792
+ });
1793
+ response.end(html, onFinish);
1794
+ }
1795
+ function statusResponse(response, status2, phase, onFinish) {
1796
+ response.writeHead(status2, {
1797
+ "Content-Type": "application/json; charset=utf-8",
1798
+ "Cache-Control": "no-store",
1799
+ Pragma: "no-cache",
1800
+ "Content-Security-Policy": "default-src 'none'; frame-ancestors 'none'",
1801
+ "X-Content-Type-Options": "nosniff",
1802
+ "X-Frame-Options": "DENY",
1803
+ "Referrer-Policy": "no-referrer",
1804
+ "Cross-Origin-Resource-Policy": "same-origin"
1805
+ });
1806
+ response.end(phase ? JSON.stringify({ phase }) : "", onFinish);
1807
+ }
1808
+ function isTerminalPagePhase(phase) {
1809
+ return phase === "success" || phase === "tools_pending" || phase === "failed" || phase === "unconfirmed";
1810
+ }
1811
+ function waitForTerminalStatusRead(page, signal) {
1812
+ if (page.terminalRead || signal.aborted) return Promise.resolve();
1813
+ return new Promise((resolve6) => {
1814
+ let settled = false;
1815
+ const finish = () => {
1816
+ if (settled) return;
1817
+ settled = true;
1818
+ clearTimeout(timer);
1819
+ signal.removeEventListener("abort", finish);
1820
+ if (page.notifyTerminalRead === finish) page.notifyTerminalRead = void 0;
1821
+ resolve6();
1822
+ };
1823
+ const timer = setTimeout(finish, CALLBACK_PAGE_FINAL_READ_TIMEOUT_MS);
1824
+ page.notifyTerminalRead = finish;
1825
+ signal.addEventListener("abort", finish, { once: true });
1826
+ if (signal.aborted) finish();
1827
+ });
1828
+ }
1829
+ function handleStatusRequest(request3, response, page) {
1830
+ if (!request3.url?.startsWith("/_status/")) return false;
1831
+ const statusPath = `/_status/${page.capability}`;
1832
+ const base = page.origin ?? `http://${MCP_LOOPBACK_REDIRECT_POLICY.host}`;
1833
+ const url = URL.canParse(request3.url, base) ? new URL(request3.url, base) : void 0;
1834
+ const fetchSite = request3.headers["sec-fetch-site"];
1835
+ if (request3.method !== "GET" || !url || url.pathname !== statusPath || url.search || request3.headers.host !== page.host || fetchSite !== void 0 && fetchSite !== "same-origin" || request3.headers.origin !== void 0 && request3.headers.origin !== page.origin || request3.headers["transfer-encoding"] !== void 0 || Number(request3.headers["content-length"] ?? 0) > 0) {
1836
+ statusResponse(response, 404);
1837
+ return true;
1838
+ }
1839
+ const phase = page.phase;
1840
+ statusResponse(response, 200, phase, () => {
1841
+ if (isTerminalPagePhase(phase)) {
1842
+ page.terminalRead = true;
1843
+ page.notifyTerminalRead?.();
1844
+ }
1845
+ });
1846
+ return true;
1847
+ }
1848
+ function rejectedCallbackResponse(response, status2) {
1849
+ const page = callbackPage();
1850
+ callbackResponse(response, status2, page.html, page.nonce);
1851
+ }
1852
+ function parseCallbackRequest(request3) {
1853
+ if (request3.method !== "GET" || !request3.url || !request3.url.startsWith("/") || request3.url.length > 16384) {
1854
+ return { reason: "malformed_response" };
1855
+ }
1856
+ if (request3.headers["transfer-encoding"] || Number(request3.headers["content-length"] ?? 0) > 0) {
1857
+ return { reason: "malformed_response" };
1858
+ }
1859
+ const callbackBase = `http://${MCP_LOOPBACK_REDIRECT_POLICY.host}`;
1860
+ if (!URL.canParse(request3.url, callbackBase)) return { reason: "malformed_response" };
1861
+ const url = new URL(request3.url, callbackBase);
1862
+ if (url.pathname !== MCP_LOOPBACK_REDIRECT_POLICY.path || url.hash) {
1863
+ return { reason: "malformed_response" };
1864
+ }
1865
+ for (const parameter of url.search.slice(1).split("&")) {
1866
+ const separator = parameter.indexOf("=");
1867
+ const rawKey = separator === -1 ? parameter : parameter.slice(0, separator);
1868
+ let key;
1869
+ try {
1870
+ key = decodeURIComponent(rawKey.replaceAll("+", " "));
1871
+ } catch (_error) {
1872
+ continue;
1873
+ }
1874
+ if (!KNOWN_CALLBACK_PARAMETERS.has(key)) continue;
1875
+ const rawValue = separator === -1 ? "" : parameter.slice(separator + 1);
1876
+ try {
1877
+ decodeURIComponent(rawValue.replaceAll("+", " "));
1878
+ } catch (_error) {
1879
+ return { reason: "malformed_response" };
1880
+ }
1881
+ }
1882
+ const params = url.searchParams;
1883
+ for (const key of ["state", "code", "error", "error_description", "iss"]) {
1884
+ if (params.getAll(key).length > 1) return { reason: "malformed_response" };
1885
+ }
1886
+ const state = params.get("state");
1887
+ const code = params.get("code");
1888
+ const error2 = params.get("error");
1889
+ const errorDescription = params.get("error_description");
1890
+ const issuer = params.get("iss");
1891
+ if (!state || state.length > 2048 || Boolean(code) === Boolean(error2) || code !== null && (!code || code.length > 8192) || error2 !== null && (!error2 || error2.length > 256) || errorDescription !== null && (!error2 || errorDescription.length > 2048) || issuer !== null && (!issuer || issuer.length > 2048)) {
1892
+ return { reason: "malformed_response" };
1893
+ }
1894
+ return {
1895
+ callback: {
1896
+ state,
1897
+ ...code === null ? {} : { code },
1898
+ ...error2 === null ? {} : { error: error2 },
1899
+ ...errorDescription === null ? {} : { error_description: errorDescription },
1900
+ ...issuer === null ? {} : { iss: issuer }
1901
+ }
1902
+ };
1903
+ }
1904
+ function reportProgress(options, event, message, details = {}) {
1905
+ if (options.json) {
1906
+ console.error(JSON.stringify({ event, ...details }));
1907
+ } else {
1908
+ console.error(message);
1909
+ }
1910
+ }
1911
+ function rejectCallback(response, options, reason) {
1912
+ rejectedCallbackResponse(response, 400);
1913
+ reportProgress(options, "callback_rejected", callbackRejectionMessage(reason), {
1914
+ reason,
1915
+ action: "still_waiting"
1916
+ });
1917
+ }
1918
+ function callbackRejectionMessage(reason) {
1919
+ switch (reason) {
1920
+ case "malformed_response":
1921
+ return "The callback had a malformed response; authorization is still waiting for a valid response. Retry authorization if needed.";
1922
+ case "state_mismatch":
1923
+ return "The callback had a state mismatch; authorization is still waiting for a valid response. Retry authorization if needed.";
1924
+ case "issuer_missing":
1925
+ return "The callback was missing its issuer; authorization is still waiting for a valid response. Update the provider or retry authorization.";
1926
+ case "issuer_mismatch":
1927
+ return "The callback had an issuer mismatch; authorization is still waiting for a valid response. Retry authorization if needed.";
1928
+ case "issuer_unavailable":
1929
+ return "The Evident endpoint has issuer validation unavailable; authorization is still waiting for a valid response. Update the endpoint or start a new authorization.";
1930
+ case "attempt_not_ready":
1931
+ return "The authorization attempt is not ready yet; authorization is still waiting for a valid response while Evident finishes starting it.";
1932
+ case "attempt_expired":
1933
+ return "The authorization attempt expired; authorization is still waiting for a valid response. Start a new authorization.";
1934
+ }
1935
+ }
1936
+ function handleCallbackRequest(request3, response, waiter, options, page) {
1937
+ if (handleStatusRequest(request3, response, page)) return;
1938
+ if (!request3.url || !request3.url.startsWith("/") || !URL.canParse(request3.url, `http://${MCP_LOOPBACK_REDIRECT_POLICY.host}`)) {
1939
+ rejectCallback(response, options, "malformed_response");
1940
+ return;
1941
+ }
1942
+ const pathname = new URL(request3.url, `http://${MCP_LOOPBACK_REDIRECT_POLICY.host}`).pathname;
1943
+ if (pathname !== MCP_LOOPBACK_REDIRECT_POLICY.path) {
1944
+ rejectedCallbackResponse(response, 404);
1945
+ return;
1946
+ }
1947
+ if (request3.method !== "GET") {
1948
+ response.setHeader("Allow", "GET");
1949
+ rejectedCallbackResponse(response, 405);
1950
+ return;
1951
+ }
1952
+ if (waiter.accepted) {
1953
+ rejectedCallbackResponse(response, 409);
1954
+ return;
1955
+ }
1956
+ const parsed = parseCallbackRequest(request3);
1957
+ if (!("callback" in parsed)) {
1958
+ rejectCallback(response, options, parsed.reason);
1959
+ return;
1960
+ }
1961
+ const callback = parsed.callback;
1962
+ const expiresAtMs = waiter.expiresAtMs;
1963
+ let rejectionReason;
1964
+ if (expiresAtMs === void 0) {
1965
+ rejectionReason = "attempt_not_ready";
1966
+ } else if (Date.now() >= expiresAtMs) {
1967
+ rejectionReason = "attempt_expired";
1968
+ } else if (!waiter.expectedState || callback.state !== waiter.expectedState) {
1969
+ rejectionReason = "state_mismatch";
1970
+ } else if (waiter.issuerParameterSupported && callback.iss === void 0) {
1971
+ rejectionReason = "issuer_missing";
1972
+ } else if (callback.iss !== void 0 && waiter.expectedIssuer === void 0) {
1973
+ rejectionReason = "issuer_unavailable";
1974
+ } else if (callback.iss !== void 0 && callback.iss !== waiter.expectedIssuer) {
1975
+ rejectionReason = "issuer_mismatch";
1976
+ }
1977
+ if (rejectionReason) {
1978
+ rejectCallback(response, options, rejectionReason);
1979
+ return;
1980
+ }
1981
+ waiter.accepted = true;
1982
+ page.phase = "received";
1983
+ reportProgress(options, "callback_received", "Provider sign-in response received.");
1984
+ const callbackPageResponse = callbackPage(`/_status/${page.capability}`);
1985
+ callbackResponse(
1986
+ response,
1987
+ 200,
1988
+ callbackPageResponse.html,
1989
+ callbackPageResponse.nonce,
1990
+ () => waiter.resolve?.(callback)
1991
+ );
1992
+ }
1993
+ function listen(server, port) {
1994
+ return new Promise((resolve6, reject) => {
1995
+ const onError = (error2) => reject(error2);
1996
+ server.once("error", onError);
1997
+ server.listen(port, MCP_LOOPBACK_REDIRECT_POLICY.host, () => {
1998
+ server.removeListener("error", onError);
1999
+ const address = server.address();
2000
+ if (!address || typeof address === "string") {
2001
+ reject(new Error("The local callback listener did not report a TCP port."));
2002
+ return;
2003
+ }
2004
+ resolve6(address.port);
2005
+ });
2006
+ });
2007
+ }
2008
+ function isAddressInUse(error2) {
2009
+ return typeof error2 === "object" && error2 !== null && "code" in error2 && error2.code === "EADDRINUSE";
2010
+ }
2011
+ async function bindCallbackListener(waiter, options, page) {
2012
+ const createListener = () => createServer(
2013
+ (request3, response) => handleCallbackRequest(request3, response, waiter, options, page)
2014
+ );
2015
+ try {
2016
+ const server2 = createListener();
2017
+ return { server: server2, port: await listen(server2, MCP_LOOPBACK_REDIRECT_POLICY.preferred_port) };
2018
+ } catch (error2) {
2019
+ if (!isAddressInUse(error2)) {
2020
+ throw new Error(
2021
+ `Could not listen on 127.0.0.1:${MCP_LOOPBACK_REDIRECT_POLICY.preferred_port}: ${error2 instanceof Error ? error2.message : String(error2)}`
2022
+ );
2023
+ }
2024
+ }
2025
+ const server = createListener();
2026
+ try {
2027
+ return { server, port: await listen(server, 0) };
2028
+ } catch (error2) {
2029
+ throw new Error(
2030
+ `Could not bind the local callback listener on preferred port ${MCP_LOOPBACK_REDIRECT_POLICY.preferred_port} or an ephemeral port: ${error2 instanceof Error ? error2.message : String(error2)}`
2031
+ );
2032
+ }
2033
+ }
2034
+ function waitForCallback(waiter, expiresAtMs, signal) {
2035
+ return new Promise((resolve6, reject) => {
2036
+ const remainingMs = expiresAtMs - Date.now();
2037
+ if (remainingMs <= 0) {
2038
+ reject(new CallbackExpiredError());
2039
+ return;
2040
+ }
2041
+ if (signal.aborted) {
2042
+ reject(new InterruptedError());
2043
+ return;
2044
+ }
2045
+ let settled = false;
2046
+ function settle(callback, error2) {
2047
+ if (settled) return;
2048
+ settled = true;
2049
+ clearTimeout(timer);
2050
+ signal.removeEventListener("abort", onAbort);
2051
+ waiter.resolve = void 0;
2052
+ if (error2) reject(error2);
2053
+ else resolve6(callback);
2054
+ }
2055
+ const onAbort = () => settle(void 0, new InterruptedError());
2056
+ const timer = setTimeout(() => settle(void 0, new CallbackExpiredError()), remainingMs);
2057
+ waiter.expiresAtMs = expiresAtMs;
2058
+ waiter.resolve = (callback) => settle(callback);
2059
+ timer.unref?.();
2060
+ signal.addEventListener("abort", onAbort, { once: true });
2061
+ if (signal.aborted) onAbort();
2062
+ });
2063
+ }
2064
+ function authorizationState(authorizationUrl) {
2065
+ let url;
2066
+ try {
2067
+ url = new URL(authorizationUrl);
2068
+ } catch (error2) {
2069
+ throw new Error(
2070
+ `Evident returned an invalid authorization URL: ${error2 instanceof Error ? error2.message : String(error2)}`
2071
+ );
2072
+ }
2073
+ const states = url.searchParams.getAll("state");
2074
+ if (url.protocol !== "https:" || url.username || url.password || url.hash || states.length !== 1 || !states[0]) {
2075
+ throw new Error("Evident returned an unsafe or incomplete authorization URL.");
2076
+ }
2077
+ return { url, state: states[0] };
2078
+ }
2079
+ function apiFailureMessage(error2) {
2080
+ const context = `Evident returned HTTP ${error2.status} while ${error2.operation}.`;
2081
+ switch (error2.status) {
2082
+ case 400:
2083
+ return `${context} Retry the command; if it continues, update the CLI and try again.`;
2084
+ case 401:
2085
+ return `${context} Your Evident user session is missing or expired. If EVIDENT_TOKEN is set, update or unset it; otherwise run \`evident login\` for the selected endpoint, then retry.`;
2086
+ case 403:
2087
+ return `${context} Only workspace owners and admins can authorize MCP connections. Ask a workspace admin for access.`;
2088
+ case 404:
2089
+ return `${context} Confirm the proxy and connection IDs and that this CLI user can access the proxy.`;
2090
+ case 409:
2091
+ return `${context} This connection does not support local sign-in. Use its hosted authorization flow in Evident.`;
2092
+ case 502:
2093
+ case 503:
2094
+ return `${context} The Evident MCP authorization service is unavailable. Retry shortly or contact your workspace admin.`;
2095
+ default:
2096
+ return `${context} Check your endpoint and retry.`;
2097
+ }
2098
+ }
2099
+ function completionFailureMessage(reason) {
2100
+ switch (reason) {
2101
+ case "state_unknown":
2102
+ return "This sign-in was started by another user or could not be found. Start a new authorization from the same user account.";
2103
+ case "state_consumed":
2104
+ return "This sign-in was already used. Start a new authorization.";
2105
+ case "state_expired":
2106
+ return "This sign-in attempt expired. Start a new authorization.";
2107
+ case "issuer_unavailable":
2108
+ return "This sign-in attempt predates issuer validation. Start a new authorization.";
2109
+ case "issuer_missing":
2110
+ return "The provider response did not include its required issuer. Start a new authorization and update the CLI if needed.";
2111
+ case "issuer_mismatch":
2112
+ return "The provider response came from an unexpected issuer. Start a new authorization and contact support if it continues.";
2113
+ case "invalid_response":
2114
+ return "The provider returned an invalid sign-in response. Start a new authorization.";
2115
+ case "provider_denied":
2116
+ return "The provider denied the sign-in. Retry and approve the requested access.";
2117
+ case "provider_error":
2118
+ return "The provider could not complete sign-in. Retry, or contact the provider if it continues.";
2119
+ case "exchange_failed":
2120
+ return "The provider sign-in completed, but Evident could not exchange the authorization. Retry or contact support.";
2121
+ case "reconcile_failed":
2122
+ case "tools_pending":
2123
+ return "Sign-in completed, but Evident could not finish setting up this connection. Retry or contact support.";
2124
+ case "not_configured":
2125
+ return "Local authorization is not configured for this Evident environment. Contact your workspace admin.";
2126
+ default:
2127
+ return "Evident could not complete this sign-in. Start a new authorization and try again.";
2128
+ }
2129
+ }
2130
+ function printLink(options, url, reason) {
2131
+ if (options.json) {
2132
+ console.error(JSON.stringify({ event: "authorization_required", authorization_url: url.href }));
2133
+ return;
2134
+ }
2135
+ printWarning(reason ?? "Open this authorization URL in your browser:");
2136
+ console.log(url.href);
2137
+ }
2138
+ function printResult(options, proxyId, connectionId, error2, successMessage = "MCP connection authorized.", reason) {
2139
+ if (options.json) {
2140
+ console.log(
2141
+ JSON.stringify({
2142
+ ok: !error2,
2143
+ proxy_id: proxyId,
2144
+ connection_id: connectionId,
2145
+ ...error2 ? { error: error2 } : {},
2146
+ ...reason ? { reason } : {}
2147
+ })
2148
+ );
2149
+ } else if (error2) {
2150
+ printError(error2);
2151
+ } else {
2152
+ printSuccess(successMessage);
2153
+ }
2154
+ }
2155
+ function errorMessage(error2) {
2156
+ if (error2 instanceof ApiHttpError) return apiFailureMessage(error2);
2157
+ if (error2 instanceof CallbackExpiredError) {
2158
+ return "The sign-in attempt expired before the provider returned. Run the command again.";
2159
+ }
2160
+ if (error2 instanceof InterruptedError) return "Authorization was interrupted.";
2161
+ if (error2 instanceof Error) return error2.message;
2162
+ return `Authorization failed: ${String(error2)}`;
2163
+ }
2164
+ function requestFailed(reason) {
2165
+ if (reason instanceof Error) throw reason;
2166
+ throw new Error(`Authorization failed: ${String(reason)}`);
2167
+ }
2168
+ function validateConnectionList(value) {
2169
+ if (!value || !Array.isArray(value.mcp_proxy_connections)) {
2170
+ throw new Error("Evident returned an invalid MCP connection list. Update the CLI and retry.");
2171
+ }
2172
+ return value.mcp_proxy_connections;
2173
+ }
2174
+ function validateBeginResponse(value) {
2175
+ if (!value || typeof value.authorization_url !== "string" || typeof value.expires_at !== "string" || !Number.isFinite(Date.parse(value.expires_at)) || value.issuer !== void 0 && (typeof value.issuer !== "string" || value.issuer.length === 0 || value.issuer.length > 2048) || value.authorization_response_iss_parameter_supported !== void 0 && typeof value.authorization_response_iss_parameter_supported !== "boolean" || value.issuer === void 0 !== (value.authorization_response_iss_parameter_supported === void 0)) {
2176
+ throw new Error(
2177
+ "Evident returned an invalid local authorization attempt. Update the CLI and retry."
2178
+ );
2179
+ }
2180
+ }
2181
+ async function startBrowser(url) {
2182
+ const child = await open2(url);
2183
+ let signalFailure = () => void 0;
2184
+ const failure = new Promise((resolve6) => {
2185
+ signalFailure = resolve6;
2186
+ });
2187
+ child.once("error", signalFailure);
2188
+ child.once("close", (code) => {
2189
+ if (code !== 0) signalFailure();
2190
+ });
2191
+ await new Promise((resolve6, reject) => {
2192
+ if (child.pid !== void 0) {
2193
+ resolve6();
2194
+ return;
2195
+ }
2196
+ child.once("spawn", resolve6);
2197
+ child.once("error", reject);
2198
+ });
2199
+ return { failure };
2200
+ }
2201
+ function closeServer(server, force) {
2202
+ if (!server.listening) return Promise.resolve();
2203
+ return new Promise((resolve6, reject) => {
2204
+ server.close((error2) => error2 ? reject(error2) : resolve6());
2205
+ if (force) server.closeAllConnections();
2206
+ });
2207
+ }
2208
+ async function authorizeMcpConnection(proxyId, connectionId, options = {}) {
2209
+ let credentials2;
2210
+ try {
2211
+ credentials2 = await getAuthCredentials();
2212
+ } catch (error2) {
2213
+ const kind = error2 instanceof Error ? error2.name : "unknown error";
2214
+ printResult(
2215
+ options,
2216
+ proxyId,
2217
+ connectionId,
2218
+ `Could not read the saved Evident credentials (${kind}). Check keychain access or run evident login again.`
2219
+ );
2220
+ process.exitCode = 1;
2221
+ return;
2222
+ }
2223
+ if (!credentials2) {
2224
+ printResult(
2225
+ options,
2226
+ proxyId,
2227
+ connectionId,
2228
+ "No credentials found. Run `evident login` and retry."
2229
+ );
2230
+ process.exitCode = 1;
2231
+ return;
2232
+ }
2233
+ if (credentials2.authType !== "bearer") {
2234
+ printResult(
2235
+ options,
2236
+ proxyId,
2237
+ connectionId,
2238
+ "MCP authorization requires a user login, not a runner key. Unset EVIDENT_RUNNER_KEY/EVIDENT_AGENT_KEY, then run `evident login`."
2239
+ );
2240
+ process.exitCode = 1;
2241
+ return;
2242
+ }
2243
+ const waiter = { accepted: false };
2244
+ const page = {
2245
+ capability: randomBytes(32).toString("base64url"),
2246
+ phase: "waiting",
2247
+ terminalRead: false
2248
+ };
2249
+ let server;
2250
+ let closePromise;
2251
+ let closeFailureLogged = false;
2252
+ let failure;
2253
+ let successMessage = "MCP connection authorized.";
2254
+ let completionReason;
2255
+ const cancelController = new AbortController();
2256
+ const closeListener = (force = false) => {
2257
+ if (!server || closePromise) return closePromise ?? Promise.resolve();
2258
+ closePromise = closeServer(server, force);
2259
+ return closePromise;
2260
+ };
2261
+ const onSigint = () => {
2262
+ cancelController.abort();
2263
+ void closeListener(true).catch((error2) => {
2264
+ closeFailureLogged = true;
2265
+ console.error(
2266
+ `[mcp authorize] listener shutdown failed for proxy_id=${JSON.stringify(proxyId)} connection_id=${JSON.stringify(connectionId)}: ${error2 instanceof Error ? error2.message : String(error2)}`
2267
+ );
2268
+ });
2269
+ };
2270
+ try {
2271
+ const listener = await bindCallbackListener(waiter, options, page);
2272
+ server = listener.server;
2273
+ process.once("SIGINT", onSigint);
2274
+ page.host = `${MCP_LOOPBACK_REDIRECT_POLICY.host}:${listener.port}`;
2275
+ page.origin = `${MCP_LOOPBACK_REDIRECT_POLICY.scheme}://${page.host}`;
2276
+ const redirectUri = `${MCP_LOOPBACK_REDIRECT_POLICY.scheme}://${MCP_LOOPBACK_REDIRECT_POLICY.host}:${listener.port}${MCP_LOOPBACK_REDIRECT_POLICY.path}`;
2277
+ const fallback = listener.port !== MCP_LOOPBACK_REDIRECT_POLICY.preferred_port;
2278
+ reportProgress(
2279
+ options,
2280
+ fallback ? "listener_fallback" : "listener_ready",
2281
+ fallback ? `Port ${MCP_LOOPBACK_REDIRECT_POLICY.preferred_port} is busy; listening at ${redirectUri}.` : `Listening for the sign-in response at ${redirectUri}.`,
2282
+ {
2283
+ callback_url: redirectUri,
2284
+ ...fallback ? { preferred_port: MCP_LOOPBACK_REDIRECT_POLICY.preferred_port } : {},
2285
+ port: listener.port
2286
+ }
2287
+ );
2288
+ const connectionList = await requestJson(
2289
+ apiPath(proxyId),
2290
+ credentials2,
2291
+ cancelController.signal,
2292
+ "checking the MCP connection"
2293
+ );
2294
+ const connection = validateConnectionList(connectionList).find(
2295
+ (candidate) => candidate.connection_id === connectionId
2296
+ );
2297
+ if (!connection)
2298
+ throw new Error("The MCP connection was not found. Check the connection ID and try again.");
2299
+ if (connection.authorization_mode !== "local") {
2300
+ throw new Error("This connection uses hosted sign-in. Authorize it from Evident instead.");
2301
+ }
2302
+ if (connection.auth_kind !== "oauth2") {
2303
+ throw new Error("This MCP connection does not support OAuth authorization.");
2304
+ }
2305
+ reportProgress(options, "authorization_starting", "Starting authorization with Evident.");
2306
+ const begin = await requestJson(
2307
+ apiPath(proxyId, connectionId, "begin"),
2308
+ credentials2,
2309
+ cancelController.signal,
2310
+ "starting local authorization",
2311
+ { redirect_uri: redirectUri }
2312
+ );
2313
+ validateBeginResponse(begin);
2314
+ const { url: authorizationUrl, state } = authorizationState(begin.authorization_url);
2315
+ waiter.expectedState = state;
2316
+ waiter.expectedIssuer = begin.issuer;
2317
+ waiter.issuerParameterSupported = begin.authorization_response_iss_parameter_supported;
2318
+ const expiresAtMs = Date.parse(begin.expires_at);
2319
+ if (expiresAtMs <= Date.now()) throw new CallbackExpiredError();
2320
+ waiter.expiresAtMs = expiresAtMs;
2321
+ const callbackOutcome = waitForCallback(waiter, expiresAtMs, cancelController.signal).then(
2322
+ (callback2) => ({ ok: true, callback: callback2 }),
2323
+ (error2) => ({ ok: false, error: error2 })
2324
+ );
2325
+ const waitForCallbackWithProgress = (linkReason) => {
2326
+ if (linkReason) printLink(options, authorizationUrl, linkReason);
2327
+ reportProgress(
2328
+ options,
2329
+ "waiting_for_callback",
2330
+ "Waiting for the provider to return to this computer."
2331
+ );
2332
+ return (async () => {
2333
+ const outcome = await callbackOutcome;
2334
+ if (!outcome.ok) requestFailed(outcome.error);
2335
+ return outcome.callback;
2336
+ })();
2337
+ };
2338
+ let callback;
2339
+ if (options.noBrowser) {
2340
+ callback = await waitForCallbackWithProgress("Open this authorization URL in your browser:");
2341
+ } else {
2342
+ reportProgress(
2343
+ options,
2344
+ "opening_browser",
2345
+ "Opening the provider authorization page in your browser."
2346
+ );
2347
+ const browserOutcome = startBrowser(authorizationUrl.href).then(
2348
+ ({ failure: browserFailure }) => ({ ok: true, failure: browserFailure }),
2349
+ () => ({ ok: false })
2350
+ );
2351
+ const first = await Promise.race([
2352
+ browserOutcome.then((outcome) => ({ kind: "browser", outcome })),
2353
+ callbackOutcome.then((outcome) => ({ kind: "callback", outcome }))
2354
+ ]);
2355
+ if (first.kind === "callback") {
2356
+ if (!first.outcome.ok) requestFailed(first.outcome.error);
2357
+ callback = first.outcome.callback;
2358
+ } else {
2359
+ if (!first.outcome.ok) {
2360
+ callback = await waitForCallbackWithProgress(
2361
+ "Could not open the browser automatically. Open this URL:"
2362
+ );
2363
+ } else {
2364
+ const callbackWait = waitForCallbackWithProgress();
2365
+ const waitOutcome = await Promise.race([
2366
+ callbackWait.then(
2367
+ (value) => ({ kind: "callback", value }),
2368
+ (error2) => ({ kind: "callback_error", error: error2 })
2369
+ ),
2370
+ first.outcome.failure.then(() => ({ kind: "browser_failure" }))
2371
+ ]);
2372
+ if (waitOutcome.kind === "callback") {
2373
+ callback = waitOutcome.value;
2374
+ } else if (waitOutcome.kind === "callback_error") {
2375
+ requestFailed(waitOutcome.error);
2376
+ } else {
2377
+ printLink(
2378
+ options,
2379
+ authorizationUrl,
2380
+ "The browser could not keep the authorization page open. Open this URL:"
2381
+ );
2382
+ callback = await callbackWait;
2383
+ }
2384
+ }
2385
+ }
2386
+ }
2387
+ reportProgress(options, "forwarding_callback", "Forwarding the sign-in response to Evident.");
2388
+ const completionBody = {
2389
+ state: callback.state,
2390
+ ...callback.code === void 0 ? {} : { code: callback.code },
2391
+ ...callback.error === void 0 ? {} : { error: callback.error },
2392
+ ...callback.error_description === void 0 ? {} : { error_description: callback.error_description },
2393
+ ...callback.iss === void 0 ? {} : { iss: callback.iss }
2394
+ };
2395
+ reportProgress(options, "completing_authorization", "Completing authorization with Evident.");
2396
+ page.phase = "completing";
2397
+ const completion = await requestJson(
2398
+ apiPath(proxyId, connectionId, "complete"),
2399
+ credentials2,
2400
+ cancelController.signal,
2401
+ "completing local authorization",
2402
+ completionBody
2403
+ );
2404
+ if (completion.outcome === "success") {
2405
+ if (completion.reason === "tools_pending") {
2406
+ completionReason = completion.reason;
2407
+ page.phase = "tools_pending";
2408
+ reportProgress(
2409
+ options,
2410
+ "tools_pending",
2411
+ "Authorization confirmed; Evident is still preparing its tools."
2412
+ );
2413
+ successMessage = "MCP connection authorized. Evident is still preparing its tools.";
2414
+ } else {
2415
+ page.phase = "success";
2416
+ }
2417
+ } else {
2418
+ page.phase = "failed";
2419
+ failure = completionFailureMessage(completion.reason);
2420
+ }
2421
+ } catch (error2) {
2422
+ if (waiter.accepted && !isTerminalPagePhase(page.phase)) {
2423
+ page.phase = "unconfirmed";
2424
+ failure = `${COMPLETION_UNCONFIRMED_MESSAGE} ${errorMessage(error2)}`;
2425
+ } else {
2426
+ failure = errorMessage(error2);
2427
+ }
2428
+ } finally {
2429
+ try {
2430
+ if (waiter.accepted && isTerminalPagePhase(page.phase) && !cancelController.signal.aborted) {
2431
+ await waitForTerminalStatusRead(page, cancelController.signal);
2432
+ }
2433
+ process.removeListener("SIGINT", onSigint);
2434
+ await closeListener();
2435
+ } catch (error2) {
2436
+ const detail = error2 instanceof Error ? error2.message : String(error2);
2437
+ if (!closeFailureLogged) {
2438
+ console.error(
2439
+ `[mcp authorize] listener teardown failed for proxy_id=${JSON.stringify(proxyId)} connection_id=${JSON.stringify(connectionId)}: ${detail}`
2440
+ );
2441
+ }
2442
+ failure ??= "The local callback listener could not be closed cleanly. Check for a lingering process and retry.";
2443
+ }
2444
+ }
2445
+ printResult(options, proxyId, connectionId, failure, successMessage, completionReason);
2446
+ if (failure) process.exitCode = cancelController.signal.aborted ? 130 : 1;
2447
+ }
2448
+
1475
2449
  // src/commands/run.ts
2450
+ import { randomUUID as randomUUID2 } from "node:crypto";
2451
+ import { chmodSync as chmodSync3, existsSync as existsSync3, readFileSync as readFileSync12, writeFileSync as writeFileSync9 } from "node:fs";
2452
+ import { homedir as homedir9 } from "node:os";
2453
+ import { isAbsolute as isAbsolute6, join as join17, parse, resolve as resolvePath2 } from "node:path";
2454
+ import chalk7 from "chalk";
1476
2455
  import ora4 from "ora";
1477
2456
  import { select as select4 } from "@inquirer/prompts";
1478
2457
 
2458
+ // src/lib/opencode-start-timeout.ts
2459
+ var OPENCODE_START_TIMEOUT_ENV = "EVIDENT_OPENCODE_START_TIMEOUT";
2460
+
1479
2461
  // src/lib/telemetry.ts
1480
- var CLI_VERSION = (true ? "3.6.1-dev.22aa800" : void 0) ?? process.env.npm_package_version ?? "unknown";
2462
+ var CLI_VERSION = (true ? "3.6.1-dev.240ba07" : void 0) ?? process.env.npm_package_version ?? "unknown";
1481
2463
  function getCliVersion() {
1482
2464
  return CLI_VERSION;
1483
2465
  }
@@ -1668,13 +2650,29 @@ function redactDiagnosticText(message) {
1668
2650
  const redacted = message.replace(/esk_[A-Za-z0-9_-]+/g, "esk_***").replace(/ct_[A-Za-z0-9_-]+/g, "ct_***").replace(/(?<![A-Za-z0-9_-])sk-ant-[A-Za-z0-9_-]{20,}(?![A-Za-z0-9_-])/g, "sk-ant-***").replace(/(?<![A-Za-z0-9_-])sk-proj-[A-Za-z0-9_-]{20,}(?![A-Za-z0-9_-])/g, "sk-proj-***").replace(/(?<![A-Za-z0-9_-])sk-[A-Za-z0-9]{20,}(?![A-Za-z0-9_-])/g, "sk-***").replace(/(?<![A-Za-z0-9_-])(gh[oprsu])_[A-Za-z0-9]{20,}(?![A-Za-z0-9_-])/g, "$1_***").replace(/(?<![A-Za-z0-9_-])github_pat_[A-Za-z0-9_]{20,}(?![A-Za-z0-9_-])/g, "github_pat_***").replace(/https?:\/\/\S+/g, "<url>");
1669
2651
  return redactHomeDirectory(redacted);
1670
2652
  }
2653
+ function describeErrorWithCause(error2) {
2654
+ const base = error2 instanceof Error ? error2.message : String(error2);
2655
+ const cause = error2 instanceof Error ? error2.cause : void 0;
2656
+ let detail;
2657
+ if (cause instanceof Error) {
2658
+ const causeWithCode = cause;
2659
+ detail = cause.message || (typeof causeWithCode.code === "string" ? causeWithCode.code : void 0) || cause.name;
2660
+ } else if (cause !== null && typeof cause === "object") {
2661
+ const causeRecord = cause;
2662
+ detail = typeof causeRecord.message === "string" && causeRecord.message || typeof causeRecord.code === "string" && causeRecord.code || void 0;
2663
+ } else if (typeof cause === "string") {
2664
+ detail = cause;
2665
+ }
2666
+ if (!detail || base.includes(detail)) return base;
2667
+ return `${base} (${redactDiagnosticText(detail).slice(0, 200)})`;
2668
+ }
1671
2669
 
1672
2670
  // src/lib/opencode/session-db-reclaim.ts
1673
2671
  var SESSION_DB_RECLAIM_CHUNK_PAGES = 100;
1674
2672
  var SESSION_DB_RECLAIM_TIME_BUDGET_MS = 500;
1675
2673
  var SESSION_DB_RECLAIM_PAGE_CEILING = 4e4;
1676
2674
  var SESSION_DB_RECLAIM_BUSY_TIMEOUT_MS = 5e3;
1677
- function errorMessage(error2) {
2675
+ function errorMessage2(error2) {
1678
2676
  if (!(error2 instanceof Error)) return String(error2);
1679
2677
  return error2.cause instanceof Error ? error2.cause.message : error2.message;
1680
2678
  }
@@ -1808,7 +2806,7 @@ async function probeReclaimAvailability(input) {
1808
2806
  try {
1809
2807
  sqlite = await import("node:sqlite");
1810
2808
  } catch (err) {
1811
- const detail = `Node ${process.version}: ${errorMessage(err)}`;
2809
+ const detail = `Node ${process.version}: ${errorMessage2(err)}`;
1812
2810
  console.warn(`[probeReclaimAvailability] node:sqlite unavailable for ${dbPath}: ` + detail);
1813
2811
  return { reason: "sqlite-unavailable", detail };
1814
2812
  }
@@ -1843,7 +2841,7 @@ async function reclaimSessionDbSpace(input) {
1843
2841
  try {
1844
2842
  sqlite = await import("node:sqlite");
1845
2843
  } catch (err) {
1846
- const detail = `Node ${process.version}: ${errorMessage(err)}`;
2844
+ const detail = `Node ${process.version}: ${errorMessage2(err)}`;
1847
2845
  console.warn(
1848
2846
  `[reclaimSessionDbSpace] node:sqlite unavailable (need Node >=22.5, >=22.13 unflagged) for ${dbPath}: ${detail}`
1849
2847
  );
@@ -1954,11 +2952,11 @@ async function reclaimSessionDbSpace(input) {
1954
2952
  );
1955
2953
  return { ok: false, skipped: "auto-vacuum-not-applicable" };
1956
2954
  } catch (err) {
1957
- console.error(`[reclaimSessionDbSpace] reclaim failed for ${dbPath}: ` + errorMessage(err));
2955
+ console.error(`[reclaimSessionDbSpace] reclaim failed for ${dbPath}: ` + errorMessage2(err));
1958
2956
  return {
1959
2957
  ok: false,
1960
2958
  skipped: isSessionStoreWriteFailure(err) ? "disk-exhaustion" : "reclaim-error",
1961
- detail: errorMessage(err)
2959
+ detail: errorMessage2(err)
1962
2960
  };
1963
2961
  } finally {
1964
2962
  db?.close();
@@ -3110,7 +4108,7 @@ function buildSessionArchive(input) {
3110
4108
  function isRecord2(value) {
3111
4109
  return typeof value === "object" && value !== null && !Array.isArray(value);
3112
4110
  }
3113
- function errorMessage2(error2) {
4111
+ function errorMessage3(error2) {
3114
4112
  return error2 instanceof Error ? error2.message : String(error2);
3115
4113
  }
3116
4114
  function invalidResponse(version2, sessionId, path, reason) {
@@ -3128,7 +4126,7 @@ async function requestPage(client, sessionId, path, signal) {
3128
4126
  } catch (error2) {
3129
4127
  throw new SessionArchiveExportError(
3130
4128
  "request-failed",
3131
- `OpenCode ${client.version} session ${sessionId} request GET ${path} failed: ${errorMessage2(error2)}`
4129
+ `OpenCode ${client.version} session ${sessionId} request GET ${path} failed: ${errorMessage3(error2)}`
3132
4130
  );
3133
4131
  }
3134
4132
  if (response.status === 404) {
@@ -3149,7 +4147,7 @@ async function requestPage(client, sessionId, path, signal) {
3149
4147
  } catch (error2) {
3150
4148
  throw new SessionArchiveExportError(
3151
4149
  "request-failed",
3152
- `OpenCode ${client.version} session ${sessionId} response body from GET ${path} could not be read: ${errorMessage2(error2)}`
4150
+ `OpenCode ${client.version} session ${sessionId} response body from GET ${path} could not be read: ${errorMessage3(error2)}`
3153
4151
  );
3154
4152
  }
3155
4153
  try {
@@ -3184,7 +4182,7 @@ function v1NextCursor(response, sessionId, path) {
3184
4182
  } catch (error2) {
3185
4183
  throw new SessionArchiveExportError(
3186
4184
  "pagination-failed",
3187
- `OpenCode v1 session ${sessionId} returned an invalid next Link for GET ${path}: ${errorMessage2(error2)}`
4185
+ `OpenCode v1 session ${sessionId} returned an invalid next Link for GET ${path}: ${errorMessage3(error2)}`
3188
4186
  );
3189
4187
  }
3190
4188
  }
@@ -3320,7 +4318,7 @@ function isRecord3(value) {
3320
4318
  }
3321
4319
  function isWatermark(value) {
3322
4320
  if (!isRecord3(value)) return false;
3323
- 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");
4321
+ 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");
3324
4322
  }
3325
4323
  function isMissingFile3(error2) {
3326
4324
  return error2 instanceof Error && "code" in error2 && error2.code === "ENOENT";
@@ -3501,6 +4499,37 @@ function isJson(body) {
3501
4499
  return false;
3502
4500
  }
3503
4501
  }
4502
+ function parseArchivePutMetadata(stderr, onMetadataDecodeError) {
4503
+ const prefix = "ARCHIVE-PUT: outcome=ok ";
4504
+ const lines = stderr.split(/\r?\n/);
4505
+ for (let index = lines.length - 1; index >= 0; index -= 1) {
4506
+ const line = lines[index];
4507
+ if (line === void 0) continue;
4508
+ const prefixIndex = line.indexOf(prefix);
4509
+ if (prefixIndex === -1) continue;
4510
+ const record = line.slice(prefixIndex + prefix.length);
4511
+ const versionMatch = /(?:^|\s)version_id=(\S*)/.exec(record);
4512
+ const etagMatch = /(?:^|\s)etag=(\S*)/.exec(record);
4513
+ const decode = (value, field) => {
4514
+ if (value === void 0 || value === "") return null;
4515
+ try {
4516
+ return decodeURIComponent(value);
4517
+ } catch (error2) {
4518
+ onMetadataDecodeError?.(
4519
+ field,
4520
+ error2 instanceof URIError ? "uri-malformed" : "decode-failed"
4521
+ );
4522
+ return null;
4523
+ }
4524
+ };
4525
+ return {
4526
+ metadataReported: versionMatch !== null || etagMatch !== null,
4527
+ versionId: decode(versionMatch?.[1], "version_id"),
4528
+ etag: decode(etagMatch?.[1], "etag")
4529
+ };
4530
+ }
4531
+ return { metadataReported: false, versionId: null, etag: null };
4532
+ }
3504
4533
  async function uploadSessionArchive(key, body, options) {
3505
4534
  const bytes = Buffer.from(body);
3506
4535
  if (bytes.byteLength > MAX_SESSION_ARCHIVE_BYTES) {
@@ -3523,7 +4552,13 @@ async function uploadSessionArchive(key, body, options) {
3523
4552
  );
3524
4553
  }
3525
4554
  if (result.timedOut) return transportFailure(bytes.byteLength, "timeout");
3526
- if (result.code === 0) return { kind: "ok", bytes: bytes.byteLength };
4555
+ if (result.code === 0) {
4556
+ return {
4557
+ kind: "ok",
4558
+ bytes: bytes.byteLength,
4559
+ ...parseArchivePutMetadata(result.stderr, options.onMetadataDecodeError)
4560
+ };
4561
+ }
3527
4562
  if (result.code === EXIT_ARCHIVE_CONFIG_MISSING) {
3528
4563
  return { kind: "config-missing", bytes: bytes.byteLength };
3529
4564
  }
@@ -3741,6 +4776,14 @@ async function runSessionArchive({
3741
4776
  uploadFailures: 0,
3742
4777
  skippedBudget: 0,
3743
4778
  skippedBudgetIds: [],
4779
+ skippedChanged: 0,
4780
+ skippedChangedSessions: [],
4781
+ skippedUnknown: 0,
4782
+ skippedUnknownIds: [],
4783
+ inventoryNeverArchived: 0,
4784
+ inventoryPriorFailures: 0,
4785
+ inventoryKnownChanged: 0,
4786
+ outcomesReconciled: false,
3744
4787
  neverWatermarkedFailures: 0,
3745
4788
  unmappedIds: [],
3746
4789
  conflictedIds: [],
@@ -3757,6 +4800,8 @@ async function runSessionArchive({
3757
4800
  parent: 0
3758
4801
  },
3759
4802
  archivedSessionIds: [],
4803
+ uploadedSessions: [],
4804
+ unchangedSessions: [],
3760
4805
  failures: [],
3761
4806
  staleSince: null
3762
4807
  };
@@ -3780,17 +4825,44 @@ async function runSessionArchive({
3780
4825
  }
3781
4826
  summary.unresolved = summary.unmappedIds.length + summary.conflictedIds.length;
3782
4827
  summary.conflicts = summary.conflictedIds.length;
4828
+ const priorFailureIds = deps.priorFailureIds ?? /* @__PURE__ */ new Set();
4829
+ const knownChanged = /* @__PURE__ */ new Map();
4830
+ for (const session of sessions) {
4831
+ if (!deps.watermarks.has(session.id)) {
4832
+ knownChanged.set(session.id, "no-prior-archive");
4833
+ summary.inventoryNeverArchived++;
4834
+ } else if (priorFailureIds.has(session.id)) {
4835
+ knownChanged.set(session.id, "prior-attempt-failed");
4836
+ summary.inventoryPriorFailures++;
4837
+ }
4838
+ }
4839
+ summary.inventoryKnownChanged = knownChanged.size;
3783
4840
  const failedWatermarks = [];
4841
+ const priorFailureUploads = [];
3784
4842
  const recordFailedWatermark = (watermark) => {
3785
4843
  if (watermark) failedWatermarks.push(watermark.uploaded_at);
3786
4844
  else summary.neverWatermarkedFailures++;
3787
4845
  };
4846
+ const recordBudgetSkip = (startIndex) => {
4847
+ const skippedIds = ordered.slice(startIndex).map(({ id }) => id);
4848
+ summary.skippedBudgetIds.push(...skippedIds);
4849
+ summary.skippedBudget = summary.skippedBudgetIds.length;
4850
+ for (const sessionId of skippedIds) {
4851
+ const reason = knownChanged.get(sessionId);
4852
+ if (reason) {
4853
+ summary.skippedChangedSessions.push({ sessionId, reason });
4854
+ summary.skippedChanged++;
4855
+ } else {
4856
+ summary.skippedUnknownIds.push(sessionId);
4857
+ summary.skippedUnknown++;
4858
+ }
4859
+ }
4860
+ };
3788
4861
  for (let index = 0; index < ordered.length; index++) {
3789
4862
  const session = ordered[index];
3790
4863
  const remainingMs = Math.floor(deadline - now());
3791
4864
  if (remainingMs <= 0 || deps.signal?.aborted) {
3792
- summary.skippedBudgetIds.push(...ordered.slice(index).map(({ id }) => id));
3793
- summary.skippedBudget = summary.skippedBudgetIds.length;
4865
+ recordBudgetSkip(index);
3794
4866
  break;
3795
4867
  }
3796
4868
  const resolution = resolutions.get(session.id) ?? { reason: "unmapped" };
@@ -3815,8 +4887,7 @@ async function runSessionArchive({
3815
4887
  messages = await exportMessages(deps.client, session.id, exportBudget.signal);
3816
4888
  } catch (error2) {
3817
4889
  if (isBudgetExpired(deadline, now, deps.signal) || exportBudget.signal.aborted) {
3818
- summary.skippedBudgetIds.push(...ordered.slice(index).map(({ id }) => id));
3819
- summary.skippedBudget = summary.skippedBudgetIds.length;
4890
+ recordBudgetSkip(index);
3820
4891
  break;
3821
4892
  }
3822
4893
  summary.failed++;
@@ -3834,8 +4905,7 @@ async function runSessionArchive({
3834
4905
  exportBudget.dispose();
3835
4906
  }
3836
4907
  if (isBudgetExpired(deadline, now, deps.signal) || exportBudget.signal.aborted) {
3837
- summary.skippedBudgetIds.push(...ordered.slice(index).map(({ id }) => id));
3838
- summary.skippedBudget = summary.skippedBudgetIds.length;
4908
+ recordBudgetSkip(index);
3839
4909
  break;
3840
4910
  }
3841
4911
  try {
@@ -3854,12 +4924,21 @@ async function runSessionArchive({
3854
4924
  if (existing?.fingerprint === snapshot.content_fingerprint) {
3855
4925
  summary.unchanged++;
3856
4926
  summary.archivedSessionIds.push(session.id);
4927
+ summary.unchangedSessions.push({
4928
+ sessionId: session.id,
4929
+ fingerprint: snapshot.content_fingerprint,
4930
+ watermarkKey: existing.key,
4931
+ watermarkFingerprint: existing.fingerprint,
4932
+ watermarkVersionId: existing.version_id ?? null,
4933
+ watermarkEtag: existing.etag ?? null,
4934
+ watermarkUploadedAt: existing.uploaded_at
4935
+ });
3857
4936
  continue;
3858
4937
  }
3859
4938
  const uploadRemainingMs = Math.floor(deadline - now());
3860
4939
  if (uploadRemainingMs <= 0 || deps.signal?.aborted) {
3861
- summary.skippedBudgetIds.push(...ordered.slice(index).map(({ id }) => id));
3862
- summary.skippedBudget = summary.skippedBudgetIds.length;
4940
+ knownChanged.set(session.id, "fingerprint-differs");
4941
+ recordBudgetSkip(index);
3863
4942
  break;
3864
4943
  }
3865
4944
  summary.uploadAttempts++;
@@ -3868,7 +4947,8 @@ async function runSessionArchive({
3868
4947
  try {
3869
4948
  outcome = await upload(key, JSON.stringify(snapshot), {
3870
4949
  timeoutMs: Math.min(uploadRemainingMs, SESSION_ARCHIVE_UPLOAD_TIMEOUT_MS),
3871
- signal: uploadBudget.signal
4950
+ signal: uploadBudget.signal,
4951
+ onMetadataDecodeError: (field, reason) => deps.onMetadataDecodeError?.(field, reason, session.id)
3872
4952
  });
3873
4953
  } finally {
3874
4954
  uploadBudget.dispose();
@@ -3891,19 +4971,31 @@ async function runSessionArchive({
3891
4971
  });
3892
4972
  recordFailedWatermark(existing);
3893
4973
  if (uploadBudget.signal.aborted) {
3894
- summary.skippedBudgetIds.push(...ordered.slice(index + 1).map(({ id }) => id));
3895
- summary.skippedBudget = summary.skippedBudgetIds.length;
4974
+ recordBudgetSkip(index + 1);
3896
4975
  break;
3897
4976
  }
3898
4977
  continue;
3899
4978
  }
3900
4979
  summary.uploaded++;
3901
4980
  summary.archivedSessionIds.push(session.id);
4981
+ const uploadRecord = {
4982
+ sessionId: session.id,
4983
+ key,
4984
+ fingerprint: snapshot.content_fingerprint,
4985
+ versionId: outcome.versionId,
4986
+ etag: outcome.etag,
4987
+ metadataReported: outcome.metadataReported,
4988
+ retriedPriorFailure: priorFailureIds.has(session.id)
4989
+ };
4990
+ if (uploadRecord.retriedPriorFailure) priorFailureUploads.push(uploadRecord);
4991
+ else summary.uploadedSessions.push(uploadRecord);
3902
4992
  const watermark = {
3903
4993
  fingerprint: snapshot.content_fingerprint,
3904
4994
  uploaded_at: new Date(now()).toISOString(),
3905
4995
  key,
3906
- conversation_id: conversationId
4996
+ conversation_id: conversationId,
4997
+ version_id: outcome.versionId,
4998
+ etag: outcome.etag
3907
4999
  };
3908
5000
  try {
3909
5001
  writeWatermark(deps.watermarkPath, session.id, watermark, deps.watermarks);
@@ -3917,8 +5009,7 @@ async function runSessionArchive({
3917
5009
  }
3918
5010
  } catch (error2) {
3919
5011
  if (isBudgetExpired(deadline, now, deps.signal)) {
3920
- summary.skippedBudgetIds.push(...ordered.slice(index).map(({ id }) => id));
3921
- summary.skippedBudget = summary.skippedBudgetIds.length;
5012
+ recordBudgetSkip(index);
3922
5013
  break;
3923
5014
  }
3924
5015
  summary.failed++;
@@ -3931,10 +5022,115 @@ async function runSessionArchive({
3931
5022
  recordFailedWatermark(deps.watermarks.get(session.id));
3932
5023
  }
3933
5024
  }
5025
+ summary.uploadedSessions = [...priorFailureUploads, ...summary.uploadedSessions];
5026
+ for (const sessionId of summary.archivedSessionIds) priorFailureIds.delete(sessionId);
5027
+ for (const failure of summary.failures) {
5028
+ if (!failure.archived) priorFailureIds.add(failure.sessionId);
5029
+ }
5030
+ summary.outcomesReconciled = summary.uploaded + summary.unchanged + summary.failed + summary.skippedChanged + summary.skippedUnknown === summary.inspected;
3934
5031
  summary.staleSince = failedWatermarks.sort()[0] ?? null;
3935
5032
  return summary;
3936
5033
  }
3937
5034
 
5035
+ // src/lib/opencode/session-archive-manifest.ts
5036
+ var SESSION_ARCHIVE_MANIFEST_SCHEMA_VERSION = 1;
5037
+ function sessionArchiveManifestKey(keyPrefix, identity) {
5038
+ return `${keyPrefix.replace(/\/+$/, "")}/archive-audit/${identity.bootId}-${String(identity.passSequence).padStart(4, "0")}-${identity.phase}.json`;
5039
+ }
5040
+ function buildSessionArchiveManifest(identity, summary) {
5041
+ const failedSessions = summary?.failures.filter(({ archived }) => !archived) ?? [];
5042
+ const watermarkWriteFailures = new Set(
5043
+ summary?.failures.filter(({ archived }) => archived).map(({ sessionId }) => sessionId)
5044
+ );
5045
+ const sessions = summary ? [
5046
+ ...summary.uploadedSessions.map((upload) => ({
5047
+ id: upload.sessionId,
5048
+ outcome: "uploaded",
5049
+ archive_key: upload.key,
5050
+ fingerprint: upload.fingerprint,
5051
+ version_id: upload.versionId,
5052
+ etag: upload.etag,
5053
+ object_metadata_reported: upload.metadataReported,
5054
+ retried_prior_failure: upload.retriedPriorFailure,
5055
+ ...watermarkWriteFailures.has(upload.sessionId) ? { watermark_write_failed: true } : {}
5056
+ })),
5057
+ ...summary.unchangedSessions.map((unchanged) => ({
5058
+ id: unchanged.sessionId,
5059
+ outcome: "unchanged",
5060
+ fingerprint: unchanged.fingerprint,
5061
+ watermark_fingerprint: unchanged.watermarkFingerprint,
5062
+ watermark_key: unchanged.watermarkKey,
5063
+ watermark_version_id: unchanged.watermarkVersionId,
5064
+ watermark_etag: unchanged.watermarkEtag,
5065
+ watermark_uploaded_at: unchanged.watermarkUploadedAt
5066
+ })),
5067
+ ...failedSessions.map((failure) => ({
5068
+ id: failure.sessionId,
5069
+ outcome: "failed",
5070
+ failure_outcome: failure.outcome,
5071
+ ...failure.reason !== void 0 ? { reason: failure.reason } : {},
5072
+ ...failure.bytes !== void 0 ? { payload_bytes: failure.bytes } : {},
5073
+ ...failure.byteLimit !== void 0 ? { payload_limit_bytes: failure.byteLimit } : {},
5074
+ ...failure.messageCount !== void 0 ? { message_count: failure.messageCount } : {},
5075
+ ...failure.partCount !== void 0 ? { part_count: failure.partCount } : {},
5076
+ ...failure.exitCode !== void 0 ? { exit_code: failure.exitCode } : {}
5077
+ })),
5078
+ ...summary.skippedChangedSessions.map((skipped) => ({
5079
+ id: skipped.sessionId,
5080
+ outcome: "skipped-changed",
5081
+ reason: skipped.reason
5082
+ })),
5083
+ ...summary.skippedUnknownIds.map((sessionId) => ({
5084
+ id: sessionId,
5085
+ outcome: "skipped-unknown"
5086
+ }))
5087
+ ] : [];
5088
+ return {
5089
+ schema_version: SESSION_ARCHIVE_MANIFEST_SCHEMA_VERSION,
5090
+ runner_id: identity.runnerId,
5091
+ boot_id: identity.bootId,
5092
+ pass_sequence: identity.passSequence,
5093
+ phase: identity.phase,
5094
+ started_at: identity.startedAt,
5095
+ completed_at: identity.completedAt,
5096
+ budget_ms: identity.budgetMs,
5097
+ enumeration_complete: identity.enumerationComplete,
5098
+ enumeration_reason: identity.enumerationReason,
5099
+ watermark_file_present: identity.watermarkFilePresent,
5100
+ watermarks_loaded: identity.watermarksLoaded,
5101
+ inspected: summary?.inspected ?? 0,
5102
+ counts: {
5103
+ uploaded: summary?.uploaded ?? 0,
5104
+ unchanged: summary?.unchanged ?? 0,
5105
+ failed: failedSessions.length,
5106
+ skipped_changed: summary?.skippedChanged ?? 0,
5107
+ skipped_unknown: summary?.skippedUnknown ?? 0
5108
+ },
5109
+ outcomes_reconciled: summary?.outcomesReconciled ?? null,
5110
+ inventory_never_archived: summary?.inventoryNeverArchived ?? 0,
5111
+ inventory_prior_failures: summary?.inventoryPriorFailures ?? 0,
5112
+ sessions
5113
+ };
5114
+ }
5115
+ async function uploadSessionArchiveManifest({
5116
+ keyPrefix,
5117
+ identity,
5118
+ summary,
5119
+ timeoutMs,
5120
+ signal,
5121
+ onMetadataDecodeError,
5122
+ upload
5123
+ }) {
5124
+ const key = sessionArchiveManifestKey(keyPrefix, identity);
5125
+ const manifest = buildSessionArchiveManifest(identity, summary);
5126
+ const outcome = await (upload ?? uploadSessionArchive)(key, JSON.stringify(manifest), {
5127
+ timeoutMs,
5128
+ signal,
5129
+ onMetadataDecodeError
5130
+ });
5131
+ return { key, outcome };
5132
+ }
5133
+
3938
5134
  // src/lib/opencode/auth.ts
3939
5135
  function buildOpenCodeBasicAuthHeader(password) {
3940
5136
  return `Basic ${Buffer.from(["opencode", password].join(":")).toString("base64")}`;
@@ -4041,9 +5237,11 @@ async function checkOpenCode2Health(port, password) {
4041
5237
  return { healthy: false, error: message };
4042
5238
  }
4043
5239
  }
4044
- async function waitForOpenCodeHealth(port, timeoutMs = 3e4) {
5240
+ async function waitForOpenCodeHealth(port, timeoutMs = 3e4, stopEarly) {
4045
5241
  const startTime = Date.now();
4046
5242
  while (Date.now() - startTime < timeoutMs) {
5243
+ const earlyStopReason = stopEarly?.();
5244
+ if (earlyStopReason) return { healthy: false, error: earlyStopReason };
4047
5245
  const health = await checkOpenCodeHealth(port);
4048
5246
  if (health.healthy || health.authFailed) {
4049
5247
  return health;
@@ -4052,9 +5250,11 @@ async function waitForOpenCodeHealth(port, timeoutMs = 3e4) {
4052
5250
  }
4053
5251
  return { healthy: false, error: "Timeout waiting for OpenCode to be healthy" };
4054
5252
  }
4055
- async function waitForOpenCode2Health(port, password, timeoutMs = 3e4) {
5253
+ async function waitForOpenCode2Health(port, password, timeoutMs = 3e4, stopEarly) {
4056
5254
  const startTime = Date.now();
4057
5255
  while (Date.now() - startTime < timeoutMs) {
5256
+ const earlyStopReason = stopEarly?.();
5257
+ if (earlyStopReason) return { healthy: false, error: earlyStopReason };
4058
5258
  const health = await checkOpenCode2Health(port, password);
4059
5259
  if (health.healthy || health.authFailed) {
4060
5260
  return health;
@@ -5708,8 +6908,8 @@ function classifyReplyAuthError(reply) {
5708
6908
  };
5709
6909
  }
5710
6910
  }
5711
- const errorMessage4 = typeof data?.message === "string" ? data.message : typeof e.message === "string" ? e.message : null;
5712
- if (errorMessage4 !== null && CLAUDE_AUTH_EXPIRY_MESSAGES.some((knownMessage) => errorMessage4.includes(knownMessage))) {
6911
+ const errorMessage5 = typeof data?.message === "string" ? data.message : typeof e.message === "string" ? e.message : null;
6912
+ if (errorMessage5 !== null && CLAUDE_AUTH_EXPIRY_MESSAGES.some((knownMessage) => errorMessage5.includes(knownMessage))) {
5713
6913
  return {
5714
6914
  kind: "model_auth",
5715
6915
  providerId: typeof data?.providerID === "string" && data.providerID || replyProviderId,
@@ -5764,7 +6964,7 @@ function hasRunningAssistantExcept(messages, exceptUserMessageId) {
5764
6964
  (m) => roleOf2(m) === "assistant" && parentIdOf2(m) !== exceptUserMessageId && isAssistantInFlight(m)
5765
6965
  );
5766
6966
  }
5767
- function hasLaterSiblingTurnStarted(messages, userMessageId, siblingUserMessageIds) {
6967
+ function hasLaterSiblingTurnStarted(messages, userMessageId, siblingUserMessageIds, apiVersion) {
5768
6968
  if (!messages || messages.length === 0) return false;
5769
6969
  const userIndex = messages.findIndex((message) => idOf2(message) === userMessageId);
5770
6970
  if (userIndex === -1) return false;
@@ -5778,7 +6978,7 @@ function hasLaterSiblingTurnStarted(messages, userMessageId, siblingUserMessageI
5778
6978
  if (laterUserMessageId === void 0 || !siblingUserMessageIds.has(laterUserMessageId)) {
5779
6979
  return false;
5780
6980
  }
5781
- if (messages.some(
6981
+ if (apiVersion === "v2" || messages.some(
5782
6982
  (candidate) => roleOf2(candidate) === "assistant" && parentIdOf2(candidate) === laterUserMessageId
5783
6983
  )) {
5784
6984
  hasStartedLaterUser = true;
@@ -7123,7 +8323,7 @@ function reportedOpenCodeVersion(input) {
7123
8323
 
7124
8324
  // src/lib/opencode/process.ts
7125
8325
  import { execSync, spawn as spawn3 } from "child_process";
7126
- import { randomBytes } from "node:crypto";
8326
+ import { randomBytes as randomBytes2 } from "node:crypto";
7127
8327
 
7128
8328
  // src/lib/process-stop.ts
7129
8329
  async function stopProcessAndWait(child, timeoutMs, sendTerm, sendKill) {
@@ -7238,28 +8438,29 @@ function getProcessCwd(pid) {
7238
8438
  }
7239
8439
  return void 0;
7240
8440
  }
7241
- function isPortInUse(port) {
7242
- const platform = process.platform;
7243
- try {
7244
- if (platform === "darwin" || platform === "linux") {
7245
- execSync(`lsof -i :${port} -sTCP:LISTEN 2>/dev/null`, {
7246
- encoding: "utf-8",
7247
- stdio: ["pipe", "pipe", "pipe"]
7248
- });
7249
- return true;
8441
+ function watchOpenCodeExit(child, log3) {
8442
+ let spawnError = null;
8443
+ child.once("error", (error2) => {
8444
+ spawnError = error2;
8445
+ const code = spawnError.code ?? "unknown error";
8446
+ log3(
8447
+ `[watchOpenCodeExit] OpenCode command ${child.spawnfile ?? "unknown"} could not be spawned: ${code}: ${spawnError.message}`,
8448
+ "error"
8449
+ );
8450
+ });
8451
+ return () => {
8452
+ if (spawnError) {
8453
+ const code = spawnError.code ?? "unknown error";
8454
+ return `it could not be spawned (${code}: ${spawnError.message})`;
7250
8455
  }
7251
- } catch {
7252
- }
7253
- return false;
7254
- }
7255
- function findAvailablePort(startPort, maxAttempts = 10) {
7256
- for (let i = 0; i < maxAttempts; i++) {
7257
- const port = startPort + i;
7258
- if (!isPortInUse(port)) {
7259
- return port;
8456
+ if (child.signalCode !== null && child.signalCode !== void 0) {
8457
+ return `it was killed by ${child.signalCode} before it answered`;
7260
8458
  }
7261
- }
7262
- return null;
8459
+ if (child.exitCode !== null && child.exitCode !== void 0) {
8460
+ return `it exited with status ${child.exitCode} before it answered`;
8461
+ }
8462
+ return null;
8463
+ };
7263
8464
  }
7264
8465
  function findProcessesByPattern(pgrepPattern, psPattern) {
7265
8466
  const instances = [];
@@ -7401,7 +8602,7 @@ async function startOpenCode(port, options = {}) {
7401
8602
  return child;
7402
8603
  }
7403
8604
  async function startOpenCode2(port, options = {}) {
7404
- const password = randomBytes(24).toString("hex");
8605
+ const password = randomBytes2(24).toString("hex");
7405
8606
  let command = options.command ?? "opencode2";
7406
8607
  const logLevel = options.inheritStdio ? ["--log-level", resolveOpenCode2LogLevel(process.env)] : [];
7407
8608
  let args = ["serve", "--port", port.toString(), "--hostname", "127.0.0.1", ...logLevel];
@@ -7449,6 +8650,144 @@ function stopOpenCodeAndWait(opencodeProcess, timeoutMs) {
7449
8650
  );
7450
8651
  }
7451
8652
 
8653
+ // src/lib/opencode/port.ts
8654
+ import { execFileSync as execFileSync2 } from "node:child_process";
8655
+ import { createServer as createServer2 } from "node:net";
8656
+ var HOLDER_LOOKUP_TIMEOUT_MS = 250;
8657
+ var RECLAIM_SIGNAL_WAIT_MS = 250;
8658
+ var RECLAIM_POLL_INTERVAL_MS = 25;
8659
+ function isPortInUse(port) {
8660
+ return new Promise((resolve6) => {
8661
+ const server = createServer2();
8662
+ server.once("error", () => resolve6(true));
8663
+ server.listen({ port, host: "127.0.0.1", exclusive: true }, () => {
8664
+ server.close(() => resolve6(false));
8665
+ });
8666
+ });
8667
+ }
8668
+ async function findAvailablePort(startPort, maxAttempts = 10) {
8669
+ for (let i = 0; i < maxAttempts; i++) {
8670
+ const port = startPort + i;
8671
+ if (!await isPortInUse(port)) return port;
8672
+ }
8673
+ return null;
8674
+ }
8675
+ function outputText(value) {
8676
+ if (typeof value === "string") return value;
8677
+ if (Buffer.isBuffer(value)) return value.toString("utf8");
8678
+ return value === void 0 || value === null ? "" : String(value);
8679
+ }
8680
+ function holderPids(stdout) {
8681
+ const tokens = stdout.trim() ? stdout.trim().split(/\s+/) : [];
8682
+ if (tokens.length === 0) return [];
8683
+ if (!tokens.every((token) => /^\d+$/.test(token))) return null;
8684
+ return tokens.map(Number);
8685
+ }
8686
+ function isExecTimeout(error2) {
8687
+ if (!error2 || typeof error2 !== "object") return false;
8688
+ const candidate = error2;
8689
+ return candidate.code === "ETIMEDOUT" || candidate.killed === true && candidate.signal === "SIGKILL";
8690
+ }
8691
+ function listLoopbackPortHolders(port) {
8692
+ try {
8693
+ const stdout = outputText(
8694
+ execFileSync2("fuser", ["-n", "tcp", String(port)], {
8695
+ encoding: "utf8",
8696
+ stdio: ["ignore", "pipe", "pipe"],
8697
+ // The resume path must not wait indefinitely on a broken /proc read.
8698
+ timeout: HOLDER_LOOKUP_TIMEOUT_MS,
8699
+ killSignal: "SIGKILL"
8700
+ })
8701
+ );
8702
+ const pids = holderPids(stdout);
8703
+ return pids !== null && pids.length > 0 ? pids : { error: "fuser failed to identify the port holder" };
8704
+ } catch (error2) {
8705
+ const candidate = error2;
8706
+ const stdout = outputText(candidate.stdout);
8707
+ const stderr = outputText(candidate.stderr);
8708
+ const pids = holderPids(stdout);
8709
+ if (pids === null) return { error: "fuser failed to identify the port holder" };
8710
+ if (pids.length > 0) return pids;
8711
+ if (candidate.code === "ENOENT") return { error: "fuser is unavailable" };
8712
+ if (isExecTimeout(error2)) return { error: "fuser timed out while identifying the port holder" };
8713
+ if (candidate.status === 1 && stderr.trim() === "") return [];
8714
+ return { error: "fuser failed to identify the port holder" };
8715
+ }
8716
+ }
8717
+ async function identifyHolders(listHolders) {
8718
+ let timer;
8719
+ const timeout = new Promise((resolve6) => {
8720
+ timer = setTimeout(
8721
+ () => resolve6({ error: "holder identification timed out" }),
8722
+ HOLDER_LOOKUP_TIMEOUT_MS
8723
+ );
8724
+ });
8725
+ try {
8726
+ return await Promise.race([Promise.resolve().then(listHolders), timeout]);
8727
+ } catch (error2) {
8728
+ return {
8729
+ error: `holder identification failed: ${error2 instanceof Error ? error2.message : String(error2)}`
8730
+ };
8731
+ } finally {
8732
+ if (timer !== void 0) clearTimeout(timer);
8733
+ }
8734
+ }
8735
+ function isErrno(error2, code) {
8736
+ return error2 !== null && typeof error2 === "object" && "code" in error2 && error2.code === code;
8737
+ }
8738
+ function signalHolders(pids, signal) {
8739
+ let failure = null;
8740
+ for (const pid of pids) {
8741
+ try {
8742
+ process.kill(pid, signal);
8743
+ } catch (error2) {
8744
+ if (isErrno(error2, "ESRCH")) continue;
8745
+ failure ??= `could not send ${signal} to holder ${pid}: ${error2 instanceof Error ? error2.message : String(error2)}`;
8746
+ }
8747
+ }
8748
+ return failure;
8749
+ }
8750
+ async function waitForPortFree(port, waitMs) {
8751
+ const deadline = Date.now() + waitMs;
8752
+ let probeError;
8753
+ for (; ; ) {
8754
+ try {
8755
+ if (!await isPortInUse(port)) return { free: true };
8756
+ } catch (error2) {
8757
+ probeError = error2 instanceof Error ? error2.message : String(error2);
8758
+ }
8759
+ const remaining = deadline - Date.now();
8760
+ if (remaining <= 0) return { free: false, detail: probeError };
8761
+ await new Promise(
8762
+ (resolve6) => setTimeout(resolve6, Math.min(RECLAIM_POLL_INTERVAL_MS, remaining))
8763
+ );
8764
+ }
8765
+ }
8766
+ async function reclaimLoopbackPort(port, options = {}) {
8767
+ const holderResult = await identifyHolders(
8768
+ options.listHolders ?? (() => listLoopbackPortHolders(port))
8769
+ );
8770
+ if (!Array.isArray(holderResult)) {
8771
+ return { kind: "blocked", port, detail: holderResult.error };
8772
+ }
8773
+ if (holderResult.length === 0) return { kind: "no-holder", port };
8774
+ const termFailure = signalHolders(holderResult, "SIGTERM");
8775
+ const afterTerm = await waitForPortFree(port, RECLAIM_SIGNAL_WAIT_MS);
8776
+ if (afterTerm.free && termFailure === null) {
8777
+ return { kind: "freed", port, pids: holderResult, usedSigkill: false };
8778
+ }
8779
+ const killFailure = signalHolders(holderResult, "SIGKILL");
8780
+ const afterKill = await waitForPortFree(port, RECLAIM_SIGNAL_WAIT_MS);
8781
+ if (!afterKill.free) {
8782
+ return {
8783
+ kind: "blocked",
8784
+ port,
8785
+ detail: afterKill.detail ?? termFailure ?? killFailure ?? "the port remained in use after SIGTERM and SIGKILL"
8786
+ };
8787
+ }
8788
+ return { kind: "freed", port, pids: holderResult, usedSigkill: true };
8789
+ }
8790
+
7452
8791
  // src/lib/opencode/install.ts
7453
8792
  import { execSync as execSync2 } from "child_process";
7454
8793
  import chalk4 from "chalk";
@@ -7666,7 +9005,7 @@ function buildSessionStoreSizeWarning(input) {
7666
9005
  import { statSync as statSync5 } from "node:fs";
7667
9006
  import { homedir as homedir5 } from "node:os";
7668
9007
  import { join as join11 } from "node:path";
7669
- import { open as open2, stat } from "node:fs/promises";
9008
+ import { open as open3, stat } from "node:fs/promises";
7670
9009
  var DEFAULT_POLL_INTERVAL_MS = 1e3;
7671
9010
  function resolveOpenCodeLogPath(homeDir = homedir5(), env = process.env) {
7672
9011
  const dataDir = env.XDG_DATA_HOME || join11(homeDir, ".local", "share");
@@ -7720,7 +9059,7 @@ function tailOpenCodeLogFile(logPath, onChunk, opts = {}) {
7720
9059
  inode = current.ino;
7721
9060
  if (current.size === offset) return;
7722
9061
  const length = current.size - offset;
7723
- const fh = await open2(logPath, "r");
9062
+ const fh = await open3(logPath, "r");
7724
9063
  try {
7725
9064
  const buf = Buffer.alloc(length);
7726
9065
  const { bytesRead } = await fh.read(buf, 0, length, offset);
@@ -7753,7 +9092,7 @@ import WebSocket from "ws";
7753
9092
 
7754
9093
  // src/lib/file-read.ts
7755
9094
  import { constants } from "node:fs";
7756
- import { open as open3, realpath as realpath2, stat as stat2 } from "node:fs/promises";
9095
+ import { open as open4, realpath as realpath2, stat as stat2 } from "node:fs/promises";
7757
9096
  import { extname, isAbsolute as isAbsolute3, resolve as resolve4 } from "node:path";
7758
9097
  import { homedir as homedir6 } from "node:os";
7759
9098
 
@@ -7803,7 +9142,7 @@ var FILE_MIME_TYPES = {
7803
9142
  ".mp4": "video/mp4",
7804
9143
  ".mov": "video/quicktime"
7805
9144
  };
7806
- async function readProjectFile(projectRoot, method, requestedPath, openFile = open3) {
9145
+ async function readProjectFile(projectRoot, method, requestedPath, openFile = open4) {
7807
9146
  if (method !== "GET") return refuse(405, "method_not_allowed");
7808
9147
  if (!projectRoot || !isAbsolute3(projectRoot)) return refuse(503, "project_root_unavailable");
7809
9148
  if (!requestedPath || requestedPath.length > 4096 || requestedPath.includes("\0")) {
@@ -8376,8 +9715,8 @@ function connectTunnel(options) {
8376
9715
  }
8377
9716
  forwarder.handleBinaryBodyFrame(frame.sid, frame.payload);
8378
9717
  } catch (error2) {
8379
- const errorMessage4 = error2 instanceof Error ? error2.message : "Unknown error";
8380
- onError?.(`Failed to handle binary message: ${errorMessage4}`);
9718
+ const errorMessage5 = error2 instanceof Error ? error2.message : "Unknown error";
9719
+ onError?.(`Failed to handle binary message: ${errorMessage5}`);
8381
9720
  }
8382
9721
  return;
8383
9722
  }
@@ -8385,8 +9724,8 @@ function connectTunnel(options) {
8385
9724
  try {
8386
9725
  message = JSON.parse(data.toString());
8387
9726
  } catch (error2) {
8388
- const errorMessage4 = error2 instanceof Error ? error2.message : "Unknown error";
8389
- onError?.(`Failed to handle message: ${errorMessage4}`);
9727
+ const errorMessage5 = error2 instanceof Error ? error2.message : "Unknown error";
9728
+ onError?.(`Failed to handle message: ${errorMessage5}`);
8390
9729
  return;
8391
9730
  }
8392
9731
  if (isStreamFrame(message)) {
@@ -8965,7 +10304,7 @@ import { join as join14 } from "node:path";
8965
10304
 
8966
10305
  // src/lib/file-push.ts
8967
10306
  import { randomUUID } from "node:crypto";
8968
- import { chmod, mkdir, open as open4, realpath as realpath3, rename, unlink } from "node:fs/promises";
10307
+ import { chmod, mkdir, open as open5, realpath as realpath3, rename, unlink } from "node:fs/promises";
8969
10308
  import { basename as basename3, dirname as dirname10, isAbsolute as isAbsolute4, join as join13 } from "node:path";
8970
10309
  var FILE_MODE = 384;
8971
10310
  var DIRECTORY_MODE = 448;
@@ -9098,7 +10437,7 @@ async function writeAtomically(realTarget, content) {
9098
10437
  const temporaryPath = join13(dirname10(realTarget), `.evident-push-${randomUUID()}.tmp`);
9099
10438
  let handle;
9100
10439
  try {
9101
- handle = await open4(temporaryPath, "wx", FILE_MODE);
10440
+ handle = await open5(temporaryPath, "wx", FILE_MODE);
9102
10441
  await handle.writeFile(content);
9103
10442
  await handle.chmod(FILE_MODE);
9104
10443
  await handle.close();
@@ -9646,6 +10985,12 @@ var ChannelTerminalError = class extends Error {
9646
10985
  this.status = status2;
9647
10986
  }
9648
10987
  };
10988
+ var LocalOpenCodeError = class extends Error {
10989
+ constructor(message, options) {
10990
+ super(message, options);
10991
+ this.name = "LocalOpenCodeError";
10992
+ }
10993
+ };
9649
10994
  function backoffDelay(attempt, policy) {
9650
10995
  const exp = policy.baseDelayMs * Math.pow(2, attempt);
9651
10996
  const capped = Math.min(policy.maxDelayMs, exp);
@@ -9822,6 +11167,9 @@ var ChannelDriver = class _ChannelDriver {
9822
11167
  awaitingCorrelation = /* @__PURE__ */ new Map();
9823
11168
  /** Pending rows seen in the current drain, used to retain terminal dispatch fences. */
9824
11169
  pendingMessageIds = /* @__PURE__ */ new Set();
11170
+ /** `processing` rows seen in the current drain, for `outstandingQueuedWork()`. */
11171
+ processingMessageIds = /* @__PURE__ */ new Set();
11172
+ outstandingQueuedMessageCount = 0;
9825
11173
  /**
9826
11174
  * "markDone for this row is TERMINALLY undeliverable" (Bug 4). Set ONLY when a
9827
11175
  * re-adopted DONE row's `markDone` returned a terminal 4xx (a status that will
@@ -10077,7 +11425,14 @@ var ChannelDriver = class _ChannelDriver {
10077
11425
  return this.isV2 ? isV2SessionOngoing(this.openCodeClient, sessionId) : isSessionOngoing(this.port, sessionId, this.openCodeClient);
10078
11426
  }
10079
11427
  async createOpenCodeSession(directory) {
10080
- return this.isV2 ? createV2Session(this.openCodeClient, directory) : createOpenCodeSession(this.port, directory, this.openCodeClient);
11428
+ try {
11429
+ return await (this.isV2 ? createV2Session(this.openCodeClient, directory) : createOpenCodeSession(this.port, directory, this.openCodeClient));
11430
+ } catch (err) {
11431
+ throw new LocalOpenCodeError(
11432
+ `creating an OpenCode session on port ${this.port} failed: ${describeErrorWithCause(err)}`,
11433
+ { cause: err }
11434
+ );
11435
+ }
10081
11436
  }
10082
11437
  async hasAnyConfiguredProvider() {
10083
11438
  return hasAnyConfiguredProvider(this.port, this.openCodeClient);
@@ -10235,6 +11590,10 @@ var ChannelDriver = class _ChannelDriver {
10235
11590
  });
10236
11591
  }
10237
11592
  await this.readoptProcessing();
11593
+ this.outstandingQueuedMessageCount = (/* @__PURE__ */ new Set([
11594
+ ...this.pendingMessageIds,
11595
+ ...this.processingMessageIds
11596
+ ])).size;
10238
11597
  } finally {
10239
11598
  this.draining = false;
10240
11599
  }
@@ -10252,6 +11611,14 @@ var ChannelDriver = class _ChannelDriver {
10252
11611
  }
10253
11612
  return false;
10254
11613
  }
11614
+ /**
11615
+ * Number of distinct non-terminal queued messages (`pending` plus `processing`)
11616
+ * observed by the last completed drain. `run.ts` treats a non-zero value as not
11617
+ * idle. A drain that could not complete both fetches leaves the previous value standing.
11618
+ */
11619
+ outstandingQueuedWork() {
11620
+ return this.outstandingQueuedMessageCount;
11621
+ }
10255
11622
  /**
10256
11623
  * Session ids active *for the `--max-active-sessions` cap*: in-flight work AND
10257
11624
  * a live watcher loop. Unlike `hasInFlightWatchers()` / `protectedSessionIds()`,
@@ -10299,12 +11666,12 @@ var ChannelDriver = class _ChannelDriver {
10299
11666
  this.sessions.delete(conversationId);
10300
11667
  this.supersede(conversationId, sessionId);
10301
11668
  const dispatchDescription = source === "readopt" ? "re-dispatched message" : "message";
10302
- const errorMessage4 = `OpenCode accepted this ${dispatchDescription} once, but its assigned id was never confirmed after ${attempts} attempts to match it up \u2014 the message was deliberately not sent again, so no duplicate turn was created; session ${sessionId.slice(0, 8)} was abandoned; a fresh one is used for further messages.`;
10303
- this.untrackableAck.set(messageId, errorMessage4);
11669
+ const errorMessage5 = `OpenCode accepted this ${dispatchDescription} once, but its assigned id was never confirmed after ${attempts} attempts to match it up \u2014 the message was deliberately not sent again, so no duplicate turn was created; session ${sessionId.slice(0, 8)} was abandoned; a fresh one is used for further messages.`;
11670
+ this.untrackableAck.set(messageId, errorMessage5);
10304
11671
  this.untrackableAckSessionIds.set(messageId, null);
10305
11672
  this.log({
10306
11673
  level: "error",
10307
- message: errorMessage4,
11674
+ message: errorMessage5,
10308
11675
  conversation_id: conversationId,
10309
11676
  message_id: messageId
10310
11677
  });
@@ -10312,7 +11679,7 @@ var ChannelDriver = class _ChannelDriver {
10312
11679
  conversationId,
10313
11680
  messageId,
10314
11681
  null,
10315
- errorMessage4
11682
+ errorMessage5
10316
11683
  );
10317
11684
  if (reportError !== null) {
10318
11685
  this.log({
@@ -10493,12 +11860,12 @@ var ChannelDriver = class _ChannelDriver {
10493
11860
  conversation_id: conv.id,
10494
11861
  message_id: message.id
10495
11862
  });
10496
- const errorMessage4 = this.untrackableAck.get(message.id);
11863
+ const errorMessage5 = this.untrackableAck.get(message.id);
10497
11864
  const reportError = await this.reportUntrackableAck(
10498
11865
  conv.id,
10499
11866
  message.id,
10500
11867
  null,
10501
- errorMessage4
11868
+ errorMessage5
10502
11869
  );
10503
11870
  if (reportError === null) {
10504
11871
  continue;
@@ -10586,7 +11953,7 @@ var ChannelDriver = class _ChannelDriver {
10586
11953
  const hasProviderAndModel = dispatchedModel !== null && separator > 0 && separator < dispatchedModel.length - 1;
10587
11954
  const providerId = hasProviderAndModel ? dispatchedModel.slice(0, separator) : null;
10588
11955
  const modelId = hasProviderAndModel ? dispatchedModel.slice(separator + 1) : null;
10589
- const errorMessage4 = `Provider namespace not loaded on this runner: ${message.opencode_model}. Refused before dispatch; no turn was started.`;
11956
+ const errorMessage5 = `Provider namespace not loaded on this runner: ${message.opencode_model}. Refused before dispatch; no turn was started.`;
10590
11957
  this.log({
10591
11958
  level: "error",
10592
11959
  message: `Refusing message ${message.id.slice(0, 8)} in conversation ${conv.id.slice(0, 8)}: provider namespace ${providerId ?? "(unknown)"} is not loaded; no turn was started`,
@@ -10594,7 +11961,7 @@ var ChannelDriver = class _ChannelDriver {
10594
11961
  message_id: message.id
10595
11962
  });
10596
11963
  try {
10597
- await this.markFailed(conv.id, message.id, sessionId, errorMessage4, void 0, {
11964
+ await this.markFailed(conv.id, message.id, sessionId, errorMessage5, void 0, {
10598
11965
  classification: {
10599
11966
  kind: "model_auth",
10600
11967
  providerId,
@@ -10672,12 +12039,12 @@ var ChannelDriver = class _ChannelDriver {
10672
12039
  } catch (err) {
10673
12040
  if (err instanceof ChannelAuthError) throw err;
10674
12041
  if (this.isV2 && err instanceof OpenCodeV2PromptAckError) {
10675
- const errorMessage5 = err instanceof Error ? err.message : String(err);
10676
- this.untrackableAck.set(message.id, errorMessage5);
12042
+ const errorMessage6 = err instanceof Error ? err.message : String(err);
12043
+ this.untrackableAck.set(message.id, errorMessage6);
10677
12044
  this.untrackableAckSessionIds.set(message.id, null);
10678
12045
  this.log({
10679
12046
  level: "error",
10680
- message: `V2 prompt dispatch for message ${message.id.slice(0, 8)} failed after a positive ack with no usable id: ${errorMessage5}`,
12047
+ message: `V2 prompt dispatch for message ${message.id.slice(0, 8)} failed after a positive ack with no usable id: ${errorMessage6}`,
10681
12048
  conversation_id: conv.id,
10682
12049
  message_id: message.id
10683
12050
  });
@@ -10685,7 +12052,7 @@ var ChannelDriver = class _ChannelDriver {
10685
12052
  conv.id,
10686
12053
  message.id,
10687
12054
  null,
10688
- errorMessage5
12055
+ errorMessage6
10689
12056
  );
10690
12057
  if (markError !== null) {
10691
12058
  this.log({
@@ -10724,7 +12091,7 @@ var ChannelDriver = class _ChannelDriver {
10724
12091
  await this.failV2ModelSwitch(conv, message, sessionId, err);
10725
12092
  break;
10726
12093
  }
10727
- const errorMessage4 = err instanceof Error ? err.message : String(err);
12094
+ const errorMessage5 = err instanceof Error ? err.message : String(err);
10728
12095
  this.sessions.delete(conv.id);
10729
12096
  this.supersede(conv.id, sessionId);
10730
12097
  this.log({
@@ -10733,7 +12100,7 @@ var ChannelDriver = class _ChannelDriver {
10733
12100
  conversation_id: conv.id,
10734
12101
  message_id: message.id
10735
12102
  });
10736
- await this.markFailed(conv.id, message.id, null, errorMessage4).catch((markErr) => {
12103
+ await this.markFailed(conv.id, message.id, null, errorMessage5).catch((markErr) => {
10737
12104
  this.log({
10738
12105
  level: "warn",
10739
12106
  message: `markFailed PATCH for message ${message.id.slice(0, 8)} (conversation ${conv.id.slice(0, 8)}) failed (best-effort, not retried): ${markErr instanceof Error ? markErr.message : String(markErr)}`,
@@ -10744,7 +12111,7 @@ var ChannelDriver = class _ChannelDriver {
10744
12111
  });
10745
12112
  this.log({
10746
12113
  level: "error",
10747
- message: `Message ${message.id.slice(0, 8)} dispatch failed: ${errorMessage4}`,
12114
+ message: `Message ${message.id.slice(0, 8)} dispatch failed: ${errorMessage5}`,
10748
12115
  conversation_id: conv.id,
10749
12116
  message_id: message.id
10750
12117
  });
@@ -11029,7 +12396,12 @@ var ChannelDriver = class _ChannelDriver {
11029
12396
  this.watchers.get(sessionId),
11030
12397
  message.id
11031
12398
  );
11032
- if (hasLaterSiblingTurnStarted(messages, ocId ?? "", siblingOcIds)) {
12399
+ if (hasLaterSiblingTurnStarted(
12400
+ messages,
12401
+ ocId ?? "",
12402
+ siblingOcIds,
12403
+ this.openCodeClient.version
12404
+ )) {
11033
12405
  this.log({
11034
12406
  level: "warn",
11035
12407
  message: `Re-drive: OpenCode already served a later, different Evident message's turn in session ${sessionId.slice(0, 8)} while message ${message.id.slice(0, 8)} produced no reply \u2014 re-dispatching instead of reattaching to someone else's turn`,
@@ -12668,7 +14040,12 @@ var ChannelDriver = class _ChannelDriver {
12668
14040
  return;
12669
14041
  }
12670
14042
  const siblingOcIds = this.siblingOpencodeMessageIds(watcher, inFlight.evidentMessageId);
12671
- const skippedByOpencode = state === "queued" && hasLaterSiblingTurnStarted(messages, inFlight.opencodeMessageId, siblingOcIds);
14043
+ const skippedByOpencode = state === "queued" && hasLaterSiblingTurnStarted(
14044
+ messages,
14045
+ inFlight.opencodeMessageId,
14046
+ siblingOcIds,
14047
+ this.openCodeClient.version
14048
+ );
12672
14049
  const pastStuckBound = this.now() - inFlight.dispatchedAt >= this.stuckQueuedMs;
12673
14050
  const sessionIdle = state === "queued" && !hasRunningAssistantExcept(messages, inFlight.opencodeMessageId);
12674
14051
  if (state === "queued" && pastStuckBound && (sessionIdle || skippedByOpencode) && !inFlight.stuckReported) {
@@ -13357,6 +14734,8 @@ var ChannelDriver = class _ChannelDriver {
13357
14734
  */
13358
14735
  async readoptProcessing() {
13359
14736
  const rows = await this.getProcessingMessages();
14737
+ this.processingMessageIds.clear();
14738
+ for (const row of rows) this.processingMessageIds.add(row.id);
13360
14739
  if (this.dontRedispatch.size > 0 || this.doneUndeliverable.size > 0 || this.readoptPollUnresolvedSignalled.size > 0) {
13361
14740
  const stillProcessing = new Set(rows.map((r) => r.id));
13362
14741
  for (const id of [
@@ -13679,12 +15058,12 @@ var ChannelDriver = class _ChannelDriver {
13679
15058
  conversation_id: row.conversation_id,
13680
15059
  message_id: row.id
13681
15060
  });
13682
- const errorMessage4 = this.untrackableAck.get(row.id);
15061
+ const errorMessage5 = this.untrackableAck.get(row.id);
13683
15062
  const reportError = await this.reportUntrackableAck(
13684
15063
  row.conversation_id,
13685
15064
  row.id,
13686
15065
  this.untrackableAckSessionIds.get(row.id) ?? null,
13687
- errorMessage4
15066
+ errorMessage5
13688
15067
  );
13689
15068
  if (reportError !== null) {
13690
15069
  this.log({
@@ -14003,14 +15382,14 @@ var ChannelDriver = class _ChannelDriver {
14003
15382
  this.awaitingReadopt.delete(row.id);
14004
15383
  if (err instanceof ChannelAuthError) throw err;
14005
15384
  if (this.isV2) {
14006
- const errorMessage4 = err instanceof Error ? err.message : String(err);
15385
+ const errorMessage5 = err instanceof Error ? err.message : String(err);
14007
15386
  const invalidPromptAck = err instanceof OpenCodeV2PromptAckError;
14008
15387
  if (!invalidPromptAck) {
14009
15388
  const exists = await this.sessionExists(sessionId);
14010
15389
  if (exists === false) {
14011
15390
  this.log({
14012
15391
  level: "warn",
14013
- message: `Re-adopt: message ${row.id.slice(0, 8)} dispatch hit a session (${sessionId.slice(0, 8)}) that was deleted mid-dispatch \u2014 deferring to the next drain: ${errorMessage4}`,
15392
+ message: `Re-adopt: message ${row.id.slice(0, 8)} dispatch hit a session (${sessionId.slice(0, 8)}) that was deleted mid-dispatch \u2014 deferring to the next drain: ${errorMessage5}`,
14014
15393
  conversation_id: row.conversation_id,
14015
15394
  message_id: row.id
14016
15395
  });
@@ -14020,7 +15399,7 @@ var ChannelDriver = class _ChannelDriver {
14020
15399
  if (exists === null) {
14021
15400
  this.log({
14022
15401
  level: "warn",
14023
- message: `Re-adopt: message ${row.id.slice(0, 8)} dispatch failed and session (${sessionId.slice(0, 8)}) existence could not be confirmed \u2014 deferring to the next drain: ${errorMessage4}`,
15402
+ message: `Re-adopt: message ${row.id.slice(0, 8)} dispatch failed and session (${sessionId.slice(0, 8)}) existence could not be confirmed \u2014 deferring to the next drain: ${errorMessage5}`,
14024
15403
  conversation_id: row.conversation_id,
14025
15404
  message_id: row.id
14026
15405
  });
@@ -14028,7 +15407,7 @@ var ChannelDriver = class _ChannelDriver {
14028
15407
  return;
14029
15408
  }
14030
15409
  } else {
14031
- this.untrackableAck.set(row.id, errorMessage4);
15410
+ this.untrackableAck.set(row.id, errorMessage5);
14032
15411
  this.untrackableAckSessionIds.set(row.id, sessionId);
14033
15412
  }
14034
15413
  if (err instanceof OpenCodeV2ModelSwitchError) {
@@ -14037,7 +15416,7 @@ var ChannelDriver = class _ChannelDriver {
14037
15416
  }
14038
15417
  this.log({
14039
15418
  level: "error",
14040
- message: `V2 re-adopt dispatch for message ${row.id.slice(0, 8)} failed: ${errorMessage4}`,
15419
+ message: `V2 re-adopt dispatch for message ${row.id.slice(0, 8)} failed: ${errorMessage5}`,
14041
15420
  conversation_id: row.conversation_id,
14042
15421
  message_id: row.id
14043
15422
  });
@@ -14046,7 +15425,7 @@ var ChannelDriver = class _ChannelDriver {
14046
15425
  row.conversation_id,
14047
15426
  row.id,
14048
15427
  sessionId,
14049
- errorMessage4
15428
+ errorMessage5
14050
15429
  );
14051
15430
  if (markError !== null) {
14052
15431
  this.log({
@@ -14057,7 +15436,7 @@ var ChannelDriver = class _ChannelDriver {
14057
15436
  });
14058
15437
  }
14059
15438
  } else {
14060
- await this.markFailed(row.conversation_id, row.id, sessionId, errorMessage4).catch(
15439
+ await this.markFailed(row.conversation_id, row.id, sessionId, errorMessage5).catch(
14061
15440
  (markErr) => {
14062
15441
  this.log({
14063
15442
  level: "warn",
@@ -15041,9 +16420,9 @@ var ChannelDriver = class _ChannelDriver {
15041
16420
  * trackable. Callers use the returned error to keep their path-specific logging
15042
16421
  * while the same report payload can be retried on a later drain.
15043
16422
  */
15044
- async reportUntrackableAck(conversationId, messageId, sessionId, errorMessage4) {
16423
+ async reportUntrackableAck(conversationId, messageId, sessionId, errorMessage5) {
15045
16424
  try {
15046
- await this.markFailed(conversationId, messageId, sessionId, errorMessage4);
16425
+ await this.markFailed(conversationId, messageId, sessionId, errorMessage5);
15047
16426
  return null;
15048
16427
  } catch (err) {
15049
16428
  this.signalUntrackableAck(conversationId, messageId);
@@ -15426,12 +16805,19 @@ import chalk5 from "chalk";
15426
16805
  import ora2 from "ora";
15427
16806
  import { select as select2 } from "@inquirer/prompts";
15428
16807
  var INTERACTIVE_START_TIMEOUT_MS = 3e4;
15429
- function checkNonInteractivePortConflict(port, isPortInUseFn) {
15430
- if (isPortInUseFn(port)) {
16808
+ async function reclaimNonInteractivePort(port, options) {
16809
+ const isPortInUseFn = options.isPortInUse ?? isPortInUse;
16810
+ if (!await isPortInUseFn(port)) return void 0;
16811
+ if (!options.imageManaged) {
15431
16812
  throw new Error(
15432
16813
  `Port ${port} is already in use by a non-OpenCode process. Free it or pass --port.`
15433
16814
  );
15434
16815
  }
16816
+ const outcome = await (options.reclaimLoopbackPort ?? reclaimLoopbackPort)(port);
16817
+ if (outcome.kind !== "blocked") return outcome;
16818
+ throw new Error(
16819
+ `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.`
16820
+ );
15435
16821
  }
15436
16822
  function unknownPasswordError(port) {
15437
16823
  return new Error(
@@ -15488,24 +16874,29 @@ async function ensureOpenCodeRunning(ctx) {
15488
16874
  }
15489
16875
  }
15490
16876
  if (!ctx.interactive) {
15491
- checkNonInteractivePortConflict(ctx.port, isPortInUse);
16877
+ const reclaimOutcome = await reclaimNonInteractivePort(ctx.port, {
16878
+ imageManaged: ctx.inheritStdio === true
16879
+ });
15492
16880
  ctx.log(`OpenCode is not running on port ${ctx.port}. Starting it automatically...`);
15493
16881
  const proc = await startOpenCode(ctx.port, { inheritStdio: ctx.inheritStdio });
15494
- const health = await waitForOpenCodeHealth(ctx.port, ctx.startTimeoutMs);
16882
+ const stopEarly = watchOpenCodeExit(proc, ctx.log);
16883
+ const health = await waitForOpenCodeHealth(ctx.port, ctx.startTimeoutMs, stopEarly);
15495
16884
  if (!health.healthy) {
15496
16885
  if (health.authFailed) {
15497
16886
  return {
15498
16887
  port: ctx.port,
15499
16888
  process: proc,
15500
16889
  version: null,
15501
- 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"
16890
+ notReadyReason: "it is answering with an authentication challenge, likely because OPENCODE_SERVER_PASSWORD is set in the environment of the process that started it",
16891
+ ...reclaimOutcome ? { reclaimOutcome } : {}
15502
16892
  };
15503
16893
  }
15504
16894
  return {
15505
16895
  port: ctx.port,
15506
16896
  process: proc,
15507
16897
  version: null,
15508
- notReadyReason: `it did not become healthy within ${Math.round(ctx.startTimeoutMs / 1e3)}s`
16898
+ 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})`,
16899
+ ...reclaimOutcome ? { reclaimOutcome } : {}
15509
16900
  };
15510
16901
  }
15511
16902
  ctx.log(`OpenCode started on port ${ctx.port}${health.version ? ` (v${health.version})` : ""}`);
@@ -15513,14 +16904,15 @@ async function ensureOpenCodeRunning(ctx) {
15513
16904
  port: ctx.port,
15514
16905
  process: proc,
15515
16906
  version: health.version ?? null,
15516
- notReadyReason: null
16907
+ notReadyReason: null,
16908
+ ...reclaimOutcome ? { reclaimOutcome } : {}
15517
16909
  };
15518
16910
  }
15519
16911
  let port = ctx.port;
15520
- if (isPortInUse(port)) {
16912
+ if (await isPortInUse(port)) {
15521
16913
  console.log(chalk5.yellow(`
15522
16914
  Port ${port} is already in use.`));
15523
- const alternativePort = findAvailablePort(port + 1);
16915
+ const alternativePort = await findAvailablePort(port + 1);
15524
16916
  if (alternativePort) {
15525
16917
  const useAlternative = await select2({
15526
16918
  message: `Use port ${alternativePort} instead?`,
@@ -15567,13 +16959,15 @@ Port ${port} is already in use.`));
15567
16959
  if (action === "start") {
15568
16960
  const spinner = ora2("Starting OpenCode...").start();
15569
16961
  const proc = await startOpenCode(port, { inheritStdio: ctx.inheritStdio });
15570
- const health = await waitForOpenCodeHealth(port, INTERACTIVE_START_TIMEOUT_MS);
16962
+ const stopEarly = watchOpenCodeExit(proc, ctx.log);
16963
+ const health = await waitForOpenCodeHealth(port, INTERACTIVE_START_TIMEOUT_MS, stopEarly);
15571
16964
  if (!health.healthy) {
15572
16965
  spinner.fail("Failed to start OpenCode");
15573
16966
  if (health.authFailed) {
15574
16967
  throw unknownPasswordError(port);
15575
16968
  }
15576
- throw new Error("OpenCode failed to start");
16969
+ const exitReason = stopEarly();
16970
+ throw new Error(`OpenCode failed to start${exitReason ? `: ${exitReason}` : ""}`);
15577
16971
  }
15578
16972
  spinner.stop();
15579
16973
  return { port, process: proc, version: health.version ?? null, notReadyReason: null };
@@ -15612,40 +17006,24 @@ async function ensureOpenCode2Running(ctx) {
15612
17006
  }
15613
17007
  let port = ctx.port;
15614
17008
  if (!ctx.interactive) {
15615
- checkNonInteractivePortConflict(port, isPortInUse);
15616
- } else if (isPortInUse(port)) {
15617
- console.log(chalk6.yellow(`
15618
- Port ${port} is already in use.`));
15619
- const alternativePort = findAvailablePort(port + 1);
15620
- if (alternativePort) {
15621
- const useAlternative = await select3({
15622
- message: `Use port ${alternativePort} instead?`,
15623
- choices: [
15624
- { name: `Yes, use port ${alternativePort}`, value: "yes" },
15625
- { name: "No, I will free the port manually", value: "no" }
15626
- ]
15627
- });
15628
- if (useAlternative === "yes") {
15629
- port = alternativePort;
15630
- } else {
15631
- throw new Error(`Port ${ctx.port} is in use`);
15632
- }
15633
- }
15634
- }
15635
- if (!ctx.interactive) {
17009
+ const reclaimOutcome = await reclaimNonInteractivePort(port, {
17010
+ imageManaged: ctx.inheritStdio === true
17011
+ });
15636
17012
  ctx.log(`OpenCode V2 is not running on port ${port}. Starting it automatically...`);
15637
17013
  const { child: proc, password } = await startOpenCode2(port, {
15638
17014
  inheritStdio: ctx.inheritStdio,
15639
17015
  command: ctx.command
15640
17016
  });
15641
- const health = await waitForOpenCode2Health(port, password, ctx.startTimeoutMs);
17017
+ const stopEarly = watchOpenCodeExit(proc, ctx.log);
17018
+ const health = await waitForOpenCode2Health(port, password, ctx.startTimeoutMs, stopEarly);
15642
17019
  if (!health.healthy) {
15643
17020
  return {
15644
17021
  port,
15645
17022
  process: proc,
15646
17023
  version: null,
15647
- notReadyReason: `it did not become healthy within ${Math.round(ctx.startTimeoutMs / 1e3)}s`,
15648
- password
17024
+ 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})`,
17025
+ password,
17026
+ ...reclaimOutcome ? { reclaimOutcome } : {}
15649
17027
  };
15650
17028
  }
15651
17029
  ctx.log(`OpenCode V2 started on port ${port}${health.version ? ` (v${health.version})` : ""}`);
@@ -15654,8 +17032,27 @@ Port ${port} is already in use.`));
15654
17032
  process: proc,
15655
17033
  version: health.version ?? null,
15656
17034
  notReadyReason: null,
15657
- password
17035
+ password,
17036
+ ...reclaimOutcome ? { reclaimOutcome } : {}
15658
17037
  };
17038
+ } else if (await isPortInUse(port)) {
17039
+ console.log(chalk6.yellow(`
17040
+ Port ${port} is already in use.`));
17041
+ const alternativePort = await findAvailablePort(port + 1);
17042
+ if (alternativePort) {
17043
+ const useAlternative = await select3({
17044
+ message: `Use port ${alternativePort} instead?`,
17045
+ choices: [
17046
+ { name: `Yes, use port ${alternativePort}`, value: "yes" },
17047
+ { name: "No, I will free the port manually", value: "no" }
17048
+ ]
17049
+ });
17050
+ if (useAlternative === "yes") {
17051
+ port = alternativePort;
17052
+ } else {
17053
+ throw new Error(`Port ${ctx.port} is in use`);
17054
+ }
17055
+ }
15659
17056
  }
15660
17057
  const command = ctx.command ?? "opencode2";
15661
17058
  const action = await select3({
@@ -15692,10 +17089,17 @@ Port ${port} is already in use.`));
15692
17089
  inheritStdio: ctx.inheritStdio,
15693
17090
  command: ctx.command
15694
17091
  });
15695
- const health = await waitForOpenCode2Health(port, password, INTERACTIVE_START_TIMEOUT_MS2);
17092
+ const stopEarly = watchOpenCodeExit(proc, ctx.log);
17093
+ const health = await waitForOpenCode2Health(
17094
+ port,
17095
+ password,
17096
+ INTERACTIVE_START_TIMEOUT_MS2,
17097
+ stopEarly
17098
+ );
15696
17099
  if (!health.healthy) {
15697
17100
  spinner.fail("Failed to start OpenCode V2");
15698
- throw new Error("OpenCode V2 failed to start");
17101
+ const exitReason = stopEarly();
17102
+ throw new Error(`OpenCode V2 failed to start${exitReason ? `: ${exitReason}` : ""}`);
15699
17103
  }
15700
17104
  spinner.stop();
15701
17105
  return {
@@ -15991,7 +17395,7 @@ async function configureGitHubAccess({ env, log: log3 }) {
15991
17395
  }
15992
17396
 
15993
17397
  // src/lib/opencode/config-overlay.ts
15994
- import { execFileSync as execFileSync2 } from "node:child_process";
17398
+ import { execFileSync as execFileSync3 } from "node:child_process";
15995
17399
  import { copyFileSync, existsSync as existsSync2, statSync as statSync6 } from "node:fs";
15996
17400
  import { isAbsolute as isAbsolute5, join as join15, resolve as resolve5 } from "node:path";
15997
17401
  function parseConfigContent(content) {
@@ -16033,7 +17437,7 @@ function applyRunnerOpenCodeConfig({
16033
17437
  }
16034
17438
  copyFileSync(source, join15(cwd, target));
16035
17439
  try {
16036
- execFileSync2("git", ["-C", cwd, "update-index", "--skip-worktree", target], {
17440
+ execFileSync3("git", ["-C", cwd, "update-index", "--skip-worktree", target], {
16037
17441
  stdio: "ignore"
16038
17442
  });
16039
17443
  } catch (error2) {
@@ -16207,7 +17611,7 @@ var MAX_FLUSH_PASSES = 2;
16207
17611
  function outcomesWith(outcome) {
16208
17612
  return { claude: outcome, opencode: outcome };
16209
17613
  }
16210
- function errorMessage3(error2) {
17614
+ function errorMessage4(error2) {
16211
17615
  return error2 instanceof Error ? error2.message : String(error2);
16212
17616
  }
16213
17617
  function waitForSettlement(promise, timeoutMs) {
@@ -16234,7 +17638,7 @@ function writeMarker(markerPath, outcomes, log3) {
16234
17638
  writeFileSync8(temporaryPath, body, { mode: 384 });
16235
17639
  renameSync(temporaryPath, markerPath);
16236
17640
  } catch (error2) {
16237
- log3(`CREDENTIAL-FLUSH-MARKER-UNWRITABLE: ${markerPath}: ${errorMessage3(error2)}`, "warn");
17641
+ log3(`CREDENTIAL-FLUSH-MARKER-UNWRITABLE: ${markerPath}: ${errorMessage4(error2)}`, "warn");
16238
17642
  }
16239
17643
  }
16240
17644
  function intervalSeconds(env, log3) {
@@ -16266,7 +17670,7 @@ async function runFlushStore(store, env, synchroniserRunner, log3, deadlineAt) {
16266
17670
  },
16267
17671
  (error2) => {
16268
17672
  failed = true;
16269
- log3(`CREDENTIAL-FLUSH-ERROR: ${store}: ${errorMessage3(error2)}`, "warn");
17673
+ log3(`CREDENTIAL-FLUSH-ERROR: ${store}: ${errorMessage4(error2)}`, "warn");
16270
17674
  }
16271
17675
  );
16272
17676
  const abortTimer = setTimeout(() => controller.abort(), remainingMs);
@@ -16326,7 +17730,7 @@ function createCredentialSync({
16326
17730
  outcomes[store] = !result.timedOut && result.code === 0 ? "ok" : "failed";
16327
17731
  } catch (error2) {
16328
17732
  outcomes[store] = "failed";
16329
- log3(`CREDENTIAL-SYNC-TICK-ERROR: ${store}: ${errorMessage3(error2)}`, "debug");
17733
+ log3(`CREDENTIAL-SYNC-TICK-ERROR: ${store}: ${errorMessage4(error2)}`, "debug");
16330
17734
  }
16331
17735
  }
16332
17736
  const failed = STORES.some((store) => outcomes[store] === "failed");
@@ -16803,7 +18207,6 @@ function resolveFileSyncExactFiles(raw, homeDir) {
16803
18207
  }
16804
18208
  var DEFAULT_OPENCODE_START_TIMEOUT_SECONDS = 180;
16805
18209
  var MAX_OPENCODE_START_TIMEOUT_SECONDS = 3600;
16806
- var OPENCODE_START_TIMEOUT_ENV = "EVIDENT_OPENCODE_START_TIMEOUT";
16807
18210
  var OPENCODE_VERSION_ENV = "EVIDENT_OPENCODE_VERSION";
16808
18211
  function resolveOpenCodeVersion(options, env = process.env) {
16809
18212
  let raw;
@@ -17217,6 +18620,10 @@ async function driveChannels(state, driver) {
17217
18620
  let idleMs = 0;
17218
18621
  let consecutiveDrainFailures = 0;
17219
18622
  let unreachableMs = 0;
18623
+ let consecutiveOpenCodeFailures = 0;
18624
+ let openCodeFailureMs = 0;
18625
+ let consecutiveOutstandingPolls = 0;
18626
+ let outstandingWorkMs = 0;
17220
18627
  let lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
17221
18628
  let lastSeenAppliedFiles = driver.fileSyncActivity().appliedFiles;
17222
18629
  let lastSeenClaudeApplies = driver.fileSyncActivity().claudeCredentialApplies;
@@ -17234,6 +18641,9 @@ async function driveChannels(state, driver) {
17234
18641
  const cycleStartedAtMs = performance.now();
17235
18642
  let idleThisCycle = false;
17236
18643
  let unreachableThisCycle = false;
18644
+ let openCodeFailureThisCycle = false;
18645
+ let outstandingWorkThisCycle = false;
18646
+ let outstandingQueuedWork = 0;
17237
18647
  if (state.connection?.reconnecting && state.connection.reconnectPromise) {
17238
18648
  logActivity(state, { type: "info", message: "Waiting for tunnel reconnection..." });
17239
18649
  if (state.interactive) displayStatus(state);
@@ -17250,6 +18660,8 @@ async function driveChannels(state, driver) {
17250
18660
  const processed = await driver.drainPending();
17251
18661
  consecutiveDrainFailures = 0;
17252
18662
  unreachableMs = 0;
18663
+ consecutiveOpenCodeFailures = 0;
18664
+ openCodeFailureMs = 0;
17253
18665
  state.messageCount += processed;
17254
18666
  if (driver.recycleRequested) {
17255
18667
  await beginGracefulShutdown(state, "recycle");
@@ -17307,16 +18719,35 @@ async function driveChannels(state, driver) {
17307
18719
  if (processed > 0 || driver.hasInFlightWatchers() || proxiedActivity || fileActivity) {
17308
18720
  idlePolls = 0;
17309
18721
  idleMs = 0;
18722
+ consecutiveOutstandingPolls = 0;
18723
+ outstandingWorkMs = 0;
17310
18724
  if (processed > 0 && state.interactive) displayStatus(state);
17311
18725
  } else if (state.idleTimeout !== null) {
17312
- idlePolls++;
17313
- idleThisCycle = true;
17314
- if (idlePolls === 1) {
17315
- logActivity(state, {
17316
- type: "info",
17317
- message: `Queue empty, waiting (timeout: ${state.idleTimeout}s)...`
17318
- });
17319
- if (state.interactive) displayStatus(state);
18726
+ outstandingQueuedWork = driver.outstandingQueuedWork();
18727
+ if (outstandingQueuedWork > 0) {
18728
+ idlePolls = 0;
18729
+ idleMs = 0;
18730
+ consecutiveOutstandingPolls++;
18731
+ outstandingWorkThisCycle = true;
18732
+ if (consecutiveOutstandingPolls === 1) {
18733
+ logActivity(state, {
18734
+ type: "info",
18735
+ message: `${outstandingQueuedWork} queued message(s) are waiting but could not be progressed, will exit if this persists past the idle timeout (timeout: ${state.idleTimeout}s)...`
18736
+ });
18737
+ if (state.interactive) displayStatus(state);
18738
+ }
18739
+ } else {
18740
+ consecutiveOutstandingPolls = 0;
18741
+ outstandingWorkMs = 0;
18742
+ idlePolls++;
18743
+ idleThisCycle = true;
18744
+ if (idlePolls === 1) {
18745
+ logActivity(state, {
18746
+ type: "info",
18747
+ message: `Queue empty, waiting (timeout: ${state.idleTimeout}s)...`
18748
+ });
18749
+ if (state.interactive) displayStatus(state);
18750
+ }
17320
18751
  }
17321
18752
  }
17322
18753
  } catch (error2) {
@@ -17331,12 +18762,28 @@ async function driveChannels(state, driver) {
17331
18762
  state.running = false;
17332
18763
  break;
17333
18764
  }
17334
- const errorMessage4 = error2 instanceof Error ? error2.message : String(error2);
17335
- logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage4}` });
18765
+ const errorMessage5 = describeErrorWithCause(error2);
18766
+ logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage5}` });
17336
18767
  if (state.interactive) displayStatus(state);
17337
18768
  if (driver.hasInFlightWatchers()) {
17338
18769
  consecutiveDrainFailures = 0;
17339
18770
  unreachableMs = 0;
18771
+ consecutiveOpenCodeFailures = 0;
18772
+ openCodeFailureMs = 0;
18773
+ } else if (error2 instanceof LocalOpenCodeError) {
18774
+ consecutiveDrainFailures = 0;
18775
+ unreachableMs = 0;
18776
+ if (state.idleTimeout !== null) {
18777
+ consecutiveOpenCodeFailures++;
18778
+ openCodeFailureThisCycle = true;
18779
+ if (consecutiveOpenCodeFailures === 1) {
18780
+ logActivity(state, {
18781
+ type: "info",
18782
+ message: `Local OpenCode server on port ${state.port} is failing, will exit if this persists past the idle timeout (timeout: ${state.idleTimeout}s)...`
18783
+ });
18784
+ if (state.interactive) displayStatus(state);
18785
+ }
18786
+ }
17340
18787
  } else if (state.idleTimeout !== null) {
17341
18788
  consecutiveDrainFailures++;
17342
18789
  unreachableThisCycle = true;
@@ -17396,6 +18843,8 @@ async function driveChannels(state, driver) {
17396
18843
  const cycleMs = performance.now() - cycleStartedAtMs;
17397
18844
  if (idleThisCycle) idleMs += cycleMs;
17398
18845
  if (unreachableThisCycle) unreachableMs += cycleMs;
18846
+ if (openCodeFailureThisCycle) openCodeFailureMs += cycleMs;
18847
+ if (outstandingWorkThisCycle) outstandingWorkMs += cycleMs;
17399
18848
  if (state.idleTimeout !== null && consecutiveDrainFailures >= 2 && unreachableMs > state.idleTimeout * 1e3) {
17400
18849
  logActivity(state, {
17401
18850
  type: "info",
@@ -17405,6 +18854,24 @@ async function driveChannels(state, driver) {
17405
18854
  if (state.interactive) displayStatus(state);
17406
18855
  break;
17407
18856
  }
18857
+ if (state.idleTimeout !== null && consecutiveOpenCodeFailures >= 2 && openCodeFailureMs > state.idleTimeout * 1e3) {
18858
+ logActivity(state, {
18859
+ type: "info",
18860
+ level: "warn",
18861
+ message: `Exiting: could not use the local OpenCode server on port ${state.port} for ${consecutiveOpenCodeFailures} consecutive polls (${Math.round(openCodeFailureMs / 1e3)}s)`
18862
+ });
18863
+ if (state.interactive) displayStatus(state);
18864
+ break;
18865
+ }
18866
+ if (state.idleTimeout !== null && outstandingWorkThisCycle && consecutiveOutstandingPolls >= 2 && outstandingWorkMs > state.idleTimeout * 1e3 && !stayAwakeHolds()) {
18867
+ logActivity(state, {
18868
+ type: "info",
18869
+ level: "warn",
18870
+ message: `Exiting: could not progress ${outstandingQueuedWork} outstanding queued message(s) for ${consecutiveOutstandingPolls} consecutive polls (${Math.round(outstandingWorkMs / 1e3)}s)`
18871
+ });
18872
+ if (state.interactive) displayStatus(state);
18873
+ break;
18874
+ }
17408
18875
  if (state.idleTimeout !== null && idlePolls >= 2 && idleMs > state.idleTimeout * 1e3 && !stayAwakeHolds()) {
17409
18876
  logActivity(state, { type: "info", message: "Idle timeout reached" });
17410
18877
  if (state.interactive) displayStatus(state);
@@ -17427,6 +18894,8 @@ var SESSION_CLEANUP_MAX_DELETES_PER_SWEEP = 100;
17427
18894
  var SESSION_CLEANUP_MAX_ISOLATED_DELETE_FAILURES = 2;
17428
18895
  var SESSION_CLEANUP_GIVE_UP_AFTER_FAILURES = 2;
17429
18896
  var MAX_SESSION_DELETE_BODY_LENGTH = 200;
18897
+ var SESSION_ARCHIVE_FAILURE_DIAGNOSTIC_BUDGET = 3;
18898
+ var SESSION_ARCHIVE_MANIFEST_BUDGET_MS = 500;
17430
18899
  function shouldWarnForReclaimSkip(reason) {
17431
18900
  if (reason !== "sqlite-unavailable" && reason !== "disk-exhaustion") return false;
17432
18901
  const version2 = /^v(\d+)\.(\d+)\.(\d+)$/.exec(process.version);
@@ -17450,18 +18919,52 @@ function logSessionArchiveActivity(state, phase, entry) {
17450
18919
  logActivity(state, {
17451
18920
  ...entry,
17452
18921
  source: "cli.session-archive",
17453
- metadata: { ...entry.metadata, phase }
18922
+ // The forwarder drops metadata beyond its 20-entry cap in insertion order.
18923
+ metadata: { phase, ...entry.metadata }
18924
+ });
18925
+ }
18926
+ function logSessionArchiveMetadataDecodeFailure(state, phase, details) {
18927
+ const subject = details.sessionId ? `session ${details.sessionId}` : "audit manifest";
18928
+ logSessionArchiveActivity(state, phase, {
18929
+ type: "info",
18930
+ level: "warn",
18931
+ message: `Session archive: ${subject} upload returned malformed ${details.field} metadata; the upload succeeded without that value`,
18932
+ metadata: {
18933
+ outcome: "archive-upload-metadata-malformed",
18934
+ metadata_field: details.field,
18935
+ metadata_decode_reason: details.reason,
18936
+ ...details.sessionId ? { session_id: details.sessionId } : {},
18937
+ ...details.manifestKey ? { manifest_key: details.manifestKey } : {}
18938
+ }
17454
18939
  });
17455
18940
  }
17456
- function logSessionArchiveSummary(state, phase, summary) {
18941
+ function logSessionArchiveSummary(state, phase, summary, reconciliation) {
17457
18942
  const everyUploadFailed = summary.uploadAttempts > 0 && summary.uploadFailures === summary.uploadAttempts;
17458
- const staleSince = everyUploadFailed && summary.staleSince !== null ? `; archive stale since ${summary.staleSince}` : "";
17459
18943
  const neverWatermarked = summary.neverWatermarkedFailures > 0 ? `; ${summary.neverWatermarkedFailures} failed session(s) had no prior successful upload` : "";
17460
18944
  const warning2 = summary.failed > 0 || summary.failures.length > 0 || everyUploadFailed || !summary.reconciliationComplete;
18945
+ if (!reconciliation.complete) {
18946
+ const failure = reconciliation.failures[0];
18947
+ 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}`;
18948
+ logSessionArchiveActivity(state, phase, {
18949
+ type: "info",
18950
+ level: "warn",
18951
+ message: `Session archive: binding reconciliation incomplete for runner ${state.agentId}; ${reconciliation.failures.length} chunk(s) failed (${detail}), unresolved sessions will not replace existing archives`,
18952
+ metadata: {
18953
+ outcome: "binding-reconciliation-incomplete",
18954
+ runner_id: state.agentId,
18955
+ failed_chunks: reconciliation.failures.length,
18956
+ first_failed_chunk: failure.chunk,
18957
+ first_failure_kind: failure.kind,
18958
+ ...failure.status !== void 0 ? { http_status: failure.status } : {}
18959
+ }
18960
+ });
18961
+ }
17461
18962
  logSessionArchiveActivity(state, phase, {
17462
18963
  type: "info",
17463
18964
  level: warning2 ? "warn" : "info",
17464
- 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,
18965
+ 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,
18966
+ // Keep this summary at the forwarder's 20-entry metadata cap; phase is
18967
+ // prepended by logSessionArchiveActivity.
17465
18968
  metadata: {
17466
18969
  outcome: "archive-run-complete",
17467
18970
  sessions_inspected: summary.inspected,
@@ -17472,7 +18975,6 @@ function logSessionArchiveSummary(state, phase, summary) {
17472
18975
  uploads_failed: summary.uploadFailures,
17473
18976
  sessions_skipped_budget: summary.skippedBudget,
17474
18977
  sessions_unmapped: summary.unmappedIds.length,
17475
- sessions_unresolved: summary.unresolved,
17476
18978
  sessions_conflicted: summary.conflicts,
17477
18979
  sessions_reconciliation_incomplete: summary.reconciliationIncomplete,
17478
18980
  binding_reconciliation_complete: summary.reconciliationComplete,
@@ -17482,11 +18984,10 @@ function logSessionArchiveSummary(state, phase, summary) {
17482
18984
  bindings_from_invocation: summary.bindingSourceCounts.invocation,
17483
18985
  bindings_from_history: summary.bindingSourceCounts.history,
17484
18986
  bindings_from_parent: summary.bindingSourceCounts.parent,
17485
- sessions_without_prior_watermark: summary.neverWatermarkedFailures,
17486
- ...everyUploadFailed && summary.staleSince !== null ? { stale_since: summary.staleSince } : {}
18987
+ sessions_without_prior_watermark: summary.neverWatermarkedFailures
17487
18988
  }
17488
18989
  });
17489
- for (const failure of summary.failures) {
18990
+ const logFailure = (failure) => {
17490
18991
  const permanentSizeFailure = failure.reason === "too-large";
17491
18992
  const hasPayloadDetails = failure.bytes !== void 0 && failure.byteLimit !== void 0 && failure.messageCount !== void 0 && failure.partCount !== void 0;
17492
18993
  const payloadDetails = hasPayloadDetails ? `; payload bytes=${failure.bytes} limit=${failure.byteLimit} messages=${failure.messageCount} parts=${failure.partCount}` : "";
@@ -17509,7 +19010,9 @@ function logSessionArchiveSummary(state, phase, summary) {
17509
19010
  } : {}
17510
19011
  }
17511
19012
  });
17512
- }
19013
+ };
19014
+ const failuresToLog = phase === "sweep" ? summary.failures : summary.failures.slice(0, SESSION_ARCHIVE_FAILURE_DIAGNOSTIC_BUDGET);
19015
+ for (const failure of failuresToLog) logFailure(failure);
17513
19016
  if (summary.unmappedIds.length > 0) {
17514
19017
  logSessionArchiveActivity(state, phase, {
17515
19018
  type: "info",
@@ -17533,6 +19036,117 @@ function logSessionArchiveSummary(state, phase, summary) {
17533
19036
  });
17534
19037
  }
17535
19038
  }
19039
+ function hasSessionArchivePrerequisites(state) {
19040
+ return Boolean(
19041
+ state.opencodeClient && state.sessionArchiveConfig.keyPrefix && state.sessionArchiveWatermarkPath && state.agentId
19042
+ );
19043
+ }
19044
+ async function publishSessionArchiveAudit(state, phase, identity, summary, manifestWindowMs, manifestSignal, parentSignal) {
19045
+ if (!hasSessionArchivePrerequisites(state)) return;
19046
+ const manifestKey = sessionArchiveManifestKey(state.sessionArchiveConfig.keyPrefix, identity);
19047
+ let manifestDurable = false;
19048
+ let manifestVersionId = null;
19049
+ let failure = null;
19050
+ if (parentSignal.aborted) {
19051
+ failure = { kind: "not-attempted", reason: "pass-aborted" };
19052
+ } else if (manifestWindowMs <= 0) {
19053
+ failure = { kind: "not-attempted", reason: "no-manifest-budget" };
19054
+ } else {
19055
+ try {
19056
+ const result = await uploadSessionArchiveManifest({
19057
+ keyPrefix: state.sessionArchiveConfig.keyPrefix,
19058
+ identity,
19059
+ summary,
19060
+ timeoutMs: manifestWindowMs,
19061
+ signal: manifestSignal,
19062
+ upload: uploadSessionArchive,
19063
+ onMetadataDecodeError: (field, reason) => logSessionArchiveMetadataDecodeFailure(state, phase, {
19064
+ field,
19065
+ reason,
19066
+ manifestKey
19067
+ })
19068
+ });
19069
+ if (result.outcome.kind === "ok") {
19070
+ manifestDurable = true;
19071
+ manifestVersionId = result.outcome.versionId;
19072
+ } else {
19073
+ failure = {
19074
+ kind: result.outcome.kind,
19075
+ ..."reason" in result.outcome ? { reason: result.outcome.reason } : {},
19076
+ ..."exitCode" in result.outcome && result.outcome.exitCode !== void 0 ? { exitCode: result.outcome.exitCode } : {}
19077
+ };
19078
+ }
19079
+ } catch (error2) {
19080
+ const diagnostic = redactDiagnosticText(
19081
+ error2 instanceof Error ? error2.message : String(error2)
19082
+ ).replace(/[\r\n]+/g, " ").slice(0, 200);
19083
+ logSessionArchiveActivity(state, phase, {
19084
+ type: "info",
19085
+ level: "warn",
19086
+ message: `Session archive audit manifest upload threw for boot ${identity.bootId}, pass ${identity.passSequence}, phase ${phase}: ${diagnostic}`,
19087
+ metadata: {
19088
+ outcome: "archive-audit-manifest-upload-threw",
19089
+ boot_id: identity.bootId,
19090
+ pass_sequence: identity.passSequence
19091
+ }
19092
+ });
19093
+ failure = { kind: "thrown", reason: "upload-threw" };
19094
+ }
19095
+ }
19096
+ if (failure !== null) {
19097
+ logSessionArchiveActivity(state, phase, {
19098
+ type: "info",
19099
+ level: "warn",
19100
+ message: `Session archive audit manifest was not durable for ${phase} pass ${identity.passSequence}: ${failure.kind}${failure.reason ? ` (${failure.reason})` : ""}`,
19101
+ metadata: {
19102
+ outcome: "archive-audit-manifest-failed",
19103
+ boot_id: identity.bootId,
19104
+ pass_sequence: identity.passSequence,
19105
+ manifest_key: manifestKey,
19106
+ kind: failure.kind,
19107
+ ...failure.reason !== void 0 ? { reason: failure.reason } : {},
19108
+ ...failure.exitCode !== void 0 ? { exit_code: failure.exitCode } : {}
19109
+ }
19110
+ });
19111
+ }
19112
+ const sessionsInspected = summary?.inspected ?? 0;
19113
+ const sessionsUploaded = summary?.uploaded ?? 0;
19114
+ const sessionsUnchanged = summary?.unchanged ?? 0;
19115
+ const sessionsFailed = summary?.failed ?? 0;
19116
+ const sessionsSkippedChanged = summary?.skippedChanged ?? 0;
19117
+ const sessionsSkippedUnknown = summary?.skippedUnknown ?? 0;
19118
+ const outcomesReconciled = summary?.outcomesReconciled ?? null;
19119
+ const retries = summary?.uploadedSessions.filter(({ retriedPriorFailure }) => retriedPriorFailure).length ?? 0;
19120
+ const everyUploadFailed = summary !== null && summary.uploadAttempts > 0 && summary.uploadFailures === summary.uploadAttempts;
19121
+ const level = summary === null || !summary.outcomesReconciled || summary.skippedChanged > 0 ? "warn" : "info";
19122
+ 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}`;
19123
+ logSessionArchiveActivity(state, phase, {
19124
+ type: "info",
19125
+ level,
19126
+ message,
19127
+ metadata: {
19128
+ outcome: "archive-outcome-audit",
19129
+ boot_id: identity.bootId,
19130
+ pass_sequence: identity.passSequence,
19131
+ enumeration_complete: identity.enumerationComplete,
19132
+ sessions_inspected: sessionsInspected,
19133
+ sessions_uploaded: sessionsUploaded,
19134
+ sessions_unchanged: sessionsUnchanged,
19135
+ sessions_failed: sessionsFailed,
19136
+ sessions_skipped_changed: sessionsSkippedChanged,
19137
+ sessions_skipped_unknown: sessionsSkippedUnknown,
19138
+ outcomes_reconciled: outcomesReconciled,
19139
+ manifest_durable: manifestDurable,
19140
+ manifest_key: manifestKey,
19141
+ manifest_version_id: manifestVersionId,
19142
+ watermark_file_present: identity.watermarkFilePresent,
19143
+ watermarks_loaded: identity.watermarksLoaded,
19144
+ uploads_retrying_prior_failures: retries,
19145
+ ...summary === null ? { enumeration_reason: identity.enumerationReason ?? "unknown" } : {},
19146
+ ...everyUploadFailed && summary?.staleSince !== null ? { stale_since: summary.staleSince } : {}
19147
+ }
19148
+ });
19149
+ }
17536
19150
  async function drainSessionDeletionReports(state) {
17537
19151
  const path = sessionDeletionReportPath(homedir9(), process.env);
17538
19152
  let delivered = 0;
@@ -17950,14 +19564,10 @@ function runSessionArchiveTask(state, phase, budgetMs, work) {
17950
19564
  }
17951
19565
  const controller = new AbortController();
17952
19566
  state.sessionArchiveAbortController = controller;
19567
+ let budgetExceeded = false;
17953
19568
  const timeout = setTimeout(() => {
19569
+ budgetExceeded = true;
17954
19570
  controller.abort();
17955
- logSessionArchiveActivity(state, phase, {
17956
- type: "info",
17957
- level: "warn",
17958
- message: `Session archive exceeded ${budgetMs}ms; remaining sessions were not confirmed archived`,
17959
- metadata: { outcome: "archive-budget-exceeded", budget_ms: budgetMs }
17960
- });
17961
19571
  }, budgetMs);
17962
19572
  const task = Promise.resolve().then(() => work(controller.signal)).catch((error2) => {
17963
19573
  logSessionArchiveActivity(state, phase, {
@@ -17968,6 +19578,19 @@ function runSessionArchiveTask(state, phase, budgetMs, work) {
17968
19578
  });
17969
19579
  return null;
17970
19580
  }).finally(() => {
19581
+ if (budgetExceeded) {
19582
+ logSessionArchiveActivity(state, phase, {
19583
+ type: "info",
19584
+ level: "warn",
19585
+ message: `Session archive exceeded ${budgetMs}ms; remaining sessions were not confirmed archived`,
19586
+ metadata: {
19587
+ outcome: "archive-budget-exceeded",
19588
+ budget_ms: budgetMs,
19589
+ boot_id: state.sessionArchiveBootId,
19590
+ pass_sequence: state.sessionArchivePassSequence
19591
+ }
19592
+ });
19593
+ }
17971
19594
  clearTimeout(timeout);
17972
19595
  if (state.sessionArchiveInFlight === task) {
17973
19596
  state.sessionArchiveInFlight = null;
@@ -17978,10 +19601,7 @@ function runSessionArchiveTask(state, phase, budgetMs, work) {
17978
19601
  return task;
17979
19602
  }
17980
19603
  async function runSessionArchiveBatch(state, phase, sessions, budgetMs, signal) {
17981
- const config = state.sessionArchiveConfig;
17982
- const client = state.opencodeClient;
17983
- const watermarkPath = state.sessionArchiveWatermarkPath;
17984
- if (!client || !config.keyPrefix || !watermarkPath || !state.agentId) {
19604
+ if (!hasSessionArchivePrerequisites(state)) {
17985
19605
  logSessionArchiveActivity(state, phase, {
17986
19606
  type: "info",
17987
19607
  level: "warn",
@@ -17990,6 +19610,9 @@ async function runSessionArchiveBatch(state, phase, sessions, budgetMs, signal)
17990
19610
  });
17991
19611
  return null;
17992
19612
  }
19613
+ const config = state.sessionArchiveConfig;
19614
+ const client = state.opencodeClient;
19615
+ const watermarkPath = state.sessionArchiveWatermarkPath;
17993
19616
  const bindings = readSessionBindings(
17994
19617
  sessionBindingLedgerPath(homedir9(), process.env),
17995
19618
  (message) => logSessionArchiveActivity(state, phase, {
@@ -18006,23 +19629,6 @@ async function runSessionArchiveBatch(state, phase, sessions, budgetMs, signal)
18006
19629
  sessions,
18007
19630
  signal
18008
19631
  });
18009
- if (!reconciliation.complete) {
18010
- const failure = reconciliation.failures[0];
18011
- 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}`;
18012
- logSessionArchiveActivity(state, phase, {
18013
- type: "info",
18014
- level: "warn",
18015
- message: `Session archive: binding reconciliation incomplete for runner ${state.agentId}; ${reconciliation.failures.length} chunk(s) failed (${detail}), unresolved sessions will not replace existing archives`,
18016
- metadata: {
18017
- outcome: "binding-reconciliation-incomplete",
18018
- runner_id: state.agentId,
18019
- failed_chunks: reconciliation.failures.length,
18020
- first_failed_chunk: failure.chunk,
18021
- first_failure_kind: failure.kind,
18022
- ...failure.status !== void 0 ? { http_status: failure.status } : {}
18023
- }
18024
- });
18025
- }
18026
19632
  const summary = await runSessionArchive({
18027
19633
  sessions,
18028
19634
  deps: {
@@ -18033,40 +19639,97 @@ async function runSessionArchiveBatch(state, phase, sessions, budgetMs, signal)
18033
19639
  projection: reconciliation.projection,
18034
19640
  reconciliationComplete: reconciliation.complete,
18035
19641
  watermarks: state.sessionArchiveWatermarks,
19642
+ priorFailureIds: state.sessionArchivePriorFailureIds,
18036
19643
  watermarkPath,
18037
19644
  signal,
19645
+ onMetadataDecodeError: (field, reason, sessionId) => logSessionArchiveMetadataDecodeFailure(state, phase, { field, reason, sessionId }),
18038
19646
  upload: uploadSessionArchive,
18039
19647
  exportMessages: exportSessionMessages,
18040
19648
  recordWatermark: recordUpload
18041
19649
  },
18042
19650
  budgetMs
18043
19651
  });
18044
- logSessionArchiveSummary(state, phase, summary);
19652
+ logSessionArchiveSummary(state, phase, summary, reconciliation);
18045
19653
  return summary;
18046
19654
  }
18047
19655
  async function runSessionArchiveFleet(state, phase, budgetMs, signal) {
19656
+ state.sessionArchivePassSequence++;
18048
19657
  const startedAt = Date.now();
18049
- const enumeration = await listAllSessions(state.port, state.opencodeClient ?? void 0, signal);
18050
- if (enumeration.sessions === null) {
18051
- const interrupted = signal.aborted;
18052
- logSessionArchiveActivity(state, phase, {
18053
- type: "info",
18054
- level: "warn",
18055
- 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`,
18056
- metadata: {
18057
- outcome: interrupted ? "enumeration-interrupted" : "enumeration-refused",
18058
- ...!interrupted ? { reason: enumeration.reason } : {}
19658
+ const passDeadline = startedAt + budgetMs;
19659
+ const workDeadline = passDeadline - SESSION_ARCHIVE_MANIFEST_BUDGET_MS;
19660
+ const watermarksLoaded = state.sessionArchiveWatermarks.size;
19661
+ const workBudget = createBudgetSignal(signal, Math.max(0, workDeadline - Date.now()));
19662
+ let summary = null;
19663
+ let enumerationComplete = false;
19664
+ let enumerationReason = null;
19665
+ try {
19666
+ const enumeration = await listAllSessions(
19667
+ state.port,
19668
+ state.opencodeClient ?? void 0,
19669
+ workBudget.signal
19670
+ );
19671
+ if (enumeration.sessions === null) {
19672
+ enumerationComplete = false;
19673
+ enumerationReason = workBudget.signal.aborted ? "enumeration-interrupted" : enumeration.reason;
19674
+ const interrupted = workBudget.signal.aborted;
19675
+ logSessionArchiveActivity(state, phase, {
19676
+ type: "info",
19677
+ level: "warn",
19678
+ 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`,
19679
+ metadata: {
19680
+ outcome: interrupted ? "enumeration-interrupted" : "enumeration-refused",
19681
+ ...!interrupted ? { reason: enumerationReason } : {}
19682
+ }
19683
+ });
19684
+ } else {
19685
+ enumerationComplete = true;
19686
+ enumerationReason = null;
19687
+ const enumeratedIds = new Set(enumeration.sessions.map(({ id }) => id));
19688
+ for (const sessionId of state.sessionArchivePriorFailureIds) {
19689
+ if (!enumeratedIds.has(sessionId)) state.sessionArchivePriorFailureIds.delete(sessionId);
18059
19690
  }
18060
- });
18061
- return null;
19691
+ summary = await runSessionArchiveBatch(
19692
+ state,
19693
+ phase,
19694
+ enumeration.sessions,
19695
+ Math.max(0, workDeadline - Date.now()),
19696
+ workBudget.signal
19697
+ );
19698
+ }
19699
+ } finally {
19700
+ workBudget.dispose();
18062
19701
  }
18063
- return runSessionArchiveBatch(
18064
- state,
18065
- phase,
18066
- enumeration.sessions,
18067
- Math.max(0, budgetMs - (Date.now() - startedAt)),
18068
- signal
18069
- );
19702
+ const manifestWindowMs = Math.max(0, passDeadline - Date.now());
19703
+ const manifestBudget = createBudgetSignal(signal, manifestWindowMs);
19704
+ try {
19705
+ if (summary !== null || !enumerationComplete) {
19706
+ const identity = {
19707
+ runnerId: state.agentId,
19708
+ bootId: state.sessionArchiveBootId,
19709
+ passSequence: state.sessionArchivePassSequence,
19710
+ phase,
19711
+ startedAt: new Date(startedAt).toISOString(),
19712
+ completedAt: new Date(Date.now()).toISOString(),
19713
+ budgetMs,
19714
+ enumerationComplete,
19715
+ enumerationReason,
19716
+ watermarkFilePresent: state.sessionArchiveWatermarkFileLoaded,
19717
+ watermarksLoaded
19718
+ };
19719
+ await publishSessionArchiveAudit(
19720
+ state,
19721
+ phase,
19722
+ identity,
19723
+ summary,
19724
+ manifestWindowMs,
19725
+ manifestBudget.signal,
19726
+ signal
19727
+ );
19728
+ }
19729
+ } finally {
19730
+ manifestBudget.dispose();
19731
+ }
19732
+ return summary;
18070
19733
  }
18071
19734
  async function runSessionArchiveShutdownFlush(state, budgetMs) {
18072
19735
  const deadline = Date.now() + budgetMs;
@@ -18089,7 +19752,13 @@ async function runSessionArchiveShutdownFlush(state, budgetMs) {
18089
19752
  type: "info",
18090
19753
  level: "warn",
18091
19754
  message: `Session archive exceeded ${budgetMs}ms while stopping a prior run; remaining sessions were not confirmed archived`,
18092
- metadata: { outcome: "archive-budget-exceeded", budget_ms: budgetMs }
19755
+ metadata: {
19756
+ outcome: "archive-budget-exceeded",
19757
+ budget_ms: budgetMs,
19758
+ boot_id: state.sessionArchiveBootId,
19759
+ pass_sequence: state.sessionArchivePassSequence,
19760
+ manifest_written: false
19761
+ }
18093
19762
  });
18094
19763
  return null;
18095
19764
  }
@@ -18100,7 +19769,13 @@ async function runSessionArchiveShutdownFlush(state, budgetMs) {
18100
19769
  type: "info",
18101
19770
  level: "warn",
18102
19771
  message: `Session archive exceeded ${budgetMs}ms while stopping a prior run; remaining sessions were not confirmed archived`,
18103
- metadata: { outcome: "archive-budget-exceeded", budget_ms: budgetMs }
19772
+ metadata: {
19773
+ outcome: "archive-budget-exceeded",
19774
+ budget_ms: budgetMs,
19775
+ boot_id: state.sessionArchiveBootId,
19776
+ pass_sequence: state.sessionArchivePassSequence,
19777
+ manifest_written: false
19778
+ }
18104
19779
  });
18105
19780
  return null;
18106
19781
  }
@@ -18124,6 +19799,7 @@ function scheduleSessionArchive(state) {
18124
19799
  metadata: { outcome: "watermark-read-failed" }
18125
19800
  })
18126
19801
  );
19802
+ state.sessionArchiveWatermarkFileLoaded = state.sessionArchiveWatermarks.size > 0;
18127
19803
  logSessionArchiveActivity(state, "startup", {
18128
19804
  type: "info",
18129
19805
  message: `Session archive enabled (interval=${config.intervalMs}ms)`,
@@ -18633,9 +20309,13 @@ async function run(options) {
18633
20309
  ),
18634
20310
  sessionArchiveTimers: [],
18635
20311
  sessionArchiveWatermarks: /* @__PURE__ */ new Map(),
20312
+ sessionArchivePriorFailureIds: /* @__PURE__ */ new Set(),
18636
20313
  sessionArchiveWatermarkPath: null,
18637
20314
  sessionArchiveInFlight: null,
18638
20315
  sessionArchiveAbortController: null,
20316
+ sessionArchiveBootId: randomUUID2(),
20317
+ sessionArchivePassSequence: 0,
20318
+ sessionArchiveWatermarkFileLoaded: false,
18639
20319
  sessionDeleteFailures: /* @__PURE__ */ new Map(),
18640
20320
  claudeUsageTimer: null,
18641
20321
  claudeUsageRearm: null,
@@ -19096,7 +20776,7 @@ async function run(options) {
19096
20776
  port: state.port,
19097
20777
  interactive: state.interactive,
19098
20778
  agentId: state.agentId,
19099
- log: (message) => log2(state, message),
20779
+ log: (message, level = "info") => log2(state, message, level),
19100
20780
  startTimeoutMs: opencodeStartTimeoutMs,
19101
20781
  inheritStdio: Boolean(options.opencodePidFile),
19102
20782
  command: opencodeV2Command
@@ -19104,10 +20784,15 @@ async function run(options) {
19104
20784
  port: state.port,
19105
20785
  interactive: state.interactive,
19106
20786
  agentId: state.agentId,
19107
- log: (message) => log2(state, message),
20787
+ log: (message, level = "info") => log2(state, message, level),
19108
20788
  startTimeoutMs: opencodeStartTimeoutMs,
19109
20789
  inheritStdio: Boolean(options.opencodePidFile)
19110
20790
  });
20791
+ if (oc.reclaimOutcome) {
20792
+ const outcome = oc.reclaimOutcome;
20793
+ 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.`;
20794
+ logActivity(state, { type: "info", level: "warn", message });
20795
+ }
19111
20796
  state.port = oc.port;
19112
20797
  state.opencodeProcess = options.opencodePidFile ? null : oc.process;
19113
20798
  state.opencodeVersion = oc.version;
@@ -19151,7 +20836,7 @@ async function run(options) {
19151
20836
  password: state.opencodePassword
19152
20837
  });
19153
20838
  state.opencodeClient = openCodeClient;
19154
- if (options.opencodePidFile && oc.process?.pid !== void 0) {
20839
+ if (options.opencodePidFile && oc.process?.pid !== void 0 && oc.process.exitCode === null && oc.process.signalCode === null) {
19155
20840
  try {
19156
20841
  writeFileSync9(options.opencodePidFile, `${oc.process.pid}
19157
20842
  `, { mode: 384 });
@@ -19162,6 +20847,12 @@ async function run(options) {
19162
20847
  error: `Failed to write OpenCode pid file ${options.opencodePidFile}: ${error2 instanceof Error ? error2.message : String(error2)}`
19163
20848
  });
19164
20849
  }
20850
+ } else if (options.opencodePidFile && oc.process?.pid !== void 0) {
20851
+ logActivity(state, {
20852
+ type: "info",
20853
+ level: "warn",
20854
+ message: `OpenCode pid file ${options.opencodePidFile} was left unchanged because the process spawned for this run had already exited.`
20855
+ });
19165
20856
  }
19166
20857
  if (state.opencodeVersion !== null) {
19167
20858
  const provenance = checkSessionDbProvenance({
@@ -19208,7 +20899,7 @@ async function run(options) {
19208
20899
  const version2 = state.opencodeVersion ? ` (v${state.opencodeVersion})` : "";
19209
20900
  ocSpinner?.succeed(`OpenCode running on port ${state.port}${version2}`);
19210
20901
  if (!state.interactive && oc.notReadyReason !== null) {
19211
- 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}).`;
20902
+ 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.`;
19212
20903
  logActivity(state, { type: "info", level: "warn", message });
19213
20904
  } else {
19214
20905
  const versionWarning = buildOpenCodeVersionWarning(
@@ -19454,7 +21145,7 @@ async function run(options) {
19454
21145
  if (state.interactive) displayStatus(state);
19455
21146
  }
19456
21147
  }).catch((error2) => {
19457
- const message = error2 instanceof Error ? error2.message : String(error2);
21148
+ const message = describeErrorWithCause(error2);
19458
21149
  logActivity(state, {
19459
21150
  type: "error",
19460
21151
  error: `Failed to drain queued messages on connect: ${message}`
@@ -19521,7 +21212,7 @@ async function run(options) {
19521
21212
  if (state.interactive) displayStatus(state);
19522
21213
  }
19523
21214
  }).catch((error2) => {
19524
- const message = error2 instanceof Error ? error2.message : String(error2);
21215
+ const message = describeErrorWithCause(error2);
19525
21216
  logActivity(state, {
19526
21217
  type: "error",
19527
21218
  error: `Failed to drain queued messages on ping: ${message}`
@@ -19618,24 +21309,95 @@ async function run(options) {
19618
21309
  }
19619
21310
  }
19620
21311
 
21312
+ // src/commands/teams.ts
21313
+ function printTeam(team, selected) {
21314
+ console.log(`${selected ? "* " : " "}${team.id} ${team.name}`);
21315
+ }
21316
+ function isTeam(value) {
21317
+ return typeof value === "object" && value !== null && typeof value.id === "string" && typeof value.name === "string";
21318
+ }
21319
+ async function teams() {
21320
+ const apiUrl = getApiUrlConfig();
21321
+ let credentials2;
21322
+ try {
21323
+ credentials2 = await getAuthCredentials();
21324
+ } catch (error2) {
21325
+ printError(
21326
+ `Could not read the saved Evident credentials: ${error2 instanceof Error ? error2.message : String(error2)}`
21327
+ );
21328
+ process.exitCode = 1;
21329
+ return;
21330
+ }
21331
+ if (!credentials2) {
21332
+ printError(`Not logged in to ${apiUrl}. Run the \`login\` command to authenticate.`);
21333
+ process.exitCode = 1;
21334
+ return;
21335
+ }
21336
+ try {
21337
+ const response = await fetch(`${apiUrl}/teams`, {
21338
+ headers: buildAuthHeaders(credentials2)
21339
+ });
21340
+ if (!response.ok) {
21341
+ const serverMessage = await readErrorMessage(response);
21342
+ throw new Error(
21343
+ `Evident returned HTTP ${response.status} while listing teams${serverMessage ? `: ${serverMessage}` : ""}`
21344
+ );
21345
+ }
21346
+ const data = await response.json();
21347
+ if (!Array.isArray(data) || !data.every(isTeam)) {
21348
+ throw new Error("Evident returned an invalid team list. Update the CLI and retry.");
21349
+ }
21350
+ const selectedTeam = getTeamSelection();
21351
+ blank();
21352
+ if (data.length === 0) {
21353
+ console.log("No teams found for this account.");
21354
+ blank();
21355
+ return;
21356
+ }
21357
+ for (const team of data) {
21358
+ printTeam(team, team.id === selectedTeam);
21359
+ }
21360
+ if (data.length === 1) {
21361
+ console.log("This is your only team; commands act in it automatically.");
21362
+ } else if (!selectedTeam) {
21363
+ console.log("Choose a team with --team <id> or set EVIDENT_TEAM.");
21364
+ }
21365
+ blank();
21366
+ } catch (error2) {
21367
+ printError(`Could not list teams: ${error2 instanceof Error ? error2.message : String(error2)}`);
21368
+ process.exitCode = 1;
21369
+ }
21370
+ }
21371
+
19621
21372
  // src/index.ts
19622
21373
  var version = getCliVersion();
19623
21374
  var program = new Command();
19624
21375
  program.name("evident").description("Run OpenCode locally and connect it to Evident").version(version).option(
19625
21376
  "--endpoint <url>",
19626
21377
  "Evident API base URL (default: production; e.g. http://localhost:3001)"
19627
- ).option("--tunnel <url>", "Tunnel WebSocket URL (default: production; e.g. ws://localhost:8787)").hook("preAction", (thisCommand) => {
19628
- const { endpoint: endpoint2, tunnel } = thisCommand.opts();
21378
+ ).option("--tunnel <url>", "Tunnel WebSocket URL (default: production; e.g. ws://localhost:8787)").option(
21379
+ "--team <id>",
21380
+ "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"
21381
+ ).hook("preAction", (thisCommand) => {
21382
+ const { endpoint: endpoint2, tunnel, team } = thisCommand.optsWithGlobals();
19629
21383
  if (endpoint2) {
19630
21384
  setEndpoint(endpoint2);
19631
21385
  }
19632
21386
  if (tunnel) {
19633
21387
  setTunnelUrl(tunnel);
19634
21388
  }
21389
+ setTeamSelection(team);
19635
21390
  });
19636
21391
  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);
19637
21392
  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 }));
19638
21393
  program.command("whoami").description("Show the currently logged in user").action(whoami);
21394
+ program.command("teams").description("List the teams you belong to").action(teams);
21395
+ 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(
21396
+ (proxyId, connectionId, options) => authorizeMcpConnection(proxyId, connectionId, {
21397
+ noBrowser: options.browser === false,
21398
+ json: options.json
21399
+ })
21400
+ );
19639
21401
  program.command("status").description("Check whether the configured credentials can reach Evident").option("--json", "Output in JSON format").action((options) => status({ json: options.json }));
19640
21402
  program.command("credential-vault-env").description("Print the shell assignment a runner image evals before starting the synchroniser").action(credentialVaultEnv);
19641
21403
  program.command("claude-usage").description("[spike] Show Claude subscription usage (requires a local `claude login`)").action(claudeUsage);