@evident-ai/cli 3.6.1-dev.3acfa88 → 3.6.1-dev.3f69f39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,9 @@
1
1
  #!/usr/bin/env node
2
+ var __defProp = Object.defineProperty;
3
+ var __export = (target, all) => {
4
+ for (var name in all)
5
+ __defProp(target, name, { get: all[name], enumerable: true });
6
+ };
2
7
 
3
8
  // src/index.ts
4
9
  import { Command } from "commander";
@@ -9,6 +14,24 @@ import ora from "ora";
9
14
  import chalk2 from "chalk";
10
15
 
11
16
  // src/lib/config.ts
17
+ var config_exports = {};
18
+ __export(config_exports, {
19
+ clearAllCredentials: () => clearAllCredentials,
20
+ clearCredentials: () => clearCredentials,
21
+ clearManagedInferenceCredential: () => clearManagedInferenceCredential,
22
+ credentials: () => credentials,
23
+ getApiUrlConfig: () => getApiUrlConfig,
24
+ getCliName: () => getCliName,
25
+ getCredentials: () => getCredentials,
26
+ getManagedInferenceCredential: () => getManagedInferenceCredential,
27
+ getTeamSelection: () => getTeamSelection,
28
+ getTunnelUrlConfig: () => getTunnelUrlConfig,
29
+ setCredentials: () => setCredentials,
30
+ setEndpoint: () => setEndpoint,
31
+ setManagedInferenceCredential: () => setManagedInferenceCredential,
32
+ setTeamSelection: () => setTeamSelection,
33
+ setTunnelUrl: () => setTunnelUrl
34
+ });
12
35
  import Conf from "conf";
13
36
  import { chmodSync, existsSync, statSync } from "node:fs";
14
37
  import { dirname } from "node:path";
@@ -20,6 +43,7 @@ var defaults = {
20
43
  };
21
44
  var endpointOverride;
22
45
  var tunnelOverride;
46
+ var teamOverride;
23
47
  function setEndpoint(url) {
24
48
  if (!url) {
25
49
  endpointOverride = void 0;
@@ -31,6 +55,13 @@ function setEndpoint(url) {
31
55
  function setTunnelUrl(url) {
32
56
  tunnelOverride = url ? url.replace(/\/+$/, "") : void 0;
33
57
  }
58
+ function setTeamSelection(id) {
59
+ const trimmed = id?.trim();
60
+ teamOverride = trimmed || void 0;
61
+ }
62
+ function getTeamSelection() {
63
+ return teamOverride ?? (process.env.EVIDENT_TEAM?.trim() || void 0);
64
+ }
34
65
  function getApiUrl() {
35
66
  return endpointOverride ?? process.env.EVIDENT_API_URL ?? defaults.apiUrl;
36
67
  }
@@ -579,6 +610,14 @@ function getAuthHeader(credentials2) {
579
610
  }
580
611
  return `Bearer ${credentials2.token}`;
581
612
  }
613
+ function buildAuthHeaders(credentials2) {
614
+ const headers = { Authorization: getAuthHeader(credentials2) };
615
+ const team = Object.hasOwn(config_exports, "getTeamSelection") ? getTeamSelection() : void 0;
616
+ if (credentials2.authType === "bearer" && team) {
617
+ headers["X-Evident-Team"] = team;
618
+ }
619
+ return headers;
620
+ }
582
621
  function isInteractive(jsonOutput) {
583
622
  if (jsonOutput) return false;
584
623
  if (process.env.CI) return false;
@@ -1178,11 +1217,10 @@ async function claudeUsage() {
1178
1217
  }
1179
1218
  }
1180
1219
 
1181
- // src/commands/run.ts
1182
- import { chmodSync as chmodSync3, existsSync as existsSync3, readFileSync as readFileSync12, writeFileSync as writeFileSync9 } from "node:fs";
1183
- import { homedir as homedir9 } from "node:os";
1184
- import { isAbsolute as isAbsolute6, join as join17, parse, resolve as resolvePath2 } from "node:path";
1185
- import chalk7 from "chalk";
1220
+ // src/commands/mcp-authorize.ts
1221
+ import { createServer } from "node:http";
1222
+ import { randomBytes } from "node:crypto";
1223
+ import open2 from "open";
1186
1224
 
1187
1225
  // ../../packages/types/src/agents/index.ts
1188
1226
  var MICROVM_MAX_LIFETIME_MS = 8 * 60 * 6e4;
@@ -1443,6 +1481,14 @@ function buildCredentialProxyNativeConfig({
1443
1481
  };
1444
1482
  }
1445
1483
 
1484
+ // ../../packages/types/src/mcp-proxies.ts
1485
+ var MCP_LOOPBACK_REDIRECT_POLICY = {
1486
+ scheme: "http",
1487
+ host: "127.0.0.1",
1488
+ path: "/callback",
1489
+ preferred_port: 18443
1490
+ };
1491
+
1446
1492
  // ../../packages/types/src/logging/index.ts
1447
1493
  var CORRELATION_ID_HEADER = "x-evident-correlation-id";
1448
1494
  var FORWARD_FAILURE_REASON_HEADER = "X-Evident-Failure-Reason";
@@ -1477,12 +1523,936 @@ function stripQuery(url) {
1477
1523
  }
1478
1524
  }
1479
1525
 
1526
+ // src/commands/mcp-authorize.ts
1527
+ var API_TIMEOUT_MS = 1e4;
1528
+ var CALLBACK_PAGE_FINAL_READ_TIMEOUT_MS = 2e3;
1529
+ var COMPLETION_UNCONFIRMED_MESSAGE = "Completion could not be confirmed; check the connection in Evident before retrying.";
1530
+ var KNOWN_CALLBACK_PARAMETERS = /* @__PURE__ */ new Set(["state", "code", "error", "error_description", "iss"]);
1531
+ var ApiHttpError = class extends Error {
1532
+ constructor(status2, operation) {
1533
+ super(`Evident API returned HTTP ${status2} while ${operation}`);
1534
+ this.status = status2;
1535
+ this.operation = operation;
1536
+ }
1537
+ };
1538
+ var CallbackExpiredError = class extends Error {
1539
+ constructor() {
1540
+ super("The local sign-in attempt expired before the provider returned.");
1541
+ }
1542
+ };
1543
+ var InterruptedError = class extends Error {
1544
+ constructor() {
1545
+ super("Authorization was interrupted.");
1546
+ }
1547
+ };
1548
+ function apiPath(proxyId, connectionId, suffix) {
1549
+ const path = `/mcp-proxies/${encodeURIComponent(proxyId)}`;
1550
+ if (!connectionId) return path + "/connections";
1551
+ return `${path}/connections/${encodeURIComponent(connectionId)}/local-authorization/${suffix}`;
1552
+ }
1553
+ async function requestJson(path, credentials2, cancelSignal, operation, body) {
1554
+ const method = body === void 0 ? "GET" : "POST";
1555
+ const requestController = new AbortController();
1556
+ const onCancel = () => requestController.abort();
1557
+ const timeout = setTimeout(() => requestController.abort(), API_TIMEOUT_MS);
1558
+ cancelSignal.addEventListener("abort", onCancel, { once: true });
1559
+ if (cancelSignal.aborted) onCancel();
1560
+ try {
1561
+ let response;
1562
+ try {
1563
+ response = await fetch(`${getApiUrlConfig()}${path}`, {
1564
+ method,
1565
+ headers: {
1566
+ ...buildAuthHeaders(credentials2),
1567
+ ...body === void 0 ? {} : { "Content-Type": "application/json" }
1568
+ },
1569
+ body: body === void 0 ? void 0 : JSON.stringify(body),
1570
+ signal: requestController.signal
1571
+ });
1572
+ } catch (error2) {
1573
+ if (cancelSignal.aborted) throw new InterruptedError();
1574
+ if (requestController.signal.aborted) {
1575
+ throw new Error(`Evident timed out while ${operation} after ${API_TIMEOUT_MS}ms.`);
1576
+ }
1577
+ const detail = error2 instanceof Error ? error2.message : String(error2);
1578
+ throw new Error(
1579
+ `Could not reach Evident while ${operation}: ${detail}. Check --endpoint or EVIDENT_API_URL and retry.`
1580
+ );
1581
+ }
1582
+ if (!response.ok) throw new ApiHttpError(response.status, operation);
1583
+ try {
1584
+ return await response.json();
1585
+ } catch (error2) {
1586
+ if (cancelSignal.aborted) throw new InterruptedError();
1587
+ if (requestController.signal.aborted) {
1588
+ throw new Error(`Evident timed out while ${operation} after ${API_TIMEOUT_MS}ms.`);
1589
+ }
1590
+ const detail = error2 instanceof Error ? error2.message : String(error2);
1591
+ throw new Error(`Evident returned an invalid response while ${operation}: ${detail}`);
1592
+ }
1593
+ } finally {
1594
+ clearTimeout(timeout);
1595
+ cancelSignal.removeEventListener("abort", onCancel);
1596
+ }
1597
+ }
1598
+ function callbackPage(statusPath) {
1599
+ const nonce = randomBytes(18).toString("base64url");
1600
+ const statusMarkup = statusPath ? `<main class="card" id="callback-page" data-status-url="${statusPath}" role="status" aria-live="polite" aria-atomic="true">
1601
+ <span class="dot" aria-hidden="true"></span>
1602
+ <h1 id="status-heading">Provider response received</h1>
1603
+ <p id="status-message">Your provider response is here. Evident is preparing the connection.</p>
1604
+ <ol class="steps" aria-label="Authorization progress">
1605
+ <li data-step="provider" data-state="done"><span class="step-mark" aria-hidden="true">\u2713</span><span>Provider response received</span></li>
1606
+ <li data-step="evident" data-state="pending"><span class="step-mark" aria-hidden="true">2</span><span>Evident completes authorization</span></li>
1607
+ <li data-step="connection" data-state="pending"><span class="step-mark" aria-hidden="true">3</span><span>Review tools in Evident</span></li>
1608
+ </ol>
1609
+ <p class="footnote" id="status-footnote">Keep this page open while Evident finishes. The terminal shows the same progress.</p>
1610
+ </main>` : `<main class="card" role="status">
1611
+ <span class="dot" aria-hidden="true"></span>
1612
+ <h1>Sign-in response not accepted</h1>
1613
+ <p>This response wasn\u2019t accepted. Return to the terminal for details, then retry authorization if needed.</p>
1614
+ </main>`;
1615
+ const script = statusPath ? `<script nonce="${nonce}">
1616
+ history.replaceState(null, '', location.pathname);
1617
+ const page = document.getElementById('callback-page');
1618
+ const statusUrl = page.dataset.statusUrl;
1619
+ const views = {
1620
+ received: {
1621
+ heading: 'Provider response received',
1622
+ message: 'Your provider response is here. Evident is preparing the connection.',
1623
+ footnote: 'Keep this page open while Evident finishes. The terminal shows the same progress.',
1624
+ steps: ['done', 'pending', 'pending'],
1625
+ },
1626
+ completing: {
1627
+ heading: 'Evident is finishing setup',
1628
+ message: 'Evident received the response and is completing authorization.',
1629
+ footnote: 'This can take a moment. The terminal shows the same progress.',
1630
+ steps: ['done', 'current', 'pending'],
1631
+ },
1632
+ success: {
1633
+ heading: 'Authorization confirmed',
1634
+ message:
1635
+ 'Evident confirmed authorization. Review the discovered tools in Evident to choose which to enable.',
1636
+ footnote: 'You can close this window.',
1637
+ steps: ['done', 'done', 'current'],
1638
+ },
1639
+ tools_pending: {
1640
+ heading: 'Authorization confirmed',
1641
+ message: 'Evident authorized the connection, but its tools are still being prepared.',
1642
+ footnote: 'Check the connection in Evident for tool status. You can close this window.',
1643
+ steps: ['done', 'done', 'current'],
1644
+ },
1645
+ failed: {
1646
+ heading: 'Sign-in did not finish',
1647
+ message: 'Evident could not complete setup. Check the terminal for the next step.',
1648
+ footnote: 'You can close this window after reading the terminal.',
1649
+ steps: ['done', 'failed', 'pending'],
1650
+ },
1651
+ unconfirmed: {
1652
+ heading: 'Completion could not be confirmed',
1653
+ message: 'Check the connection in Evident before retrying.',
1654
+ footnote: 'The terminal has the same status. Check the connection before starting another sign-in.',
1655
+ steps: ['done', 'uncertain', 'pending'],
1656
+ },
1657
+ };
1658
+ const terminalPhases = new Set(['success', 'tools_pending', 'failed', 'unconfirmed']);
1659
+ function showView(phase, view) {
1660
+ document.body.dataset.phase = phase;
1661
+ document.getElementById('status-heading').textContent = view.heading;
1662
+ document.getElementById('status-message').textContent = view.message;
1663
+ document.getElementById('status-footnote').textContent = view.footnote;
1664
+ ['provider', 'evident', 'connection'].forEach((name, index) => {
1665
+ const step = document.querySelector('[data-step="' + name + '"]');
1666
+ const state = view.steps[index];
1667
+ step.dataset.state = state;
1668
+ step.querySelector('.step-mark').textContent = state === 'done' ? '\u2713' : String(index + 1);
1669
+ });
1670
+ }
1671
+ async function poll() {
1672
+ try {
1673
+ const response = await fetch(statusUrl, {
1674
+ cache: 'no-store',
1675
+ credentials: 'omit',
1676
+ redirect: 'error',
1677
+ headers: { Accept: 'application/json' },
1678
+ });
1679
+ if (!response.ok) throw new Error('status unavailable');
1680
+ const result = await response.json();
1681
+ const view = views[result.phase];
1682
+ if (!view) throw new Error('unknown status');
1683
+ showView(result.phase, view);
1684
+ if (terminalPhases.has(result.phase)) return;
1685
+ } catch (_error) {
1686
+ document.getElementById('status-message').textContent =
1687
+ 'Evident is still finishing. Check the terminal for the latest status.';
1688
+ }
1689
+ window.setTimeout(poll, 400);
1690
+ }
1691
+ document.addEventListener('DOMContentLoaded', poll, { once: true });
1692
+ </script>` : `<script nonce="${nonce}">history.replaceState(null, '', location.pathname);</script>`;
1693
+ const html = `<!doctype html>
1694
+ <html lang="en">
1695
+ <head>
1696
+ <meta charset="utf-8" />
1697
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
1698
+ <meta name="robots" content="noindex" />
1699
+ <meta name="referrer" content="no-referrer" />
1700
+ <title>Sign-in \xB7 Evident</title>
1701
+ <style nonce="${nonce}">
1702
+ :root { color-scheme: light dark; }
1703
+ * { box-sizing: border-box; }
1704
+ body {
1705
+ margin: 0;
1706
+ min-height: 100vh;
1707
+ display: flex;
1708
+ align-items: center;
1709
+ justify-content: center;
1710
+ padding: 24px;
1711
+ font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
1712
+ background: #0b0d12;
1713
+ color: #e6e8ee;
1714
+ }
1715
+ .card {
1716
+ width: 100%;
1717
+ max-width: 420px;
1718
+ text-align: center;
1719
+ background: #12151c;
1720
+ border: 1px solid #232838;
1721
+ border-radius: 16px;
1722
+ padding: 36px 24px;
1723
+ box-shadow: 0 10px 40px rgba(0, 0, 0, 0.35);
1724
+ }
1725
+ .dot {
1726
+ width: 12px;
1727
+ height: 12px;
1728
+ border-radius: 50%;
1729
+ background: #f59e0b;
1730
+ display: inline-block;
1731
+ margin-bottom: 20px;
1732
+ box-shadow: 0 0 0 4px rgba(245, 158, 11, 0.15);
1733
+ }
1734
+ body[data-phase="success"] .dot {
1735
+ background: #34d399;
1736
+ box-shadow: 0 0 0 4px rgba(52, 211, 153, 0.15);
1737
+ }
1738
+ body[data-phase="failed"] .dot {
1739
+ background: #fb7185;
1740
+ box-shadow: 0 0 0 4px rgba(251, 113, 133, 0.15);
1741
+ }
1742
+ h1 { font-size: 20px; margin: 0 0 8px; font-weight: 600; }
1743
+ p { margin: 0; color: #9aa2b4; font-size: 14px; line-height: 1.5; }
1744
+ .steps { list-style: none; margin: 24px 0 0; padding: 0; text-align: left; }
1745
+ .steps li {
1746
+ display: flex;
1747
+ align-items: center;
1748
+ gap: 12px;
1749
+ min-height: 48px;
1750
+ border-top: 1px solid #232838;
1751
+ color: #9aa2b4;
1752
+ font-size: 14px;
1753
+ }
1754
+ .step-mark {
1755
+ width: 24px;
1756
+ height: 24px;
1757
+ border: 1px solid #42495b;
1758
+ border-radius: 50%;
1759
+ display: inline-flex;
1760
+ align-items: center;
1761
+ justify-content: center;
1762
+ flex: 0 0 auto;
1763
+ font-size: 12px;
1764
+ }
1765
+ [data-state="done"] { color: #e6e8ee !important; }
1766
+ [data-state="done"] .step-mark { border-color: #34d399; color: #34d399; }
1767
+ [data-state="current"] { color: #e6e8ee !important; }
1768
+ [data-state="current"] .step-mark { border-color: #f59e0b; color: #fbbf24; }
1769
+ [data-state="failed"] .step-mark { border-color: #fb7185; color: #fb7185; }
1770
+ [data-state="uncertain"] .step-mark { border-color: #f59e0b; color: #fbbf24; }
1771
+ .footnote { margin-top: 20px; font-size: 12px; }
1772
+ @media (max-width: 480px) {
1773
+ body { padding: 16px; }
1774
+ .card { padding: 32px 20px; }
1775
+ }
1776
+ </style>
1777
+ </head>
1778
+ <body>${statusMarkup}${script}</body>
1779
+ </html>`;
1780
+ return { html, nonce };
1781
+ }
1782
+ function callbackResponse(response, status2, html, nonce, onFinish) {
1783
+ response.writeHead(status2, {
1784
+ "Content-Type": "text/html; charset=utf-8",
1785
+ "Cache-Control": "no-store",
1786
+ Pragma: "no-cache",
1787
+ "Content-Security-Policy": `default-src 'none'; script-src 'nonce-${nonce}'; style-src 'nonce-${nonce}'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`,
1788
+ "X-Content-Type-Options": "nosniff",
1789
+ "X-Frame-Options": "DENY",
1790
+ "Referrer-Policy": "no-referrer",
1791
+ "Cross-Origin-Resource-Policy": "same-origin"
1792
+ });
1793
+ response.end(html, onFinish);
1794
+ }
1795
+ function statusResponse(response, status2, phase, onFinish) {
1796
+ response.writeHead(status2, {
1797
+ "Content-Type": "application/json; charset=utf-8",
1798
+ "Cache-Control": "no-store",
1799
+ Pragma: "no-cache",
1800
+ "Content-Security-Policy": "default-src 'none'; frame-ancestors 'none'",
1801
+ "X-Content-Type-Options": "nosniff",
1802
+ "X-Frame-Options": "DENY",
1803
+ "Referrer-Policy": "no-referrer",
1804
+ "Cross-Origin-Resource-Policy": "same-origin"
1805
+ });
1806
+ response.end(phase ? JSON.stringify({ phase }) : "", onFinish);
1807
+ }
1808
+ function isTerminalPagePhase(phase) {
1809
+ return phase === "success" || phase === "tools_pending" || phase === "failed" || phase === "unconfirmed";
1810
+ }
1811
+ function waitForTerminalStatusRead(page, signal) {
1812
+ if (page.terminalRead || signal.aborted) return Promise.resolve();
1813
+ return new Promise((resolve6) => {
1814
+ let settled = false;
1815
+ const finish = () => {
1816
+ if (settled) return;
1817
+ settled = true;
1818
+ clearTimeout(timer);
1819
+ signal.removeEventListener("abort", finish);
1820
+ if (page.notifyTerminalRead === finish) page.notifyTerminalRead = void 0;
1821
+ resolve6();
1822
+ };
1823
+ const timer = setTimeout(finish, CALLBACK_PAGE_FINAL_READ_TIMEOUT_MS);
1824
+ page.notifyTerminalRead = finish;
1825
+ signal.addEventListener("abort", finish, { once: true });
1826
+ if (signal.aborted) finish();
1827
+ });
1828
+ }
1829
+ function handleStatusRequest(request3, response, page) {
1830
+ if (!request3.url?.startsWith("/_status/")) return false;
1831
+ const statusPath = `/_status/${page.capability}`;
1832
+ const base = page.origin ?? `http://${MCP_LOOPBACK_REDIRECT_POLICY.host}`;
1833
+ const url = URL.canParse(request3.url, base) ? new URL(request3.url, base) : void 0;
1834
+ const fetchSite = request3.headers["sec-fetch-site"];
1835
+ if (request3.method !== "GET" || !url || url.pathname !== statusPath || url.search || request3.headers.host !== page.host || fetchSite !== void 0 && fetchSite !== "same-origin" || request3.headers.origin !== void 0 && request3.headers.origin !== page.origin || request3.headers["transfer-encoding"] !== void 0 || Number(request3.headers["content-length"] ?? 0) > 0) {
1836
+ statusResponse(response, 404);
1837
+ return true;
1838
+ }
1839
+ const phase = page.phase;
1840
+ statusResponse(response, 200, phase, () => {
1841
+ if (isTerminalPagePhase(phase)) {
1842
+ page.terminalRead = true;
1843
+ page.notifyTerminalRead?.();
1844
+ }
1845
+ });
1846
+ return true;
1847
+ }
1848
+ function rejectedCallbackResponse(response, status2) {
1849
+ const page = callbackPage();
1850
+ callbackResponse(response, status2, page.html, page.nonce);
1851
+ }
1852
+ function parseCallbackRequest(request3) {
1853
+ if (request3.method !== "GET" || !request3.url || !request3.url.startsWith("/") || request3.url.length > 16384) {
1854
+ return { reason: "malformed_response" };
1855
+ }
1856
+ if (request3.headers["transfer-encoding"] || Number(request3.headers["content-length"] ?? 0) > 0) {
1857
+ return { reason: "malformed_response" };
1858
+ }
1859
+ const callbackBase = `http://${MCP_LOOPBACK_REDIRECT_POLICY.host}`;
1860
+ if (!URL.canParse(request3.url, callbackBase)) return { reason: "malformed_response" };
1861
+ const url = new URL(request3.url, callbackBase);
1862
+ if (url.pathname !== MCP_LOOPBACK_REDIRECT_POLICY.path || url.hash) {
1863
+ return { reason: "malformed_response" };
1864
+ }
1865
+ for (const parameter of url.search.slice(1).split("&")) {
1866
+ const separator = parameter.indexOf("=");
1867
+ const rawKey = separator === -1 ? parameter : parameter.slice(0, separator);
1868
+ let key;
1869
+ try {
1870
+ key = decodeURIComponent(rawKey.replaceAll("+", " "));
1871
+ } catch (_error) {
1872
+ continue;
1873
+ }
1874
+ if (!KNOWN_CALLBACK_PARAMETERS.has(key)) continue;
1875
+ const rawValue = separator === -1 ? "" : parameter.slice(separator + 1);
1876
+ try {
1877
+ decodeURIComponent(rawValue.replaceAll("+", " "));
1878
+ } catch (_error) {
1879
+ return { reason: "malformed_response" };
1880
+ }
1881
+ }
1882
+ const params = url.searchParams;
1883
+ for (const key of ["state", "code", "error", "error_description", "iss"]) {
1884
+ if (params.getAll(key).length > 1) return { reason: "malformed_response" };
1885
+ }
1886
+ const state = params.get("state");
1887
+ const code = params.get("code");
1888
+ const error2 = params.get("error");
1889
+ const errorDescription = params.get("error_description");
1890
+ const issuer = params.get("iss");
1891
+ if (!state || state.length > 2048 || Boolean(code) === Boolean(error2) || code !== null && (!code || code.length > 8192) || error2 !== null && (!error2 || error2.length > 256) || errorDescription !== null && (!error2 || errorDescription.length > 2048) || issuer !== null && (!issuer || issuer.length > 2048)) {
1892
+ return { reason: "malformed_response" };
1893
+ }
1894
+ return {
1895
+ callback: {
1896
+ state,
1897
+ ...code === null ? {} : { code },
1898
+ ...error2 === null ? {} : { error: error2 },
1899
+ ...errorDescription === null ? {} : { error_description: errorDescription },
1900
+ ...issuer === null ? {} : { iss: issuer }
1901
+ }
1902
+ };
1903
+ }
1904
+ function reportProgress(options, event, message, details = {}) {
1905
+ if (options.json) {
1906
+ console.error(JSON.stringify({ event, ...details }));
1907
+ } else {
1908
+ console.error(message);
1909
+ }
1910
+ }
1911
+ function rejectCallback(response, options, reason) {
1912
+ rejectedCallbackResponse(response, 400);
1913
+ reportProgress(options, "callback_rejected", callbackRejectionMessage(reason), {
1914
+ reason,
1915
+ action: "still_waiting"
1916
+ });
1917
+ }
1918
+ function callbackRejectionMessage(reason) {
1919
+ switch (reason) {
1920
+ case "malformed_response":
1921
+ return "The callback had a malformed response; authorization is still waiting for a valid response. Retry authorization if needed.";
1922
+ case "state_mismatch":
1923
+ return "The callback had a state mismatch; authorization is still waiting for a valid response. Retry authorization if needed.";
1924
+ case "issuer_missing":
1925
+ return "The callback was missing its issuer; authorization is still waiting for a valid response. Update the provider or retry authorization.";
1926
+ case "issuer_mismatch":
1927
+ return "The callback had an issuer mismatch; authorization is still waiting for a valid response. Retry authorization if needed.";
1928
+ case "issuer_unavailable":
1929
+ return "The Evident endpoint has issuer validation unavailable; authorization is still waiting for a valid response. Update the endpoint or start a new authorization.";
1930
+ case "attempt_not_ready":
1931
+ return "The authorization attempt is not ready yet; authorization is still waiting for a valid response while Evident finishes starting it.";
1932
+ case "attempt_expired":
1933
+ return "The authorization attempt expired; authorization is still waiting for a valid response. Start a new authorization.";
1934
+ }
1935
+ }
1936
+ function handleCallbackRequest(request3, response, waiter, options, page) {
1937
+ if (handleStatusRequest(request3, response, page)) return;
1938
+ if (!request3.url || !request3.url.startsWith("/") || !URL.canParse(request3.url, `http://${MCP_LOOPBACK_REDIRECT_POLICY.host}`)) {
1939
+ rejectCallback(response, options, "malformed_response");
1940
+ return;
1941
+ }
1942
+ const pathname = new URL(request3.url, `http://${MCP_LOOPBACK_REDIRECT_POLICY.host}`).pathname;
1943
+ if (pathname !== MCP_LOOPBACK_REDIRECT_POLICY.path) {
1944
+ rejectedCallbackResponse(response, 404);
1945
+ return;
1946
+ }
1947
+ if (request3.method !== "GET") {
1948
+ response.setHeader("Allow", "GET");
1949
+ rejectedCallbackResponse(response, 405);
1950
+ return;
1951
+ }
1952
+ if (waiter.accepted) {
1953
+ rejectedCallbackResponse(response, 409);
1954
+ return;
1955
+ }
1956
+ const parsed = parseCallbackRequest(request3);
1957
+ if (!("callback" in parsed)) {
1958
+ rejectCallback(response, options, parsed.reason);
1959
+ return;
1960
+ }
1961
+ const callback = parsed.callback;
1962
+ const expiresAtMs = waiter.expiresAtMs;
1963
+ let rejectionReason;
1964
+ if (expiresAtMs === void 0) {
1965
+ rejectionReason = "attempt_not_ready";
1966
+ } else if (Date.now() >= expiresAtMs) {
1967
+ rejectionReason = "attempt_expired";
1968
+ } else if (!waiter.expectedState || callback.state !== waiter.expectedState) {
1969
+ rejectionReason = "state_mismatch";
1970
+ } else if (waiter.issuerParameterSupported && callback.iss === void 0) {
1971
+ rejectionReason = "issuer_missing";
1972
+ } else if (callback.iss !== void 0 && waiter.expectedIssuer === void 0) {
1973
+ rejectionReason = "issuer_unavailable";
1974
+ } else if (callback.iss !== void 0 && callback.iss !== waiter.expectedIssuer) {
1975
+ rejectionReason = "issuer_mismatch";
1976
+ }
1977
+ if (rejectionReason) {
1978
+ rejectCallback(response, options, rejectionReason);
1979
+ return;
1980
+ }
1981
+ waiter.accepted = true;
1982
+ page.phase = "received";
1983
+ reportProgress(options, "callback_received", "Provider sign-in response received.");
1984
+ const callbackPageResponse = callbackPage(`/_status/${page.capability}`);
1985
+ callbackResponse(
1986
+ response,
1987
+ 200,
1988
+ callbackPageResponse.html,
1989
+ callbackPageResponse.nonce,
1990
+ () => waiter.resolve?.(callback)
1991
+ );
1992
+ }
1993
+ function listen(server, port) {
1994
+ return new Promise((resolve6, reject) => {
1995
+ const onError = (error2) => reject(error2);
1996
+ server.once("error", onError);
1997
+ server.listen(port, MCP_LOOPBACK_REDIRECT_POLICY.host, () => {
1998
+ server.removeListener("error", onError);
1999
+ const address = server.address();
2000
+ if (!address || typeof address === "string") {
2001
+ reject(new Error("The local callback listener did not report a TCP port."));
2002
+ return;
2003
+ }
2004
+ resolve6(address.port);
2005
+ });
2006
+ });
2007
+ }
2008
+ function isAddressInUse(error2) {
2009
+ return typeof error2 === "object" && error2 !== null && "code" in error2 && error2.code === "EADDRINUSE";
2010
+ }
2011
+ async function bindCallbackListener(waiter, options, page) {
2012
+ const createListener = () => createServer(
2013
+ (request3, response) => handleCallbackRequest(request3, response, waiter, options, page)
2014
+ );
2015
+ try {
2016
+ const server2 = createListener();
2017
+ return { server: server2, port: await listen(server2, MCP_LOOPBACK_REDIRECT_POLICY.preferred_port) };
2018
+ } catch (error2) {
2019
+ if (!isAddressInUse(error2)) {
2020
+ throw new Error(
2021
+ `Could not listen on 127.0.0.1:${MCP_LOOPBACK_REDIRECT_POLICY.preferred_port}: ${error2 instanceof Error ? error2.message : String(error2)}`
2022
+ );
2023
+ }
2024
+ }
2025
+ const server = createListener();
2026
+ try {
2027
+ return { server, port: await listen(server, 0) };
2028
+ } catch (error2) {
2029
+ throw new Error(
2030
+ `Could not bind the local callback listener on preferred port ${MCP_LOOPBACK_REDIRECT_POLICY.preferred_port} or an ephemeral port: ${error2 instanceof Error ? error2.message : String(error2)}`
2031
+ );
2032
+ }
2033
+ }
2034
+ function waitForCallback(waiter, expiresAtMs, signal) {
2035
+ return new Promise((resolve6, reject) => {
2036
+ const remainingMs = expiresAtMs - Date.now();
2037
+ if (remainingMs <= 0) {
2038
+ reject(new CallbackExpiredError());
2039
+ return;
2040
+ }
2041
+ if (signal.aborted) {
2042
+ reject(new InterruptedError());
2043
+ return;
2044
+ }
2045
+ let settled = false;
2046
+ function settle(callback, error2) {
2047
+ if (settled) return;
2048
+ settled = true;
2049
+ clearTimeout(timer);
2050
+ signal.removeEventListener("abort", onAbort);
2051
+ waiter.resolve = void 0;
2052
+ if (error2) reject(error2);
2053
+ else resolve6(callback);
2054
+ }
2055
+ const onAbort = () => settle(void 0, new InterruptedError());
2056
+ const timer = setTimeout(() => settle(void 0, new CallbackExpiredError()), remainingMs);
2057
+ waiter.expiresAtMs = expiresAtMs;
2058
+ waiter.resolve = (callback) => settle(callback);
2059
+ timer.unref?.();
2060
+ signal.addEventListener("abort", onAbort, { once: true });
2061
+ if (signal.aborted) onAbort();
2062
+ });
2063
+ }
2064
+ function authorizationState(authorizationUrl) {
2065
+ let url;
2066
+ try {
2067
+ url = new URL(authorizationUrl);
2068
+ } catch (error2) {
2069
+ throw new Error(
2070
+ `Evident returned an invalid authorization URL: ${error2 instanceof Error ? error2.message : String(error2)}`
2071
+ );
2072
+ }
2073
+ const states = url.searchParams.getAll("state");
2074
+ if (url.protocol !== "https:" || url.username || url.password || url.hash || states.length !== 1 || !states[0]) {
2075
+ throw new Error("Evident returned an unsafe or incomplete authorization URL.");
2076
+ }
2077
+ return { url, state: states[0] };
2078
+ }
2079
+ function apiFailureMessage(error2) {
2080
+ const context = `Evident returned HTTP ${error2.status} while ${error2.operation}.`;
2081
+ switch (error2.status) {
2082
+ case 400:
2083
+ return `${context} Retry the command; if it continues, update the CLI and try again.`;
2084
+ case 401:
2085
+ return `${context} Your Evident user session is missing or expired. If EVIDENT_TOKEN is set, update or unset it; otherwise run \`evident login\` for the selected endpoint, then retry.`;
2086
+ case 403:
2087
+ return `${context} Only workspace owners and admins can authorize MCP connections. Ask a workspace admin for access.`;
2088
+ case 404:
2089
+ return `${context} Confirm the proxy and connection IDs and that this CLI user can access the proxy.`;
2090
+ case 409:
2091
+ return `${context} This connection does not support local sign-in. Use its hosted authorization flow in Evident.`;
2092
+ case 502:
2093
+ case 503:
2094
+ return `${context} The Evident MCP authorization service is unavailable. Retry shortly or contact your workspace admin.`;
2095
+ default:
2096
+ return `${context} Check your endpoint and retry.`;
2097
+ }
2098
+ }
2099
+ function completionFailureMessage(reason) {
2100
+ switch (reason) {
2101
+ case "state_unknown":
2102
+ return "This sign-in was started by another user or could not be found. Start a new authorization from the same user account.";
2103
+ case "state_consumed":
2104
+ return "This sign-in was already used. Start a new authorization.";
2105
+ case "state_expired":
2106
+ return "This sign-in attempt expired. Start a new authorization.";
2107
+ case "issuer_unavailable":
2108
+ return "This sign-in attempt predates issuer validation. Start a new authorization.";
2109
+ case "issuer_missing":
2110
+ return "The provider response did not include its required issuer. Start a new authorization and update the CLI if needed.";
2111
+ case "issuer_mismatch":
2112
+ return "The provider response came from an unexpected issuer. Start a new authorization and contact support if it continues.";
2113
+ case "invalid_response":
2114
+ return "The provider returned an invalid sign-in response. Start a new authorization.";
2115
+ case "provider_denied":
2116
+ return "The provider denied the sign-in. Retry and approve the requested access.";
2117
+ case "provider_error":
2118
+ return "The provider could not complete sign-in. Retry, or contact the provider if it continues.";
2119
+ case "exchange_failed":
2120
+ return "The provider sign-in completed, but Evident could not exchange the authorization. Retry or contact support.";
2121
+ case "reconcile_failed":
2122
+ case "tools_pending":
2123
+ return "Sign-in completed, but Evident could not finish setting up this connection. Retry or contact support.";
2124
+ case "not_configured":
2125
+ return "Local authorization is not configured for this Evident environment. Contact your workspace admin.";
2126
+ default:
2127
+ return "Evident could not complete this sign-in. Start a new authorization and try again.";
2128
+ }
2129
+ }
2130
+ function printLink(options, url, reason) {
2131
+ if (options.json) {
2132
+ console.error(JSON.stringify({ event: "authorization_required", authorization_url: url.href }));
2133
+ return;
2134
+ }
2135
+ printWarning(reason ?? "Open this authorization URL in your browser:");
2136
+ console.log(url.href);
2137
+ }
2138
+ function printResult(options, proxyId, connectionId, error2, successMessage = "MCP connection authorized.") {
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
+ })
2147
+ );
2148
+ } else if (error2) {
2149
+ printError(error2);
2150
+ } else {
2151
+ printSuccess(successMessage);
2152
+ }
2153
+ }
2154
+ function errorMessage(error2) {
2155
+ if (error2 instanceof ApiHttpError) return apiFailureMessage(error2);
2156
+ if (error2 instanceof CallbackExpiredError) {
2157
+ return "The sign-in attempt expired before the provider returned. Run the command again.";
2158
+ }
2159
+ if (error2 instanceof InterruptedError) return "Authorization was interrupted.";
2160
+ if (error2 instanceof Error) return error2.message;
2161
+ return `Authorization failed: ${String(error2)}`;
2162
+ }
2163
+ function requestFailed(reason) {
2164
+ if (reason instanceof Error) throw reason;
2165
+ throw new Error(`Authorization failed: ${String(reason)}`);
2166
+ }
2167
+ function validateConnectionList(value) {
2168
+ if (!value || !Array.isArray(value.mcp_proxy_connections)) {
2169
+ throw new Error("Evident returned an invalid MCP connection list. Update the CLI and retry.");
2170
+ }
2171
+ return value.mcp_proxy_connections;
2172
+ }
2173
+ function validateBeginResponse(value) {
2174
+ 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)) {
2175
+ throw new Error(
2176
+ "Evident returned an invalid local authorization attempt. Update the CLI and retry."
2177
+ );
2178
+ }
2179
+ }
2180
+ async function startBrowser(url) {
2181
+ const child = await open2(url);
2182
+ let signalFailure = () => void 0;
2183
+ const failure = new Promise((resolve6) => {
2184
+ signalFailure = resolve6;
2185
+ });
2186
+ child.once("error", signalFailure);
2187
+ child.once("close", (code) => {
2188
+ if (code !== 0) signalFailure();
2189
+ });
2190
+ await new Promise((resolve6, reject) => {
2191
+ if (child.pid !== void 0) {
2192
+ resolve6();
2193
+ return;
2194
+ }
2195
+ child.once("spawn", resolve6);
2196
+ child.once("error", reject);
2197
+ });
2198
+ return { failure };
2199
+ }
2200
+ function closeServer(server, force) {
2201
+ if (!server.listening) return Promise.resolve();
2202
+ return new Promise((resolve6, reject) => {
2203
+ server.close((error2) => error2 ? reject(error2) : resolve6());
2204
+ if (force) server.closeAllConnections();
2205
+ });
2206
+ }
2207
+ async function authorizeMcpConnection(proxyId, connectionId, options = {}) {
2208
+ let credentials2;
2209
+ try {
2210
+ credentials2 = await getAuthCredentials();
2211
+ } catch (error2) {
2212
+ const kind = error2 instanceof Error ? error2.name : "unknown error";
2213
+ printResult(
2214
+ options,
2215
+ proxyId,
2216
+ connectionId,
2217
+ `Could not read the saved Evident credentials (${kind}). Check keychain access or run evident login again.`
2218
+ );
2219
+ process.exitCode = 1;
2220
+ return;
2221
+ }
2222
+ if (!credentials2) {
2223
+ printResult(
2224
+ options,
2225
+ proxyId,
2226
+ connectionId,
2227
+ "No credentials found. Run `evident login` and retry."
2228
+ );
2229
+ process.exitCode = 1;
2230
+ return;
2231
+ }
2232
+ if (credentials2.authType !== "bearer") {
2233
+ printResult(
2234
+ options,
2235
+ proxyId,
2236
+ connectionId,
2237
+ "MCP authorization requires a user login, not a runner key. Unset EVIDENT_RUNNER_KEY/EVIDENT_AGENT_KEY, then run `evident login`."
2238
+ );
2239
+ process.exitCode = 1;
2240
+ return;
2241
+ }
2242
+ const waiter = { accepted: false };
2243
+ const page = {
2244
+ capability: randomBytes(32).toString("base64url"),
2245
+ phase: "waiting",
2246
+ terminalRead: false
2247
+ };
2248
+ let server;
2249
+ let closePromise;
2250
+ let closeFailureLogged = false;
2251
+ let failure;
2252
+ let successMessage = "MCP connection authorized.";
2253
+ const cancelController = new AbortController();
2254
+ const closeListener = (force = false) => {
2255
+ if (!server || closePromise) return closePromise ?? Promise.resolve();
2256
+ closePromise = closeServer(server, force);
2257
+ return closePromise;
2258
+ };
2259
+ const onSigint = () => {
2260
+ cancelController.abort();
2261
+ void closeListener(true).catch((error2) => {
2262
+ closeFailureLogged = true;
2263
+ console.error(
2264
+ `[mcp authorize] listener shutdown failed for proxy_id=${JSON.stringify(proxyId)} connection_id=${JSON.stringify(connectionId)}: ${error2 instanceof Error ? error2.message : String(error2)}`
2265
+ );
2266
+ });
2267
+ };
2268
+ try {
2269
+ const listener = await bindCallbackListener(waiter, options, page);
2270
+ server = listener.server;
2271
+ process.once("SIGINT", onSigint);
2272
+ page.host = `${MCP_LOOPBACK_REDIRECT_POLICY.host}:${listener.port}`;
2273
+ page.origin = `${MCP_LOOPBACK_REDIRECT_POLICY.scheme}://${page.host}`;
2274
+ const redirectUri = `${MCP_LOOPBACK_REDIRECT_POLICY.scheme}://${MCP_LOOPBACK_REDIRECT_POLICY.host}:${listener.port}${MCP_LOOPBACK_REDIRECT_POLICY.path}`;
2275
+ const fallback = listener.port !== MCP_LOOPBACK_REDIRECT_POLICY.preferred_port;
2276
+ reportProgress(
2277
+ options,
2278
+ fallback ? "listener_fallback" : "listener_ready",
2279
+ fallback ? `Port ${MCP_LOOPBACK_REDIRECT_POLICY.preferred_port} is busy; listening at ${redirectUri}.` : `Listening for the sign-in response at ${redirectUri}.`,
2280
+ {
2281
+ callback_url: redirectUri,
2282
+ ...fallback ? { preferred_port: MCP_LOOPBACK_REDIRECT_POLICY.preferred_port } : {},
2283
+ port: listener.port
2284
+ }
2285
+ );
2286
+ const connectionList = await requestJson(
2287
+ apiPath(proxyId),
2288
+ credentials2,
2289
+ cancelController.signal,
2290
+ "checking the MCP connection"
2291
+ );
2292
+ const connection = validateConnectionList(connectionList).find(
2293
+ (candidate) => candidate.connection_id === connectionId
2294
+ );
2295
+ if (!connection)
2296
+ throw new Error("The MCP connection was not found. Check the connection ID and try again.");
2297
+ if (connection.authorization_mode !== "local") {
2298
+ throw new Error("This connection uses hosted sign-in. Authorize it from Evident instead.");
2299
+ }
2300
+ if (connection.auth_kind !== "oauth2") {
2301
+ throw new Error("This MCP connection does not support OAuth authorization.");
2302
+ }
2303
+ reportProgress(options, "authorization_starting", "Starting authorization with Evident.");
2304
+ const begin = await requestJson(
2305
+ apiPath(proxyId, connectionId, "begin"),
2306
+ credentials2,
2307
+ cancelController.signal,
2308
+ "starting local authorization",
2309
+ { redirect_uri: redirectUri }
2310
+ );
2311
+ validateBeginResponse(begin);
2312
+ const { url: authorizationUrl, state } = authorizationState(begin.authorization_url);
2313
+ waiter.expectedState = state;
2314
+ waiter.expectedIssuer = begin.issuer;
2315
+ waiter.issuerParameterSupported = begin.authorization_response_iss_parameter_supported;
2316
+ const expiresAtMs = Date.parse(begin.expires_at);
2317
+ if (expiresAtMs <= Date.now()) throw new CallbackExpiredError();
2318
+ waiter.expiresAtMs = expiresAtMs;
2319
+ const callbackOutcome = waitForCallback(waiter, expiresAtMs, cancelController.signal).then(
2320
+ (callback2) => ({ ok: true, callback: callback2 }),
2321
+ (error2) => ({ ok: false, error: error2 })
2322
+ );
2323
+ const waitForCallbackWithProgress = (linkReason) => {
2324
+ if (linkReason) printLink(options, authorizationUrl, linkReason);
2325
+ reportProgress(
2326
+ options,
2327
+ "waiting_for_callback",
2328
+ "Waiting for the provider to return to this computer."
2329
+ );
2330
+ return (async () => {
2331
+ const outcome = await callbackOutcome;
2332
+ if (!outcome.ok) requestFailed(outcome.error);
2333
+ return outcome.callback;
2334
+ })();
2335
+ };
2336
+ let callback;
2337
+ if (options.noBrowser) {
2338
+ callback = await waitForCallbackWithProgress("Open this authorization URL in your browser:");
2339
+ } else {
2340
+ reportProgress(
2341
+ options,
2342
+ "opening_browser",
2343
+ "Opening the provider authorization page in your browser."
2344
+ );
2345
+ const browserOutcome = startBrowser(authorizationUrl.href).then(
2346
+ ({ failure: browserFailure }) => ({ ok: true, failure: browserFailure }),
2347
+ () => ({ ok: false })
2348
+ );
2349
+ const first = await Promise.race([
2350
+ browserOutcome.then((outcome) => ({ kind: "browser", outcome })),
2351
+ callbackOutcome.then((outcome) => ({ kind: "callback", outcome }))
2352
+ ]);
2353
+ if (first.kind === "callback") {
2354
+ if (!first.outcome.ok) requestFailed(first.outcome.error);
2355
+ callback = first.outcome.callback;
2356
+ } else {
2357
+ if (!first.outcome.ok) {
2358
+ callback = await waitForCallbackWithProgress(
2359
+ "Could not open the browser automatically. Open this URL:"
2360
+ );
2361
+ } else {
2362
+ const callbackWait = waitForCallbackWithProgress();
2363
+ const waitOutcome = await Promise.race([
2364
+ callbackWait.then(
2365
+ (value) => ({ kind: "callback", value }),
2366
+ (error2) => ({ kind: "callback_error", error: error2 })
2367
+ ),
2368
+ first.outcome.failure.then(() => ({ kind: "browser_failure" }))
2369
+ ]);
2370
+ if (waitOutcome.kind === "callback") {
2371
+ callback = waitOutcome.value;
2372
+ } else if (waitOutcome.kind === "callback_error") {
2373
+ requestFailed(waitOutcome.error);
2374
+ } else {
2375
+ printLink(
2376
+ options,
2377
+ authorizationUrl,
2378
+ "The browser could not keep the authorization page open. Open this URL:"
2379
+ );
2380
+ callback = await callbackWait;
2381
+ }
2382
+ }
2383
+ }
2384
+ }
2385
+ reportProgress(options, "forwarding_callback", "Forwarding the sign-in response to Evident.");
2386
+ const completionBody = {
2387
+ state: callback.state,
2388
+ ...callback.code === void 0 ? {} : { code: callback.code },
2389
+ ...callback.error === void 0 ? {} : { error: callback.error },
2390
+ ...callback.error_description === void 0 ? {} : { error_description: callback.error_description },
2391
+ ...callback.iss === void 0 ? {} : { iss: callback.iss }
2392
+ };
2393
+ reportProgress(options, "completing_authorization", "Completing authorization with Evident.");
2394
+ page.phase = "completing";
2395
+ const completion = await requestJson(
2396
+ apiPath(proxyId, connectionId, "complete"),
2397
+ credentials2,
2398
+ cancelController.signal,
2399
+ "completing local authorization",
2400
+ completionBody
2401
+ );
2402
+ if (completion.outcome === "success") {
2403
+ if (completion.reason === "tools_pending") {
2404
+ page.phase = "tools_pending";
2405
+ reportProgress(
2406
+ options,
2407
+ "tools_pending",
2408
+ "Authorization confirmed; Evident is still preparing its tools."
2409
+ );
2410
+ successMessage = "MCP connection authorized. Evident is still preparing its tools.";
2411
+ } else {
2412
+ page.phase = "success";
2413
+ }
2414
+ } else {
2415
+ page.phase = "failed";
2416
+ failure = completionFailureMessage(completion.reason);
2417
+ }
2418
+ } catch (error2) {
2419
+ if (waiter.accepted && !isTerminalPagePhase(page.phase)) {
2420
+ page.phase = "unconfirmed";
2421
+ failure = `${COMPLETION_UNCONFIRMED_MESSAGE} ${errorMessage(error2)}`;
2422
+ } else {
2423
+ failure = errorMessage(error2);
2424
+ }
2425
+ } finally {
2426
+ try {
2427
+ if (waiter.accepted && isTerminalPagePhase(page.phase) && !cancelController.signal.aborted) {
2428
+ await waitForTerminalStatusRead(page, cancelController.signal);
2429
+ }
2430
+ process.removeListener("SIGINT", onSigint);
2431
+ await closeListener();
2432
+ } catch (error2) {
2433
+ const detail = error2 instanceof Error ? error2.message : String(error2);
2434
+ if (!closeFailureLogged) {
2435
+ console.error(
2436
+ `[mcp authorize] listener teardown failed for proxy_id=${JSON.stringify(proxyId)} connection_id=${JSON.stringify(connectionId)}: ${detail}`
2437
+ );
2438
+ }
2439
+ failure ??= "The local callback listener could not be closed cleanly. Check for a lingering process and retry.";
2440
+ }
2441
+ }
2442
+ printResult(options, proxyId, connectionId, failure, successMessage);
2443
+ if (failure) process.exitCode = cancelController.signal.aborted ? 130 : 1;
2444
+ }
2445
+
1480
2446
  // src/commands/run.ts
2447
+ import { chmodSync as chmodSync3, existsSync as existsSync3, readFileSync as readFileSync12, writeFileSync as writeFileSync9 } from "node:fs";
2448
+ import { homedir as homedir9 } from "node:os";
2449
+ import { isAbsolute as isAbsolute6, join as join17, parse, resolve as resolvePath2 } from "node:path";
2450
+ import chalk7 from "chalk";
1481
2451
  import ora4 from "ora";
1482
2452
  import { select as select4 } from "@inquirer/prompts";
1483
2453
 
1484
2454
  // src/lib/telemetry.ts
1485
- var CLI_VERSION = (true ? "3.6.1-dev.3acfa88" : void 0) ?? process.env.npm_package_version ?? "unknown";
2455
+ var CLI_VERSION = (true ? "3.6.1-dev.3f69f39" : void 0) ?? process.env.npm_package_version ?? "unknown";
1486
2456
  function getCliVersion() {
1487
2457
  return CLI_VERSION;
1488
2458
  }
@@ -1679,7 +2649,7 @@ var SESSION_DB_RECLAIM_CHUNK_PAGES = 100;
1679
2649
  var SESSION_DB_RECLAIM_TIME_BUDGET_MS = 500;
1680
2650
  var SESSION_DB_RECLAIM_PAGE_CEILING = 4e4;
1681
2651
  var SESSION_DB_RECLAIM_BUSY_TIMEOUT_MS = 5e3;
1682
- function errorMessage(error2) {
2652
+ function errorMessage2(error2) {
1683
2653
  if (!(error2 instanceof Error)) return String(error2);
1684
2654
  return error2.cause instanceof Error ? error2.cause.message : error2.message;
1685
2655
  }
@@ -1813,7 +2783,7 @@ async function probeReclaimAvailability(input) {
1813
2783
  try {
1814
2784
  sqlite = await import("node:sqlite");
1815
2785
  } catch (err) {
1816
- const detail = `Node ${process.version}: ${errorMessage(err)}`;
2786
+ const detail = `Node ${process.version}: ${errorMessage2(err)}`;
1817
2787
  console.warn(`[probeReclaimAvailability] node:sqlite unavailable for ${dbPath}: ` + detail);
1818
2788
  return { reason: "sqlite-unavailable", detail };
1819
2789
  }
@@ -1848,7 +2818,7 @@ async function reclaimSessionDbSpace(input) {
1848
2818
  try {
1849
2819
  sqlite = await import("node:sqlite");
1850
2820
  } catch (err) {
1851
- const detail = `Node ${process.version}: ${errorMessage(err)}`;
2821
+ const detail = `Node ${process.version}: ${errorMessage2(err)}`;
1852
2822
  console.warn(
1853
2823
  `[reclaimSessionDbSpace] node:sqlite unavailable (need Node >=22.5, >=22.13 unflagged) for ${dbPath}: ${detail}`
1854
2824
  );
@@ -1959,11 +2929,11 @@ async function reclaimSessionDbSpace(input) {
1959
2929
  );
1960
2930
  return { ok: false, skipped: "auto-vacuum-not-applicable" };
1961
2931
  } catch (err) {
1962
- console.error(`[reclaimSessionDbSpace] reclaim failed for ${dbPath}: ` + errorMessage(err));
2932
+ console.error(`[reclaimSessionDbSpace] reclaim failed for ${dbPath}: ` + errorMessage2(err));
1963
2933
  return {
1964
2934
  ok: false,
1965
2935
  skipped: isSessionStoreWriteFailure(err) ? "disk-exhaustion" : "reclaim-error",
1966
- detail: errorMessage(err)
2936
+ detail: errorMessage2(err)
1967
2937
  };
1968
2938
  } finally {
1969
2939
  db?.close();
@@ -3115,7 +4085,7 @@ function buildSessionArchive(input) {
3115
4085
  function isRecord2(value) {
3116
4086
  return typeof value === "object" && value !== null && !Array.isArray(value);
3117
4087
  }
3118
- function errorMessage2(error2) {
4088
+ function errorMessage3(error2) {
3119
4089
  return error2 instanceof Error ? error2.message : String(error2);
3120
4090
  }
3121
4091
  function invalidResponse(version2, sessionId, path, reason) {
@@ -3133,7 +4103,7 @@ async function requestPage(client, sessionId, path, signal) {
3133
4103
  } catch (error2) {
3134
4104
  throw new SessionArchiveExportError(
3135
4105
  "request-failed",
3136
- `OpenCode ${client.version} session ${sessionId} request GET ${path} failed: ${errorMessage2(error2)}`
4106
+ `OpenCode ${client.version} session ${sessionId} request GET ${path} failed: ${errorMessage3(error2)}`
3137
4107
  );
3138
4108
  }
3139
4109
  if (response.status === 404) {
@@ -3154,7 +4124,7 @@ async function requestPage(client, sessionId, path, signal) {
3154
4124
  } catch (error2) {
3155
4125
  throw new SessionArchiveExportError(
3156
4126
  "request-failed",
3157
- `OpenCode ${client.version} session ${sessionId} response body from GET ${path} could not be read: ${errorMessage2(error2)}`
4127
+ `OpenCode ${client.version} session ${sessionId} response body from GET ${path} could not be read: ${errorMessage3(error2)}`
3158
4128
  );
3159
4129
  }
3160
4130
  try {
@@ -3189,7 +4159,7 @@ function v1NextCursor(response, sessionId, path) {
3189
4159
  } catch (error2) {
3190
4160
  throw new SessionArchiveExportError(
3191
4161
  "pagination-failed",
3192
- `OpenCode v1 session ${sessionId} returned an invalid next Link for GET ${path}: ${errorMessage2(error2)}`
4162
+ `OpenCode v1 session ${sessionId} returned an invalid next Link for GET ${path}: ${errorMessage3(error2)}`
3193
4163
  );
3194
4164
  }
3195
4165
  }
@@ -5713,8 +6683,8 @@ function classifyReplyAuthError(reply) {
5713
6683
  };
5714
6684
  }
5715
6685
  }
5716
- const errorMessage4 = typeof data?.message === "string" ? data.message : typeof e.message === "string" ? e.message : null;
5717
- if (errorMessage4 !== null && CLAUDE_AUTH_EXPIRY_MESSAGES.some((knownMessage) => errorMessage4.includes(knownMessage))) {
6686
+ const errorMessage5 = typeof data?.message === "string" ? data.message : typeof e.message === "string" ? e.message : null;
6687
+ if (errorMessage5 !== null && CLAUDE_AUTH_EXPIRY_MESSAGES.some((knownMessage) => errorMessage5.includes(knownMessage))) {
5718
6688
  return {
5719
6689
  kind: "model_auth",
5720
6690
  providerId: typeof data?.providerID === "string" && data.providerID || replyProviderId,
@@ -5769,7 +6739,7 @@ function hasRunningAssistantExcept(messages, exceptUserMessageId) {
5769
6739
  (m) => roleOf2(m) === "assistant" && parentIdOf2(m) !== exceptUserMessageId && isAssistantInFlight(m)
5770
6740
  );
5771
6741
  }
5772
- function hasLaterSiblingTurnStarted(messages, userMessageId, siblingUserMessageIds) {
6742
+ function hasLaterSiblingTurnStarted(messages, userMessageId, siblingUserMessageIds, apiVersion) {
5773
6743
  if (!messages || messages.length === 0) return false;
5774
6744
  const userIndex = messages.findIndex((message) => idOf2(message) === userMessageId);
5775
6745
  if (userIndex === -1) return false;
@@ -5783,7 +6753,7 @@ function hasLaterSiblingTurnStarted(messages, userMessageId, siblingUserMessageI
5783
6753
  if (laterUserMessageId === void 0 || !siblingUserMessageIds.has(laterUserMessageId)) {
5784
6754
  return false;
5785
6755
  }
5786
- if (messages.some(
6756
+ if (apiVersion === "v2" || messages.some(
5787
6757
  (candidate) => roleOf2(candidate) === "assistant" && parentIdOf2(candidate) === laterUserMessageId
5788
6758
  )) {
5789
6759
  hasStartedLaterUser = true;
@@ -7128,7 +8098,7 @@ function reportedOpenCodeVersion(input) {
7128
8098
 
7129
8099
  // src/lib/opencode/process.ts
7130
8100
  import { execSync, spawn as spawn3 } from "child_process";
7131
- import { randomBytes } from "node:crypto";
8101
+ import { randomBytes as randomBytes2 } from "node:crypto";
7132
8102
 
7133
8103
  // src/lib/process-stop.ts
7134
8104
  async function stopProcessAndWait(child, timeoutMs, sendTerm, sendKill) {
@@ -7406,7 +8376,7 @@ async function startOpenCode(port, options = {}) {
7406
8376
  return child;
7407
8377
  }
7408
8378
  async function startOpenCode2(port, options = {}) {
7409
- const password = randomBytes(24).toString("hex");
8379
+ const password = randomBytes2(24).toString("hex");
7410
8380
  let command = options.command ?? "opencode2";
7411
8381
  const logLevel = options.inheritStdio ? ["--log-level", resolveOpenCode2LogLevel(process.env)] : [];
7412
8382
  let args = ["serve", "--port", port.toString(), "--hostname", "127.0.0.1", ...logLevel];
@@ -7671,7 +8641,7 @@ function buildSessionStoreSizeWarning(input) {
7671
8641
  import { statSync as statSync5 } from "node:fs";
7672
8642
  import { homedir as homedir5 } from "node:os";
7673
8643
  import { join as join11 } from "node:path";
7674
- import { open as open2, stat } from "node:fs/promises";
8644
+ import { open as open3, stat } from "node:fs/promises";
7675
8645
  var DEFAULT_POLL_INTERVAL_MS = 1e3;
7676
8646
  function resolveOpenCodeLogPath(homeDir = homedir5(), env = process.env) {
7677
8647
  const dataDir = env.XDG_DATA_HOME || join11(homeDir, ".local", "share");
@@ -7725,7 +8695,7 @@ function tailOpenCodeLogFile(logPath, onChunk, opts = {}) {
7725
8695
  inode = current.ino;
7726
8696
  if (current.size === offset) return;
7727
8697
  const length = current.size - offset;
7728
- const fh = await open2(logPath, "r");
8698
+ const fh = await open3(logPath, "r");
7729
8699
  try {
7730
8700
  const buf = Buffer.alloc(length);
7731
8701
  const { bytesRead } = await fh.read(buf, 0, length, offset);
@@ -7758,7 +8728,7 @@ import WebSocket from "ws";
7758
8728
 
7759
8729
  // src/lib/file-read.ts
7760
8730
  import { constants } from "node:fs";
7761
- import { open as open3, realpath as realpath2, stat as stat2 } from "node:fs/promises";
8731
+ import { open as open4, realpath as realpath2, stat as stat2 } from "node:fs/promises";
7762
8732
  import { extname, isAbsolute as isAbsolute3, resolve as resolve4 } from "node:path";
7763
8733
  import { homedir as homedir6 } from "node:os";
7764
8734
 
@@ -7808,7 +8778,7 @@ var FILE_MIME_TYPES = {
7808
8778
  ".mp4": "video/mp4",
7809
8779
  ".mov": "video/quicktime"
7810
8780
  };
7811
- async function readProjectFile(projectRoot, method, requestedPath, openFile = open3) {
8781
+ async function readProjectFile(projectRoot, method, requestedPath, openFile = open4) {
7812
8782
  if (method !== "GET") return refuse(405, "method_not_allowed");
7813
8783
  if (!projectRoot || !isAbsolute3(projectRoot)) return refuse(503, "project_root_unavailable");
7814
8784
  if (!requestedPath || requestedPath.length > 4096 || requestedPath.includes("\0")) {
@@ -8381,8 +9351,8 @@ function connectTunnel(options) {
8381
9351
  }
8382
9352
  forwarder.handleBinaryBodyFrame(frame.sid, frame.payload);
8383
9353
  } catch (error2) {
8384
- const errorMessage4 = error2 instanceof Error ? error2.message : "Unknown error";
8385
- onError?.(`Failed to handle binary message: ${errorMessage4}`);
9354
+ const errorMessage5 = error2 instanceof Error ? error2.message : "Unknown error";
9355
+ onError?.(`Failed to handle binary message: ${errorMessage5}`);
8386
9356
  }
8387
9357
  return;
8388
9358
  }
@@ -8390,8 +9360,8 @@ function connectTunnel(options) {
8390
9360
  try {
8391
9361
  message = JSON.parse(data.toString());
8392
9362
  } catch (error2) {
8393
- const errorMessage4 = error2 instanceof Error ? error2.message : "Unknown error";
8394
- onError?.(`Failed to handle message: ${errorMessage4}`);
9363
+ const errorMessage5 = error2 instanceof Error ? error2.message : "Unknown error";
9364
+ onError?.(`Failed to handle message: ${errorMessage5}`);
8395
9365
  return;
8396
9366
  }
8397
9367
  if (isStreamFrame(message)) {
@@ -8970,7 +9940,7 @@ import { join as join14 } from "node:path";
8970
9940
 
8971
9941
  // src/lib/file-push.ts
8972
9942
  import { randomUUID } from "node:crypto";
8973
- import { chmod, mkdir, open as open4, realpath as realpath3, rename, unlink } from "node:fs/promises";
9943
+ import { chmod, mkdir, open as open5, realpath as realpath3, rename, unlink } from "node:fs/promises";
8974
9944
  import { basename as basename3, dirname as dirname10, isAbsolute as isAbsolute4, join as join13 } from "node:path";
8975
9945
  var FILE_MODE = 384;
8976
9946
  var DIRECTORY_MODE = 448;
@@ -9103,7 +10073,7 @@ async function writeAtomically(realTarget, content) {
9103
10073
  const temporaryPath = join13(dirname10(realTarget), `.evident-push-${randomUUID()}.tmp`);
9104
10074
  let handle;
9105
10075
  try {
9106
- handle = await open4(temporaryPath, "wx", FILE_MODE);
10076
+ handle = await open5(temporaryPath, "wx", FILE_MODE);
9107
10077
  await handle.writeFile(content);
9108
10078
  await handle.chmod(FILE_MODE);
9109
10079
  await handle.close();
@@ -10304,12 +11274,12 @@ var ChannelDriver = class _ChannelDriver {
10304
11274
  this.sessions.delete(conversationId);
10305
11275
  this.supersede(conversationId, sessionId);
10306
11276
  const dispatchDescription = source === "readopt" ? "re-dispatched message" : "message";
10307
- const errorMessage4 = `OpenCode accepted this ${dispatchDescription} once, but its assigned id was never confirmed after ${attempts} attempts to match it up \u2014 the message was deliberately not sent again, so no duplicate turn was created; session ${sessionId.slice(0, 8)} was abandoned; a fresh one is used for further messages.`;
10308
- this.untrackableAck.set(messageId, errorMessage4);
11277
+ 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.`;
11278
+ this.untrackableAck.set(messageId, errorMessage5);
10309
11279
  this.untrackableAckSessionIds.set(messageId, null);
10310
11280
  this.log({
10311
11281
  level: "error",
10312
- message: errorMessage4,
11282
+ message: errorMessage5,
10313
11283
  conversation_id: conversationId,
10314
11284
  message_id: messageId
10315
11285
  });
@@ -10317,7 +11287,7 @@ var ChannelDriver = class _ChannelDriver {
10317
11287
  conversationId,
10318
11288
  messageId,
10319
11289
  null,
10320
- errorMessage4
11290
+ errorMessage5
10321
11291
  );
10322
11292
  if (reportError !== null) {
10323
11293
  this.log({
@@ -10498,12 +11468,12 @@ var ChannelDriver = class _ChannelDriver {
10498
11468
  conversation_id: conv.id,
10499
11469
  message_id: message.id
10500
11470
  });
10501
- const errorMessage4 = this.untrackableAck.get(message.id);
11471
+ const errorMessage5 = this.untrackableAck.get(message.id);
10502
11472
  const reportError = await this.reportUntrackableAck(
10503
11473
  conv.id,
10504
11474
  message.id,
10505
11475
  null,
10506
- errorMessage4
11476
+ errorMessage5
10507
11477
  );
10508
11478
  if (reportError === null) {
10509
11479
  continue;
@@ -10591,7 +11561,7 @@ var ChannelDriver = class _ChannelDriver {
10591
11561
  const hasProviderAndModel = dispatchedModel !== null && separator > 0 && separator < dispatchedModel.length - 1;
10592
11562
  const providerId = hasProviderAndModel ? dispatchedModel.slice(0, separator) : null;
10593
11563
  const modelId = hasProviderAndModel ? dispatchedModel.slice(separator + 1) : null;
10594
- const errorMessage4 = `Provider namespace not loaded on this runner: ${message.opencode_model}. Refused before dispatch; no turn was started.`;
11564
+ const errorMessage5 = `Provider namespace not loaded on this runner: ${message.opencode_model}. Refused before dispatch; no turn was started.`;
10595
11565
  this.log({
10596
11566
  level: "error",
10597
11567
  message: `Refusing message ${message.id.slice(0, 8)} in conversation ${conv.id.slice(0, 8)}: provider namespace ${providerId ?? "(unknown)"} is not loaded; no turn was started`,
@@ -10599,7 +11569,7 @@ var ChannelDriver = class _ChannelDriver {
10599
11569
  message_id: message.id
10600
11570
  });
10601
11571
  try {
10602
- await this.markFailed(conv.id, message.id, sessionId, errorMessage4, void 0, {
11572
+ await this.markFailed(conv.id, message.id, sessionId, errorMessage5, void 0, {
10603
11573
  classification: {
10604
11574
  kind: "model_auth",
10605
11575
  providerId,
@@ -10677,12 +11647,12 @@ var ChannelDriver = class _ChannelDriver {
10677
11647
  } catch (err) {
10678
11648
  if (err instanceof ChannelAuthError) throw err;
10679
11649
  if (this.isV2 && err instanceof OpenCodeV2PromptAckError) {
10680
- const errorMessage5 = err instanceof Error ? err.message : String(err);
10681
- this.untrackableAck.set(message.id, errorMessage5);
11650
+ const errorMessage6 = err instanceof Error ? err.message : String(err);
11651
+ this.untrackableAck.set(message.id, errorMessage6);
10682
11652
  this.untrackableAckSessionIds.set(message.id, null);
10683
11653
  this.log({
10684
11654
  level: "error",
10685
- message: `V2 prompt dispatch for message ${message.id.slice(0, 8)} failed after a positive ack with no usable id: ${errorMessage5}`,
11655
+ message: `V2 prompt dispatch for message ${message.id.slice(0, 8)} failed after a positive ack with no usable id: ${errorMessage6}`,
10686
11656
  conversation_id: conv.id,
10687
11657
  message_id: message.id
10688
11658
  });
@@ -10690,7 +11660,7 @@ var ChannelDriver = class _ChannelDriver {
10690
11660
  conv.id,
10691
11661
  message.id,
10692
11662
  null,
10693
- errorMessage5
11663
+ errorMessage6
10694
11664
  );
10695
11665
  if (markError !== null) {
10696
11666
  this.log({
@@ -10729,7 +11699,7 @@ var ChannelDriver = class _ChannelDriver {
10729
11699
  await this.failV2ModelSwitch(conv, message, sessionId, err);
10730
11700
  break;
10731
11701
  }
10732
- const errorMessage4 = err instanceof Error ? err.message : String(err);
11702
+ const errorMessage5 = err instanceof Error ? err.message : String(err);
10733
11703
  this.sessions.delete(conv.id);
10734
11704
  this.supersede(conv.id, sessionId);
10735
11705
  this.log({
@@ -10738,7 +11708,7 @@ var ChannelDriver = class _ChannelDriver {
10738
11708
  conversation_id: conv.id,
10739
11709
  message_id: message.id
10740
11710
  });
10741
- await this.markFailed(conv.id, message.id, null, errorMessage4).catch((markErr) => {
11711
+ await this.markFailed(conv.id, message.id, null, errorMessage5).catch((markErr) => {
10742
11712
  this.log({
10743
11713
  level: "warn",
10744
11714
  message: `markFailed PATCH for message ${message.id.slice(0, 8)} (conversation ${conv.id.slice(0, 8)}) failed (best-effort, not retried): ${markErr instanceof Error ? markErr.message : String(markErr)}`,
@@ -10749,7 +11719,7 @@ var ChannelDriver = class _ChannelDriver {
10749
11719
  });
10750
11720
  this.log({
10751
11721
  level: "error",
10752
- message: `Message ${message.id.slice(0, 8)} dispatch failed: ${errorMessage4}`,
11722
+ message: `Message ${message.id.slice(0, 8)} dispatch failed: ${errorMessage5}`,
10753
11723
  conversation_id: conv.id,
10754
11724
  message_id: message.id
10755
11725
  });
@@ -11034,7 +12004,12 @@ var ChannelDriver = class _ChannelDriver {
11034
12004
  this.watchers.get(sessionId),
11035
12005
  message.id
11036
12006
  );
11037
- if (hasLaterSiblingTurnStarted(messages, ocId ?? "", siblingOcIds)) {
12007
+ if (hasLaterSiblingTurnStarted(
12008
+ messages,
12009
+ ocId ?? "",
12010
+ siblingOcIds,
12011
+ this.openCodeClient.version
12012
+ )) {
11038
12013
  this.log({
11039
12014
  level: "warn",
11040
12015
  message: `Re-drive: OpenCode already served a later, different Evident message's turn in session ${sessionId.slice(0, 8)} while message ${message.id.slice(0, 8)} produced no reply \u2014 re-dispatching instead of reattaching to someone else's turn`,
@@ -12673,7 +13648,12 @@ var ChannelDriver = class _ChannelDriver {
12673
13648
  return;
12674
13649
  }
12675
13650
  const siblingOcIds = this.siblingOpencodeMessageIds(watcher, inFlight.evidentMessageId);
12676
- const skippedByOpencode = state === "queued" && hasLaterSiblingTurnStarted(messages, inFlight.opencodeMessageId, siblingOcIds);
13651
+ const skippedByOpencode = state === "queued" && hasLaterSiblingTurnStarted(
13652
+ messages,
13653
+ inFlight.opencodeMessageId,
13654
+ siblingOcIds,
13655
+ this.openCodeClient.version
13656
+ );
12677
13657
  const pastStuckBound = this.now() - inFlight.dispatchedAt >= this.stuckQueuedMs;
12678
13658
  const sessionIdle = state === "queued" && !hasRunningAssistantExcept(messages, inFlight.opencodeMessageId);
12679
13659
  if (state === "queued" && pastStuckBound && (sessionIdle || skippedByOpencode) && !inFlight.stuckReported) {
@@ -13684,12 +14664,12 @@ var ChannelDriver = class _ChannelDriver {
13684
14664
  conversation_id: row.conversation_id,
13685
14665
  message_id: row.id
13686
14666
  });
13687
- const errorMessage4 = this.untrackableAck.get(row.id);
14667
+ const errorMessage5 = this.untrackableAck.get(row.id);
13688
14668
  const reportError = await this.reportUntrackableAck(
13689
14669
  row.conversation_id,
13690
14670
  row.id,
13691
14671
  this.untrackableAckSessionIds.get(row.id) ?? null,
13692
- errorMessage4
14672
+ errorMessage5
13693
14673
  );
13694
14674
  if (reportError !== null) {
13695
14675
  this.log({
@@ -14008,14 +14988,14 @@ var ChannelDriver = class _ChannelDriver {
14008
14988
  this.awaitingReadopt.delete(row.id);
14009
14989
  if (err instanceof ChannelAuthError) throw err;
14010
14990
  if (this.isV2) {
14011
- const errorMessage4 = err instanceof Error ? err.message : String(err);
14991
+ const errorMessage5 = err instanceof Error ? err.message : String(err);
14012
14992
  const invalidPromptAck = err instanceof OpenCodeV2PromptAckError;
14013
14993
  if (!invalidPromptAck) {
14014
14994
  const exists = await this.sessionExists(sessionId);
14015
14995
  if (exists === false) {
14016
14996
  this.log({
14017
14997
  level: "warn",
14018
- message: `Re-adopt: message ${row.id.slice(0, 8)} dispatch hit a session (${sessionId.slice(0, 8)}) that was deleted mid-dispatch \u2014 deferring to the next drain: ${errorMessage4}`,
14998
+ message: `Re-adopt: message ${row.id.slice(0, 8)} dispatch hit a session (${sessionId.slice(0, 8)}) that was deleted mid-dispatch \u2014 deferring to the next drain: ${errorMessage5}`,
14019
14999
  conversation_id: row.conversation_id,
14020
15000
  message_id: row.id
14021
15001
  });
@@ -14025,7 +15005,7 @@ var ChannelDriver = class _ChannelDriver {
14025
15005
  if (exists === null) {
14026
15006
  this.log({
14027
15007
  level: "warn",
14028
- message: `Re-adopt: message ${row.id.slice(0, 8)} dispatch failed and session (${sessionId.slice(0, 8)}) existence could not be confirmed \u2014 deferring to the next drain: ${errorMessage4}`,
15008
+ message: `Re-adopt: message ${row.id.slice(0, 8)} dispatch failed and session (${sessionId.slice(0, 8)}) existence could not be confirmed \u2014 deferring to the next drain: ${errorMessage5}`,
14029
15009
  conversation_id: row.conversation_id,
14030
15010
  message_id: row.id
14031
15011
  });
@@ -14033,7 +15013,7 @@ var ChannelDriver = class _ChannelDriver {
14033
15013
  return;
14034
15014
  }
14035
15015
  } else {
14036
- this.untrackableAck.set(row.id, errorMessage4);
15016
+ this.untrackableAck.set(row.id, errorMessage5);
14037
15017
  this.untrackableAckSessionIds.set(row.id, sessionId);
14038
15018
  }
14039
15019
  if (err instanceof OpenCodeV2ModelSwitchError) {
@@ -14042,7 +15022,7 @@ var ChannelDriver = class _ChannelDriver {
14042
15022
  }
14043
15023
  this.log({
14044
15024
  level: "error",
14045
- message: `V2 re-adopt dispatch for message ${row.id.slice(0, 8)} failed: ${errorMessage4}`,
15025
+ message: `V2 re-adopt dispatch for message ${row.id.slice(0, 8)} failed: ${errorMessage5}`,
14046
15026
  conversation_id: row.conversation_id,
14047
15027
  message_id: row.id
14048
15028
  });
@@ -14051,7 +15031,7 @@ var ChannelDriver = class _ChannelDriver {
14051
15031
  row.conversation_id,
14052
15032
  row.id,
14053
15033
  sessionId,
14054
- errorMessage4
15034
+ errorMessage5
14055
15035
  );
14056
15036
  if (markError !== null) {
14057
15037
  this.log({
@@ -14062,7 +15042,7 @@ var ChannelDriver = class _ChannelDriver {
14062
15042
  });
14063
15043
  }
14064
15044
  } else {
14065
- await this.markFailed(row.conversation_id, row.id, sessionId, errorMessage4).catch(
15045
+ await this.markFailed(row.conversation_id, row.id, sessionId, errorMessage5).catch(
14066
15046
  (markErr) => {
14067
15047
  this.log({
14068
15048
  level: "warn",
@@ -15046,9 +16026,9 @@ var ChannelDriver = class _ChannelDriver {
15046
16026
  * trackable. Callers use the returned error to keep their path-specific logging
15047
16027
  * while the same report payload can be retried on a later drain.
15048
16028
  */
15049
- async reportUntrackableAck(conversationId, messageId, sessionId, errorMessage4) {
16029
+ async reportUntrackableAck(conversationId, messageId, sessionId, errorMessage5) {
15050
16030
  try {
15051
- await this.markFailed(conversationId, messageId, sessionId, errorMessage4);
16031
+ await this.markFailed(conversationId, messageId, sessionId, errorMessage5);
15052
16032
  return null;
15053
16033
  } catch (err) {
15054
16034
  this.signalUntrackableAck(conversationId, messageId);
@@ -16212,7 +17192,7 @@ var MAX_FLUSH_PASSES = 2;
16212
17192
  function outcomesWith(outcome) {
16213
17193
  return { claude: outcome, opencode: outcome };
16214
17194
  }
16215
- function errorMessage3(error2) {
17195
+ function errorMessage4(error2) {
16216
17196
  return error2 instanceof Error ? error2.message : String(error2);
16217
17197
  }
16218
17198
  function waitForSettlement(promise, timeoutMs) {
@@ -16239,7 +17219,7 @@ function writeMarker(markerPath, outcomes, log3) {
16239
17219
  writeFileSync8(temporaryPath, body, { mode: 384 });
16240
17220
  renameSync(temporaryPath, markerPath);
16241
17221
  } catch (error2) {
16242
- log3(`CREDENTIAL-FLUSH-MARKER-UNWRITABLE: ${markerPath}: ${errorMessage3(error2)}`, "warn");
17222
+ log3(`CREDENTIAL-FLUSH-MARKER-UNWRITABLE: ${markerPath}: ${errorMessage4(error2)}`, "warn");
16243
17223
  }
16244
17224
  }
16245
17225
  function intervalSeconds(env, log3) {
@@ -16271,7 +17251,7 @@ async function runFlushStore(store, env, synchroniserRunner, log3, deadlineAt) {
16271
17251
  },
16272
17252
  (error2) => {
16273
17253
  failed = true;
16274
- log3(`CREDENTIAL-FLUSH-ERROR: ${store}: ${errorMessage3(error2)}`, "warn");
17254
+ log3(`CREDENTIAL-FLUSH-ERROR: ${store}: ${errorMessage4(error2)}`, "warn");
16275
17255
  }
16276
17256
  );
16277
17257
  const abortTimer = setTimeout(() => controller.abort(), remainingMs);
@@ -16331,7 +17311,7 @@ function createCredentialSync({
16331
17311
  outcomes[store] = !result.timedOut && result.code === 0 ? "ok" : "failed";
16332
17312
  } catch (error2) {
16333
17313
  outcomes[store] = "failed";
16334
- log3(`CREDENTIAL-SYNC-TICK-ERROR: ${store}: ${errorMessage3(error2)}`, "debug");
17314
+ log3(`CREDENTIAL-SYNC-TICK-ERROR: ${store}: ${errorMessage4(error2)}`, "debug");
16335
17315
  }
16336
17316
  }
16337
17317
  const failed = STORES.some((store) => outcomes[store] === "failed");
@@ -17336,8 +18316,8 @@ async function driveChannels(state, driver) {
17336
18316
  state.running = false;
17337
18317
  break;
17338
18318
  }
17339
- const errorMessage4 = error2 instanceof Error ? error2.message : String(error2);
17340
- logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage4}` });
18319
+ const errorMessage5 = error2 instanceof Error ? error2.message : String(error2);
18320
+ logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage5}` });
17341
18321
  if (state.interactive) displayStatus(state);
17342
18322
  if (driver.hasInFlightWatchers()) {
17343
18323
  consecutiveDrainFailures = 0;
@@ -19623,24 +20603,95 @@ async function run(options) {
19623
20603
  }
19624
20604
  }
19625
20605
 
20606
+ // src/commands/teams.ts
20607
+ function printTeam(team, selected) {
20608
+ console.log(`${selected ? "* " : " "}${team.id} ${team.name}`);
20609
+ }
20610
+ function isTeam(value) {
20611
+ return typeof value === "object" && value !== null && typeof value.id === "string" && typeof value.name === "string";
20612
+ }
20613
+ async function teams() {
20614
+ const apiUrl = getApiUrlConfig();
20615
+ let credentials2;
20616
+ try {
20617
+ credentials2 = await getAuthCredentials();
20618
+ } catch (error2) {
20619
+ printError(
20620
+ `Could not read the saved Evident credentials: ${error2 instanceof Error ? error2.message : String(error2)}`
20621
+ );
20622
+ process.exitCode = 1;
20623
+ return;
20624
+ }
20625
+ if (!credentials2) {
20626
+ printError(`Not logged in to ${apiUrl}. Run the \`login\` command to authenticate.`);
20627
+ process.exitCode = 1;
20628
+ return;
20629
+ }
20630
+ try {
20631
+ const response = await fetch(`${apiUrl}/teams`, {
20632
+ headers: buildAuthHeaders(credentials2)
20633
+ });
20634
+ if (!response.ok) {
20635
+ const serverMessage = await readErrorMessage(response);
20636
+ throw new Error(
20637
+ `Evident returned HTTP ${response.status} while listing teams${serverMessage ? `: ${serverMessage}` : ""}`
20638
+ );
20639
+ }
20640
+ const data = await response.json();
20641
+ if (!Array.isArray(data) || !data.every(isTeam)) {
20642
+ throw new Error("Evident returned an invalid team list. Update the CLI and retry.");
20643
+ }
20644
+ const selectedTeam = getTeamSelection();
20645
+ blank();
20646
+ if (data.length === 0) {
20647
+ console.log("No teams found for this account.");
20648
+ blank();
20649
+ return;
20650
+ }
20651
+ for (const team of data) {
20652
+ printTeam(team, team.id === selectedTeam);
20653
+ }
20654
+ if (data.length === 1) {
20655
+ console.log("This is your only team; commands act in it automatically.");
20656
+ } else if (!selectedTeam) {
20657
+ console.log("Choose a team with --team <id> or set EVIDENT_TEAM.");
20658
+ }
20659
+ blank();
20660
+ } catch (error2) {
20661
+ printError(`Could not list teams: ${error2 instanceof Error ? error2.message : String(error2)}`);
20662
+ process.exitCode = 1;
20663
+ }
20664
+ }
20665
+
19626
20666
  // src/index.ts
19627
20667
  var version = getCliVersion();
19628
20668
  var program = new Command();
19629
20669
  program.name("evident").description("Run OpenCode locally and connect it to Evident").version(version).option(
19630
20670
  "--endpoint <url>",
19631
20671
  "Evident API base URL (default: production; e.g. http://localhost:3001)"
19632
- ).option("--tunnel <url>", "Tunnel WebSocket URL (default: production; e.g. ws://localhost:8787)").hook("preAction", (thisCommand) => {
19633
- const { endpoint: endpoint2, tunnel } = thisCommand.opts();
20672
+ ).option("--tunnel <url>", "Tunnel WebSocket URL (default: production; e.g. ws://localhost:8787)").option(
20673
+ "--team <id>",
20674
+ "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"
20675
+ ).hook("preAction", (thisCommand) => {
20676
+ const { endpoint: endpoint2, tunnel, team } = thisCommand.optsWithGlobals();
19634
20677
  if (endpoint2) {
19635
20678
  setEndpoint(endpoint2);
19636
20679
  }
19637
20680
  if (tunnel) {
19638
20681
  setTunnelUrl(tunnel);
19639
20682
  }
20683
+ setTeamSelection(team);
19640
20684
  });
19641
20685
  program.command("login").description("Authenticate with Evident").option("--token", "Use token-based authentication (for CI/CD)").option("--no-browser", "Do not open the browser automatically").action(login);
19642
20686
  program.command("logout").description("Remove stored credentials for the current endpoint").option("--all", "Remove stored credentials for all endpoints").action((options) => logout({ all: options.all }));
19643
20687
  program.command("whoami").description("Show the currently logged in user").action(whoami);
20688
+ program.command("teams").description("List the teams you belong to").action(teams);
20689
+ 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(
20690
+ (proxyId, connectionId, options) => authorizeMcpConnection(proxyId, connectionId, {
20691
+ noBrowser: options.browser === false,
20692
+ json: options.json
20693
+ })
20694
+ );
19644
20695
  program.command("status").description("Check whether the configured credentials can reach Evident").option("--json", "Output in JSON format").action((options) => status({ json: options.json }));
19645
20696
  program.command("credential-vault-env").description("Print the shell assignment a runner image evals before starting the synchroniser").action(credentialVaultEnv);
19646
20697
  program.command("claude-usage").description("[spike] Show Claude subscription usage (requires a local `claude login`)").action(claudeUsage);